[
  {
    "path": ".clang-format",
    "content": "Language: Cpp\nAccessModifierOffset: -2\nAlignAfterOpenBracket: Align\nAlignConsecutiveAssignments: false\nAlignConsecutiveDeclarations: true\nAlignEscapedNewlinesLeft: true\nAlignOperands: true\nAlignTrailingComments: true\nAllowAllParametersOfDeclarationOnNextLine: true\nAllowShortBlocksOnASingleLine: false\nAllowShortCaseLabelsOnASingleLine: false\nAllowShortFunctionsOnASingleLine: All\nAllowShortIfStatementsOnASingleLine: false\nAllowShortLoopsOnASingleLine: false\nAlwaysBreakAfterReturnType: None\nAlwaysBreakBeforeMultilineStrings: false\nAlwaysBreakTemplateDeclarations: false\nBinPackArguments: true\nBinPackParameters: true\nBreakBeforeBinaryOperators: None\nBreakBeforeBraces: Allman\nBreakBeforeTernaryOperators: true\nBreakConstructorInitializersBeforeComma: true\nBreakStringLiterals: false\nColumnLimit: 100\nCommentPragmas: '^ IWYU pragma:'\nConstructorInitializerAllOnOneLineOrOnePerLine: false\nConstructorInitializerIndentWidth: 2\nContinuationIndentWidth: 2\nCpp11BracedListStyle: true\nDerivePointerAlignment: false\nDisableFormat: false\nExperimentalAutoDetectBinPacking: false\nFixNamespaceComments: false\nForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]\nIncludeCategories: \n  - Regex:    '^\"'\n    Priority: 0\n  - Regex:    '^<'\n    Priority: -1\n  - Regex:    '.*'\n    Priority: 1\nIncludeIsMainRegex: '$'\nIndentCaseLabels: true\nIndentWidth: 2\nIndentWrappedFunctionNames: false\nKeepEmptyLinesAtTheStartOfBlocks: false\nMacroBlockBegin: ''\nMacroBlockEnd: ''\nMaxEmptyLinesToKeep: 1\nNamespaceIndentation: All\nPenaltyBreakBeforeFirstCallParameter: 19\nPenaltyBreakComment: 300\nPenaltyBreakFirstLessLess: 120\nPenaltyBreakString: 1000\nPenaltyExcessCharacter: 1000000\nPenaltyReturnTypeOnItsOwnLine: 60\nPointerAlignment: Left\nReflowComments: true\nSortIncludes: true\nSpaceAfterCStyleCast: true\nSpaceBeforeAssignmentOperators: true\nSpaceBeforeParens: Always\nSpaceInEmptyParentheses: false\nSpacesBeforeTrailingComments: 2\nSpacesInAngles: false\nSpacesInContainerLiterals: false\nSpacesInCStyleCastParentheses: false\nSpacesInParentheses: false\nSpacesInSquareBrackets: false\nStandard: Cpp11\nUseTab: Never\n"
  },
  {
    "path": ".gitignore",
    "content": "obj/\nmoc/\ndilay\ndilay_debug\nMakefile\narchive/\ni18n/*.qm\nrun-tests\nlib/Makefile\nlib/Makefile.Release\nlib/Makefile.Debug\nlib/libdilay.a\napp/Makefile\napp/Makefile.Release\napp/Makefile.Debug\napp/translations\ntest/Makefile\ntest/Makefile.Release\ntest/Makefile.Debug\nvalgrind.log\n.qmake.stash\nicon.pdf\nicon.png\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Dilay - a 3D sculpting application\n\n**Project website:** https://abau.org/dilay\n\n**Building instructions:** https://abau.org/dilay/manual.html#installing\n"
  },
  {
    "path": "app/app.pro",
    "content": "include (../common.pri)\n\nTEMPLATE        = app\nDESTDIR         = $$OUT_PWD/..\nDEPENDPATH     += src \nINCLUDEPATH    += src $$PWD/../lib/src\nSOURCES        += src/main.cpp\n\nCONFIG(release, debug|release): TARGET = dilay\nCONFIG(debug  , debug|release): TARGET = dilay_debug\n\nwin32 {\n  CONFIG(release, debug|release) {\n    LIBS += -L$$OUT_PWD/../lib/release/ -ldilay\n\n    win32-g++ {\n      PRE_TARGETDEPS += $$OUT_PWD/../lib/release/libdilay.a\n    }\n    else {\n      PRE_TARGETDEPS += $$OUT_PWD/../lib/release/dilay.lib\n    }\n  }\n  CONFIG(debug, debug|release) {\n    LIBS += -L$$OUT_PWD/../lib/debug/ -ldilay\n\n    win32-g++ {\n      PRE_TARGETDEPS += $$OUT_PWD/../lib/debug/libdilay.a\n    }\n    else {\n      PRE_TARGETDEPS += $$OUT_PWD/../lib/debug/dilay.lib\n    }\n  }\n  RC_ICONS = $$PWD/../win32/icon.ico\n\n  QMAKE_POST_LINK += $$PWD/../win32/deploy.bat $$shell_path($$[QT_INSTALL_PREFIX]) \\\n                                               $$shell_path($$DESTDIR) \\\n                                               $$shell_path($$PWD/../) \\\n                                               $$VERSION\n}\n\nunix {\n  LIBS           += -L$$OUT_PWD/../lib/ -ldilay\n  PRE_TARGETDEPS += $$OUT_PWD/../lib/libdilay.a\n\n  target.path     = $$PREFIX/bin/\n  INSTALLS       += target\n\n  desktop.path    = $$PREFIX/share/applications/\n  desktop.files   = ../unix/dilay.desktop\n  INSTALLS       += desktop\n\n  icon16.path     = $$PREFIX/share/icons/hicolor/16x16/apps/\n  icon16.files    = ../unix/icon/16x16/dilay.png\n  INSTALLS       += icon16\n\n  icon32.path     = $$PREFIX/share/icons/hicolor/32x32/apps/\n  icon32.files    = ../unix/icon/32x32/dilay.png\n  INSTALLS       += icon32\n\n  icon48.path     = $$PREFIX/share/icons/hicolor/48x48/apps/\n  icon48.files    = ../unix/icon/48x48/dilay.png\n  INSTALLS       += icon48\n\n  icon256.path    = $$PREFIX/share/icons/hicolor/256x256/apps/\n  icon256.files   = ../unix/icon/256x256/dilay.png\n  INSTALLS       += icon256\n\n  format.commands = clang-format -style=file -i $$SOURCES $$HEADERS\n  QMAKE_EXTRA_TARGETS += format\n}\n"
  },
  {
    "path": "app/src/main.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QApplication>\n#include <QDir>\n#include <QLibraryInfo>\n#include <QStandardPaths>\n#include \"cache.hpp\"\n#include \"config.hpp\"\n#include \"opengl.hpp\"\n#include \"time-delta.hpp\"\n#include \"util.hpp\"\n#include \"view/log.hpp\"\n#include \"view/main-window.hpp\"\n\nnamespace\n{\n  QString configPath ()\n  {\n    return QStandardPaths::locate (QStandardPaths::ConfigLocation, \"dilay.config\");\n  }\n\n  void backupCrashLog ()\n  {\n    QFile log (ViewLog::logPath ());\n    QFile crashLog (ViewLog::crashLogPath ());\n\n    if (log.exists ())\n    {\n      if (crashLog.exists ())\n      {\n        crashLog.remove ();\n      }\n      log.rename (ViewLog::crashLogPath ());\n    }\n  }\n}\n\nint main (int argv, char** args)\n{\n  backupCrashLog ();\n  Log::initialize (ViewLog::logPath ().toStdString ());\n  DILAY_INFO (\"Version: %s\", DILAY_VERSION);\n  DILAY_INFO (\"Architecture: %s\", QSysInfo::buildCpuArchitecture ().toStdString ().c_str ());\n  DILAY_INFO (\"OS: %s\", QSysInfo::prettyProductName ().toStdString ().c_str ());\n  DILAY_INFO (\"Qt: %s\", QLibraryInfo::version ().toString ().toStdString ().c_str ());\n\n  QCoreApplication::setApplicationName (\"Dilay\");\n  QCoreApplication::setAttribute (Qt::AA_UseDesktopOpenGL);\n  OpenGL::setDefaultFormat ();\n\n  QApplication app (argv, args);\n  Config       config;\n  Cache        cache;\n\n  if (configPath ().isEmpty () == false)\n  {\n    config.fromFile (configPath ().toStdString ());\n  }\n\n  ViewMainWindow mainWindow (config, cache);\n  mainWindow.resize (config.get<int> (\"window/initial-width\"),\n                     config.get<int> (\"window/initial-height\"));\n  mainWindow.show ();\n\n  QObject::connect (&app, &QApplication::aboutToQuit, [&config]() {\n    const QString configDirName (QStandardPaths::writableLocation (QStandardPaths::ConfigLocation));\n    const QDir    configDir (configDirName);\n\n    if (configDirName.isEmpty () == false)\n    {\n      if (configDir.exists () == false)\n      {\n        configDir.mkpath (\".\");\n      }\n      config.toFile (configDir.filePath (\"dilay.config\").toStdString ());\n    }\n  });\n  TimeDelta::initialize ();\n  return app.exec ();\n}\n"
  },
  {
    "path": "common.pri",
    "content": "VERSION                 = 1.9.0\nCONFIG                 += debug_and_release warn_on object_parallel_to_source ordered c++14\nQT                     += widgets opengl openglextensions xml\nMOC_DIR                 = moc\nOBJECTS_DIR             = obj\nQMAKE_CXXFLAGS         += -DDILAY_VERSION=\\\\\\\"$$VERSION\\\\\\\" -DGLM_FORCE_RADIANS -DGLM_ENABLE_EXPERIMENTAL\nQMAKE_CXXFLAGS_RELEASE += -DNDEBUG\nQMAKE_CXXFLAGS_DEBUG   += -Wall # -pg # -DDILAY_RENDER_OCTREE\nQMAKE_LFLAGS_DEBUG     += # -pg\n\nwin32:INCLUDEPATH      += $$PWD/glm/\n\nunix {\n  isEmpty (PREFIX) {\n    PREFIX = /usr/local\n  }\n}\n"
  },
  {
    "path": "dilay.pro",
    "content": "CONFIG      += debug_and_release\nTEMPLATE     = subdirs\nSUBDIRS      = lib app test\n\napp.depends  = lib\ntest.depends = lib\n\ndisable-test {\n  SUBDIRS -= test\n}\n\ndisable-app {\n  SUBDIRS -= app\n}\n\nunix {\n  gdb.commands = gdb -ex run ./dilay_debug\n  valgrind.commands = valgrind ./dilay_debug &> valgrind.log\n  leak.commands = valgrind --leak-check=yes ./dilay_debug &> valgrind.log\n  format.CONFIG = recursive\n  copyright.commands = find $$SUBDIRS \\\\( -name \"*.cpp\" -o -name \"*.hpp\" -o -name \"*.hs\" \\\\) -print0 | \\\n                       xargs -0 sed -i 's/Copyright\\ ©\\ 2015-2017/Copyright\\ ©\\ 2015-2018/'\n\n  docker.commands = docker build -t dilay-$(IMAGE) unix/docker/$(IMAGE) && \\\n                    docker run --rm --mount type=bind,src=$$(PWD),dst=/dilay dilay-$(IMAGE)\n\n  QMAKE_EXTRA_TARGETS += gdb valgrind leak format copyright icon docker\n}\n"
  },
  {
    "path": "icon.tex",
    "content": "\\documentclass[crop,tikz,convert={size=512x512,outext=.png}]{standalone}\n\\usetikzlibrary{shapes.geometric}\n\\begin{document}\n  \\begin{tikzpicture}\n    [linestyle/.style={draw=black!80,line width=5pt,transform shape},\n     emptylinestyle/.style={transform shape},\n     circlestyle/.style={fill=black!80,circle,minimum size=10pt}]\n\n    \\begin{scope}[rotate=-10]\n    \\shadedraw [shading=ball, ball color=black!10] (0,0) circle (101pt);\n\n    \\node[linestyle,circle,minimum size=201pt] {};\n    \\node[emptylinestyle,regular polygon, regular polygon sides=9,rotate=20, minimum size=200pt] (p) {};\n    \\node[emptylinestyle, regular polygon, regular polygon sides=3,minimum size=120pt] (t) {};\n    \\node[linestyle, regular polygon, regular polygon sides=3,minimum size=120pt] {};\n\n    \\draw [linestyle] (t.corner 1) -- (p.corner 1);\n    \\draw [linestyle] (t.corner 1) -- (p.corner 2);\n    \\draw [linestyle] (t.corner 1) -- (p.corner 8);\n    \\draw [linestyle] (t.corner 1) -- (p.corner 9);\n    \\draw [linestyle] (t.corner 2) -- (p.corner 2);\n    \\draw [linestyle] (t.corner 2) -- (p.corner 3);\n    \\draw [linestyle] (t.corner 2) -- (p.corner 4);\n    \\draw [linestyle] (t.corner 2) -- (p.corner 5);\n    \\draw [linestyle] (t.corner 3) -- (p.corner 5);\n    \\draw [linestyle] (t.corner 3) -- (p.corner 6);\n    \\draw [linestyle] (t.corner 3) -- (p.corner 7);\n    \\draw [linestyle] (t.corner 3) -- (p.corner 8);\n\n    \\node [circlestyle] at (t.corner 1) {};\n    \\node [circlestyle] at (t.corner 2) {};\n    \\node [circlestyle] at (t.corner 3) {};\n    \\node [circlestyle] at (p.corner 1) {};\n    \\node [circlestyle] at (p.corner 2) {};\n    \\node [circlestyle] at (p.corner 3) {};\n    \\node [circlestyle] at (p.corner 4) {};\n    \\node [circlestyle] at (p.corner 5) {};\n    \\node [circlestyle] at (p.corner 6) {};\n    \\node [circlestyle] at (p.corner 7) {};\n    \\node [circlestyle] at (p.corner 8) {};\n    \\node [circlestyle] at (p.corner 9) {};\n    \\end{scope}\n  \\end{tikzpicture}\n\\end{document}\n"
  },
  {
    "path": "lib/lib.pro",
    "content": "include (../common.pri)\n\nTEMPLATE     = lib\nTARGET       = dilay\nDEPENDPATH  += src \nINCLUDEPATH += src \nCONFIG      += staticlib\n\nSOURCES += \\\n           src/camera.cpp \\\n           src/color.cpp \\\n           src/config.cpp \\\n           src/configurable.cpp \\\n           src/dimension.cpp \\\n           src/distance.cpp \\\n           src/dynamic/faces.cpp \\\n           src/dynamic/mesh.cpp \\\n           src/dynamic/mesh-intersection.cpp \\\n           src/dynamic/octree.cpp \\\n           src/history.cpp \\\n           src/import-export.cpp \\\n           src/intersection.cpp \\\n           src/isosurface-extraction.cpp \\\n           src/isosurface-extraction/grid.cpp \\\n           src/kvstore.cpp \\\n           src/log.cpp \\\n           src/mesh.cpp \\\n           src/mesh-util.cpp \\\n           src/mirror.cpp \\\n           src/opengl.cpp \\\n           src/opengl-buffer-id.cpp \\\n           src/primitive/aabox.cpp \\\n           src/primitive/cone.cpp \\\n           src/primitive/cone-sphere.cpp \\\n           src/primitive/cylinder.cpp \\\n           src/primitive/plane.cpp \\\n           src/primitive/ray.cpp \\\n           src/primitive/sphere.cpp \\\n           src/primitive/triangle.cpp \\\n           src/render-mode.cpp \\\n           src/renderer.cpp \\\n           src/scene.cpp \\\n           src/shader.cpp \\\n           src/sketch/bone-intersection.cpp \\\n           src/sketch/mesh.cpp \\\n           src/sketch/mesh-intersection.cpp \\\n           src/sketch/node-intersection.cpp \\\n           src/sketch/path.cpp \\\n           src/sketch/path-intersection.cpp \\\n           src/state.cpp \\\n           src/time-delta.cpp \\\n           src/tool.cpp \\\n           src/tool/convert-sketch.cpp \\\n           src/tool/delete-mesh.cpp \\\n           src/tool/delete-sketch.cpp \\\n           src/tool/edit-sketch.cpp \\\n           src/tool/move-camera.cpp \\\n           src/tool/new-mesh.cpp \\\n           src/tool/remesh.cpp \\\n           src/tool/sculpt.cpp \\\n           src/tool/sculpt/draw.cpp \\\n           src/tool/sculpt/crease.cpp \\\n           src/tool/sculpt/flatten.cpp \\\n           src/tool/sculpt/grab.cpp \\\n           src/tool/sculpt/pinch.cpp \\\n           src/tool/sculpt/reduce.cpp \\\n           src/tool/sculpt/smooth.cpp \\\n           src/tool/sculpt/util/action.cpp \\\n           src/tool/sculpt/util/brush.cpp \\\n           src/tool/sculpt/util/edge-collection.cpp \\\n           src/tool/sketch-spheres.cpp \\\n           src/tool/transform-mesh.cpp \\\n           src/tool/trim-mesh.cpp \\\n           src/tool/trim-mesh/action.cpp \\\n           src/tool/trim-mesh/border.cpp \\\n           src/tool/trim-mesh/split-mesh.cpp \\\n           src/tool/util/movement.cpp \\\n           src/tool/util/rotation.cpp \\\n           src/tool/util/scaling.cpp \\\n           src/tool/util/step.cpp \\\n           src/util.cpp \\\n           src/view/axis.cpp \\\n           src/view/color-button.cpp \\\n           src/view/configuration.cpp \\\n           src/view/context-menu.cpp \\\n           src/view/cursor.cpp \\\n           src/view/double-slider.cpp \\\n           src/view/floor-plane.cpp \\\n           src/view/gl-widget.cpp \\\n           src/view/info-pane.cpp \\\n           src/view/info-pane/scene.cpp \\\n           src/view/input.cpp \\\n           src/view/key-event.cpp \\\n           src/view/light.cpp \\\n           src/view/log.cpp \\\n           src/view/main-window.cpp \\\n           src/view/menu-bar.cpp \\\n           src/view/pointing-event.cpp \\\n           src/view/resolution-slider.cpp \\\n           src/view/shortcut.cpp \\\n           src/view/tool-pane.cpp \\\n           src/view/tool-tip.cpp \\\n           src/view/two-column-grid.cpp \\\n           src/view/util.cpp \\\n           src/view/vector-edit.cpp \\\n           src/xml-conversion.cpp \\\n\nHEADERS += \\\n           src/bitset.hpp \\\n           src/cache.hpp \\\n           src/camera.hpp \\\n           src/color.hpp \\\n           src/config.hpp \\\n           src/configurable.hpp \\\n           src/dimension.hpp \\\n           src/distance.hpp \\\n           src/dynamic/faces.hpp \\\n           src/dynamic/mesh.hpp \\\n           src/dynamic/mesh-intersection.hpp \\\n           src/dynamic/octree.hpp \\\n           src/hash.hpp \\\n           src/history.hpp \\\n           src/import-export.hpp \\\n           src/intersection.hpp \\\n           src/isosurface-extraction.hpp \\\n           src/isosurface-extraction/grid.hpp \\\n           src/kvstore.hpp \\\n           src/log.hpp \\\n           src/macro.hpp \\\n           src/maybe.hpp \\\n           src/mesh.hpp \\\n           src/mesh-util.hpp \\\n           src/mirror.hpp \\\n           src/opengl.hpp \\\n           src/opengl-buffer-id.hpp \\\n           src/primitive/aabox.hpp \\\n           src/primitive/cone.hpp \\\n           src/primitive/cone-sphere.hpp \\\n           src/primitive/cylinder.hpp \\\n           src/primitive/plane.hpp \\\n           src/primitive/ray.hpp \\\n           src/primitive/sphere.hpp \\\n           src/primitive/triangle.hpp \\\n           src/render-mode.hpp \\\n           src/renderer.hpp \\\n           src/scene.hpp \\\n           src/shader.hpp \\\n           src/sketch/bone-intersection.hpp \\\n           src/sketch/fwd.hpp \\\n           src/sketch/mesh.hpp \\\n           src/sketch/mesh-intersection.hpp \\\n           src/sketch/node-intersection.hpp \\\n           src/sketch/path.hpp \\\n           src/sketch/path-intersection.hpp \\\n           src/state.hpp \\\n           src/time-delta.hpp \\\n           src/tool.hpp \\\n           src/tool/key.hpp \\\n           src/tool/move-camera.hpp \\\n           src/tool/sculpt.hpp \\\n           src/tool/sculpt/util/action.hpp \\\n           src/tool/sculpt/util/brush.hpp \\\n           src/tool/sculpt/util/edge-collection.hpp \\\n           src/tool/trim-mesh/action.hpp \\\n           src/tool/trim-mesh/border.hpp \\\n           src/tool/trim-mesh/split-mesh.hpp \\\n           src/tool/util/movement.hpp \\\n           src/tool/util/rotation.hpp \\\n           src/tool/util/scaling.hpp \\\n           src/tool/util/step.hpp \\\n           src/tools.hpp \\\n           src/tree.hpp \\\n           src/util.hpp \\\n           src/variant.hpp \\\n           src/view/axis.hpp \\\n           src/view/color-button.hpp \\\n           src/view/configuration.hpp \\\n           src/view/context-menu.hpp \\\n           src/view/cursor.hpp \\\n           src/view/double-slider.hpp \\\n           src/view/floor-plane.cpp \\\n           src/view/gl-widget.hpp \\\n           src/view/info-pane.hpp \\\n           src/view/info-pane/scene.hpp \\\n           src/view/input.hpp \\\n           src/view/key-event.hpp \\\n           src/view/light.hpp \\\n           src/view/log.hpp \\\n           src/view/main-window.hpp \\\n           src/view/menu-bar.hpp \\\n           src/view/pointing-event.hpp \\\n           src/view/resolution-slider.hpp \\\n           src/view/shortcut.hpp \\\n           src/view/tool-pane.hpp \\\n           src/view/tool-tip.hpp \\\n           src/view/two-column-grid.hpp \\\n           src/view/util.hpp \\\n           src/view/vector-edit.hpp \\\n           src/xml-conversion.hpp \\\n\nunix {\n  format.commands = clang-format -style=file -i $$SOURCES $$HEADERS\n  QMAKE_EXTRA_TARGETS += format\n}\n"
  },
  {
    "path": "lib/src/IsosurfaceExtractionConfigurations.hs",
    "content": "{- This file is part of Dilay\n - Copyright © 2015-2018 Alexander Bau\n - Use and redistribute under the terms of the GNU General Public License\n -}\n\nimport Control.Exception (assert)\nimport Control.Monad (forM_)\nimport Data.Char (toLower)\nimport Data.Function (on)\nimport Data.List (intercalate,nubBy,sortBy)\n\ndata Configuration = Configuration \n  { base :: Int\n  , vertices :: [Bool]\n  , vertexIndices :: [Int]\n  , nonManifoldConfig :: Bool\n  } \n  deriving Show\n\nset :: Int -> a -> [a] -> [a]\nset 0 x (y:ys) = x:ys\nset i x (y:ys) = y:(set (i - 1) x ys)\n\nsetList :: [Int] -> a -> [a] -> [a]\nsetList is value xs = foldl (\\xs i -> set i value xs) xs is\n\nbaseConfigurations :: [Configuration]\nbaseConfigurations = \n  [ go 0  []                       []                                             False\n  , go 1  [4]                      [[2, 6, 7]]                                    False\n  , go 2  [4, 5]                   [[2, 5, 7, 10]]                                False\n  , go 3  [4, 7]                   [[2, 6, 7], [9, 10, 11]]                       False\n  , go 4  [3, 4]                   [[2, 6, 7], [3, 4, 11]]                        False\n\n  , go 5  [0, 1, 5]                [[1, 2, 4, 6, 10]]                             False\n  , go 6  [3, 4, 5]                [[2, 5, 7, 10], [3, 4, 11]]                    False\n  , go 7  [3, 5, 6]                [[7, 8, 9], [3, 4, 11], [5, 6, 10]]            False\n  , go 8  [0, 1, 4, 5]             [[1, 4, 7, 10]]                                False\n  , go 9  [0, 1, 2, 4]             [[3, 4, 5, 6, 7, 8]]                           False\n\n  , go 10 [1, 3, 4, 6]             [[2, 6, 8, 9], [0, 3, 5, 11]]                  False\n  , go 11 [0, 1, 3, 4]             [[1, 3, 5, 6, 7, 11]]                          False\n  , go 12 [0, 1, 5, 6]             [[7, 8, 9], [1, 2, 4, 6, 10]]                  False\n  , go 13 [1, 2, 4, 7]             [[2, 6, 7], [9, 10, 11], [1, 3, 8], [0, 4, 5]] False\n  , go 14 [0, 1, 2, 5]             [[2, 3, 4, 6, 8, 10]]                          False\n\n  , go 15 [0, 1, 2, 4, 7]          [[3, 4, 5, 6, 7, 8], [9, 10, 11]]              False\n  , go 16 [0, 1, 2, 6, 7]          [[2, 5, 7, 10], [3, 4, 11]]                    True\n  , go 17 [2, 3, 4, 6, 7]          [[1, 2, 4, 6, 10]]                             False\n  , go 18 [0, 1, 2, 5, 6, 7]       [[2, 6, 7], [3, 4, 11]]                        False\n  , go 19 [0, 1, 2, 3, 5, 6]       [[2, 6, 7], [9, 10, 11]]                       True\n\n  , go 20 [0, 1, 2, 3, 6, 7]       [[2, 5, 7, 10]]                                False\n  , go 21 [0, 1, 2, 3, 5, 6, 7]    [[2, 6, 7]]                                    False\n  , go 22 [0, 1, 2, 3, 4, 5, 6, 7] []                                             False\n  ]\n  where\n    go base vertices vertexIndices nonManifold = \n      Configuration base (setList vertices True $ replicate 8 False)\n                    (mkVertexIndices 0 vertexIndices) nonManifold\n\n    mkVertexIndices :: Int -> [[Int]] -> [Int]\n    mkVertexIndices vertexIndex [] = replicate 12 (-1)\n    mkVertexIndices vertexIndex (edgeGroup:edgeGroups) = setList edgeGroup vertexIndex rest\n      where\n        rest = mkVertexIndices (vertexIndex + 1) edgeGroups\n\n\nallConfigurations :: [Configuration]\nallConfigurations = sortBy (sort `on` vertices)\n                  $ nubBy ((==) `on` vertices)\n                  $ concat\n                  $ do\n  x <- [id, rotateX, rotateX . rotateX, rotateX . rotateX . rotateX]\n  y <- [id, rotateY, rotateY . rotateY, rotateY . rotateY . rotateY]\n  z <- [id, rotateZ, rotateZ . rotateZ, rotateZ . rotateZ . rotateZ]\n\n  return $ map (($) (x . y . z)) baseConfigurations\n\n  where\n    rotateX (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7]\n                           [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold)\n\n      = Configuration base [v4, v5, v0, v1, v6, v7, v2, v3]\n                      [e6, e2, e7, e0, e5, e10, e9, e8, e1, e3, e11, e4] nonManifold\n\n\n    rotateY (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7]\n                           [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold)\n\n      = Configuration base [v1, v5, v3, v7, v0, v4, v2, v6]\n                      [e5, e4, e0, e11, e10, e6, e2, e1, e3, e8, e7, e9] nonManifold\n\n\n    rotateZ (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7]\n                           [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold)\n\n      = Configuration base [v2, v0, v3, v1, v6, v4, v7, v5]\n                      [e1, e3, e8, e4, e0, e2, e7, e9, e11, e10, e6, e5] nonManifold\n\n    sort xs ys = go (reverse xs) (reverse ys)\n      where\n        go (False:xs) (True:ys)  = LT\n        go (True:xs)  (False:ys) = GT\n        go (_:xs)     (_:ys)     = go xs ys\n\nmain :: IO ()\nmain = assert (length allConfigurations == 256)\n     $ printBases >> printNonManifold >> printVertexIndices\n  where\n    printBases = putStrLn $ toList (show . base) allConfigurations\n\n    printNonManifold = putStrLn $ toList (map toLower . show . nonManifoldConfig) allConfigurations\n\n    printVertexIndices =\n      putStrLn $ toList (\\c -> toList show (vertexIndices c) ++ \"\\n\") allConfigurations\n\n    toList xToString xs = unwords $ \"{\" :\n                                  [ intercalate \", \" $ map xToString xs ]\n                                  ++ [\"}\"]\n"
  },
  {
    "path": "lib/src/bitset.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_BITSET\n#define DILAY_BITSET\n\n#include <cmath>\n\ntemplate <typename T> class Bitset\n{\npublic:\n  Bitset ()\n    : _data (0)\n  {\n  }\n\n  Bitset (const Bitset& other)\n    : _data (other._data)\n  {\n  }\n\n  template <unsigned short N> bool get () const\n  {\n    static_assert (N < sizeof (T) * 8, \"invalid bitset index\");\n    return this->_data & 1 << N;\n  }\n\n  template <unsigned short N> void set (bool value = true)\n  {\n    static_assert (N < sizeof (T) * 8, \"invalid bitset index\");\n\n    if (value)\n    {\n      this->_data = this->_data | 1 << N;\n    }\n    else\n    {\n      this->_data = this->_data & ~(1 << N);\n    }\n  }\n\n  template <unsigned short N> void toggle () { this->set<N> (!this->get<N> ()); }\n\n  template <unsigned short N> void reset () { this->set<N> (false); }\n\n  void reset () { this->_data = 0; }\n\n  bool none () const { return this->_data == 0; }\n\n  template <unsigned short N> bool all () const\n  {\n    static_assert (N < sizeof (T) * 8, \"invalid bitset index\");\n\n    const T allBits = std::pow (2, N) - 1;\n    return (this->_data & allBits) == allBits;\n  }\n\n  T value () const { return this->_data; }\n\nprivate:\n  T _data;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/cache.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_CACHE\n#define DILAY_CACHE\n\n#include \"kvstore.hpp\"\n\nclass Cache\n{\npublic:\n  Cache ()\n    : store (\"cache\")\n  {\n  }\n\n  template <class T> const T& get (const std::string& path, const T& value) const\n  {\n    return this->store.get<T> (path, value);\n  }\n\n  template <class T> void set (const std::string& path, const T& value)\n  {\n    this->store.set<T> (path, value);\n  }\n\nprivate:\n  KVStore store;\n};\n\nclass CacheProxy\n{\npublic:\n  CacheProxy (Cache& c, const std::string& p)\n    : _cache (c)\n    , prefix (p)\n  {\n    assert (p.back () == '/');\n  }\n\n  CacheProxy (CacheProxy& o, const std::string& path)\n    : CacheProxy (o._cache, o.prefix + path)\n  {\n  }\n\n  Cache& cache () const { return this->_cache; }\n\n  std::string key (const std::string& path) const { return this->prefix + path; }\n\n  template <class T> const T& get (const std::string& path, const T& v) const\n  {\n    return this->_cache.get<T> (this->key (path), v);\n  }\n\n  template <class T> void set (const std::string& path, const T& v) const\n  {\n    return this->_cache.set<T> (this->key (path), v);\n  }\n\nprivate:\n  Cache&            _cache;\n  const std::string prefix;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/camera.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/gtc/matrix_transform.hpp>\n#include <glm/gtx/matrix_major_storage.hpp>\n#include <glm/gtx/quaternion.hpp>\n#include \"camera.hpp\"\n#include \"config.hpp\"\n#include \"dimension.hpp\"\n#include \"intersection.hpp\"\n#include \"opengl.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"renderer.hpp\"\n#include \"util.hpp\"\n\nstruct Camera::Impl\n{\n  Camera*     self;\n  Renderer    renderer;\n  glm::vec3   gazePoint;\n  glm::vec3   toEyePoint;\n  glm::vec3   right;\n  glm::mat4x4 projection;\n  glm::mat4x4 view;\n  glm::mat4x4 viewRotation;\n  glm::uvec2  resolution;\n  float       nearClipping;\n  float       farClipping;\n  float       fieldOfView;\n\n  Impl (Camera* s, const Config& config)\n    : self (s)\n    , renderer (config)\n    , resolution (config.get<int> (\"window/initial-width\"),\n                  config.get<int> (\"window/initial-height\"))\n  {\n    this->set (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 0.0f, 6.0f));\n    this->runFromConfig (config);\n  }\n\n  const glm::vec3& up () const\n  {\n    static const glm::vec3 up (0.0f, 1.0f, 0.0f);\n    return up;\n  }\n\n  glm::vec3 realUp () const { return glm::normalize (glm::cross (this->toEyePoint, this->right)); }\n\n  glm::vec3 position () const { return this->gazePoint + this->toEyePoint; }\n\n  glm::mat4x4 world () const\n  {\n    const glm::vec3 x = this->right;\n    const glm::vec3 z = glm::normalize (this->toEyePoint);\n    const glm::vec3 y = glm::cross (z, x);\n    const glm::vec3 p = this->position ();\n\n    return glm::colMajor4 (glm::vec4 (x, 0.0f), glm::vec4 (y, 0.0f), glm::vec4 (z, 0.0f),\n                           glm::vec4 (p, 1.0f));\n  }\n\n  void updateResolution (const glm::uvec2& dimension)\n  {\n    this->resolution = dimension;\n    this->updateProjection ();\n  }\n\n  void setModelViewProjection (const glm::mat4x4& model, const glm::mat3x3& modelNormal,\n                               bool onlyRotation)\n  {\n    this->renderer.setModel (&model[0][0], &modelNormal[0][0]);\n    this->renderer.setProjection (&this->projection[0][0]);\n\n    if (onlyRotation)\n    {\n      this->renderer.setView (&this->viewRotation[0][0]);\n    }\n    else\n    {\n      this->renderer.setView (&this->view[0][0]);\n    }\n  }\n\n  void set (const glm::vec3& g, const glm::vec3& e)\n  {\n    this->gazePoint = g;\n    this->toEyePoint = e;\n\n    if (Util::colinear (e, this->up ()))\n    {\n      this->right = glm::vec3 (1.0f, 0.0f, 0.0f);\n    }\n    else\n    {\n      this->right = glm::normalize (glm::cross (this->up (), this->toEyePoint));\n    }\n    this->updateView ();\n  }\n\n  void setGaze (const glm::vec3& g)\n  {\n    this->gazePoint = g;\n    this->updateView ();\n  }\n\n  void stepAlongGaze (float factor)\n  {\n    constexpr float minD = 0.01f;\n    constexpr float maxD = 1000.0f;\n\n    const float d = glm::length (this->toEyePoint);\n    const float newD = d * factor;\n\n    if (minD <= newD && newD <= maxD)\n    {\n      this->toEyePoint *= glm::vec3 (factor);\n    }\n    this->updateView ();\n  }\n\n  void verticalRotation (float angle)\n  {\n    const glm::quat q = glm::angleAxis (angle, this->up ());\n    this->right = glm::rotate (q, this->right);\n    this->toEyePoint = glm::rotate (q, this->toEyePoint);\n    this->updateView ();\n  }\n\n  void horizontalRotation (float angle)\n  {\n    const glm::quat q = glm::angleAxis (angle, this->right);\n    this->toEyePoint = glm::rotate (q, this->toEyePoint);\n    this->updateView ();\n  }\n\n  glm::vec4 viewport () const { return glm::vec4 (0, 0, this->resolution.x, this->resolution.y); }\n\n  glm::vec2 fromWorld (const glm::vec3& p, const glm::mat4x4& model, bool onlyRotation) const\n  {\n    const glm::mat4x4 mv = onlyRotation ? this->viewRotation * model : this->view * model;\n    const glm::vec3   w = glm::project (p, mv, this->projection, this->viewport ());\n\n    return glm::vec2 (w.x, float(resolution.y) - w.y);\n  }\n\n  glm::vec3 toWorld (const glm::ivec2& p, float z = 0.0f) const\n  {\n    const float invY = this->resolution.y - float(p.y);\n    const float normZ = z / this->farClipping;\n    return glm::unProject (glm::vec3 (float(p.x), invY, normZ), this->view, this->projection,\n                           this->viewport ());\n  }\n\n  float toWorld (float length, float z)\n  {\n    const float onNearPlane = 2.0f * this->nearClipping * glm::tan (this->fieldOfView * 0.5f) *\n                              length / float(this->resolution.x);\n    return onNearPlane * (this->nearClipping + z) / this->nearClipping;\n  }\n\n  PrimRay ray (const glm::ivec2& p) const\n  {\n    const glm::vec3 w = this->toWorld (p);\n    const glm::vec3 eye = this->position ();\n    return PrimRay (eye, w - eye);\n  }\n\n  void updateProjection ()\n  {\n    OpenGL::glViewport (0, 0, this->resolution.x, this->resolution.y);\n    this->projection =\n      glm::perspective (this->fieldOfView, float(this->resolution.x) / float(this->resolution.y),\n                        this->nearClipping, this->farClipping);\n  }\n\n  void updateView ()\n  {\n    const glm::vec3 up = this->realUp ();\n\n    this->view = glm::lookAt (this->position (), this->gazePoint, up);\n    this->viewRotation = glm::lookAt (glm::normalize (this->toEyePoint), glm::vec3 (0.0f), up);\n    this->renderer.setEyePoint (this->position ());\n  }\n\n  Dimension primaryDimension () const\n  {\n    const glm::vec3 t = glm::abs (this->toEyePoint);\n    if (t.x > t.y && t.x > t.z)\n    {\n      return Dimension::X;\n    }\n    else if (t.y > t.z)\n    {\n      return Dimension::Y;\n    }\n    return Dimension::Z;\n  }\n\n  glm::vec3 planeIntersection (const glm::ivec2& p, const PrimPlane& plane) const\n  {\n    const PrimRay ray = this->ray (p);\n    float         t;\n\n    if (IntersectionUtil::intersects (ray, plane, &t))\n    {\n      return ray.pointAt (t);\n    }\n    else\n    {\n      DILAY_WARN (\"No view-plane intersection\");\n      return plane.point ();\n    }\n  }\n\n  glm::vec3 viewPlaneIntersection (const glm::ivec2& p) const\n  {\n    const PrimPlane plane (this->gazePoint, this->toEyePoint);\n    return this->planeIntersection (p, plane);\n  }\n\n  glm::vec3 primaryPlaneIntersection (const glm::ivec2& p) const\n  {\n    const PrimPlane plane (this->gazePoint, DimensionUtil::vector (this->primaryDimension ()));\n    return this->planeIntersection (p, plane);\n  }\n\n  void runFromConfig (const Config& config)\n  {\n    this->renderer.fromConfig (config);\n\n    this->nearClipping = config.get<float> (\"editor/camera/near-clipping\");\n    this->farClipping = config.get<float> (\"editor/camera/far-clipping\");\n    this->fieldOfView = glm::radians (config.get<float> (\"editor/camera/field-of-view\"));\n\n    this->updateProjection ();\n  }\n};\n\nDELEGATE1_BIG3_SELF (Camera, const Config&)\n\nGETTER_CONST (Renderer&, Camera, renderer)\nGETTER_CONST (const glm::uvec2&, Camera, resolution)\nGETTER_CONST (const glm::vec3&, Camera, gazePoint)\nGETTER_CONST (const glm::vec3&, Camera, toEyePoint)\nDELEGATE_CONST (glm::vec3, Camera, realUp)\nGETTER_CONST (const glm::vec3&, Camera, right)\nGETTER_CONST (const glm::mat4x4&, Camera, view)\nGETTER_CONST (const glm::mat4x4&, Camera, viewRotation)\nDELEGATE_CONST (glm::vec3, Camera, position)\nDELEGATE_CONST (glm::mat4x4, Camera, world)\nDELEGATE1 (void, Camera, updateResolution, const glm::uvec2&)\nDELEGATE3 (void, Camera, setModelViewProjection, const glm::mat4x4&, const glm::mat3x3&, bool)\nDELEGATE2 (void, Camera, set, const glm::vec3&, const glm::vec3&)\nDELEGATE1 (void, Camera, setGaze, const glm::vec3&)\nDELEGATE1 (void, Camera, stepAlongGaze, float)\nDELEGATE1 (void, Camera, verticalRotation, float)\nDELEGATE1 (void, Camera, horizontalRotation, float)\nDELEGATE3_CONST (glm::vec2, Camera, fromWorld, const glm::vec3&, const glm::mat4x4&, bool)\nDELEGATE2_CONST (glm::vec3, Camera, toWorld, const glm::ivec2&, float)\nDELEGATE2_CONST (float, Camera, toWorld, float, float)\nDELEGATE1_CONST (PrimRay, Camera, ray, const glm::ivec2&)\nDELEGATE_CONST (Dimension, Camera, primaryDimension)\nDELEGATE1_CONST (glm::vec3, Camera, viewPlaneIntersection, const glm::ivec2&)\nDELEGATE1_CONST (glm::vec3, Camera, primaryPlaneIntersection, const glm::ivec2&)\nDELEGATE1 (void, Camera, runFromConfig, const Config&)\n"
  },
  {
    "path": "lib/src/camera.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_CAMERA\n#define DILAY_CAMERA\n\n#include <glm/fwd.hpp>\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n\nenum class Dimension;\nclass PrimRay;\nclass Renderer;\n\nclass Camera : public Configurable\n{\npublic:\n  DECLARE_BIG3 (Camera, const Config&)\n\n  Renderer&          renderer () const;\n  const glm::uvec2&  resolution () const;\n  const glm::vec3&   gazePoint () const;\n  const glm::vec3&   toEyePoint () const;\n  glm::vec3          realUp () const;\n  const glm::vec3&   right () const;\n  const glm::mat4x4& view () const;\n  const glm::mat4x4& viewRotation () const;\n  glm::vec3          position () const;\n  glm::mat4x4        world () const;\n\n  void updateResolution (const glm::uvec2&);\n  void setModelViewProjection (const glm::mat4x4&, const glm::mat3x3&, bool);\n\n  void      set (const glm::vec3&, const glm::vec3&);\n  void      setGaze (const glm::vec3&);\n  void      stepAlongGaze (float);\n  void      verticalRotation (float);\n  void      horizontalRotation (float);\n  glm::vec2 fromWorld (const glm::vec3&, const glm::mat4x4&, bool) const;\n  glm::vec3 toWorld (const glm::ivec2&, float = 0.0f) const;\n  float     toWorld (float, float = 0.0f) const;\n  PrimRay   ray (const glm::ivec2&) const;\n  Dimension primaryDimension () const;\n  glm::vec3 viewPlaneIntersection (const glm::ivec2&) const;\n  glm::vec3 primaryPlaneIntersection (const glm::ivec2&) const;\n\nprivate:\n  IMPLEMENTATION\n\n  void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/color.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QColor>\n#include <glm/glm.hpp>\n#include \"color.hpp\"\n#include \"util.hpp\"\n\nColor::Color (float r, float g, float b, float o)\n  : _r (r)\n  , _g (g)\n  , _b (b)\n  , _opacity (o)\n{\n}\n\nColor::Color ()\n  : Color (0.0f, 0.0f, 0.0f, 1.0f)\n{\n}\n\nColor::Color (float v)\n  : Color (v, v, v, 1.0f)\n{\n}\n\nColor::Color (float r, float g, float b)\n  : Color (r, g, b, 1.0f)\n{\n}\n\nColor::Color (const glm::vec3& v)\n  : Color (v.x, v.y, v.z)\n{\n}\n\nColor::Color (const glm::vec4& v)\n  : Color (v.x, v.y, v.z, v.w)\n{\n}\n\nColor::Color (const QColor& c)\n  : Color (c.redF (), c.greenF (), c.blueF (), c.alphaF ())\n{\n}\n\nColor::Color (const Color& c, float f)\n  : Color (c)\n{\n  this->scale (f);\n}\n\nColor Color::Black () { return Color (0.0f, 0.0f, 0.0f); }\n\nColor Color::White () { return Color (1.0f, 1.0f, 1.0f); }\n\nColor Color::Red () { return Color (1.0f, 0.0f, 0.0f); }\n\nColor Color::Green () { return Color (0.0f, 1.0f, 0.0f); }\n\nColor Color::Blue () { return Color (0.0f, 0.0f, 1.0f); }\n\nfloat Color::r () const { return this->_r; }\n\nfloat Color::g () const { return this->_g; }\n\nfloat Color::b () const { return this->_b; }\n\nfloat Color::opacity () const { return this->_opacity; }\n\nvoid Color::r (float v) { this->_r = v; }\n\nvoid Color::g (float v) { this->_g = v; }\n\nvoid Color::b (float v) { this->_b = v; }\n\nvoid Color::opacity (float v) { this->_opacity = v; }\n\nvoid Color::scale (float f)\n{\n  this->_r = f * this->_r;\n  this->_g = f * this->_g;\n  this->_b = f * this->_b;\n}\n\nglm::vec3 Color::vec3 () const { return glm::vec3 (this->_r, this->_g, this->_b); }\n\nglm::vec4 Color::vec4 () const { return glm::vec4 (this->_r, this->_g, this->_b, this->_opacity); }\n\nQColor Color::qColor () const\n{\n  return QColor (glm::min (255, int(255.0f * this->_r)), glm::min (255, int(255.0f * this->_g)),\n                 glm::min (255, int(255.0f * this->_b)),\n                 glm::min (255, int(255.0f * this->_opacity)));\n}\n\nbool Color::isOpaque () const { return Util::almostEqual (this->_opacity, 1.0f); }\n"
  },
  {
    "path": "lib/src/color.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_COLOR\n#define DILAY_COLOR\n\n#include <glm/fwd.hpp>\n\nclass QColor;\n\nclass Color\n{\npublic:\n  Color ();\n  Color (float);\n  Color (float, float, float);\n  Color (float, float, float, float);\n  explicit Color (const glm::vec3&);\n  explicit Color (const glm::vec4&);\n  explicit Color (const QColor&);\n\n  // copies and scales a color using `scale`\n  Color (const Color&, float);\n\n  static Color Black ();\n  static Color White ();\n  static Color Red ();\n  static Color Green ();\n  static Color Blue ();\n\n  float r () const;\n  float g () const;\n  float b () const;\n  float opacity () const;\n\n  void r (float);\n  void g (float);\n  void b (float);\n  void opacity (float);\n\n  // `scale` does not scale opacity\n  void scale (float);\n\n  glm::vec3 vec3 () const;\n  glm::vec4 vec4 () const;\n  QColor    qColor () const;\n  bool      isOpaque () const;\n\nprivate:\n  float _r;\n  float _g;\n  float _b;\n  float _opacity;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/config.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <functional>\n#include <glm/glm.hpp>\n#include \"color.hpp\"\n#include \"config.hpp\"\n\nnamespace\n{\n  static constexpr int latestVersion = 10;\n\n  template <typename T>\n  void updateValue (Config& config, const std::string& path, const T& oldValue, const T& newValue)\n  {\n    if (config.get<T> (path) == oldValue)\n    {\n      config.set (path, newValue);\n    }\n  }\n\n  template <typename T>\n  void forceUpdateValue (Config& config, const std::string& path, const T& newValue)\n  {\n    config.set (path, newValue);\n  }\n\n  template <typename T>\n  void mapValue (Config& config, const std::string& path, const std::function<T (const T&)>& f)\n  {\n    config.set (path, f (config.get<T> (path)));\n  }\n}\n\nConfig::Config ()\n  : store (\"config\")\n{\n  this->restoreDefaults ();\n}\n\nvoid Config::restoreDefaults ()\n{\n  this->store.reset ();\n\n  this->set (\"version\", latestVersion);\n\n  this->set (\"editor/axis/color/normal\", Color (0.3f, 0.3f, 0.4f));\n  this->set (\"editor/axis/color/label\", Color (1.0f, 1.0f, 1.0f));\n  this->set (\"editor/axis/scaling\", glm::vec3 (0.01f, 0.3f, 0.01f));\n  this->set (\"editor/axis/arrow-scaling\", glm::vec3 (0.03f, 0.1f, 0.03f));\n\n  this->set (\"editor/floor-plane/color\", Color (0.3f, 0.3f, 0.4f));\n  this->set (\"editor/floor-plane/tile-width\", 1.0f);\n\n  this->set (\"editor/background\", Color (0.1f, 0.1f, 0.2f));\n  this->set (\"editor/on-screen-color\", Color (0.4f, 0.4f, 0.9f, 0.6f));\n\n  this->set (\"editor/camera/near-clipping\", 0.01f);\n  this->set (\"editor/camera/far-clipping\", 1000.0f);\n  this->set (\"editor/camera/rotation-factor\", 1.0f);\n  this->set (\"editor/camera/movement-factor\", 0.01f);\n  this->set (\"editor/camera/zoom-in-mouse-wheel-factor\", 0.9f);\n  this->set (\"editor/camera/field-of-view\", 45.0f);\n\n  this->set (\"editor/light/light1/direction\", glm::vec3 (0.2f, -1.0f, -0.2f));\n  this->set (\"editor/light/light1/color\", Color (1.0f, 1.0f, 1.0f));\n  this->set (\"editor/light/light1/irradiance\", 0.7f);\n\n  this->set (\"editor/light/light2/direction\", glm::vec3 (0.0f, 0.0f, -1.0f));\n  this->set (\"editor/light/light2/color\", Color (1.0f, 1.0f, 1.0f));\n  this->set (\"editor/light/light2/irradiance\", 0.8f);\n\n  this->set (\"editor/mesh/color/normal\", Color (0.8f, 0.8f, 0.8f));\n  this->set (\"editor/mesh/color/wireframe\", Color (0.3f, 0.3f, 0.3f));\n\n  this->set (\"editor/sketch/node/color\", Color (0.5f, 0.5f, 0.9f));\n  this->set (\"editor/sketch/bubble/color\", Color (0.5f, 0.5f, 0.7f));\n  this->set (\"editor/sketch/sphere/color\", Color (0.7f, 0.7f, 0.9f));\n\n  this->set (\"editor/tool/cursor-color\", Color (1.0f, 0.9f, 0.9f));\n\n  this->set (\"editor/tool/sculpt/detail-factor\", 0.75f);\n  this->set (\"editor/tool/sculpt/step-width-factor\", 0.3f);\n  this->set (\"editor/tool/sculpt/max-absolute-radius\", 2.0f);\n  this->set (\"editor/tool/sculpt/mirror/render\", false);\n  this->set (\"editor/tool/sculpt/mirror/width\", 0.02f);\n  this->set (\"editor/tool/sculpt/mirror/color\", Color (0.8f, 0.8f, 0.8f));\n\n  this->set (\"editor/tool/sketch-spheres/step-width-factor\", 0.3f);\n\n  this->set (\"editor/undo-depth\", 15);\n\n  this->set (\"editor/tablet-pressure-intensity\", 1.0f);\n\n  this->set (\"editor/use-geometry-shader\", true);\n\n  this->set (\"window/initial-width\", 1024);\n  this->set (\"window/initial-height\", 768);\n}\n\nvoid Config::update ()\n{\n  const int version = this->get<int> (\"version\");\n\n  switch (version)\n  {\n    case 1:\n      break;\n\n    case 2:\n      break;\n\n    case 3:\n      updateValue<int> (*this, \"editor/undo-depth\", 5, 15);\n      break;\n\n    case 4:\n      this->remove (\"editor/camera/gaze-point\");\n      this->remove (\"editor/camera/eye-point\");\n      this->remove (\"editor/camera/up\");\n      break;\n\n    case 5:\n      mapValue<glm::vec3> (*this, \"editor/light/light1/direction\",\n                           [](const glm::vec3& v) { return -v; });\n      mapValue<glm::vec3> (*this, \"editor/light/light2/direction\",\n                           [](const glm::vec3& v) { return -v; });\n      break;\n\n    case 6:\n      forceUpdateValue<float> (*this, \"editor/tool/sculpt/step-width-factor\", 0.3f);\n      forceUpdateValue<float> (*this, \"editor/tool/sketch-spheres/step-width-factor\", 0.3f);\n      break;\n\n    case 7:\n      forceUpdateValue<float> (*this, \"editor/camera/zoom-in-factor\", 0.95f);\n      break;\n\n    case 8:\n      this->remove (\"editor/tool/sculpt/cursor-color\");\n      this->remove (\"editor/tool/sketch-spheres/cursor-color\");\n      break;\n\n    case 9:\n      this->remove (\"editor/camera/zoom-in-factor\");\n      break;\n\n    case latestVersion:\n      return;\n\n    default:\n      this->restoreDefaults ();\n      return;\n  }\n  this->set (\"version\", version + 1);\n  this->update ();\n}\n"
  },
  {
    "path": "lib/src/config.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_CONFIG\n#define DILAY_CONFIG\n\n#include \"kvstore.hpp\"\n\nclass Config\n{\npublic:\n  Config ();\n\n  template <class T> const T& get (const std::string& path) const\n  {\n    return this->store.get<T> (path);\n  }\n\n  template <class T> void set (const std::string& path, const T& value)\n  {\n    this->store.set<T> (path, value);\n  }\n\n  void fromFile (const std::string& fileName)\n  {\n    this->store.fromFile (fileName);\n    this->update ();\n  }\n\n  void toFile (const std::string& fileName) const { this->store.toFile (fileName); }\n\n  void remove (const std::string& path) { this->store.remove (path); }\n\n  void restoreDefaults ();\n\nprivate:\n  void update ();\n\n  KVStore store;\n};\n\nclass ConfigProxy\n{\npublic:\n  ConfigProxy (const Config& c, const std::string& p)\n    : _config (c)\n    , prefix (p)\n  {\n    assert (p.back () == '/');\n  }\n\n  ConfigProxy (const ConfigProxy& o, const std::string& path)\n    : ConfigProxy (o._config, o.prefix + path)\n  {\n  }\n\n  const Config& config () const { return this->_config; }\n\n  std::string key (const std::string& path) const { return this->prefix + path; }\n\n  template <class T> const T& get (const std::string& path) const\n  {\n    return this->_config.get<T> (this->key (path));\n  }\n\nprivate:\n  const Config&     _config;\n  const std::string prefix;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/configurable.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"configurable.hpp\"\n\nvoid Configurable::fromConfig (const Config& c) { this->runFromConfig (c); }\n\nvoid ProxyConfigurable::fromConfig (const ConfigProxy& c) { this->runFromConfig (c); }\n"
  },
  {
    "path": "lib/src/configurable.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_CONFIGURABLE\n#define DILAY_CONFIGURABLE\n\nclass Config;\nclass ConfigProxy;\n\nclass Configurable\n{\npublic:\n  void fromConfig (const Config&);\n\nprivate:\n  virtual void runFromConfig (const Config&) = 0;\n};\n\nclass ProxyConfigurable\n{\npublic:\n  void fromConfig (const ConfigProxy&);\n\nprivate:\n  virtual void runFromConfig (const ConfigProxy&) = 0;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/dimension.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <cstdlib>\n#include <glm/glm.hpp>\n#include \"dimension.hpp\"\n#include \"util.hpp\"\n\nunsigned int DimensionUtil::index (Dimension d)\n{\n  switch (d)\n  {\n    case Dimension::X:\n      return 0;\n    case Dimension::Y:\n      return 1;\n    case Dimension::Z:\n      return 2;\n  }\n  DILAY_IMPOSSIBLE\n}\n\nglm::vec3 DimensionUtil::vector (Dimension d)\n{\n  switch (d)\n  {\n    case Dimension::X:\n      return glm::vec3 (1.0f, 0.0f, 0.0f);\n    case Dimension::Y:\n      return glm::vec3 (0.0f, 1.0f, 0.0f);\n    case Dimension::Z:\n      return glm::vec3 (0.0f, 0.0f, 1.0f);\n  }\n  DILAY_IMPOSSIBLE\n}\n"
  },
  {
    "path": "lib/src/dimension.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_DIMENSION\n#define DILAY_DIMENSION\n\n#include <glm/fwd.hpp>\n\nenum class Dimension\n{\n  X,\n  Y,\n  Z\n};\n\nnamespace DimensionUtil\n{\n  unsigned int index (Dimension);\n  glm::vec3    vector (Dimension);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/distance.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"distance.hpp\"\n#include \"primitive/cone-sphere.hpp\"\n#include \"primitive/cone.hpp\"\n#include \"primitive/cylinder.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  float distanceToCylinder (const glm::vec3& center1, float radius, float length,\n                            const glm::vec3& direction, const glm::vec3& point)\n  {\n    const glm::vec3 toP = point - center1;\n    const float     x = glm::dot (toP, direction);\n    const float     ySqr = glm::dot (toP, toP) - (x * x);\n    const float     y = Util::almostEqual (0.0f, ySqr) ? 0.0f : glm::sqrt (ySqr);\n    const float     yr = y - radius;\n    const float     xl = x - length;\n    const bool      insideR = yr <= 0.0f;\n\n    if (x <= 0.0f)\n    {\n      return insideR ? glm::abs (x) : glm::sqrt ((x * x) + (yr * yr));\n    }\n    else if (x >= length)\n    {\n      return insideR ? xl : glm::sqrt ((xl * xl) + (yr * yr));\n    }\n    else\n    {\n      return insideR ? glm::max (-x, glm::max (yr, xl)) : yr;\n    }\n  }\n}\n\nfloat Distance::distance (const PrimSphere& sphere, const glm::vec3& point)\n{\n  return glm::distance (sphere.center (), point) - sphere.radius ();\n}\n\nfloat Distance::distance (const PrimCylinder& cylinder, const glm::vec3& point)\n{\n  return distanceToCylinder (cylinder.center1 (), cylinder.radius (), cylinder.length (),\n                             cylinder.direction (), point);\n}\n\nfloat Distance::distance (const PrimCone& cone, const glm::vec3& point)\n{\n  if (cone.isCylinder ())\n  {\n    return distanceToCylinder (cone.center1 (), cone.radius1 (), cone.length (), cone.direction (),\n                               point);\n  }\n  else\n  {\n    const glm::vec3 toP = point - cone.center1 ();\n    const float     x = glm::dot (toP, cone.direction ());\n    const float     ySqr = glm::dot (toP, toP) - (x * x);\n    const float     y = Util::almostEqual (0.0f, ySqr) ? 0.0f : glm::sqrt (ySqr);\n    const float     r1 = cone.radius1 ();\n    const float     r2 = cone.radius2 ();\n    const float     l = cone.length ();\n\n    if (x <= 0.0f)\n    {\n      return y <= r1 ? -x : glm::sqrt ((x * x) + ((y - r1) * (y - r1)));\n    }\n    else if (x >= l && y <= r2)\n    {\n      return x - l;\n    }\n    else\n    {\n      const float xn = (x * cone.cosAlpha ()) - ((y - r1) * cone.sinAlpha ());\n      const float yn = (x * cone.sinAlpha ()) + ((y - r1) * cone.cosAlpha ());\n      const float delta = r1 - r2;\n      const float s = glm::sqrt ((l * l) + (delta * delta));\n\n      if (xn <= 0.0f)\n      {\n        return glm::sqrt ((x * x) + ((y - r1) * (y - r1)));\n      }\n      else if (xn >= s)\n      {\n        if (x <= l)\n        {\n          assert (yn <= 0.0f);\n          return x - l;\n        }\n        else\n        {\n          return glm::sqrt ((yn * yn) + ((xn - s) * (xn - s)));\n        }\n      }\n      else if (yn >= 0.0f)\n      {\n        return yn;\n      }\n      else\n      {\n        return glm::max (-x, glm::max (yn, x - l));\n      }\n    }\n  }\n}\n\nfloat Distance::distance (const PrimConeSphere& coneSphere, const glm::vec3& point)\n{\n  const glm::vec3 toP = point - coneSphere.sphere1 ().center ();\n  const float     x = glm::dot (toP, coneSphere.direction ());\n  const float     ySqr = glm::dot (toP, toP) - (x * x);\n  const float     y = Util::almostEqual (0.0f, ySqr) ? 0.0f : glm::sqrt (ySqr);\n  const float     r1 = coneSphere.sphere1 ().radius ();\n  const float     r2 = coneSphere.sphere2 ().radius ();\n  const float     l = coneSphere.length ();\n\n  if (coneSphere.sameRadii ())\n  {\n    if (x <= 0.0f)\n    {\n      return glm::sqrt ((x * x) + (y * y)) - r1;\n    }\n    else if (x >= l)\n    {\n      return glm::sqrt (((x - l) * (x - l)) + (y * y)) - r1;\n    }\n    else\n    {\n      return y - r1;\n    }\n  }\n  else if (coneSphere.hasCone ())\n  {\n    const float s = coneSphere.coneSideLength ();\n    const float h1 = r1 * coneSphere.delta () / l;\n    const float h2 = r2 * coneSphere.delta () / l;\n    const float r1c = r1 * s / l;\n    const float r2c = r2 * s / l;\n\n    if (x <= 0.0f)\n    {\n      return glm::sqrt ((x * x) + (y * y)) - r1;\n    }\n    else if (x >= l + h2 && y <= r2c)\n    {\n      return glm::sqrt (((x - l) * (x - l)) + (y * y)) - r2;\n    }\n    else\n    {\n      const float xn = ((x - h1) * coneSphere.cosAlpha ()) - ((y - r1c) * coneSphere.sinAlpha ());\n      const float yn = ((x - h1) * coneSphere.sinAlpha ()) + ((y - r1c) * coneSphere.cosAlpha ());\n\n      if (xn <= 0.0f)\n      {\n        return glm::sqrt ((x * x) + (y * y)) - r1;\n      }\n      else if (xn >= s)\n      {\n        return glm::sqrt (((x - l) * (x - l)) + (y * y)) - r2;\n      }\n      else\n      {\n        return yn;\n      }\n    }\n  }\n  else\n  {\n    return glm::sqrt ((x * x) + (y * y)) - r1;\n  }\n}\n\n// cf. https://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf\nfloat Distance::distance (const PrimTriangle& tri, const glm::vec3& point)\n{\n  const glm::vec3& P = point;\n  const glm::vec3& B = tri.vertex1 ();\n  const glm::vec3  E0 = tri.vertex2 () - tri.vertex1 ();\n  const glm::vec3  E1 = tri.vertex3 () - tri.vertex1 ();\n  const glm::vec3  D = B - P;\n\n  const float a = glm::dot (E0, E0);\n  const float b = glm::dot (E0, E1);\n  const float c = glm::dot (E1, E1);\n  const float d = glm::dot (E0, D);\n  const float e = glm::dot (E1, D);\n\n  float       s = (b * e) - (c * d);\n  float       t = (b * d) - (a * e);\n  const float det = (a * c) - (b * b);\n\n  if (s + t <= det)\n  {\n    if (s < 0.0f)\n    {\n      if (t < 0.0f)\n      {\n        // region 4\n        if (d < 0.0f)\n        {\n          t = 0.0f;\n          s = -d > a ? 1.0f : -d / a;\n        }\n        else\n        {\n          s = 0.0f;\n          if (e >= 0.0f)\n          {\n            t = 0.0f;\n          }\n          else if (-e >= c)\n          {\n            t = 1.0f;\n          }\n          else\n          {\n            t = -e / c;\n          }\n        }\n      }\n      else\n      {\n        // region 3\n        s = 0.0f;\n        if (e >= 0.0f)\n        {\n          t = 0.0f;\n        }\n        else if (-e >= c)\n        {\n          t = 1.0f;\n        }\n        else\n        {\n          t = -e / c;\n        }\n      }\n    }\n    else if (t < 0.0f)\n    {\n      // region 5\n      t = 0.0f;\n      if (d >= 0.0f)\n      {\n        s = 0.0f;\n      }\n      else if (-d >= a)\n      {\n        s = 1.0f;\n      }\n      else\n      {\n        s = -d / a;\n      }\n    }\n    else\n    {\n      // region 0\n      s /= det;\n      t /= det;\n    }\n  }\n  else\n  {\n    if (s < 0.0f)\n    {\n      // region 2\n      const float tmp0 = b + d;\n      const float tmp1 = c + e;\n      if (tmp1 > tmp0)\n      {\n        const float numer = tmp1 - tmp0;\n        const float denom = a - (2.0f * b) + c;\n        s = numer >= denom ? 1.0f : numer / denom;\n        t = 1.0f - s;\n      }\n      else\n      {\n        s = 0.0f;\n        if (tmp1 <= 0.0f)\n        {\n          t = 1.0f;\n        }\n        else if (e >= 0.0f)\n        {\n          t = 0.0f;\n        }\n        else\n        {\n          t = -e / c;\n        }\n      }\n    }\n    else if (t < 0.0f)\n    {\n      // region 6\n      const float tmp0 = b + e;\n      const float tmp1 = a + d;\n      if (tmp1 > tmp0)\n      {\n        const float numer = tmp1 - tmp0;\n        const float denom = a - (2.0f * b) + c;\n        t = numer >= denom ? 1.0f : numer / denom;\n        s = 1.0f - t;\n      }\n      else\n      {\n        t = 0.0f;\n        if (tmp1 <= 0.0f)\n        {\n          s = 1.0f;\n        }\n        else if (d >= 0.0f)\n        {\n          s = 0.0f;\n        }\n        else\n        {\n          s = -d / a;\n        }\n      }\n    }\n    else\n    {\n      // region 1\n      const float numer = (c + e) - (b + d);\n      if (numer <= 0.0f)\n      {\n        s = 0.0f;\n      }\n      else\n      {\n        const float denom = a - (2.0f * b) + c;\n        s = numer >= denom ? 1.0f : numer / denom;\n      }\n      t = 1.0f - s;\n    }\n  }\n  return glm::distance (point, B + (s * E0) + (t * E1));\n}\n"
  },
  {
    "path": "lib/src/distance.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_DISTANCE\n#define DILAY_DISTANCE\n\n#include <glm/fwd.hpp>\n\nclass PrimCone;\nclass PrimConeSphere;\nclass PrimCylinder;\nclass PrimSphere;\nclass PrimTriangle;\n\nnamespace Distance\n{\n  float distance (const PrimSphere&, const glm::vec3&);\n  float distance (const PrimCylinder&, const glm::vec3&);\n  float distance (const PrimCone&, const glm::vec3&);\n  float distance (const PrimConeSphere&, const glm::vec3&);\n  float distance (const PrimTriangle&, const glm::vec3&);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/dynamic/faces.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"dynamic/faces.hpp\"\n\nvoid DynamicFaces::insert (unsigned int i) { this->_uncommitted.insert (i); }\n\nvoid DynamicFaces::insert (const DynamicFaces::Container& v)\n{\n  this->_uncommitted.insert (v.begin (), v.end ());\n}\n\nvoid DynamicFaces::reset ()\n{\n  this->resetCommitted ();\n  this->_uncommitted.clear ();\n}\n\nvoid DynamicFaces::resetCommitted () { this->_indices.clear (); }\n\nvoid DynamicFaces::commit ()\n{\n  if (this->_indices.empty ())\n  {\n    this->_indices.swap (this->_uncommitted);\n  }\n  else\n  {\n    this->_indices.insert (this->_uncommitted.begin (), this->_uncommitted.end ());\n    this->_uncommitted.clear ();\n  }\n}\n\nbool DynamicFaces::contains (unsigned int i) const\n{\n  return this->_indices.find (i) != this->_indices.end ();\n}\n\nbool DynamicFaces::isEmpty () const\n{\n  return this->_indices.empty () && this->_uncommitted.empty ();\n}\n\nbool DynamicFaces::hasUncomitted () const { return this->_uncommitted.empty () == false; }\n\nvoid DynamicFaces::filter (const std::function<bool(unsigned int)>& f)\n{\n  for (auto it = this->_indices.begin (); it != this->_indices.end ();)\n  {\n    if (f (*it) == false)\n    {\n      it = this->_indices.erase (it);\n    }\n    else\n    {\n      ++it;\n    }\n  }\n  for (auto it = this->_uncommitted.begin (); it != this->_uncommitted.end ();)\n  {\n    if (f (*it) == false)\n    {\n      it = this->_uncommitted.erase (it);\n    }\n    else\n    {\n      ++it;\n    }\n  }\n}\n"
  },
  {
    "path": "lib/src/dynamic/faces.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_DYNAMIC_FACES\n#define DILAY_DYNAMIC_FACES\n\n#include <functional>\n#include <unordered_set>\n\nclass DynamicFaces\n{\npublic:\n  typedef std::unordered_set<unsigned int> Container;\n\n  const Container& indices () const { return this->_indices; }\n  const Container& uncommitted () const { return this->_uncommitted; }\n  unsigned int     numElements () const { return this->_indices.size (); }\n\n  Container::iterator       begin () { return this->_indices.begin (); }\n  Container::iterator       end () { return this->_indices.end (); }\n  Container::const_iterator begin () const { return this->_indices.begin (); }\n  Container::const_iterator end () const { return this->_indices.end (); }\n\n  void insert (unsigned int);\n  void insert (const Container&);\n  void reset ();\n  void resetCommitted ();\n  void commit ();\n  bool contains (unsigned int) const;\n  bool isEmpty () const;\n  bool hasUncomitted () const;\n  void filter (const std::function<bool(unsigned int)>&);\n\nprivate:\n  Container _indices;\n  Container _uncommitted;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/dynamic/mesh-intersection.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"util.hpp\"\n\nDynamicMeshIntersection::DynamicMeshIntersection ()\n  : _faceIndex (Util::invalidIndex ())\n  , _mesh (nullptr)\n{\n}\n\nbool DynamicMeshIntersection::update (float d, const glm::vec3& p, const glm::vec3& n,\n                                      unsigned int i, DynamicMesh& mesh)\n{\n  if (this->Intersection::update (d, p, n))\n  {\n    this->_mesh = &mesh;\n    this->_faceIndex = i;\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nunsigned int DynamicMeshIntersection::faceIndex () const\n{\n  assert (this->isIntersection ());\n  return this->_faceIndex;\n}\n\nDynamicMesh& DynamicMeshIntersection::mesh () const\n{\n  assert (this->isIntersection ());\n  assert (this->_mesh);\n  return *this->_mesh;\n}\n"
  },
  {
    "path": "lib/src/dynamic/mesh-intersection.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_DYNAMIC_MESH_INTERSECTION\n#define DILAY_DYNAMIC_MESH_INTERSECTION\n\n#include \"intersection.hpp\"\n\nclass DynamicMesh;\n\nclass DynamicMeshIntersection : public Intersection\n{\npublic:\n  DynamicMeshIntersection ();\n\n  DynamicMesh& mesh () const;\n  unsigned int faceIndex () const;\n  bool         update (float, const glm::vec3&, const glm::vec3&, unsigned int, DynamicMesh&);\n\nprivate:\n  unsigned int _faceIndex;\n  DynamicMesh* _mesh;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/dynamic/mesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <cstring>\n#include <glm/glm.hpp>\n#include <glm/gtx/norm.hpp>\n#include <vector>\n#include \"../mesh.hpp\"\n#include \"config.hpp\"\n#include \"distance.hpp\"\n#include \"dynamic/faces.hpp\"\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"dynamic/octree.hpp\"\n#include \"intersection.hpp\"\n#include \"mesh-util.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"tool/sculpt/util/action.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  struct VertexData\n  {\n    bool                      isFree;\n    std::vector<unsigned int> adjacentFaces;\n\n    VertexData () { this->reset (); }\n    void reset ()\n    {\n      this->isFree = true;\n      this->adjacentFaces.clear ();\n    }\n\n    void addAdjacentFace (unsigned int face) { this->adjacentFaces.push_back (face); }\n\n    void deleteAdjacentFace (unsigned int face)\n    {\n      for (auto it = this->adjacentFaces.begin (); it != this->adjacentFaces.end (); ++it)\n      {\n        if (*it == face)\n        {\n          this->adjacentFaces.erase (it);\n          return;\n        }\n      }\n      DILAY_IMPOSSIBLE\n    }\n  };\n\n  struct FaceData\n  {\n    bool isFree;\n\n    FaceData () { this->reset (); }\n    void reset () { this->isFree = true; }\n  };\n}\n\nstruct DynamicMesh::Impl\n{\n  DynamicMesh*               self;\n  Mesh                       mesh;\n  std::vector<VertexData>    vertexData;\n  std::vector<unsigned char> vertexVisited;\n  std::vector<unsigned int>  freeVertexIndices;\n  std::vector<FaceData>      faceData;\n  std::vector<unsigned char> faceVisited;\n  std::vector<unsigned int>  freeFaceIndices;\n  DynamicOctree              octree;\n\n  Impl (DynamicMesh* s)\n    : self (s)\n  {\n  }\n\n  Impl (DynamicMesh* s, const Mesh& m)\n    : self (s)\n  {\n    this->fromMesh (m);\n  }\n\n  unsigned int numVertices () const\n  {\n    assert (this->mesh.numVertices () >= this->freeVertexIndices.size ());\n    assert (this->mesh.numVertices () == this->vertexData.size ());\n    return this->mesh.numVertices () - this->freeVertexIndices.size ();\n  }\n\n  unsigned int numFaces () const\n  {\n    assert (this->faceData.size () >= this->freeFaceIndices.size ());\n    return this->faceData.size () - this->freeFaceIndices.size ();\n  }\n\n  bool isEmpty () const { return this->numFaces () == 0; }\n\n  bool isFreeVertex (unsigned int i) const\n  {\n    assert (i < this->vertexData.size ());\n    return this->vertexData[i].isFree;\n  }\n\n  bool isFreeFace (unsigned int i) const\n  {\n    assert (i < this->faceData.size ());\n    return this->faceData[i].isFree;\n  }\n\n  bool isPruned () const\n  {\n    return this->freeFaceIndices.empty () && this->freeVertexIndices.empty ();\n  }\n\n  unsigned int valence (unsigned int i) const\n  {\n    assert (this->isFreeVertex (i) == false);\n    return this->vertexData[i].adjacentFaces.size ();\n  }\n\n  void vertexIndices (unsigned int i, unsigned int& i1, unsigned int& i2, unsigned int& i3) const\n  {\n    assert (this->isFreeFace (i) == false);\n\n    i1 = this->mesh.index ((3 * i) + 0);\n    i2 = this->mesh.index ((3 * i) + 1);\n    i3 = this->mesh.index ((3 * i) + 2);\n  }\n\n  PrimTriangle face (unsigned int i) const\n  {\n    assert (this->isFreeFace (i) == false);\n\n    return PrimTriangle (this->mesh.vertex (this->mesh.index ((3 * i) + 0)),\n                         this->mesh.vertex (this->mesh.index ((3 * i) + 1)),\n                         this->mesh.vertex (this->mesh.index ((3 * i) + 2)));\n  }\n\n  const glm::vec3& vertexNormal (unsigned int i) const { return this->mesh.normal (i); }\n\n  glm::vec3 faceNormal (unsigned int i) const\n  {\n    assert (this->isFreeFace (i) == false);\n\n    unsigned int i1, i2, i3;\n    this->vertexIndices (i, i1, i2, i3);\n\n    return glm::normalize (glm::cross (this->mesh.vertex (i2) - this->mesh.vertex (i1),\n                                       this->mesh.vertex (i3) - this->mesh.vertex (i1)));\n  }\n\n  void findAdjacent (unsigned int e1, unsigned int e2, unsigned int& leftFace,\n                     unsigned int& leftVertex, unsigned int& rightFace,\n                     unsigned int& rightVertex) const\n  {\n    assert (this->isFreeVertex (e1) == false);\n    assert (this->isFreeVertex (e2) == false);\n\n    leftFace = Util::invalidIndex ();\n    leftVertex = Util::invalidIndex ();\n    rightFace = Util::invalidIndex ();\n    rightVertex = Util::invalidIndex ();\n\n    for (unsigned int a : this->vertexData[e1].adjacentFaces)\n    {\n      unsigned int i1, i2, i3;\n      this->vertexIndices (a, i1, i2, i3);\n\n      if (e1 == i1 && e2 == i2)\n      {\n        leftFace = a;\n        leftVertex = i3;\n      }\n      else if (e1 == i2 && e2 == i1)\n      {\n        rightFace = a;\n        rightVertex = i3;\n      }\n      else if (e1 == i2 && e2 == i3)\n      {\n        leftFace = a;\n        leftVertex = i1;\n      }\n      else if (e1 == i3 && e2 == i2)\n      {\n        rightFace = a;\n        rightVertex = i1;\n      }\n      else if (e1 == i3 && e2 == i1)\n      {\n        leftFace = a;\n        leftVertex = i2;\n      }\n      else if (e1 == i1 && e2 == i3)\n      {\n        rightFace = a;\n        rightVertex = i2;\n      }\n    }\n    assert (leftFace != Util::invalidIndex ());\n    assert (leftVertex != Util::invalidIndex ());\n    assert (rightFace != Util::invalidIndex ());\n    assert (rightVertex != Util::invalidIndex ());\n  }\n\n  const std::vector<unsigned int>& adjacentFaces (unsigned int i) const\n  {\n    assert (this->isFreeVertex (i) == false);\n    return this->vertexData[i].adjacentFaces;\n  }\n\n  void forEachVertex (const std::function<void(unsigned int)>& f) const\n  {\n    for (unsigned int i = 0; i < this->vertexData.size (); i++)\n    {\n      if (this->isFreeVertex (i) == false)\n      {\n        f (i);\n      }\n    }\n  }\n\n  void visitVertices (unsigned int i, const std::function<void(unsigned int)>& f)\n  {\n    assert (this->isFreeFace (i) == false);\n\n    unsigned int i1, i2, i3;\n    this->vertexIndices (i, i1, i2, i3);\n\n    if (this->vertexVisited[i1] == 0)\n    {\n      this->vertexVisited[i1] = 1;\n      f (i1);\n    }\n    if (this->vertexVisited[i2] == 0)\n    {\n      this->vertexVisited[i2] = 1;\n      f (i2);\n    }\n    if (this->vertexVisited[i3] == 0)\n    {\n      this->vertexVisited[i3] = 1;\n      f (i3);\n    }\n    this->faceVisited[i] = 1;\n  }\n\n  void unvisitVertices ()\n  {\n    std::memset (this->vertexVisited.data (), 0, this->vertexVisited.size ());\n  }\n\n  void unvisitFaces () { std::memset (this->faceVisited.data (), 0, this->faceVisited.size ()); }\n\n  void forEachVertex (const DynamicFaces& faces, const std::function<void(unsigned int)>& f)\n  {\n    this->unvisitVertices ();\n\n    for (unsigned int i : faces)\n    {\n      this->visitVertices (i, f);\n    }\n  }\n\n  void forEachVertexExt (const DynamicFaces& faces, const std::function<void(unsigned int)>& f)\n  {\n    this->unvisitVertices ();\n    this->unvisitFaces ();\n\n    for (unsigned int i : faces)\n    {\n      this->visitVertices (i, [this, &f](unsigned int j) {\n        f (j);\n\n        for (unsigned int a : this->vertexData[j].adjacentFaces)\n        {\n          if (this->faceVisited[a] == 0)\n          {\n            this->visitVertices (a, f);\n          }\n        }\n      });\n    }\n  }\n\n  void forEachVertexAdjacentToVertex (unsigned int                             i,\n                                      const std::function<void(unsigned int)>& f) const\n  {\n    assert (this->isFreeVertex (i) == false);\n\n    for (unsigned int a : this->vertexData[i].adjacentFaces)\n    {\n      unsigned int a1, a2, a3;\n      this->vertexIndices (a, a1, a2, a3);\n\n      if (i == a1)\n      {\n        f (a2);\n      }\n      else if (i == a2)\n      {\n        f (a3);\n      }\n      else if (i == a3)\n      {\n        f (a1);\n      }\n      else\n      {\n        DILAY_IMPOSSIBLE\n      }\n    }\n  }\n\n  void forEachVertexAdjacentToFace (unsigned int                             i,\n                                    const std::function<void(unsigned int)>& f) const\n  {\n    assert (this->isFreeFace (i) == false);\n\n    unsigned int i1, i2, i3;\n    this->vertexIndices (i, i1, i2, i3);\n\n    f (i1);\n    f (i2);\n    f (i3);\n  }\n\n  void forEachFace (const std::function<void(unsigned int)>& f) const\n  {\n    for (unsigned int i = 0; i < this->faceData.size (); i++)\n    {\n      if (this->isFreeFace (i) == false)\n      {\n        f (i);\n      }\n    }\n  }\n\n  void forEachFaceExt (const DynamicFaces& faces, const std::function<void(unsigned int)>& f)\n  {\n    this->unvisitVertices ();\n    this->unvisitFaces ();\n\n    for (unsigned int i : faces)\n    {\n      if (this->faceVisited[i] == 0)\n      {\n        f (i);\n        this->faceVisited[i] = 1;\n      }\n      this->visitVertices (i, [this, &f](unsigned int j) {\n        for (unsigned int a : this->vertexData[j].adjacentFaces)\n        {\n          if (this->faceVisited[a] == 0)\n          {\n            f (a);\n            this->faceVisited[a] = 1;\n          }\n        }\n      });\n    }\n  }\n\n  void average (const DynamicFaces& faces, glm::vec3& position, glm::vec3& normal) const\n  {\n    assert (faces.numElements () > 0);\n\n    position = glm::vec3 (0.0f);\n    normal = glm::vec3 (0.0f);\n\n    for (unsigned int f : faces)\n    {\n      unsigned int i1, i2, i3;\n      this->vertexIndices (f, i1, i2, i3);\n\n      position += this->mesh.vertex (i1);\n      position += this->mesh.vertex (i2);\n      position += this->mesh.vertex (i3);\n      normal += glm::cross (this->mesh.vertex (i2) - this->mesh.vertex (i1),\n                            this->mesh.vertex (i3) - this->mesh.vertex (i1));\n    }\n    position /= float(faces.numElements () * 3);\n    normal = glm::normalize (normal);\n  }\n\n  glm::vec3 averagePosition (const DynamicFaces& faces) const\n  {\n    assert (faces.numElements () > 0);\n\n    glm::vec3 position = glm::vec3 (0.0f);\n\n    for (unsigned int f : faces)\n    {\n      this->forEachVertexAdjacentToFace (\n        f, [this, &position](unsigned int v) { position += this->mesh.vertex (v); });\n    }\n    return position / float(faces.numElements () * 3);\n  }\n\n  glm::vec3 averagePosition (unsigned int i) const\n  {\n    assert (this->isFreeVertex (i) == false);\n    assert (this->vertexData[i].adjacentFaces.size () > 0);\n\n    glm::vec3 position = glm::vec3 (0.0f);\n\n    this->forEachVertexAdjacentToVertex (\n      i, [this, &position](unsigned int v) { position += this->mesh.vertex (v); });\n    return position / float(this->vertexData[i].adjacentFaces.size ());\n  }\n\n  glm::vec3 averageNormal (const DynamicFaces& faces) const\n  {\n    assert (faces.numElements () > 0);\n\n    glm::vec3 normal = glm::vec3 (0.0f);\n\n    for (unsigned int f : faces)\n    {\n      unsigned int i1, i2, i3;\n      this->vertexIndices (f, i1, i2, i3);\n\n      normal += glm::cross (this->mesh.vertex (i2) - this->mesh.vertex (i1),\n                            this->mesh.vertex (i3) - this->mesh.vertex (i1));\n    }\n    return glm::normalize (normal);\n  }\n\n  glm::vec3 averageNormal (unsigned int i) const\n  {\n    assert (this->isFreeVertex (i) == false);\n    assert (this->vertexData[i].adjacentFaces.size () > 0);\n\n    glm::vec3 normal = glm::vec3 (0.0f);\n\n    for (unsigned int f : this->vertexData[i].adjacentFaces)\n    {\n      unsigned int i1, i2, i3;\n      this->vertexIndices (f, i1, i2, i3);\n\n      normal += glm::cross (this->mesh.vertex (i2) - this->mesh.vertex (i1),\n                            this->mesh.vertex (i3) - this->mesh.vertex (i1));\n    }\n    return glm::normalize (normal);\n  }\n\n  float averageEdgeLengthSqr (const DynamicFaces& faces) const\n  {\n    assert (faces.numElements () > 0);\n\n    float length = 0.0f;\n    for (unsigned int i : faces)\n    {\n      length += this->averageEdgeLengthSqr (i);\n    }\n    return length / float(faces.numElements ());\n  }\n\n  float averageEdgeLengthSqr (unsigned int i) const\n  {\n    assert (this->isFreeFace (i) == false);\n\n    unsigned int i1, i2, i3;\n    this->vertexIndices (i, i1, i2, i3);\n\n    const glm::vec3& v1 = this->mesh.vertex (i1);\n    const glm::vec3& v2 = this->mesh.vertex (i2);\n    const glm::vec3& v3 = this->mesh.vertex (i3);\n\n    return (glm::distance2 (v1, v2) + glm::distance2 (v1, v3) + glm::distance2 (v2, v3)) / 3.0f;\n  }\n\n  unsigned int addVertex (const glm::vec3& vertex, const glm::vec3& normal)\n  {\n    assert (this->vertexData.size () == this->mesh.numVertices ());\n    assert (this->vertexVisited.size () == this->mesh.numVertices ());\n\n    if (this->freeVertexIndices.empty ())\n    {\n      this->vertexData.emplace_back ();\n      this->vertexData.back ().isFree = false;\n      this->vertexVisited.push_back (0);\n      return this->mesh.addVertex (vertex, normal);\n    }\n    else\n    {\n      const unsigned int index = this->freeVertexIndices.back ();\n      this->mesh.vertex (index, vertex);\n      this->mesh.normal (index, normal);\n      this->vertexData[index].reset ();\n      this->vertexData[index].isFree = false;\n      this->vertexVisited[index] = 0;\n      this->freeVertexIndices.pop_back ();\n      return index;\n    }\n  }\n\n  unsigned int addFace (unsigned int i1, unsigned int i2, unsigned int i3)\n  {\n    assert (i1 < this->mesh.numVertices ());\n    assert (i2 < this->mesh.numVertices ());\n    assert (i3 < this->mesh.numVertices ());\n    assert (3 * this->faceData.size () == this->mesh.numIndices ());\n    assert (this->faceData.size () == this->faceVisited.size ());\n\n    unsigned int index = Util::invalidIndex ();\n\n    if (this->freeFaceIndices.empty ())\n    {\n      index = this->numFaces ();\n      this->faceData.emplace_back ();\n      this->faceVisited.push_back (0);\n\n      this->mesh.addIndex (i1);\n      this->mesh.addIndex (i2);\n      this->mesh.addIndex (i3);\n    }\n    else\n    {\n      index = this->freeFaceIndices.back ();\n      this->faceData[index].reset ();\n      this->faceVisited[index] = 0;\n      this->freeFaceIndices.pop_back ();\n\n      this->mesh.index ((3 * index) + 0, i1);\n      this->mesh.index ((3 * index) + 1, i2);\n      this->mesh.index ((3 * index) + 2, i3);\n    }\n    this->faceData[index].isFree = false;\n\n    this->vertexData[i1].addAdjacentFace (index);\n    this->vertexData[i2].addAdjacentFace (index);\n    this->vertexData[i3].addAdjacentFace (index);\n\n    this->addFaceToOctree (index);\n\n    return index;\n  }\n\n  void addFaceToOctree (unsigned int i)\n  {\n    const PrimTriangle tri = this->face (i);\n\n    if (this->octree.hasRoot () == false)\n    {\n      this->octree.setupRoot (tri.center (), tri.maxDimExtent ());\n    }\n\n    this->octree.addElement (i, tri.center (), tri.maxDimExtent ());\n  }\n\n  void deleteVertex (unsigned int i)\n  {\n    assert (i < this->vertexData.size ());\n    assert (i < this->vertexVisited.size ());\n\n    std::vector<unsigned int> adjacentFaces = this->vertexData[i].adjacentFaces;\n    for (unsigned int f : adjacentFaces)\n    {\n      this->deleteFace (f);\n    }\n    this->vertexData[i].reset ();\n    this->vertexVisited[i] = 0;\n    this->freeVertexIndices.push_back (i);\n  }\n\n  void deleteFace (unsigned int i)\n  {\n    assert (i < this->faceData.size ());\n    assert (i < this->faceVisited.size ());\n\n    this->vertexData[this->mesh.index ((3 * i) + 0)].deleteAdjacentFace (i);\n    this->vertexData[this->mesh.index ((3 * i) + 1)].deleteAdjacentFace (i);\n    this->vertexData[this->mesh.index ((3 * i) + 2)].deleteAdjacentFace (i);\n\n    this->faceData[i].reset ();\n    this->faceVisited[i] = 0;\n    this->freeFaceIndices.push_back (i);\n    this->octree.deleteElement (i);\n  }\n\n  void vertexNormal (unsigned int i, const glm::vec3& n)\n  {\n    assert (this->isFreeVertex (i) == false);\n    assert (this->mesh.numVertices () == this->vertexData.size ());\n\n    this->mesh.normal (i, n);\n  }\n\n  void setVertexNormal (unsigned int i)\n  {\n    const glm::vec3 avg = this->averageNormal (i);\n\n    if (Util::isNaN (avg))\n    {\n      this->mesh.normal (i, glm::vec3 (0.0f));\n    }\n    else\n    {\n      this->mesh.normal (i, avg);\n    }\n  }\n\n  void setAllNormals ()\n  {\n    this->forEachVertex ([this](unsigned int i) { this->setVertexNormal (i); });\n  }\n\n  void reset ()\n  {\n    this->mesh.reset ();\n    this->vertexData.clear ();\n    this->vertexVisited.clear ();\n    this->freeVertexIndices.clear ();\n    this->faceData.clear ();\n    this->faceVisited.clear ();\n    this->freeFaceIndices.clear ();\n    this->octree.reset ();\n  }\n\n  void fromMesh (const Mesh& mesh)\n  {\n    this->reset ();\n    this->mesh.reserveVertices (mesh.numVertices ());\n\n    for (unsigned int i = 0; i < mesh.numVertices (); i++)\n    {\n      this->addVertex (mesh.vertex (i), mesh.normal (i));\n    }\n\n    assert (mesh.numIndices () % 3 == 0);\n    this->mesh.reserveIndices (mesh.numIndices ());\n\n    for (unsigned int i = 0; i < mesh.numIndices (); i += 3)\n    {\n      this->addFace (mesh.index (i), mesh.index (i + 1), mesh.index (i + 2));\n    }\n    this->setAllNormals ();\n    this->mesh.bufferData ();\n  }\n\n  void realignFace (unsigned int i)\n  {\n    assert (this->isFreeFace (i) == false);\n\n    const PrimTriangle tri = this->face (i);\n\n    this->octree.realignElement (i, tri.center (), tri.maxDimExtent ());\n  }\n\n  void realignFaces (const DynamicFaces& faces)\n  {\n    for (unsigned int i : faces)\n    {\n      this->realignFace (i);\n    }\n  }\n\n  void realignAllFaces ()\n  {\n    this->forEachFace ([this](unsigned int i) { this->realignFace (i); });\n  }\n\n  void sanitize ()\n  {\n    this->octree.deleteEmptyChildren ();\n    this->octree.shrinkRoot ();\n  }\n\n  void prune (std::vector<unsigned int>* pVertexIndexMap, std::vector<unsigned int>* pFaceIndexMap)\n  {\n    if (this->isPruned () == false)\n    {\n      std::vector<unsigned int> defaultVertexIndexMap;\n      std::vector<unsigned int> defaultFaceIndexMap;\n\n      if (pVertexIndexMap == nullptr)\n      {\n        pVertexIndexMap = &defaultVertexIndexMap;\n      }\n      if (pFaceIndexMap == nullptr)\n      {\n        pFaceIndexMap = &defaultFaceIndexMap;\n      }\n\n      Util::prune<VertexData> (this->vertexData, [](const VertexData& d) { return d.isFree; },\n                               pVertexIndexMap);\n      Util::prune<FaceData> (this->faceData, [](const FaceData& d) { return d.isFree; },\n                             pFaceIndexMap);\n\n      const unsigned int newNumVertices = this->vertexData.size ();\n      const unsigned int newNumFaces = this->faceData.size ();\n\n      for (VertexData& d : this->vertexData)\n      {\n        for (unsigned int& f : d.adjacentFaces)\n        {\n          assert (pFaceIndexMap->at (f) != Util::invalidIndex ());\n\n          f = pFaceIndexMap->at (f);\n        }\n      }\n\n      for (unsigned int i = 0; i < pVertexIndexMap->size (); i++)\n      {\n        const unsigned int newV = pVertexIndexMap->at (i);\n        if (newV != Util::invalidIndex ())\n        {\n          this->mesh.vertex (newV, this->mesh.vertex (i));\n          this->mesh.normal (newV, this->mesh.normal (i));\n        }\n        else\n        {\n          // Expensive (!) in debug builds\n          assert (std::find (this->freeVertexIndices.begin (), this->freeVertexIndices.end (), i) !=\n                  this->freeVertexIndices.end ());\n        }\n      }\n      this->freeVertexIndices.clear ();\n      this->mesh.shrinkVertices (newNumVertices);\n      this->vertexVisited.resize (newNumVertices);\n      assert (this->numVertices () == newNumVertices);\n\n      for (unsigned int i = 0; i < pFaceIndexMap->size (); i++)\n      {\n        const unsigned int newF = pFaceIndexMap->at (i);\n        if (newF != Util::invalidIndex ())\n        {\n          const unsigned int oldI1 = this->mesh.index ((3 * i) + 0);\n          const unsigned int oldI2 = this->mesh.index ((3 * i) + 1);\n          const unsigned int oldI3 = this->mesh.index ((3 * i) + 2);\n\n          assert (pVertexIndexMap->at (oldI1) != Util::invalidIndex ());\n          assert (pVertexIndexMap->at (oldI2) != Util::invalidIndex ());\n          assert (pVertexIndexMap->at (oldI3) != Util::invalidIndex ());\n\n          this->mesh.index ((3 * newF) + 0, pVertexIndexMap->at (oldI1));\n          this->mesh.index ((3 * newF) + 1, pVertexIndexMap->at (oldI2));\n          this->mesh.index ((3 * newF) + 2, pVertexIndexMap->at (oldI3));\n        }\n        else\n        {\n          // Expensive (!) in debug builds\n          assert (std::find (this->freeFaceIndices.begin (), this->freeFaceIndices.end (), i) !=\n                  this->freeFaceIndices.end ());\n        }\n      }\n      this->freeFaceIndices.clear ();\n      this->mesh.shrinkIndices (3 * newNumFaces);\n      this->faceVisited.resize (newNumFaces);\n      assert (this->numFaces () == newNumFaces);\n\n      this->octree.updateIndices (*pFaceIndexMap);\n    }\n  }\n\n  bool pruneAndCheckConsistency (std::vector<unsigned int>* pVertexIndexMap,\n                                 std::vector<unsigned int>* pFaceIndexMap)\n  {\n    this->prune (pVertexIndexMap, pFaceIndexMap);\n    this->bufferData ();\n\n    if (MeshUtil::checkConsistency (this->mesh))\n    {\n      for (unsigned int i = 0; i < this->vertexData.size (); i++)\n      {\n        if (this->vertexData[i].isFree == false)\n        {\n          if (this->vertexData[i].adjacentFaces.empty ())\n          {\n            DILAY_WARN (\"vertex %u is not free but has no adjacent faces\", i);\n            return false;\n          }\n        }\n      }\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  bool mirrorPositive (const PrimPlane& plane)\n  {\n    assert (this->pruneAndCheckConsistency (nullptr, nullptr));\n\n    const auto inBorder = [this, &plane](unsigned int f) {\n      unsigned int i1, i2, i3;\n      this->vertexIndices (f, i1, i2, i3);\n\n      const float d1 = glm::abs (plane.distance (this->mesh.vertex (i1)));\n      const float d2 = glm::abs (plane.distance (this->mesh.vertex (i2)));\n      const float d3 = glm::abs (plane.distance (this->mesh.vertex (i3)));\n\n      return d1 <= Util::epsilon () && d2 <= Util::epsilon () && d3 <= Util::epsilon ();\n    };\n\n    DynamicFaces faces;\n    do\n    {\n      faces.reset ();\n      if (this->intersects (plane, faces) == false)\n      {\n        break;\n      }\n      faces.filter (inBorder);\n      if (faces.isEmpty ())\n      {\n        break;\n      }\n    } while (ToolSculptAction::deleteFaces (*this->self, faces));\n    assert (this->pruneAndCheckConsistency (nullptr, nullptr));\n\n    this->prune (nullptr, nullptr);\n\n    Mesh mirrored = MeshUtil::mirrorPositive (this->mesh, plane);\n    if (mirrored.numVertices () == 0)\n    {\n      this->setAllNormals ();\n      return false;\n    }\n    else\n    {\n      this->fromMesh (mirrored);\n      assert (this->pruneAndCheckConsistency (nullptr, nullptr));\n      return true;\n    }\n  }\n\n  void mirror (const PrimPlane& plane)\n  {\n    MeshUtil::mirror (this->mesh, plane);\n    this->realignAllFaces ();\n    this->bufferData ();\n  }\n\n  void moveToCenter ()\n  {\n    MeshUtil::moveToCenter (this->mesh);\n    this->realignAllFaces ();\n    this->bufferData ();\n  }\n\n  void normalizeScaling ()\n  {\n    MeshUtil::normalizeScaling (this->mesh);\n    this->realignAllFaces ();\n    this->bufferData ();\n  }\n\n  void bufferData ()\n  {\n    const auto findNonFreeFaceIndex = [this]() -> unsigned int {\n      assert (this->numFaces () > 0);\n\n      for (unsigned int i = 0; i < this->faceData.size (); i++)\n      {\n        if (this->isFreeFace (i) == false)\n        {\n          return i;\n        }\n      }\n      DILAY_IMPOSSIBLE\n    };\n\n    if (this->numFaces () > 0 && this->freeFaceIndices.empty () == false)\n    {\n      const unsigned int nonFree = findNonFreeFaceIndex ();\n\n      for (unsigned int i : this->freeFaceIndices)\n      {\n        this->mesh.index ((3 * i) + 0, this->mesh.index ((3 * nonFree) + 0));\n        this->mesh.index ((3 * i) + 1, this->mesh.index ((3 * nonFree) + 1));\n        this->mesh.index ((3 * i) + 2, this->mesh.index ((3 * nonFree) + 2));\n      }\n    }\n    this->mesh.bufferData ();\n  }\n\n  void render (Camera& camera) const\n  {\n    this->mesh.render (camera);\n#ifdef DILAY_RENDER_OCTREE\n    this->octree.render (camera);\n#endif\n  }\n\n  bool intersects (const PrimRay& ray, Intersection& intersection, bool bothSides) const\n  {\n    this->octree.intersects (ray, [this, &ray, &intersection, bothSides](unsigned int i) -> float {\n      const PrimTriangle tri = this->face (i);\n      float              t;\n\n      if (IntersectionUtil::intersects (ray, tri, bothSides, &t))\n      {\n        intersection.update (t, ray.pointAt (t), tri.normal ());\n        return t;\n      }\n      else\n      {\n        return Util::maxFloat ();\n      }\n    });\n    return intersection.isIntersection ();\n  }\n\n  bool intersects (const PrimRay& ray, DynamicMeshIntersection& intersection)\n  {\n    this->octree.intersects (ray, [this, &ray, &intersection](unsigned int i) -> float {\n      const PrimTriangle tri = this->face (i);\n      float              t;\n\n      if (IntersectionUtil::intersects (ray, tri, false, &t))\n      {\n        intersection.update (t, ray.pointAt (t), tri.normal (), i, *this->self);\n        return intersection.distance ();\n      }\n      else\n      {\n        return Util::maxFloat ();\n      }\n    });\n    return intersection.isIntersection ();\n  }\n\n  template <typename T, typename... Ts>\n  bool intersectsT (const T& t, DynamicFaces& faces, const Ts&... args) const\n  {\n    this->octree.intersects (t, [this, &t, &faces, &args...](unsigned int i) {\n      if (IntersectionUtil::intersects (t, this->face (i), args...))\n      {\n        faces.insert (i);\n      }\n    });\n    faces.commit ();\n    return faces.isEmpty () == false;\n  }\n\n  template <typename T, typename... Ts>\n  bool containsOrIntersectsT (const T& t, DynamicFaces& faces, const Ts&... args) const\n  {\n    this->octree.intersects (t, [this, &t, &faces, &args...](bool contains, unsigned int i) {\n      if (contains || IntersectionUtil::intersects (t, this->face (i), args...))\n      {\n        faces.insert (i);\n        faces.commit ();\n      }\n    });\n    return faces.isEmpty () == false;\n  }\n\n  bool intersects (const PrimPlane& plane, DynamicFaces& faces) const\n  {\n    return this->intersectsT<PrimPlane> (plane, faces);\n  }\n\n  bool intersects (const PrimSphere& sphere, DynamicFaces& faces) const\n  {\n    return this->containsOrIntersectsT<PrimSphere> (sphere, faces);\n  }\n\n  bool intersects (const PrimAABox& box, DynamicFaces& faces) const\n  {\n    return this->containsOrIntersectsT<PrimAABox> (box, faces);\n  }\n\n  float unsignedDistance (const glm::vec3& pos) const\n  {\n    return this->octree.distance (\n      pos, [this, &pos](unsigned int i) { return Distance::distance (this->face (i), pos); });\n  }\n\n  void normalize ()\n  {\n    this->mesh.normalize ();\n    this->octree.reset ();\n\n    this->forEachFace ([this](unsigned int i) { this->addFaceToOctree (i); });\n  }\n\n  void printStatistics () const { this->octree.printStatistics (); }\n\n  void runFromConfig (const Config& config)\n  {\n    this->mesh.color (config.get<Color> (\"editor/mesh/color/normal\"));\n    this->mesh.wireframeColor (config.get<Color> (\"editor/mesh/color/wireframe\"));\n  }\n};\n\nDELEGATE_BIG4_COPY_SELF (DynamicMesh)\nDELEGATE1_CONSTRUCTOR_SELF (DynamicMesh, const Mesh&)\nDELEGATE_CONST (unsigned int, DynamicMesh, numVertices)\nDELEGATE_CONST (unsigned int, DynamicMesh, numFaces)\nDELEGATE_CONST (bool, DynamicMesh, isEmpty)\nDELEGATE1_CONST (bool, DynamicMesh, isFreeVertex, unsigned int)\nDELEGATE1_CONST (bool, DynamicMesh, isFreeFace, unsigned int)\nDELEGATE1_MEMBER_CONST (const glm::vec3&, DynamicMesh, vertex, mesh, unsigned int)\nDELEGATE1_CONST (unsigned int, DynamicMesh, valence, unsigned int)\nDELEGATE4_CONST (void, DynamicMesh, vertexIndices, unsigned int, unsigned int&, unsigned int&,\n                 unsigned int&)\nDELEGATE1_CONST (PrimTriangle, DynamicMesh, face, unsigned int)\nDELEGATE1_CONST (const glm::vec3&, DynamicMesh, vertexNormal, unsigned int)\nDELEGATE1_CONST (glm::vec3, DynamicMesh, faceNormal, unsigned int)\nDELEGATE1_CONST (const std::vector<unsigned int>&, DynamicMesh, adjacentFaces, unsigned int)\nGETTER_CONST (const Mesh&, DynamicMesh, mesh)\nDELEGATE1_CONST (void, DynamicMesh, forEachVertex, const std::function<void(unsigned int)>&)\nDELEGATE2 (void, DynamicMesh, forEachVertex, const DynamicFaces&,\n           const std::function<void(unsigned int)>&)\nDELEGATE2 (void, DynamicMesh, forEachVertexExt, const DynamicFaces&,\n           const std::function<void(unsigned int)>&)\nDELEGATE2_CONST (void, DynamicMesh, forEachVertexAdjacentToVertex, unsigned int,\n                 const std::function<void(unsigned int)>&)\nDELEGATE2_CONST (void, DynamicMesh, forEachVertexAdjacentToFace, unsigned int,\n                 const std::function<void(unsigned int)>&)\nDELEGATE1_CONST (void, DynamicMesh, forEachFace, const std::function<void(unsigned int)>&)\nDELEGATE2 (void, DynamicMesh, forEachFaceExt, const DynamicFaces&,\n           const std::function<void(unsigned int)>&)\nDELEGATE3_CONST (void, DynamicMesh, average, const DynamicFaces&, glm::vec3&, glm::vec3&)\nDELEGATE1_CONST (glm::vec3, DynamicMesh, averagePosition, const DynamicFaces&)\nDELEGATE1_CONST (glm::vec3, DynamicMesh, averagePosition, unsigned int)\nDELEGATE1_CONST (glm::vec3, DynamicMesh, averageNormal, const DynamicFaces&)\nDELEGATE1_CONST (glm::vec3, DynamicMesh, averageNormal, unsigned int)\nDELEGATE1_CONST (float, DynamicMesh, averageEdgeLengthSqr, const DynamicFaces&)\nDELEGATE1_CONST (float, DynamicMesh, averageEdgeLengthSqr, unsigned int)\nDELEGATE2 (unsigned int, DynamicMesh, addVertex, const glm::vec3&, const glm::vec3&)\nDELEGATE3 (unsigned int, DynamicMesh, addFace, unsigned int, unsigned int, unsigned int)\nDELEGATE1 (void, DynamicMesh, deleteVertex, unsigned int)\nDELEGATE1 (void, DynamicMesh, deleteFace, unsigned int)\nDELEGATE2_MEMBER (void, DynamicMesh, vertex, mesh, unsigned int, const glm::vec3&)\nDELEGATE2 (void, DynamicMesh, vertexNormal, unsigned int, const glm::vec3&)\nDELEGATE1 (void, DynamicMesh, setVertexNormal, unsigned int)\nDELEGATE (void, DynamicMesh, setAllNormals)\nDELEGATE (void, DynamicMesh, reset)\nDELEGATE1 (void, DynamicMesh, fromMesh, const Mesh&)\nDELEGATE1 (void, DynamicMesh, realignFace, unsigned int)\nDELEGATE1 (void, DynamicMesh, realignFaces, const DynamicFaces&)\nDELEGATE (void, DynamicMesh, realignAllFaces)\nDELEGATE (void, DynamicMesh, sanitize)\nDELEGATE2 (void, DynamicMesh, prune, std::vector<unsigned int>*, std::vector<unsigned int>*)\nDELEGATE2 (bool, DynamicMesh, pruneAndCheckConsistency, std::vector<unsigned int>*,\n           std::vector<unsigned int>*)\nDELEGATE1 (bool, DynamicMesh, mirrorPositive, const PrimPlane&)\nDELEGATE1 (void, DynamicMesh, mirror, const PrimPlane&)\nDELEGATE (void, DynamicMesh, moveToCenter)\nDELEGATE (void, DynamicMesh, normalizeScaling)\nDELEGATE (void, DynamicMesh, bufferData)\nDELEGATE1_CONST (void, DynamicMesh, render, Camera&)\nDELEGATE_MEMBER_CONST (const RenderMode&, DynamicMesh, renderMode, mesh)\nDELEGATE_MEMBER (RenderMode&, DynamicMesh, renderMode, mesh)\n\nDELEGATE3_CONST (bool, DynamicMesh, intersects, const PrimRay&, Intersection&, bool)\nDELEGATE2 (bool, DynamicMesh, intersects, const PrimRay&, DynamicMeshIntersection&)\nDELEGATE2_CONST (bool, DynamicMesh, intersects, const PrimPlane&, DynamicFaces&)\nDELEGATE2_CONST (bool, DynamicMesh, intersects, const PrimSphere&, DynamicFaces&)\nDELEGATE2_CONST (bool, DynamicMesh, intersects, const PrimAABox&, DynamicFaces&)\nDELEGATE1_CONST (float, DynamicMesh, unsignedDistance, const glm::vec3&)\n\nDELEGATE (void, DynamicMesh, normalize)\nDELEGATE1_MEMBER (void, DynamicMesh, scale, mesh, const glm::vec3&)\nDELEGATE1_MEMBER (void, DynamicMesh, scaling, mesh, const glm::vec3&)\nDELEGATE_MEMBER_CONST (glm::vec3, DynamicMesh, scaling, mesh)\nDELEGATE1_MEMBER (void, DynamicMesh, translate, mesh, const glm::vec3&)\nDELEGATE1_MEMBER (void, DynamicMesh, position, mesh, const glm::vec3&)\nDELEGATE_MEMBER_CONST (glm::vec3, DynamicMesh, position, mesh)\nDELEGATE1_MEMBER (void, DynamicMesh, rotationMatrix, mesh, const glm::mat4x4&)\nDELEGATE_MEMBER_CONST (const glm::mat4x4&, DynamicMesh, rotationMatrix, mesh)\nDELEGATE2_MEMBER (void, DynamicMesh, rotation, mesh, const glm::vec3&, float)\nDELEGATE1_MEMBER (void, DynamicMesh, rotationX, mesh, float)\nDELEGATE1_MEMBER (void, DynamicMesh, rotationY, mesh, float)\nDELEGATE1_MEMBER (void, DynamicMesh, rotationZ, mesh, float)\nDELEGATE1_MEMBER (void, DynamicMesh, rotate, mesh, const glm::mat4x4&)\nDELEGATE2_MEMBER (void, DynamicMesh, rotate, mesh, const glm::vec3&, float)\nDELEGATE1_MEMBER (void, DynamicMesh, rotateX, mesh, float)\nDELEGATE1_MEMBER (void, DynamicMesh, rotateY, mesh, float)\nDELEGATE1_MEMBER (void, DynamicMesh, rotateZ, mesh, float)\nDELEGATE_MEMBER_CONST (const Color&, DynamicMesh, color, mesh)\nDELEGATE1_MEMBER (void, DynamicMesh, color, mesh, const Color&)\nDELEGATE_MEMBER_CONST (const Color&, DynamicMesh, wireframeColor, mesh)\nDELEGATE1_MEMBER (void, DynamicMesh, wireframeColor, mesh, const Color&)\n\nDELEGATE_CONST (void, DynamicMesh, printStatistics)\nDELEGATE1 (void, DynamicMesh, runFromConfig, const Config&)\n\nvoid DynamicMesh::findAdjacent (unsigned int e1, unsigned int e2, unsigned int& leftFace,\n                                unsigned int& leftVertex, unsigned int& rightFace,\n                                unsigned int& rightVertex) const\n{\n  return this->impl->findAdjacent (e1, e2, leftFace, leftVertex, rightFace, rightVertex);\n}\n"
  },
  {
    "path": "lib/src/dynamic/mesh.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_DYNAMIC_MESH\n#define DILAY_DYNAMIC_MESH\n\n#include <functional>\n#include <glm/fwd.hpp>\n#include <vector>\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n\nclass Camera;\nclass Color;\nclass DynamicFaces;\nclass DynamicMeshIntersection;\nclass Intersection;\nclass Mesh;\nclass PrimAABox;\nclass PrimPlane;\nclass PrimRay;\nclass PrimSphere;\nclass PrimTriangle;\nclass RenderMode;\n\nclass DynamicMesh : public Configurable\n{\npublic:\n  DECLARE_BIG4_EXPLICIT_COPY (DynamicMesh);\n  DynamicMesh (const Mesh&);\n\n  unsigned int     numVertices () const;\n  unsigned int     numFaces () const;\n  bool             isEmpty () const;\n  bool             isFreeVertex (unsigned int) const;\n  bool             isFreeFace (unsigned int) const;\n  const glm::vec3& vertex (unsigned int) const;\n  unsigned int     valence (unsigned int) const;\n  void             vertexIndices (unsigned int, unsigned int&, unsigned int&, unsigned int&) const;\n  PrimTriangle     face (unsigned int) const;\n  const glm::vec3& vertexNormal (unsigned int) const;\n  glm::vec3        faceNormal (unsigned int) const;\n  void findAdjacent (unsigned int, unsigned int, unsigned int&, unsigned int&, unsigned int&,\n                     unsigned int&) const;\n\n  const std::vector<unsigned int>& adjacentFaces (unsigned int) const;\n\n  void forEachVertex (const std::function<void(unsigned int)>&) const;\n  void forEachVertex (const DynamicFaces&, const std::function<void(unsigned int)>&);\n  void forEachVertexExt (const DynamicFaces&, const std::function<void(unsigned int)>&);\n  void forEachVertexAdjacentToVertex (unsigned int, const std::function<void(unsigned int)>&) const;\n  void forEachVertexAdjacentToFace (unsigned int, const std::function<void(unsigned int)>&) const;\n  void forEachFace (const std::function<void(unsigned int)>&) const;\n  void forEachFaceExt (const DynamicFaces&, const std::function<void(unsigned int)>&);\n\n  void      average (const DynamicFaces&, glm::vec3&, glm::vec3&) const;\n  glm::vec3 averagePosition (const DynamicFaces&) const;\n  glm::vec3 averagePosition (unsigned int) const;\n  glm::vec3 averageNormal (const DynamicFaces&) const;\n  glm::vec3 averageNormal (unsigned int) const;\n  float     averageEdgeLengthSqr (const DynamicFaces&) const;\n  float     averageEdgeLengthSqr (unsigned int) const;\n\n  const Mesh&  mesh () const;\n  unsigned int addVertex (const glm::vec3&, const glm::vec3&);\n  unsigned int addFace (unsigned int, unsigned int, unsigned int);\n  void         deleteVertex (unsigned int);\n  void         deleteFace (unsigned int);\n\n  void vertex (unsigned int, const glm::vec3&);\n  void vertexNormal (unsigned int, const glm::vec3&);\n  void setVertexNormal (unsigned int);\n  void setAllNormals ();\n\n  void reset ();\n  void fromMesh (const Mesh&);\n  void realignFace (unsigned int);\n  void realignFaces (const DynamicFaces&);\n  void realignAllFaces ();\n  void sanitize ();\n  void prune (std::vector<unsigned int>* = nullptr, std::vector<unsigned int>* = nullptr);\n  bool pruneAndCheckConsistency (std::vector<unsigned int>* = nullptr,\n                                 std::vector<unsigned int>* = nullptr);\n  bool mirrorPositive (const PrimPlane&);\n  void mirror (const PrimPlane&);\n  void moveToCenter ();\n  void normalizeScaling ();\n  void bufferData ();\n\n  void render (Camera&) const;\n\n  const RenderMode& renderMode () const;\n  RenderMode&       renderMode ();\n\n  bool  intersects (const PrimRay&, Intersection&, bool = false) const;\n  bool  intersects (const PrimRay&, DynamicMeshIntersection&);\n  bool  intersects (const PrimPlane&, DynamicFaces&) const;\n  bool  intersects (const PrimSphere&, DynamicFaces&) const;\n  bool  intersects (const PrimAABox&, DynamicFaces&) const;\n  float unsignedDistance (const glm::vec3&) const;\n\n  void               normalize ();\n  void               scale (const glm::vec3&);\n  void               scaling (const glm::vec3&);\n  glm::vec3          scaling () const;\n  void               translate (const glm::vec3&);\n  void               position (const glm::vec3&);\n  glm::vec3          position () const;\n  void               rotationMatrix (const glm::mat4x4&);\n  const glm::mat4x4& rotationMatrix () const;\n  void               rotation (const glm::vec3&, float);\n  void               rotationX (float);\n  void               rotationY (float);\n  void               rotationZ (float);\n  void               rotate (const glm::mat4x4&);\n  void               rotate (const glm::vec3&, float);\n  void               rotateX (float);\n  void               rotateY (float);\n  void               rotateZ (float);\n  const Color&       color () const;\n  void               color (const Color&);\n  const Color&       wireframeColor () const;\n  void               wireframeColor (const Color&);\n\n  void printStatistics () const;\n\nprivate:\n  IMPLEMENTATION\n\n  void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/dynamic/octree.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <array>\n#include <functional>\n#include <glm/glm.hpp>\n#include <iostream>\n#include <unordered_map>\n#include <unordered_set>\n#include \"dynamic/octree.hpp\"\n#include \"intersection.hpp\"\n#include \"maybe.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"util.hpp\"\n\n#ifdef DILAY_RENDER_OCTREE\n#include \"../mesh.hpp\"\n#include \"color.hpp\"\n#include \"render-mode.hpp\"\n#endif\n\nnamespace\n{\n  struct IndexOctreeNode;\n  typedef Maybe<IndexOctreeNode> Child;\n\n  struct IndexOctreeStatistics\n  {\n    typedef std::unordered_map<int, unsigned int> DepthMap;\n\n    unsigned int numNodes;\n    unsigned int numElements;\n    int          minDepth;\n    int          maxDepth;\n    unsigned int maxElementsPerNode;\n    DepthMap     numElementsPerDepth;\n    DepthMap     numNodesPerDepth;\n  };\n\n  struct IndexOctreeNode\n  {\n    const glm::vec3                  center;\n    const float                      width;\n    const int                        depth;\n    const PrimAABox                  looseAABox;\n    std::array<Child, 8>             children;\n    std::unordered_set<unsigned int> indices;\n\n    static constexpr float relativeMinElementExtent = 0.25f;\n\n    IndexOctreeNode (const glm::vec3& c, float w, int d)\n      : center (c)\n      , width (w)\n      , depth (d)\n      , looseAABox (c, 2.0f * w, 2.0f * w, 2.0f * w)\n    {\n      static_assert (IndexOctreeNode::relativeMinElementExtent < 0.5f,\n                     \"relativeMinElementExtent must be smaller than 0.5f\");\n      assert (w > 0.0f);\n    }\n\n    bool approxContains (const glm::vec3& position, float maxDimExtent) const\n    {\n      const glm::vec3 min = this->center - glm::vec3 (Util::epsilon () + (this->width * 0.5f));\n      const glm::vec3 max = this->center + glm::vec3 (Util::epsilon () + (this->width * 0.5f));\n      return glm::all (glm::lessThanEqual (min, position)) &&\n             glm::all (glm::lessThanEqual (position, max)) && maxDimExtent <= this->width;\n    }\n\n    /* node indices:\n     *   (-,-,-) -> 0\n     *   (-,-,+) -> 1\n     *   (-,+,-) -> 2\n     *   (-,+,+) -> 3\n     *   (+,-,-) -> 4\n     *   (+,-,+) -> 5\n     *   (+,+,-) -> 6\n     *   (+,+,+) -> 7\n     */\n    unsigned int childIndex (const glm::vec3& position) const\n    {\n      unsigned int index = 0;\n      if (this->center.x < position.x)\n      {\n        index += 4;\n      }\n      if (this->center.y < position.y)\n      {\n        index += 2;\n      }\n      if (this->center.z < position.z)\n      {\n        index += 1;\n      }\n      return index;\n    }\n\n    bool hasChildren () const\n    {\n      return bool(this->children[0]) || bool(this->children[1]) || bool(this->children[2]) ||\n             bool(this->children[3]) || bool(this->children[4]) || bool(this->children[5]) ||\n             bool(this->children[6]) || bool(this->children[7]);\n    }\n\n    bool insertIntoChild (float maxDimExtent) const\n    {\n      return maxDimExtent <= this->width * IndexOctreeNode::relativeMinElementExtent;\n    }\n\n    IndexOctreeNode& insertIntoChild (unsigned int index, const glm::vec3& position,\n                                      float maxDimExtent)\n    {\n      const unsigned int childIndex = this->childIndex (position);\n\n      if (this->children[childIndex] == false)\n      {\n        const float q = this->width * 0.25f;\n        const float width = this->width * 0.5f;\n        const int   depth = this->depth + 1;\n\n        switch (childIndex)\n        {\n          case 0:\n            this->children[0] = Child::make (this->center + glm::vec3 (-q, -q, -q), width, depth);\n            break;\n          case 1:\n            this->children[1] = Child::make (this->center + glm::vec3 (-q, -q, +q), width, depth);\n            break;\n          case 2:\n            this->children[2] = Child::make (this->center + glm::vec3 (-q, +q, -q), width, depth);\n            break;\n          case 3:\n            this->children[3] = Child::make (this->center + glm::vec3 (-q, +q, +q), width, depth);\n            break;\n          case 4:\n            this->children[4] = Child::make (this->center + glm::vec3 (+q, -q, -q), width, depth);\n            break;\n          case 5:\n            this->children[5] = Child::make (this->center + glm::vec3 (+q, -q, +q), width, depth);\n            break;\n          case 6:\n            this->children[6] = Child::make (this->center + glm::vec3 (+q, +q, -q), width, depth);\n            break;\n          case 7:\n            this->children[7] = Child::make (this->center + glm::vec3 (+q, +q, +q), width, depth);\n            break;\n        }\n      }\n      return this->children[childIndex]->addElement (index, position, maxDimExtent);\n    }\n\n    IndexOctreeNode& addElement (unsigned int index, const glm::vec3& position, float maxDimExtent)\n    {\n      assert (this->approxContains (position, maxDimExtent));\n\n      if (this->insertIntoChild (maxDimExtent))\n      {\n        return this->insertIntoChild (index, position, maxDimExtent);\n      }\n      else\n      {\n        this->indices.insert (index);\n        return *this;\n      }\n    }\n\n    bool isEmpty () const { return this->indices.empty () && this->hasChildren () == false; }\n\n    void deleteElement (unsigned int index)\n    {\n      unsigned int n = this->indices.erase (index);\n      assert (n > 0);\n      unused (n);\n    }\n\n    bool deleteEmptyChildren ()\n    {\n      bool allChildrenEmpty = true;\n\n      for (unsigned int i = 0; i < 8; i++)\n      {\n        if (this->children[i])\n        {\n          if (this->children[i]->deleteEmptyChildren ())\n          {\n            this->children[i].reset ();\n          }\n          else\n          {\n            allChildrenEmpty = false;\n          }\n        }\n      }\n\n      if (allChildrenEmpty)\n      {\n        assert (this->hasChildren () == false);\n        return this->indices.empty ();\n      }\n      else\n      {\n        return false;\n      }\n    }\n\n#ifdef DILAY_RENDER_OCTREE\n    void render (Camera& camera, Mesh& nodeMesh) const\n    {\n      nodeMesh.position (this->center);\n      nodeMesh.scaling (glm::vec3 (this->width * 0.5f));\n      nodeMesh.renderLines (camera);\n\n      for (unsigned int i = 0; i < 8; i++)\n      {\n        if (this->children[i])\n        {\n          this->children[i]->render (camera, nodeMesh);\n        }\n      }\n    }\n#endif\n\n    template <typename T>\n    void containsOrIntersectsT (const T&                                           t,\n                                const DynamicOctree::ContainsIntersectionCallback& f) const\n    {\n      const bool contains = t.contains (this->looseAABox);\n\n      if (contains || IntersectionUtil::intersects (t, this->looseAABox))\n      {\n        for (unsigned int index : this->indices)\n        {\n          f (contains, index);\n        }\n        for (unsigned int i = 0; i < 8; i++)\n        {\n          if (this->children[i])\n          {\n            this->children[i]->containsOrIntersectsT<T> (t, f);\n          }\n        }\n      }\n    }\n\n    template <typename T>\n    void intersectsT (const T& t, const DynamicOctree::IntersectionCallback& f) const\n    {\n      if (IntersectionUtil::intersects (t, this->looseAABox))\n      {\n        for (unsigned int index : this->indices)\n        {\n          f (index);\n        }\n        for (unsigned int i = 0; i < 8; i++)\n        {\n          if (this->children[i])\n          {\n            this->children[i]->intersectsT<T> (t, f);\n          }\n        }\n      }\n    }\n\n    void intersects (const PrimRay& ray, float& distance,\n                     const DynamicOctree::RayIntersectionCallback& f) const\n    {\n      float t;\n      if (IntersectionUtil::intersects (ray, this->looseAABox, &t) && t < distance)\n      {\n        for (unsigned int index : this->indices)\n        {\n          distance = glm::min (f (index), distance);\n        }\n        for (unsigned int i = 0; i < 8; i++)\n        {\n          if (this->children[i])\n          {\n            this->children[i]->intersects (ray, distance, f);\n          }\n        }\n      }\n    }\n\n    void distance (PrimSphere& sphere, const DynamicOctree::DistanceCallback& getDistance) const\n    {\n      for (unsigned int i : this->indices)\n      {\n        const float distance = getDistance (i);\n        if (distance < sphere.radius ())\n        {\n          sphere.radius (distance);\n        }\n      }\n\n      const unsigned int first = this->childIndex (sphere.center ());\n      const bool         hasFirst = bool(this->children[first]);\n      if (hasFirst && IntersectionUtil::intersects (sphere, this->children[first]->looseAABox))\n      {\n        this->children[first]->distance (sphere, getDistance);\n      }\n\n      for (unsigned int i = 0; i < 8; i++)\n      {\n        const bool hasChild = i != first && bool(this->children[i]);\n        if (hasChild && IntersectionUtil::intersects (sphere, this->children[i]->looseAABox))\n        {\n          this->children[i]->distance (sphere, getDistance);\n        }\n      }\n    }\n\n    unsigned int numElements () const { return this->indices.size (); }\n\n    void updateIndices (const std::vector<unsigned int>& indexMap)\n    {\n      std::unordered_set<unsigned int> newIndices;\n\n      for (unsigned int i : this->indices)\n      {\n        assert (indexMap[i] != Util::invalidIndex ());\n\n        newIndices.insert (indexMap[i]);\n      }\n      this->indices = std::move (newIndices);\n\n      for (unsigned int i = 0; i < 8; i++)\n      {\n        if (this->children[i])\n        {\n          this->children[i]->updateIndices (indexMap);\n        }\n      }\n    }\n\n    void updateStatistics (IndexOctreeStatistics& stats) const\n    {\n      stats.numNodes += 1;\n      stats.numElements += this->numElements ();\n      stats.minDepth = glm::min (stats.minDepth, this->depth);\n      stats.maxDepth = glm::max (stats.maxDepth, this->depth);\n      stats.maxElementsPerNode = glm::max (stats.maxElementsPerNode, this->numElements ());\n\n      auto e = stats.numElementsPerDepth.find (this->depth);\n      if (e == stats.numElementsPerDepth.end ())\n      {\n        stats.numElementsPerDepth.emplace (this->depth, this->numElements ());\n      }\n      else\n      {\n        e->second = e->second + this->numElements ();\n      }\n      e = stats.numNodesPerDepth.find (this->depth);\n      if (e == stats.numNodesPerDepth.end ())\n      {\n        stats.numNodesPerDepth.emplace (this->depth, 1);\n      }\n      else\n      {\n        e->second = e->second + 1;\n      }\n      for (unsigned int i = 0; i < 8; i++)\n      {\n        if (this->children[i])\n        {\n          this->children[i]->updateStatistics (stats);\n        }\n      }\n    }\n  };\n}\n\nstruct DynamicOctree::Impl\n{\n  Child                         root;\n  std::vector<IndexOctreeNode*> elementNodeMap;\n\n  Impl () {}\n\n  Impl (const Impl& other)\n    : root (other.root)\n  {\n    this->makeElementNodeMap ();\n  }\n\n  bool hasRoot () const { return bool(this->root); }\n\n  void setupRoot (const glm::vec3& position, float width)\n  {\n    assert (this->hasRoot () == false);\n    this->root = IndexOctreeNode (position, width, 0);\n  }\n\n  void makeElementNodeMap ()\n  {\n    std::function<void(IndexOctreeNode&)> traverse = [this, &traverse](IndexOctreeNode& node) {\n      for (unsigned i : node.indices)\n      {\n        this->addToElementNodeMap (i, node);\n      }\n      for (unsigned int i = 0; i < 8; i++)\n      {\n        if (node.children[i])\n        {\n          traverse (*node.children[i]);\n        }\n      }\n    };\n    if (this->root)\n    {\n      traverse (*this->root);\n    }\n  }\n\n  void addToElementNodeMap (unsigned int index, IndexOctreeNode& node)\n  {\n    if (index >= this->elementNodeMap.size ())\n    {\n      this->elementNodeMap.resize (index + 1, nullptr);\n    }\n    assert (this->elementNodeMap[index] == nullptr);\n    this->elementNodeMap[index] = &node;\n  }\n\n  void makeParent (const glm::vec3& position)\n  {\n    assert (this->hasRoot ());\n\n    const glm::vec3 rootCenter = this->root->center;\n    const float     rootWidth = this->root->width;\n    const float     halfRootWidth = this->root->width * 0.5f;\n    glm::vec3       parentCenter;\n    int             index = 0;\n\n    if (rootCenter.x < position.x)\n      parentCenter.x = rootCenter.x + halfRootWidth;\n    else\n    {\n      parentCenter.x = rootCenter.x - halfRootWidth;\n      index += 4;\n    }\n    if (rootCenter.y < position.y)\n      parentCenter.y = rootCenter.y + halfRootWidth;\n    else\n    {\n      parentCenter.y = rootCenter.y - halfRootWidth;\n      index += 2;\n    }\n    if (rootCenter.z < position.z)\n      parentCenter.z = rootCenter.z + halfRootWidth;\n    else\n    {\n      parentCenter.z = rootCenter.z - halfRootWidth;\n      index += 1;\n    }\n\n    IndexOctreeNode* newRoot =\n      new IndexOctreeNode (parentCenter, rootWidth * 2.0f, this->root->depth - 1);\n    newRoot->children[index] = std::move (this->root);\n    this->root.reset (newRoot);\n  }\n\n  void addElement (unsigned int index, const glm::vec3& position, float maxDimExtent)\n  {\n    assert (this->hasRoot ());\n\n    if (this->root->approxContains (position, maxDimExtent))\n    {\n      IndexOctreeNode& node = this->root->addElement (index, position, maxDimExtent);\n      this->addToElementNodeMap (index, node);\n    }\n    else\n    {\n      this->makeParent (position);\n      this->addElement (index, position, maxDimExtent);\n    }\n  }\n\n  void realignElement (unsigned int index, const glm::vec3& position, float maxDimExtent)\n  {\n    assert (this->hasRoot ());\n    assert (index < this->elementNodeMap.size ());\n    assert (this->elementNodeMap[index]);\n\n    IndexOctreeNode* node = this->elementNodeMap[index];\n\n    if (node->approxContains (position, maxDimExtent) == false ||\n        node->insertIntoChild (maxDimExtent))\n    {\n      this->deleteElement (index);\n      this->addElement (index, position, maxDimExtent);\n    }\n  }\n\n  void deleteElement (unsigned int index)\n  {\n    assert (index < this->elementNodeMap.size ());\n    assert (this->elementNodeMap[index]);\n\n    this->elementNodeMap[index]->deleteElement (index);\n    this->elementNodeMap[index] = nullptr;\n\n    if (this->hasRoot ())\n    {\n      if (this->root->isEmpty ())\n      {\n        this->root.reset ();\n      }\n      else\n      {\n        this->shrinkRoot ();\n      }\n    }\n  }\n\n  void deleteEmptyChildren ()\n  {\n    if (this->hasRoot ())\n    {\n      if (this->root->deleteEmptyChildren ())\n      {\n        this->root.reset ();\n      }\n    }\n  }\n\n  void updateIndices (const std::vector<unsigned int>& newIndices)\n  {\n    for (unsigned int i = 0; i < newIndices.size (); i++)\n    {\n      const unsigned int newI = newIndices[i];\n      if (newI != Util::invalidIndex () && newI != i)\n      {\n        assert (i < this->elementNodeMap.size ());\n        assert (newI < this->elementNodeMap.size ());\n        assert (this->elementNodeMap[i]);\n        assert (this->elementNodeMap[newI] == nullptr);\n\n        this->elementNodeMap[newI] = this->elementNodeMap[i];\n        this->elementNodeMap[i] = nullptr;\n      }\n    }\n    this->elementNodeMap.resize (newIndices.size ());\n\n    if (this->hasRoot ())\n    {\n      this->root->updateIndices (newIndices);\n    }\n  }\n\n  void shrinkRoot ()\n  {\n    if (this->hasRoot () && this->root->indices.empty () && this->root->hasChildren ())\n    {\n      int singleNonEmptyChildIndex = -1;\n      for (int i = 0; i < 8; i++)\n      {\n        if (this->root->children[i] && this->root->children[i]->isEmpty () == false)\n        {\n          if (singleNonEmptyChildIndex == -1)\n          {\n            singleNonEmptyChildIndex = i;\n          }\n          else\n          {\n            return;\n          }\n        }\n      }\n      if (singleNonEmptyChildIndex != -1)\n      {\n        this->root = std::move (this->root->children[singleNonEmptyChildIndex]);\n        this->shrinkRoot ();\n      }\n    }\n  }\n\n  void reset ()\n  {\n    this->root.reset ();\n    this->elementNodeMap.clear ();\n  }\n\n#ifdef DILAY_RENDER_OCTREE\n  void render (Camera& camera) const\n  {\n    Mesh nodeMesh;\n    nodeMesh.addVertex (glm::vec3 (-1.0f, -1.0f, -1.0f));\n    nodeMesh.addVertex (glm::vec3 (-1.0f, -1.0f, 1.0f));\n    nodeMesh.addVertex (glm::vec3 (-1.0f, 1.0f, -1.0f));\n    nodeMesh.addVertex (glm::vec3 (-1.0f, 1.0f, 1.0f));\n    nodeMesh.addVertex (glm::vec3 (1.0f, -1.0f, -1.0f));\n    nodeMesh.addVertex (glm::vec3 (1.0f, -1.0f, 1.0f));\n    nodeMesh.addVertex (glm::vec3 (1.0f, 1.0f, -1.0f));\n    nodeMesh.addVertex (glm::vec3 (1.0f, 1.0f, 1.0f));\n\n    nodeMesh.addIndex (0);\n    nodeMesh.addIndex (1);\n    nodeMesh.addIndex (1);\n    nodeMesh.addIndex (3);\n    nodeMesh.addIndex (3);\n    nodeMesh.addIndex (2);\n    nodeMesh.addIndex (2);\n    nodeMesh.addIndex (0);\n\n    nodeMesh.addIndex (4);\n    nodeMesh.addIndex (5);\n    nodeMesh.addIndex (5);\n    nodeMesh.addIndex (7);\n    nodeMesh.addIndex (7);\n    nodeMesh.addIndex (6);\n    nodeMesh.addIndex (6);\n    nodeMesh.addIndex (4);\n\n    nodeMesh.addIndex (1);\n    nodeMesh.addIndex (5);\n    nodeMesh.addIndex (5);\n    nodeMesh.addIndex (7);\n    nodeMesh.addIndex (7);\n    nodeMesh.addIndex (3);\n    nodeMesh.addIndex (3);\n    nodeMesh.addIndex (1);\n\n    nodeMesh.addIndex (4);\n    nodeMesh.addIndex (6);\n    nodeMesh.addIndex (6);\n    nodeMesh.addIndex (2);\n    nodeMesh.addIndex (2);\n    nodeMesh.addIndex (0);\n    nodeMesh.addIndex (0);\n    nodeMesh.addIndex (4);\n\n    nodeMesh.renderMode ().constantShading (true);\n    nodeMesh.renderMode ().noDepthTest (true);\n    nodeMesh.color (Color (1.0f, 1.0f, 0.0f));\n    nodeMesh.bufferData ();\n\n    if (this->hasRoot ())\n    {\n      this->root->render (camera, nodeMesh);\n    }\n  }\n#else\n  void render (Camera&) const { DILAY_IMPOSSIBLE }\n#endif\n\n  void intersects (const PrimRay& ray, const DynamicOctree::RayIntersectionCallback& f) const\n  {\n    if (this->hasRoot ())\n    {\n      float distance = Util::maxFloat ();\n      return this->root->intersects (ray, distance, f);\n    }\n  }\n\n  void intersects (const PrimPlane& plane, const DynamicOctree::IntersectionCallback& f) const\n  {\n    if (this->hasRoot ())\n    {\n      return this->root->intersectsT<PrimPlane> (plane, f);\n    }\n  }\n\n  void intersects (const PrimSphere&                                  sphere,\n                   const DynamicOctree::ContainsIntersectionCallback& f) const\n  {\n    if (this->hasRoot ())\n    {\n      return this->root->containsOrIntersectsT<PrimSphere> (sphere, f);\n    }\n  }\n\n  void intersects (const PrimAABox& box, const DynamicOctree::ContainsIntersectionCallback& f) const\n  {\n    if (this->hasRoot ())\n    {\n      return this->root->containsOrIntersectsT<PrimAABox> (box, f);\n    }\n  }\n\n  float distance (const glm::vec3& p, const DistanceCallback& getDistance) const\n  {\n    assert (this->hasRoot ());\n    PrimSphere sphere (p, Util::maxFloat ());\n    this->root->distance (sphere, getDistance);\n    return sphere.radius ();\n  }\n\n  void printStatistics () const\n  {\n    IndexOctreeStatistics stats{0,\n                                0,\n                                Util::maxInt (),\n                                Util::minInt (),\n                                0,\n                                IndexOctreeStatistics::DepthMap (),\n                                IndexOctreeStatistics::DepthMap ()};\n    if (this->hasRoot ())\n    {\n      this->root->updateStatistics (stats);\n    }\n    std::cout << \"octree:\"\n              << \"\\n\\tnum nodes:\\t\\t\\t\" << stats.numNodes << \"\\n\\tnum elements:\\t\\t\\t\"\n              << stats.numElements << \"\\n\\tmax elements per node:\\t\\t\" << stats.maxElementsPerNode\n              << \"\\n\\tmin depth:\\t\\t\\t\" << stats.minDepth << \"\\n\\tmax depth:\\t\\t\\t\"\n              << stats.maxDepth << \"\\n\\telements per node:\\t\\t\"\n              << float(stats.numElements) / float(stats.numNodes) << std::endl;\n  }\n};\n\nDELEGATE_BIG4_COPY (DynamicOctree)\n\nDELEGATE_CONST (bool, DynamicOctree, hasRoot)\nDELEGATE2 (void, DynamicOctree, setupRoot, const glm::vec3&, float)\nDELEGATE3 (void, DynamicOctree, addElement, unsigned int, const glm::vec3&, float)\nDELEGATE3 (void, DynamicOctree, realignElement, unsigned int, const glm::vec3&, float)\nDELEGATE1 (void, DynamicOctree, deleteElement, unsigned int)\nDELEGATE (void, DynamicOctree, deleteEmptyChildren)\nDELEGATE1 (void, DynamicOctree, updateIndices, const std::vector<unsigned int>&)\nDELEGATE (void, DynamicOctree, shrinkRoot)\nDELEGATE (void, DynamicOctree, reset)\nDELEGATE1_CONST (void, DynamicOctree, render, Camera&)\nDELEGATE2_CONST (void, DynamicOctree, intersects, const PrimRay&,\n                 const DynamicOctree::RayIntersectionCallback&)\nDELEGATE2_CONST (void, DynamicOctree, intersects, const PrimPlane&,\n                 const DynamicOctree::IntersectionCallback&)\nDELEGATE2_CONST (void, DynamicOctree, intersects, const PrimSphere&,\n                 const DynamicOctree::ContainsIntersectionCallback&)\nDELEGATE2_CONST (void, DynamicOctree, intersects, const PrimAABox&,\n                 const DynamicOctree::ContainsIntersectionCallback&)\nDELEGATE2_CONST (float, DynamicOctree, distance, const glm::vec3&,\n                 const DynamicOctree::DistanceCallback&)\nDELEGATE_CONST (void, DynamicOctree, printStatistics)\n"
  },
  {
    "path": "lib/src/dynamic/octree.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_DYNAMIC_OCTREE\n#define DILAY_DYNAMIC_OCTREE\n\n#include <functional>\n#include <glm/fwd.hpp>\n#include <vector>\n#include \"macro.hpp\"\n\nclass Camera;\nclass PrimAABox;\nclass PrimPlane;\nclass PrimRay;\nclass PrimSphere;\n\nclass DynamicOctree\n{\npublic:\n  DECLARE_BIG4_EXPLICIT_COPY (DynamicOctree)\n\n  typedef std::function<void(unsigned int)>       IntersectionCallback;\n  typedef std::function<float(unsigned int)>      RayIntersectionCallback;\n  typedef std::function<void(bool, unsigned int)> ContainsIntersectionCallback;\n  typedef std::function<float(unsigned int)>      DistanceCallback;\n\n  bool  hasRoot () const;\n  void  setupRoot (const glm::vec3&, float);\n  void  addElement (unsigned int, const glm::vec3&, float);\n  void  realignElement (unsigned int, const glm::vec3&, float);\n  void  deleteElement (unsigned int);\n  void  deleteEmptyChildren ();\n  void  updateIndices (const std::vector<unsigned int>&);\n  void  shrinkRoot ();\n  void  reset ();\n  void  render (Camera&) const;\n  void  intersects (const PrimRay&, const RayIntersectionCallback&) const;\n  void  intersects (const PrimPlane&, const IntersectionCallback&) const;\n  void  intersects (const PrimSphere&, const ContainsIntersectionCallback&) const;\n  void  intersects (const PrimAABox&, const ContainsIntersectionCallback&) const;\n  float distance (const glm::vec3&, const DistanceCallback&) const;\n  void  printStatistics () const;\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/hash.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_HASH\n#define DILAY_HASH\n\n#include <functional>\n#include <utility>\n\nnamespace Hash\n{\n  // cf. `http://www.boost.org/doc/libs/1_55_0/boost/functional/hash/hash.hpp`\n  template <typename T> void combine (std::size_t& seed, const T& value)\n  {\n    seed ^= std::hash<T> () (value) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n  }\n}\n\nnamespace std\n{\n  template <typename T1, typename T2> struct hash<std::pair<T1, T2>>\n  {\n    size_t operator() (const std::pair<T1, T2>& pair) const\n    {\n      size_t seed = 0;\n      Hash::combine (seed, pair.first);\n      Hash::combine (seed, pair.second);\n      return seed;\n    }\n  };\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/history.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <list>\n#include <vector>\n#include \"config.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"history.hpp\"\n#include \"maybe.hpp\"\n#include \"mesh.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/path.hpp\"\n#include \"state.hpp\"\n\nnamespace\n{\n  struct SnapshotConfig\n  {\n    bool snapshotDynamicMeshes;\n    bool snapshotSketchMeshes;\n\n    SnapshotConfig (bool d, bool s)\n      : snapshotDynamicMeshes (d)\n      , snapshotSketchMeshes (s)\n    {\n      assert (this->snapshotDynamicMeshes || this->snapshotSketchMeshes);\n    }\n  };\n\n  struct SceneSnapshot\n  {\n    const SnapshotConfig   config;\n    std::list<DynamicMesh> dynamicMeshes;\n    std::list<SketchMesh>  sketchMeshes;\n\n    SceneSnapshot (const SnapshotConfig& c)\n      : config (c)\n    {\n    }\n  };\n\n  typedef std::list<SceneSnapshot> Timeline;\n\n  SceneSnapshot sceneSnapshot (const Scene& scene, const SnapshotConfig& config)\n  {\n    SceneSnapshot snapshot (config);\n\n    if (config.snapshotDynamicMeshes)\n    {\n      scene.forEachConstMesh (\n        [&snapshot](const DynamicMesh& mesh) { snapshot.dynamicMeshes.emplace_back (mesh); });\n    }\n    if (config.snapshotSketchMeshes)\n    {\n      scene.forEachConstMesh (\n        [&snapshot](const SketchMesh& mesh) { snapshot.sketchMeshes.emplace_back (mesh); });\n    }\n    return snapshot;\n  }\n\n  void resetToSnapshot (const SceneSnapshot& snapshot, State& state)\n  {\n    Scene& scene = state.scene ();\n\n    if (snapshot.config.snapshotDynamicMeshes)\n    {\n      scene.deleteDynamicMeshes ();\n\n      for (const DynamicMesh& mesh : snapshot.dynamicMeshes)\n      {\n        scene.newDynamicMesh (state.config (), mesh);\n      }\n    }\n    if (snapshot.config.snapshotSketchMeshes)\n    {\n      scene.deleteSketchMeshes ();\n\n      for (const SketchMesh& mesh : snapshot.sketchMeshes)\n      {\n        scene.newSketchMesh (state.config (), mesh);\n      }\n    }\n  }\n}\n\nstruct History::Impl\n{\n  unsigned int undoDepth;\n  Timeline     past;\n  Timeline     future;\n\n  Impl (const Config& config) { this->runFromConfig (config); }\n\n  void snapshotAll (const Scene& scene) { this->snapshot (scene, SnapshotConfig (true, true)); }\n\n  void snapshotDynamicMeshes (const Scene& scene)\n  {\n    this->snapshot (scene, SnapshotConfig (true, false));\n  }\n\n  void snapshotSketchMeshes (const Scene& scene)\n  {\n    this->snapshot (scene, SnapshotConfig (false, true));\n  }\n\n  void snapshot (const Scene& scene, const SnapshotConfig& config)\n  {\n    assert (undoDepth > 0);\n\n    this->future.clear ();\n\n    while (this->past.size () >= this->undoDepth)\n    {\n      this->past.pop_back ();\n    }\n    this->past.push_front (sceneSnapshot (scene, config));\n  }\n\n  void dropPastSnapshot ()\n  {\n    if (this->past.empty () == false)\n    {\n      this->past.pop_front ();\n    }\n  }\n\n  void dropFutureSnapshot ()\n  {\n    if (this->future.empty () == false)\n    {\n      this->future.pop_front ();\n    }\n  }\n\n  void undo (State& state)\n  {\n    if (this->past.empty () == false)\n    {\n      const SnapshotConfig& config = this->past.front ().config;\n\n      this->future.push_front (sceneSnapshot (state.scene (), config));\n      resetToSnapshot (this->past.front (), state);\n      this->past.pop_front ();\n    }\n  }\n\n  void redo (State& state)\n  {\n    if (this->future.empty () == false)\n    {\n      const SnapshotConfig& config = this->future.front ().config;\n\n      this->past.push_front (sceneSnapshot (state.scene (), config));\n      resetToSnapshot (this->future.front (), state);\n      this->future.pop_front ();\n    }\n  }\n\n  bool hasRecentDynamicMesh () const\n  {\n    return this->past.empty () == false && this->past.front ().config.snapshotDynamicMeshes;\n  }\n\n  void forEachRecentDynamicMesh (const std::function<void(const DynamicMesh&)>& f) const\n  {\n    assert (this->hasRecentDynamicMesh ());\n\n    for (const DynamicMesh& m : this->past.front ().dynamicMeshes)\n    {\n      f (m);\n    }\n  }\n\n  void reset ()\n  {\n    this->past.clear ();\n    this->future.clear ();\n  }\n\n  void runFromConfig (const Config& config)\n  {\n    this->undoDepth = config.get<int> (\"editor/undo-depth\");\n  }\n};\n\nDELEGATE1_BIG3 (History, const Config&)\nDELEGATE1 (void, History, snapshotAll, const Scene&)\nDELEGATE1 (void, History, snapshotDynamicMeshes, const Scene&)\nDELEGATE1 (void, History, snapshotSketchMeshes, const Scene&)\nDELEGATE (void, History, dropPastSnapshot)\nDELEGATE (void, History, dropFutureSnapshot)\nDELEGATE1 (void, History, undo, State&)\nDELEGATE1 (void, History, redo, State&)\nDELEGATE_CONST (bool, History, hasRecentDynamicMesh)\nDELEGATE1_CONST (void, History, forEachRecentDynamicMesh,\n                 const std::function<void(const DynamicMesh&)>&)\nDELEGATE (void, History, reset)\nDELEGATE1 (void, History, runFromConfig, const Config&)\n"
  },
  {
    "path": "lib/src/history.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_HISTORY\n#define DILAY_HISTORY\n\n#include <functional>\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n\nclass DynamicMesh;\nclass Scene;\nclass State;\n\nclass History : public Configurable\n{\npublic:\n  DECLARE_BIG3 (History, const Config&)\n\n  void snapshotAll (const Scene&);\n  void snapshotDynamicMeshes (const Scene&);\n  void snapshotSketchMeshes (const Scene&);\n  void dropPastSnapshot ();\n  void dropFutureSnapshot ();\n  void undo (State&);\n  void redo (State&);\n  bool hasRecentDynamicMesh () const;\n  void forEachRecentDynamicMesh (const std::function<void(const DynamicMesh&)>&) const;\n  void reset ();\n\nprivate:\n  IMPLEMENTATION\n\n  void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/import-export.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <algorithm>\n#include <fstream>\n#include <sstream>\n#include \"dynamic/mesh.hpp\"\n#include \"import-export.hpp\"\n#include \"mesh-util.hpp\"\n#include \"mesh.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/fwd.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/path.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  std::ostream& operator<< (std::ostream& os, const glm::vec3& v)\n  {\n    os << v.x << \" \" << v.y << \" \" << v.z;\n    return os;\n  }\n\n  std::istream& operator>> (std::istream& is, glm::vec3& v)\n  {\n    is >> v.x >> v.y >> v.z;\n    return is;\n  }\n\n  void toDlyFile (std::ostream& stream, const Mesh& mesh)\n  {\n    stream << \"o\\n\";\n    for (unsigned int i = 0; i < mesh.numVertices (); i++)\n    {\n      stream << \"v \" << mesh.vertex (i) << std::endl;\n    }\n    for (unsigned int i = 0; i < mesh.numIndices (); i += 3)\n    {\n      stream << \"f \" << mesh.index (i + 0) + 1 << \" \" << mesh.index (i + 1) + 1 << \" \"\n             << mesh.index (i + 2) + 1 << std::endl;\n    }\n  }\n\n  unsigned int toDlyFile (std::ostream& stream, const SketchNode& node, unsigned int parentIndex,\n                          unsigned nodeIndex)\n  {\n    stream << \"dly_sketch_node \" << nodeIndex << \" \" << parentIndex << \" \" << node.data ().center ()\n           << \" \" << node.data ().radius () << std::endl;\n\n    unsigned int childIndex = nodeIndex;\n\n    node.forEachConstChild ([&stream, nodeIndex, &childIndex](const SketchNode& child) {\n      childIndex = toDlyFile (stream, child, nodeIndex, childIndex + 1);\n    });\n    return childIndex;\n  }\n\n  void toDlyFile (std::ostream& stream, const SketchPath& path)\n  {\n    if (path.isEmpty () == false)\n    {\n      stream << \"dly_sketch_path\"\n             << \" \" << path.intersectionFirst () << \" \" << path.intersectionLast () << std::endl;\n\n      for (const PrimSphere& s : path.spheres ())\n      {\n        stream << \"dly_sketch_sphere\"\n               << \" \" << s.center () << \" \" << s.radius () << std::endl;\n      }\n    }\n  }\n\n  void toDlyFile (std::ostream& stream, const SketchMesh& mesh)\n  {\n    if (mesh.isEmpty () == false)\n    {\n      stream << \"dly_sketch_mesh\\n\";\n\n      if (mesh.tree ().hasRoot ())\n      {\n        toDlyFile (stream, mesh.tree ().root (), Util::invalidIndex (), 0);\n      }\n\n      for (const SketchPath& p : mesh.paths ())\n      {\n        toDlyFile (stream, p);\n      }\n    }\n  }\n};\n\nnamespace ImportExport\n{\n  void toDlyFile (std::ostream& stream, Scene& scene, bool isObjFile)\n  {\n    scene.forEachMesh ([&stream](DynamicMesh& mesh) {\n      mesh.prune ();\n      ::toDlyFile (stream, mesh.mesh ());\n    });\n\n    if (isObjFile == false)\n    {\n      scene.forEachConstMesh ([&stream](const SketchMesh& mesh) { ::toDlyFile (stream, mesh); });\n    }\n  }\n\n  bool toDlyFile (const std::string& fileName, Scene& scene, bool isObjFile)\n  {\n    std::ofstream file (fileName);\n\n    if (file.is_open ())\n    {\n      ImportExport::toDlyFile (file, scene, isObjFile);\n      file.close ();\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  bool fromDlyFile (std::istream& stream, const Config& config, Scene& scene)\n  {\n    unsigned int       lineNumber = 0;\n    std::istringstream lineStream;\n\n    std::vector<Mesh>        meshes;\n    std::vector<SketchNode*> nodes;\n    SketchMesh*              sketch = nullptr;\n    SketchPath*              sketchPath = nullptr;\n    glm::vec3                intersectionFirst, intersectionLast;\n\n    auto extractFirst = [](const std::string& string, unsigned int& value) -> bool {\n      auto slashPos = string.find ('/');\n      return Util::fromString (string.substr (0, slashPos), value);\n    };\n\n    auto nextLine = [&stream, &lineNumber, &lineStream]() -> bool {\n      std::string line;\n      std::getline (stream, line);\n\n      if (stream)\n      {\n        lineNumber++;\n        lineStream.clear ();\n        lineStream.str (line);\n        return true;\n      }\n      else\n      {\n        return false;\n      }\n    };\n\n    while (nextLine ())\n    {\n      std::string keyword;\n      lineStream >> keyword;\n\n      if (lineStream.fail () == false)\n      {\n        if (keyword == \"o\")\n        {\n          meshes.push_back (Mesh ());\n        }\n        else if (keyword == \"v\")\n        {\n          glm::vec3 vertex;\n          lineStream >> vertex;\n\n          if (lineStream.fail ())\n          {\n            DILAY_WARN (\"could not parse vertex at line %u\", lineNumber)\n            return false;\n          }\n          else\n          {\n            if (meshes.empty ())\n            {\n              meshes.push_back (Mesh ());\n            }\n            meshes.back ().addVertex (vertex);\n          }\n        }\n        else if (keyword == \"f\")\n        {\n          std::string  v1String, v2String, v3String;\n          unsigned int v1, v2, v3;\n\n          lineStream >> v1String >> v2String >> v3String;\n\n          if (lineStream.fail () || extractFirst (v1String, v1) == false ||\n              extractFirst (v2String, v2) == false || extractFirst (v3String, v3) == false)\n          {\n            DILAY_WARN (\"could not parse face at line %u\", lineNumber)\n            return false;\n          }\n          else\n          {\n            std::string  v4String;\n            unsigned int v4;\n            lineStream >> v4String;\n\n            if (lineStream.fail ())\n            {\n              lineStream.clear ();\n\n              if (meshes.empty ())\n              {\n                meshes.push_back (Mesh ());\n              }\n              MeshUtil::addFace (meshes.back (), v1 - 1, v2 - 1, v3 - 1);\n            }\n            else if (extractFirst (v4String, v4) == false)\n            {\n              DILAY_WARN (\"could not parse face at line %u\", lineNumber)\n              return false;\n            }\n            else\n            {\n              if (meshes.empty ())\n              {\n                meshes.push_back (Mesh ());\n              }\n              MeshUtil::addFace (meshes.back (), v1 - 1, v2 - 1, v3 - 1, v4 - 1);\n            }\n          }\n        }\n        else if (keyword == \"dly_sketch_mesh\")\n        {\n          nodes.clear ();\n          sketch = &scene.newSketchMesh (config, SketchTree ());\n        }\n        else if (keyword == \"dly_sketch_node\")\n        {\n          if (sketch == nullptr)\n          {\n            DILAY_WARN (\"could not parse sketch node: no sketch found at line %u\", lineNumber)\n            return false;\n          }\n          unsigned int nodeIndex;\n          unsigned int parentIndex;\n          glm::vec3    center;\n          float        radius;\n\n          lineStream >> nodeIndex >> parentIndex >> center >> radius;\n\n          if (lineStream.fail ())\n          {\n            DILAY_WARN (\"could not parse sketch node at line %u\", lineNumber)\n            return false;\n          }\n\n          if (nodeIndex == nodes.size ())\n          {\n            if (nodeIndex == 0)\n            {\n              nodes.push_back (&sketch->tree ().emplaceRoot (PrimSphere (center, radius)));\n            }\n            else if (parentIndex < nodes.size ())\n            {\n              nodes.push_back (&nodes.at (parentIndex)->emplaceChild (PrimSphere (center, radius)));\n            }\n            else\n            {\n              DILAY_WARN (\"invalid parent index at line %u\", lineNumber)\n              return false;\n            }\n          }\n          else\n          {\n            DILAY_WARN (\"invalid node index at line %u\", lineNumber)\n            return false;\n          }\n        }\n        else if (keyword == \"dly_sketch_path\")\n        {\n          lineStream >> intersectionFirst >> intersectionLast;\n\n          if (lineStream.fail ())\n          {\n            DILAY_WARN (\"could not parse sketch path at line %u\", lineNumber)\n            return false;\n          }\n          if (sketch)\n          {\n            sketchPath = &sketch->addPath (SketchPath ());\n          }\n          else\n          {\n            DILAY_WARN (\"could not parse sketch path: no sketch found at line %u\", lineNumber)\n            return false;\n          }\n        }\n        else if (keyword == \"dly_sketch_sphere\")\n        {\n          glm::vec3 center;\n          float     radius;\n\n          lineStream >> center >> radius;\n\n          if (lineStream.fail ())\n          {\n            DILAY_WARN (\"could not parse sketch sphere at line %u\", lineNumber)\n            return false;\n          }\n\n          if (sketchPath)\n          {\n            if (sketchPath->isEmpty ())\n            {\n              sketchPath->addSphere (intersectionFirst, center, radius);\n            }\n            else\n            {\n              sketchPath->addSphere (intersectionLast, center, radius);\n            }\n          }\n          else\n          {\n            DILAY_WARN (\"could not parse sketch sphere: no sketch path found at line %u\",\n                        lineNumber)\n            return false;\n          }\n        }\n      }\n    }\n    meshes.erase (std::remove_if (meshes.begin (), meshes.end (),\n                                  [](Mesh& m) { return m.numVertices () == 0; }),\n                  meshes.end ());\n\n    if (std::all_of (meshes.begin (), meshes.end (),\n                     [](Mesh& m) { return MeshUtil::checkConsistency (m); }))\n    {\n      for (Mesh& m : meshes)\n      {\n        scene.newDynamicMesh (config, m);\n      }\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  bool fromDlyFile (const std::string& fileName, const Config& config, Scene& scene)\n  {\n    std::ifstream file (fileName);\n\n    if (file.is_open ())\n    {\n      const bool success = ImportExport::fromDlyFile (file, config, scene);\n      file.close ();\n      return success;\n    }\n    else\n    {\n      return false;\n    }\n  }\n};\n"
  },
  {
    "path": "lib/src/import-export.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_IMPORT_EXPORT\n#define DILAY_IMPORT_EXPORT\n\n#include <iosfwd>\n#include <string>\n\nclass Config;\nclass Scene;\n\nnamespace ImportExport\n{\n  void toDlyFile (std::ostream&, Scene&, bool);\n  bool toDlyFile (const std::string&, Scene&, bool);\n  bool fromDlyFile (std::istream&, const Config&, Scene&);\n  bool fromDlyFile (const std::string&, const Config&, Scene&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/intersection.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include <glm/gtx/norm.hpp>\n#include \"intersection.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/cone.hpp\"\n#include \"primitive/cylinder.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"util.hpp\"\n\nIntersection ::Intersection ()\n  : _isIntersection (false)\n  , _distance (Util::maxFloat ())\n{\n}\n\nbool             Intersection::isIntersection () const { return this->_isIntersection; }\nconst glm::vec3& Intersection::position () const\n{\n  assert (this->_isIntersection);\n  return this->_position;\n}\nconst glm::vec3& Intersection::normal () const\n{\n  assert (this->_isIntersection);\n  return this->_normal;\n}\nfloat Intersection::distance () const\n{\n  assert (this->_isIntersection);\n  return this->_distance;\n}\n\nvoid Intersection::reset () { this->_isIntersection = false; }\n\nbool Intersection::update (float d, const glm::vec3& p, const glm::vec3& n)\n{\n  if (this->_isIntersection == false || d < this->_distance)\n  {\n    this->_isIntersection = true;\n    this->_distance = d;\n    this->_position = p;\n    this->_normal = n;\n    return true;\n  }\n  return false;\n}\n\nIntersection& Intersection::min (Intersection& a, Intersection& b)\n{\n  if (a._isIntersection && (b._isIntersection == false || a._distance < b._distance))\n  {\n    return a;\n  }\n  else\n  {\n    return b;\n  }\n}\n\nvoid Intersection::sort (Intersection& a, Intersection& b)\n{\n  if (b._isIntersection && (a._isIntersection == false || b._distance < a._distance))\n  {\n    std::swap (a, b);\n  }\n}\n\nnamespace\n{\n  bool intersectsQuadric (float a, float b, float c, bool alongLine, float* t)\n  {\n    float              s1, s2;\n    const unsigned int n = Util::solveQuadraticEq (a, b, c, s1, s2);\n\n    switch (n)\n    {\n      case 0:\n        return false;\n\n      case 1:\n        if (s1 >= 0.0f || alongLine)\n        {\n          Util::setIfNotNull (t, s1);\n          return true;\n        }\n        else\n        {\n          return false;\n        }\n\n      case 2:\n      {\n        const float sMin = glm::min (s1, s2);\n        const float sMax = glm::max (s1, s2);\n\n        if (sMin >= 0.0f)\n        {\n          Util::setIfNotNull (t, sMin);\n          return true;\n        }\n        else if (sMax >= 0.0f || alongLine)\n        {\n          Util::setIfNotNull (t, sMax);\n          return true;\n        }\n        return false;\n      }\n      default:\n        DILAY_IMPOSSIBLE\n    }\n  }\n}\n\n// see http://realtimecollisiondetection.net/blog/?p=103\nbool IntersectionUtil::intersects (const PrimSphere& sphere, const PrimTriangle& tri)\n{\n  const glm::vec3 A = tri.vertex1 () - sphere.center ();\n  const glm::vec3 B = tri.vertex2 () - sphere.center ();\n  const glm::vec3 C = tri.vertex3 () - sphere.center ();\n\n  const float     rr = sphere.radius () * sphere.radius ();\n  const glm::vec3 V = glm::cross (B - A, C - A);\n  const float     d = glm::dot (A, V);\n  const float     e = glm::dot (V, V);\n  const bool      sep1 = d * d > rr * e;\n\n  const float aa = glm::dot (A, A);\n  const float ab = glm::dot (A, B);\n  const float ac = glm::dot (A, C);\n  const float bb = glm::dot (B, B);\n  const float bc = glm::dot (B, C);\n  const float cc = glm::dot (C, C);\n  const bool  sep2 = (aa > rr) && (ab > aa) && (ac > aa);\n  const bool  sep3 = (bb > rr) && (ab > bb) && (bc > bb);\n  const bool  sep4 = (cc > rr) && (ac > cc) && (bc > cc);\n\n  const glm::vec3 AB = B - A;\n  const glm::vec3 BC = C - B;\n  const glm::vec3 CA = A - C;\n\n  const float d1 = ab - aa;\n  const float d2 = bc - bb;\n  const float d3 = ac - cc;\n  const float e1 = glm::dot (AB, AB);\n  const float e2 = glm::dot (BC, BC);\n  const float e3 = glm::dot (CA, CA);\n\n  const glm::vec3 Q1 = (A * e1) - (d1 * AB);\n  const glm::vec3 Q2 = (B * e2) - (d2 * BC);\n  const glm::vec3 Q3 = (C * e3) - (d3 * CA);\n  const glm::vec3 QC = (C * e1) - Q1;\n  const glm::vec3 QA = (A * e2) - Q2;\n  const glm::vec3 QB = (B * e3) - Q3;\n\n  const bool sep5 = (glm::dot (Q1, Q1) > rr * e1 * e1) && (glm::dot (Q1, QC) > 0.0f);\n  const bool sep6 = (glm::dot (Q2, Q2) > rr * e2 * e2) && (glm::dot (Q2, QA) > 0.0f);\n  const bool sep7 = (glm::dot (Q3, Q3) > rr * e3 * e3) && (glm::dot (Q3, QB) > 0.0f);\n\n  return (sep1 || sep2 || sep3 || sep4 || sep5 || sep6 || sep7) == false;\n}\n\nbool IntersectionUtil::intersects (const PrimSphere& sphere, const PrimAABox& box)\n{\n  const glm::vec3  c = sphere.center ();\n  const glm::vec3& min = box.minimum ();\n  const glm::vec3& max = box.maximum ();\n  float            d = 0.0f;\n\n  for (unsigned int i = 0; i < 3; i++)\n  {\n    if (c[i] < min[i])\n    {\n      const float s = c[i] - min[i];\n      d += s * s;\n    }\n    else if (c[i] > max[i])\n    {\n      const float s = c[i] - max[i];\n      d += s * s;\n    }\n  }\n  return d <= sphere.radius () * sphere.radius ();\n}\n\nbool IntersectionUtil::intersects (const PrimSphere& sphere1, const PrimSphere& sphere2)\n{\n  return glm::distance2 (sphere1.center (), sphere2.center ()) <\n         ((sphere1.radius () + sphere2.radius ()) * (sphere1.radius () + sphere2.radius ()));\n}\n\nbool IntersectionUtil::intersects (const PrimRay& ray, const PrimSphere& sphere, float* t)\n{\n  const glm::vec3& dir = ray.direction ();\n  const glm::vec3& origin = ray.origin () - sphere.center ();\n  const float      radius2 = sphere.radius () * sphere.radius ();\n\n  return intersectsQuadric (glm::dot (dir, dir), 2.0f * glm::dot (dir, origin),\n                            glm::dot (origin, origin) - radius2, ray.isLine (), t);\n}\n\nbool IntersectionUtil::intersects (const PrimRay& ray, const PrimPlane& plane, float* t)\n{\n  const float d = glm::dot (ray.direction (), plane.normal ());\n\n  if (Util::almostEqual (d, 0.0f))\n  {\n    return false;\n  }\n  const float s = glm::dot (plane.point () - ray.origin (), plane.normal ()) / d;\n\n  if (s >= 0.0f || ray.isLine ())\n  {\n    Util::setIfNotNull (t, s);\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\n// see\n// http://www.cs.virginia.edu/~gfx/Courses/2003/ImageSynthesis/papers/Acceleration/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf\nbool IntersectionUtil::intersects (const PrimRay& ray, const PrimTriangle& tri, bool both, float* t)\n{\n  const float dot = glm::dot (ray.direction (), tri.normal ());\n\n  if (both == false && dot > -Util::epsilon ())\n  {\n    return false;\n  }\n  else if (both && dot < Util::epsilon () && dot > -Util::epsilon ())\n  {\n    return false;\n  }\n\n  const glm::vec3 e1 = tri.vertex2 () - tri.vertex1 ();\n  const glm::vec3 e2 = tri.vertex3 () - tri.vertex1 ();\n  const glm::vec3 s1 = glm::cross (ray.direction (), e2);\n  const float     invDet = 1.0f / glm::dot (s1, e1);\n  const glm::vec3 d = ray.origin () - tri.vertex1 ();\n  const glm::vec3 s2 = glm::cross (d, e1);\n  const float     b1 = glm::dot (d, s1) * invDet;\n  const float     b2 = glm::dot (ray.direction (), s2) * invDet;\n  const float     tRay = glm::dot (e2, s2) * invDet;\n\n  if (b1 < 0.0f || b2 < 0.0f || b1 + b2 > 1.0f || (tRay < 0.0f && ray.isLine () == false))\n  {\n    return false;\n  }\n  else\n  {\n    Util::setIfNotNull (t, tRay);\n    return true;\n  }\n}\n\nbool IntersectionUtil::intersects (const PrimRay& ray, const PrimAABox& box, float* t)\n{\n  const glm::vec3 invDir = glm::vec3 (1.0f) / ray.direction ();\n  const glm::vec3 lowerTs = (box.minimum () - ray.origin ()) * invDir;\n  const glm::vec3 upperTs = (box.maximum () - ray.origin ()) * invDir;\n  const glm::vec3 min = glm::min (lowerTs, upperTs);\n  const glm::vec3 max = glm::max (lowerTs, upperTs);\n\n  const float tMin = glm::max (glm::max (min.x, min.y), min.z);\n  const float tMax = glm::min (glm::min (max.x, max.y), max.z);\n\n  if ((tMax >= 0.0f || ray.isLine ()) && tMin <= tMax)\n  {\n    Util::setIfNotNull (t, tMin);\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nbool IntersectionUtil::intersects (const PrimRay& ray, const PrimCylinder& cylinder, float* tRay,\n                                   float* tCyl)\n{\n  const glm::vec3& dir = ray.direction ();\n  const glm::vec3& cylDir = cylinder.direction ();\n  const glm::vec3  offset = ray.origin () - cylinder.center1 ();\n  const glm::vec3  d = dir - (cylDir * glm::dot (cylDir, dir));\n  const glm::vec3  c = offset - (cylDir * glm::dot (cylDir, offset));\n  const float      radius2 = cylinder.radius () * cylinder.radius ();\n  float            tmpRay;\n\n  if (intersectsQuadric (glm::dot (d, d), 2.0f * glm::dot (c, d), glm::dot (c, c) - radius2,\n                         ray.isLine (), &tmpRay))\n  {\n    const glm::vec3 p = ray.pointAt (tmpRay);\n    const float     tmpCyl = glm::dot (cylDir, p - cylinder.center1 ());\n\n    if (tmpCyl >= 0.0f && tmpCyl <= cylinder.length ())\n    {\n      Util::setIfNotNull (tRay, tmpRay);\n      Util::setIfNotNull (tCyl, tmpCyl);\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n  else\n  {\n    return false;\n  }\n}\n\nbool IntersectionUtil::intersects (const PrimRay& ray, const PrimCone& cone, float* tRay,\n                                   float* tCone)\n{\n  if (cone.isCylinder ())\n  {\n    return IntersectionUtil::intersects (ray, PrimCylinder (cone), tRay, tCone);\n  }\n  else\n  {\n    const glm::vec3& dir = ray.direction ();\n    const glm::vec3& coneDir = cone.direction ();\n    const glm::vec3  offset = ray.origin () - cone.apex ();\n    const float      dotD = glm::dot (coneDir, dir);\n    const float      dotO = glm::dot (coneDir, offset);\n    const glm::vec3  d = dir - (coneDir * dotD);\n    const glm::vec3  c = offset - (coneDir * glm::dot (coneDir, offset));\n    const float      sinSqr = cone.sinAlpha () * cone.sinAlpha ();\n    const float      cosSqr = cone.cosAlpha () * cone.cosAlpha ();\n    float            tmpRay;\n\n    if (intersectsQuadric ((cosSqr * glm::dot (d, d)) - (sinSqr * dotD * dotD),\n                           (2.0f * cosSqr * glm::dot (c, d)) - (2.0f * sinSqr * dotD * dotO),\n                           (cosSqr * glm::dot (c, c)) - (sinSqr * dotO * dotO), ray.isLine (),\n                           &tmpRay))\n    {\n      const glm::vec3 p = ray.pointAt (tmpRay);\n      const float     tmpCone = glm::dot (coneDir, p - cone.center1 ());\n\n      if (tmpCone >= 0.0f && tmpCone <= cone.length ())\n      {\n        Util::setIfNotNull (tRay, tmpRay);\n        Util::setIfNotNull (tCone, tmpCone);\n        return true;\n      }\n      else\n      {\n        return false;\n      }\n    }\n    else\n    {\n      return false;\n    }\n  }\n}\n\nbool IntersectionUtil::intersects (const PrimPlane& plane, const PrimAABox& box)\n{\n  const glm::vec3& max = box.maximum ();\n  const glm::vec3& min = box.minimum ();\n  const glm::vec3  p =\n    glm::vec3 (plane.normal ().x >= 0.0f ? max.x : min.x, plane.normal ().y >= 0.0f ? max.y : min.y,\n               plane.normal ().z >= 0.0f ? max.z : min.z);\n  const glm::vec3 n =\n    glm::vec3 (plane.normal ().x >= 0.0f ? min.x : max.x, plane.normal ().y >= 0.0f ? min.y : max.y,\n               plane.normal ().z >= 0.0f ? min.z : max.z);\n\n  return plane.distance (p) * plane.distance (n) < 0.0f;\n}\n\nbool IntersectionUtil::intersects (const PrimPlane& plane, const PrimTriangle& tri)\n{\n  const float d1 = plane.distance (tri.vertex1 ());\n  const float d2 = plane.distance (tri.vertex2 ());\n  const float d3 = plane.distance (tri.vertex3 ());\n\n  const bool oneLess = d1 < Util::epsilon () || d2 < Util::epsilon () || d3 < Util::epsilon ();\n  const bool oneGreater =\n    d1 > -Util::epsilon () || d2 > -Util::epsilon () || d3 > -Util::epsilon ();\n\n  return oneLess && oneGreater;\n}\n\nbool IntersectionUtil::intersects (const PrimCylinder& cylinder, const glm::vec3& point)\n{\n  const glm::vec3 d = point - cylinder.center1 ();\n  const float     dot = glm::dot (cylinder.direction (), d);\n  const glm::vec3 t = d - (cylinder.direction () * dot);\n\n  return dot >= 0.0f && dot <= cylinder.length () &&\n         glm::dot (t, t) <= cylinder.radius () * cylinder.radius ();\n}\n\nbool IntersectionUtil::intersects (const PrimCone& cone, const glm::vec3& point)\n{\n  if (cone.isCylinder ())\n  {\n    return IntersectionUtil::intersects (PrimCylinder (cone), point);\n  }\n  else\n  {\n    const glm::vec3 d = point - cone.center1 ();\n    const float     dot = glm::dot (cone.direction (), d);\n    const glm::vec3 t = d - (cone.direction () * dot);\n    const float     r = glm::mix (cone.radius1 (), cone.radius2 (), dot / cone.length ());\n\n    return dot >= 0.0f && dot <= cone.length () && glm::dot (t, t) <= r * r;\n  }\n}\n\nbool IntersectionUtil::intersects (const PrimAABox& a, const PrimAABox& b)\n{\n  const bool overlap1 = glm::all (glm::greaterThanEqual (a.minimum (), b.maximum ()));\n  const bool overlap2 = glm::all (glm::greaterThanEqual (b.minimum (), a.maximum ()));\n  const bool contain1 = glm::all (glm::greaterThan (a.maximum (), b.maximum ())) &&\n                        glm::all (glm::lessThan (a.minimum (), b.minimum ()));\n  const bool contain2 = glm::all (glm::greaterThan (b.maximum (), a.maximum ())) &&\n                        glm::all (glm::lessThan (b.minimum (), a.minimum ()));\n\n  return overlap1 || overlap2 || contain1 || contain2;\n}\n\n// http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/code/tribox_tam.pdf\nbool IntersectionUtil::intersects (const PrimAABox& box, const PrimTriangle& tri)\n{\n  const glm::vec3 v0 = tri.vertex1 () - box.center ();\n  const glm::vec3 v1 = tri.vertex2 () - box.center ();\n  const glm::vec3 v2 = tri.vertex3 () - box.center ();\n  const glm::vec3 e0 = v1 - v0;\n  const glm::vec3 e1 = v2 - v1;\n  const glm::vec3 e2 = v0 - v2;\n  const glm::vec3 hw = box.halfWidth ();\n  const glm::vec3 x = glm::vec3 (1.0f, 0.0f, 0.0f);\n  const glm::vec3 y = glm::vec3 (0.0f, 1.0f, 0.0f);\n  const glm::vec3 z = glm::vec3 (0.0f, 0.0f, 1.0f);\n\n  auto sepAxis = [&v0, &v1, &v2, &hw](const glm::vec3& a) -> bool {\n    const float radius = glm::dot (hw, glm::abs (a));\n    const float p0 = glm::dot (a, v0);\n    const float p1 = glm::dot (a, v1);\n    const float p2 = glm::dot (a, v2);\n    const float min = glm::min (p0, glm::min (p1, p2));\n    const float max = glm::max (p0, glm::max (p1, p2));\n\n    return min > radius || max < -radius;\n  };\n\n  const bool sep1 = glm::min (v0.x, glm::min (v1.x, v2.x)) > hw.x;\n  const bool sep2 = glm::max (v0.x, glm::max (v1.x, v2.x)) < -hw.x;\n\n  const bool sep3 = glm::min (v0.y, glm::min (v1.y, v2.y)) > hw.y;\n  const bool sep4 = glm::max (v0.y, glm::max (v1.y, v2.y)) < -hw.y;\n\n  const bool sep5 = glm::min (v0.z, glm::min (v1.z, v2.z)) > hw.z;\n  const bool sep6 = glm::max (v0.z, glm::max (v1.z, v2.z)) < -hw.z;\n\n  if (sep1 || sep2 || sep3 || sep4 || sep5 || sep6)\n  {\n    return false;\n  }\n\n  const bool sep7 = sepAxis (glm::cross (x, e0));\n  const bool sep8 = sepAxis (glm::cross (x, e1));\n  const bool sep9 = sepAxis (glm::cross (x, e2));\n\n  const bool sep10 = sepAxis (glm::cross (y, e0));\n  const bool sep11 = sepAxis (glm::cross (y, e1));\n  const bool sep12 = sepAxis (glm::cross (y, e2));\n\n  const bool sep13 = sepAxis (glm::cross (z, e0));\n  const bool sep14 = sepAxis (glm::cross (z, e1));\n  const bool sep15 = sepAxis (glm::cross (z, e2));\n\n  if (sep7 || sep8 || sep9 || sep10 || sep11 || sep12 || sep13 || sep14 || sep15)\n  {\n    return false;\n  }\n  else\n  {\n    return IntersectionUtil::intersects (PrimPlane (tri.vertex1 (), tri.normal ()), box);\n  }\n}\n"
  },
  {
    "path": "lib/src/intersection.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_INTERSECTION\n#define DILAY_INTERSECTION\n\n#include <glm/glm.hpp>\n\nclass PrimAABox;\nclass PrimCone;\nclass PrimCylinder;\nclass PrimPlane;\nclass PrimRay;\nclass PrimSphere;\nclass PrimTriangle;\n\nclass Intersection\n{\npublic:\n  Intersection ();\n\n  bool             isIntersection () const;\n  const glm::vec3& position () const;\n  const glm::vec3& normal () const;\n  float            distance () const;\n\n  void reset ();\n  bool update (float, const glm::vec3&, const glm::vec3&);\n\n  static Intersection& min (Intersection&, Intersection&);\n  static void          sort (Intersection&, Intersection&);\n\nprivate:\n  bool      _isIntersection;\n  float     _distance;\n  glm::vec3 _position;\n  glm::vec3 _normal;\n};\n\nnamespace IntersectionUtil\n{\n  bool intersects (const PrimSphere&, const PrimTriangle&);\n  bool intersects (const PrimSphere&, const PrimAABox&);\n  bool intersects (const PrimSphere&, const PrimSphere&);\n  bool intersects (const PrimRay&, const PrimSphere&, float*);\n  bool intersects (const PrimRay&, const PrimPlane&, float*);\n  bool intersects (const PrimRay&, const PrimTriangle&, bool, float*);\n  bool intersects (const PrimRay&, const PrimAABox&, float*);\n  bool intersects (const PrimRay&, const PrimCylinder&, float*, float*);\n  bool intersects (const PrimRay&, const PrimCone&, float*, float*);\n  bool intersects (const PrimPlane&, const PrimAABox&);\n  bool intersects (const PrimPlane&, const PrimTriangle&);\n  bool intersects (const PrimCylinder&, const glm::vec3&);\n  bool intersects (const PrimCone&, const glm::vec3&);\n  bool intersects (const PrimAABox&, const PrimAABox&);\n  bool intersects (const PrimAABox&, const PrimTriangle&);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/isosurface-extraction/IsosurfaceExtractionConfigurations.hs",
    "content": "{- This file is part of Dilay\n - Copyright © 2015-2018 Alexander Bau\n - Use and redistribute under the terms of the GNU General Public License\n -}\n\nimport Control.Exception (assert)\nimport Control.Monad (forM_)\nimport Data.Char (toLower)\nimport Data.Function (on)\nimport Data.List (intercalate,nubBy,sortBy)\n\ndata Configuration = Configuration \n  { base :: Int\n  , vertices :: [Bool]\n  , vertexIndices :: [Int]\n  , nonManifoldConfig :: Bool\n  } \n  deriving Show\n\nset :: Int -> a -> [a] -> [a]\nset 0 x (y:ys) = x:ys\nset i x (y:ys) = y:(set (i - 1) x ys)\n\nsetList :: [Int] -> a -> [a] -> [a]\nsetList is value xs = foldl (\\xs i -> set i value xs) xs is\n\nbaseConfigurations :: [Configuration]\nbaseConfigurations = \n  [ go 0  []                       []                                             False\n  , go 1  [4]                      [[2, 6, 7]]                                    False\n  , go 2  [4, 5]                   [[2, 5, 7, 10]]                                False\n  , go 3  [4, 7]                   [[2, 6, 7], [9, 10, 11]]                       False\n  , go 4  [3, 4]                   [[2, 6, 7], [3, 4, 11]]                        False\n\n  , go 5  [0, 1, 5]                [[1, 2, 4, 6, 10]]                             False\n  , go 6  [3, 4, 5]                [[2, 5, 7, 10], [3, 4, 11]]                    False\n  , go 7  [3, 5, 6]                [[7, 8, 9], [3, 4, 11], [5, 6, 10]]            False\n  , go 8  [0, 1, 4, 5]             [[1, 4, 7, 10]]                                False\n  , go 9  [0, 1, 2, 4]             [[3, 4, 5, 6, 7, 8]]                           False\n\n  , go 10 [1, 3, 4, 6]             [[2, 6, 8, 9], [0, 3, 5, 11]]                  False\n  , go 11 [0, 1, 3, 4]             [[1, 3, 5, 6, 7, 11]]                          False\n  , go 12 [0, 1, 5, 6]             [[7, 8, 9], [1, 2, 4, 6, 10]]                  False\n  , go 13 [1, 2, 4, 7]             [[2, 6, 7], [9, 10, 11], [1, 3, 8], [0, 4, 5]] False\n  , go 14 [0, 1, 2, 5]             [[2, 3, 4, 6, 8, 10]]                          False\n\n  , go 15 [0, 1, 2, 4, 7]          [[3, 4, 5, 6, 7, 8], [9, 10, 11]]              False\n  , go 16 [0, 1, 2, 6, 7]          [[2, 5, 7, 10], [3, 4, 11]]                    True\n  , go 17 [2, 3, 4, 6, 7]          [[1, 2, 4, 6, 10]]                             False\n  , go 18 [0, 1, 2, 5, 6, 7]       [[2, 6, 7], [3, 4, 11]]                        False\n  , go 19 [0, 1, 2, 3, 5, 6]       [[2, 6, 7], [9, 10, 11]]                       True\n\n  , go 20 [0, 1, 2, 3, 6, 7]       [[2, 5, 7, 10]]                                False\n  , go 21 [0, 1, 2, 3, 5, 6, 7]    [[2, 6, 7]]                                    False\n  , go 22 [0, 1, 2, 3, 4, 5, 6, 7] []                                             False\n  ]\n  where\n    go base vertices vertexIndices nonManifold = \n      Configuration base (setList vertices True $ replicate 8 False)\n                    (mkVertexIndices 0 vertexIndices) nonManifold\n\n    mkVertexIndices :: Int -> [[Int]] -> [Int]\n    mkVertexIndices vertexIndex [] = replicate 12 (-1)\n    mkVertexIndices vertexIndex (edgeGroup:edgeGroups) = setList edgeGroup vertexIndex rest\n      where\n        rest = mkVertexIndices (vertexIndex + 1) edgeGroups\n\n\nallConfigurations :: [Configuration]\nallConfigurations = sortBy (sort `on` vertices)\n                  $ nubBy ((==) `on` vertices)\n                  $ concat\n                  $ do\n  x <- [id, rotateX, rotateX . rotateX, rotateX . rotateX . rotateX]\n  y <- [id, rotateY, rotateY . rotateY, rotateY . rotateY . rotateY]\n  z <- [id, rotateZ, rotateZ . rotateZ, rotateZ . rotateZ . rotateZ]\n\n  return $ map (($) (x . y . z)) baseConfigurations\n\n  where\n    rotateX (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7]\n                           [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold)\n\n      = Configuration base [v4, v5, v0, v1, v6, v7, v2, v3]\n                      [e6, e2, e7, e0, e5, e10, e9, e8, e1, e3, e11, e4] nonManifold\n\n\n    rotateY (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7]\n                           [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold)\n\n      = Configuration base [v1, v5, v3, v7, v0, v4, v2, v6]\n                      [e5, e4, e0, e11, e10, e6, e2, e1, e3, e8, e7, e9] nonManifold\n\n\n    rotateZ (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7]\n                           [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold)\n\n      = Configuration base [v2, v0, v3, v1, v6, v4, v7, v5]\n                      [e1, e3, e8, e4, e0, e2, e7, e9, e11, e10, e6, e5] nonManifold\n\n    sort xs ys = go (reverse xs) (reverse ys)\n      where\n        go (False:xs) (True:ys)  = LT\n        go (True:xs)  (False:ys) = GT\n        go (_:xs)     (_:ys)     = go xs ys\n\nmain :: IO ()\nmain = assert (length allConfigurations == 256)\n     $ printBases >> printNonManifold >> printVertexIndices\n  where\n    printBases = putStrLn $ toList (show . base) allConfigurations\n\n    printNonManifold = putStrLn $ toList (map toLower . show . nonManifoldConfig) allConfigurations\n\n    printVertexIndices =\n      putStrLn $ toList (\\c -> toList show (vertexIndices c) ++ \"\\n\") allConfigurations\n\n    toList xToString xs = unwords $ \"{\" :\n                                  [ intercalate \", \" $ map xToString xs ]\n                                  ++ [\"}\"]\n"
  },
  {
    "path": "lib/src/isosurface-extraction/grid.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <array>\n#include <glm/gtx/norm.hpp>\n#include \"dynamic/mesh.hpp\"\n#include \"isosurface-extraction/grid.hpp\"\n#include \"mesh.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"util.hpp\"\n\n/* vertex layout:          edge layout:          face layout:\n *\n *     2------------3          o-----3------o      - 0: bottom\n *    /|           /|         /|           /|      - 1: top\n *   / |          / |        8 1         11 |      - 2: left\n *  /  |         /  |       /  |         /  4      - 3: right\n * 6------------7   |      o-----9------o   |      - 4: back\n * |   |        |   |      |   |        |   |      - 5: front\n * |   0--------|---1      |   o----0---|---o\n * |  /         |  /       7  /        10  /\n * | /          | /        | 2          | 5\n * |/           |/         |/           |/\n * 4------------5          o-----6------o\n */\nnamespace\n{\n  static const glm::vec3 invalidVec3 = glm::vec3 (Util::minFloat ());\n\n  static bool nonManifoldConfig[256] = {\n    false, false, false, false, false, false, false, false, false, false, false, false, false,\n    false, false, false, false, false, false, false, false, false, false, false, false, false,\n    false, false, false, false, false, false, false, false, false, false, false, false, false,\n    false, false, false, false, false, false, false, false, false, false, false, false, false,\n    false, false, false, false, false, false, false, false, false, true,  true,  false, false,\n    false, false, false, false, false, false, false, false, false, false, false, false, false,\n    false, false, false, false, false, false, false, false, false, false, false, false, false,\n    true,  false, false, true,  false, false, false, false, false, false, false, false, true,\n    false, false, false, false, false, false, true,  true,  false, false, false, false, false,\n    false, true,  false, false, false, true,  true,  true,  true,  false, false, false, false,\n    false, false, false, false, false, false, false, false, false, false, false, false, false,\n    false, false, false, false, false, false, false, false, false, false, false, false, true,\n    false, true,  false, true,  false, false, false, false, false, false, false, true,  false,\n    false, false, false, false, true,  false, false, false, false, false, false, false, true,\n    false, true,  false, true,  false, false, true,  false, true,  false, false, false, false,\n    false, false, false, false, true,  false, false, false, true,  false, false, false, false,\n    false, false, false, true,  false, false, false, true,  false, true,  true,  false, false,\n    false, true,  false, false, false, false, true,  false, true,  true,  false, false, false,\n    false, true,  false, true,  false, false, false, false, false, false, false, false, true,\n    false, false, true,  false, false, false, false, false, false};\n\n  static char vertexIndicesByConfiguration[256][12] = {\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {0, -1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1},\n    {-1, 0, 0, -1, 0, 0, -1, -1, -1, -1, -1, -1},\n    {-1, 0, -1, 0, -1, -1, -1, -1, 0, -1, -1, -1},\n    {0, -1, 0, 0, -1, -1, -1, -1, 0, -1, -1, -1},\n    {0, 1, -1, 1, 0, 0, -1, -1, 1, -1, -1, -1},\n    {-1, -1, 0, 0, 0, 0, -1, -1, 0, -1, -1, -1},\n    {-1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1, 0},\n    {0, 0, 0, 1, 1, -1, -1, -1, -1, -1, -1, 1},\n    {0, -1, -1, 0, -1, 0, -1, -1, -1, -1, -1, 0},\n    {-1, 0, 0, 0, -1, 0, -1, -1, -1, -1, -1, 0},\n    {-1, 0, -1, -1, 0, -1, -1, -1, 0, -1, -1, 0},\n    {0, -1, 0, -1, 0, -1, -1, -1, 0, -1, -1, 0},\n    {0, 0, -1, -1, -1, 0, -1, -1, 0, -1, -1, 0},\n    {-1, -1, 0, -1, -1, 0, -1, -1, 0, -1, -1, 0},\n    {-1, -1, 0, -1, -1, -1, 0, 0, -1, -1, -1, -1},\n    {0, 0, -1, -1, -1, -1, 0, 0, -1, -1, -1, -1},\n    {0, -1, 1, -1, 0, 0, 1, 1, -1, -1, -1, -1},\n    {-1, 0, -1, -1, 0, 0, 0, 0, -1, -1, -1, -1},\n    {-1, 1, 0, 1, -1, -1, 0, 0, 1, -1, -1, -1},\n    {0, -1, -1, 0, -1, -1, 0, 0, 0, -1, -1, -1},\n    {2, 0, 1, 0, 2, 2, 1, 1, 0, -1, -1, -1},\n    {-1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, -1},\n    {-1, -1, 0, 1, 1, -1, 0, 0, -1, -1, -1, 1},\n    {0, 0, -1, 1, 1, -1, 0, 0, -1, -1, -1, 1},\n    {0, -1, 1, 0, -1, 0, 1, 1, -1, -1, -1, 0},\n    {-1, 0, -1, 0, -1, 0, 0, 0, -1, -1, -1, 0},\n    {-1, 0, 1, -1, 0, -1, 1, 1, 0, -1, -1, 0},\n    {0, -1, -1, -1, 0, -1, 0, 0, 0, -1, -1, 0},\n    {1, 1, 0, -1, -1, 1, 0, 0, 1, -1, -1, 1},\n    {-1, -1, -1, -1, -1, 0, 0, 0, 0, -1, -1, 0},\n    {-1, -1, -1, -1, -1, 0, 0, -1, -1, -1, 0, -1},\n    {0, 0, 0, -1, -1, 1, 1, -1, -1, -1, 1, -1},\n    {0, -1, -1, -1, 0, -1, 0, -1, -1, -1, 0, -1},\n    {-1, 0, 0, -1, 0, -1, 0, -1, -1, -1, 0, -1},\n    {-1, 1, -1, 1, -1, 0, 0, -1, 1, -1, 0, -1},\n    {0, -1, 0, 0, -1, 1, 1, -1, 0, -1, 1, -1},\n    {0, 1, -1, 1, 0, -1, 0, -1, 1, -1, 0, -1},\n    {-1, -1, 0, 0, 0, -1, 0, -1, 0, -1, 0, -1},\n    {-1, -1, -1, 1, 1, 0, 0, -1, -1, -1, 0, 1},\n    {1, 1, 1, 0, 0, 2, 2, -1, -1, -1, 2, 0},\n    {0, -1, -1, 0, -1, -1, 0, -1, -1, -1, 0, 0},\n    {-1, 0, 0, 0, -1, -1, 0, -1, -1, -1, 0, 0},\n    {-1, 0, -1, -1, 0, 1, 1, -1, 0, -1, 1, 0},\n    {1, -1, 1, -1, 1, 0, 0, -1, 1, -1, 0, 1},\n    {0, 0, -1, -1, -1, -1, 0, -1, 0, -1, 0, 0},\n    {-1, -1, 0, -1, -1, -1, 0, -1, 0, -1, 0, 0},\n    {-1, -1, 0, -1, -1, 0, -1, 0, -1, -1, 0, -1},\n    {0, 0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1},\n    {0, -1, 0, -1, 0, -1, -1, 0, -1, -1, 0, -1},\n    {-1, 0, -1, -1, 0, -1, -1, 0, -1, -1, 0, -1},\n    {-1, 1, 0, 1, -1, 0, -1, 0, 1, -1, 0, -1},\n    {0, -1, -1, 0, -1, 0, -1, 0, 0, -1, 0, -1},\n    {1, 0, 1, 0, 1, -1, -1, 1, 0, -1, 1, -1},\n    {-1, -1, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1},\n    {-1, -1, 0, 1, 1, 0, -1, 0, -1, -1, 0, 1},\n    {1, 1, -1, 0, 0, 1, -1, 1, -1, -1, 1, 0},\n    {0, -1, 0, 0, -1, -1, -1, 0, -1, -1, 0, 0},\n    {-1, 0, -1, 0, -1, -1, -1, 0, -1, -1, 0, 0},\n    {-1, 1, 0, -1, 1, 0, -1, 0, 1, -1, 0, 1},\n    {1, -1, -1, -1, 1, 1, -1, 0, 0, -1, 0, 0},\n    {1, 1, 1, -1, -1, -1, -1, 0, 0, -1, 0, 0},\n    {-1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, 0},\n    {-1, -1, -1, -1, -1, -1, -1, 0, 0, 0, -1, -1},\n    {0, 0, 0, -1, -1, -1, -1, 1, 1, 1, -1, -1},\n    {1, -1, -1, -1, 1, 1, -1, 0, 0, 0, -1, -1},\n    {-1, 0, 0, -1, 0, 0, -1, 1, 1, 1, -1, -1},\n    {-1, 0, -1, 0, -1, -1, -1, 0, -1, 0, -1, -1},\n    {0, -1, 0, 0, -1, -1, -1, 0, -1, 0, -1, -1},\n    {1, 0, -1, 0, 1, 1, -1, 0, -1, 0, -1, -1},\n    {-1, -1, 0, 0, 0, 0, -1, 0, -1, 0, -1, -1},\n    {-1, -1, -1, 0, 0, -1, -1, 1, 1, 1, -1, 0},\n    {2, 2, 2, 0, 0, -1, -1, 1, 1, 1, -1, 0},\n    {0, -1, -1, 0, -1, 0, -1, 1, 1, 1, -1, 0},\n    {-1, 1, 1, 1, -1, 1, -1, 0, 0, 0, -1, 1},\n    {-1, 0, -1, -1, 0, -1, -1, 0, -1, 0, -1, 0},\n    {0, -1, 0, -1, 0, -1, -1, 0, -1, 0, -1, 0},\n    {0, 0, -1, -1, -1, 0, -1, 0, -1, 0, -1, 0},\n    {-1, -1, 0, -1, -1, 0, -1, 0, -1, 0, -1, 0},\n    {-1, -1, 0, -1, -1, -1, 0, -1, 0, 0, -1, -1},\n    {0, 0, -1, -1, -1, -1, 0, -1, 0, 0, -1, -1},\n    {1, -1, 0, -1, 1, 1, 0, -1, 0, 0, -1, -1},\n    {-1, 0, -1, -1, 0, 0, 0, -1, 0, 0, -1, -1},\n    {-1, 0, 0, 0, -1, -1, 0, -1, -1, 0, -1, -1},\n    {0, -1, -1, 0, -1, -1, 0, -1, -1, 0, -1, -1},\n    {0, 1, 1, 1, 0, 0, 1, -1, -1, 1, -1, -1},\n    {-1, -1, -1, 0, 0, 0, 0, -1, -1, 0, -1, -1},\n    {-1, -1, 0, 1, 1, -1, 0, -1, 0, 0, -1, 1},\n    {1, 1, -1, 0, 0, -1, 1, -1, 1, 1, -1, 0},\n    {1, -1, 0, 1, -1, 1, 0, -1, 0, 0, -1, 1},\n    {-1, 1, -1, 1, -1, 0, 0, -1, 1, 0, -1, 0},\n    {-1, 0, 0, -1, 0, -1, 0, -1, -1, 0, -1, 0},\n    {0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1, 0},\n    {1, 1, 1, -1, -1, 0, 0, -1, -1, 0, -1, 0},\n    {-1, -1, -1, -1, -1, 0, 0, -1, -1, 0, -1, 0},\n    {-1, -1, -1, -1, -1, 0, 0, 1, 1, 1, 0, -1},\n    {1, 1, 1, -1, -1, 0, 0, 2, 2, 2, 0, -1},\n    {0, -1, -1, -1, 0, -1, 0, 1, 1, 1, 0, -1},\n    {-1, 1, 1, -1, 1, -1, 1, 0, 0, 0, 1, -1},\n    {-1, 0, -1, 0, -1, 1, 1, 0, -1, 0, 1, -1},\n    {1, -1, 1, 1, -1, 0, 0, 1, -1, 1, 0, -1},\n    {0, 1, -1, 1, 0, -1, 0, 1, -1, 1, 0, -1},\n    {-1, -1, 1, 0, 0, -1, 1, 1, -1, 0, 0, -1},\n    {-1, -1, -1, 1, 1, 2, 2, 0, 0, 0, 2, 1},\n    {2, 2, 2, 3, 3, 0, 0, 1, 1, 1, 0, 3},\n    {1, -1, -1, 1, -1, -1, 1, 0, 0, 0, 1, 1},\n    {-1, 0, 0, 0, -1, -1, 0, 1, 1, 1, 0, 0},\n    {-1, 1, -1, -1, 1, 0, 0, 1, -1, 1, 0, 1},\n    {0, -1, 0, -1, 0, 1, 1, 0, -1, 0, 1, 0},\n    {0, 0, -1, -1, -1, -1, 0, 0, -1, 1, 1, 1},\n    {-1, -1, 0, -1, -1, -1, 0, 0, -1, 1, 1, 1},\n    {-1, -1, 0, -1, -1, 0, -1, -1, 0, 0, 0, -1},\n    {0, 0, -1, -1, -1, 0, -1, -1, 0, 0, 0, -1},\n    {0, -1, 0, -1, 0, -1, -1, -1, 0, 0, 0, -1},\n    {-1, 0, -1, -1, 0, -1, -1, -1, 0, 0, 0, -1},\n    {-1, 0, 0, 0, -1, 0, -1, -1, -1, 0, 0, -1},\n    {0, -1, -1, 0, -1, 0, -1, -1, -1, 0, 0, -1},\n    {1, 1, 1, 0, 0, -1, -1, -1, -1, 0, 0, -1},\n    {-1, -1, -1, 0, 0, -1, -1, -1, -1, 0, 0, -1},\n    {-1, -1, 1, 0, 0, 1, -1, -1, 1, 1, 1, 0},\n    {0, 0, -1, 1, 1, 0, -1, -1, 0, 0, 0, 1},\n    {0, -1, 0, 0, -1, -1, -1, -1, 0, 1, 1, 1},\n    {-1, 0, -1, 0, -1, -1, -1, -1, 0, 1, 1, 1},\n    {-1, 0, 0, -1, 0, 0, -1, -1, -1, 1, 1, 1},\n    {0, -1, -1, -1, 0, 0, -1, -1, -1, 1, 1, 1},\n    {1, 1, 1, -1, -1, -1, -1, -1, -1, 0, 0, 0},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0},\n    {1, 1, 1, -1, -1, -1, -1, -1, -1, 0, 0, 0},\n    {0, -1, -1, -1, 0, 0, -1, -1, -1, 1, 1, 1},\n    {-1, 0, 0, -1, 0, 0, -1, -1, -1, 1, 1, 1},\n    {-1, 0, -1, 0, -1, -1, -1, -1, 0, 1, 1, 1},\n    {0, -1, 0, 0, -1, -1, -1, -1, 0, 1, 1, 1},\n    {2, 1, -1, 1, 2, 2, -1, -1, 1, 0, 0, 0},\n    {-1, -1, 1, 1, 1, 1, -1, -1, 1, 0, 0, 0},\n    {-1, -1, -1, 0, 0, -1, -1, -1, -1, 0, 0, -1},\n    {1, 1, 1, 0, 0, -1, -1, -1, -1, 0, 0, -1},\n    {0, -1, -1, 0, -1, 0, -1, -1, -1, 0, 0, -1},\n    {-1, 0, 0, 0, -1, 0, -1, -1, -1, 0, 0, -1},\n    {-1, 0, -1, -1, 0, -1, -1, -1, 0, 0, 0, -1},\n    {0, -1, 0, -1, 0, -1, -1, -1, 0, 0, 0, -1},\n    {0, 0, -1, -1, -1, 0, -1, -1, 0, 0, 0, -1},\n    {-1, -1, 0, -1, -1, 0, -1, -1, 0, 0, 0, -1},\n    {-1, -1, 0, -1, -1, -1, 0, 0, -1, 1, 1, 1},\n    {0, 0, -1, -1, -1, -1, 0, 0, -1, 1, 1, 1},\n    {1, -1, 2, -1, 1, 1, 2, 2, -1, 0, 0, 0},\n    {-1, 1, -1, -1, 1, 1, 1, 1, -1, 0, 0, 0},\n    {-1, 1, 0, 1, -1, -1, 0, 0, 1, 2, 2, 2},\n    {1, -1, -1, 1, -1, -1, 1, 1, 1, 0, 0, 0},\n    {3, 2, 0, 2, 3, 3, 0, 0, 2, 1, 1, 1},\n    {-1, -1, -1, 0, 0, 0, 0, 0, 0, 1, 1, 1},\n    {-1, -1, 1, 0, 0, -1, 1, 1, -1, 0, 0, -1},\n    {1, 1, -1, 0, 0, -1, 1, 1, -1, 0, 0, -1},\n    {1, -1, 0, 1, -1, 1, 0, 0, -1, 1, 1, -1},\n    {-1, 0, -1, 0, -1, 1, 1, 0, -1, 0, 1, -1},\n    {-1, 1, 0, -1, 1, -1, 0, 0, 1, 1, 1, -1},\n    {0, -1, -1, -1, 0, -1, 0, 1, 1, 1, 0, -1},\n    {0, 0, 1, -1, -1, 0, 1, 1, 0, 0, 0, -1},\n    {-1, -1, -1, -1, -1, 0, 0, 1, 1, 1, 0, -1},\n    {-1, -1, -1, -1, -1, 0, 0, -1, -1, 0, -1, 0},\n    {1, 1, 1, -1, -1, 0, 0, -1, -1, 0, -1, 0},\n    {0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1, 0},\n    {-1, 0, 0, -1, 0, -1, 0, -1, -1, 0, -1, 0},\n    {-1, 1, -1, 1, -1, 0, 0, -1, 1, 0, -1, 0},\n    {1, -1, 1, 1, -1, 0, 0, -1, 1, 0, -1, 0},\n    {1, 0, -1, 0, 1, -1, 1, -1, 0, 1, -1, 1},\n    {-1, -1, 0, 1, 1, -1, 0, -1, 0, 0, -1, 1},\n    {-1, -1, -1, 0, 0, 0, 0, -1, -1, 0, -1, -1},\n    {0, 0, 0, 1, 1, 1, 1, -1, -1, 1, -1, -1},\n    {0, -1, -1, 0, -1, -1, 0, -1, -1, 0, -1, -1},\n    {-1, 0, 0, 0, -1, -1, 0, -1, -1, 0, -1, -1},\n    {-1, 0, -1, -1, 0, 0, 0, -1, 0, 0, -1, -1},\n    {1, -1, 0, -1, 1, 1, 0, -1, 0, 0, -1, -1},\n    {0, 0, -1, -1, -1, -1, 0, -1, 0, 0, -1, -1},\n    {-1, -1, 0, -1, -1, -1, 0, -1, 0, 0, -1, -1},\n    {-1, -1, 0, -1, -1, 0, -1, 0, -1, 0, -1, 0},\n    {0, 0, -1, -1, -1, 0, -1, 0, -1, 0, -1, 0},\n    {0, -1, 0, -1, 0, -1, -1, 0, -1, 0, -1, 0},\n    {-1, 0, -1, -1, 0, -1, -1, 0, -1, 0, -1, 0},\n    {-1, 0, 1, 0, -1, 1, -1, 1, 0, 1, -1, 1},\n    {0, -1, -1, 0, -1, 0, -1, 1, 1, 1, -1, 0},\n    {0, 1, 0, 1, 0, -1, -1, 0, 1, 0, -1, 0},\n    {-1, -1, -1, 0, 0, -1, -1, 1, 1, 1, -1, 0},\n    {-1, -1, 0, 0, 0, 0, -1, 0, -1, 0, -1, -1},\n    {1, 0, -1, 0, 1, 1, -1, 0, -1, 0, -1, -1},\n    {0, -1, 0, 0, -1, -1, -1, 0, -1, 0, -1, -1},\n    {-1, 0, -1, 0, -1, -1, -1, 0, -1, 0, -1, -1},\n    {-1, 0, 0, -1, 0, 0, -1, 1, 1, 1, -1, -1},\n    {1, -1, -1, -1, 1, 1, -1, 0, 0, 0, -1, -1},\n    {0, 0, 0, -1, -1, -1, -1, 1, 1, 1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, 0, 0, 0, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, 0},\n    {1, 1, 1, -1, -1, -1, -1, 0, 0, -1, 0, 0},\n    {1, -1, -1, -1, 1, 1, -1, 0, 0, -1, 0, 0},\n    {-1, 1, 1, -1, 1, 1, -1, 0, 0, -1, 0, 0},\n    {-1, 0, -1, 0, -1, -1, -1, 0, -1, -1, 0, 0},\n    {0, -1, 0, 0, -1, -1, -1, 0, -1, -1, 0, 0},\n    {0, 1, -1, 1, 0, 0, -1, 1, -1, -1, 1, 1},\n    {-1, -1, 0, 1, 1, 0, -1, 0, -1, -1, 0, 1},\n    {-1, -1, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1},\n    {0, 0, 0, 1, 1, -1, -1, 1, 1, -1, 1, -1},\n    {0, -1, -1, 0, -1, 0, -1, 0, 0, -1, 0, -1},\n    {-1, 1, 0, 1, -1, 0, -1, 0, 1, -1, 0, -1},\n    {-1, 0, -1, -1, 0, -1, -1, 0, -1, -1, 0, -1},\n    {0, -1, 0, -1, 0, -1, -1, 0, -1, -1, 0, -1},\n    {0, 0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1},\n    {-1, -1, 0, -1, -1, 0, -1, 0, -1, -1, 0, -1},\n    {-1, -1, 0, -1, -1, -1, 0, -1, 0, -1, 0, 0},\n    {0, 0, -1, -1, -1, -1, 0, -1, 0, -1, 0, 0},\n    {0, -1, 1, -1, 0, 0, 1, -1, 1, -1, 1, 1},\n    {-1, 0, -1, -1, 0, 1, 1, -1, 0, -1, 1, 0},\n    {-1, 0, 0, 0, -1, -1, 0, -1, -1, -1, 0, 0},\n    {0, -1, -1, 0, -1, -1, 0, -1, -1, -1, 0, 0},\n    {1, 0, 0, 0, 1, 1, 0, -1, -1, -1, 0, 0},\n    {-1, -1, -1, 1, 1, 0, 0, -1, -1, -1, 0, 1},\n    {-1, -1, 0, 0, 0, -1, 0, -1, 0, -1, 0, -1},\n    {0, 1, -1, 1, 0, -1, 0, -1, 1, -1, 0, -1},\n    {0, -1, 0, 0, -1, 1, 1, -1, 0, -1, 1, -1},\n    {-1, 1, -1, 1, -1, 0, 0, -1, 1, -1, 0, -1},\n    {-1, 0, 0, -1, 0, -1, 0, -1, -1, -1, 0, -1},\n    {0, -1, -1, -1, 0, -1, 0, -1, -1, -1, 0, -1},\n    {0, 0, 0, -1, -1, 1, 1, -1, -1, -1, 1, -1},\n    {-1, -1, -1, -1, -1, 0, 0, -1, -1, -1, 0, -1},\n    {-1, -1, -1, -1, -1, 0, 0, 0, 0, -1, -1, 0},\n    {0, 0, 0, -1, -1, 1, 1, 1, 1, -1, -1, 1},\n    {0, -1, -1, -1, 0, -1, 0, 0, 0, -1, -1, 0},\n    {-1, 0, 1, -1, 0, -1, 1, 1, 0, -1, -1, 0},\n    {-1, 0, -1, 0, -1, 0, 0, 0, -1, -1, -1, 0},\n    {0, -1, 1, 0, -1, 0, 1, 1, -1, -1, -1, 0},\n    {0, 0, -1, 1, 1, -1, 0, 0, -1, -1, -1, 1},\n    {-1, -1, 0, 1, 1, -1, 0, 0, -1, -1, -1, 1},\n    {-1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, -1},\n    {1, 1, 1, 0, 0, 0, 0, 0, 0, -1, -1, -1},\n    {0, -1, -1, 0, -1, -1, 0, 0, 0, -1, -1, -1},\n    {-1, 1, 0, 1, -1, -1, 0, 0, 1, -1, -1, -1},\n    {-1, 0, -1, -1, 0, 0, 0, 0, -1, -1, -1, -1},\n    {0, -1, 1, -1, 0, 0, 1, 1, -1, -1, -1, -1},\n    {0, 0, -1, -1, -1, -1, 0, 0, -1, -1, -1, -1},\n    {-1, -1, 0, -1, -1, -1, 0, 0, -1, -1, -1, -1},\n    {-1, -1, 0, -1, -1, 0, -1, -1, 0, -1, -1, 0},\n    {0, 0, -1, -1, -1, 0, -1, -1, 0, -1, -1, 0},\n    {0, -1, 0, -1, 0, -1, -1, -1, 0, -1, -1, 0},\n    {-1, 0, -1, -1, 0, -1, -1, -1, 0, -1, -1, 0},\n    {-1, 0, 0, 0, -1, 0, -1, -1, -1, -1, -1, 0},\n    {0, -1, -1, 0, -1, 0, -1, -1, -1, -1, -1, 0},\n    {0, 0, 0, 1, 1, -1, -1, -1, -1, -1, -1, 1},\n    {-1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1, 0},\n    {-1, -1, 0, 0, 0, 0, -1, -1, 0, -1, -1, -1},\n    {0, 1, -1, 1, 0, 0, -1, -1, 1, -1, -1, -1},\n    {0, -1, 0, 0, -1, -1, -1, -1, 0, -1, -1, -1},\n    {-1, 0, -1, 0, -1, -1, -1, -1, 0, -1, -1, -1},\n    {-1, 0, 0, -1, 0, 0, -1, -1, -1, -1, -1, -1},\n    {0, -1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1},\n    {0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}};\n\n  static unsigned char edgeIndicesByFace[6][4] = {{0, 2, 5, 6},   {3, 8, 9, 11}, {1, 2, 7, 8},\n                                                  {4, 5, 10, 11}, {0, 1, 3, 4},  {6, 7, 9, 10}};\n\n  unsigned char numVertices (unsigned char configuration)\n  {\n    char n = -1;\n    for (unsigned char i = 0; i < 12; i++)\n    {\n      n = std::max (n, vertexIndicesByConfiguration[configuration][i]);\n    }\n    return (unsigned char) (n + 1);\n  }\n\n  bool isIntersecting (float s1, float s2)\n  {\n    return (s1 < 0.0f && s2 >= 0.0f) || (s1 >= 0.0f && s2 < 0.0f);\n  }\n\n  struct Cube\n  {\n    unsigned char               configuration;\n    glm::vec3                   vertex;\n    unsigned char               numVertexIndicesInMesh;\n    std::array<unsigned int, 3> vertexIndicesInMesh;\n    bool                        nonManifold;\n\n    Cube ()\n      : configuration (0)\n      , vertex (invalidVec3)\n      , numVertexIndicesInMesh (0)\n      , nonManifold (false)\n    {\n    }\n\n    bool nonManifoldConfig () const { return ::nonManifoldConfig[this->configuration]; }\n\n    bool collapseNonManifoldConfig () const\n    {\n      return this->nonManifoldConfig () && this->nonManifold == false;\n    }\n\n    unsigned int vertexIndex (unsigned char edge) const\n    {\n      assert (edge < 12);\n      assert (vertexIndicesByConfiguration[this->configuration][edge] >= 0);\n      assert (this->nonManifold == false || this->nonManifoldConfig ());\n\n      const unsigned char i = this->collapseNonManifoldConfig ()\n                                ? 0\n                                : vertexIndicesByConfiguration[this->configuration][edge];\n      assert (i < this->vertexIndicesInMesh.size ());\n      assert (i < this->numVertexIndicesInMesh);\n\n      return this->vertexIndicesInMesh[i];\n    }\n\n    unsigned char getAmbiguousFaceOfNonManifoldConfig () const\n    {\n      assert (this->nonManifoldConfig ());\n\n      for (unsigned int i = 0; i < 6; i++)\n      {\n        const unsigned char edge1 = edgeIndicesByFace[i][0];\n        const unsigned char edge2 = edgeIndicesByFace[i][1];\n        const unsigned char edge3 = edgeIndicesByFace[i][2];\n        const unsigned char edge4 = edgeIndicesByFace[i][3];\n\n        const char vertex1 = vertexIndicesByConfiguration[this->configuration][edge1];\n        const char vertex2 = vertexIndicesByConfiguration[this->configuration][edge2];\n        const char vertex3 = vertexIndicesByConfiguration[this->configuration][edge3];\n        const char vertex4 = vertexIndicesByConfiguration[this->configuration][edge4];\n\n        if (vertex1 != -1 && vertex2 != -1 && vertex3 != -1 && vertex4 != -1)\n        {\n          return (unsigned char) i;\n        }\n      }\n      DILAY_IMPOSSIBLE\n    }\n  };\n}\n\nconst unsigned char IsosurfaceExtractionGrid::vertexIndicesByEdge[12][2] = {\n  {0, 1}, {0, 2}, {0, 4}, {2, 3}, {1, 3}, {1, 5}, {4, 5}, {4, 6}, {2, 6}, {6, 7}, {5, 7}, {3, 7}};\n\nstruct IsosurfaceExtractionGrid::Impl\n{\n  float              resolution;\n  glm::vec3          sampleMin;\n  glm::vec3          sampleMax;\n  glm::uvec3         numSamples;\n  std::vector<float> samples;\n  glm::uvec3         numCubes;\n  std::vector<Cube>  cubes;\n\n  Impl (const PrimAABox& bounds, float r)\n    : resolution (r)\n  {\n    const glm::vec3 min = bounds.minimum () - glm::vec3 (Util::epsilon () + r);\n    const glm::vec3 max = bounds.maximum () + glm::vec3 (Util::epsilon () + r);\n\n    this->sampleMin = min;\n    this->numSamples = glm::vec3 (1.0f) + glm::ceil ((max - min) / glm::vec3 (r));\n    this->numCubes = this->numSamples - glm::uvec3 (1);\n\n    const unsigned int totalNumSamples =\n      this->numSamples.x * this->numSamples.y * this->numSamples.z;\n    const unsigned int totalNumCubes = this->numCubes.x * this->numCubes.y * this->numCubes.z;\n\n    this->samples.resize (totalNumSamples, Util::maxFloat ());\n    this->cubes.resize (totalNumCubes);\n  }\n\n  glm::vec3 samplePos (unsigned int x, unsigned int y, unsigned int z) const\n  {\n    assert (x < (unsigned int) this->numSamples.x);\n    assert (y < (unsigned int) this->numSamples.y);\n    assert (z < (unsigned int) this->numSamples.z);\n\n    return this->sampleMin +\n           (glm::vec3 (this->resolution) * glm::vec3 (float(x), float(y), float(z)));\n  }\n\n  glm::vec3 samplePos (unsigned int i) const\n  {\n    const std::div_t divZ = std::div (int(i), int(this->numSamples.x * this->numSamples.y));\n    const std::div_t divY = std::div (divZ.rem, int(this->numSamples.x));\n\n    const unsigned int x = (unsigned int) (divY.rem);\n    const unsigned int y = (unsigned int) (divY.quot);\n    const unsigned int z = (unsigned int) (divZ.quot);\n\n    assert (this->sampleIndex (x, y, z) == i);\n\n    return this->samplePos (x, y, z);\n  }\n\n  unsigned int sampleIndex (unsigned int x, unsigned int y, unsigned int z) const\n  {\n    return (z * this->numSamples.x * this->numSamples.y) + (y * this->numSamples.x) + x;\n  }\n\n  unsigned int sampleIndex (unsigned int cubeIndex, unsigned char vertex) const\n  {\n    assert (vertex < 8);\n\n    const std::div_t   divZ = std::div (int(cubeIndex), int(this->numCubes.x * this->numCubes.y));\n    const std::div_t   divY = std::div (divZ.rem, int(this->numCubes.x));\n    const unsigned int x = (unsigned int) (divY.rem);\n    const unsigned int y = (unsigned int) (divY.quot);\n    const unsigned int z = (unsigned int) (divZ.quot);\n\n    assert (this->cubeIndex (x, y, z) == cubeIndex);\n\n    switch (vertex)\n    {\n      case 0:\n        return this->sampleIndex (x, y, z);\n      case 1:\n        return this->sampleIndex (x + 1, y, z);\n      case 2:\n        return this->sampleIndex (x, y + 1, z);\n      case 3:\n        return this->sampleIndex (x + 1, y + 1, z);\n      case 4:\n        return this->sampleIndex (x, y, z + 1);\n      case 5:\n        return this->sampleIndex (x + 1, y, z + 1);\n      case 6:\n        return this->sampleIndex (x, y + 1, z + 1);\n      case 7:\n        return this->sampleIndex (x + 1, y + 1, z + 1);\n      default:\n        DILAY_IMPOSSIBLE\n    }\n  }\n\n  unsigned int cubeIndex (unsigned int x, unsigned int y, unsigned int z) const\n  {\n    return (z * this->numCubes.x * this->numCubes.y) + (y * this->numCubes.x) + x;\n  }\n\n  unsigned int cubeVertexIndex (unsigned int cubeIndex, unsigned char edge) const\n  {\n    return this->cubes[cubeIndex].vertexIndex (edge);\n  }\n\n  void setCubeVertex (unsigned int cubeIndex)\n  {\n    glm::vec3    vertex = glm::vec3 (0.0f);\n    unsigned int numCrossedEdges = 0;\n    Cube&        cube = this->cubes[cubeIndex];\n\n    const unsigned int indices[] = {\n      this->sampleIndex (cubeIndex, 0), this->sampleIndex (cubeIndex, 1),\n      this->sampleIndex (cubeIndex, 2), this->sampleIndex (cubeIndex, 3),\n      this->sampleIndex (cubeIndex, 4), this->sampleIndex (cubeIndex, 5),\n      this->sampleIndex (cubeIndex, 6), this->sampleIndex (cubeIndex, 7)};\n\n    const float samples[] = {this->samples[indices[0]], this->samples[indices[1]],\n                             this->samples[indices[2]], this->samples[indices[3]],\n                             this->samples[indices[4]], this->samples[indices[5]],\n                             this->samples[indices[6]], this->samples[indices[7]]};\n\n    const glm::vec3 positions[] = {this->samplePos (indices[0]), this->samplePos (indices[1]),\n                                   this->samplePos (indices[2]), this->samplePos (indices[3]),\n                                   this->samplePos (indices[4]), this->samplePos (indices[5]),\n                                   this->samplePos (indices[6]), this->samplePos (indices[7])};\n\n    cube.configuration = 0;\n    for (unsigned char edge = 0; edge < 12; edge++)\n    {\n      const unsigned char vertex1 = vertexIndicesByEdge[edge][0];\n      const unsigned char vertex2 = vertexIndicesByEdge[edge][1];\n\n      cube.configuration |= ((samples[vertex1] < 0.0f) << vertex1);\n      cube.configuration |= ((samples[vertex2] < 0.0f) << vertex2);\n\n      if (isIntersecting (samples[vertex1], samples[vertex2]))\n      {\n        const float     factor = samples[vertex1] / (samples[vertex1] - samples[vertex2]);\n        const glm::vec3 delta = positions[vertex2] - positions[vertex1];\n\n        vertex += positions[vertex1] + (delta * factor);\n        numCrossedEdges++;\n      }\n    }\n\n#ifndef NDEBUG\n    for (unsigned char edge = 0; edge < 12; edge++)\n    {\n      const unsigned char vertex1 = vertexIndicesByEdge[edge][0];\n      const unsigned char vertex2 = vertexIndicesByEdge[edge][1];\n\n      if (samples[vertex1] < 0.0f)\n      {\n        assert ((cube.configuration & (1 << vertex1)) != 0);\n      }\n      else\n      {\n        assert ((cube.configuration & (1 << vertex1)) == 0);\n      }\n\n      if (samples[vertex2] < 0.0f)\n      {\n        assert ((cube.configuration & (1 << vertex2)) != 0);\n      }\n      else\n      {\n        assert ((cube.configuration & (1 << vertex2)) == 0);\n      }\n\n      if (isIntersecting (samples[vertex1], samples[vertex2]))\n      {\n        assert (vertexIndicesByConfiguration[cube.configuration][edge] != -1);\n      }\n    }\n#endif\n\n    if (numCrossedEdges > 0)\n    {\n      cube.vertex = vertex / float(numCrossedEdges);\n    }\n    else\n    {\n      assert (numVertices (cube.configuration) == 0);\n    }\n  }\n\n  void setCubeVertices ()\n  {\n    for (unsigned int z = 0; z < this->numCubes.z; z++)\n    {\n      for (unsigned int y = 0; y < this->numCubes.y; y++)\n      {\n        for (unsigned int x = 0; x < this->numCubes.x; x++)\n        {\n          this->setCubeVertex (this->cubeIndex (x, y, z));\n        }\n      }\n    }\n\n#ifndef NDEBUG\n    for (unsigned int z = 0; z < this->numCubes.z; z++)\n    {\n      for (unsigned int y = 0; y < this->numCubes.y; y++)\n      {\n        for (unsigned int x = 0; x < this->numCubes.x; x++)\n        {\n          unsigned char config = this->cubes[this->cubeIndex (x, y, z)].configuration;\n\n          if (x > 0)\n          {\n            unsigned char left = this->cubes[this->cubeIndex (x - 1, y, z)].configuration;\n\n            assert (((config & (1 << 0)) == 0) == ((left & (1 << 1)) == 0));\n            assert (((config & (1 << 2)) == 0) == ((left & (1 << 3)) == 0));\n            assert (((config & (1 << 4)) == 0) == ((left & (1 << 5)) == 0));\n            assert (((config & (1 << 6)) == 0) == ((left & (1 << 7)) == 0));\n          }\n          if (y > 0)\n          {\n            unsigned char below = this->cubes[this->cubeIndex (x, y - 1, z)].configuration;\n\n            assert (((config & (1 << 0)) == 0) == ((below & (1 << 2)) == 0));\n            assert (((config & (1 << 1)) == 0) == ((below & (1 << 3)) == 0));\n            assert (((config & (1 << 4)) == 0) == ((below & (1 << 6)) == 0));\n            assert (((config & (1 << 5)) == 0) == ((below & (1 << 7)) == 0));\n          }\n          if (z > 0)\n          {\n            unsigned char behind = this->cubes[this->cubeIndex (x, y, z - 1)].configuration;\n\n            assert (((config & (1 << 0)) == 0) == ((behind & (1 << 4)) == 0));\n            assert (((config & (1 << 1)) == 0) == ((behind & (1 << 5)) == 0));\n            assert (((config & (1 << 2)) == 0) == ((behind & (1 << 6)) == 0));\n            assert (((config & (1 << 3)) == 0) == ((behind & (1 << 7)) == 0));\n          }\n        }\n      }\n    }\n#endif\n  }\n\n  bool hasAmbiguousNeighbor (const Cube& cube, unsigned int x, unsigned int y, unsigned int z,\n                             unsigned char ambiguousFace, char dim)\n  {\n    assert (cube.nonManifoldConfig ());\n    assert (dim == -3 || dim == -2 || dim == -1 || dim == 1 || dim == 2 || dim == 3);\n    unused (cube);\n\n    Cube& other = this->cubes[this->cubeIndex (dim == -1 ? x - 1 : (dim == 1 ? x + 1 : x),\n                                               dim == -2 ? y - 1 : (dim == 2 ? y + 1 : y),\n                                               dim == -3 ? z - 1 : (dim == 3 ? z + 1 : z))];\n    if (other.nonManifoldConfig ())\n    {\n      const unsigned char otherAmbiguousFace = other.getAmbiguousFaceOfNonManifoldConfig ();\n\n      const bool nx = dim == -1 && ambiguousFace == 2 && otherAmbiguousFace == 3;\n      const bool px = dim == 1 && ambiguousFace == 3 && otherAmbiguousFace == 2;\n      const bool ny = dim == -2 && ambiguousFace == 0 && otherAmbiguousFace == 1;\n      const bool py = dim == 2 && ambiguousFace == 1 && otherAmbiguousFace == 0;\n      const bool nz = dim == -3 && ambiguousFace == 4 && otherAmbiguousFace == 5;\n      const bool pz = dim == 3 && ambiguousFace == 5 && otherAmbiguousFace == 4;\n\n      return nx || px || ny || py || nz || pz;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  void resolveNonManifold (unsigned int x, unsigned int y, unsigned int z)\n  {\n    Cube& cube = this->cubes[this->cubeIndex (x, y, z)];\n\n    if (cube.nonManifoldConfig ())\n    {\n      const unsigned char ambiguousFace = cube.getAmbiguousFaceOfNonManifoldConfig ();\n\n      const bool nx = x > 0 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, -1);\n      const bool px =\n        x < this->numCubes.x - 1 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, 1);\n      const bool ny = y > 0 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, -2);\n      const bool py =\n        y < this->numCubes.y - 1 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, 2);\n      const bool nz = z > 0 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, -3);\n      const bool pz =\n        z < this->numCubes.z - 1 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, 3);\n\n      cube.nonManifold = nx || px || ny || py || nz || pz;\n    }\n    else\n    {\n      cube.nonManifold = false;\n    }\n  }\n\n  void resolveNonManifolds ()\n  {\n    for (unsigned int z = 0; z < this->numCubes.z; z++)\n    {\n      for (unsigned int y = 0; y < this->numCubes.y; y++)\n      {\n        for (unsigned int x = 0; x < this->numCubes.x; x++)\n        {\n          this->resolveNonManifold (x, y, z);\n        }\n      }\n    }\n  }\n\n  void addCubeVerticesToMesh (Cube& cube, DynamicMesh& mesh)\n  {\n    cube.numVertexIndicesInMesh =\n      cube.collapseNonManifoldConfig () ? 1 : numVertices (cube.configuration);\n\n    for (unsigned char i = 0; i < cube.numVertexIndicesInMesh; i++)\n    {\n      cube.vertexIndicesInMesh[i] = mesh.addVertex (cube.vertex, glm::vec3 (0.0f));\n    }\n#ifndef NDEBUG\n    for (unsigned char i = cube.numVertexIndicesInMesh; i < cube.vertexIndicesInMesh.size (); i++)\n    {\n      cube.vertexIndicesInMesh[i] = Util::invalidIndex ();\n    }\n#endif\n  }\n\n  void addQuadToMesh (DynamicMesh& mesh, unsigned int i, unsigned int iu, unsigned int iv,\n                      unsigned int iuv)\n  {\n    if (glm::distance2 (mesh.vertex (i), mesh.vertex (iuv)) <=\n        glm::distance2 (mesh.vertex (iu), mesh.vertex (iv)))\n    {\n      mesh.addFace (i, iu, iuv);\n      mesh.addFace (i, iuv, iv);\n    }\n    else\n    {\n      mesh.addFace (iu, iuv, iv);\n      mesh.addFace (iu, iv, i);\n    }\n  }\n\n  void makeFaces (DynamicMesh& mesh, unsigned char edge, unsigned int x, unsigned int y,\n                  unsigned int z)\n  {\n    assert (edge == 0 || edge == 1 || edge == 2);\n\n    const float s1 = this->samples[this->sampleIndex (x, y, z)];\n    const float s2 = this->samples[this->sampleIndex (edge == 0 ? x + 1 : x, edge == 1 ? y + 1 : y,\n                                                      edge == 2 ? z + 1 : z)];\n\n    if (isIntersecting (s1, s2))\n    {\n      unsigned int i, iu, iv, iuv;\n\n      if (edge == 0)\n      {\n        i = this->cubeVertexIndex (this->cubeIndex (x, y, z), 0);\n        iu = this->cubeVertexIndex (this->cubeIndex (x, y - 1, z), 3);\n        iuv = this->cubeVertexIndex (this->cubeIndex (x, y - 1, z - 1), 9);\n        iv = this->cubeVertexIndex (this->cubeIndex (x, y, z - 1), 6);\n      }\n      else if (edge == 1)\n      {\n        i = this->cubeVertexIndex (this->cubeIndex (x, y, z), 1);\n        iu = this->cubeVertexIndex (this->cubeIndex (x, y, z - 1), 7);\n        iuv = this->cubeVertexIndex (this->cubeIndex (x - 1, y, z - 1), 10);\n        iv = this->cubeVertexIndex (this->cubeIndex (x - 1, y, z), 4);\n      }\n      else if (edge == 2)\n      {\n        i = this->cubeVertexIndex (this->cubeIndex (x, y, z), 2);\n        iu = this->cubeVertexIndex (this->cubeIndex (x - 1, y, z), 5);\n        iuv = this->cubeVertexIndex (this->cubeIndex (x - 1, y - 1, z), 11);\n        iv = this->cubeVertexIndex (this->cubeIndex (x, y - 1, z), 8);\n      }\n      else\n      {\n        DILAY_IMPOSSIBLE\n      }\n\n      if (s1 >= 0.0f)\n      {\n        std::swap (iu, iv);\n      }\n\n      this->addQuadToMesh (mesh, i, iu, iv, iuv);\n    }\n  }\n\n  void makeFaces (DynamicMesh& mesh, unsigned int x, unsigned int y, unsigned int z)\n  {\n    if (y > 0 && z > 0)\n    {\n      this->makeFaces (mesh, 0, x, y, z);\n    }\n    if (x > 0 && z > 0)\n    {\n      this->makeFaces (mesh, 1, x, y, z);\n    }\n    if (x > 0 && y > 0)\n    {\n      this->makeFaces (mesh, 2, x, y, z);\n    }\n  }\n\n  void makeMesh (DynamicMesh& mesh)\n  {\n    this->setCubeVertices ();\n    this->resolveNonManifolds ();\n\n    mesh.reset ();\n    for (Cube& cube : this->cubes)\n    {\n      this->addCubeVerticesToMesh (cube, mesh);\n    }\n\n    for (unsigned int z = 0; z < this->numCubes.z; z++)\n    {\n      for (unsigned int y = 0; y < this->numCubes.y; y++)\n      {\n        for (unsigned int x = 0; x < this->numCubes.x; x++)\n        {\n          this->makeFaces (mesh, x, y, z);\n        }\n      }\n    }\n    mesh.setAllNormals ();\n\n#ifndef NDEBUG\n    std::vector<unsigned int> vertexIndexMap, faceIndexMap;\n    assert (mesh.numFaces () == 0 || mesh.pruneAndCheckConsistency (&vertexIndexMap, nullptr));\n\n    for (Cube& c : this->cubes)\n    {\n      if (vertexIndexMap.empty () == false)\n      {\n        for (unsigned char i = 0; i < c.numVertexIndicesInMesh; i++)\n        {\n          c.vertexIndicesInMesh[i] = vertexIndexMap[c.vertexIndicesInMesh[i]];\n          assert (c.vertexIndicesInMesh[i] != Util::invalidIndex ());\n        }\n      }\n    }\n#endif\n    mesh.bufferData ();\n  }\n};\n\nDELEGATE2_BIG4_COPY (IsosurfaceExtractionGrid, const PrimAABox&, float)\nGETTER_CONST (float, IsosurfaceExtractionGrid, resolution)\nGETTER_CONST (const glm::uvec3&, IsosurfaceExtractionGrid, numSamples)\nGETTER_CONST (const glm::uvec3&, IsosurfaceExtractionGrid, numCubes)\nGETTER (std::vector<float>&, IsosurfaceExtractionGrid, samples)\nDELEGATE3_CONST (glm::vec3, IsosurfaceExtractionGrid, samplePos, unsigned int, unsigned int,\n                 unsigned int)\nDELEGATE1_CONST (glm::vec3, IsosurfaceExtractionGrid, samplePos, unsigned int)\nDELEGATE3_CONST (unsigned int, IsosurfaceExtractionGrid, sampleIndex, unsigned int, unsigned int,\n                 unsigned int)\nDELEGATE2_CONST (unsigned int, IsosurfaceExtractionGrid, sampleIndex, unsigned int, unsigned char)\nDELEGATE3_CONST (unsigned int, IsosurfaceExtractionGrid, cubeIndex, unsigned int, unsigned int,\n                 unsigned int)\nDELEGATE1 (void, IsosurfaceExtractionGrid, makeMesh, DynamicMesh&)\n"
  },
  {
    "path": "lib/src/isosurface-extraction/grid.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_ISOSURFACE_EXTRACTION_GRID\n#define DILAY_ISOSURFACE_EXTRACTION_GRID\n\n#include <glm/glm.hpp>\n#include <vector>\n#include \"macro.hpp\"\n\nclass DynamicMesh;\nclass PrimAABox;\n\nclass IsosurfaceExtractionGrid\n{\npublic:\n  static const unsigned char vertexIndicesByEdge[12][2];\n\n  DECLARE_BIG4_EXPLICIT_COPY (IsosurfaceExtractionGrid, const PrimAABox&, float)\n\n  float               resolution () const;\n  const glm::uvec3&   numSamples () const;\n  const glm::uvec3&   numCubes () const;\n  std::vector<float>& samples ();\n\n  glm::vec3    samplePos (unsigned int, unsigned int, unsigned int) const;\n  glm::vec3    samplePos (unsigned int) const;\n  unsigned int sampleIndex (unsigned int, unsigned int, unsigned int) const;\n  unsigned int sampleIndex (unsigned int, unsigned char) const;\n  unsigned int cubeIndex (unsigned int, unsigned int, unsigned int) const;\n\n  void makeMesh (DynamicMesh&);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/isosurface-extraction.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include <glm/gtx/norm.hpp>\n#include <thread>\n#include <vector>\n#include \"distance.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"intersection.hpp\"\n#include \"isosurface-extraction.hpp\"\n#include \"isosurface-extraction/grid.hpp\"\n#include \"mesh.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  typedef IsosurfaceExtraction::DistanceCallback     DistanceCallback;\n  typedef IsosurfaceExtraction::IntersectionCallback IntersectionCallback;\n\n  static const float markInside = -0.5f;\n  static const float markOutside = 0.5f;\n  static const float markInsideToSample = -0.6f;\n  static const float markOutsideToSample = 0.6f;\n\n  struct Parameters\n  {\n    const DistanceCallback&     getDistance;\n    const IntersectionCallback* getIntersection;\n    IsosurfaceExtractionGrid    grid;\n\n    Parameters (const DistanceCallback& d, const IntersectionCallback* i, const PrimAABox& b,\n                float r)\n      : getDistance (d)\n      , getIntersection (i)\n      , grid (b, r)\n    {\n    }\n  };\n\n  void sampleDistancesThread (Parameters& params, unsigned int numThreads, unsigned int threadId)\n  {\n    std::vector<float>& samples = params.grid.samples ();\n\n    for (unsigned int z = 0; z < params.grid.numSamples ().z; z++)\n    {\n      for (unsigned int y = 0; y < params.grid.numSamples ().y; y++)\n      {\n        for (unsigned int x = 0; x < params.grid.numSamples ().x; x++)\n        {\n          const unsigned int index = params.grid.sampleIndex (x, y, z);\n\n          if (index % numThreads == threadId)\n          {\n            const glm::vec3 pos = params.grid.samplePos (x, y, z);\n\n            if (params.getIntersection)\n            {\n              if (samples[index] == markInsideToSample)\n              {\n                samples[index] = -params.getDistance (pos);\n              }\n              else if (samples[index] == markOutsideToSample)\n              {\n                samples[index] = params.getDistance (pos);\n              }\n              else\n              {\n                continue;\n              }\n            }\n            else\n            {\n              assert (samples[index] == Util::maxFloat ());\n              samples[index] = params.getDistance (pos);\n            }\n            assert (Util::isNaN (samples[index]) == false);\n            assert (samples[index] != Util::maxFloat ());\n            assert ((x > 0 && x < params.grid.numSamples ().x - 1) || samples[index] > 0.0f);\n            assert ((y > 0 && y < params.grid.numSamples ().y - 1) || samples[index] > 0.0f);\n            assert ((z > 0 && z < params.grid.numSamples ().z - 1) || samples[index] > 0.0f);\n          }\n        }\n      }\n    }\n  }\n\n  void sampleDistances (Parameters& params)\n  {\n    const unsigned int       numThreads = std::thread::hardware_concurrency ();\n    std::vector<std::thread> threads;\n\n    for (unsigned int i = 0; i < numThreads; i++)\n    {\n      threads.emplace_back (sampleDistancesThread, std::ref (params), numThreads, i);\n    }\n    for (unsigned int i = 0; i < numThreads; i++)\n    {\n      threads.at (i).join ();\n    }\n  }\n\n  void sampleIntersectionsThread (Parameters& params, unsigned int numThreads,\n                                  unsigned int threadId)\n  {\n    assert (params.getIntersection);\n\n    std::vector<float>& samples = params.grid.samples ();\n\n    for (unsigned int y = 0; y < params.grid.numSamples ().y; y++)\n    {\n      for (unsigned int x = 0; x < params.grid.numSamples ().x; x++)\n      {\n        if (params.grid.sampleIndex (x, y, 0) % numThreads == threadId)\n        {\n          const glm::vec3 dir (0.0f, 0.0f, 1.0f);\n          bool            inside = false;\n          unsigned int    z = 0;\n          Intersection    intersection;\n          PrimRay         ray (params.grid.samplePos (x, y, 0.0f) - (dir * Util::epsilon ()), dir);\n\n          while (true)\n          {\n            intersection.reset ();\n            IsosurfaceExtraction::Intersection i = (*params.getIntersection) (ray, intersection);\n\n            if (i == IsosurfaceExtraction::Intersection::None)\n            {\n              break;\n            }\n            else\n            {\n              const float d2 = intersection.distance () * intersection.distance ();\n\n              while (glm::distance2 (params.grid.samplePos (x, y, z), ray.origin ()) < d2)\n              {\n                const unsigned int index = params.grid.sampleIndex (x, y, z);\n\n                assert (samples[index] == Util::maxFloat ());\n                samples[index] = inside ? markInside : markOutside;\n\n                z++;\n              }\n              ray.origin (intersection.position () + (dir * Util::epsilon ()));\n\n              if (i == IsosurfaceExtraction::Intersection::Sample)\n              {\n                inside = not inside;\n              }\n            }\n          }\n\n          assert (z < params.grid.numSamples ().z - 1);\n          for (; z < params.grid.numSamples ().z; z++)\n          {\n            const unsigned int index = params.grid.sampleIndex (x, y, z);\n\n            assert (samples[index] == Util::maxFloat ());\n            samples[index] = markOutside;\n          }\n        }\n      }\n    }\n  }\n\n  void sampleIntersections (Parameters& params)\n  {\n    const unsigned int       numThreads = std::thread::hardware_concurrency ();\n    std::vector<std::thread> threads;\n\n    for (unsigned int i = 0; i < numThreads; i++)\n    {\n      threads.emplace_back (sampleIntersectionsThread, std::ref (params), numThreads, i);\n    }\n    for (unsigned int i = 0; i < numThreads; i++)\n    {\n      threads.at (i).join ();\n    }\n  }\n\n  bool isIntersecting (float s1, float s2)\n  {\n    return (s1 < 0.0f && s2 >= 0.0f) || (s1 >= 0.0f && s2 < 0.0f);\n  }\n\n  void markSamplePositions (Parameters& params)\n  {\n    std::vector<float>& samples = params.grid.samples ();\n\n    for (unsigned int z = 0; z < params.grid.numCubes ().z; z++)\n    {\n      for (unsigned int y = 0; y < params.grid.numCubes ().y; y++)\n      {\n        for (unsigned int x = 0; x < params.grid.numCubes ().x; x++)\n        {\n          const unsigned int cubeIndex = params.grid.cubeIndex (x, y, z);\n\n          const unsigned int cubeSampleIndices[] = {\n            params.grid.sampleIndex (cubeIndex, 0), params.grid.sampleIndex (cubeIndex, 1),\n            params.grid.sampleIndex (cubeIndex, 2), params.grid.sampleIndex (cubeIndex, 3),\n            params.grid.sampleIndex (cubeIndex, 4), params.grid.sampleIndex (cubeIndex, 5),\n            params.grid.sampleIndex (cubeIndex, 6), params.grid.sampleIndex (cubeIndex, 7)};\n\n          const float cubeSamples[] = {\n            samples[cubeSampleIndices[0]], samples[cubeSampleIndices[1]],\n            samples[cubeSampleIndices[2]], samples[cubeSampleIndices[3]],\n            samples[cubeSampleIndices[4]], samples[cubeSampleIndices[5]],\n            samples[cubeSampleIndices[6]], samples[cubeSampleIndices[7]]};\n\n          for (unsigned int edge = 0; edge < 12; edge++)\n          {\n            const unsigned char vertex1 = IsosurfaceExtractionGrid::vertexIndicesByEdge[edge][0];\n            const unsigned char vertex2 = IsosurfaceExtractionGrid::vertexIndicesByEdge[edge][1];\n\n            if (isIntersecting (cubeSamples[vertex1], cubeSamples[vertex2]))\n            {\n              for (unsigned int i = 0; i < 8; i++)\n              {\n                if (cubeSamples[i] == markInside)\n                {\n                  samples[cubeSampleIndices[i]] = markInsideToSample;\n                }\n                else if (cubeSamples[i] == markOutside)\n                {\n                  samples[cubeSampleIndices[i]] = markOutsideToSample;\n                }\n              }\n              break;\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid IsosurfaceExtraction::extract (const DistanceCallback& getDistance, const PrimAABox& bounds,\n                                    float resolution, DynamicMesh& mesh)\n{\n  Parameters                params (getDistance, nullptr, bounds, resolution);\n  IsosurfaceExtractionGrid& grid = params.grid;\n\n  if (grid.numSamples ().x > 0 && grid.numSamples ().y > 0 && grid.numSamples ().z > 0)\n  {\n    sampleDistances (params);\n    grid.makeMesh (mesh);\n  }\n}\n\nvoid IsosurfaceExtraction::extract (const DistanceCallback&     getDistance,\n                                    const IntersectionCallback& getIntersection,\n                                    const PrimAABox& bounds, float resolution, DynamicMesh& mesh)\n{\n  Parameters                params (getDistance, &getIntersection, bounds, resolution);\n  IsosurfaceExtractionGrid& grid = params.grid;\n\n  if (grid.numSamples ().x > 0 && grid.numSamples ().y > 0 && grid.numSamples ().z > 0)\n  {\n    sampleIntersections (params);\n    markSamplePositions (params);\n    sampleDistances (params);\n    grid.makeMesh (mesh);\n  }\n}\n"
  },
  {
    "path": "lib/src/isosurface-extraction.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_ISOSURFACE_EXTRACTION\n#define DILAY_ISOSURFACE_EXTRACTION\n\n#include <functional>\n#include <glm/fwd.hpp>\n\nclass DynamicMesh;\nclass Intersection;\nclass PrimAABox;\nclass PrimRay;\n\nnamespace IsosurfaceExtraction\n{\n  enum class Intersection\n  {\n    None,\n    Sample,\n    Continue\n  };\n\n  typedef std::function<float(const glm::vec3&)>                        DistanceCallback;\n  typedef std::function<Intersection (const PrimRay&, ::Intersection&)> IntersectionCallback;\n\n  void extract (const DistanceCallback&, const IntersectionCallback&, const PrimAABox&, float,\n                DynamicMesh&);\n  void extract (const DistanceCallback&, const PrimAABox&, float, DynamicMesh&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/kvstore.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QDomNode>\n#include <QFile>\n#include <QTextStream>\n#include <glm/glm.hpp>\n#include <unordered_map>\n#include \"color.hpp\"\n#include \"kvstore.hpp\"\n#include \"util.hpp\"\n#include \"variant.hpp\"\n#include \"xml-conversion.hpp\"\n\nstruct KVStore::Impl\n{\n  typedef Variant<float, int, bool, glm::vec3, glm::ivec2, Color> Value;\n  typedef std::unordered_map<std::string, Value>                  Map;\n\n  const std::string root;\n  Map               map;\n\n  Impl (const std::string& r)\n    : root (r)\n  {\n    assert (this->root.find ('/') == std::string::npos);\n  }\n\n  std::string path (const std::string& suffix) const\n  {\n    assert (suffix.back () != '/');\n\n    if (suffix.front () == '/')\n    {\n      assert (suffix.find (\"/\" + this->root + \"/\") == 0);\n      return suffix;\n    }\n    else\n    {\n      return \"/\" + this->root + \"/\" + suffix;\n    }\n  }\n\n  template <class T> const T& get (const std::string& p) const\n  {\n    Map::const_iterator value = this->map.find (this->path (p));\n\n    if (value == this->map.end ())\n    {\n      throw (std::runtime_error (\"Can not find path '\" + this->path (p) + \"' in kv-store\"));\n    }\n    else\n    {\n      return value->second.get<T> ();\n    }\n  }\n\n  template <class T> const T& get (const std::string& p, const T& defaultV) const\n  {\n    Map::const_iterator value = this->map.find (this->path (p));\n\n    if (value == this->map.end ())\n    {\n      return defaultV;\n    }\n    else\n    {\n      return value->second.get<T> ();\n    }\n  }\n\n  template <class T> void set (const std::string& p, const T& t)\n  {\n    this->remove (p);\n\n    Value value;\n    value.set<T> (t);\n    this->map.emplace (this->path (p), value);\n  }\n\n  void fromFile (const std::string& fileName)\n  {\n    Util::withCLocale<void> ([this, &fileName]() {\n      QFile file (fileName.c_str ());\n\n      if (file.open (QIODevice::ReadOnly | QIODevice::Text) == false)\n      {\n        throw (std::runtime_error (\"Can not open kv-store file '\" + fileName + \"'\"));\n      }\n      QDomDocument doc (fileName.c_str ());\n      QString      errorMsg;\n      int          errorLine = -1;\n      int          errorColumn = -1;\n      if (doc.setContent (&file, &errorMsg, &errorLine, &errorColumn) == false)\n      {\n        file.close ();\n        throw (std::runtime_error (\n          \"Error while loading kv-store file '\" + fileName + \"': \" + errorMsg.toStdString () +\n          \" (\" + std::to_string (errorLine) + \",\" + std::to_string (errorColumn) + \")\"));\n      }\n      file.close ();\n      try\n      {\n        this->loadNode (\"\", doc);\n      }\n      catch (std::runtime_error& e)\n      {\n        throw (std::runtime_error (\"Error while parsing kv-store file '\" + fileName +\n                                   \"': \" + e.what ()));\n      }\n    });\n  }\n\n  void loadNode (const QString& prefix, QDomNode& node)\n  {\n    QDomNode child = node.firstChild ();\n\n    while (child.isNull () == false)\n    {\n      if (child.isElement ())\n      {\n        QDomElement element = child.toElement ();\n        QDomAttr    attribute = element.attributeNode (\"type\");\n        Value       value;\n\n        if (attribute.isNull ())\n        {\n          this->loadNode (prefix + \"/\" + element.tagName (), child);\n        }\n        else if (attribute.value () == \"float\")\n        {\n          this->loadElement<float> (prefix, element);\n        }\n        else if (attribute.value () == \"integer\")\n        {\n          this->loadElement<int> (prefix, element);\n        }\n        else if (attribute.value () == \"boolean\")\n        {\n          this->loadElement<bool> (prefix, element);\n        }\n        else if (attribute.value () == \"vector3f\")\n        {\n          this->loadElement<glm::vec3> (prefix, element);\n        }\n        else if (attribute.value () == \"vector2i\")\n        {\n          this->loadElement<glm::ivec2> (prefix, element);\n        }\n        else if (attribute.value () == \"color\")\n        {\n          this->loadElement<Color> (prefix, element);\n        }\n        else\n        {\n          throw (std::runtime_error (\"invalid type '\" + attribute.value ().toStdString () + \"' \" +\n                                     \"(\" + std::to_string (child.lineNumber ()) + \",\" +\n                                     std::to_string (child.columnNumber ()) + \")\"));\n        }\n      }\n      else\n      {\n        throw (std::runtime_error (\"invalid node (\" + std::to_string (child.lineNumber ()) + \",\" +\n                                   std::to_string (child.columnNumber ()) + \")\"));\n      }\n      child = child.nextSibling ();\n    }\n  }\n\n  template <typename T> bool loadElement (const QString& prefix, QDomElement& element)\n  {\n    T                 t;\n    const bool        ok = XmlConversion::fromDomElement (element, t);\n    const std::string suffix = element.tagName ().toStdString ();\n    const std::string key = prefix.toStdString () + \"/\" + suffix;\n\n    if (ok)\n    {\n      this->set<T> (key, t);\n    }\n    else\n    {\n      throw (std::runtime_error (\"can not parse value of key '\" + key + \"' \" + \"(\" +\n                                 std::to_string (element.lineNumber ()) + \",\" +\n                                 std::to_string (element.columnNumber ()) + \")\"));\n    }\n    return ok;\n  }\n\n  void toFile (const std::string& fileName) const\n  {\n    Util::withCLocale<void> ([this, &fileName]() {\n      QDomDocument doc;\n\n      for (auto& c : this->map)\n      {\n        const std::string& key = c.first;\n        const Value&       value = c.second;\n        QStringList        path = QString (key.c_str ()).split (\"/\", QString::SkipEmptyParts);\n\n        this->appendAsDomChild (doc, doc, path, value);\n      }\n      if (doc.isNull () == false)\n      {\n        QFile file (fileName.c_str ());\n        if (file.open (QIODevice::WriteOnly | QIODevice::Text))\n        {\n          QTextStream stream (&file);\n          doc.save (stream, 2);\n          file.close ();\n        }\n        else\n        {\n          throw (std::runtime_error (\"Can not save kv-store file '\" + fileName + \"'\"));\n        }\n      }\n    });\n  }\n\n  void appendAsDomChild (QDomDocument& doc, QDomNode& parent, QStringList& path,\n                         const Value& value) const\n  {\n    if (path.empty ())\n    {\n      assert (parent.isElement ());\n      QDomElement elem = parent.toElement ();\n      if (value.is<float> ())\n      {\n        XmlConversion::toDomElement (doc, elem, value.get<float> ());\n      }\n      else if (value.is<int> ())\n      {\n        XmlConversion::toDomElement (doc, elem, value.get<int> ());\n      }\n      else if (value.is<bool> ())\n      {\n        XmlConversion::toDomElement (doc, elem, value.get<bool> ());\n      }\n      else if (value.is<glm::vec3> ())\n      {\n        XmlConversion::toDomElement (doc, elem, value.get<glm::vec3> ());\n      }\n      else if (value.is<glm::ivec2> ())\n      {\n        XmlConversion::toDomElement (doc, elem, value.get<glm::ivec2> ());\n      }\n      else if (value.is<Color> ())\n      {\n        XmlConversion::toDomElement (doc, elem, value.get<Color> ());\n      }\n      else\n        DILAY_IMPOSSIBLE\n    }\n    else\n    {\n      const QString& head = path.first ();\n      QDomElement    child = parent.firstChildElement (head);\n      if (child.isNull ())\n      {\n        child = doc.createElement (head);\n        if (parent.isNull ())\n        {\n          doc.appendChild (child);\n        }\n        else\n        {\n          parent.appendChild (child);\n        }\n      }\n      assert (child.hasAttribute (\"type\") == false);\n\n      path.removeFirst ();\n      this->appendAsDomChild (doc, child, path, value);\n    }\n  }\n\n  void remove (const std::string& p) { this->map.erase (this->path (p)); }\n\n  void reset () { this->map.clear (); }\n};\n\nDELEGATE1_BIG2 (KVStore, const std::string&)\nDELEGATE1 (void, KVStore, fromFile, const std::string&);\nDELEGATE1_CONST (void, KVStore, toFile, const std::string&);\nDELEGATE1 (void, KVStore, remove, const std::string&);\nDELEGATE (void, KVStore, reset);\n\ntemplate <class T> const T& KVStore::get (const std::string& path) const\n{\n  return this->impl->get<T> (path);\n}\n\ntemplate <class T> const T& KVStore::get (const std::string& path, const T& defaultV) const\n{\n  return this->impl->get<T> (path, defaultV);\n}\n\ntemplate <class T> void KVStore::set (const std::string& path, const T& value)\n{\n  return this->impl->set<T> (path, value);\n}\n\ntemplate const float&      KVStore::get<float> (const std::string&) const;\ntemplate const float&      KVStore::get<float> (const std::string&, const float&) const;\ntemplate void              KVStore::set<float> (const std::string&, const float&);\ntemplate const int&        KVStore::get<int> (const std::string&) const;\ntemplate const int&        KVStore::get<int> (const std::string&, const int&) const;\ntemplate void              KVStore::set<int> (const std::string&, const int&);\ntemplate const bool&       KVStore::get<bool> (const std::string&) const;\ntemplate const bool&       KVStore::get<bool> (const std::string&, const bool&) const;\ntemplate void              KVStore::set<bool> (const std::string&, const bool&);\ntemplate const Color&      KVStore::get<Color> (const std::string&) const;\ntemplate const Color&      KVStore::get<Color> (const std::string&, const Color&) const;\ntemplate void              KVStore::set<Color> (const std::string&, const Color&);\ntemplate const glm::vec3&  KVStore::get<glm::vec3> (const std::string&) const;\ntemplate const glm::vec3&  KVStore::get<glm::vec3> (const std::string&, const glm::vec3&) const;\ntemplate void              KVStore::set<glm::vec3> (const std::string&, const glm::vec3&);\ntemplate const glm::ivec2& KVStore::get<glm::ivec2> (const std::string&) const;\ntemplate const glm::ivec2& KVStore::get<glm::ivec2> (const std::string&, const glm::ivec2&) const;\ntemplate void              KVStore::set<glm::ivec2> (const std::string&, const glm::ivec2&);\n"
  },
  {
    "path": "lib/src/kvstore.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_KVSTORE\n#define DILAY_KVSTORE\n\n#include <string>\n#include \"macro.hpp\"\n\nclass KVStore\n{\npublic:\n  DECLARE_BIG2 (KVStore, const std::string&)\n\n  template <class T> const T& get (const std::string&) const;\n  template <class T> const T& get (const std::string&, const T&) const;\n  template <class T> void     set (const std::string&, const T&);\n\n  void fromFile (const std::string&);\n  void toFile (const std::string&) const;\n  void remove (const std::string&);\n  void reset ();\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/log.cpp",
    "content": "#include <cstdarg>\n#include <cstdio>\n#include <ctime>\n#include <string>\n#include \"log.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  static std::FILE*  fileHandle = nullptr;\n  static std::string filePath;\n  static std::time_t startTime;\n\n  const char* levelToString (Log::Level level)\n  {\n    switch (level)\n    {\n      case Log::Level::Info:\n        return \"INFO\";\n      case Log::Level::Warning:\n        return \"WARNING\";\n      case Log::Level::Panic:\n        return \"PANIC\";\n    }\n    return nullptr;\n  }\n\n  void shutdown ()\n  {\n    if (fileHandle)\n    {\n      std::fclose (fileHandle);\n      std::remove (filePath.c_str ());\n    }\n  }\n}\n\nnamespace Log\n{\n  void initialize (const std::string& path)\n  {\n    assert (fileHandle == nullptr);\n\n    fileHandle = std::fopen (path.c_str (), \"w\");\n\n    if (fileHandle)\n    {\n      filePath = path;\n      startTime = std::time (nullptr);\n      std::atexit (shutdown);\n    }\n    else\n    {\n      DILAY_WARN (\"Could not open log file %s\", path.c_str ());\n    }\n  }\n\n  void log (Log::Level level, const char* file, unsigned int line, const char* format, ...)\n  {\n    const unsigned int secDiff = (unsigned int) std::difftime (std::time (nullptr), startTime);\n\n    va_list args1;\n    va_list args2;\n\n    va_start (args1, format);\n    va_copy (args2, args1);\n\n    std::vector<char> buffer (1 + std::vsnprintf (nullptr, 0, format, args1));\n    va_end (args1);\n\n    std::vsnprintf (buffer.data (), buffer.size (), format, args2);\n    va_end (args2);\n\n    if (fileHandle)\n    {\n      std::fprintf (fileHandle, \"%09u [%s] %s (%u): %s\\n\", secDiff, levelToString (level), file,\n                    line, buffer.data ());\n      std::fflush (fileHandle);\n    }\n\n    if (level != Log::Level::Info)\n    {\n      std::fprintf (stderr, \"%09u [%s] %s (%u): %s\\n\", secDiff, levelToString (level), file, line,\n                    buffer.data ());\n    }\n  }\n}\n"
  },
  {
    "path": "lib/src/log.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_LOG\n#define DILAY_LOG\n\n#include <string>\n\nnamespace Log\n{\n  enum class Level\n  {\n    Info,\n    Warning,\n    Panic\n  };\n\n  void initialize (const std::string&);\n  void log (Level, const char*, unsigned int, const char*, ...);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/macro.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_MACRO\n#define DILAY_MACRO\n\n#include <cassert>\n#include <memory>\n\n// delegators\n\n#define SET_SELF this->impl->self = this;\n\n#define DELEGATE_COPY_CONSTRUCTOR(from) \\\n  from::from (const from& a1)           \\\n    : impl (new Impl (*a1.impl))        \\\n  {                                     \\\n  }\n\n#define DELEGATE_COPY_CONSTRUCTOR_SELF(from) \\\n  from::from (const from& a1)                \\\n    : impl (new Impl (*a1.impl))             \\\n  {                                          \\\n    SET_SELF                                 \\\n  }\n\n#define DELEGATE_COPY_CONSTRUCTOR_BASE(from, base) \\\n  from::from (const from& a1)                      \\\n    : base (a1)                                    \\\n    , impl (new Impl (*a1.impl))                   \\\n  {                                                \\\n    SET_SELF                                       \\\n  }\n\n#define DELEGATE_MOVE_CONSTRUCTOR(from)      \\\n  from::from (from&& a1)                     \\\n    : impl (new Impl (std::move (*a1.impl))) \\\n  {                                          \\\n  }\n\n#define DELEGATE_MOVE_CONSTRUCTOR_SELF(from) \\\n  from::from (from&& a1)                     \\\n    : impl (new Impl (std::move (*a1.impl))) \\\n  {                                          \\\n    SET_SELF                                 \\\n  }\n\n#define DELEGATE_MOVE_CONSTRUCTOR_BASE(from, base) \\\n  from::from (from&& a1)                           \\\n    : base (std::forward<base> (a1))               \\\n    , impl (new Impl (std::move (*a1.impl)))       \\\n  {                                                \\\n    SET_SELF                                       \\\n  }\n\n#define DELEGATE_ASSIGNMENT_OP(from)               \\\n  const from& from::operator= (const from& source) \\\n  {                                                \\\n    this->impl->operator= (*source.impl);          \\\n    return *this;                                  \\\n  }\n\n#define DELEGATE_MOVE_ASSIGNMENT_OP(from)             \\\n  const from& from::operator= (from&& source)         \\\n  {                                                   \\\n    this->impl->operator= (std::move (*source.impl)); \\\n    return *this;                                     \\\n  }\n\n#define DELEGATE_MOVE_ASSIGNMENT_OP_SELF(from)        \\\n  const from& from::operator= (from&& source)         \\\n  {                                                   \\\n    this->impl->operator= (std::move (*source.impl)); \\\n    SET_SELF                                          \\\n    return *this;                                     \\\n  }\n\n#define DELEGATE_DESTRUCTOR(from) \\\n  from::~from () {}\n\n#define DELEGATE_BIG3_WITHOUT_CONSTRUCTOR(from) \\\n  DELEGATE_DESTRUCTOR (from)                    \\\n  DELEGATE_MOVE_CONSTRUCTOR (from)\n\n#define DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF(from) \\\n  DELEGATE_DESTRUCTOR (from)                         \\\n  DELEGATE_MOVE_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR(from) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from)           \\\n  DELEGATE_COPY_CONSTRUCTOR (from)\n\n#define DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF(from) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from)           \\\n  DELEGATE_COPY_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE_BIG6_WITHOUT_CONSTRUCTOR(from) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from)      \\\n  DELEGATE_MOVE_ASSIGNMENT_OP (from)            \\\n  DELEGATE_COPY_CONSTRUCTOR (from)              \\\n  DELEGATE_ASSIGNMENT_OP (from)\n\n#define DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF(from) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from)      \\\n  DELEGATE_MOVE_ASSIGNMENT_OP_SELF (from)            \\\n  DELEGATE_COPY_CONSTRUCTOR_SELF (from)              \\\n  DELEGATE_ASSIGNMENT_OP (from)\n\n#define DELEGATE_CONSTRUCTOR(from) \\\n  from::from ()                    \\\n    : impl (new Impl ())           \\\n  {                                \\\n  }\n\n#define DELEGATE1_CONSTRUCTOR(from, t1)       \\\n  from::from (t1 a1)                          \\\n    : impl (new Impl (std::forward<t1> (a1))) \\\n  {                                           \\\n  }\n\n#define DELEGATE2_CONSTRUCTOR(from, t1, t2)                          \\\n  from::from (t1 a1, t2 a2)                                          \\\n    : impl (new Impl (std::forward<t1> (a1), std::forward<t2> (a2))) \\\n  {                                                                  \\\n  }\n\n#define DELEGATE3_CONSTRUCTOR(from, t1, t2, t3)                                             \\\n  from::from (t1 a1, t2 a2, t3 a3)                                                          \\\n    : impl (new Impl (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3))) \\\n  {                                                                                         \\\n  }\n\n#define DELEGATE4_CONSTRUCTOR(from, t1, t2, t3, t4)                                        \\\n  from::from (t1 a1, t2 a2, t3 a3, t4 a4)                                                  \\\n    : impl (new Impl (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), \\\n                      std::forward<t4> (a4)))                                              \\\n  {                                                                                        \\\n  }\n\n#define DELEGATE5_CONSTRUCTOR(from, t1, t2, t3, t4, t5)                                    \\\n  from::from (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5)                                           \\\n    : impl (new Impl (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), \\\n                      std::forward<t4> (a4), std::forward<t5> (a5)))                       \\\n  {                                                                                        \\\n  }\n\n#define DELEGATE_CONSTRUCTOR_SELF(from) \\\n  from::from ()                         \\\n    : impl (new Impl (this))            \\\n  {                                     \\\n  }\n\n#define DELEGATE1_CONSTRUCTOR_SELF(from, t1) \\\n  from::from (t1 a1)                         \\\n    : impl (new Impl (this, a1))             \\\n  {                                          \\\n  }\n\n#define DELEGATE2_CONSTRUCTOR_SELF(from, t1, t2) \\\n  from::from (t1 a1, t2 a2)                      \\\n    : impl (new Impl (this, a1, a2))             \\\n  {                                              \\\n  }\n\n#define DELEGATE3_CONSTRUCTOR_SELF(from, t1, t2, t3) \\\n  from::from (t1 a1, t2 a2, t3 a3)                   \\\n    : impl (new Impl (this, a1, a2, a3))             \\\n  {                                                  \\\n  }\n\n#define DELEGATE4_CONSTRUCTOR_SELF(from, t1, t2, t3, t4) \\\n  from::from (t1 a1, t2 a2, t3 a3, t4 a4)                \\\n    : impl (new Impl (this, a1, a2, a3, a4))             \\\n  {                                                      \\\n  }\n\n#define DELEGATE5_CONSTRUCTOR_SELF(from, t1, t2, t3, t4, t5) \\\n  from::from (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5)             \\\n    : impl (new Impl (this, a1, a2, a3, a4, a5))             \\\n  {                                                          \\\n  }\n\n#define DELEGATE_CONSTRUCTOR_BASE(from, params, fromArgs, base, baseArgs) \\\n  from::from params : base baseArgs, impl (new Impl fromArgs) {}\n\n#define DELEGATE_IMPL(r, from, method, ifaceParams, implArgs) \\\n  r from::method ifaceParams { return this->impl->method implArgs; }\n\n#define DELEGATE(r, from, method) DELEGATE_IMPL (r, from, method, (), ())\n\n#define DELEGATE1(r, from, method, t1) \\\n  DELEGATE_IMPL (r, from, method, (t1 a1), (std::forward<t1> (a1)))\n\n#define DELEGATE2(r, from, method, t1, t2) \\\n  DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2), (std::forward<t1> (a1), std::forward<t2> (a2)))\n\n#define DELEGATE3(r, from, method, t1, t2, t3)           \\\n  DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2, t3 a3), \\\n                 (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3)))\n\n#define DELEGATE4(r, from, method, t1, t2, t3, t4) \\\n  DELEGATE_IMPL (                                  \\\n    r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4), \\\n    (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), std::forward<t4> (a4)))\n\n#define DELEGATE5(r, from, method, t1, t2, t3, t4, t5)                                 \\\n  DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5),                 \\\n                 (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), \\\n                  std::forward<t4> (a4), std::forward<t5> (a5)))\n\n#define DELEGATE_CONST(r, from, method) DELEGATE_IMPL (r, from, method, () const, ())\n\n#define DELEGATE1_CONST(r, from, method, t1) \\\n  DELEGATE_IMPL (r, from, method, (t1 a1) const, (std::forward<t1> (a1)))\n\n#define DELEGATE2_CONST(r, from, method, t1, t2)        \\\n  DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2) const, \\\n                 (std::forward<t1> (a1), std::forward<t2> (a2)))\n\n#define DELEGATE3_CONST(r, from, method, t1, t2, t3)           \\\n  DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2, t3 a3) const, \\\n                 (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3)))\n\n#define DELEGATE4_CONST(r, from, method, t1, t2, t3, t4) \\\n  DELEGATE_IMPL (                                        \\\n    r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4) const, \\\n    (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), std::forward<t4> (a4)))\n\n#define DELEGATE5_CONST(r, from, method, t1, t2, t3, t4, t5)                           \\\n  DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) const,           \\\n                 (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), \\\n                  std::forward<t4> (a4), std::forward<t5> (a5)))\n\n#define DELEGATE_BASE_STATIC(r, from, method, ifaceParams, implArgs) \\\n  r from::method ifaceParams { return Impl::method implArgs; }\n\n#define DELEGATE_STATIC(r, from, method) DELEGATE_BASE_STATIC (r, from, method, (), ())\n\n#define DELEGATE1_STATIC(r, from, method, t1) DELEGATE_BASE_STATIC (r, from, method, (t1 a1), (a1))\n\n#define DELEGATE2_STATIC(r, from, method, t1, t2) \\\n  DELEGATE_BASE_STATIC (r, from, method, (t1 a1, t2 a2), (a1, a2))\n\n#define DELEGATE3_STATIC(r, from, method, t1, t2, t3) \\\n  DELEGATE_BASE_STATIC (r, from, method, (t1 a1, t2 a2, t3 a3), (a1, a2, a3))\n\n#define DELEGATE4_STATIC(r, from, method, t1, t2, t3, t4) \\\n  DELEGATE_BASE_STATIC (r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4), (a1, a2, a3, a4))\n\n#define DELEGATE5_STATIC(r, from, method, t1, t2, t3, t4, t5) \\\n  DELEGATE_BASE_STATIC (r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5), (a1, a2, a3, a4, a5))\n\n#define DELEGATE_IMPL_MEMBER(r, from, method, member, ifaceParams, implArgs) \\\n  r from::method ifaceParams { return this->impl->member.method implArgs; }\n\n#define DELEGATE_MEMBER(r, from, method, member) \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (), ())\n\n#define DELEGATE1_MEMBER(r, from, method, member, t1) \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1), (std::forward<t1> (a1)))\n\n#define DELEGATE2_MEMBER(r, from, method, member, t1, t2)        \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2), \\\n                        (std::forward<t1> (a1), std::forward<t2> (a2)))\n\n#define DELEGATE3_MEMBER(r, from, method, member, t1, t2, t3)           \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2, t3 a3), \\\n                        (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3)))\n\n#define DELEGATE4_MEMBER(r, from, method, member, t1, t2, t3, t4) \\\n  DELEGATE_IMPL_MEMBER (                                          \\\n    r, from, method, member, (t1 a1, t2 a2, t3 a3, t4 a4),        \\\n    (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), std::forward<t4> (a4)))\n\n#define DELEGATE5_MEMBER(r, from, method, member, t1, t2, t3, t4, t5)                         \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5),         \\\n                        (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), \\\n                         std::forward<t4> (a4), std::forward<t5> (a5)))\n\n#define DELEGATE_MEMBER_CONST(r, from, method, member) \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, () const, ())\n\n#define DELEGATE1_MEMBER_CONST(r, from, method, member, t1) \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1) const, (std::forward<t1> (a1)))\n\n#define DELEGATE2_MEMBER_CONST(r, from, method, member, t1, t2)        \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2) const, \\\n                        (std::forward<t1> (a1), std::forward<t2> (a2)))\n\n#define DELEGATE3_MEMBER_CONST(r, from, method, member, t1, t2, t3)           \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2, t3 a3) const, \\\n                        (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3)))\n\n#define DELEGATE4_MEMBER_CONST(r, from, method, member, t1, t2, t3, t4) \\\n  DELEGATE_IMPL_MEMBER (                                                \\\n    r, from, method, member, (t1 a1, t2 a2, t3 a3, t4 a4) const,        \\\n    (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), std::forward<t4> (a4)))\n\n#define DELEGATE5_MEMBER_CONST(r, from, method, member, t1, t2, t3, t4, t5)                   \\\n  DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) const,   \\\n                        (std::forward<t1> (a1), std::forward<t2> (a2), std::forward<t3> (a3), \\\n                         std::forward<t4> (a4), std::forward<t5> (a5)))\n\n// big 2 delegators\n\n#define DELEGATE_BIG2(from)   \\\n  DELEGATE_CONSTRUCTOR (from) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE1_BIG2(from, t1)   \\\n  DELEGATE1_CONSTRUCTOR (from, t1) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE2_BIG2(from, t1, t2)   \\\n  DELEGATE2_CONSTRUCTOR (from, t1, t2) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE3_BIG2(from, t1, t2, t3)   \\\n  DELEGATE3_CONSTRUCTOR (from, t1, t2, t3) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE4_BIG2(from, t1, t2, t3, t4)   \\\n  DELEGATE4_CONSTRUCTOR (from, t1, t2, t3, t4) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE5_BIG2(from, t1, t2, t3, t4, t5)   \\\n  DELEGATE5_CONSTRUCTOR (from, t1, t2, t3, t4, t5) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE_BIG2_SELF(from)   \\\n  DELEGATE_CONSTRUCTOR_SELF (from) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE1_BIG2_SELF(from, t1)   \\\n  DELEGATE1_CONSTRUCTOR_SELF (from, t1) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE2_BIG2_SELF(from, t1, t2)   \\\n  DELEGATE2_CONSTRUCTOR_SELF (from, t1, t2) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE3_BIG2_SELF(from, t1, t2, t3)   \\\n  DELEGATE3_CONSTRUCTOR_SELF (from, t1, t2, t3) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE4_BIG2_SELF(from, t1, t2, t3, t4)   \\\n  DELEGATE4_CONSTRUCTOR_SELF (from, t1, t2, t3, t4) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE5_BIG2_SELF(from, t1, t2, t3, t4, t5)   \\\n  DELEGATE5_CONSTRUCTOR_SELF (from, t1, t2, t3, t4, t5) \\\n  DELEGATE_DESTRUCTOR (from)\n\n#define DELEGATE_BIG2_BASE(from, params, fromArgs, base, baseArgs)   \\\n  DELEGATE_CONSTRUCTOR_BASE (from, params, fromArgs, base, baseArgs) \\\n  DELEGATE_DESTRUCTOR (from)\n\n// big 3 delegators\n\n#define DELEGATE_BIG3(from)   \\\n  DELEGATE_CONSTRUCTOR (from) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE1_BIG3(from, t1)   \\\n  DELEGATE1_CONSTRUCTOR (from, t1) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE2_BIG3(from, t1, t2)   \\\n  DELEGATE2_CONSTRUCTOR (from, t1, t2) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE3_BIG3(from, t1, t2, t3)   \\\n  DELEGATE3_CONSTRUCTOR (from, t1, t2, t3) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE4_BIG3(from, t1, t2, t3, t4)   \\\n  DELEGATE4_CONSTRUCTOR (from, t1, t2, t3, t4) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE5_BIG3(from, t1, t2, t3, t4, t5)   \\\n  DELEGATE5_CONSTRUCTOR (from, t1, t2, t3, t4, t5) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE_BIG3_SELF(from)   \\\n  DELEGATE_CONSTRUCTOR_SELF (from) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE1_BIG3_SELF(from, t1)   \\\n  DELEGATE1_CONSTRUCTOR_SELF (from, t1) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE2_BIG3_SELF(from, t1, t2)   \\\n  DELEGATE2_CONSTRUCTOR_SELF (from, t1, t2) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE3_BIG3_SELF(from, t1, t2, t3)   \\\n  DELEGATE3_CONSTRUCTOR_SELF (from, t1, t2, t3) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE4_BIG3_SELF(from, t1, t2, t3, t4)   \\\n  DELEGATE4_CONSTRUCTOR_SELF (from, t1, t2, t3, t4) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE5_BIG3_SELF(from, t1, t2, t3, t4, t5)   \\\n  DELEGATE5_CONSTRUCTOR_SELF (from, t1, t2, t3, t4, t5) \\\n  DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE_BIG3_BASE(from, params, fromArgs, base, baseArgs)   \\\n  DELEGATE_CONSTRUCTOR_BASE (from, params, fromArgs, base, baseArgs) \\\n  DELEGATE_DESTRUCTOR (from)                                         \\\n  DELEGATE_MOVE_CONSTRUCTOR_BASE (from, base)\n\n// big 4 delegators\n\n#define DELEGATE_BIG4_COPY(from) \\\n  DELEGATE_CONSTRUCTOR (from)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE1_BIG4_COPY(from, t1) \\\n  DELEGATE1_CONSTRUCTOR (from, t1)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE2_BIG4_COPY(from, t1, t2) \\\n  DELEGATE2_CONSTRUCTOR (from, t1, t2)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE3_BIG4_COPY(from, t1, t2, t3) \\\n  DELEGATE3_CONSTRUCTOR (from, t1, t2, t3)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE4_BIG4_COPY(from, t1, t2, t3, t4) \\\n  DELEGATE4_CONSTRUCTOR (from, t1, t2, t3, t4)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE5_BIG4_COPY(from, t1, t2, t3, t4, t5) \\\n  DELEGATE5_CONSTRUCTOR (from, t1, t2, t3, t4, t5)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE_BIG4_COPY_SELF(from) \\\n  DELEGATE_CONSTRUCTOR_SELF (from)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE1_BIG4_COPY_SELF(from, t1) \\\n  DELEGATE1_CONSTRUCTOR_SELF (from, t1)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE2_BIG4_COPY_SELF(from, t1, t2) \\\n  DELEGATE2_CONSTRUCTOR_SELF (from, t1, t2)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE3_BIG4_COPY_SELF(from, t1, t2, t3) \\\n  DELEGATE3_CONSTRUCTOR_SELF (from, t1, t2, t3)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE4_BIG4_COPY_SELF(from, t1, t2, t3, t4) \\\n  DELEGATE4_CONSTRUCTOR_SELF (from, t1, t2, t3, t4)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE5_BIG4_COPY_SELF(from, t1, t2, t3, t4, t5) \\\n  DELEGATE5_CONSTRUCTOR_SELF (from, t1, t2, t3, t4, t5)    \\\n  DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE_BIG4_COPY_BASE(from, params, fromArgs, base, baseArgs) \\\n  DELEGATE_CONSTRUCTOR_BASE (from, params, fromArgs, base, baseArgs)    \\\n  DELEGATE_DESTRUCTOR (from)                                            \\\n  DELEGATE_MOVE_CONSTRUCTOR_BASE (from, base)                           \\\n  DELEGATE_COPY_CONSTRUCTOR_BASE (from, base)\n\n// big 6 delegators\n\n#define DELEGATE_BIG6(from)   \\\n  DELEGATE_CONSTRUCTOR (from) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE1_BIG6(from, t1)   \\\n  DELEGATE1_CONSTRUCTOR (from, t1) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE2_BIG6(from, t1, t2)   \\\n  DELEGATE2_CONSTRUCTOR (from, t1, t2) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE3_BIG6(from, t1, t2, t3)   \\\n  DELEGATE3_CONSTRUCTOR (from, t1, t2, t3) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE4_BIG6(from, t1, t2, t3, t4)   \\\n  DELEGATE4_CONSTRUCTOR (from, t1, t2, t3, t4) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE5_BIG6(from, t1, t2, t3, t4, t5)   \\\n  DELEGATE5_CONSTRUCTOR (from, t1, t2, t3, t4, t5) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from)\n\n#define DELEGATE_BIG6_SELF(from)   \\\n  DELEGATE_CONSTRUCTOR_SELF (from) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE1_BIG6_SELF(from, t1)   \\\n  DELEGATE1_CONSTRUCTOR_SELF (from, t1) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE2_BIG6_SELF(from, t1, t2)   \\\n  DELEGATE2_CONSTRUCTOR_SELF (from, t1, t2) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE3_BIG6_SELF(from, t1, t2, t3)   \\\n  DELEGATE3_CONSTRUCTOR_SELF (from, t1, t2, t3) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE4_BIG6_SELF(from, t1, t2, t3, t4)   \\\n  DELEGATE4_CONSTRUCTOR_SELF (from, t1, t2, t3, t4) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE5_BIG6_SELF(from, t1, t2, t3, t4, t5)   \\\n  DELEGATE5_CONSTRUCTOR_SELF (from, t1, t2, t3, t4, t5) \\\n  DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from)\n\n#define DELEGATE_BIG6_BASE(from, params, fromArgs, base, baseArgs)   \\\n  DELEGATE_CONSTRUCTOR_BASE (from, params, fromArgs, base, baseArgs) \\\n  DELEGATE_DESTRUCTOR (from)                                         \\\n  DELEGATE_COPY_CONSTRUCTOR_BASE (from, base)                        \\\n  DELEGATE_MOVE_CONSTRUCTOR_BASE (from, base)                        \\\n  DELEGATE_ASSIGNMENT_OP (from)                                      \\\n  DELEGATE_MOVE_ASSIGNMENT_OP_SELF (from)\n\n// getters/setters\n\n#define GETTER_CONST(r, from, member) \\\n  r from::member () const { return this->impl->member; }\n\n#define GETTER(r, from, member) \\\n  r from::member () { return this->impl->member; }\n\n#define SETTER(t, from, member) \\\n  void from::member (t a) { this->impl->member = a; }\n\n#define _MEMBER_GETTER_SETTER(type, name, pass_type)  \\\npublic:                                               \\\n  pass_type name () const { return this->_##name; }   \\\n  void      name (pass_type v) { this->_##name = v; } \\\n                                                      \\\nprivate:                                              \\\n  type _##name;\n\n#define MEMBER_GETTER_SETTER(type, name) _MEMBER_GETTER_SETTER (type, name, type)\n\n#define MEMBER_REF_GETTER_SETTER(type, name) _MEMBER_GETTER_SETTER (type, name, const type&)\n\n#define _MEMBER_GETTER_EXPLICIT_SETTER(type, name, pass_type) \\\npublic:                                                       \\\n  pass_type name () const { return this->_##name; }           \\\n  void      name (pass_type v);                               \\\n                                                              \\\nprivate:                                                      \\\n  type _##name;\n\n#define MEMBER_GETTER_EXPLICIT_SETTER(type, name) _MEMBER_GETTER_EXPLICIT_SETTER (type, name, type)\n\n#define MEMBER_REF_GETTER_EXPLICIT_SETTER(type, name) \\\n  _MEMBER_GETTER_EXPLICIT_SETTER (type, name, const type&)\n\n#define _MEMBER_GETTER(type, name, pass_type)       \\\npublic:                                             \\\n  pass_type name () const { return this->_##name; } \\\n                                                    \\\nprivate:                                            \\\n  type _##name;\n\n#define MEMBER_GETTER(type, name) _MEMBER_GETTER (type, name, type)\n\n#define MEMBER_REF_GETTER(type, name) _MEMBER_GETTER (type, name, const type&)\n\n// safe references\n\n#define SAFE_REF(r, method)   \\\n  r& method##Ref ()           \\\n  {                           \\\n    r* ptr = this->method (); \\\n    assert (ptr);             \\\n    return *ptr;              \\\n  }\n\n#define SAFE_REF1(r, method, t1) \\\n  r& method##Ref (t1 a1)         \\\n  {                              \\\n    r* ptr = this->method (a1);  \\\n    assert (ptr);                \\\n    return *ptr;                 \\\n  }\n\n#define SAFE_REF2(r, method, t1, t2) \\\n  r& method##Ref (t1 a1, t2 a2)      \\\n  {                                  \\\n    r* ptr = this->method (a1, a2);  \\\n    assert (ptr);                    \\\n    return *ptr;                     \\\n  }\n\n#define SAFE_REF3(r, method, t1, t2, t3) \\\n  r& method##Ref (t1 a1, t2 a2, t3 a3)   \\\n  {                                      \\\n    r* ptr = this->method (a1, a2, a3);  \\\n    assert (ptr);                        \\\n    return *ptr;                         \\\n  }\n\n#define SAFE_REF4(r, method, t1, t2, t3, t4)  \\\n  r& method##Ref (t1 a1, t2 a2, t3 a3, t4 a4) \\\n  {                                           \\\n    r* ptr = this->method (a1, a2, a3, a4);   \\\n    assert (ptr);                             \\\n    return *ptr;                              \\\n  }\n\n#define SAFE_REF5(r, method, t1, t2, t3, t4, t5)     \\\n  r& method##Ref (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) \\\n  {                                                  \\\n    r* ptr = this->method (a1, a2, a3, a4, a5);      \\\n    assert (ptr);                                    \\\n    return *ptr;                                     \\\n  }\n\n#define SAFE_REF_CONST(r, method) \\\n  r& method##Ref () const         \\\n  {                               \\\n    r* ptr = this->method ();     \\\n    assert (ptr);                 \\\n    return *ptr;                  \\\n  }\n\n#define SAFE_REF1_CONST(r, method, t1) \\\n  r& method##Ref (t1 a1) const         \\\n  {                                    \\\n    r* ptr = this->method (a1);        \\\n    assert (ptr);                      \\\n    return *ptr;                       \\\n  }\n\n#define SAFE_REF2_CONST(r, method, t1, t2) \\\n  r& method##Ref (t1 a1, t2 a2) const      \\\n  {                                        \\\n    r* ptr = this->method (a1, a2);        \\\n    assert (ptr);                          \\\n    return *ptr;                           \\\n  }\n\n#define SAFE_REF3_CONST(r, method, t1, t2, t3) \\\n  r& method##Ref (t1 a1, t2 a2, t3 a3) const   \\\n  {                                            \\\n    r* ptr = this->method (a1, a2, a3);        \\\n    assert (ptr);                              \\\n    return *ptr;                               \\\n  }\n\n#define SAFE_REF4_CONST(r, method, t1, t2, t3, t4)  \\\n  r& method##Ref (t1 a1, t2 a2, t3 a3, t4 a4) const \\\n  {                                                 \\\n    r* ptr = this->method (a1, a2, a3, a4);         \\\n    assert (ptr);                                   \\\n    return *ptr;                                    \\\n  }\n\n#define SAFE_REF5_CONST(r, method, t1, t2, t3, t4, t5)     \\\n  r& method##Ref (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) const \\\n  {                                                        \\\n    r* ptr = this->method (a1, a2, a3, a4, a5);            \\\n    assert (ptr);                                          \\\n    return *ptr;                                           \\\n  }\n\n// big 2 declarations\n\n#define DECLARE_BIG2(t, ...)              \\\n  t (__VA_ARGS__);                        \\\n  t (const t&) = delete;                  \\\n  t (t&&) = delete;                       \\\n  const t& operator= (const t&) = delete; \\\n  const t& operator= (t&&) = delete;      \\\n  ~t ();\n\n#define DECLARE_BIG2_VIRTUAL(t, ...)      \\\n  t (__VA_ARGS__);                        \\\n  t (const t&) = delete;                  \\\n  t (t&&) = delete;                       \\\n  const t& operator= (const t&) = delete; \\\n  const t& operator= (t&&) = delete;      \\\n  virtual ~t ();\n\n// big 3 declarations\n\n#define DECLARE_BIG3(t, ...)              \\\n  t (__VA_ARGS__);                        \\\n  t (const t&) = delete;                  \\\n  t (t&&);                                \\\n  const t& operator= (const t&) = delete; \\\n  const t& operator= (t&&) = delete;      \\\n  ~t ();\n\n#define DECLARE_BIG3_VIRTUAL(t, ...)      \\\n  t (__VA_ARGS__);                        \\\n  t (const t&) = delete;                  \\\n  t (t&&);                                \\\n  const t& operator= (const t&) = delete; \\\n  const t& operator= (t&&) = delete;      \\\n  virtual ~t ();\n\n// big 4 declarations\n\n#define DECLARE_BIG4_COPY(t, ...)         \\\n  t (__VA_ARGS__);                        \\\n  t (const t&);                           \\\n  t (t&&);                                \\\n  const t& operator= (const t&) = delete; \\\n  const t& operator= (t&&) = delete;      \\\n  ~t ();\n\n#define DECLARE_BIG4_COPY_VIRTUAL(t, ...) \\\n  t (__VA_ARGS__);                        \\\n  t (const t&);                           \\\n  t (t&&);                                \\\n  const t& operator= (const t&) = delete; \\\n  const t& operator= (t&&) = delete;      \\\n  virtual ~t ();\n\n#define DECLARE_BIG4_EXPLICIT_COPY(t, ...) \\\n  t (__VA_ARGS__);                         \\\n  explicit t (const t&);                   \\\n  t (t&&);                                 \\\n  const t& operator= (const t&) = delete;  \\\n  const t& operator= (t&&) = delete;       \\\n  ~t ();\n\n#define DECLARE_BIG4_EXPLICIT_COPY_VIRTUAL(t, ...) \\\n  t (__VA_ARGS__);                                 \\\n  explicit t (const t&);                           \\\n  t (t&&);                                         \\\n  const t& operator= (const t&) = delete;          \\\n  const t& operator= (t&&) = delete;               \\\n  virtual ~t ();\n\n// big 6 declarations\n\n#define DECLARE_BIG6(t, ...)     \\\n  t (__VA_ARGS__);               \\\n  t (const t&);                  \\\n  t (t&&);                       \\\n  const t& operator= (const t&); \\\n  const t& operator= (t&&);      \\\n  ~t ();\n\n#define DECLARE_BIG6_VIRTUAL(t, ...) \\\n  t (__VA_ARGS__);                   \\\n  t (const t&);                      \\\n  t (t&&);                           \\\n  const t& operator= (const t&);     \\\n  const t& operator= (t&&);          \\\n  virtual ~t ();\n\n// miscellaneous\n\n#define DELETE_COPYMOVEASSIGN(t)          \\\n  t (const t&) = delete;                  \\\n  t (t&&) = delete;                       \\\n  const t& operator= (const t&) = delete; \\\n  const t& operator= (t&&) = delete;\n\n#define DEFAULT_COPYMOVEASSIGN(t)          \\\n  t (const t&) = default;                  \\\n  t (t&&) = default;                       \\\n  const t& operator= (const t&) = default; \\\n  const t& operator= (t&&) = default;\n\n#define IMPLEMENTATION \\\n  struct Impl;         \\\n  std::unique_ptr<Impl> impl;\n\n#define ESC_PARENS(...) __VA_ARGS__\n\n#endif\n"
  },
  {
    "path": "lib/src/maybe.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_MAYBE\n#define DILAY_MAYBE\n\n#include <cassert>\n#include <memory>\n\ntemplate <typename T> class Maybe\n{\n  static_assert (std::is_pointer<T>::value == false, \"Maybe does not support pointers\");\n  static_assert (std::is_reference<T>::value == false, \"Maybe does not support references\");\n\npublic:\n  Maybe () = default;\n\n  explicit Maybe (T* v)\n    : value (v)\n  {\n  }\n\n  Maybe (const T& v)\n    : value (new T (v))\n  {\n  }\n\n  Maybe (const Maybe<T>& o)\n    : value (o.hasValue () ? new T (*o) : nullptr)\n  {\n  }\n\n  Maybe (Maybe<T>&&) = default;\n\n  Maybe (std::unique_ptr<T>&& v)\n    : value (std::move (v))\n  {\n  }\n\n  template <typename... Args> static Maybe<T> make (Args&&... args)\n  {\n    return Maybe (std::make_unique<T> (std::forward<Args> (args)...));\n  }\n\n  ~Maybe () = default;\n\n  Maybe<T>& operator= (T* v)\n  {\n    if (this->get () != v)\n    {\n      this->value.reset (v);\n    }\n    return *this;\n  }\n\n  Maybe<T>& operator= (const T& v)\n  {\n    if (this->get () != &v)\n    {\n      this->value.reset (new T (v));\n    }\n    return *this;\n  }\n\n  Maybe<T>& operator= (const Maybe<T>& o)\n  {\n    if (this != &o)\n    {\n      this->value.reset (o.hasValue () ? new T (*o) : nullptr);\n    }\n    return *this;\n  }\n\n  Maybe<T>& operator= (Maybe<T>&&) = default;\n\n  explicit operator bool () const { return this->hasValue (); }\n\n  bool operator== (bool v) const { return this->operator bool () == v; }\n\n  T& operator* ()\n  {\n    assert (this->hasValue ());\n    return *this->value;\n  }\n\n  const T& operator* () const\n  {\n    assert (this->hasValue ());\n    return *this->value;\n  }\n\n  T* operator-> () { return this->get (); }\n\n  const T* operator-> () const { return this->get (); }\n\n  T* get () { return this->value.get (); }\n\n  const T* get () const { return this->value.get (); }\n\n  T* release () { return this->value.release (); }\n\n  bool hasValue () const { return bool(this->value); }\n\n  void reset (T* newValue = nullptr) { this->value.reset (newValue); }\n\n  void swap (Maybe<T>& o) { this->value.swap (o.value); }\n\nprivate:\n  std::unique_ptr<T> value;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/mesh-util.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <algorithm>\n#include <functional>\n#include <glm/glm.hpp>\n#include <glm/gtc/constants.hpp>\n#include <unordered_map>\n#include <vector>\n#include \"hash.hpp\"\n#include \"intersection.hpp\"\n#include \"mesh-util.hpp\"\n#include \"mesh.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  struct VertexCache\n  {\n    typedef std::function<unsigned int(unsigned int, unsigned int)> MakeNewVertex;\n\n    std::unordered_map<ui_pair, unsigned int> cache;\n\n    unsigned int lookup (unsigned int i1, unsigned int i2, const MakeNewVertex& f)\n    {\n      const ui_pair key = std::make_pair (glm::min (i1, i2), glm::max (i1, i2));\n\n      const auto it = this->cache.find (key);\n      if (it == this->cache.end ())\n      {\n        const unsigned int n = f (i1, i2);\n        this->cache.emplace (key, n);\n        return n;\n      }\n      else\n      {\n        return it->second;\n      }\n    }\n  };\n\n  struct EdgeMap\n  {\n    EdgeMap (unsigned int numVertices) { this->elements.resize (numVertices - 1); }\n\n    unsigned int* find (unsigned int i1, unsigned int i2)\n    {\n      const unsigned int minI = glm::min (i1, i2);\n      const unsigned int maxI = glm::max (i1, i2);\n\n      if (minI < this->elements.size ())\n      {\n        return this->findInSequence (elements[minI], maxI);\n      }\n      else\n      {\n        return nullptr;\n      }\n    }\n\n    void add (unsigned int i1, unsigned int i2, const unsigned int& element)\n    {\n      const unsigned int minI = glm::min (i1, i2);\n      const unsigned int maxI = glm::max (i1, i2);\n\n      assert (minI < this->elements.size ());\n      assert (this->findInSequence (this->elements[minI], maxI) == nullptr);\n\n      if (this->elements[minI].empty ())\n      {\n        this->elements[minI].reserve (6);\n      }\n      this->elements[minI].push_back (std::make_pair (maxI, element));\n    }\n\n    void increase (unsigned int i1, unsigned int i2)\n    {\n      const unsigned int minI = glm::min (i1, i2);\n      const unsigned int maxI = glm::max (i1, i2);\n\n      assert (minI < this->elements.size ());\n\n      unsigned int* value = this->findInSequence (this->elements[minI], maxI);\n      if (value)\n      {\n        (*value)++;\n      }\n      else\n      {\n        if (this->elements[minI].empty ())\n        {\n          this->elements[minI].reserve (6);\n        }\n        this->elements[minI].push_back (std::make_pair (maxI, 1));\n      }\n    }\n\n    unsigned int* findInSequence (std::vector<std::pair<unsigned int, unsigned int>>& sequence,\n                                  unsigned int                                        i)\n    {\n      for (auto& p : sequence)\n      {\n        if (p.first == i)\n        {\n          return &p.second;\n        }\n      }\n      return nullptr;\n    }\n\n    std::vector<std::vector<std::pair<unsigned int, unsigned int>>> elements;\n  };\n\n  Mesh& withDefaultNormals (Mesh& mesh)\n  {\n    for (unsigned int i = 0; i < mesh.numVertices (); i++)\n    {\n      mesh.normal (i, glm::normalize (mesh.vertex (i)));\n    }\n    return mesh;\n  }\n}\n\nvoid MeshUtil::addFace (Mesh& mesh, unsigned int i1, unsigned int i2, unsigned int i3)\n{\n  mesh.addIndex (i1);\n  mesh.addIndex (i2);\n  mesh.addIndex (i3);\n}\n\nvoid MeshUtil::addFace (Mesh& mesh, unsigned int i1, unsigned int i2, unsigned int i3,\n                        unsigned int i4)\n{\n  mesh.addIndex (i1);\n  mesh.addIndex (i2);\n  mesh.addIndex (i3);\n  mesh.addIndex (i4);\n  mesh.addIndex (i1);\n  mesh.addIndex (i3);\n}\n\nMesh MeshUtil::cube (unsigned int numSubdivisions)\n{\n  Mesh        mesh;\n  VertexCache vertexCache;\n\n  const auto addStartVertex = [&mesh](const glm::vec3& v) -> unsigned int {\n    return mesh.addVertex (v, glm::normalize (v));\n  };\n\n  const auto addRefinedVertex = [&mesh](unsigned int i1, unsigned int i2) -> unsigned int {\n    return mesh.addVertex (Util::midpoint (mesh.vertex (i1), mesh.vertex (i2)));\n  };\n\n  std::function<void(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int)>\n    subdivide = [&mesh, &subdivide, &addRefinedVertex,\n                 &vertexCache](unsigned int s, unsigned int i1, unsigned int i2, unsigned int i3,\n                               unsigned int i4) -> void {\n    if (s == 0)\n    {\n      MeshUtil::addFace (mesh, i1, i2, i3);\n      MeshUtil::addFace (mesh, i1, i3, i4);\n    }\n    else\n    {\n      const glm::vec3    v1 = mesh.vertex (i1);\n      const glm::vec3    v2 = mesh.vertex (i2);\n      const glm::vec3    v3 = mesh.vertex (i3);\n      const glm::vec3    v4 = mesh.vertex (i4);\n      const unsigned int iC = mesh.addVertex ((v1 + v2 + v3 + v4) / 4.0f);\n      const unsigned int i12 = vertexCache.lookup (i1, i2, addRefinedVertex);\n      const unsigned int i23 = vertexCache.lookup (i2, i3, addRefinedVertex);\n      const unsigned int i34 = vertexCache.lookup (i3, i4, addRefinedVertex);\n      const unsigned int i41 = vertexCache.lookup (i4, i1, addRefinedVertex);\n\n      subdivide (s - 1, i1, i12, iC, i41);\n      subdivide (s - 1, i2, i23, iC, i12);\n      subdivide (s - 1, i3, i34, iC, i23);\n      subdivide (s - 1, i4, i41, iC, i34);\n    }\n  };\n\n  addStartVertex (glm::vec3 (-0.5f, -0.5f, -0.5f));\n  addStartVertex (glm::vec3 (-0.5f, -0.5f, +0.5f));\n  addStartVertex (glm::vec3 (-0.5f, +0.5f, -0.5f));\n  addStartVertex (glm::vec3 (-0.5f, +0.5f, +0.5f));\n  addStartVertex (glm::vec3 (+0.5f, -0.5f, -0.5f));\n  addStartVertex (glm::vec3 (+0.5f, -0.5f, +0.5f));\n  addStartVertex (glm::vec3 (+0.5f, +0.5f, -0.5f));\n  addStartVertex (glm::vec3 (+0.5f, +0.5f, +0.5f));\n\n  subdivide (numSubdivisions, 0, 1, 3, 2);\n  subdivide (numSubdivisions, 1, 5, 7, 3);\n  subdivide (numSubdivisions, 5, 4, 6, 7);\n  subdivide (numSubdivisions, 4, 0, 2, 6);\n  subdivide (numSubdivisions, 3, 7, 6, 2);\n  subdivide (numSubdivisions, 0, 4, 5, 1);\n\n  for (unsigned int i = 0; i < mesh.numVertices (); i++)\n  {\n    const glm::vec3& vertex = mesh.vertex (i);\n    glm::vec3        normal = glm::vec3 (0.0f);\n\n    if (Util::almostEqual (vertex.x, 0.5f))\n    {\n      normal.x = 1.0f;\n    }\n    else if (Util::almostEqual (vertex.x, -0.5f))\n    {\n      normal.x = -1.0f;\n    }\n\n    if (Util::almostEqual (vertex.y, 0.5f))\n    {\n      normal.y = 1.0f;\n    }\n    else if (Util::almostEqual (vertex.y, -0.5f))\n    {\n      normal.y = -1.0f;\n    }\n\n    if (Util::almostEqual (vertex.z, 0.5f))\n    {\n      normal.z = 1.0f;\n    }\n    else if (Util::almostEqual (vertex.z, -0.5f))\n    {\n      normal.z = -1.0f;\n    }\n    mesh.normal (i, glm::normalize (normal));\n  }\n  return mesh;\n}\n\nMesh MeshUtil::sphere (unsigned int rings, unsigned int sectors)\n{\n  assert (rings > 1 && sectors > 2);\n  Mesh mesh;\n\n  const float radius = 1.0f;\n  const float ringStep = glm::pi<float> () / float(rings);\n  const float sectorStep = 2.0f * glm::pi<float> () / float(sectors);\n  float       phi = ringStep;\n  float       theta = 0.0f;\n\n  // inner rings vertices\n  for (unsigned int r = 0; r < rings - 1; r++)\n  {\n    for (unsigned int s = 0; s < sectors; s++)\n    {\n      const float x = radius * sin (theta) * sin (phi);\n      const float y = radius * cos (phi);\n      const float z = radius * cos (theta) * sin (phi);\n\n      mesh.addVertex (glm::vec3 (x, y, z));\n\n      theta += sectorStep;\n    }\n    phi += ringStep;\n  }\n\n  // caps vertices\n  const unsigned int topCapIndex = mesh.addVertex (glm::vec3 (0.0f, radius, 0.0f));\n  const unsigned int botCapIndex = mesh.addVertex (glm::vec3 (0.0f, -radius, 0.0f));\n\n  // inner rings indices\n  for (unsigned int r = 0; r < rings - 2; r++)\n  {\n    for (unsigned int s = 0; s < sectors; s++)\n    {\n      MeshUtil::addFace (mesh, (sectors * r) + s, (sectors * (r + 1)) + s,\n                         (sectors * (r + 1)) + ((s + 1) % sectors),\n                         (sectors * r) + ((s + 1) % sectors));\n    }\n  }\n\n  // caps indices\n  for (unsigned int s = 0; s < sectors; s++)\n  {\n    MeshUtil::addFace (mesh, topCapIndex, s, (s + 1) % sectors);\n\n    MeshUtil::addFace (mesh, botCapIndex, (sectors * (rings - 2)) + ((s + 1) % sectors),\n                       (sectors * (rings - 2)) + s);\n  }\n  return withDefaultNormals (mesh);\n}\n\nMesh MeshUtil::icosphere (unsigned int numSubdivisions)\n{\n  Mesh        mesh;\n  VertexCache vertexCache;\n\n  const auto addStartVertex = [&mesh](const glm::vec3& v) -> unsigned int {\n    return mesh.addVertex (glm::normalize (v), glm::normalize (v));\n  };\n\n  const auto addRefinedVertex = [&mesh](unsigned int i1, unsigned int i2) -> unsigned int {\n    const glm::vec3 pos = glm::normalize (Util::midpoint (mesh.vertex (i1), mesh.vertex (i2)));\n    const glm::vec3 normal = glm::normalize (pos);\n    return mesh.addVertex (pos, normal);\n  };\n\n  std::function<void(unsigned int, unsigned int, unsigned int, unsigned int)> subdivide =\n    [&mesh, &subdivide, &addRefinedVertex, &vertexCache](unsigned int s, unsigned int i1,\n                                                         unsigned int i2, unsigned int i3) -> void {\n    if (s == 0)\n    {\n      MeshUtil::addFace (mesh, i1, i2, i3);\n    }\n    else\n    {\n      const unsigned int i12 = vertexCache.lookup (i1, i2, addRefinedVertex);\n      const unsigned int i23 = vertexCache.lookup (i2, i3, addRefinedVertex);\n      const unsigned int i31 = vertexCache.lookup (i3, i1, addRefinedVertex);\n\n      subdivide (s - 1, i1, i12, i31);\n      subdivide (s - 1, i2, i23, i12);\n      subdivide (s - 1, i3, i31, i23);\n      subdivide (s - 1, i12, i23, i31);\n    }\n  };\n\n  const float t = (1.0f + glm::sqrt (5.0f)) * 0.5f;\n\n  addStartVertex (glm::vec3 (-1.0f, +t, 0.0f));\n  addStartVertex (glm::vec3 (+1.0f, +t, 0.0f));\n  addStartVertex (glm::vec3 (-1.0f, -t, 0.0f));\n  addStartVertex (glm::vec3 (+1.0f, -t, 0.0f));\n\n  addStartVertex (glm::vec3 (0.0f, -1.0f, +t));\n  addStartVertex (glm::vec3 (0.0f, +1.0f, +t));\n  addStartVertex (glm::vec3 (0.0f, -1.0f, -t));\n  addStartVertex (glm::vec3 (0.0f, +1.0f, -t));\n\n  addStartVertex (glm::vec3 (+t, 0.0f, -1.0f));\n  addStartVertex (glm::vec3 (+t, 0.0f, +1.0f));\n  addStartVertex (glm::vec3 (-t, 0.0f, -1.0f));\n  addStartVertex (glm::vec3 (-t, 0.0f, +1.0f));\n\n  subdivide (numSubdivisions, 0, 11, 5);\n  subdivide (numSubdivisions, 0, 5, 1);\n  subdivide (numSubdivisions, 0, 1, 7);\n  subdivide (numSubdivisions, 0, 7, 10);\n  subdivide (numSubdivisions, 0, 10, 11);\n\n  subdivide (numSubdivisions, 1, 5, 9);\n  subdivide (numSubdivisions, 5, 11, 4);\n  subdivide (numSubdivisions, 11, 10, 2);\n  subdivide (numSubdivisions, 10, 7, 6);\n  subdivide (numSubdivisions, 7, 1, 8);\n\n  subdivide (numSubdivisions, 3, 9, 4);\n  subdivide (numSubdivisions, 3, 4, 2);\n  subdivide (numSubdivisions, 3, 2, 6);\n  subdivide (numSubdivisions, 3, 6, 8);\n  subdivide (numSubdivisions, 3, 8, 9);\n\n  subdivide (numSubdivisions, 4, 9, 5);\n  subdivide (numSubdivisions, 2, 4, 11);\n  subdivide (numSubdivisions, 6, 2, 10);\n  subdivide (numSubdivisions, 8, 6, 7);\n  subdivide (numSubdivisions, 9, 8, 1);\n\n  return mesh;\n}\n\nMesh MeshUtil::cone (unsigned int numBaseVertices)\n{\n  assert (numBaseVertices >= 3);\n\n  Mesh        mesh;\n  const float c = 2.0f * glm::pi<float> () / float(numBaseVertices);\n\n  for (unsigned int i = 0; i < numBaseVertices; i++)\n  {\n    mesh.addVertex (glm::vec3 (glm::sin (float(i) * c), -0.5f, glm::cos (float(i) * c)));\n  }\n  mesh.addVertex (glm::vec3 (0.0f, -0.5f, 0.0f));\n  mesh.addVertex (glm::vec3 (0.0f, 0.5f, 0.0f));\n\n  for (unsigned int i = 0; i < numBaseVertices - 1; i++)\n  {\n    MeshUtil::addFace (mesh, i, i + 1, numBaseVertices + 1);\n    MeshUtil::addFace (mesh, i + 1, i, numBaseVertices);\n  }\n  MeshUtil::addFace (mesh, numBaseVertices - 1, 0, numBaseVertices + 1);\n  MeshUtil::addFace (mesh, 0, numBaseVertices - 1, numBaseVertices);\n\n  return withDefaultNormals (mesh);\n}\n\nMesh MeshUtil::cylinder (unsigned int numVertices)\n{\n  assert (numVertices >= 3);\n\n  Mesh        mesh;\n  const float c = 2.0f * glm::pi<float> () / float(numVertices);\n\n  for (unsigned int i = 0; i < numVertices; i++)\n  {\n    mesh.addVertex (glm::vec3 (glm::sin (float(i) * c), -0.5f, glm::cos (float(i) * c)));\n  }\n  for (unsigned int i = 0; i < numVertices; i++)\n  {\n    mesh.addVertex (glm::vec3 (glm::sin (float(i) * c), 0.5f, glm::cos (float(i) * c)));\n  }\n  mesh.addVertex (glm::vec3 (0.0f, -0.5f, 0.0f));\n  mesh.addVertex (glm::vec3 (0.0f, 0.5f, 0.0f));\n\n  for (unsigned int i = 0; i < numVertices - 1; i++)\n  {\n    MeshUtil::addFace (mesh, i, i + 1, i + numVertices + 1, i + numVertices);\n\n    MeshUtil::addFace (mesh, i + 1, i, 2 * numVertices);\n    MeshUtil::addFace (mesh, i + numVertices, i + numVertices + 1, (2 * numVertices) + 1);\n  }\n  MeshUtil::addFace (mesh, numVertices - 1, 0, numVertices, (2 * numVertices) - 1);\n\n  MeshUtil::addFace (mesh, 0, numVertices - 1, 2 * numVertices);\n  MeshUtil::addFace (mesh, (2 * numVertices) - 1, numVertices, (2 * numVertices) + 1);\n\n  return withDefaultNormals (mesh);\n}\n\nMesh MeshUtil::mirrorPositive (const Mesh& mesh, const PrimPlane& plane)\n{\n  assert (MeshUtil::checkConsistency (mesh));\n\n  enum class Side\n  {\n    Negative,\n    Border,\n    Positive\n  };\n  enum class BorderFlag\n  {\n    NoBorder,\n    ConnectsNegative,\n    ConnectsPositive,\n    ConnectsBoth\n  };\n\n  auto side = [&plane](const glm::vec3& v) -> Side {\n    const float eps = Util::epsilon () * 0.5f;\n    const float d = plane.distance (v);\n\n    return d < -eps ? Side::Negative : (d > eps ? Side::Positive : Side::Border);\n  };\n\n  Mesh                    m;\n  std::vector<Side>       sides;\n  std::vector<BorderFlag> borderFlags;\n  std::vector<ui_pair>    newIndices;\n  EdgeMap                 newBorderVertices (mesh.numVertices ());\n\n  auto updateBorderFlag = [&borderFlags](unsigned int i, Side side) {\n    BorderFlag& current = borderFlags[i];\n\n    if (side == Side::Border)\n    {\n    }\n    else if (side == Side::Negative)\n    {\n      if (current == BorderFlag::NoBorder)\n      {\n        current = BorderFlag::ConnectsNegative;\n      }\n      else if (current == BorderFlag::ConnectsPositive)\n      {\n        current = BorderFlag::ConnectsBoth;\n      }\n    }\n    else if (side == Side::Positive)\n    {\n      if (current == BorderFlag::NoBorder)\n      {\n        current = BorderFlag::ConnectsPositive;\n      }\n      else if (current == BorderFlag::ConnectsNegative)\n      {\n        current = BorderFlag::ConnectsBoth;\n      }\n    }\n  };\n\n  auto newBorderVertex = [&mesh, &plane, &newBorderVertices, &m](unsigned int i1,\n                                                                 unsigned int i2) -> unsigned int {\n    const unsigned int* existentIndex = newBorderVertices.find (i1, i2);\n\n    if (existentIndex)\n    {\n      return *existentIndex;\n    }\n    else\n    {\n      const glm::vec3 v1 (mesh.vertex (i1));\n      const glm::vec3 v2 (mesh.vertex (i2));\n      const PrimRay   ray (true, v1, v2 - v1);\n\n      float     t;\n      glm::vec3 position;\n\n      if (IntersectionUtil::intersects (ray, plane, &t))\n      {\n        position = ray.pointAt (t);\n      }\n      else\n      {\n        position = (v1 + v2) * 0.5f;\n      }\n      const unsigned int newIndex = m.addVertex (position);\n\n      newBorderVertices.add (i1, i2, newIndex);\n      return newIndex;\n    }\n  };\n\n  m.copyNonGeometry (mesh);\n\n  sides.reserve (mesh.numVertices ());\n  borderFlags.reserve (mesh.numVertices ());\n\n  newIndices.resize (mesh.numVertices (),\n                     std::make_pair (Util::invalidIndex (), Util::invalidIndex ()));\n\n  // cache data\n  for (unsigned int i = 0; i < mesh.numVertices (); i++)\n  {\n    sides.push_back (side (mesh.vertex (i)));\n    borderFlags.push_back (BorderFlag::NoBorder);\n  }\n\n  // update border flags\n  for (unsigned int i = 0; i < mesh.numIndices (); i += 3)\n  {\n    const unsigned int i1 = mesh.index (i + 0);\n    const unsigned int i2 = mesh.index (i + 1);\n    const unsigned int i3 = mesh.index (i + 2);\n\n    assert (sides[i1] != Side::Border || sides[i2] != Side::Border || sides[i3] != Side::Border);\n\n    updateBorderFlag (i1, sides[i2]);\n    updateBorderFlag (i1, sides[i3]);\n    updateBorderFlag (i2, sides[i1]);\n    updateBorderFlag (i2, sides[i3]);\n    updateBorderFlag (i3, sides[i1]);\n    updateBorderFlag (i3, sides[i2]);\n  }\n\n  // mirror vertices\n  for (unsigned int i = 0; i < mesh.numVertices (); i++)\n  {\n    switch (sides[i])\n    {\n      case Side::Negative:\n        break;\n\n      case Side::Border:\n      {\n        switch (borderFlags[i])\n        {\n          case BorderFlag::NoBorder:\n            DILAY_IMPOSSIBLE\n            break;\n          case BorderFlag::ConnectsNegative:\n            break;\n          case BorderFlag::ConnectsPositive:\n          {\n            const unsigned int index1 = m.addVertex (mesh.vertex (i));\n            const unsigned int index2 = m.addVertex (mesh.vertex (i));\n\n            newIndices[i] = std::make_pair (index1, index2);\n            break;\n          }\n          case BorderFlag::ConnectsBoth:\n          {\n            const unsigned int index = m.addVertex (mesh.vertex (i));\n\n            newIndices[i] = std::make_pair (index, index);\n            break;\n          }\n        }\n        break;\n      }\n      case Side::Positive:\n      {\n        const unsigned int index1 = m.addVertex (mesh.vertex (i));\n        const unsigned int index2 = m.addVertex (plane.mirror (mesh.vertex (i)));\n\n        newIndices[i] = std::make_pair (index1, index2);\n        break;\n      }\n    }\n  }\n\n  // mirror faces\n  for (unsigned int i = 0; i < mesh.numIndices (); i += 3)\n  {\n    const unsigned int oldIndex1 = mesh.index (i + 0);\n    const unsigned int oldIndex2 = mesh.index (i + 1);\n    const unsigned int oldIndex3 = mesh.index (i + 2);\n\n    const Side s1 = sides[oldIndex1];\n    const Side s2 = sides[oldIndex2];\n    const Side s3 = sides[oldIndex3];\n\n    if (s1 == Side::Positive || s2 == Side::Positive || s3 == Side::Positive)\n    {\n      const ui_pair& new1 = newIndices[oldIndex1];\n      const ui_pair& new2 = newIndices[oldIndex2];\n      const ui_pair& new3 = newIndices[oldIndex3];\n\n      // 3 non-negative\n      if (s1 != Side::Negative && s2 != Side::Negative && s3 != Side::Negative)\n      {\n        MeshUtil::addFace (m, new1.first, new2.first, new3.first);\n        MeshUtil::addFace (m, new3.second, new2.second, new1.second);\n      }\n      // 1 negative - 2 positive\n      else if (s1 == Side::Positive && s2 == Side::Positive && s3 == Side::Negative)\n      {\n        unsigned int b1 = newBorderVertex (oldIndex1, oldIndex3);\n        unsigned int b2 = newBorderVertex (oldIndex2, oldIndex3);\n\n        MeshUtil::addFace (m, new2.first, b2, new1.first);\n        MeshUtil::addFace (m, new1.second, b2, new2.second);\n\n        MeshUtil::addFace (m, new1.first, b2, b1);\n        MeshUtil::addFace (m, b1, b2, new1.second);\n      }\n      else if (s1 == Side::Positive && s2 == Side::Negative && s3 == Side::Positive)\n      {\n        unsigned int b1 = newBorderVertex (oldIndex1, oldIndex2);\n        unsigned int b2 = newBorderVertex (oldIndex2, oldIndex3);\n\n        MeshUtil::addFace (m, new1.first, b1, new3.first);\n        MeshUtil::addFace (m, new3.second, b1, new1.second);\n\n        MeshUtil::addFace (m, new3.first, b1, b2);\n        MeshUtil::addFace (m, b2, b1, new3.second);\n      }\n      else if (s1 == Side::Negative && s2 == Side::Positive && s3 == Side::Positive)\n      {\n        unsigned int b1 = newBorderVertex (oldIndex1, oldIndex2);\n        unsigned int b2 = newBorderVertex (oldIndex1, oldIndex3);\n\n        MeshUtil::addFace (m, new3.first, b2, new2.first);\n        MeshUtil::addFace (m, new2.second, b2, new3.second);\n\n        MeshUtil::addFace (m, new2.first, b2, b1);\n        MeshUtil::addFace (m, b1, b2, new2.second);\n      }\n      // 1 positive - 2 negative\n      else if (s1 == Side::Positive && s2 == Side::Negative && s3 == Side::Negative)\n      {\n        unsigned int b1 = newBorderVertex (oldIndex1, oldIndex2);\n        unsigned int b2 = newBorderVertex (oldIndex1, oldIndex3);\n\n        MeshUtil::addFace (m, new1.first, b1, b2);\n        MeshUtil::addFace (m, b2, b1, new1.second);\n      }\n      else if (s1 == Side::Negative && s2 == Side::Positive && s3 == Side::Negative)\n      {\n        unsigned int b1 = newBorderVertex (oldIndex1, oldIndex2);\n        unsigned int b2 = newBorderVertex (oldIndex2, oldIndex3);\n\n        MeshUtil::addFace (m, new2.first, b2, b1);\n        MeshUtil::addFace (m, b1, b2, new2.second);\n      }\n      else if (s1 == Side::Negative && s2 == Side::Negative && s3 == Side::Positive)\n      {\n        unsigned int b1 = newBorderVertex (oldIndex1, oldIndex3);\n        unsigned int b2 = newBorderVertex (oldIndex2, oldIndex3);\n\n        MeshUtil::addFace (m, new3.first, b1, b2);\n        MeshUtil::addFace (m, b2, b1, new3.second);\n      }\n      // 1 positive - 1 border - 1 negative\n      else if (s1 == Side::Positive && s2 == Side::Border && s3 == Side::Negative)\n      {\n        assert (borderFlags[oldIndex2] == BorderFlag::ConnectsBoth);\n\n        unsigned int b = newBorderVertex (oldIndex1, oldIndex3);\n\n        MeshUtil::addFace (m, new1.first, new2.first, b);\n        MeshUtil::addFace (m, b, new2.second, new1.second);\n      }\n      else if (s1 == Side::Border && s2 == Side::Positive && s3 == Side::Negative)\n      {\n        assert (borderFlags[oldIndex1] == BorderFlag::ConnectsBoth);\n\n        unsigned int b = newBorderVertex (oldIndex2, oldIndex3);\n\n        MeshUtil::addFace (m, new1.first, new2.first, b);\n        MeshUtil::addFace (m, b, new2.second, new1.second);\n      }\n      else if (s1 == Side::Positive && s2 == Side::Negative && s3 == Side::Border)\n      {\n        assert (borderFlags[oldIndex3] == BorderFlag::ConnectsBoth);\n\n        unsigned int b = newBorderVertex (oldIndex1, oldIndex2);\n\n        MeshUtil::addFace (m, new1.first, b, new3.first);\n        MeshUtil::addFace (m, new3.second, b, new1.second);\n      }\n      else if (s1 == Side::Border && s2 == Side::Negative && s3 == Side::Positive)\n      {\n        assert (borderFlags[oldIndex1] == BorderFlag::ConnectsBoth);\n\n        unsigned int b = newBorderVertex (oldIndex2, oldIndex3);\n\n        MeshUtil::addFace (m, new1.first, b, new3.first);\n        MeshUtil::addFace (m, new3.second, b, new1.second);\n      }\n      else if (s1 == Side::Negative && s2 == Side::Positive && s3 == Side::Border)\n      {\n        assert (borderFlags[oldIndex3] == BorderFlag::ConnectsBoth);\n\n        unsigned int b = newBorderVertex (oldIndex1, oldIndex2);\n\n        MeshUtil::addFace (m, new2.first, new3.first, b);\n        MeshUtil::addFace (m, b, new3.second, new2.second);\n      }\n      else if (s1 == Side::Negative && s2 == Side::Border && s3 == Side::Positive)\n      {\n        assert (borderFlags[oldIndex2] == BorderFlag::ConnectsBoth);\n\n        unsigned int b = newBorderVertex (oldIndex1, oldIndex3);\n\n        MeshUtil::addFace (m, new2.first, new3.first, b);\n        MeshUtil::addFace (m, b, new3.second, new2.second);\n      }\n      else\n      {\n        DILAY_IMPOSSIBLE\n      }\n    }\n  }\n\n  if (MeshUtil::checkConsistency (m) == false)\n  {\n    m.reset ();\n  }\n  return m;\n}\n\nvoid MeshUtil::mirror (Mesh& mesh, const PrimPlane& plane)\n{\n  for (unsigned int i = 0; i < mesh.numVertices (); i++)\n  {\n    mesh.vertex (i, plane.mirror (mesh.vertex (i)));\n    mesh.normal (i, plane.mirrorDirection (mesh.normal (i)));\n  }\n\n  assert (mesh.numIndices () % 3 == 0);\n\n  for (unsigned int i = 0; i < mesh.numIndices (); i += 3)\n  {\n    const unsigned int i2 = mesh.index (i + 1);\n    const unsigned int i3 = mesh.index (i + 2);\n\n    mesh.index (i + 1, i3);\n    mesh.index (i + 2, i2);\n  }\n}\n\nvoid MeshUtil::moveToCenter (Mesh& mesh)\n{\n  const PrimAABox bounds = mesh.bounds ();\n\n  mesh.translate (-bounds.center ());\n  mesh.normalize ();\n}\n\nvoid MeshUtil::normalizeScaling (Mesh& mesh)\n{\n  const PrimAABox  bounds = mesh.bounds ();\n  const glm::vec3& center = bounds.center ();\n  const float      factor = 2.0f / bounds.maxDimExtent ();\n\n  for (unsigned int i = 0; i < mesh.numVertices (); i++)\n  {\n    const glm::vec3& v = mesh.vertex (i);\n\n    mesh.vertex (i, (factor * (v - center)) + center);\n  }\n}\n\nbool MeshUtil::checkConsistency (const Mesh& mesh)\n{\n  if (mesh.numVertices () == 0)\n  {\n    DILAY_WARN (\"empty mesh\");\n    return false;\n  }\n  EdgeMap                   numEdgeAdjacentFaces (mesh.numVertices ());\n  std::vector<unsigned int> numVertexAdjacentFaces;\n  numVertexAdjacentFaces.resize (mesh.numVertices (), 0);\n\n  for (unsigned int i = 0; i < mesh.numIndices (); i += 3)\n  {\n    const unsigned int i1 = mesh.index (i + 0);\n    const unsigned int i2 = mesh.index (i + 1);\n    const unsigned int i3 = mesh.index (i + 2);\n\n    numVertexAdjacentFaces[i1]++;\n    numVertexAdjacentFaces[i2]++;\n    numVertexAdjacentFaces[i3]++;\n\n    numEdgeAdjacentFaces.increase (i1, i2);\n    numEdgeAdjacentFaces.increase (i1, i3);\n    numEdgeAdjacentFaces.increase (i2, i3);\n  }\n\n  for (unsigned int v = 0; v < numVertexAdjacentFaces.size (); v++)\n  {\n    if (numVertexAdjacentFaces[v] < 3)\n    {\n      DILAY_WARN (\"inconsistent vertex %u with %u adjacent faces\", v, numVertexAdjacentFaces[v]);\n      return false;\n    }\n  }\n\n  for (unsigned int i = 0; i < numEdgeAdjacentFaces.elements.size (); i++)\n  {\n    for (const auto& pair : numEdgeAdjacentFaces.elements[i])\n    {\n      const unsigned int j = pair.first;\n      const unsigned int value = pair.second;\n\n      if (value != 2)\n      {\n        DILAY_WARN (\"inconsistent edge (%u,%u) with %u adjacent faces\", i, j, value);\n        return false;\n      }\n    }\n  }\n  return true;\n}\n"
  },
  {
    "path": "lib/src/mesh-util.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_MESH_UTIL\n#define DILAY_MESH_UTIL\n\nclass Mesh;\nclass PrimPlane;\n\nnamespace MeshUtil\n{\n  void addFace (Mesh&, unsigned int, unsigned int, unsigned int);\n  void addFace (Mesh&, unsigned int, unsigned int, unsigned int, unsigned int);\n\n  Mesh cube (unsigned int);\n  Mesh sphere (unsigned int, unsigned int);\n  Mesh icosphere (unsigned int);\n  Mesh cone (unsigned int);\n  Mesh cylinder (unsigned int);\n\n  Mesh mirrorPositive (const Mesh&, const PrimPlane&);\n  void mirror (Mesh&, const PrimPlane&);\n\n  void moveToCenter (Mesh&);\n  void normalizeScaling (Mesh&);\n  bool checkConsistency (const Mesh&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/mesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include <glm/gtc/matrix_inverse.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <vector>\n#include \"camera.hpp\"\n#include \"color.hpp\"\n#include \"mesh.hpp\"\n#include \"opengl-buffer-id.hpp\"\n#include \"opengl.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"render-mode.hpp\"\n#include \"renderer.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  static_assert (sizeof (glm::vec3) == 3 * sizeof (float), \"Unexpected memory layout\");\n\n  template <typename T> struct BufferedData\n  {\n    OpenGLBufferId id;\n    std::vector<T> data;\n    unsigned int   dataLowerBound;\n    unsigned int   dataUpperBound;\n    unsigned int   bufferSize;\n\n    BufferedData () { this->reset (); }\n\n    void reset ()\n    {\n      this->id.reset ();\n      this->data.clear ();\n      this->resetBounds ();\n      this->bufferSize = 0;\n    }\n\n    void resetBounds ()\n    {\n      this->dataLowerBound = Util::maxUnsignedInt ();\n      this->dataUpperBound = 0;\n    }\n\n    unsigned int numElements () const { return this->data.size (); }\n\n    void reserve (unsigned int size) { this->data.reserve (size); }\n\n    void shrink (unsigned int n)\n    {\n      assert (n <= this->numElements ());\n      this->data.resize (n);\n      this->dataLowerBound = 0;\n      this->dataUpperBound = n > 0 ? n - 1 : 0;\n    }\n\n    void updateBounds (unsigned int index)\n    {\n      this->dataLowerBound = glm::min (this->dataLowerBound, index);\n      this->dataUpperBound = glm::max (this->dataUpperBound, index);\n    }\n\n    unsigned int add (const T& value)\n    {\n      this->data.push_back (value);\n      this->updateBounds (this->numElements () - 1);\n      return this->numElements () - 1;\n    }\n\n    void set (unsigned int index, const T& value)\n    {\n      assert (index < this->numElements ());\n      this->data[index] = value;\n      this->updateBounds (index);\n    }\n\n    const T& get (unsigned int index) const\n    {\n      assert (index < this->numElements ());\n      return this->data[index];\n    }\n\n    void bufferData (unsigned int target)\n    {\n      if (this->id.isValid () == false)\n      {\n        this->id.allocate ();\n        this->bufferSize = 0;\n      }\n      OpenGL::glBindBuffer (target, this->id.id ());\n\n      const unsigned int dataSize = this->numElements () * sizeof (T);\n\n      if (this->bufferSize == 0)\n      {\n        OpenGL::glBufferData (target, dataSize, this->data.data (), OpenGL::StaticDraw ());\n        this->bufferSize = dataSize;\n      }\n      else if (this->bufferSize < dataSize)\n      {\n        const unsigned int newBufferSize = this->bufferSize + (100 * (dataSize - this->bufferSize));\n\n        OpenGL::glBufferData (target, newBufferSize, nullptr, OpenGL::StaticDraw ());\n        OpenGL::glBufferSubData (target, 0, dataSize, this->data.data ());\n        this->bufferSize = newBufferSize;\n      }\n      else if (this->dataLowerBound <= this->dataUpperBound)\n      {\n        const unsigned int size = (this->dataUpperBound - this->dataLowerBound + 1) * sizeof (T);\n\n        OpenGL::glBufferSubData (target, this->dataLowerBound * sizeof (T), size,\n                                 &this->get (this->dataLowerBound));\n      }\n      this->resetBounds ();\n    }\n  };\n}\n\nstruct Mesh::Impl\n{\n  // cf. copy-constructor, reset\n  glm::mat4x4                scalingMatrix;\n  glm::mat4x4                rotationMatrix;\n  glm::mat4x4                translationMatrix;\n  BufferedData<glm::vec3>    vertices;\n  BufferedData<unsigned int> indices;\n  BufferedData<glm::vec3>    normals;\n  Color                      color;\n  Color                      wireframeColor;\n\n  RenderMode renderMode;\n\n  Impl ()\n    : scalingMatrix (glm::mat4x4 (1.0f))\n    , rotationMatrix (glm::mat4x4 (1.0f))\n    , translationMatrix (glm::mat4x4 (1.0f))\n    , color (Color::White ())\n    , wireframeColor (Color::Black ())\n  {\n    this->renderMode.smoothShading (true);\n  }\n\n  unsigned int numVertices () const { return this->vertices.numElements (); }\n\n  unsigned int numIndices () const { return this->indices.numElements (); }\n\n  const glm::vec3& vertex (unsigned int i) const { return this->vertices.get (i); }\n\n  unsigned int index (unsigned int i) const { return this->indices.get (i); }\n\n  const glm::vec3& normal (unsigned int i) const { return this->normals.get (i); }\n\n  void copyNonGeometry (const Mesh& source)\n  {\n    this->scalingMatrix = source.impl->scalingMatrix;\n    this->rotationMatrix = source.impl->rotationMatrix;\n    this->translationMatrix = source.impl->translationMatrix;\n    this->color = source.impl->color;\n    this->wireframeColor = source.impl->wireframeColor;\n    this->renderMode = source.impl->renderMode;\n  }\n\n  unsigned int addIndex (unsigned int i) { return this->indices.add (i); }\n\n  void reserveIndices (unsigned int n) { this->indices.reserve (n); }\n\n  void shrinkIndices (unsigned int n) { this->indices.shrink (n); }\n\n  unsigned int addVertex (const glm::vec3& v) { return this->addVertex (v, glm::vec3 (0.0f)); }\n\n  unsigned int addVertex (const glm::vec3& v, const glm::vec3& n)\n  {\n    assert (Util::isNaN (v) == false);\n    assert (Util::isNaN (n) == false);\n    assert (this->vertices.numElements () == this->normals.numElements ());\n\n    this->vertices.add (v);\n    return this->normals.add (n);\n  }\n\n  void reserveVertices (unsigned int n)\n  {\n    this->vertices.reserve (n);\n    this->normals.reserve (n);\n  }\n\n  void shrinkVertices (unsigned int n)\n  {\n    this->vertices.shrink (n);\n    this->normals.shrink (n);\n  }\n\n  void index (unsigned int i, unsigned int index) { this->indices.set (i, index); }\n\n  void vertex (unsigned int i, const glm::vec3& v)\n  {\n    assert (Util::isNaN (v) == false);\n    this->vertices.set (i, v);\n  }\n\n  void normal (unsigned int i, const glm::vec3& n)\n  {\n    assert (Util::isNaN (n) == false);\n    this->normals.set (i, n);\n  }\n\n  void bufferData ()\n  {\n    this->vertices.bufferData (OpenGL::ArrayBuffer ());\n    this->indices.bufferData (OpenGL::ElementArrayBuffer ());\n    this->normals.bufferData (OpenGL::ArrayBuffer ());\n\n    OpenGL::glBindBuffer (OpenGL::ElementArrayBuffer (), 0);\n    OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), 0);\n  }\n\n  glm::mat4x4 modelMatrix () const\n  {\n    return this->translationMatrix * this->rotationMatrix * this->scalingMatrix;\n  }\n\n  glm::mat3x3 modelNormalMatrix () const\n  {\n    return glm::inverseTranspose (glm::mat3x3 (this->modelMatrix ()));\n  }\n\n  void setModelMatrix (Camera& camera, bool noZoom) const\n  {\n    camera.setModelViewProjection (this->modelMatrix (), this->modelNormalMatrix (), noZoom);\n  }\n\n  void renderBegin (Camera& camera) const\n  {\n    if (this->renderMode.renderWireframe () && OpenGL::hasGeometryShader () == false)\n    {\n      RenderMode nonWireframeRenderMode (this->renderMode);\n      nonWireframeRenderMode.renderWireframe (false);\n\n      camera.renderer ().setProgram (nonWireframeRenderMode);\n    }\n    else\n    {\n      camera.renderer ().setProgram (this->renderMode);\n    }\n    camera.renderer ().setColor (this->color);\n    camera.renderer ().setWireframeColor (this->wireframeColor);\n\n    this->setModelMatrix (camera, this->renderMode.cameraRotationOnly ());\n\n    OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), this->vertices.id.id ());\n    OpenGL::glEnableVertexAttribArray (OpenGL::PositionIndex);\n    OpenGL::glVertexAttribPointer (OpenGL::PositionIndex, 3, OpenGL::Float (), false, 0, 0);\n\n    OpenGL::glBindBuffer (OpenGL::ElementArrayBuffer (), this->indices.id.id ());\n\n    if (this->renderMode.smoothShading ())\n    {\n      OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), this->normals.id.id ());\n      OpenGL::glEnableVertexAttribArray (OpenGL::NormalIndex);\n      OpenGL::glVertexAttribPointer (OpenGL::NormalIndex, 3, OpenGL::Float (), false, 0, 0);\n    }\n    OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), 0);\n\n    if (this->renderMode.noDepthTest ())\n    {\n      OpenGL::glDisable (OpenGL::DepthTest ());\n    }\n  }\n\n  void renderEnd () const\n  {\n    OpenGL::glDisableVertexAttribArray (OpenGL::PositionIndex);\n    OpenGL::glDisableVertexAttribArray (OpenGL::NormalIndex);\n    OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), 0);\n    OpenGL::glBindBuffer (OpenGL::ElementArrayBuffer (), 0);\n    OpenGL::glEnable (OpenGL::DepthTest ());\n  }\n\n  void render (Camera& camera) const\n  {\n    this->renderBegin (camera);\n\n    OpenGL::glDrawElements (OpenGL::Triangles (), this->numIndices (), OpenGL::UnsignedInt (),\n                            nullptr);\n\n    if (this->renderMode.renderWireframe () && OpenGL::hasGeometryShader () == false)\n    {\n      camera.renderer ().setColor (this->wireframeColor);\n      OpenGL::glPolygonMode (OpenGL::FrontAndBack (), OpenGL::Line ());\n\n      OpenGL::glDrawElements (OpenGL::Triangles (), this->numIndices (), OpenGL::UnsignedInt (),\n                              nullptr);\n\n      OpenGL::glPolygonMode (OpenGL::FrontAndBack (), OpenGL::Fill ());\n    }\n\n    this->renderEnd ();\n  }\n\n  void renderLines (Camera& camera) const\n  {\n    this->renderBegin (camera);\n    OpenGL::glDrawElements (OpenGL::Lines (), this->numIndices (), OpenGL::UnsignedInt (), nullptr);\n    this->renderEnd ();\n  }\n\n  void reset ()\n  {\n    this->scalingMatrix = glm::mat4x4 (1.0f);\n    this->rotationMatrix = glm::mat4x4 (1.0f);\n    this->translationMatrix = glm::mat4x4 (1.0f);\n    this->resetGeometry ();\n  }\n\n  void resetGeometry ()\n  {\n    this->vertices.reset ();\n    this->indices.reset ();\n    this->normals.reset ();\n  }\n\n  void scale (const glm::vec3& v) { this->scalingMatrix = glm::scale (this->scalingMatrix, v); }\n\n  void scaling (const glm::vec3& v) { this->scalingMatrix = glm::scale (glm::mat4x4 (1.0f), v); }\n\n  glm::vec3 scaling () const\n  {\n    return glm::vec3 (this->scalingMatrix[0][0], this->scalingMatrix[1][1],\n                      this->scalingMatrix[2][2]);\n  }\n\n  void translate (const glm::vec3& v)\n  {\n    this->translationMatrix = glm::translate (this->translationMatrix, v);\n  }\n\n  void position (const glm::vec3& v)\n  {\n    this->translationMatrix = glm::translate (glm::mat4x4 (1.0f), v);\n  }\n\n  glm::vec3 position () const\n  {\n    return glm::vec3 (this->translationMatrix[3][0], this->translationMatrix[3][1],\n                      this->translationMatrix[3][2]);\n  }\n\n  void rotation (const glm::vec3& axis, float angle)\n  {\n    this->rotationMatrix = glm::rotate (glm::mat4x4 (1.0f), angle, axis);\n  }\n\n  void rotationX (float angle) { this->rotation (glm::vec3 (1.0f, 0.0f, 0.0f), angle); }\n\n  void rotationY (float angle) { this->rotation (glm::vec3 (0.0f, 1.0f, 0.0f), angle); }\n\n  void rotationZ (float angle) { this->rotation (glm::vec3 (0.0f, 0.0f, 1.0f), angle); }\n\n  void rotate (const glm::mat4x4& matrix) { this->rotationMatrix = matrix * this->rotationMatrix; }\n\n  void rotate (const glm::vec3& axis, float angle)\n  {\n    this->rotationMatrix = glm::rotate (this->rotationMatrix, angle, axis);\n  }\n\n  void rotateX (float angle) { this->rotate (glm::vec3 (1.0f, 0.0f, 0.0f), angle); }\n\n  void rotateY (float angle) { this->rotate (glm::vec3 (0.0f, 1.0f, 0.0f), angle); }\n\n  void rotateZ (float angle) { this->rotate (glm::vec3 (0.0f, 0.0f, 1.0f), angle); }\n\n  void normalize ()\n  {\n    const glm::mat4x4 model = this->modelMatrix ();\n    const glm::mat3x3 modelNormal = this->modelNormalMatrix ();\n\n    for (unsigned int i = 0; i < this->numVertices (); i++)\n    {\n      this->vertex (i, Util::transformPosition (model, this->vertex (i)));\n      if (Util::isNotNull (this->normal (i)))\n      {\n        this->normal (i, glm::normalize (modelNormal * this->normal (i)));\n      }\n    }\n    this->position (glm::vec3 (0.0f));\n    this->scaling (glm::vec3 (1.0f));\n    this->rotationMatrix = glm::mat4x4 (1.0f);\n  }\n\n  PrimAABox bounds () const\n  {\n    glm::vec3 min = glm::vec3 (Util::maxFloat ());\n    glm::vec3 max = glm::vec3 (Util::minFloat ());\n\n    for (unsigned int i = 0; i < this->numVertices (); i++)\n    {\n      min = glm::min (min, this->vertices.get (i));\n      max = glm::max (max, this->vertices.get (i));\n    }\n    return PrimAABox (min, max);\n  }\n};\n\nDELEGATE_BIG6 (Mesh)\nDELEGATE_CONST (unsigned int, Mesh, numVertices)\nDELEGATE_CONST (unsigned int, Mesh, numIndices)\nDELEGATE1_CONST (const glm::vec3&, Mesh, vertex, unsigned int)\nDELEGATE1_CONST (unsigned int, Mesh, index, unsigned int)\nDELEGATE1_CONST (const glm::vec3&, Mesh, normal, unsigned int)\n\nDELEGATE1 (void, Mesh, copyNonGeometry, const Mesh&)\nDELEGATE1 (unsigned int, Mesh, addIndex, unsigned int)\nDELEGATE1 (void, Mesh, reserveIndices, unsigned int)\nDELEGATE1 (void, Mesh, shrinkIndices, unsigned int)\nDELEGATE1 (unsigned int, Mesh, addVertex, const glm::vec3&)\nDELEGATE2 (unsigned int, Mesh, addVertex, const glm::vec3&, const glm::vec3&)\nDELEGATE1 (void, Mesh, reserveVertices, unsigned int)\nDELEGATE1 (void, Mesh, shrinkVertices, unsigned int)\nDELEGATE2 (void, Mesh, index, unsigned int, unsigned int)\nDELEGATE2 (void, Mesh, vertex, unsigned int, const glm::vec3&)\nDELEGATE2 (void, Mesh, normal, unsigned int, const glm::vec3&)\n\nDELEGATE (void, Mesh, bufferData)\nDELEGATE_CONST (glm::mat4x4, Mesh, modelMatrix)\nDELEGATE_CONST (glm::mat3x3, Mesh, modelNormalMatrix)\nDELEGATE1_CONST (void, Mesh, renderBegin, Camera&)\nDELEGATE_CONST (void, Mesh, renderEnd)\nDELEGATE1_CONST (void, Mesh, render, Camera&)\nDELEGATE1_CONST (void, Mesh, renderLines, Camera&)\nDELEGATE (void, Mesh, reset)\nDELEGATE (void, Mesh, resetGeometry)\nGETTER_CONST (const RenderMode&, Mesh, renderMode)\nGETTER (RenderMode&, Mesh, renderMode)\n\nDELEGATE1 (void, Mesh, scale, const glm::vec3&)\nDELEGATE1 (void, Mesh, scaling, const glm::vec3&)\nDELEGATE_CONST (glm::vec3, Mesh, scaling)\nDELEGATE1 (void, Mesh, translate, const glm::vec3&)\nDELEGATE1 (void, Mesh, position, const glm::vec3&)\nDELEGATE_CONST (glm::vec3, Mesh, position)\nSETTER (const glm::mat4x4&, Mesh, rotationMatrix)\nGETTER_CONST (const glm::mat4x4&, Mesh, rotationMatrix)\nDELEGATE2 (void, Mesh, rotation, const glm::vec3&, float)\nDELEGATE1 (void, Mesh, rotationX, float)\nDELEGATE1 (void, Mesh, rotationY, float)\nDELEGATE1 (void, Mesh, rotationZ, float)\nDELEGATE1 (void, Mesh, rotate, const glm::mat4x4&)\nDELEGATE2 (void, Mesh, rotate, const glm::vec3&, float)\nDELEGATE1 (void, Mesh, rotateX, float)\nDELEGATE1 (void, Mesh, rotateY, float)\nDELEGATE1 (void, Mesh, rotateZ, float)\nDELEGATE (void, Mesh, normalize)\nDELEGATE_CONST (PrimAABox, Mesh, bounds)\nGETTER_CONST (const Color&, Mesh, color)\nSETTER (const Color&, Mesh, color)\nGETTER_CONST (const Color&, Mesh, wireframeColor)\nSETTER (const Color&, Mesh, wireframeColor)\n"
  },
  {
    "path": "lib/src/mesh.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_MESH\n#define DILAY_MESH\n\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n\nclass Camera;\nclass Color;\nclass PrimAABox;\nclass RenderFlags;\nclass RenderMode;\n\nclass Mesh\n{\npublic:\n  DECLARE_BIG6 (Mesh)\n\n  unsigned int     numVertices () const;\n  unsigned int     numIndices () const;\n  const glm::vec3& vertex (unsigned int) const;\n  unsigned int     index (unsigned int) const;\n  const glm::vec3& normal (unsigned int) const;\n  void             copyNonGeometry (const Mesh&);\n  unsigned int     addIndex (unsigned int);\n  void             reserveIndices (unsigned int);\n  void             shrinkIndices (unsigned int);\n  unsigned int     addVertex (const glm::vec3&);\n  unsigned int     addVertex (const glm::vec3&, const glm::vec3&);\n  void             reserveVertices (unsigned int);\n  void             shrinkVertices (unsigned int);\n  void             index (unsigned int, unsigned int);\n  void             vertex (unsigned int, const glm::vec3&);\n  void             normal (unsigned int, const glm::vec3&);\n\n  void              bufferData ();\n  glm::mat4x4       modelMatrix () const;\n  glm::mat3x3       modelNormalMatrix () const;\n  void              renderBegin (Camera&) const;\n  void              renderEnd () const;\n  void              render (Camera&) const;\n  void              renderLines (Camera&) const;\n  void              reset ();\n  void              resetGeometry ();\n  const RenderMode& renderMode () const;\n  RenderMode&       renderMode ();\n\n  void               scale (const glm::vec3&);\n  void               scaling (const glm::vec3&);\n  glm::vec3          scaling () const;\n  void               translate (const glm::vec3&);\n  void               position (const glm::vec3&);\n  glm::vec3          position () const;\n  void               rotationMatrix (const glm::mat4x4&);\n  const glm::mat4x4& rotationMatrix () const;\n  void               rotation (const glm::vec3&, float);\n  void               rotationX (float);\n  void               rotationY (float);\n  void               rotationZ (float);\n  void               rotate (const glm::mat4x4&);\n  void               rotate (const glm::vec3&, float);\n  void               rotateX (float);\n  void               rotateY (float);\n  void               rotateZ (float);\n  void               normalize ();\n  PrimAABox          bounds () const;\n  const Color&       color () const;\n  void               color (const Color&);\n  const Color&       wireframeColor () const;\n  void               wireframeColor (const Color&);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/mirror.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"camera.hpp\"\n#include \"color.hpp\"\n#include \"config.hpp\"\n#include \"dimension.hpp\"\n#include \"mesh-util.hpp\"\n#include \"mesh.hpp\"\n#include \"mirror.hpp\"\n#include \"opengl.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"render-mode.hpp\"\n\nstruct Mirror::Impl\n{\n  Dimension                  _dimension;\n  float                      width;\n  Mesh                       mirrorMesh;\n  std::unique_ptr<PrimPlane> _plane;\n\n  Impl (const Config& config, Dimension d)\n    : _dimension (d)\n    , width (1.0f)\n  {\n    this->mirrorMesh = MeshUtil::cube (0);\n    this->mirrorMesh.renderMode ().constantShading (true);\n    this->mirrorMesh.bufferData ();\n\n    this->runFromConfig (config);\n    this->dimension (d);\n  }\n\n  Dimension dimension () const { return this->_dimension; }\n\n  void dimension (Dimension d)\n  {\n    this->_dimension = d;\n    this->_plane = std::make_unique<PrimPlane> (glm::vec3 (0.0f), DimensionUtil::vector (d));\n  }\n\n  void position (const glm::vec3& p)\n  {\n    this->_plane =\n      std::make_unique<PrimPlane> (glm::vec3 (p), DimensionUtil::vector (this->_dimension));\n    this->mirrorMesh.position (p);\n  }\n\n  const PrimPlane& plane () const { return *this->_plane; }\n\n  void render (Camera& camera) const\n  {\n    const glm::vec3 pos = camera.position ();\n    const float     width2 = this->width * 0.5f;\n    const bool      inside =\n      (this->_dimension == Dimension::X && glm::abs (pos.x - this->_plane->point ().x) <= width2) ||\n      (this->_dimension == Dimension::Y && glm::abs (pos.y - this->_plane->point ().y) <= width2) ||\n      (this->_dimension == Dimension::Z && glm::abs (pos.z - this->_plane->point ().z) <= width2);\n\n    OpenGL::glClear (OpenGL::StencilBufferBit ());\n    OpenGL::glDepthMask (false);\n    OpenGL::glEnable (OpenGL::StencilTest ());\n\n    OpenGL::glColorMask (false, false, false, false);\n\n    OpenGL::glCullFace (OpenGL::Front ());\n\n    OpenGL::glEnable (OpenGL::StencilTest ());\n    OpenGL::glStencilFunc (OpenGL::Always (), 1, 255);\n    OpenGL::glStencilOp (OpenGL::Keep (), OpenGL::Replace (), OpenGL::Keep ());\n\n    this->mirrorMesh.render (camera);\n\n    if (inside)\n    {\n      OpenGL::glDisable (OpenGL::DepthTest ());\n    }\n    else\n    {\n      OpenGL::glCullFace (OpenGL::Back ());\n    }\n\n    OpenGL::glColorMask (true, true, true, true);\n\n    OpenGL::glStencilFunc (OpenGL::Equal (), 1, 255);\n    OpenGL::glStencilOp (OpenGL::Keep (), OpenGL::Keep (), OpenGL::Keep ());\n\n    OpenGL::glEnable (OpenGL::Blend ());\n    OpenGL::glBlendEquation (OpenGL::FuncAdd ());\n    OpenGL::glBlendFunc (OpenGL::DstColor (), OpenGL::Zero ());\n\n    this->mirrorMesh.render (camera);\n\n    OpenGL::glDisable (OpenGL::Blend ());\n\n    if (inside)\n    {\n      OpenGL::glCullFace (OpenGL::Back ());\n      OpenGL::glEnable (OpenGL::DepthTest ());\n    }\n    OpenGL::glDisable (OpenGL::StencilTest ());\n    OpenGL::glDepthMask (true);\n  }\n\n  void updateMesh ()\n  {\n    const float extent = 1000.0f;\n\n    switch (this->_dimension)\n    {\n      case Dimension::X:\n        this->mirrorMesh.scaling (glm::vec3 (this->width, extent, extent));\n        break;\n\n      case Dimension::Y:\n        this->mirrorMesh.scaling (glm::vec3 (extent, this->width, extent));\n        break;\n\n      case Dimension::Z:\n        this->mirrorMesh.scaling (glm::vec3 (extent, extent, this->width));\n        break;\n    }\n  }\n\n  void runFromConfig (const Config& config)\n  {\n    this->width = config.get<float> (\"editor/tool/sculpt/mirror/width\");\n    this->mirrorMesh.color (config.get<Color> (\"editor/tool/sculpt/mirror/color\"));\n    this->updateMesh ();\n  }\n};\n\nDELEGATE2_BIG2 (Mirror, const Config&, Dimension)\nDELEGATE_CONST (Dimension, Mirror, dimension)\nGETTER_CONST (float, Mirror, width)\nDELEGATE1 (void, Mirror, dimension, Dimension)\nDELEGATE1 (void, Mirror, position, const glm::vec3&)\nDELEGATE_CONST (const PrimPlane&, Mirror, plane)\nDELEGATE1_CONST (void, Mirror, render, Camera&)\nDELEGATE1 (void, Mirror, runFromConfig, const Config&)\n"
  },
  {
    "path": "lib/src/mirror.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_MIRROR\n#define DILAY_MIRROR\n\n#include <glm/fwd.hpp>\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n\nclass Camera;\nenum class Dimension;\nclass PrimPlane;\n\nclass Mirror : public Configurable\n{\npublic:\n  DECLARE_BIG2 (Mirror, const Config&, Dimension)\n\n  Dimension        dimension () const;\n  float            width () const;\n  const PrimPlane& plane () const;\n\n  void dimension (Dimension);\n  void position (const glm::vec3&);\n  void render (Camera&) const;\n\nprivate:\n  IMPLEMENTATION\n\n  void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/opengl-buffer-id.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"opengl-buffer-id.hpp\"\n#include \"opengl.hpp\"\n\nOpenGLBufferId::OpenGLBufferId ()\n  : _id (0)\n{\n}\n\nOpenGLBufferId::OpenGLBufferId (const OpenGLBufferId&)\n  : OpenGLBufferId ()\n{\n}\n\nOpenGLBufferId::OpenGLBufferId (OpenGLBufferId&& other)\n  : _id (other._id)\n{\n}\n\nconst OpenGLBufferId& OpenGLBufferId::operator= (const OpenGLBufferId&) { return *this; }\n\nconst OpenGLBufferId& OpenGLBufferId::operator= (OpenGLBufferId&& other)\n{\n  this->_id = other._id;\n  return *this;\n}\n\nOpenGLBufferId::~OpenGLBufferId () { this->reset (); }\n\nunsigned int OpenGLBufferId::id () const { return this->_id; }\n\nbool OpenGLBufferId::isValid () const { return this->_id > 0; }\n\nvoid OpenGLBufferId::allocate ()\n{\n  assert (this->isValid () == false);\n\n  OpenGL::glGenBuffers (1, &this->_id);\n\n  assert (this->isValid ());\n}\n\nvoid OpenGLBufferId::reset ()\n{\n  if (this->isValid ())\n  {\n    OpenGL::safeDeleteBuffer (this->_id);\n  }\n}\n"
  },
  {
    "path": "lib/src/opengl-buffer-id.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_OPENGL_BUFFER_ID\n#define DILAY_OPENGL_BUFFER_ID\n\n#include \"macro.hpp\"\n\nclass OpenGLBufferId\n{\npublic:\n  DECLARE_BIG6 (OpenGLBufferId)\n\n  unsigned int id () const;\n  bool         isValid () const;\n\n  void allocate ();\n  void reset ();\n\nprivate:\n  unsigned int _id;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/opengl.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QOpenGLContext>\n#include <QOpenGLExtensions>\n#include <QOpenGLFunctions_2_1>\n#include <glm/glm.hpp>\n#include <iostream>\n#include <memory>\n#include \"log.hpp\"\n#include \"opengl.hpp\"\n#include \"shader.hpp\"\n#include \"util.hpp\"\n\n#define DELEGATE_GL_CONSTANT(method, constant) \\\n  unsigned int method () { return constant; }\n#define DELEGATE_GL(r, method) \\\n  r method () { return fun->method (); }\n#define DELEGATE1_GL(r, method, t1) \\\n  r method (t1 a1) { return fun->method (a1); }\n#define DELEGATE2_GL(r, method, t1, t2) \\\n  r method (t1 a1, t2 a2) { return fun->method (a1, a2); }\n#define DELEGATE3_GL(r, method, t1, t2, t3) \\\n  r method (t1 a1, t2 a2, t3 a3) { return fun->method (a1, a2, a3); }\n#define DELEGATE4_GL(r, method, t1, t2, t3, t4) \\\n  r method (t1 a1, t2 a2, t3 a3, t4 a4) { return fun->method (a1, a2, a3, a4); }\n#define DELEGATE5_GL(r, method, t1, t2, t3, t4, t5) \\\n  r method (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) { return fun->method (a1, a2, a3, a4, a5); }\n#define DELEGATE6_GL(r, method, t1, t2, t3, t4, t5, t6) \\\n  r method (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6)   \\\n  {                                                     \\\n    return fun->method (a1, a2, a3, a4, a5, a6);        \\\n  }\n\nnamespace OpenGL\n{\n  static_assert (sizeof (unsigned int) >= 4, \"type does not meet size required by OpenGL\");\n  static_assert (sizeof (int) >= 4, \"type does not meet size required by OpenGL\");\n  static_assert (sizeof (float) >= 4, \"type does not meet size required by OpenGL\");\n\n  static QOpenGLFunctions_2_1*                                  fun = nullptr;\n  static std::unique_ptr<QOpenGLExtension_EXT_geometry_shader4> gsFun;\n\n  void setDefaultFormat ()\n  {\n    QSurfaceFormat format;\n\n    format.setVersion (2, 1);\n    format.setDepthBufferSize (24);\n    format.setStencilBufferSize (1);\n    format.setProfile (QSurfaceFormat::NoProfile);\n    format.setRenderableType (QSurfaceFormat::OpenGL);\n\n    QSurfaceFormat::setDefaultFormat (format);\n  }\n\n  void initializeFunctions (bool initGeometryShader)\n  {\n    fun = QOpenGLContext::currentContext ()->versionFunctions<QOpenGLFunctions_2_1> ();\n    if (fun == nullptr)\n    {\n      DILAY_PANIC (\"could not obtain OpenGL 2.1 context\")\n    }\n    fun->initializeOpenGLFunctions ();\n\n    if (initGeometryShader)\n    {\n      const bool support =\n        QOpenGLContext::currentContext ()->hasExtension (QByteArray (\"GL_EXT_geometry_shader4\"));\n      if (support)\n      {\n        gsFun = std::make_unique<QOpenGLExtension_EXT_geometry_shader4> ();\n        if (gsFun == nullptr)\n        {\n          DILAY_PANIC (\"could not initialize GL_EXT_geometry_shader4 extension\")\n        }\n        gsFun->initializeOpenGLFunctions ();\n      }\n    }\n\n    DILAY_INFO (\"OpenGL version: %s\", fun->glGetString (GL_VERSION));\n    DILAY_INFO (\"OpenGL vendor: %s\", fun->glGetString (GL_VENDOR));\n    DILAY_INFO (\"OpenGL renderer: %s\", fun->glGetString (GL_RENDERER));\n    DILAY_INFO (\"OpenGL GLSL version: %s\", fun->glGetString (GL_SHADING_LANGUAGE_VERSION));\n    DILAY_INFO (\"OpenGL supports GL_EXT_geometry_shader4: %i\", gsFun != nullptr);\n  }\n\n  DELEGATE_GL_CONSTANT (Always, GL_ALWAYS);\n  DELEGATE_GL_CONSTANT (ArrayBuffer, GL_ARRAY_BUFFER);\n  DELEGATE_GL_CONSTANT (Back, GL_BACK);\n  DELEGATE_GL_CONSTANT (Blend, GL_BLEND);\n  DELEGATE_GL_CONSTANT (BufferSize, GL_BUFFER_SIZE);\n  DELEGATE_GL_CONSTANT (ColorBufferBit, GL_COLOR_BUFFER_BIT);\n  DELEGATE_GL_CONSTANT (CullFace, GL_CULL_FACE);\n  DELEGATE_GL_CONSTANT (CW, GL_CW);\n  DELEGATE_GL_CONSTANT (CCW, GL_CCW);\n  DELEGATE_GL_CONSTANT (Decr, GL_DECR);\n  DELEGATE_GL_CONSTANT (DecrWrap, GL_DECR_WRAP);\n  DELEGATE_GL_CONSTANT (DepthBufferBit, GL_DEPTH_BUFFER_BIT);\n  DELEGATE_GL_CONSTANT (DepthTest, GL_DEPTH_TEST);\n  DELEGATE_GL_CONSTANT (DstColor, GL_DST_COLOR);\n  DELEGATE_GL_CONSTANT (ElementArrayBuffer, GL_ELEMENT_ARRAY_BUFFER);\n  DELEGATE_GL_CONSTANT (Equal, GL_EQUAL);\n  DELEGATE_GL_CONSTANT (Fill, GL_FILL);\n  DELEGATE_GL_CONSTANT (Float, GL_FLOAT);\n  DELEGATE_GL_CONSTANT (Front, GL_FRONT);\n  DELEGATE_GL_CONSTANT (FrontAndBack, GL_FRONT_AND_BACK);\n  DELEGATE_GL_CONSTANT (FuncAdd, GL_FUNC_ADD);\n  DELEGATE_GL_CONSTANT (Greater, GL_GREATER);\n  DELEGATE_GL_CONSTANT (Incr, GL_INCR);\n  DELEGATE_GL_CONSTANT (IncrWrap, GL_INCR_WRAP);\n  DELEGATE_GL_CONSTANT (Invert, GL_INVERT);\n  DELEGATE_GL_CONSTANT (Keep, GL_KEEP);\n  DELEGATE_GL_CONSTANT (LEqual, GL_LEQUAL);\n  DELEGATE_GL_CONSTANT (Line, GL_LINE);\n  DELEGATE_GL_CONSTANT (Lines, GL_LINES);\n  DELEGATE_GL_CONSTANT (Never, GL_NEVER);\n  DELEGATE_GL_CONSTANT (PolygonOffsetFill, GL_POLYGON_OFFSET_FILL);\n  DELEGATE_GL_CONSTANT (Replace, GL_REPLACE);\n  DELEGATE_GL_CONSTANT (StaticDraw, GL_STATIC_DRAW);\n  DELEGATE_GL_CONSTANT (StencilBufferBit, GL_STENCIL_BUFFER_BIT);\n  DELEGATE_GL_CONSTANT (StencilTest, GL_STENCIL_TEST);\n  DELEGATE_GL_CONSTANT (Triangles, GL_TRIANGLES);\n  DELEGATE_GL_CONSTANT (UnsignedInt, GL_UNSIGNED_INT);\n  DELEGATE_GL_CONSTANT (Zero, GL_ZERO);\n\n  DELEGATE2_GL (void, glBindBuffer, unsigned int, unsigned int)\n  DELEGATE1_GL (void, glBlendEquation, unsigned int)\n  DELEGATE2_GL (void, glBlendFunc, unsigned int, unsigned int)\n  DELEGATE4_GL (void, glBufferData, unsigned int, unsigned int, const void*, unsigned int)\n  DELEGATE4_GL (void, glBufferSubData, unsigned int, unsigned int, unsigned int, const void*)\n  DELEGATE1_GL (void, glClear, unsigned int)\n  DELEGATE4_GL (void, glClearColor, float, float, float, float)\n  DELEGATE1_GL (void, glClearStencil, int)\n  DELEGATE4_GL (void, glColorMask, bool, bool, bool, bool)\n  DELEGATE1_GL (void, glCullFace, unsigned int)\n  DELEGATE1_GL (void, glDepthFunc, unsigned int)\n  DELEGATE1_GL (void, glDepthMask, bool)\n  DELEGATE1_GL (void, glDisable, unsigned int)\n  DELEGATE1_GL (void, glDisableVertexAttribArray, unsigned int)\n  DELEGATE4_GL (void, glDrawElements, unsigned int, unsigned int, unsigned int, const void*)\n  DELEGATE1_GL (void, glEnable, unsigned int)\n  DELEGATE1_GL (void, glEnableVertexAttribArray, unsigned int)\n  DELEGATE1_GL (void, glFrontFace, unsigned int)\n  DELEGATE2_GL (void, glGenBuffers, unsigned int, unsigned int*)\n  DELEGATE3_GL (void, glGetBufferParameteriv, unsigned int, unsigned int, int*)\n  DELEGATE2_GL (int, glGetUniformLocation, unsigned int, const char*)\n  DELEGATE1_GL (bool, glIsBuffer, unsigned int)\n  DELEGATE1_GL (bool, glIsProgram, unsigned int)\n  DELEGATE2_GL (void, glPolygonMode, unsigned int, unsigned int)\n  DELEGATE2_GL (void, glPolygonOffset, float, float)\n  DELEGATE3_GL (void, glStencilFunc, unsigned int, int, unsigned int)\n  DELEGATE3_GL (void, glStencilOp, unsigned int, unsigned int, unsigned int)\n  DELEGATE2_GL (void, glUniform1f, int, float)\n  DELEGATE4_GL (void, glUniformMatrix3fv, int, unsigned int, bool, const float*)\n  DELEGATE4_GL (void, glUniformMatrix4fv, int, unsigned int, bool, const float*)\n  DELEGATE1_GL (void, glUseProgram, unsigned int)\n  DELEGATE6_GL (void, glVertexAttribPointer, unsigned int, int, unsigned int, bool, unsigned int,\n                const void*)\n  DELEGATE4_GL (void, glViewport, unsigned int, unsigned int, unsigned int, unsigned int)\n\n  bool hasGeometryShader () { return bool(gsFun); }\n\n  void glUniformVec3 (unsigned int id, const glm::vec3& v) { fun->glUniform3f (id, v.x, v.y, v.z); }\n  void glUniformVec4 (unsigned int id, const glm::vec4& v)\n  {\n    fun->glUniform4f (id, v.x, v.y, v.z, v.w);\n  }\n\n  void safeDeleteBuffer (unsigned int& id)\n  {\n    if (id > 0)\n    {\n      fun->glDeleteBuffers (1, &id);\n    }\n    id = 0;\n  }\n\n  void safeDeleteShader (unsigned int& id)\n  {\n    if (id > 0 && fun->glIsShader (id) == GL_TRUE)\n    {\n      fun->glDeleteShader (id);\n    }\n    id = 0;\n  }\n\n  void safeDeleteProgram (unsigned int& id)\n  {\n    if (id > 0 && fun->glIsProgram (id) == GL_TRUE)\n    {\n      GLsizei numShaders;\n      GLuint  shaderIds[2];\n\n      fun->glGetAttachedShaders (id, 2, &numShaders, shaderIds);\n\n      for (GLsizei i = 0; i < numShaders; i++)\n      {\n        OpenGL::safeDeleteShader (shaderIds[i]);\n      }\n      fun->glDeleteProgram (id);\n    }\n    id = 0;\n  }\n\n  unsigned int loadProgram (const char* vertexShader, const char* fragmentShader,\n                            bool loadGeometryShader)\n  {\n    auto showInfoLog = [](GLuint id) {\n      const int maxLogLength = 1000;\n      char      logBuffer[maxLogLength];\n      GLsizei   logLength;\n      fun->glGetShaderInfoLog (id, maxLogLength, &logLength, logBuffer);\n      if (logLength > 0)\n      {\n        DILAY_WARN (\"%s\", logBuffer)\n      }\n    };\n\n    auto compileShader = [&showInfoLog](GLenum shaderType, const char* shaderSource) -> GLuint {\n      GLuint shaderId = fun->glCreateShader (shaderType);\n      fun->glShaderSource (shaderId, 1, &shaderSource, NULL);\n      fun->glCompileShader (shaderId);\n\n      GLint status;\n      fun->glGetShaderiv (shaderId, GL_COMPILE_STATUS, &status);\n      if (status == GL_FALSE)\n      {\n        showInfoLog (shaderId);\n        DILAY_PANIC (\"can not compile shader: see info log above\")\n      }\n      return shaderId;\n    };\n\n    GLuint programId = fun->glCreateProgram ();\n    GLuint vsId = compileShader (GL_VERTEX_SHADER, vertexShader);\n    GLuint fsId = compileShader (GL_FRAGMENT_SHADER, fragmentShader);\n    GLuint gmId = 0;\n\n    fun->glAttachShader (programId, vsId);\n    fun->glAttachShader (programId, fsId);\n\n    if (loadGeometryShader)\n    {\n      assert (OpenGL::hasGeometryShader ());\n\n      gmId = compileShader (GL_GEOMETRY_SHADER_EXT, Shader::geometryShader ());\n      fun->glAttachShader (programId, gmId);\n\n      gsFun->glProgramParameteriEXT (programId, GL_GEOMETRY_VERTICES_OUT_EXT, 3);\n      gsFun->glProgramParameteriEXT (programId, GL_GEOMETRY_INPUT_TYPE_EXT, GL_TRIANGLES);\n      gsFun->glProgramParameteriEXT (programId, GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP);\n    }\n\n    fun->glBindAttribLocation (programId, OpenGL::PositionIndex, \"position\");\n    fun->glBindAttribLocation (programId, OpenGL::NormalIndex, \"normal\");\n\n    fun->glLinkProgram (programId);\n\n    GLint status;\n    fun->glGetProgramiv (programId, GL_LINK_STATUS, &status);\n\n    if (status == GL_FALSE)\n    {\n      showInfoLog (programId);\n      OpenGL::safeDeleteProgram (programId);\n      DILAY_PANIC (\"can not link shader program: see info log above\")\n    }\n    OpenGL::safeDeleteShader (vsId);\n    OpenGL::safeDeleteShader (fsId);\n    OpenGL::safeDeleteShader (gmId);\n    return programId;\n  }\n\n  void clearError () { fun->glGetError (); }\n\n  void printError ()\n  {\n    const unsigned int glError = fun->glGetError ();\n\n    switch (glError)\n    {\n      case GL_NO_ERROR:\n        std::cout << \"GL_NO_ERROR\\n\";\n        break;\n      case GL_INVALID_ENUM:\n        std::cout << \"GL_INVALID_ENUM\\n\";\n        break;\n      case GL_INVALID_VALUE:\n        std::cout << \"GL_INVALID_VALUE\\n\";\n        break;\n      case GL_INVALID_OPERATION:\n        std::cout << \"GL_INVALID_OPERATION\\n\";\n        break;\n      case GL_INVALID_FRAMEBUFFER_OPERATION:\n        std::cout << \"GL_INVALID_FRAMEBUFFER_OPERATION\\n\";\n        break;\n      case GL_OUT_OF_MEMORY:\n        std::cout << \"GL_OUT_OF_MEMORY\\n\";\n        break;\n      case GL_STACK_UNDERFLOW:\n        std::cout << \"GL_STACK_UNDERFLOW\\n\";\n        break;\n      case GL_STACK_OVERFLOW:\n        std::cout << \"GL_STACK_OVERFLOW\\n\";\n        break;\n      default:\n        std::cout << \"Unknown OpenGL error '\" << glError << \"'\\n\";\n        break;\n    }\n  }\n}\n"
  },
  {
    "path": "lib/src/opengl.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_OPENGL\n#define DILAY_OPENGL\n\n#include <glm/fwd.hpp>\n#include <string>\n\nnamespace OpenGL\n{\n  // QT related\n  void setDefaultFormat ();\n  void initializeFunctions (bool);\n\n  // wrappers\n  unsigned int Always ();\n  unsigned int ArrayBuffer ();\n  unsigned int Back ();\n  unsigned int Blend ();\n  unsigned int BufferSize ();\n  unsigned int ColorBufferBit ();\n  unsigned int CullFace ();\n  unsigned int CW ();\n  unsigned int CCW ();\n  unsigned int Decr ();\n  unsigned int DecrWrap ();\n  unsigned int DepthBufferBit ();\n  unsigned int DepthTest ();\n  unsigned int DstColor ();\n  unsigned int ElementArrayBuffer ();\n  unsigned int Equal ();\n  unsigned int Fill ();\n  unsigned int Float ();\n  unsigned int Front ();\n  unsigned int FrontAndBack ();\n  unsigned int FuncAdd ();\n  unsigned int Greater ();\n  unsigned int Incr ();\n  unsigned int IncrWrap ();\n  unsigned int Invert ();\n  unsigned int Keep ();\n  unsigned int LEqual ();\n  unsigned int Line ();\n  unsigned int Lines ();\n  unsigned int Never ();\n  unsigned int PolygonOffsetFill ();\n  unsigned int Replace ();\n  unsigned int StaticDraw ();\n  unsigned int StencilBufferBit ();\n  unsigned int StencilTest ();\n  unsigned int Triangles ();\n  unsigned int UnsignedInt ();\n  unsigned int Zero ();\n\n  void glBindBuffer (unsigned int, unsigned int);\n  void glBlendEquation (unsigned int);\n  void glBlendFunc (unsigned int, unsigned);\n  void glBufferData (unsigned int, unsigned int, const void*, unsigned int);\n  void glBufferSubData (unsigned int, unsigned int, unsigned int, const void*);\n  void glClear (unsigned int);\n  void glClearColor (float, float, float, float);\n  void glClearStencil (int);\n  void glColorMask (bool, bool, bool, bool);\n  void glCullFace (unsigned int);\n  void glDepthFunc (unsigned int);\n  void glDepthMask (bool);\n  void glDisable (unsigned int);\n  void glDisableVertexAttribArray (unsigned int);\n  void glDrawElements (unsigned int, unsigned int, unsigned int, const void*);\n  void glEnable (unsigned int);\n  void glEnableVertexAttribArray (unsigned int);\n  void glFrontFace (unsigned int);\n  void glGenBuffers (unsigned int, unsigned int*);\n  void glGetBufferParameteriv (unsigned int, unsigned int, int*);\n  int  glGetUniformLocation (unsigned int, const char*);\n  bool glIsBuffer (unsigned int);\n  bool glIsProgram (unsigned int);\n  void glPolygonMode (unsigned int, unsigned int);\n  void glPolygonOffset (float, float);\n  void glStencilFunc (unsigned int, int, unsigned int);\n  void glStencilOp (unsigned int, unsigned int, unsigned int);\n  void glUniform1f (int, float);\n  void glUniformMatrix3fv (int, unsigned int, bool, const float*);\n  void glUniformMatrix4fv (int, unsigned int, bool, const float*);\n  void glUseProgram (unsigned int);\n  void glVertexAttribPointer (unsigned int, int, unsigned int, bool, unsigned int, const void*);\n  void glViewport (unsigned int, unsigned int, unsigned int, unsigned int);\n\n  // utilities\n  enum VertexAttributIndex\n  {\n    PositionIndex = 0,\n    NormalIndex = 1\n  };\n\n  bool         hasGeometryShader ();\n  void         glUniformVec3 (unsigned int, const glm::vec3&);\n  void         glUniformVec4 (unsigned int, const glm::vec4&);\n  void         safeDeleteBuffer (unsigned int&);\n  void         safeDeleteShader (unsigned int&);\n  void         safeDeleteProgram (unsigned int&);\n  unsigned int loadProgram (const char*, const char*, bool);\n  void         clearError ();\n  void         printError ();\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/primitive/aabox.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"primitive/aabox.hpp\"\n\nPrimAABox::PrimAABox (const glm::vec3& min, const glm::vec3& max)\n  : _minimum (min)\n  , _maximum (max)\n  , _center ((min + max) * 0.5f)\n{\n}\n\nPrimAABox::PrimAABox (const glm::vec3& pos, float xW, float yW, float zW)\n  : PrimAABox (pos - glm::vec3 (xW * 0.5f, yW * 0.5f, zW * 0.5f),\n               pos + glm::vec3 (xW * 0.5f, yW * 0.5f, zW * 0.5f))\n{\n}\n\nPrimAABox::PrimAABox (const glm::vec3& pos, float w)\n  : PrimAABox (pos, w, w, w)\n{\n}\n\nglm::vec3 PrimAABox::halfWidth () const { return (this->_maximum - this->_minimum) * 0.5f; }\n\nfloat PrimAABox::maxDimExtent () const\n{\n  const glm::vec3 extent = this->_maximum - this->_minimum;\n  return glm::max (glm::max (extent.x, extent.y), extent.z);\n}\n\nbool PrimAABox::contains (const PrimAABox& box) const\n{\n  return glm::all (glm::lessThanEqual (this->_minimum, box._minimum)) &&\n         glm::all (glm::greaterThanEqual (this->_maximum, box._maximum));\n}\n"
  },
  {
    "path": "lib/src/primitive/aabox.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_PRIMITIVE_AABOX\n#define DILAY_PRIMITIVE_AABOX\n\n#include <glm/glm.hpp>\n\nclass PrimAABox\n{\npublic:\n  PrimAABox (const glm::vec3&, const glm::vec3&);\n  PrimAABox (const glm::vec3&, float, float, float);\n  PrimAABox (const glm::vec3&, float);\n\n  const glm::vec3& maximum () const { return this->_maximum; }\n  const glm::vec3& minimum () const { return this->_minimum; }\n  const glm::vec3& center () const { return this->_center; }\n\n  glm::vec3 halfWidth () const;\n  float     maxDimExtent () const;\n  bool      contains (const PrimAABox&) const;\n\nprivate:\n  const glm::vec3 _minimum;\n  const glm::vec3 _maximum;\n  const glm::vec3 _center;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/primitive/cone-sphere.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/gtc/constants.hpp>\n#include \"primitive/cone-sphere.hpp\"\n#include \"primitive/cone.hpp\"\n#include \"util.hpp\"\n\nPrimConeSphere::PrimConeSphere (const PrimSphere& s1, const PrimSphere& s2)\n  : _sphere1 (s1.radius () > s2.radius () ? s1 : s2)\n  , _sphere2 (s1.radius () > s2.radius () ? s2 : s1)\n  , _length (glm::distance (s1.center (), s2.center ()))\n  , _direction ((this->_sphere2.center () - this->_sphere1.center ()) / glm::vec3 (this->_length))\n  , _alpha (glm::half_pi<float> () - glm::acos (this->delta () / this->_length))\n  , _sinAlpha (glm::sin (this->_alpha))\n  , _cosAlpha (glm::cos (this->_alpha))\n{\n}\n\nfloat PrimConeSphere::delta () const { return this->_sphere1.radius () - this->_sphere2.radius (); }\n\nbool PrimConeSphere::sameRadii () const { return Util::almostEqual (this->delta (), 0.0f); }\n\nbool PrimConeSphere::hasCone () const { return this->_length > this->delta (); }\n\nfloat PrimConeSphere::coneSideLength () const\n{\n  assert (this->hasCone ());\n\n  return glm::sqrt ((this->_length * this->_length) - (this->delta () * this->delta ()));\n}\n\nPrimCone PrimConeSphere::toCone () const\n{\n  assert (this->hasCone ());\n\n  const float s = this->coneSideLength ();\n  const float h1 = this->_sphere1.radius () * this->delta () / this->_length;\n  const float h2 = this->_sphere2.radius () * this->delta () / this->_length;\n  const float r1c = this->_sphere1.radius () * s / this->_length;\n  const float r2c = this->_sphere2.radius () * s / this->_length;\n\n  return PrimCone (this->_sphere2.center () + (this->_direction * h2), r2c,\n                   this->_sphere1.center () + (this->_direction * h1), r1c);\n}\n"
  },
  {
    "path": "lib/src/primitive/cone-sphere.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_PRIMITIVE_CONE_SPHERE\n#define DILAY_PRIMITIVE_CONE_SPHERE\n\n#include <glm/glm.hpp>\n#include \"primitive/sphere.hpp\"\n\nclass PrimCone;\n\nclass PrimConeSphere\n{\npublic:\n  PrimConeSphere (const PrimSphere&, const PrimSphere&);\n\n  const PrimSphere& sphere1 () const { return this->_sphere1; }\n\n  const PrimSphere& sphere2 () const { return this->_sphere2; }\n\n  float length () const { return this->_length; }\n\n  const glm::vec3& direction () const { return this->_direction; }\n\n  float alpha () const { return this->_alpha; }\n\n  float sinAlpha () const { return this->_sinAlpha; }\n\n  float cosAlpha () const { return this->_cosAlpha; }\n\n  float    delta () const;\n  bool     sameRadii () const;\n  bool     hasCone () const;\n  float    coneSideLength () const;\n  PrimCone toCone () const;\n\nprivate:\n  const PrimSphere _sphere1;\n  const PrimSphere _sphere2;\n  const float      _length;\n  const glm::vec3  _direction;\n  const float      _alpha;\n  const float      _sinAlpha;\n  const float      _cosAlpha;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/primitive/cone.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"primitive/cone.hpp\"\n#include \"util.hpp\"\n\nPrimCone::PrimCone (const glm::vec3& c1, float r1, const glm::vec3& c2, float r2, float l)\n  : _center1 (r1 > r2 ? c1 : c2)\n  , _radius1 (r1 > r2 ? r1 : r2)\n  , _center2 (r1 > r2 ? c2 : c1)\n  , _radius2 (r1 > r2 ? r2 : r1)\n  , _length (l)\n  , _direction ((this->_center2 - this->_center1) / glm::vec3 (l))\n  , _isCylinder (Util::almostEqual (r1, r2))\n  , _apex (this->_isCylinder\n             ? glm::vec3 (0.0f)\n             : this->_center1 + (this->_radius1 * (this->_center2 - this->_center1) /\n                                 (this->_radius1 - this->_radius2)))\n  , _alpha (glm::atan ((this->_radius1 - this->_radius2) / l))\n  , _sinAlpha (glm::sin (this->_alpha))\n  , _cosAlpha (glm::cos (this->_alpha))\n{\n}\n\nPrimCone::PrimCone (const glm::vec3& c1, float r1, const glm::vec3& c2, float r2)\n  : PrimCone (c1, r1, c2, r2, glm::distance (c1, c2))\n{\n}\n\nglm::vec3 PrimCone::projPointAt (float t) const { return this->_center1 + (t * this->_direction); }\n\nglm::vec3 PrimCone::normalAt (const glm::vec3& pointAt, float tCone) const\n{\n  const glm::vec3 projP = this->projPointAt (tCone);\n  const glm::vec3 diff = glm::normalize (pointAt - projP);\n  const glm::vec3 slope =\n    (this->_center2 + (this->_radius2 * diff)) - (this->_center1 + (this->_radius1 * diff));\n  const glm::vec3 tang = glm::cross (diff, this->_direction);\n\n  return glm::normalize (glm::cross (slope, tang));\n}\n"
  },
  {
    "path": "lib/src/primitive/cone.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_PRIMITIVE_CONE\n#define DILAY_PRIMITIVE_CONE\n\n#include <glm/glm.hpp>\n\nclass PrimCone\n{\npublic:\n  PrimCone (const glm::vec3&, float, const glm::vec3&, float);\n  PrimCone (const glm::vec3&, float, const glm::vec3&, float, float);\n\n  const glm::vec3& center1 () const { return this->_center1; }\n  float            radius1 () const { return this->_radius1; }\n  const glm::vec3& center2 () const { return this->_center2; }\n  float            radius2 () const { return this->_radius2; }\n  float            length () const { return this->_length; }\n  const glm::vec3& direction () const { return this->_direction; }\n  bool             isCylinder () const { return this->_isCylinder; }\n  const glm::vec3& apex () const { return this->_apex; }\n  float            alpha () const { return this->_alpha; }\n  float            sinAlpha () const { return this->_sinAlpha; }\n  float            cosAlpha () const { return this->_cosAlpha; }\n\n  glm::vec3 projPointAt (float) const;\n  glm::vec3 normalAt (const glm::vec3&, float) const;\n\nprivate:\n  const glm::vec3 _center1;\n  const float     _radius1;\n  const glm::vec3 _center2;\n  const float     _radius2;\n  const float     _length;\n  const glm::vec3 _direction;\n  const bool      _isCylinder;\n  const glm::vec3 _apex;\n  const float     _alpha;\n  const float     _sinAlpha;\n  const float     _cosAlpha;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/primitive/cylinder.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"primitive/cone.hpp\"\n#include \"primitive/cylinder.hpp\"\n#include \"util.hpp\"\n\nPrimCylinder::PrimCylinder (const glm::vec3& c1, const glm::vec3& c2, float r, float l)\n  : _center1 (c1)\n  , _center2 (c2)\n  , _radius (r)\n  , _length (l)\n  , _direction ((c2 - c1) / glm::vec3 (l))\n{\n}\n\nPrimCylinder::PrimCylinder (const glm::vec3& c1, const glm::vec3& c2, float r)\n  : PrimCylinder (c1, c2, r, glm::distance (c1, c2))\n{\n}\n\nPrimCylinder::PrimCylinder (const PrimCone& cone)\n  : _center1 (cone.center1 ())\n  , _center2 (cone.center2 ())\n  , _radius (cone.radius1 ())\n  , _length (cone.length ())\n  , _direction (cone.direction ())\n{\n  assert (cone.isCylinder ());\n}\n"
  },
  {
    "path": "lib/src/primitive/cylinder.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_PRIMITIVE_CYLINDER\n#define DILAY_PRIMITIVE_CYLINDER\n\n#include <glm/glm.hpp>\n\nclass PrimCone;\n\nclass PrimCylinder\n{\npublic:\n  PrimCylinder (const glm::vec3&, const glm::vec3&, float);\n  PrimCylinder (const glm::vec3&, const glm::vec3&, float, float);\n  PrimCylinder (const PrimCone&);\n\n  const glm::vec3& center1 () const { return this->_center1; }\n  const glm::vec3& center2 () const { return this->_center2; }\n  float            radius () const { return this->_radius; }\n  float            length () const { return this->_length; }\n  const glm::vec3& direction () const { return this->_direction; }\n\nprivate:\n  const glm::vec3 _center1;\n  const glm::vec3 _center2;\n  const float     _radius;\n  const float     _length;\n  const glm::vec3 _direction;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/primitive/plane.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"primitive/plane.hpp\"\n#include \"util.hpp\"\n\nPrimPlane::PrimPlane (const glm::vec3& p, const glm::vec3& n)\n  : _point (p)\n{\n  this->normal (n);\n}\n\nvoid PrimPlane::normal (const glm::vec3& n)\n{\n  this->_normal = glm::normalize (n);\n  this->_u = glm::normalize (Util::orthogonal (this->_normal));\n  this->_v = glm::normalize (glm::cross (this->_normal, this->_u));\n}\n\nfloat PrimPlane::distance (const glm::vec3& p) const\n{\n  return glm::dot (this->_normal, p - this->_point);\n}\n\nfloat PrimPlane::absDistance (const glm::vec3& p) const { return glm::abs (this->distance (p)); }\n\nbool PrimPlane::onPlane (const glm::vec3& p) const\n{\n  return this->absDistance (p) < Util::epsilon ();\n}\n\nglm::vec3 PrimPlane::project (const glm::vec3& p) const\n{\n  return p - (this->_normal * this->distance (p));\n}\n\nglm::vec3 PrimPlane::project (const glm::vec2& p) const\n{\n  return this->_point + (this->_u * p.x) + (this->_v * p.y);\n}\n\nglm::vec2 PrimPlane::project2d (const glm::vec3& p) const\n{\n  const glm::vec3 proj = this->project (p) - this->_point;\n\n  return glm::vec2 (glm::dot (this->_u, proj), glm::dot (this->_v, proj));\n}\n\nglm::vec3 PrimPlane::projectDirection (const glm::vec3& d) const\n{\n  return this->project (d + this->_point) - this->_point;\n}\n\nglm::vec3 PrimPlane::mirror (const glm::vec3& p) const\n{\n  return p - (2.0f * this->_normal * this->distance (p));\n}\n\nglm::vec3 PrimPlane::mirrorDirection (const glm::vec3& d) const\n{\n  return this->mirror (d + this->_point) - this->_point;\n}\n"
  },
  {
    "path": "lib/src/primitive/plane.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_PRIMITIVE_PLANE\n#define DILAY_PRIMITIVE_PLANE\n\n#include <glm/glm.hpp>\n#include \"macro.hpp\"\n\nclass PrimPlane\n{\npublic:\n  PrimPlane (const glm::vec3&, const glm::vec3&);\n\n  float     distance (const glm::vec3&) const;\n  float     absDistance (const glm::vec3&) const;\n  bool      onPlane (const glm::vec3&) const;\n  glm::vec3 project (const glm::vec3&) const;\n  glm::vec3 project (const glm::vec2&) const;\n  glm::vec2 project2d (const glm::vec3&) const;\n  glm::vec3 projectDirection (const glm::vec3&) const;\n  glm::vec3 mirror (const glm::vec3&) const;\n  glm::vec3 mirrorDirection (const glm::vec3&) const;\n\n  MEMBER_REF_GETTER_SETTER (glm::vec3, point)\n  MEMBER_REF_GETTER_EXPLICIT_SETTER (glm::vec3, normal)\n  MEMBER_REF_GETTER (glm::vec3, u)\n  MEMBER_REF_GETTER (glm::vec3, v)\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/primitive/ray.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"primitive/ray.hpp\"\n#include \"util.hpp\"\n\nPrimRay::PrimRay (bool l, const glm::vec3& o, const glm::vec3& d)\n  : _isLine (l)\n  , _origin (o)\n  , _direction (glm::normalize (d))\n{\n}\n\nPrimRay::PrimRay (const glm::vec3& o, const glm::vec3& d)\n  : PrimRay (false, o, d)\n{\n}\n\nglm::vec3 PrimRay::pointAt (float t) const\n{\n  assert (t >= 0.0f || this->_isLine);\n  return this->_origin + (this->_direction * glm::vec3 (t));\n}\n\nfloat PrimRay::distance (const glm::vec3& p) const\n{\n  const float t = glm::dot (this->_direction, p - this->_origin);\n\n  return t >= 0.0f || this->_isLine ? glm::distance (p, this->pointAt (t))\n                                    : glm::distance (p, this->_origin);\n}\n\nbool PrimRay::onRay (const glm::vec3& p) const { return this->distance (p) < Util::epsilon (); }\n"
  },
  {
    "path": "lib/src/primitive/ray.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_PRIMITIVE_RAY\n#define DILAY_PRIMITIVE_RAY\n\n#include <glm/glm.hpp>\n\nclass PrimRay\n{\npublic:\n  PrimRay (bool, const glm::vec3&, const glm::vec3&);\n  PrimRay (const glm::vec3&, const glm::vec3&);\n\n  bool             isLine () const { return this->_isLine; }\n  const glm::vec3& origin () const { return this->_origin; }\n  const glm::vec3& direction () const { return this->_direction; }\n\n  void origin (const glm::vec3& o) { this->_origin = o; }\n\n  glm::vec3 pointAt (float) const;\n  float     distance (const glm::vec3&) const;\n  bool      onRay (const glm::vec3&) const;\n\nprivate:\n  const bool      _isLine;\n  glm::vec3       _origin;\n  const glm::vec3 _direction;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/primitive/sphere.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/gtx/norm.hpp>\n#include \"primitive/aabox.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"util.hpp\"\n\nPrimSphere::PrimSphere (const glm::vec3& o, float r)\n  : _center (o)\n  , _radius (r)\n{\n}\n\nbool PrimSphere::contains (const glm::vec3& p) const\n{\n  return glm::distance2 (this->_center, p) <= (this->_radius * this->_radius);\n}\n\nbool PrimSphere::contains (const PrimAABox& aabox) const\n{\n  return this->contains (aabox.minimum ()) && this->contains (aabox.maximum ());\n}\n\nbool PrimSphere::contains (const PrimTriangle& tri) const\n{\n  return this->contains (tri.vertex1 ()) && this->contains (tri.vertex2 ()) &&\n         this->contains (tri.vertex3 ());\n}\n"
  },
  {
    "path": "lib/src/primitive/sphere.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_PRIMITIVE_SPHERE\n#define DILAY_PRIMITIVE_SPHERE\n\n#include <glm/glm.hpp>\n\nclass PrimAABox;\nclass PrimTriangle;\n\nclass PrimSphere\n{\npublic:\n  PrimSphere (const glm::vec3&, float);\n\n  const glm::vec3& center () const { return this->_center; }\n  float            radius () const { return this->_radius; }\n\n  void center (const glm::vec3& c) { this->_center = c; }\n  void radius (float r) { this->_radius = r; }\n\n  bool contains (const glm::vec3&) const;\n  bool contains (const PrimAABox&) const;\n  bool contains (const PrimTriangle&) const;\n\nprivate:\n  glm::vec3 _center;\n  float     _radius;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/primitive/triangle.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/gtx/norm.hpp>\n#include \"primitive/triangle.hpp\"\n#include \"util.hpp\"\n\nPrimTriangle::PrimTriangle (const glm::vec3& v1, const glm::vec3& v2, const glm::vec3& v3)\n  : _vertex1 (v1)\n  , _vertex2 (v2)\n  , _vertex3 (v3)\n{\n}\n\nglm::vec3 PrimTriangle::cross () const\n{\n  return glm::cross (this->_vertex2 - this->_vertex1, this->_vertex3 - this->_vertex1);\n}\n\nglm::vec3 PrimTriangle::normal () const\n{\n  const glm::vec3 c = this->cross ();\n  const float     l = glm::length (c);\n\n  return l > 0.0f ? (c / l) : glm::vec3 (0.0f);\n}\n\nglm::vec3 PrimTriangle::center () const\n{\n  return (this->_vertex1 + this->_vertex2 + this->_vertex3) / glm::vec3 (3.0f);\n}\n\nglm::vec3 PrimTriangle::minimum () const\n{\n  return glm::min (glm::min (this->_vertex1, this->_vertex2), this->_vertex3);\n}\n\nglm::vec3 PrimTriangle::maximum () const\n{\n  return glm::max (glm::max (this->_vertex1, this->_vertex2), this->_vertex3);\n}\n\nfloat PrimTriangle::maxExtent () const { return glm::length (this->maximum () - this->minimum ()); }\n\nfloat PrimTriangle::maxDimExtent () const\n{\n  const glm::vec3 extent = this->maximum () - this->minimum ();\n  return glm::max (glm::max (extent.x, extent.y), extent.z);\n}\n\nfloat PrimTriangle::incircleRadiusSqr () const\n{\n  const float a = glm::distance (this->_vertex1, this->_vertex2);\n  const float b = glm::distance (this->_vertex2, this->_vertex3);\n  const float c = glm::distance (this->_vertex1, this->_vertex3);\n  const float s = 0.5f * (a + b + c);\n  return (s - a) * (s - b) * (s - c) / s;\n}\n\nfloat PrimTriangle::longestEdgeSqr () const\n{\n  return glm::max (glm::max (glm::distance2 (this->_vertex1, this->_vertex2),\n                             glm::distance2 (this->_vertex2, this->_vertex3)),\n                   glm::distance2 (this->_vertex1, this->_vertex3));\n}\n"
  },
  {
    "path": "lib/src/primitive/triangle.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_PRIMITIVE_TRIANGLE\n#define DILAY_PRIMITIVE_TRIANGLE\n\n#include <glm/glm.hpp>\n\nclass PrimTriangle\n{\npublic:\n  PrimTriangle (const glm::vec3&, const glm::vec3&, const glm::vec3&);\n\n  const glm::vec3& vertex1 () const { return this->_vertex1; }\n  const glm::vec3& vertex2 () const { return this->_vertex2; }\n  const glm::vec3& vertex3 () const { return this->_vertex3; }\n\n  glm::vec3 cross () const;\n  glm::vec3 normal () const;\n  glm::vec3 center () const;\n  glm::vec3 minimum () const;\n  glm::vec3 maximum () const;\n  float     maxExtent () const;\n  float     maxDimExtent () const;\n  float     incircleRadiusSqr () const;\n  float     longestEdgeSqr () const;\n\nprivate:\n  const glm::vec3& _vertex1;\n  const glm::vec3& _vertex2;\n  const glm::vec3& _vertex3;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/render-mode.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <cstdlib>\n#include \"render-mode.hpp\"\n#include \"shader.hpp\"\n#include \"util.hpp\"\n\nRenderMode::RenderMode ()\n{\n  this->smoothShading (true);\n  this->renderWireframe (false);\n  this->cameraRotationOnly (false);\n  this->noDepthTest (false);\n}\n\nRenderMode::RenderMode (const RenderMode& other)\n  : flags (other.flags)\n{\n}\n\nbool RenderMode::smoothShading () const { return this->flags.get<0> (); }\n\nbool RenderMode::flatShading () const { return this->flags.get<1> (); }\n\nbool RenderMode::constantShading () const { return this->flags.get<2> (); }\n\nbool RenderMode::renderWireframe () const { return this->flags.get<3> (); }\n\nbool RenderMode::cameraRotationOnly () const { return this->flags.get<4> (); }\n\nbool RenderMode::noDepthTest () const { return this->flags.get<5> (); }\n\nconst char* RenderMode::vertexShader () const\n{\n  if (this->smoothShading ())\n  {\n    return Shader::smoothVertexShader ();\n  }\n  else if (this->flatShading ())\n  {\n    return Shader::flatVertexShader ();\n  }\n  else if (this->constantShading ())\n  {\n    return Shader::constantVertexShader ();\n  }\n  else\n  {\n    DILAY_IMPOSSIBLE\n  }\n}\n\nconst char* RenderMode::fragmentShader () const\n{\n  if (this->smoothShading ())\n  {\n    return this->renderWireframe () ? Shader::smoothWireframeFragmentShader ()\n                                    : Shader::smoothFragmentShader ();\n  }\n  else if (this->flatShading ())\n  {\n    return this->renderWireframe () ? Shader::flatWireframeFragmentShader ()\n                                    : Shader::flatFragmentShader ();\n  }\n  else if (this->constantShading ())\n  {\n    return this->renderWireframe () ? Shader::constantWireframeFragmentShader ()\n                                    : Shader::constantFragmentShader ();\n  }\n  else\n  {\n    DILAY_IMPOSSIBLE\n  }\n}\n\nvoid RenderMode::smoothShading (bool v)\n{\n  this->flags.set<0> (v);\n  if (v)\n  {\n    this->flags.set<1> (false);\n    this->flags.set<2> (false);\n  }\n}\n\nvoid RenderMode::flatShading (bool v)\n{\n  this->flags.set<1> (v);\n  if (v)\n  {\n    this->flags.set<0> (false);\n    this->flags.set<2> (false);\n  }\n}\n\nvoid RenderMode::constantShading (bool v)\n{\n  this->flags.set<2> (v);\n  if (v)\n  {\n    this->flags.set<0> (false);\n    this->flags.set<1> (false);\n  }\n}\n\nvoid RenderMode::renderWireframe (bool v) { this->flags.set<3> (v); }\n\nvoid RenderMode::cameraRotationOnly (bool v) { this->flags.set<4> (v); }\n\nvoid RenderMode::noDepthTest (bool v) { this->flags.set<5> (v); }\n"
  },
  {
    "path": "lib/src/render-mode.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_RENDER_MODE\n#define DILAY_RENDER_MODE\n\n#include \"bitset.hpp\"\n\nclass RenderMode\n{\npublic:\n  RenderMode ();\n  RenderMode (const RenderMode&);\n\n  bool        smoothShading () const;\n  bool        flatShading () const;\n  bool        constantShading () const;\n  bool        renderWireframe () const;\n  bool        cameraRotationOnly () const;\n  bool        noDepthTest () const;\n  const char* vertexShader () const;\n  const char* fragmentShader () const;\n\n  void smoothShading (bool);\n  void flatShading (bool);\n  void constantShading (bool);\n  void renderWireframe (bool);\n  void cameraRotationOnly (bool);\n  void noDepthTest (bool);\n\nprivate:\n  Bitset<unsigned int> flags;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/renderer.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"color.hpp\"\n#include \"config.hpp\"\n#include \"opengl.hpp\"\n#include \"render-mode.hpp\"\n#include \"renderer.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  const unsigned int numLights = 2;\n\n  struct LightIds\n  {\n    int directionId;\n    int colorId;\n    int irradianceId;\n\n    LightIds ()\n      : directionId (0)\n      , colorId (0)\n      , irradianceId (0)\n    {\n    }\n  };\n\n  struct ShaderIds\n  {\n    unsigned int programId;\n    int          modelId;\n    int          modelNormalId;\n    int          viewId;\n    int          projectionId;\n    int          colorId;\n    int          wireframeColorId;\n    int          eyePointId;\n    int          barycentricId;\n    LightIds     lightIds[numLights];\n\n    ShaderIds ()\n      : programId (0)\n      , modelId (0)\n      , modelNormalId (0)\n      , viewId (0)\n      , projectionId (0)\n      , colorId (0)\n      , wireframeColorId (0)\n      , eyePointId (0)\n      , barycentricId (0)\n    {\n    }\n  };\n\n  struct GlobalLightUniforms\n  {\n    glm::vec3 direction;\n    Color     color;\n    float     irradiance;\n  };\n\n  struct GlobalUniforms\n  {\n    GlobalLightUniforms lightUniforms[numLights];\n    glm::vec3           eyePoint;\n  };\n};\n\nstruct Renderer::Impl\n{\n  static const unsigned int numShaders = 6;\n\n  ShaderIds      shaderIds[Impl::numShaders];\n  ShaderIds*     activeShaderIndex;\n  GlobalUniforms globalUniforms;\n  Color          clearColor;\n\n  Impl (const Config& config)\n    : activeShaderIndex (nullptr)\n  {\n    this->runFromConfig (config);\n  }\n\n  ~Impl ()\n  {\n    for (unsigned int i = 0; i < Impl::numShaders; i++)\n    {\n      OpenGL::safeDeleteProgram (this->shaderIds[i].programId);\n    }\n  }\n\n  void setupRendering ()\n  {\n    OpenGL::glClearColor (this->clearColor.r (), this->clearColor.g (), this->clearColor.b (),\n                          0.0f);\n    OpenGL::glClearStencil (0);\n    OpenGL::glFrontFace (OpenGL::CCW ());\n    OpenGL::glEnable (OpenGL::CullFace ());\n    OpenGL::glCullFace (OpenGL::Back ());\n    OpenGL::glEnable (OpenGL::DepthTest ());\n    OpenGL::glDepthFunc (OpenGL::LEqual ());\n    OpenGL::glClear (OpenGL::ColorBufferBit () | OpenGL::DepthBufferBit ());\n  }\n\n  void shutdownRendering ()\n  {\n    OpenGL::glDisable (OpenGL::DepthTest ());\n    OpenGL::glDisable (OpenGL::CullFace ());\n  }\n\n  unsigned int shaderIndex (const RenderMode& renderMode)\n  {\n    if (renderMode.smoothShading ())\n    {\n      return renderMode.renderWireframe () ? 0 : 1;\n    }\n    else if (renderMode.flatShading ())\n    {\n      return renderMode.renderWireframe () ? 2 : 3;\n    }\n    else if (renderMode.constantShading ())\n    {\n      return renderMode.renderWireframe () ? 4 : 5;\n    }\n    else\n    {\n      DILAY_IMPOSSIBLE\n    }\n  }\n\n  void initalizeProgram (const RenderMode& renderMode)\n  {\n    assert (renderMode.renderWireframe () == false || OpenGL::hasGeometryShader ());\n\n    const unsigned int id = OpenGL::loadProgram (\n      renderMode.vertexShader (), renderMode.fragmentShader (), renderMode.renderWireframe ());\n\n    unsigned int index = this->shaderIndex (renderMode);\n    assert (this->shaderIds[index].programId == 0);\n\n    ShaderIds* s = &this->shaderIds[index];\n\n    s->programId = id;\n    s->modelId = OpenGL::glGetUniformLocation (id, \"model\");\n    s->modelNormalId = OpenGL::glGetUniformLocation (id, \"modelNormal\");\n    s->viewId = OpenGL::glGetUniformLocation (id, \"view\");\n    s->projectionId = OpenGL::glGetUniformLocation (id, \"projection\");\n    s->colorId = OpenGL::glGetUniformLocation (id, \"color\");\n    s->wireframeColorId = OpenGL::glGetUniformLocation (id, \"wireframeColor\");\n    s->eyePointId = OpenGL::glGetUniformLocation (id, \"eyePoint\");\n    s->barycentricId = OpenGL::glGetUniformLocation (id, \"barycentric\");\n    s->lightIds[0].directionId = OpenGL::glGetUniformLocation (id, \"light1Direction\");\n    s->lightIds[0].colorId = OpenGL::glGetUniformLocation (id, \"light1Color\");\n    s->lightIds[0].irradianceId = OpenGL::glGetUniformLocation (id, \"light1Irradiance\");\n    s->lightIds[1].directionId = OpenGL::glGetUniformLocation (id, \"light2Direction\");\n    s->lightIds[1].colorId = OpenGL::glGetUniformLocation (id, \"light2Color\");\n    s->lightIds[1].irradianceId = OpenGL::glGetUniformLocation (id, \"light2Irradiance\");\n  }\n\n  void setProgram (const RenderMode& renderMode)\n  {\n    const unsigned int index = this->shaderIndex (renderMode);\n\n    if (this->shaderIds[index].programId == 0)\n    {\n      this->initalizeProgram (renderMode);\n    }\n    assert (this->shaderIds[index].programId);\n\n    this->activeShaderIndex = &this->shaderIds[index];\n    OpenGL::glUseProgram (this->activeShaderIndex->programId);\n\n    OpenGL::glUniformVec3 (this->activeShaderIndex->eyePointId, this->globalUniforms.eyePoint);\n\n    for (unsigned int i = 0; i < numLights; i++)\n    {\n      OpenGL::glUniformVec3 (this->activeShaderIndex->lightIds[i].directionId,\n                             this->globalUniforms.lightUniforms[i].direction);\n      OpenGL::glUniformVec3 (this->activeShaderIndex->lightIds[i].colorId,\n                             this->globalUniforms.lightUniforms[i].color.vec3 ());\n      OpenGL::glUniform1f (this->activeShaderIndex->lightIds[i].irradianceId,\n                           this->globalUniforms.lightUniforms[i].irradiance);\n    }\n  }\n\n  void setModel (const float* model, const float* modelNormal)\n  {\n    assert (this->activeShaderIndex);\n    OpenGL::glUniformMatrix4fv (this->activeShaderIndex->modelId, 1, false, model);\n    OpenGL::glUniformMatrix3fv (this->activeShaderIndex->modelNormalId, 1, false, modelNormal);\n  }\n\n  void setView (const float* view)\n  {\n    assert (this->activeShaderIndex);\n    OpenGL::glUniformMatrix4fv (this->activeShaderIndex->viewId, 1, false, view);\n  }\n\n  void setProjection (const float* projection)\n  {\n    assert (this->activeShaderIndex);\n    OpenGL::glUniformMatrix4fv (this->activeShaderIndex->projectionId, 1, false, projection);\n  }\n\n  void setColor (const Color& c, bool withOpacity)\n  {\n    assert (this->activeShaderIndex);\n\n    if (withOpacity)\n    {\n      OpenGL::glUniformVec4 (this->activeShaderIndex->colorId, c.vec4 ());\n    }\n    else\n    {\n      OpenGL::glUniformVec3 (this->activeShaderIndex->colorId, c.vec3 ());\n    }\n  }\n\n  void setWireframeColor (const Color& c, bool withOpacity)\n  {\n    assert (this->activeShaderIndex);\n\n    if (withOpacity)\n    {\n      OpenGL::glUniformVec4 (this->activeShaderIndex->wireframeColorId, c.vec4 ());\n    }\n    else\n    {\n      OpenGL::glUniformVec3 (this->activeShaderIndex->wireframeColorId, c.vec3 ());\n    }\n  }\n\n  void setEyePoint (const glm::vec3& e) { this->globalUniforms.eyePoint = e; }\n\n  void setLightDirection (unsigned int i, const glm::vec3& d)\n  {\n    assert (i < numLights);\n    this->globalUniforms.lightUniforms[i].direction = d;\n  }\n\n  void setLightColor (unsigned int i, const Color& c)\n  {\n    assert (i < numLights);\n    this->globalUniforms.lightUniforms[i].color = c;\n  }\n\n  void setLightIrradiance (unsigned int i, float irr)\n  {\n    assert (i < numLights);\n    this->globalUniforms.lightUniforms[i].irradiance = irr;\n  }\n\n  void runFromConfig (const Config& config)\n  {\n    this->clearColor = config.get<Color> (\"editor/background\");\n\n    for (unsigned int i = 0; i < numLights; i++)\n    {\n      const std::string key = \"editor/light/light\" + std::to_string (i + 1) + \"/\";\n\n      const glm::vec3 dir = config.get<glm::vec3> (key + \"direction\");\n      this->setLightDirection (i, glm::normalize (dir));\n      this->setLightColor (i, config.get<Color> (key + \"color\"));\n      this->setLightIrradiance (i, config.get<float> (key + \"irradiance\"));\n    }\n  }\n};\n\nDELEGATE1_BIG3 (Renderer, const Config&)\n\nDELEGATE (void, Renderer, setupRendering)\nDELEGATE (void, Renderer, shutdownRendering)\nDELEGATE1 (void, Renderer, setProgram, const RenderMode&)\nDELEGATE2 (void, Renderer, setModel, const float*, const float*)\nDELEGATE1 (void, Renderer, setView, const float*)\nDELEGATE1 (void, Renderer, setProjection, const float*)\nDELEGATE2 (void, Renderer, setColor, const Color&, bool)\nDELEGATE2 (void, Renderer, setWireframeColor, const Color&, bool)\nDELEGATE1 (void, Renderer, setEyePoint, const glm::vec3&)\nDELEGATE2 (void, Renderer, setLightDirection, unsigned int, const glm::vec3&)\nDELEGATE2 (void, Renderer, setLightColor, unsigned int, const Color&)\nDELEGATE2 (void, Renderer, setLightIrradiance, unsigned int, float)\nDELEGATE1 (void, Renderer, runFromConfig, const Config&)\n"
  },
  {
    "path": "lib/src/renderer.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_RENDERER\n#define DILAY_RENDERER\n\n#include <glm/fwd.hpp>\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n\nclass Color;\nclass Config;\nclass RenderMode;\n\nclass Renderer : public Configurable\n{\npublic:\n  DECLARE_BIG3 (Renderer, const Config&)\n\n  void setupRendering ();\n  void shutdownRendering ();\n  void setProgram (const RenderMode&);\n  void setModel (const float*, const float*);\n  void setView (const float*);\n  void setProjection (const float*);\n  void setColor (const Color&, bool = false);\n  void setWireframeColor (const Color&, bool = false);\n  void setEyePoint (const glm::vec3&);\n  void setLightDirection (unsigned int, const glm::vec3&);\n  void setLightColor (unsigned int, const Color&);\n  void setLightIrradiance (unsigned int, float);\n\nprivate:\n  IMPLEMENTATION\n\n  void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/scene.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <list>\n#include \"config.hpp\"\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"import-export.hpp\"\n#include \"intersection.hpp\"\n#include \"render-mode.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/bone-intersection.hpp\"\n#include \"sketch/mesh-intersection.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/node-intersection.hpp\"\n#include \"sketch/path-intersection.hpp\"\n#include \"util.hpp\"\n\nstruct Scene::Impl\n{\n  Scene*                 self;\n  std::list<DynamicMesh> dynamicMeshes;\n  std::list<SketchMesh>  sketchMeshes;\n  RenderMode             commonRenderMode;\n  std::string            fileName;\n\n  Impl (Scene* s, const Config& config)\n    : self (s)\n  {\n    this->runFromConfig (config);\n\n    this->commonRenderMode.smoothShading (true);\n  }\n\n  DynamicMesh& newDynamicMesh (const Config& config, const DynamicMesh& other)\n  {\n    this->dynamicMeshes.emplace_back (other);\n    this->setupMesh (config, this->dynamicMeshes.back ());\n    return this->dynamicMeshes.back ();\n  }\n\n  DynamicMesh& newDynamicMesh (const Config& config, const Mesh& mesh)\n  {\n    this->dynamicMeshes.emplace_back (mesh);\n    this->setupMesh (config, this->dynamicMeshes.back ());\n    return this->dynamicMeshes.back ();\n  }\n\n  SketchMesh& newSketchMesh (const Config& config, const SketchMesh& other)\n  {\n    this->sketchMeshes.emplace_back (other);\n    this->setupMesh (config, this->sketchMeshes.back ());\n    return this->sketchMeshes.back ();\n  }\n\n  SketchMesh& newSketchMesh (const Config& config, const SketchTree& tree)\n  {\n    this->sketchMeshes.emplace_back ();\n    this->sketchMeshes.back ().fromTree (tree);\n    this->setupMesh (config, this->sketchMeshes.back ());\n    return this->sketchMeshes.back ();\n  }\n\n  void setupMesh (const Config& config, DynamicMesh& mesh)\n  {\n    mesh.bufferData ();\n    mesh.renderMode () = this->commonRenderMode;\n    mesh.fromConfig (config);\n  }\n\n  void setupMesh (const Config& config, SketchMesh& mesh)\n  {\n    mesh.renderWireframe (this->commonRenderMode.renderWireframe ());\n    mesh.fromConfig (config);\n  }\n\n  void deleteMesh (DynamicMesh& mesh)\n  {\n    for (auto it = this->dynamicMeshes.begin (); it != this->dynamicMeshes.end (); ++it)\n    {\n      if (&*it == &mesh)\n      {\n        this->dynamicMeshes.erase (it);\n        this->resetIfEmpty ();\n        return;\n      }\n    }\n    DILAY_IMPOSSIBLE\n  }\n\n  void deleteMesh (SketchMesh& mesh)\n  {\n    for (auto it = this->sketchMeshes.begin (); it != this->sketchMeshes.end (); ++it)\n    {\n      if (&*it == &mesh)\n      {\n        this->sketchMeshes.erase (it);\n        this->resetIfEmpty ();\n        return;\n      }\n    }\n    DILAY_IMPOSSIBLE\n  }\n\n  void deleteDynamicMeshes () { this->dynamicMeshes.clear (); }\n\n  void deleteSketchMeshes () { this->sketchMeshes.clear (); }\n\n  void deleteEmptyMeshes ()\n  {\n    this->dynamicMeshes.remove_if ([](const auto& mesh) { return mesh.isEmpty (); });\n    this->sketchMeshes.remove_if ([](const auto& mesh) { return mesh.isEmpty (); });\n    this->resetIfEmpty ();\n  }\n\n  void render (Camera& camera)\n  {\n    this->forEachMesh ([&](DynamicMesh& m) { m.render (camera); });\n    this->forEachMesh ([&](SketchMesh& m) { m.render (camera); });\n  }\n\n  template <typename TMesh, typename TIntersection, typename... Ts>\n  bool intersectsT (const PrimRay& ray, TIntersection& intersection, Ts... args)\n  {\n    this->forEachMesh ([&ray, &intersection, &args...](TMesh& m) {\n      m.intersects (ray, intersection, std::forward<Ts> (args)...);\n    });\n    return intersection.isIntersection ();\n  }\n\n  bool intersects (const PrimRay& ray, DynamicMeshIntersection& intersection)\n  {\n    return this->intersectsT<DynamicMesh> (ray, intersection);\n  }\n\n  bool intersects (const PrimRay& ray, SketchNodeIntersection& intersection,\n                   const SketchNode* exclude)\n  {\n    return this->intersectsT<SketchMesh> (ray, intersection, exclude);\n  }\n\n  bool intersects (const PrimRay& ray, SketchBoneIntersection& intersection)\n  {\n    return this->intersectsT<SketchMesh> (ray, intersection);\n  }\n\n  bool intersects (const PrimRay& ray, SketchMeshIntersection& intersection)\n  {\n    return this->intersectsT<SketchMesh> (ray, intersection);\n  }\n\n  bool intersects (const PrimRay& ray, SketchMeshIntersection& intersection,\n                   unsigned int numExcludedLastPaths)\n  {\n    return this->intersectsT<SketchMesh> (ray, intersection, numExcludedLastPaths);\n  }\n\n  bool intersects (const PrimRay& ray, SketchPathIntersection& intersection)\n  {\n    return this->intersectsT<SketchMesh> (ray, intersection);\n  }\n\n  bool intersects (const PrimRay& ray, Intersection& intersection)\n  {\n    DynamicMeshIntersection dIntersection;\n    SketchMeshIntersection  sIntersection;\n\n    if (this->intersects (ray, dIntersection))\n    {\n      intersection.update (dIntersection.distance (), dIntersection.position (),\n                           dIntersection.normal ());\n    }\n    if (this->intersects (ray, sIntersection))\n    {\n      intersection.update (sIntersection.distance (), sIntersection.position (),\n                           sIntersection.normal ());\n    }\n    return intersection.isIntersection ();\n  }\n\n  void printStatistics () const\n  {\n    this->forEachConstMesh ([](const DynamicMesh& mesh) { mesh.printStatistics (); });\n  }\n\n  template <typename T> void forEachMeshT (std::list<T>& list, const std::function<void(T&)>& f)\n  {\n    const unsigned int n = list.size ();\n    unsigned int       i = 0;\n\n    for (T& mesh : list)\n    {\n      if (i >= n)\n      {\n        break;\n      }\n      else\n      {\n        f (mesh);\n        i++;\n      }\n    }\n  }\n\n  template <typename T>\n  void forEachConstMeshT (const std::list<T>& list, const std::function<void(const T&)>& f) const\n  {\n    const unsigned int n = list.size ();\n    unsigned int       i = 0;\n\n    for (const T& mesh : list)\n    {\n      if (i >= n)\n      {\n        break;\n      }\n      else\n      {\n        f (mesh);\n        i++;\n      }\n    }\n  }\n\n  void forEachMesh (const std::function<void(DynamicMesh&)>& f)\n  {\n    this->forEachMeshT<DynamicMesh> (this->dynamicMeshes, f);\n  }\n\n  void forEachMesh (const std::function<void(SketchMesh&)>& f)\n  {\n    this->forEachMeshT<SketchMesh> (this->sketchMeshes, f);\n  }\n\n  void forEachConstMesh (const std::function<void(const DynamicMesh&)>& f) const\n  {\n    this->forEachConstMeshT<DynamicMesh> (this->dynamicMeshes, f);\n  }\n\n  void forEachConstMesh (const std::function<void(const SketchMesh&)>& f) const\n  {\n    this->forEachConstMeshT<SketchMesh> (this->sketchMeshes, f);\n  }\n\n  void sanitizeMeshes ()\n  {\n    this->forEachMesh ([](DynamicMesh& mesh) { mesh.sanitize (); });\n  }\n\n  void reset ()\n  {\n    this->deleteDynamicMeshes ();\n    this->deleteSketchMeshes ();\n    this->fileName.clear ();\n  }\n\n  void resetIfEmpty ()\n  {\n    if (this->isEmpty ())\n    {\n      this->reset ();\n    }\n  }\n\n  void setCommonRenderMode (const RenderMode& mode)\n  {\n    this->commonRenderMode = mode;\n    this->forEachMesh ([this](DynamicMesh& mesh) { mesh.renderMode () = this->commonRenderMode; });\n    this->forEachMesh (\n      [&mode](SketchMesh& mesh) { mesh.renderWireframe (mode.renderWireframe ()); });\n  }\n\n  bool renderWireframe () const { return this->commonRenderMode.renderWireframe (); }\n\n  void renderWireframe (bool value)\n  {\n    this->commonRenderMode.renderWireframe (value);\n    this->setCommonRenderMode (this->commonRenderMode);\n  }\n\n  void toggleWireframe () { this->renderWireframe (!this->commonRenderMode.renderWireframe ()); }\n\n  void toggleShading ()\n  {\n    if (this->commonRenderMode.smoothShading ())\n    {\n      this->commonRenderMode.flatShading (true);\n    }\n    else if (this->commonRenderMode.flatShading ())\n    {\n      this->commonRenderMode.smoothShading (true);\n    }\n    this->setCommonRenderMode (this->commonRenderMode);\n  }\n\n  bool isEmpty () const { return this->numDynamicMeshes () == 0 && this->numSketchMeshes () == 0; }\n\n  unsigned int numDynamicMeshes () const { return this->dynamicMeshes.size (); }\n\n  unsigned int numSketchMeshes () const { return this->sketchMeshes.size (); }\n\n  unsigned int numFaces () const\n  {\n    unsigned int n = 0;\n    this->forEachConstMesh ([&n](const DynamicMesh& mesh) { n += mesh.numFaces (); });\n    return n;\n  }\n\n  bool hasFileName () const { return !this->fileName.empty (); }\n\n  bool toDlyFile (bool isObjFile)\n  {\n    assert (this->hasFileName ());\n\n    return Util::withCLocale<bool> ([this, isObjFile]() {\n      if (ImportExport::toDlyFile (this->fileName, *this->self, isObjFile))\n      {\n        return true;\n      }\n      else\n      {\n        this->fileName.clear ();\n        return false;\n      }\n    });\n  }\n\n  bool toDlyFile (const std::string& newFileName, bool isObjFile)\n  {\n    this->fileName = newFileName;\n    return this->toDlyFile (isObjFile);\n  }\n\n  bool fromDlyFile (const Config& config, const std::string& newFileName)\n  {\n    this->fileName = newFileName;\n\n    if (ImportExport::fromDlyFile (this->fileName, config, *this->self))\n    {\n      return true;\n    }\n    else\n    {\n      this->fileName.clear ();\n      return false;\n    }\n  }\n\n  void runFromConfig (const Config& config)\n  {\n    this->forEachMesh ([&config](DynamicMesh& mesh) { mesh.fromConfig (config); });\n    this->forEachMesh ([&config](SketchMesh& mesh) { mesh.fromConfig (config); });\n  }\n};\n\nDELEGATE1_BIG3_SELF (Scene, const Config&)\n\nDELEGATE2 (DynamicMesh&, Scene, newDynamicMesh, const Config&, const DynamicMesh&)\nDELEGATE2 (DynamicMesh&, Scene, newDynamicMesh, const Config&, const Mesh&)\nDELEGATE2 (SketchMesh&, Scene, newSketchMesh, const Config&, const SketchMesh&)\nDELEGATE2 (SketchMesh&, Scene, newSketchMesh, const Config&, const SketchTree&)\nDELEGATE2 (void, Scene, setupMesh, const Config&, DynamicMesh&)\nDELEGATE2 (void, Scene, setupMesh, const Config&, SketchMesh&)\nDELEGATE1 (void, Scene, deleteMesh, DynamicMesh&)\nDELEGATE1 (void, Scene, deleteMesh, SketchMesh&)\nDELEGATE (void, Scene, deleteDynamicMeshes)\nDELEGATE (void, Scene, deleteSketchMeshes)\nDELEGATE (void, Scene, deleteEmptyMeshes)\nDELEGATE1 (void, Scene, render, Camera&)\nDELEGATE2 (bool, Scene, intersects, const PrimRay&, DynamicMeshIntersection&)\nDELEGATE3 (bool, Scene, intersects, const PrimRay&, SketchNodeIntersection&, const SketchNode*)\nDELEGATE2 (bool, Scene, intersects, const PrimRay&, SketchBoneIntersection&)\nDELEGATE2 (bool, Scene, intersects, const PrimRay&, SketchMeshIntersection&)\nDELEGATE3 (bool, Scene, intersects, const PrimRay&, SketchMeshIntersection&, unsigned int)\nDELEGATE2 (bool, Scene, intersects, const PrimRay&, SketchPathIntersection&)\nDELEGATE2 (bool, Scene, intersects, const PrimRay&, Intersection&)\nDELEGATE_CONST (void, Scene, printStatistics)\nDELEGATE1 (void, Scene, forEachMesh, const std::function<void(DynamicMesh&)>&)\nDELEGATE1 (void, Scene, forEachMesh, const std::function<void(SketchMesh&)>&)\nDELEGATE1_CONST (void, Scene, forEachConstMesh, const std::function<void(const DynamicMesh&)>&)\nDELEGATE1_CONST (void, Scene, forEachConstMesh, const std::function<void(const SketchMesh&)>&)\nDELEGATE (void, Scene, sanitizeMeshes)\nDELEGATE (void, Scene, reset)\nGETTER_CONST (const RenderMode&, Scene, commonRenderMode)\nDELEGATE_CONST (bool, Scene, renderWireframe)\nDELEGATE1 (void, Scene, renderWireframe, bool)\nDELEGATE (void, Scene, toggleWireframe)\nDELEGATE (void, Scene, toggleShading)\nDELEGATE_CONST (bool, Scene, isEmpty)\nDELEGATE_CONST (unsigned int, Scene, numDynamicMeshes)\nDELEGATE_CONST (unsigned int, Scene, numSketchMeshes)\nDELEGATE_CONST (unsigned int, Scene, numFaces)\nDELEGATE_CONST (bool, Scene, hasFileName)\nGETTER_CONST (const std::string&, Scene, fileName)\nDELEGATE1 (bool, Scene, toDlyFile, bool)\nDELEGATE2 (bool, Scene, toDlyFile, const std::string&, bool)\nDELEGATE2 (bool, Scene, fromDlyFile, const Config&, const std::string&)\nDELEGATE1 (void, Scene, runFromConfig, const Config&)\n"
  },
  {
    "path": "lib/src/scene.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SCENE\n#define DILAY_SCENE\n\n#include <string>\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n#include \"sketch/fwd.hpp\"\n\nclass Camera;\nclass DynamicMesh;\nclass DynamicMeshIntersection;\nclass Intersection;\nclass Mesh;\nclass PrimRay;\nclass RenderMode;\n\nclass Scene : public Configurable\n{\npublic:\n  DECLARE_BIG3 (Scene, const Config&)\n\n  DynamicMesh& newDynamicMesh (const Config&, const DynamicMesh&);\n  DynamicMesh& newDynamicMesh (const Config&, const Mesh&);\n  SketchMesh&  newSketchMesh (const Config&, const SketchMesh&);\n  SketchMesh&  newSketchMesh (const Config&, const SketchTree&);\n  void         setupMesh (const Config&, DynamicMesh&);\n  void         setupMesh (const Config&, SketchMesh&);\n  void         deleteMesh (DynamicMesh&);\n  void         deleteMesh (SketchMesh&);\n  void         deleteDynamicMeshes ();\n  void         deleteSketchMeshes ();\n  void         deleteEmptyMeshes ();\n  void         render (Camera&);\n  bool         intersects (const PrimRay&, DynamicMeshIntersection&);\n  bool         intersects (const PrimRay&, SketchNodeIntersection&, const SketchNode* = nullptr);\n  bool         intersects (const PrimRay&, SketchBoneIntersection&);\n  bool         intersects (const PrimRay&, SketchMeshIntersection&);\n  bool         intersects (const PrimRay&, SketchMeshIntersection&, unsigned int);\n  bool         intersects (const PrimRay&, SketchPathIntersection&);\n  bool         intersects (const PrimRay&, Intersection&);\n  void         printStatistics () const;\n  void         forEachMesh (const std::function<void(DynamicMesh&)>&);\n  void         forEachMesh (const std::function<void(SketchMesh&)>&);\n  void         forEachConstMesh (const std::function<void(const DynamicMesh&)>&) const;\n  void         forEachConstMesh (const std::function<void(const SketchMesh&)>&) const;\n  void         sanitizeMeshes ();\n  void         reset ();\n  const RenderMode&  commonRenderMode () const;\n  bool               renderWireframe () const;\n  void               renderWireframe (bool);\n  void               toggleWireframe ();\n  void               toggleShading ();\n  bool               isEmpty () const;\n  unsigned int       numDynamicMeshes () const;\n  unsigned int       numSketchMeshes () const;\n  unsigned int       numFaces () const;\n  bool               hasFileName () const;\n  const std::string& fileName () const;\n  bool               toDlyFile (bool);\n  bool               toDlyFile (const std::string&, bool);\n  bool               fromDlyFile (const Config&, const std::string&);\n\nprivate:\n  IMPLEMENTATION\n\n  void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/shader.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"shader.hpp\"\n\n#define SMOOTH_VERTEX_SHADER                                                                   \\\n  \"#version 120                                                                            \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"uniform   mat4  model;                                                                  \\n\" \\\n  \"uniform   mat3  modelNormal;                                                            \\n\" \\\n  \"uniform   mat4  view;                                                                   \\n\" \\\n  \"uniform   mat4  projection;                                                             \\n\" \\\n  \"attribute vec3  position;                                                               \\n\" \\\n  \"attribute vec3  normal;                                                                 \\n\" \\\n  \"uniform   vec3  color;                                                                  \\n\" \\\n  \"uniform   vec3  light1Direction;                                                        \\n\" \\\n  \"uniform   vec3  light1Color;                                                            \\n\" \\\n  \"uniform   float light1Irradiance;                                                       \\n\" \\\n  \"uniform   vec3  light2Direction;                                                        \\n\" \\\n  \"uniform   vec3  light2Color;                                                            \\n\" \\\n  \"uniform   float light2Irradiance;                                                       \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"varying vec3 vsColor;                                                                   \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"void main () {                                                                          \\n\" \\\n  \"  gl_Position      = (projection * view * model) * vec4 (position, 1.0);                \\n\" \\\n  \"  vec3  viewNormal = vec3 (view * vec4 (normalize (modelNormal * normal), 0.0));        \\n\" \\\n  \"  float light1Diff = max (0.0, dot (-light1Direction, viewNormal));                     \\n\" \\\n  \"  float light2Diff = max (0.0, dot (-light2Direction, viewNormal));                     \\n\" \\\n  \"  vec3  light1     = light1Irradiance * light1Color * light1Diff;                       \\n\" \\\n  \"  vec3  light2     = light2Irradiance * light2Color * light2Diff;                       \\n\" \\\n  \"        vsColor    = color * (light1 + light2);                                         \\n\" \\\n  \"}                                                                                       \\n\"\n\n#define SMOOTH_FRAGMENT_SHADER(COLOR, FINAL)                                                   \\\n  \"#version 120                                                                            \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"uniform vec3 wireframeColor;                                                            \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"varying vec3 \" COLOR \";                                                                 \\n\" \\\n  \"varying vec3 barycentric;                                                               \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"void main () {                                                                          \\n\" \\\n  \"  gl_FragColor = vec4 (\" COLOR                                                              \\\n  \", 1.0);                                                 \\n\" FINAL                           \\\n  \"}                                                                                       \\n\"\n\n#define FLAT_VERTEX_SHADER                                                                     \\\n  \"#version 120                                                                            \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"uniform   mat4 model;                                                                   \\n\" \\\n  \"uniform   mat4 view;                                                                    \\n\" \\\n  \"uniform   mat4 projection;                                                              \\n\" \\\n  \"attribute vec3 position;                                                                \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"varying vec3 vsColor;                                                                   \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"void main () {                                                                          \\n\" \\\n  \"  gl_Position = (projection * view * model) * vec4 (position,1.0);                      \\n\" \\\n  \"  vsColor     = vec3 (model * vec4 (position, 1.0));                                    \\n\" \\\n  \"}                                                                                       \\n\"\n\n#define FLAT_FRAGMENT_SHADER(COLOR, FINAL)                                                     \\\n  \"#version 120                                                                            \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"uniform mat4  view;                                                                     \\n\" \\\n  \"uniform vec3  color;                                                                    \\n\" \\\n  \"uniform vec3  wireframeColor;                                                           \\n\" \\\n  \"uniform vec3  light1Direction;                                                          \\n\" \\\n  \"uniform vec3  light1Color;                                                              \\n\" \\\n  \"uniform float light1Irradiance;                                                         \\n\" \\\n  \"uniform vec3  light2Direction;                                                          \\n\" \\\n  \"uniform vec3  light2Color;                                                              \\n\" \\\n  \"uniform float light2Irradiance;                                                         \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"varying vec3 \" COLOR \";                                                                 \\n\" \\\n  \"varying vec3 barycentric;                                                               \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"void main () {                                                                          \\n\" \\\n  \"  vec3  normal     = normalize(cross(dFdx(\" COLOR \"),dFdy(\" COLOR \")));                 \\n\" \\\n  \"  vec3  viewNormal = vec3 (view * vec4 (normal,0.0));                                   \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"  float light1Diff = max (0.0, dot (-light1Direction, viewNormal));                     \\n\" \\\n  \"  float light2Diff = max (0.0, dot (-light2Direction, viewNormal));                     \\n\" \\\n  \"  vec3  light1     = light1Irradiance * light1Color * vec3 (light1Diff);                \\n\" \\\n  \"  vec3  light2     = light2Irradiance * light2Color * vec3 (light2Diff);                \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"  gl_FragColor     = vec4 (color * (light1 + light2), 1.0);                             \"   \\\n  \"\\n\" FINAL                                                                                   \\\n  \"}                                                                                       \\n\"\n\n#define CONSTANT_VERTEX_SHADER                                                                 \\\n  \"#version 120                                                                            \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"uniform   mat4 model;                                                                   \\n\" \\\n  \"uniform   mat4 view;                                                                    \\n\" \\\n  \"uniform   mat4 projection;                                                              \\n\" \\\n  \"attribute vec3 position;                                                                \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"void main(){                                                                            \\n\" \\\n  \"  gl_Position = (projection * view * model) * vec4 (position,1.0);                      \\n\" \\\n  \"}                                                                                       \\n\"\n\n#define CONSTANT_FRAGMENT_SHADER(FINAL)                                                        \\\n  \"#version 120                                                                            \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"uniform vec3 color;                                                                     \\n\" \\\n  \"uniform vec3 wireframeColor;                                                            \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"varying vec3 barycentric;                                                               \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"void main(){                                                                            \\n\" \\\n  \"  gl_FragColor = vec4 (color, 1.0);                                                     \"   \\\n  \"\\n\" FINAL                                                                                   \\\n  \"}                                                                                       \\n\"\n\n#define ADD_WIREFRAME                                                                          \\\n  \"vec3 barycDelta = fwidth (barycentric);                                                 \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"vec3 edgeFactor = smoothstep (vec3 (0.0), barycDelta * 1.0, barycentric);               \\n\" \\\n  \"float minEdgeFactor = min (min (edgeFactor.x, edgeFactor.y), edgeFactor.z);             \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"gl_FragColor.rgb = mix (wireframeColor, gl_FragColor.rgb, minEdgeFactor);               \\n\"\n\n#define GEOMETRY_SHADER                                                                        \\\n  \"#extension GL_EXT_geometry_shader4: require                                             \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"varying in  vec3 vsColor[3];                                                            \\n\" \\\n  \"varying out vec3 gsColor;                                                               \\n\" \\\n  \"varying out vec3 barycentric;                                                           \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"void main() {                                                                           \\n\" \\\n  \"    gl_Position = gl_PositionIn[0];                                                     \\n\" \\\n  \"    gsColor     = vsColor[0];                                                           \\n\" \\\n  \"    barycentric = vec3 (1.0,0.0,0.0);                                                   \\n\" \\\n  \"    EmitVertex();                                                                       \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"    gl_Position = gl_PositionIn[1];                                                     \\n\" \\\n  \"    gsColor     = vsColor[1];                                                           \\n\" \\\n  \"    barycentric = vec3 (0.0,1.0,0.0);                                                   \\n\" \\\n  \"    EmitVertex();                                                                       \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"    gl_Position = gl_PositionIn[2];                                                     \\n\" \\\n  \"    gsColor     = vsColor[2];                                                           \\n\" \\\n  \"    barycentric = vec3 (0.0,0.0,1.0);                                                   \\n\" \\\n  \"    EmitVertex();                                                                       \\n\" \\\n  \"                                                                                        \\n\" \\\n  \"    EndPrimitive();                                                                     \\n\" \\\n  \"}                                                                                       \\n\"\n\nconst char* Shader::smoothVertexShader () { return SMOOTH_VERTEX_SHADER; }\n\nconst char* Shader::smoothFragmentShader () { return SMOOTH_FRAGMENT_SHADER (\"vsColor\", \"\"); }\n\nconst char* Shader::smoothWireframeFragmentShader ()\n{\n  return SMOOTH_FRAGMENT_SHADER (\"gsColor\", ADD_WIREFRAME);\n}\n\nconst char* Shader::flatVertexShader () { return FLAT_VERTEX_SHADER; }\n\nconst char* Shader::flatFragmentShader () { return FLAT_FRAGMENT_SHADER (\"vsColor\", \"\"); }\n\nconst char* Shader::flatWireframeFragmentShader ()\n{\n  return FLAT_FRAGMENT_SHADER (\"gsColor\", ADD_WIREFRAME);\n}\n\nconst char* Shader::constantVertexShader () { return CONSTANT_VERTEX_SHADER; }\n\nconst char* Shader::constantFragmentShader () { return CONSTANT_FRAGMENT_SHADER (\"\"); }\n\nconst char* Shader::constantWireframeFragmentShader ()\n{\n  return CONSTANT_FRAGMENT_SHADER (ADD_WIREFRAME);\n}\n\nconst char* Shader::geometryShader () { return GEOMETRY_SHADER; }\n"
  },
  {
    "path": "lib/src/shader.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SHADER\n#define DILAY_SHADER\n\nnamespace Shader\n{\n  const char* smoothVertexShader ();\n  const char* smoothFragmentShader ();\n  const char* smoothWireframeFragmentShader ();\n\n  const char* flatVertexShader ();\n  const char* flatFragmentShader ();\n  const char* flatWireframeFragmentShader ();\n\n  const char* constantVertexShader ();\n  const char* constantFragmentShader ();\n  const char* constantWireframeFragmentShader ();\n  const char* geometryShader ();\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/sketch/bone-intersection.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"sketch/bone-intersection.hpp\"\n#include \"sketch/mesh.hpp\"\n\nSketchBoneIntersection::SketchBoneIntersection ()\n  : _child (nullptr)\n{\n}\n\nbool SketchBoneIntersection::update (float d, const glm::vec3& p, const glm::vec3& projP,\n                                     const glm::vec3& n, SketchMesh& mesh, SketchNode& child)\n{\n  assert (child.parent ());\n\n  if (this->SketchMeshIntersection::update (d, p, n, mesh))\n  {\n    this->_child = &child;\n    this->_projectedPosition = projP;\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nSketchNode& SketchBoneIntersection::parent () const\n{\n  assert (this->isIntersection ());\n  assert (this->_child);\n  return *this->_child->parent ();\n}\n\nSketchNode& SketchBoneIntersection::child () const\n{\n  assert (this->isIntersection ());\n  assert (this->_child);\n  return *this->_child;\n}\n\nconst glm::vec3& SketchBoneIntersection::projectedPosition () const\n{\n  assert (this->isIntersection ());\n  return this->_projectedPosition;\n}\n"
  },
  {
    "path": "lib/src/sketch/bone-intersection.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SKETCH_BONE_INTERSECTION\n#define DILAY_SKETCH_BONE_INTERSECTION\n\n#include \"sketch/fwd.hpp\"\n#include \"sketch/mesh-intersection.hpp\"\n\nclass SketchBoneIntersection : public SketchMeshIntersection\n{\npublic:\n  SketchBoneIntersection ();\n\n  SketchNode&      parent () const;\n  SketchNode&      child () const;\n  const glm::vec3& projectedPosition () const;\n  bool             update (float, const glm::vec3&, const glm::vec3&, const glm::vec3&, SketchMesh&,\n                           SketchNode&);\n\nprivate:\n  SketchNode* _child;\n  glm::vec3   _projectedPosition;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/sketch/fwd.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SKETCH_FWD\n#define DILAY_SKETCH_FWD\n\n#include \"primitive/sphere.hpp\"\n#include \"tree.hpp\"\n\nclass SketchPath;\nusing SketchPaths = std::vector<SketchPath>;\nclass SketchNodeIntersection;\nclass SketchBoneIntersection;\nclass SketchMeshIntersection;\nclass SketchPathIntersection;\nusing SketchNode = TreeNode<PrimSphere>;\nusing SketchTree = Tree<PrimSphere>;\nclass SketchMesh;\n\n#endif\n"
  },
  {
    "path": "lib/src/sketch/mesh-intersection.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"sketch/mesh-intersection.hpp\"\n#include \"sketch/mesh.hpp\"\n\nSketchMeshIntersection::SketchMeshIntersection ()\n  : _mesh (nullptr)\n{\n}\n\nbool SketchMeshIntersection::update (float d, const glm::vec3& p, const glm::vec3& n,\n                                     SketchMesh& mesh)\n{\n  if (this->Intersection::update (d, p, n))\n  {\n    this->_mesh = &mesh;\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nSketchMesh& SketchMeshIntersection::mesh () const\n{\n  assert (this->isIntersection ());\n  assert (this->_mesh);\n  return *this->_mesh;\n}\n"
  },
  {
    "path": "lib/src/sketch/mesh-intersection.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SKETCH_MESH_INTERSECTION\n#define DILAY_SKETCH_MESH_INTERSECTION\n\n#include \"intersection.hpp\"\n#include \"sketch/fwd.hpp\"\n\nclass SketchMeshIntersection : public Intersection\n{\npublic:\n  SketchMeshIntersection ();\n\n  SketchMesh& mesh () const;\n  bool        update (float, const glm::vec3&, const glm::vec3&, SketchMesh&);\n\nprivate:\n  SketchMesh* _mesh;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/sketch/mesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/gtx/norm.hpp>\n#include <glm/gtx/rotate_vector.hpp>\n#include \"../mesh.hpp\"\n#include \"color.hpp\"\n#include \"config.hpp\"\n#include \"dimension.hpp\"\n#include \"distance.hpp\"\n#include \"mesh-util.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/cone-sphere.hpp\"\n#include \"primitive/cone.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"render-mode.hpp\"\n#include \"sketch/bone-intersection.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/node-intersection.hpp\"\n#include \"sketch/path-intersection.hpp\"\n#include \"sketch/path.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  struct RenderConfig\n  {\n    bool  renderWireframe;\n    Color nodeColor;\n    Color bubbleColor;\n    Color sphereColor;\n\n    RenderConfig ()\n      : renderWireframe (false)\n    {\n    }\n  };\n\n  bool almostEqual (const glm::vec3& a, const glm::vec3& b)\n  {\n    return glm::distance2 (a, b) <= Util::epsilon () * Util::epsilon ();\n  }\n\n  class PrimSphereIntersection : public Intersection\n  {\n  public:\n    PrimSphereIntersection ()\n      : _sphere (PrimSphere (glm::vec3 (0.0f), 0.0f))\n    {\n    }\n\n    bool update (float d, const PrimSphere& s)\n    {\n      if (this->Intersection::update (d, s.center (), glm::vec3 (0.0f)))\n      {\n        this->_sphere = s;\n        return true;\n      }\n      else\n      {\n        return false;\n      }\n    }\n\n    const PrimSphere& sphere ()\n    {\n      assert (this->isIntersection ());\n      return this->_sphere;\n    }\n\n  private:\n    PrimSphere _sphere;\n  };\n}\n\nstruct SketchMesh::Impl\n{\n  SketchMesh*  self;\n  SketchTree   tree;\n  SketchPaths  paths;\n  Mesh         sphereMesh;\n  Mesh         boneMesh;\n  RenderConfig renderConfig;\n\n  Impl (SketchMesh* s)\n    : self (s)\n  {\n    this->sphereMesh = MeshUtil::icosphere (3);\n    this->sphereMesh.bufferData ();\n\n    this->boneMesh = MeshUtil::cone (16);\n    this->boneMesh.renderMode ().flatShading (true);\n    this->boneMesh.position (glm::vec3 (0.0f, 0.5f, 0.0f));\n    this->boneMesh.normalize ();\n    this->boneMesh.bufferData ();\n  }\n\n  Impl (const Impl& other)\n    : self (nullptr)\n    , tree (other.tree)\n    , paths (other.paths)\n    , sphereMesh (other.sphereMesh)\n    , boneMesh (other.boneMesh)\n    , renderConfig (other.renderConfig)\n  {\n    this->sphereMesh.bufferData ();\n    this->boneMesh.bufferData ();\n  }\n\n  bool isEmpty () const { return this->tree.hasRoot () == false && this->paths.empty (); }\n\n  void fromTree (const SketchTree& newTree) { this->tree = newTree; }\n\n  void reset () { this->tree.reset (); }\n\n  bool intersects (const PrimRay& ray, SketchNodeIntersection& intersection,\n                   const SketchNode* exclude = nullptr)\n  {\n    if (this->tree.hasRoot ())\n    {\n      this->tree.root ().forEachNode ([this, &ray, &intersection, exclude](SketchNode& node) {\n        float t;\n        if (&node != exclude && IntersectionUtil::intersects (ray, node.data (), &t))\n        {\n          const glm::vec3 p = ray.pointAt (t);\n          intersection.update (t, p, glm::normalize (p - node.data ().center ()), *this->self,\n                               node);\n        }\n      });\n    }\n    return intersection.isIntersection ();\n  }\n\n  bool intersects (const PrimRay& ray, SketchBoneIntersection& intersection)\n  {\n    if (this->tree.hasRoot ())\n    {\n      this->tree.root ().forEachNode ([this, &ray, &intersection](SketchNode& node) {\n        if (node.parent ())\n        {\n          const PrimConeSphere coneSphere (node.data (), node.parent ()->data ());\n\n          if (coneSphere.hasCone ())\n          {\n            const PrimCone cone = coneSphere.toCone ();\n\n            float tRay, tCone;\n            if (IntersectionUtil::intersects (ray, cone, &tRay, &tCone))\n            {\n              const glm::vec3 p = ray.pointAt (tRay);\n\n              intersection.update (tRay, p, cone.projPointAt (tCone), cone.normalAt (p, tCone),\n                                   *this->self, node);\n            }\n          }\n        }\n      });\n    }\n    return intersection.isIntersection ();\n  }\n\n  bool intersects (const PrimRay& ray, SketchMeshIntersection& intersection,\n                   unsigned int numExcludedLastPaths)\n  {\n    SketchNodeIntersection snIntersection;\n    SketchBoneIntersection sbIntersection;\n    SketchPathIntersection spIntersection;\n\n    if (this->intersects (ray, snIntersection))\n    {\n      intersection.update (snIntersection.distance (), snIntersection.position (),\n                           snIntersection.normal (), snIntersection.mesh ());\n    }\n    if (this->intersects (ray, sbIntersection))\n    {\n      intersection.update (sbIntersection.distance (), sbIntersection.position (),\n                           sbIntersection.normal (), sbIntersection.mesh ());\n    }\n    if (numExcludedLastPaths < this->paths.size ())\n    {\n      for (unsigned int i = 0; i < this->paths.size () - numExcludedLastPaths; i++)\n      {\n        if (this->paths.at (i).intersects (ray, *this->self, spIntersection))\n        {\n          intersection.update (spIntersection.distance (), spIntersection.position (),\n                               spIntersection.normal (), spIntersection.mesh ());\n        }\n      }\n    }\n    return intersection.isIntersection ();\n  }\n\n  bool intersects (const PrimRay& ray, SketchPathIntersection& intersection)\n  {\n    for (unsigned int i = 0; i < this->paths.size (); i++)\n    {\n      this->paths.at (i).intersects (ray, *this->self, intersection);\n    }\n    return intersection.isIntersection ();\n  }\n\n  bool intersects (const glm::vec3& point, PrimSphereIntersection& intersection,\n                   const SketchPath& excluded)\n  {\n    auto checkSphere = [&point, &intersection](const SketchNode& node) {\n      const float d2 = glm::distance2 (point, node.data ().center ());\n      if (d2 <= node.data ().radius () * node.data ().radius ())\n      {\n        intersection.update (glm::sqrt (d2), node.data ());\n      }\n    };\n\n    auto checkBone = [&point, &intersection, &checkSphere](const SketchNode& node) {\n      if (node.parent ())\n      {\n        const PrimConeSphere coneSphere (node.data (), node.parent ()->data ());\n\n        if (coneSphere.hasCone ())\n        {\n          const glm::vec3 toP = point - coneSphere.sphere1 ().center ();\n          const float     x = glm::dot (toP, coneSphere.direction ());\n          const float     y = glm::sqrt (glm::dot (toP, toP) - (x * x));\n          const float     sigma = glm::half_pi<float> () - coneSphere.alpha ();\n          const float     xOff = x - (y / glm::tan (sigma));\n\n          float nearestFactor;\n          float nearestRadius;\n\n          if (xOff <= 0.0f)\n          {\n            nearestFactor = 0.0f;\n            nearestRadius = coneSphere.sphere1 ().radius ();\n          }\n          else if (xOff >= coneSphere.length ())\n          {\n            nearestFactor = coneSphere.length ();\n            nearestRadius = coneSphere.sphere2 ().radius ();\n          }\n          else\n          {\n            nearestFactor = xOff;\n            nearestRadius = glm::mix (coneSphere.sphere1 ().radius (),\n                                      coneSphere.sphere2 ().radius (), xOff / coneSphere.length ());\n          }\n\n          const glm::vec3 nearestCenter =\n            coneSphere.sphere1 ().center () + (nearestFactor * coneSphere.direction ());\n          const float d2 = glm::distance2 (point, nearestCenter);\n\n          if (d2 <= nearestRadius * nearestRadius)\n          {\n            intersection.update (glm::sqrt (d2), PrimSphere (nearestCenter, nearestRadius));\n          }\n        }\n        else\n        {\n          const float d2 = glm::distance2 (point, coneSphere.sphere1 ().center ());\n\n          if (d2 <= coneSphere.sphere1 ().radius () * coneSphere.sphere1 ().radius ())\n          {\n            intersection.update (glm::sqrt (d2), coneSphere.sphere1 ());\n          }\n        }\n      }\n      else\n      {\n        checkSphere (node);\n      }\n    };\n\n    if (this->tree.hasRoot ())\n    {\n      this->tree.root ().forEachNode ([&checkBone](SketchNode& node) { checkBone (node); });\n    }\n\n    for (const SketchPath& p : this->paths)\n    {\n      if (&p != &excluded)\n      {\n        for (const PrimSphere& s : p.spheres ())\n        {\n          checkSphere (s);\n        }\n      }\n    }\n    return intersection.isIntersection ();\n  }\n\n  void renderTree (Camera& camera)\n  {\n    if (this->tree.hasRoot ())\n    {\n      this->tree.root ().forEachConstNode ([this, &camera](const SketchNode& node) {\n        const glm::vec3& pos = node.data ().center ();\n        const float      radius = node.data ().radius ();\n\n        this->sphereMesh.position (pos);\n        this->sphereMesh.scaling (glm::vec3 (radius));\n        this->sphereMesh.color (this->renderConfig.nodeColor);\n        this->sphereMesh.render (camera);\n\n        if (node.parent ())\n        {\n          const glm::vec3& parPos = node.parent ()->data ().center ();\n          const float      parRadius = node.parent ()->data ().radius ();\n          const float      distance = glm::distance (pos, parPos);\n          const glm::vec3  direction = (parPos - pos) / distance;\n\n          if (this->renderConfig.renderWireframe)\n          {\n            const glm::vec3 down = glm::vec3 (0.0f, -1.0f, 0.0f);\n\n            if (Util::colinearUnit (direction, down))\n            {\n              this->boneMesh.rotationMatrix (glm::mat4x4 (1.0f));\n\n              if (glm::dot (direction, down) < 0.0f)\n              {\n                this->boneMesh.rotateX (glm::pi<float> ());\n              }\n            }\n            else\n            {\n              this->boneMesh.rotationMatrix (glm::orientation (direction, down));\n            }\n\n            this->boneMesh.color (this->renderConfig.nodeColor);\n            this->boneMesh.position (parPos);\n            this->boneMesh.scaling (glm::vec3 (parRadius, distance, parRadius));\n            this->boneMesh.render (camera);\n          }\n          else\n          {\n            this->sphereMesh.color (this->renderConfig.bubbleColor);\n\n            for (float d = radius * 0.5f; d < distance;)\n            {\n              const glm::vec3 bubblePos = pos + (d * direction);\n              const float     bubbleRadius = glm::mix (radius, parRadius, d / distance);\n\n              this->sphereMesh.position (bubblePos);\n              this->sphereMesh.scaling (glm::vec3 (bubbleRadius));\n              this->sphereMesh.render (camera);\n\n              d += bubbleRadius * 0.5f;\n            }\n          }\n        }\n      });\n    }\n  }\n\n  void renderPaths (Camera& camera)\n  {\n    this->sphereMesh.color (this->renderConfig.sphereColor);\n\n    for (const SketchPath& p : this->paths)\n    {\n      p.render (camera, this->sphereMesh);\n    }\n  }\n\n  void render (Camera& camera)\n  {\n    this->renderTree (camera);\n\n    if (this->renderConfig.renderWireframe == false)\n    {\n      this->renderPaths (camera);\n    }\n  }\n\n  void renderWireframe (bool v) { this->renderConfig.renderWireframe = v; }\n\n  PrimPlane mirrorPlane (Dimension dim) const\n  {\n    if (this->tree.hasRoot ())\n    {\n      return PrimPlane (this->tree.root ().data ().center (), DimensionUtil::vector (dim));\n    }\n    else\n    {\n      return PrimPlane (glm::vec3 (0.0f), DimensionUtil::vector (dim));\n    }\n  }\n\n  SketchNode* mirrored (const SketchNode& node, const PrimPlane& mirrorPlane,\n                        const SketchNode& exclude)\n  {\n    if (this->tree.hasRoot () && node.parent ())\n    {\n      SketchNode*     result = nullptr;\n      const glm::vec3 pos = mirrorPlane.mirror (node.data ().center ());\n\n      this->tree.root ().forEachNode ([&exclude, &result, &pos](SketchNode& n) {\n        if (n.parent () && (&exclude != &n) && almostEqual (n.data ().center (), pos))\n        {\n          result = &n;\n        }\n      });\n      return result;\n    }\n    else\n    {\n      return nullptr;\n    }\n  }\n\n  SketchPath* mirrored (const SketchPath& path)\n  {\n    const unsigned int pathIndex = Util::findIndexByReference (this->paths, path);\n\n    if (pathIndex > 0 &&\n        this->paths.at (pathIndex - 1).spheres ().size () == path.spheres ().size ())\n    {\n      return &this->paths.at (pathIndex - 1);\n    }\n    else if (pathIndex < this->paths.size () - 1 &&\n             this->paths.at (pathIndex + 1).spheres ().size () == path.spheres ().size ())\n\n    {\n      return &this->paths.at (pathIndex + 1);\n    }\n    else\n    {\n      return nullptr;\n    }\n  }\n\n  SketchNode* addMirroredNode (SketchNode& node, const PrimPlane& mirrorPlane)\n  {\n    const glm::vec3 pos = mirrorPlane.mirror (node.data ().center ());\n    const float     radius = node.data ().radius ();\n    SketchNode&     parent = *node.parent ();\n\n    if (parent.parent () == nullptr)\n    {\n      return &parent.emplaceChild (pos, radius);\n    }\n    else\n    {\n      SketchNode* parentM = this->mirrored (parent, mirrorPlane, node);\n\n      return bool(parentM) ? &parentM->emplaceChild (pos, radius) : nullptr;\n    }\n  }\n\n  SketchNode& addChild (SketchNode& parent, const glm::vec3& pos, float radius,\n                        const Dimension* dim)\n  {\n    SketchNode& newNode = parent.emplaceChild (pos, radius);\n\n    if (dim)\n    {\n      this->addMirroredNode (newNode, this->mirrorPlane (*dim));\n    }\n    return newNode;\n  }\n\n  SketchNode& addParent (SketchNode& child, const glm::vec3& pos, float radius,\n                         const Dimension* dim)\n  {\n    assert (child.parent ());\n\n    SketchNode& newNode = child.parent ()->emplaceChild (pos, radius);\n    newNode.addChild (child);\n\n    if (dim)\n    {\n      const PrimPlane mPlane = this->mirrorPlane (*dim);\n      SketchNode*     childM = this->mirrored (child, mPlane, child);\n\n      if (childM && childM->parent ())\n      {\n        SketchNode* newNodeM = this->addMirroredNode (newNode, mPlane);\n        if (newNodeM)\n        {\n          newNodeM->addChild (*childM);\n          childM->parent ()->deleteChild (*childM);\n        }\n      }\n    }\n    child.parent ()->deleteChild (child);\n    return newNode;\n  }\n\n  SketchPath& addPath (const SketchPath& path)\n  {\n    this->paths.push_back (path);\n    return this->paths.back ();\n  }\n\n  void addSphere (bool newPath, const glm::vec3& intersection, const glm::vec3& position,\n                  float radius, const Dimension* dim)\n  {\n    if (newPath)\n    {\n      this->paths.emplace_back ();\n      if (dim)\n      {\n        this->paths.emplace_back ();\n      }\n    }\n    this->paths.back ().addSphere (intersection, position, radius);\n\n    if (dim)\n    {\n      const PrimPlane mirrorPlane = this->mirrorPlane (*dim);\n\n      this->paths.at (this->paths.size () - 2)\n        .addSphere (mirrorPlane.mirror (intersection), mirrorPlane.mirror (position), radius);\n    }\n  }\n\n  void move (SketchNode& node, const glm::vec3& delta, bool all, const Dimension* dim)\n  {\n    const auto moveNodes = [all](SketchNode& node, const glm::vec3& delta) {\n      if (all)\n      {\n        node.forEachNode (\n          [&delta](SketchNode& n) { n.data ().center (n.data ().center () + delta); });\n      }\n      else\n      {\n        node.data ().center (node.data ().center () + delta);\n      }\n    };\n\n    if (dim)\n    {\n      const PrimPlane mirrorPlane = this->mirrorPlane (*dim);\n      SketchNode*     nodeM = this->mirrored (node, mirrorPlane, node);\n\n      moveNodes (node, delta);\n\n      if (nodeM)\n      {\n        moveNodes (*nodeM, mirrorPlane.mirrorDirection (delta));\n      }\n    }\n    else\n    {\n      moveNodes (node, delta);\n    }\n  }\n\n  void scale (SketchNode& node, float factor, bool all, const Dimension* dim)\n  {\n    const auto scaleNodes = [factor, all](SketchNode& node) {\n      if (all)\n      {\n        node.forEachNode (\n          [factor](SketchNode& n) { n.data ().radius (n.data ().radius () * factor); });\n      }\n      else\n      {\n        node.data ().radius (node.data ().radius () * factor);\n      }\n    };\n\n    if (dim)\n    {\n      SketchNode* nodeM = this->mirrored (node, this->mirrorPlane (*dim), node);\n\n      scaleNodes (node);\n\n      if (nodeM)\n      {\n        scaleNodes (*nodeM);\n      }\n    }\n    else\n    {\n      scaleNodes (node);\n    }\n  }\n\n  void rotate (SketchNode& node, const glm::vec3& axis, float angle, const Dimension* dim)\n  {\n    const auto rotateNodes = [](SketchNode& node, const glm::vec3& axis, float angle) {\n      const glm::mat4x4 matrix = Util::rotation (node.data ().center (), axis, angle);\n\n      node.forEachNode ([&matrix](SketchNode& n) {\n        n.data ().center (glm::vec3 (matrix * glm::vec4 (n.data ().center (), 1.0f)));\n      });\n    };\n\n    if (dim)\n    {\n      const PrimPlane mirrorPlane = this->mirrorPlane (*dim);\n      SketchNode*     nodeM = this->mirrored (node, mirrorPlane, node);\n\n      rotateNodes (node, axis, angle);\n\n      if (nodeM)\n      {\n        rotateNodes (*nodeM, mirrorPlane.mirrorDirection (axis), -angle);\n      }\n    }\n    else\n    {\n      rotateNodes (node, axis, angle);\n    }\n  }\n\n  void deleteNode (SketchNode& node, bool deleteChildren, const Dimension* dim)\n  {\n    assert (this->tree.hasRoot ());\n\n    if (node.parent () == nullptr)\n    {\n      this->reset ();\n    }\n    else if (deleteChildren)\n    {\n      if (dim)\n      {\n        SketchNode* nodeM = this->mirrored (node, this->mirrorPlane (*dim), node);\n\n        if (nodeM && nodeM->parent ())\n        {\n          nodeM->parent ()->deleteChild (*nodeM);\n        }\n      }\n      node.parent ()->deleteChild (node);\n    }\n    else\n    {\n      node.forEachChild ([&node](SketchNode& child) { node.parent ()->addChild (child); });\n\n      if (dim)\n      {\n        SketchNode* nodeM = this->mirrored (node, this->mirrorPlane (*dim), node);\n\n        if (nodeM && nodeM->parent ())\n        {\n          nodeM->forEachChild ([nodeM](SketchNode& child) { nodeM->parent ()->addChild (child); });\n          nodeM->parent ()->deleteChild (*nodeM);\n        }\n      }\n      node.parent ()->deleteChild (node);\n    }\n  }\n\n  void deletePath (SketchPath& path, const Dimension* dim)\n  {\n    assert (this->paths.empty () == false);\n\n    if (dim && this->paths.size () >= 2)\n    {\n      const unsigned int index = Util::findIndexByReference (this->paths, path);\n      const SketchPath*  mPath = this->mirrored (path);\n\n      if (mPath)\n      {\n        const unsigned int mIndex = Util::findIndexByReference (this->paths, *mPath);\n\n        if (mIndex < index)\n        {\n          this->paths.erase (this->paths.begin () + index);\n          this->paths.erase (this->paths.begin () + mIndex);\n        }\n        else if (index < mIndex)\n        {\n          this->paths.erase (this->paths.begin () + mIndex);\n          this->paths.erase (this->paths.begin () + index);\n        }\n        else\n        {\n          DILAY_IMPOSSIBLE\n        }\n      }\n      else\n      {\n        this->paths.erase (this->paths.begin () + index);\n      }\n    }\n    else\n    {\n      this->paths.erase (this->paths.begin ());\n    }\n  }\n\n  void mirrorPositiveTree (Dimension dim)\n  {\n    if (this->tree.hasRoot ())\n    {\n      const PrimPlane mirrorPlane = this->mirrorPlane (dim);\n\n      auto requiresMirroring = [&mirrorPlane](const SketchNode& node) {\n        assert (node.parent ());\n        return (mirrorPlane.absDistance (node.data ().center ()) > Util::epsilon ()) ||\n               (mirrorPlane.absDistance (node.parent ()->data ().center ()) > Util::epsilon ());\n      };\n\n      std::function<void(SketchNode&)> mirrorPositiveNode =\n        [this, &mirrorPlane, &requiresMirroring, &mirrorPositiveNode](SketchNode& node) {\n          unsigned int numChildren = node.numChildren ();\n          node.forEachChild ([this, &mirrorPlane, &requiresMirroring, &mirrorPositiveNode,\n                              &numChildren](SketchNode& c) {\n            if (numChildren > 0)\n            {\n              if (requiresMirroring (c))\n              {\n                this->addMirroredNode (c, mirrorPlane);\n              }\n              mirrorPositiveNode (c);\n              numChildren--;\n            }\n          });\n        };\n\n      this->tree.root ().forEachNode ([&mirrorPlane](SketchNode& parent) {\n        parent.deleteChildIf ([&mirrorPlane](const SketchNode& child) {\n          return mirrorPlane.distance (child.data ().center ()) < -Util::epsilon ();\n        });\n      });\n\n      mirrorPositiveNode (this->tree.root ());\n    }\n  }\n\n  void mirrorPositivePaths (Dimension dim)\n  {\n    const PrimPlane mPlane = this->mirrorPlane (dim);\n    SketchPaths     oldPaths = std::move (this->paths);\n\n    this->paths.clear ();\n\n    for (SketchPath& p : oldPaths)\n    {\n      SketchPath mirrored = p.mirrorPositive (mPlane);\n\n      if (p.isEmpty () == false)\n      {\n        this->paths.push_back (std::move (mirrored));\n        this->paths.push_back (std::move (p));\n      }\n    }\n  }\n\n  void mirrorPositive (Dimension dim)\n  {\n    this->mirrorPositiveTree (dim);\n    this->mirrorPositivePaths (dim);\n  }\n\n  void rebalance (SketchNode& newRoot)\n  {\n    assert (this->tree.hasRoot ());\n    this->tree.rebalance (newRoot);\n  }\n\n  SketchNode& snap (SketchNode& node, Dimension dim)\n  {\n    assert (this->tree.hasRoot ());\n    const PrimPlane mPlane = this->mirrorPlane (dim);\n\n    SketchNode* nodeM = this->mirrored (node, mPlane, node);\n    if (nodeM && nodeM != &node)\n    {\n      if (nodeM->parent () == node.parent ())\n      {\n        SketchNode& snapped = this->addChild (\n          *node.parent (), 0.5f * (node.data ().center () + nodeM->data ().center ()),\n          node.data ().radius (), nullptr);\n\n        node.forEachConstChild ([&snapped](const SketchNode& c) { snapped.addChild (c); });\n        nodeM->forEachConstChild ([&snapped](const SketchNode& c) { snapped.addChild (c); });\n        this->deleteNode (node, true, &dim);\n        return snapped;\n      }\n      else\n      {\n        node.data ().center (mPlane.project (node.data ().center ()));\n        nodeM->data ().center (mPlane.project (nodeM->data ().center ()));\n        return node;\n      }\n    }\n    else\n    {\n      node.data ().center (mPlane.project (node.data ().center ()));\n      return node;\n    }\n  }\n\n  void minMax (glm::vec3& min, glm::vec3& max) const\n  {\n    min = glm::vec3 (Util::maxFloat ());\n    max = glm::vec3 (Util::minFloat ());\n\n    if (this->tree.hasRoot ())\n    {\n      this->tree.root ().forEachConstNode ([&min, &max](const SketchNode& node) {\n        min = glm::min (min, node.data ().center () - glm::vec3 (node.data ().radius ()));\n        max = glm::max (max, node.data ().center () + glm::vec3 (node.data ().radius ()));\n      });\n    }\n    for (const SketchPath& p : this->paths)\n    {\n      min = glm::min (min, p.minimum ());\n      max = glm::max (max, p.maximum ());\n    }\n  }\n\n  void smoothPath (SketchPath& path, const PrimSphere& range, unsigned int halfWidth,\n                   SketchPathSmoothEffect effect, const Dimension* dim)\n  {\n    if (IntersectionUtil::intersects (range, path.aabox ()))\n    {\n      PrimSphereIntersection intersection1, intersection2;\n\n      this->intersects (path.spheres ().front ().center (), intersection1, path);\n      this->intersects (path.spheres ().back ().center (), intersection2, path);\n\n      if (dim)\n      {\n        SketchPath* mPath = this->mirrored (path);\n\n        if (mPath)\n        {\n          PrimSphereIntersection intersection3, intersection4;\n\n          this->intersects (mPath->spheres ().front ().center (), intersection3, *mPath);\n          this->intersects (mPath->spheres ().back ().center (), intersection4, *mPath);\n\n          mPath->smooth (\n            PrimSphere (this->mirrorPlane (*dim).mirror (range.center ()), range.radius ()),\n            halfWidth, effect, intersection3.isIntersection () ? &intersection3.sphere () : nullptr,\n            intersection4.isIntersection () ? &intersection4.sphere () : nullptr);\n        }\n      }\n      path.smooth (range, halfWidth, effect,\n                   intersection1.isIntersection () ? &intersection1.sphere () : nullptr,\n                   intersection2.isIntersection () ? &intersection2.sphere () : nullptr);\n    }\n  }\n\n  void optimizePaths ()\n  {\n    for (SketchPath& p1 : this->paths)\n    {\n      for (SketchPath& p2 : this->paths)\n      {\n        if (&p1 < &p2)\n        {\n          for (auto it1 = p1.spheres ().begin (); it1 != p1.spheres ().end ();)\n          {\n            bool deletedP1Sphere = false;\n\n            for (auto it2 = p2.spheres ().begin (); it2 != p2.spheres ().end ();)\n            {\n              const PrimSphere& s1 = *it1;\n              const PrimSphere& s2 = *it2;\n              const float       d = glm::distance (s1.center (), s2.center ());\n\n              if (s2.radius () > d + s1.radius ())\n              {\n                it1 = p1.deleteSphere (it1);\n                deletedP1Sphere = true;\n                break;\n              }\n              else if (s1.radius () > d + s2.radius ())\n              {\n                it2 = p2.deleteSphere (it2);\n              }\n              else\n              {\n                ++it2;\n              }\n            }\n            if (deletedP1Sphere == false)\n            {\n              ++it1;\n            }\n          }\n        }\n      }\n      if (this->tree.hasRoot ())\n      {\n        this->tree.root ().forEachNode ([&p1](SketchNode& node) {\n          if (node.parent ())\n          {\n            const PrimConeSphere coneSphere (node.data (), node.parent ()->data ());\n\n            for (auto it1 = p1.spheres ().begin (); it1 != p1.spheres ().end ();)\n            {\n              const PrimSphere& s1 = *it1;\n              const float       d = Distance::distance (coneSphere, s1.center ());\n\n              if (d < -s1.radius ())\n              {\n                it1 = p1.deleteSphere (it1);\n              }\n              else\n              {\n                ++it1;\n              }\n            }\n          }\n        });\n      }\n    }\n  }\n\n  void runFromConfig (const Config& config)\n  {\n    this->renderConfig.nodeColor = config.get<Color> (\"editor/sketch/node/color\");\n    this->renderConfig.bubbleColor = config.get<Color> (\"editor/sketch/bubble/color\");\n    this->renderConfig.sphereColor = config.get<Color> (\"editor/sketch/sphere/color\");\n  }\n};\n\nDELEGATE_BIG4_COPY_SELF (SketchMesh);\nGETTER_CONST (const SketchTree&, SketchMesh, tree)\nGETTER (SketchTree&, SketchMesh, tree)\nGETTER_CONST (const SketchPaths&, SketchMesh, paths)\nDELEGATE_CONST (bool, SketchMesh, isEmpty)\nDELEGATE1 (void, SketchMesh, fromTree, const SketchTree&)\nDELEGATE (void, SketchMesh, reset)\nDELEGATE3 (bool, SketchMesh, intersects, const PrimRay&, SketchNodeIntersection&, const SketchNode*)\nDELEGATE2 (bool, SketchMesh, intersects, const PrimRay&, SketchBoneIntersection&)\nDELEGATE3 (bool, SketchMesh, intersects, const PrimRay&, SketchMeshIntersection&, unsigned int)\nDELEGATE2 (bool, SketchMesh, intersects, const PrimRay&, SketchPathIntersection&)\nDELEGATE1 (void, SketchMesh, render, Camera&)\nDELEGATE1 (void, SketchMesh, renderWireframe, bool)\nDELEGATE1 (PrimPlane, SketchMesh, mirrorPlane, Dimension)\nDELEGATE4 (SketchNode&, SketchMesh, addChild, SketchNode&, const glm::vec3&, float,\n           const Dimension*)\nDELEGATE4 (SketchNode&, SketchMesh, addParent, SketchNode&, const glm::vec3&, float,\n           const Dimension*)\nDELEGATE1 (SketchPath&, SketchMesh, addPath, const SketchPath&)\nDELEGATE5 (void, SketchMesh, addSphere, bool, const glm::vec3&, const glm::vec3&, float,\n           const Dimension*)\nDELEGATE4 (void, SketchMesh, move, SketchNode&, const glm::vec3&, bool, const Dimension*)\nDELEGATE4 (void, SketchMesh, scale, SketchNode&, float, bool, const Dimension*)\nDELEGATE4 (void, SketchMesh, rotate, SketchNode&, const glm::vec3&, float, const Dimension*)\nDELEGATE3 (void, SketchMesh, deleteNode, SketchNode&, bool, const Dimension*)\nDELEGATE2 (void, SketchMesh, deletePath, SketchPath&, const Dimension*)\nDELEGATE1 (void, SketchMesh, mirrorPositive, Dimension)\nDELEGATE1 (void, SketchMesh, rebalance, SketchNode&)\nDELEGATE2 (SketchNode&, SketchMesh, snap, SketchNode&, Dimension)\nDELEGATE2_CONST (void, SketchMesh, minMax, glm::vec3&, glm::vec3&)\nDELEGATE5 (void, SketchMesh, smoothPath, SketchPath&, const PrimSphere&, unsigned int,\n           SketchPathSmoothEffect, const Dimension*)\nDELEGATE (void, SketchMesh, optimizePaths)\nDELEGATE1 (void, SketchMesh, runFromConfig, const Config&)\n"
  },
  {
    "path": "lib/src/sketch/mesh.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SKETCH_MESH\n#define DILAY_SKETCH_MESH\n\n#include <glm/glm.hpp>\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n#include \"sketch/fwd.hpp\"\n\nclass Camera;\nenum class Dimension;\nclass PrimPlane;\nclass PrimRay;\nclass PrimSphere;\nenum class SketchPathSmoothEffect;\n\nclass SketchMesh : public Configurable\n{\npublic:\n  DECLARE_BIG4_EXPLICIT_COPY (SketchMesh);\n\n  const SketchTree&  tree () const;\n  SketchTree&        tree ();\n  const SketchPaths& paths () const;\n  bool               isEmpty () const;\n  void               fromTree (const SketchTree&);\n  void               reset ();\n  bool        intersects (const PrimRay&, SketchNodeIntersection&, const SketchNode* = nullptr);\n  bool        intersects (const PrimRay&, SketchBoneIntersection&);\n  bool        intersects (const PrimRay&, SketchMeshIntersection&, unsigned int = 0);\n  bool        intersects (const PrimRay&, SketchPathIntersection&);\n  void        render (Camera&);\n  void        renderWireframe (bool);\n  PrimPlane   mirrorPlane (Dimension);\n  SketchNode& addChild (SketchNode&, const glm::vec3&, float, const Dimension*);\n  SketchNode& addParent (SketchNode&, const glm::vec3&, float, const Dimension*);\n  SketchPath& addPath (const SketchPath&);\n  void        addSphere (bool, const glm::vec3&, const glm::vec3&, float, const Dimension*);\n  void        move (SketchNode&, const glm::vec3&, bool, const Dimension*);\n  void        scale (SketchNode&, float, bool, const Dimension*);\n  void        rotate (SketchNode&, const glm::vec3&, float, const Dimension*);\n  void        deleteNode (SketchNode&, bool, const Dimension*);\n  void        deletePath (SketchPath&, const Dimension*);\n  void        mirrorPositive (Dimension);\n  void        rebalance (SketchNode&);\n  SketchNode& snap (SketchNode&, Dimension);\n  void        minMax (glm::vec3&, glm::vec3&) const;\n  void        smoothPath (SketchPath&, const PrimSphere&, unsigned int, SketchPathSmoothEffect,\n                          const Dimension*);\n  void        optimizePaths ();\n\nprivate:\n  IMPLEMENTATION\n\n  void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/sketch/node-intersection.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"sketch/mesh.hpp\"\n#include \"sketch/node-intersection.hpp\"\n\nSketchNodeIntersection::SketchNodeIntersection ()\n  : _node (nullptr)\n{\n}\n\nbool SketchNodeIntersection::update (float d, const glm::vec3& p, const glm::vec3& n,\n                                     SketchMesh& mesh, SketchNode& node)\n{\n  if (this->SketchMeshIntersection::update (d, p, n, mesh))\n  {\n    this->_node = &node;\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nSketchNode& SketchNodeIntersection::node () const\n{\n  assert (this->isIntersection ());\n  assert (this->_node);\n  return *this->_node;\n}\n"
  },
  {
    "path": "lib/src/sketch/node-intersection.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SKETCH_NODE_INTERSECTION\n#define DILAY_SKETCH_NODE_INTERSECTION\n\n#include \"sketch/fwd.hpp\"\n#include \"sketch/mesh-intersection.hpp\"\n\nclass SketchNodeIntersection : public SketchMeshIntersection\n{\npublic:\n  SketchNodeIntersection ();\n\n  SketchNode& node () const;\n  bool        update (float, const glm::vec3&, const glm::vec3&, SketchMesh&, SketchNode&);\n\nprivate:\n  SketchNode* _node;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/sketch/path-intersection.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"sketch/path-intersection.hpp\"\n#include \"sketch/path.hpp\"\n\nSketchPathIntersection::SketchPathIntersection ()\n  : _path (nullptr)\n{\n}\n\nbool SketchPathIntersection::update (float d, const glm::vec3& p, const glm::vec3& n,\n                                     SketchMesh& mesh, SketchPath& path)\n{\n  if (this->SketchMeshIntersection::update (d, p, n, mesh))\n  {\n    this->_path = &path;\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nSketchPath& SketchPathIntersection::path () const\n{\n  assert (this->isIntersection ());\n  assert (this->_path);\n  return *this->_path;\n}\n"
  },
  {
    "path": "lib/src/sketch/path-intersection.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SKETCH_PATH_INTERSECTION\n#define DILAY_SKETCH_PATH_INTERSECTION\n\n#include \"sketch/fwd.hpp\"\n#include \"sketch/mesh-intersection.hpp\"\n\nclass SketchPathIntersection : public SketchMeshIntersection\n{\npublic:\n  SketchPathIntersection ();\n\n  SketchPath& path () const;\n  bool        update (float, const glm::vec3&, const glm::vec3&, SketchMesh&, SketchPath&);\n\nprivate:\n  SketchPath* _path;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/sketch/path.cpp",
    "content": "#include \"../mesh.hpp\"\n#include \"intersection.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"sketch/path-intersection.hpp\"\n#include \"sketch/path.hpp\"\n#include \"util.hpp\"\n\nstruct SketchPath::Impl\n{\n  SketchPath*         self;\n  SketchPath::Spheres spheres;\n  glm::vec3           minimum;\n  glm::vec3           maximum;\n  glm::vec3           intersectionFirst;\n  glm::vec3           intersectionLast;\n\n  Impl (SketchPath* s)\n    : self (s)\n  {\n    this->resetMinMax ();\n  }\n\n  void resetMinMax ()\n  {\n    this->minimum = glm::vec3 (Util::maxFloat ());\n    this->maximum = glm::vec3 (Util::minFloat ());\n  }\n\n  void reset ()\n  {\n    this->resetMinMax ();\n    this->spheres.clear ();\n  }\n\n  void setMinMax ()\n  {\n    this->resetMinMax ();\n\n    for (const PrimSphere& s : this->spheres)\n    {\n      this->maximum = glm::max (this->maximum, s.center () + glm::vec3 (s.radius ()));\n      this->minimum = glm::min (this->minimum, s.center () - glm::vec3 (s.radius ()));\n    }\n  }\n\n  bool isEmpty () const { return this->spheres.empty (); }\n\n  PrimAABox aabox () const\n  {\n    assert (this->isEmpty () == false);\n    return PrimAABox (this->minimum, this->maximum);\n  }\n\n  void addSphere (const glm::vec3& intersection, const glm::vec3& position, float radius)\n  {\n    if (this->spheres.empty ())\n    {\n      this->intersectionFirst = intersection;\n      this->intersectionLast = intersection;\n    }\n    else\n    {\n      this->intersectionLast = intersection;\n    }\n    this->maximum = glm::max (this->maximum, position + glm::vec3 (radius));\n    this->minimum = glm::min (this->minimum, position - glm::vec3 (radius));\n\n    this->spheres.emplace_back (position, radius);\n  }\n\n  SketchPath::Spheres::iterator deleteSphere (SketchPath::Spheres::const_iterator it)\n  {\n    return this->spheres.erase (it);\n  }\n\n  void render (Camera& camera, Mesh& mesh) const\n  {\n    for (const PrimSphere& s : this->spheres)\n    {\n      mesh.position (s.center ());\n      mesh.scaling (glm::vec3 (s.radius ()));\n      mesh.render (camera);\n    }\n  }\n\n  bool intersects (const PrimRay& ray, SketchMesh& mesh, SketchPathIntersection& intersection)\n  {\n    const PrimAABox aabox (this->minimum, this->maximum);\n    float           t;\n    if (IntersectionUtil::intersects (ray, aabox, &t))\n    {\n      if (intersection.isIntersection () == false || t < intersection.distance ())\n      {\n        for (const PrimSphere& s : this->spheres)\n        {\n          if (IntersectionUtil::intersects (ray, s, &t))\n          {\n            intersection.update (t, ray.pointAt (t), glm::normalize (ray.pointAt (t) - s.center ()),\n                                 mesh, *this->self);\n          }\n        }\n      }\n    }\n    return intersection.isIntersection ();\n  }\n\n  SketchPath mirrorPositive (const PrimPlane& mPlane)\n  {\n    SketchPath::Spheres oldSpheres (std::move (this->spheres));\n    const glm::vec3     oldIntersectionFirst (this->intersectionFirst);\n    const glm::vec3     oldIntersectionLast (this->intersectionLast);\n    SketchPath          mirrored;\n\n    this->reset ();\n    for (unsigned int i = 0; i < oldSpheres.size (); i++)\n    {\n      const PrimSphere& s = oldSpheres[i];\n\n      if (mPlane.distance (s.center ()) > -Util::epsilon ())\n      {\n        const glm::vec3 mCenter = mPlane.mirror (s.center ());\n\n        if (i == 0)\n        {\n          this->addSphere (oldIntersectionFirst, s.center (), s.radius ());\n          mirrored.addSphere (mPlane.mirror (oldIntersectionFirst), mCenter, s.radius ());\n        }\n        else if (i == oldSpheres.size () - 1)\n        {\n          this->addSphere (oldIntersectionLast, s.center (), s.radius ());\n          mirrored.addSphere (mPlane.mirror (oldIntersectionLast), mCenter, s.radius ());\n        }\n        else\n        {\n          this->addSphere (s.center (), s.center (), s.radius ());\n          mirrored.addSphere (mCenter, mCenter, s.radius ());\n        }\n      }\n    }\n    return mirrored;\n  }\n\n  void smooth (const PrimSphere& range, unsigned int halfWidth, SketchPathSmoothEffect effect,\n               const PrimSphere* nearestToFirst, const PrimSphere* nearestToLast)\n  {\n    const unsigned int numS = this->spheres.size ();\n\n    for (unsigned int i = 0; i < numS; i++)\n    {\n      if (IntersectionUtil::intersects (range, this->spheres.at (i)))\n      {\n        const unsigned int hW =\n          i < halfWidth ? i : (i >= numS - halfWidth ? numS - i - 1 : halfWidth);\n        glm::vec3 center (0.0f);\n        float     radius (0.0f);\n        for (unsigned int j = i - hW; j <= i + hW; j++)\n        {\n          center += this->spheres.at (j).center ();\n          radius += this->spheres.at (j).radius ();\n        }\n\n        const bool effectEmbeds = effect == SketchPathSmoothEffect::Embed ||\n                                  effect == SketchPathSmoothEffect::EmbedAndAdjust;\n        unsigned int numAffectedCenter = 0;\n        unsigned int numAffectedRadius = 0;\n\n        if (effect != SketchPathSmoothEffect::None)\n        {\n          if (i < halfWidth)\n          {\n            if (nearestToFirst && effectEmbeds)\n            {\n              numAffectedCenter++;\n              center += nearestToFirst->center ();\n            }\n\n            if (nearestToFirst && effect == SketchPathSmoothEffect::EmbedAndAdjust)\n            {\n              numAffectedRadius++;\n              radius += nearestToFirst->radius ();\n            }\n            else if (effect == SketchPathSmoothEffect::Pinch)\n            {\n              numAffectedRadius++;\n              numAffectedCenter++;\n              center += this->intersectionFirst;\n            }\n          }\n\n          if (i >= numS - halfWidth)\n          {\n            if (nearestToLast && effectEmbeds)\n            {\n              numAffectedCenter++;\n              center += nearestToLast->center ();\n            }\n\n            if (nearestToLast && effect == SketchPathSmoothEffect::EmbedAndAdjust)\n            {\n              numAffectedRadius++;\n              radius += nearestToLast->radius ();\n            }\n            else if (effect == SketchPathSmoothEffect::Pinch)\n            {\n              numAffectedRadius++;\n              numAffectedCenter++;\n              center += this->intersectionLast;\n            }\n          }\n        }\n        this->spheres.at (i).center (center / float((2 * hW) + 1 + numAffectedCenter));\n        this->spheres.at (i).radius (radius / float((2 * hW) + 1 + numAffectedRadius));\n      }\n    }\n    this->setMinMax ();\n  }\n};\n\nDELEGATE_BIG6_SELF (SketchPath)\nGETTER_CONST (const SketchPath::Spheres&, SketchPath, spheres)\nGETTER_CONST (const glm::vec3&, SketchPath, minimum)\nGETTER_CONST (const glm::vec3&, SketchPath, maximum)\nGETTER_CONST (const glm::vec3&, SketchPath, intersectionFirst)\nGETTER_CONST (const glm::vec3&, SketchPath, intersectionLast)\nSETTER (const glm::vec3&, SketchPath, intersectionFirst)\nSETTER (const glm::vec3&, SketchPath, intersectionLast)\nDELEGATE (void, SketchPath, reset)\nDELEGATE_CONST (bool, SketchPath, isEmpty)\nDELEGATE_CONST (PrimAABox, SketchPath, aabox)\nDELEGATE3 (void, SketchPath, addSphere, const glm::vec3&, const glm::vec3&, float)\nDELEGATE1 (SketchPath::Spheres::iterator, SketchPath, deleteSphere,\n           SketchPath::Spheres::const_iterator)\nDELEGATE2_CONST (void, SketchPath, render, Camera&, Mesh&)\nDELEGATE3 (bool, SketchPath, intersects, const PrimRay&, SketchMesh&, SketchPathIntersection&)\nDELEGATE1 (SketchPath, SketchPath, mirrorPositive, const PrimPlane&)\nDELEGATE5 (void, SketchPath, smooth, const PrimSphere&, unsigned int, SketchPathSmoothEffect,\n           const PrimSphere*, const PrimSphere*)\n"
  },
  {
    "path": "lib/src/sketch/path.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_SKETCH_PATH\n#define DILAY_SKETCH_PATH\n\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n#include \"sketch/fwd.hpp\"\n\nclass Camera;\nclass Intersection;\nclass Mesh;\nclass PrimAABox;\nclass PrimPlane;\nclass PrimRay;\n\nenum class SketchPathSmoothEffect\n{\n  None,\n  Embed,\n  EmbedAndAdjust,\n  Pinch\n};\n\nclass SketchPath\n{\npublic:\n  using Spheres = std::vector<PrimSphere>;\n\n  DECLARE_BIG6 (SketchPath);\n\n  const Spheres&    spheres () const;\n  const glm::vec3&  minimum () const;\n  const glm::vec3&  maximum () const;\n  const glm::vec3&  intersectionFirst () const;\n  const glm::vec3&  intersectionLast () const;\n  void              intersectionFirst (const glm::vec3&);\n  void              intersectionLast (const glm::vec3&);\n  void              reset ();\n  bool              isEmpty () const;\n  PrimAABox         aabox () const;\n  void              addSphere (const glm::vec3&, const glm::vec3&, float);\n  Spheres::iterator deleteSphere (Spheres::const_iterator);\n  void              render (Camera&, Mesh&) const;\n  bool              intersects (const PrimRay&, SketchMesh&, SketchPathIntersection&);\n  SketchPath        mirrorPositive (const PrimPlane&);\n  void smooth (const PrimSphere&, unsigned int, SketchPathSmoothEffect, const PrimSphere*,\n               const PrimSphere*);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/state.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QShortcut>\n#include <memory>\n#include \"cache.hpp\"\n#include \"camera.hpp\"\n#include \"config.hpp\"\n#include \"history.hpp\"\n#include \"maybe.hpp\"\n#include \"scene.hpp\"\n#include \"state.hpp\"\n#include \"tool.hpp\"\n#include \"tools.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/info-pane.hpp\"\n#include \"view/info-pane/scene.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/shortcut.hpp\"\n#include \"view/tool-pane.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n\nnamespace\n{\n  typedef State::ViewShortcuts ViewShortcuts;\n}\n\nstruct State::Impl\n{\n  State*                  self;\n  ViewMainWindow&         mainWindow;\n  Config&                 config;\n  Cache&                  cache;\n  Camera                  camera;\n  History                 history;\n  Scene                   scene;\n  std::unique_ptr<Tool>   toolPtr;\n  Maybe<ToolKey>          previousToolKey;\n  std::vector<QShortcut*> shortcuts;\n\n  Impl (State* s, ViewMainWindow& mW, Config& cfg, Cache& cch)\n    : self (s)\n    , mainWindow (mW)\n    , config (cfg)\n    , cache (cch)\n    , camera (this->config)\n    , history (this->config)\n    , scene (this->config)\n  {\n    this->resetTool ();\n  }\n\n  bool hasTool () const { return bool(this->toolPtr); }\n\n  Tool& tool ()\n  {\n    assert (this->hasTool ());\n    return *this->toolPtr;\n  }\n\n  void addToolShortcut (const ViewShortcut& shortcut, ViewToolTip& tip)\n  {\n    tip.add (shortcut.event (), shortcut.modifier (), shortcut.label ());\n    this->shortcuts.push_back (&shortcut.toQShortcut (this->mainWindow));\n  }\n\n  void addToolShortcut (ToolKey key, ViewToolTip& tip, ViewInputEvent event, const QString& label)\n  {\n    const QKeySequence keys = ViewInput::toQKeySequence (event, ViewInputModifier::None);\n\n    tip.add (event, label);\n    this->shortcuts.push_back (new QShortcut (keys, &this->mainWindow));\n\n    QObject::connect (this->shortcuts.back (), &QShortcut::activated,\n                      [this, key]() { this->setTool (key); });\n  }\n\n  void addToolShortcut (ToolKey key, ViewToolTip& tip, ViewInputEvent event)\n  {\n    this->addToolShortcut (key, tip, event, this->mainWindow.toolPane ().buttonText (key));\n  }\n\n  void addToggleToolShortcut (ViewToolTip& tip, ViewInputEvent event)\n  {\n    const QKeySequence keys = ViewInput::toQKeySequence (event, ViewInputModifier::None);\n\n    tip.add (event, QObject::tr (\"Toggle back\"));\n    this->shortcuts.push_back (new QShortcut (keys, &this->mainWindow));\n\n    QObject::connect (this->shortcuts.back (), &QShortcut::activated,\n                      [this]() { this->setPreviousTool (); });\n  }\n\n  void addExitToolShortcut (ViewToolTip& tip, ViewInputEvent event)\n  {\n    const QKeySequence keys = ViewInput::toQKeySequence (event, ViewInputModifier::None);\n\n    tip.add (event, QObject::tr (\"Exit\"));\n    this->shortcuts.push_back (new QShortcut (keys, &this->mainWindow));\n\n    QObject::connect (this->shortcuts.back (), &QShortcut::activated, [this]() {\n#ifndef NDEBUG\n      if (this->hasTool ())\n      {\n        this->resetTool ();\n      }\n      else\n      {\n        this->mainWindow.close ();\n      }\n#else\n      assert (this->hasTool ());\n      this->resetTool ();\n#endif\n    });\n  }\n\n  void setToolTip (const ViewToolTip* toolSpecificToolTip, const ViewShortcuts& shortcuts)\n  {\n    for (QShortcut* s : this->shortcuts)\n    {\n      delete s;\n    }\n    this->shortcuts.clear ();\n    this->mainWindow.infoPane ().resetToolTip ();\n\n    if (toolSpecificToolTip)\n    {\n      this->mainWindow.infoPane ().addToolTip (*toolSpecificToolTip);\n    }\n\n    ViewToolTip tip;\n    for (const ViewShortcut& s : shortcuts)\n    {\n      this->addToolShortcut (s, tip);\n    }\n\n    if (this->hasTool () == false || this->toolPtr->getKey () != ToolKey::MoveCamera)\n    {\n      this->addToolShortcut (ToolKey::MoveCamera, tip, ViewInputEvent::Space,\n                             QObject::tr (\"Camera mode\"));\n    }\n\n    switch (this->mainWindow.toolPane ().selection ())\n    {\n      case ViewToolPaneSelection::Sculpt:\n        if (this->hasTool () == false)\n        {\n          this->addToolShortcut (ToolKey::SculptDraw, tip, ViewInputEvent::D);\n          this->addToolShortcut (ToolKey::SculptCrease, tip, ViewInputEvent::C);\n          this->addToolShortcut (ToolKey::SculptGrab, tip, ViewInputEvent::G);\n          this->addToolShortcut (ToolKey::SculptPinch, tip, ViewInputEvent::P);\n          this->addToolShortcut (ToolKey::SculptSmooth, tip, ViewInputEvent::S);\n          this->addToolShortcut (ToolKey::SculptFlatten, tip, ViewInputEvent::F);\n          this->addToolShortcut (ToolKey::SculptReduce, tip, ViewInputEvent::R);\n          this->addToolShortcut (ToolKey::TrimMesh, tip, ViewInputEvent::T);\n          this->addToolShortcut (ToolKey::Remesh, tip, ViewInputEvent::M);\n#ifndef NDEBUG\n          this->addExitToolShortcut (tip, ViewInputEvent::Esc);\n#endif\n        }\n        else\n        {\n          const bool smoothShortcut = (this->toolPtr->getKey () == ToolKey::SculptDraw) ||\n                                      (this->toolPtr->getKey () == ToolKey::SculptCrease) ||\n                                      (this->toolPtr->getKey () == ToolKey::SculptGrab) ||\n                                      (this->toolPtr->getKey () == ToolKey::SculptFlatten) ||\n                                      (this->toolPtr->getKey () == ToolKey::SculptPinch) ||\n                                      (this->toolPtr->getKey () == ToolKey::SculptReduce) ||\n                                      (this->toolPtr->getKey () == ToolKey::TrimMesh) ||\n                                      (this->toolPtr->getKey () == ToolKey::Remesh);\n\n          const bool toggleBackFromSmooth = (this->toolPtr->getKey () == ToolKey::SculptSmooth) &&\n                                            this->previousToolKey &&\n                                            (*this->previousToolKey != ToolKey::SculptSmooth);\n\n          if (smoothShortcut)\n          {\n            this->addToolShortcut (ToolKey::SculptSmooth, tip, ViewInputEvent::S);\n          }\n          else if (toggleBackFromSmooth)\n          {\n            this->addToggleToolShortcut (tip, ViewInputEvent::S);\n          }\n          this->addExitToolShortcut (tip, ViewInputEvent::Esc);\n        }\n        break;\n      case ViewToolPaneSelection::Sketch:\n        if (this->hasTool () == false)\n        {\n#ifndef NDEBUG\n          this->addExitToolShortcut (tip, ViewInputEvent::Esc);\n#endif\n        }\n        else\n        {\n          this->addExitToolShortcut (tip, ViewInputEvent::Esc);\n        }\n        break;\n    }\n    this->mainWindow.infoPane ().addToolTip (tip);\n\n    if (this->hasTool () == false || this->toolPtr->getKey () != ToolKey::MoveCamera)\n    {\n      tip.reset ();\n      tip.add (ViewInputEvent::MouseMiddle, QObject::tr (\"Drag to rotate\"));\n      tip.add (ViewInputEvent::MouseMiddle, ViewInputModifier::Shift, QObject::tr (\"Drag to move\"));\n      tip.add (ViewInputEvent::MouseMiddle, ViewInputModifier::Ctrl, QObject::tr (\"Drag to zoom\"));\n      tip.add (ViewInputEvent::MouseMiddle, ViewInputModifier::Alt, QObject::tr (\"Gaze\"));\n      tip.add (ViewInputEvent::MouseWheel, QObject::tr (\"Zoom\"));\n      this->mainWindow.infoPane ().addToolTip (tip);\n    }\n  }\n\n  void setToolTip (const ViewToolTip* toolSpecificToolTip)\n  {\n    this->setToolTip (toolSpecificToolTip, {});\n  }\n\n  void setTool (ToolKey key)\n  {\n    if (this->hasTool ())\n    {\n      this->resetTool ();\n    }\n#define SET_TOOL(name)                                  \\\n  case ToolKey::name:                                   \\\n    this->toolPtr.reset (new Tool##name (*this->self)); \\\n    break;\n\n    switch (key)\n    {\n      SET_TOOL (TransformMesh)\n      SET_TOOL (DeleteMesh)\n      SET_TOOL (NewMesh)\n      SET_TOOL (SculptDraw)\n      SET_TOOL (SculptGrab)\n      SET_TOOL (SculptSmooth)\n      SET_TOOL (SculptFlatten)\n      SET_TOOL (SculptCrease)\n      SET_TOOL (SculptPinch)\n      SET_TOOL (SculptReduce)\n      SET_TOOL (EditSketch)\n      SET_TOOL (DeleteSketch)\n      SET_TOOL (ConvertSketch)\n      SET_TOOL (SketchSpheres)\n      SET_TOOL (TrimMesh)\n      SET_TOOL (Remesh)\n      SET_TOOL (MoveCamera)\n    }\n#undef SET_TOOL\n\n    this->mainWindow.toolPane ().setButtonState (this->toolPtr->getKey (), true);\n\n    ToolResponse initResponse = this->toolPtr->initialize ();\n    switch (initResponse)\n    {\n      case ToolResponse::None:\n        this->handleToolResponse (ToolResponse::Redraw);\n        break;\n      default:\n        this->handleToolResponse (initResponse);\n        break;\n    }\n  }\n\n  void setPreviousTool ()\n  {\n    if (this->previousToolKey)\n    {\n      this->setTool (*this->previousToolKey);\n    }\n    else\n    {\n      this->resetTool ();\n    }\n  }\n\n  void resetTool ()\n  {\n    if (this->hasTool ())\n    {\n      if (this->toolPtr->getKey () != ToolKey::MoveCamera)\n      {\n        this->previousToolKey = this->toolPtr->getKey ();\n      }\n      this->mainWindow.toolPane ().setButtonState (this->toolPtr->getKey (), false);\n      this->toolPtr->commit ();\n      this->toolPtr.reset ();\n\n      this->mainWindow.toolPane ().properties ().reset ();\n      this->mainWindow.update ();\n    }\n    this->setToolTip (nullptr);\n  }\n\n  void fromConfig ()\n  {\n    this->camera.fromConfig (this->config);\n    this->history.fromConfig (this->config);\n    this->scene.fromConfig (this->config);\n\n    if (this->hasTool ())\n    {\n      this->toolPtr->fromConfig ();\n    }\n  }\n\n  void undo ()\n  {\n    if (this->hasTool ())\n    {\n      this->handleToolResponse (this->toolPtr->commit ());\n    }\n    this->history.undo (*this->self);\n    this->mainWindow.update ();\n  }\n\n  void redo ()\n  {\n    if (this->hasTool ())\n    {\n      this->handleToolResponse (this->toolPtr->commit ());\n    }\n    this->history.redo (*this->self);\n    this->mainWindow.update ();\n  }\n\n  void handleToolResponse (ToolResponse response)\n  {\n    switch (response)\n    {\n      case ToolResponse::None:\n        break;\n      case ToolResponse::Redraw:\n        this->mainWindow.update ();\n        break;\n      case ToolResponse::Terminate:\n        this->resetTool ();\n        break;\n    }\n  }\n};\n\nDELEGATE3_BIG2_SELF (State, ViewMainWindow&, Config&, Cache&)\n\nGETTER (ViewMainWindow&, State, mainWindow)\nGETTER (Config&, State, config)\nGETTER (Cache&, State, cache)\nGETTER (Camera&, State, camera)\nGETTER (History&, State, history)\nGETTER (Scene&, State, scene)\nDELEGATE (bool, State, hasTool)\nDELEGATE (Tool&, State, tool)\nDELEGATE1 (void, State, setTool, ToolKey)\nDELEGATE (void, State, setPreviousTool)\nDELEGATE2 (void, State, setToolTip, const ViewToolTip*, const ViewShortcuts&)\nDELEGATE1 (void, State, setToolTip, const ViewToolTip*)\nDELEGATE (void, State, resetTool)\nDELEGATE (void, State, fromConfig)\nDELEGATE (void, State, undo)\nDELEGATE (void, State, redo)\nDELEGATE1 (void, State, handleToolResponse, ToolResponse)\n"
  },
  {
    "path": "lib/src/state.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_STATE\n#define DILAY_STATE\n\n#include <initializer_list>\n#include \"macro.hpp\"\n\nclass Cache;\nclass Camera;\nclass Config;\nclass History;\nclass Id;\nclass Mesh;\nclass Scene;\nclass Tool;\nenum class ToolKey;\nenum class ToolResponse;\nclass ViewMainWindow;\nclass ViewShortcut;\nclass ViewToolTip;\n\nclass State\n{\npublic:\n  typedef std::initializer_list<ViewShortcut> ViewShortcuts;\n\n  DECLARE_BIG2 (State, ViewMainWindow&, Config&, Cache&)\n\n  ViewMainWindow& mainWindow ();\n  Config&         config ();\n  Cache&          cache ();\n  Camera&         camera ();\n  History&        history ();\n  Scene&          scene ();\n  bool            hasTool ();\n  Tool&           tool ();\n  void            setTool (ToolKey);\n  void            setPreviousTool ();\n  void            setToolTip (const ViewToolTip*, const ViewShortcuts&);\n  void            setToolTip (const ViewToolTip*);\n  void            resetTool ();\n  void            fromConfig ();\n  void            undo ();\n  void            redo ();\n\n  void handleToolResponse (ToolResponse);\n\nprivate:\n  IMPLEMENTATION\n};\n#endif\n"
  },
  {
    "path": "lib/src/time-delta.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <unordered_map>\n#include \"time-delta.hpp\"\n\nnamespace TimeDelta\n{\n  struct TimeData\n  {\n    unsigned int numCalls;\n    std::clock_t localTime;\n\n    TimeData (std::clock_t c)\n      : numCalls (1)\n      , localTime (c)\n    {\n    }\n\n    void call (std::clock_t c)\n    {\n      this->localTime += c;\n      this->numCalls++;\n    }\n  };\n\n  const unsigned int                        nameWidth = 80;\n  std::unordered_map<std::string, TimeData> data;\n  std::clock_t                              globalTime;\n  std::clock_t                              startTime;\n\n  void printResults ()\n  {\n    if (data.empty () == false)\n    {\n      const std::streamsize originalPrec = std::cout.precision ();\n\n      std::cout << \"##### time-delta (\" << (float(globalTime) / CLOCKS_PER_SEC) << \"s) ######\\n\";\n\n      for (auto pair : data)\n      {\n        std::cout << std::setw (nameWidth + 1) << std::left << pair.first\n                  << std::resetiosflags (std::ios_base::left)\n                  << (float(pair.second.localTime) / CLOCKS_PER_SEC) << \"s (\" << std::fixed\n                  << std::setprecision (1)\n                  << (100.0f * float(pair.second.localTime) / float(globalTime)) << \"%) \"\n                  << std::defaultfloat << std::setprecision (originalPrec) << \"(\"\n                  << pair.second.numCalls << \" calls -> \"\n                  << (1000.0f * (float(pair.second.localTime) / CLOCKS_PER_SEC) /\n                      float(pair.second.numCalls))\n                  << \"ms / call)\\n\";\n      }\n    }\n  }\n\n  void initialize ()\n  {\n    globalTime = 0;\n    std::atexit (TimeDelta::printResults);\n  }\n\n  void resetTimer () { startTime = std::clock (); }\n  void addBreakpoint (const char* name)\n  {\n    const std::clock_t diff = std::clock () - startTime;\n    const std::string  key = std::string (name).substr (0, nameWidth);\n    auto               it = data.find (key);\n\n    if (it == data.end ())\n    {\n      data.emplace (key, TimeData (diff));\n    }\n    else\n    {\n      it->second.call (diff);\n    }\n    globalTime += diff;\n    TimeDelta::resetTimer ();\n  }\n}\n"
  },
  {
    "path": "lib/src/time-delta.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TIME_DELTA\n#define DILAY_TIME_DELTA\n\n#define TIME_DELTA(X)       \\\n  TimeDelta::resetTimer (); \\\n  X;                        \\\n  TimeDelta::addBreakpoint (#X);\n\nnamespace TimeDelta\n{\n  void initialize ();\n  void resetTimer ();\n  void addBreakpoint (const char*);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/convert-sketch.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include \"cache.hpp\"\n#include \"distance.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"isosurface-extraction.hpp\"\n#include \"mesh.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/cone-sphere.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/mesh-intersection.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/path.hpp\"\n#include \"state.hpp\"\n#include \"tool/sculpt/util/action.hpp\"\n#include \"tools.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/resolution-slider.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolConvertSketch::Impl\n{\n  ToolConvertSketch* self;\n  float              resolution;\n\n  Impl (ToolConvertSketch* s)\n    : self (s)\n    , resolution (s->cache ().get<float> (\"resolution\", 0.06))\n  {\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->setupProperties ();\n    this->setupToolTip ();\n\n    return ToolResponse::Redraw;\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    ViewResolutionSlider& resolutionEdit =\n      ViewUtil::resolutionSlider (0.01f, this->resolution, 0.1f);\n    ViewUtil::connect (resolutionEdit, [this](float r) {\n      this->resolution = r;\n      this->self->cache ().set (\"resolution\", r);\n    });\n    properties.addStacked (QObject::tr (\"Resolution\"), resolutionEdit);\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Convert selection\"));\n    this->self->state ().setToolTip (&toolTip);\n  }\n\n  DynamicMesh& convert (SketchMesh& sketch)\n  {\n    glm::vec3 min, max;\n    sketch.minMax (min, max);\n\n    const IsosurfaceExtraction::DistanceCallback getDistance = [&sketch](const glm::vec3& pos) {\n      float distance = Util::maxFloat ();\n\n      if (sketch.tree ().hasRoot ())\n      {\n        sketch.tree ().root ().forEachConstNode ([&pos, &distance](const SketchNode& node) {\n          const float d =\n            node.parent ()\n              ? Distance::distance (PrimConeSphere (node.data (), node.parent ()->data ()), pos)\n              : Distance::distance (node.data (), pos);\n\n          distance = glm::min (distance, d);\n        });\n      }\n      for (const SketchPath& p : sketch.paths ())\n      {\n        for (const PrimSphere& s : p.spheres ())\n        {\n          distance = glm::min (distance, Distance::distance (s, pos));\n        }\n      }\n      return distance;\n    };\n\n    sketch.optimizePaths ();\n    DynamicMesh mesh;\n    IsosurfaceExtraction::extract (getDistance, PrimAABox (min, max), this->resolution, mesh);\n\n    State& state = this->self->state ();\n    return state.scene ().newDynamicMesh (state.config (), mesh);\n  }\n\n  ToolResponse runReleaseEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton ())\n    {\n      SketchMeshIntersection intersection;\n      if (this->self->intersectsScene (e, intersection))\n      {\n        SketchMesh& sMesh = intersection.mesh ();\n\n        this->self->snapshotAll ();\n\n        ToolSculptAction::smoothMesh (this->convert (sMesh));\n        this->self->state ().scene ().deleteMesh (sMesh);\n        return ToolResponse::Redraw;\n      }\n    }\n    return ToolResponse::None;\n  }\n};\n\nDELEGATE_TOOL (ToolConvertSketch)\nDELEGATE_TOOL_RUN_RELEASE_EVENT (ToolConvertSketch)\n"
  },
  {
    "path": "lib/src/tool/delete-mesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QObject>\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"scene.hpp\"\n#include \"state.hpp\"\n#include \"tools.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/tool-tip.hpp\"\n\nstruct ToolDeleteMesh::Impl\n{\n  ToolDeleteMesh* self;\n\n  Impl (ToolDeleteMesh* s)\n    : self (s)\n  {\n  }\n\n  ToolResponse runInitialize ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Delete selection\"));\n    this->self->state ().setToolTip (&toolTip);\n\n    return ToolResponse::None;\n  }\n\n  ToolResponse runReleaseEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton ())\n    {\n      DynamicMeshIntersection intersection;\n      if (this->self->intersectsScene (e, intersection))\n      {\n        Scene& scene = this->self->state ().scene ();\n        this->self->snapshotDynamicMeshes ();\n        scene.deleteMesh (intersection.mesh ());\n        return ToolResponse::Redraw;\n      }\n    }\n    return ToolResponse::None;\n  }\n};\n\nDELEGATE_TOOL (ToolDeleteMesh)\nDELEGATE_TOOL_RUN_RELEASE_EVENT (ToolDeleteMesh)\n"
  },
  {
    "path": "lib/src/tool/delete-sketch.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include <QFrame>\n#include <QRadioButton>\n#include \"cache.hpp\"\n#include \"dimension.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/node-intersection.hpp\"\n#include \"sketch/path-intersection.hpp\"\n#include \"state.hpp\"\n#include \"tools.hpp\"\n#include \"util.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  enum class Mode\n  {\n    DeleteSketch,\n    DeleteNode,\n    DeleteSpheres\n  };\n}\n\nstruct ToolDeleteSketch::Impl\n{\n  ToolDeleteSketch* self;\n  Mode              mode;\n  bool              deleteChildren;\n\n  Impl (ToolDeleteSketch* s)\n    : self (s)\n    , mode (Mode (s->cache ().get<int> (\"mode\", int(Mode::DeleteNode))))\n    , deleteChildren (s->cache ().get<bool> (\"delete-children\", false))\n  {\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->self->supportsMirror ();\n\n    this->setupProperties ();\n    this->setupToolTip ();\n\n    return ToolResponse::None;\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    QCheckBox& deleteChildrenEdit =\n      ViewUtil::checkBox (QObject::tr (\"Delete children\"), this->deleteChildren);\n    ViewUtil::connect (deleteChildrenEdit, [this](bool m) {\n      this->deleteChildren = m;\n      this->self->cache ().set (\"delete-children\", m);\n    });\n    deleteChildrenEdit.setEnabled (this->mode == Mode::DeleteNode);\n\n    QRadioButton& deleteSketchEdit =\n      ViewUtil::radioButton (QObject::tr (\"Delete sketch\"), this->mode == Mode::DeleteSketch);\n    ViewUtil::connect (deleteSketchEdit, [this, &deleteChildrenEdit](bool m) {\n      this->mode = Mode::DeleteSketch;\n      this->self->cache ().set (\"mode\", int(this->mode));\n\n      deleteChildrenEdit.setEnabled (!m);\n      this->self->enableMirrorProperties (!m);\n    });\n\n    QRadioButton& deleteNodeEdit =\n      ViewUtil::radioButton (QObject::tr (\"Delete node\"), this->mode == Mode::DeleteNode);\n    ViewUtil::connect (deleteNodeEdit, [this, &deleteChildrenEdit](bool m) {\n      this->mode = Mode::DeleteNode;\n      this->self->cache ().set (\"mode\", int(this->mode));\n\n      deleteChildrenEdit.setEnabled (m);\n      this->self->enableMirrorProperties (m);\n    });\n\n    QRadioButton& deleteSpheresEdit =\n      ViewUtil::radioButton (QObject::tr (\"Delete spheres\"), this->mode == Mode::DeleteSpheres);\n    ViewUtil::connect (deleteSpheresEdit, [this, &deleteChildrenEdit](bool m) {\n      this->mode = Mode::DeleteSpheres;\n      this->self->cache ().set (\"mode\", int(this->mode));\n\n      deleteChildrenEdit.setEnabled (!m);\n      this->self->enableMirrorProperties (m);\n    });\n\n    properties.add (deleteSketchEdit);\n    properties.add (deleteNodeEdit);\n    properties.add (deleteSpheresEdit);\n    properties.add (ViewUtil::horizontalLine ());\n\n    this->self->addMirrorProperties ();\n    this->self->enableMirrorProperties (this->mode != Mode::DeleteSketch);\n\n    properties.add (deleteChildrenEdit);\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Delete selection\"));\n    this->self->state ().setToolTip (&toolTip);\n  }\n\n  ToolResponse runReleaseEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton ())\n    {\n      switch (this->mode)\n      {\n        case Mode::DeleteSketch:\n        {\n          SketchMeshIntersection intersection;\n          if (this->self->intersectsScene (e, intersection))\n          {\n            this->self->snapshotSketchMeshes ();\n            this->self->state ().scene ().deleteMesh (intersection.mesh ());\n          }\n          return ToolResponse::Redraw;\n        }\n        case Mode::DeleteNode:\n        {\n          SketchNodeIntersection intersection;\n          if (this->self->intersectsScene (e, intersection))\n          {\n            this->self->snapshotSketchMeshes ();\n            intersection.mesh ().deleteNode (intersection.node (), this->deleteChildren,\n                                             this->self->mirrorDimension ());\n            if (intersection.mesh ().isEmpty ())\n            {\n              this->self->state ().scene ().deleteMesh (intersection.mesh ());\n            }\n          }\n          return ToolResponse::Redraw;\n        }\n        case Mode::DeleteSpheres:\n        {\n          SketchPathIntersection intersection;\n          if (this->self->intersectsScene (e, intersection))\n          {\n            this->self->snapshotSketchMeshes ();\n            intersection.mesh ().deletePath (intersection.path (), this->self->mirrorDimension ());\n            if (intersection.mesh ().isEmpty ())\n            {\n              this->self->state ().scene ().deleteMesh (intersection.mesh ());\n            }\n          }\n          return ToolResponse::Redraw;\n        }\n      }\n    }\n    return ToolResponse::None;\n  }\n};\n\nDELEGATE_TOOL (ToolDeleteSketch)\nDELEGATE_TOOL_RUN_RELEASE_EVENT (ToolDeleteSketch)\n"
  },
  {
    "path": "lib/src/tool/edit-sketch.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include <QSlider>\n#include \"cache.hpp\"\n#include \"camera.hpp\"\n#include \"mirror.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/bone-intersection.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/node-intersection.hpp\"\n#include \"state.hpp\"\n#include \"tool/util/movement.hpp\"\n#include \"tool/util/rotation.hpp\"\n#include \"tool/util/scaling.hpp\"\n#include \"tools.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolEditSketch::Impl\n{\n  ToolEditSketch*  self;\n  SketchMesh*      mesh;\n  SketchNode*      node;\n  SketchNode*      parent;\n  ToolUtilMovement movement;\n  ToolUtilScaling  scaling;\n  ToolUtilRotation rotation;\n  bool             transformChildren;\n  bool             splitAndJoin;\n  bool             snap;\n  QSlider&         snapWidthEdit;\n\n  Impl (ToolEditSketch* s)\n    : self (s)\n    , mesh (nullptr)\n    , node (nullptr)\n    , parent (nullptr)\n    , movement (s->state ().camera (), false)\n    , scaling (s->state ().camera ())\n    , rotation (s->state ().camera ())\n    , transformChildren (s->cache ().get<bool> (\"transform-children\", false))\n    , splitAndJoin (s->cache ().get<bool> (\"split-and-join\", false))\n    , snap (s->cache ().get<bool> (\"snap\", true))\n    , snapWidthEdit (ViewUtil::slider (1, s->cache ().get<int> (\"snap-width\", 5), 10))\n  {\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->self->supportsMirror ();\n\n    this->setupProperties ();\n    this->setupToolTip ();\n\n    return ToolResponse::None;\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    this->self->addMirrorProperties ();\n    this->self->enableMirrorProperties (not this->splitAndJoin);\n\n    this->self->addMoveOnPrimaryPlaneProperties (this->movement);\n\n    QCheckBox& transformCEdit =\n      ViewUtil::checkBox (QObject::tr (\"Transform children\"), this->transformChildren);\n    ViewUtil::connect (transformCEdit, [this](bool m) {\n      this->transformChildren = m;\n      this->self->cache ().set (\"transform-children\", m);\n    });\n    transformCEdit.setEnabled (not this->splitAndJoin);\n    properties.add (transformCEdit);\n\n    QCheckBox& splitAndJoinEdit =\n      ViewUtil::checkBox (QObject::tr (\"Split and join\"), this->splitAndJoin);\n    properties.add (splitAndJoinEdit);\n\n    QCheckBox& snapEdit = ViewUtil::checkBox (QObject::tr (\"Snap\"), this->snap);\n    ViewUtil::connect (snapEdit, [this](bool s) {\n      this->snap = s;\n      this->snapWidthEdit.setEnabled (s);\n      this->self->cache ().set (\"snap\", s);\n    });\n    snapEdit.setEnabled (not this->splitAndJoin);\n    properties.add (snapEdit);\n\n    ViewUtil::connect (this->snapWidthEdit,\n                       [this](int w) { this->self->cache ().set (\"snap-width\", w); });\n    this->snapWidthEdit.setEnabled (this->snap && not this->splitAndJoin);\n    properties.addStacked (QObject::tr (\"Snap width\"), this->snapWidthEdit);\n\n    ViewUtil::connect (splitAndJoinEdit, [this, &transformCEdit, &snapEdit](bool s) {\n      this->splitAndJoin = s;\n      this->self->cache ().set (\"split-and-join\", s);\n      transformCEdit.setEnabled (not this->splitAndJoin);\n      snapEdit.setEnabled (not this->splitAndJoin);\n      this->snapWidthEdit.setEnabled (not this->splitAndJoin);\n      this->self->enableMirrorProperties (not this->splitAndJoin);\n    });\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Add new sketch\"));\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Drag node to move\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift,\n                 QObject::tr (\"Drag node to scale\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Ctrl,\n                 QObject::tr (\"Drag node to rotate\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Alt,\n                 QObject::tr (\"Drag node to add child\"));\n    toolTip.add (ViewInputEvent::R, QObject::tr (\"Click to set new root\"));\n    this->self->state ().setToolTip (&toolTip);\n  }\n\n  ToolResponse runMoveEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton () && this->node)\n    {\n      if (e.modifiers () == Qt::ShiftModifier)\n      {\n        if (this->scaling.move (e))\n        {\n          if (this->parent)\n          {\n            this->mesh->scale (*this->parent, this->scaling.factor (), false,\n                               this->self->mirrorDimension ());\n          }\n          this->mesh->scale (*this->node, this->scaling.factor (), this->transformChildren,\n                             this->self->mirrorDimension ());\n        }\n      }\n      else if (e.modifiers () == Qt::ControlModifier)\n      {\n        if (this->rotation.rotate (e))\n        {\n          this->mesh->rotate (*this->node, this->rotation.axis (), this->rotation.angle (),\n                              this->self->mirrorDimension ());\n        }\n      }\n      else if (this->movement.move (e))\n      {\n        if (this->parent)\n        {\n          this->mesh->move (*this->parent, this->movement.delta (), false,\n                            this->self->mirrorDimension ());\n        }\n\n        const bool transformChildren = this->transformChildren || this->splitAndJoin;\n        this->mesh->move (*this->node, this->movement.delta (), transformChildren,\n                          this->self->mirrorDimension ());\n      }\n      return ToolResponse::Redraw;\n    }\n    else\n    {\n      return ToolResponse::None;\n    }\n  }\n\n  ToolResponse runPressEvent (const ViewPointingEvent& e)\n  {\n    auto handleNodeIntersection = [this, &e](SketchNodeIntersection& intersection) {\n      this->self->snapshotSketchMeshes ();\n\n      this->movement.reset (intersection.position ());\n      this->scaling.reset (intersection.node ().data ().center (), intersection.position ());\n      this->rotation.reset (intersection.node ().data ().center ());\n\n      this->parent = nullptr;\n\n      if (e.modifiers () == Qt::NoModifier && this->splitAndJoin && intersection.node ().parent ())\n      {\n        SketchTree tree = intersection.mesh ().tree ().split (intersection.node ());\n\n        State&      state = this->self->state ();\n        SketchMesh& mesh = state.scene ().newSketchMesh (state.config (), tree);\n\n        this->mesh = &mesh;\n        this->node = &mesh.tree ().root ();\n        this->self->mirrorPosition (this->mesh->tree ().root ().data ().center ());\n      }\n      else if (e.modifiers () == Qt::NoModifier && this->self->onKeymap ('r'))\n      {\n        intersection.mesh ().rebalance (intersection.node ());\n\n        this->mesh = nullptr;\n        this->node = nullptr;\n        this->self->mirrorPosition (intersection.mesh ().tree ().root ().data ().center ());\n      }\n      else if (e.modifiers () == Qt::AltModifier)\n      {\n        SketchNode& iNode = intersection.node ();\n\n        const float radius =\n          iNode.numChildren () > 0 ? iNode.lastChild ().data ().radius () : iNode.data ().radius ();\n\n        this->mesh = &intersection.mesh ();\n        this->node = &this->mesh->addChild (iNode, iNode.data ().center (), radius,\n                                            this->self->mirrorDimension ());\n        this->self->mirrorPosition (this->mesh->tree ().root ().data ().center ());\n      }\n      else\n      {\n        this->mesh = &intersection.mesh ();\n        this->node = &intersection.node ();\n        this->self->mirrorPosition (this->mesh->tree ().root ().data ().center ());\n      }\n    };\n\n    auto handleBoneIntersection = [this, &e](SketchBoneIntersection& intersection) {\n      this->self->snapshotSketchMeshes ();\n\n      this->movement.reset (intersection.position ());\n      this->scaling.reset (intersection.projectedPosition (), intersection.position ());\n\n      const glm::vec3 axis =\n        intersection.parent ().data ().center () - intersection.child ().data ().center ();\n      this->rotation.reset (intersection.projectedPosition (), axis);\n\n      this->mesh = &intersection.mesh ();\n\n      this->self->mirrorPosition (intersection.mesh ().tree ().root ().data ().center ());\n\n      if (e.modifiers () == Qt::AltModifier)\n      {\n        const float radius =\n          glm::distance (intersection.projectedPosition (), intersection.position ());\n\n        this->parent = nullptr;\n        this->node =\n          &this->mesh->addParent (intersection.child (), intersection.projectedPosition (), radius,\n                                  this->self->mirrorDimension ());\n      }\n      else\n      {\n        this->node = &intersection.child ();\n        this->parent = &intersection.parent ();\n      }\n    };\n\n    if (e.leftButton ())\n    {\n      SketchNodeIntersection nodeIntersection;\n      SketchBoneIntersection boneIntersection;\n\n      if (this->self->intersectsScene (e, nodeIntersection))\n      {\n        handleNodeIntersection (nodeIntersection);\n        return ToolResponse::Redraw;\n      }\n      else if (this->self->intersectsScene (e, boneIntersection))\n      {\n        handleBoneIntersection (boneIntersection);\n        return ToolResponse::Redraw;\n      }\n      else if (e.modifiers () == Qt::NoModifier)\n      {\n        this->self->snapshotSketchMeshes ();\n\n        State&     state = this->self->state ();\n        SketchTree tree;\n        tree.emplaceRoot (state.camera ().viewPlaneIntersection (e.position ()), 0.1f);\n\n        state.scene ().newSketchMesh (state.config (), tree);\n\n        return this->runPressEvent (e);\n      }\n    }\n    return ToolResponse::None;\n  }\n\n  ToolResponse runReleaseEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton ())\n    {\n      if (this->splitAndJoin)\n      {\n        SketchNodeIntersection nodeIntersection;\n        if (this->self->intersectsScene (e, nodeIntersection, (const SketchNode*) this->node))\n        {\n          this->self->snapshotSketchMeshes ();\n\n          this->node->forEachChild (\n            [&nodeIntersection](SketchNode& child) { nodeIntersection.node ().addChild (child); });\n          this->self->state ().scene ().deleteMesh (*this->mesh);\n          this->node = &nodeIntersection.node ();\n          this->mesh = &nodeIntersection.mesh ();\n        }\n      }\n      return this->runCommit ();\n    }\n    return ToolResponse::None;\n  }\n\n  ToolResponse runCommit ()\n  {\n    if (this->snap && this->mesh && this->self->mirrorEnabled ())\n    {\n      PrimPlane mirrorPlane = this->mesh->mirrorPlane (*this->self->mirrorDimension ());\n\n      const auto isSnappable = [this, &mirrorPlane](const SketchNode& node) -> bool {\n        return mirrorPlane.absDistance (node.data ().center ()) <=\n               (this->snapWidthEdit.value ()) * this->self->mirror ().width ();\n      };\n\n      if (this->node && isSnappable (*this->node))\n      {\n        this->mesh->snap (*this->node, *this->self->mirrorDimension ());\n      }\n\n      if (this->parent && isSnappable (*this->parent))\n      {\n        this->mesh->snap (*this->parent, *this->self->mirrorDimension ());\n      }\n    }\n\n    if (this->mesh)\n    {\n      const bool selectedRootNode = this->node->parent () == nullptr;\n      const bool selectedRootBone = this->parent && this->parent->parent () == nullptr;\n\n      if (selectedRootNode || selectedRootBone)\n      {\n        this->self->mirrorPosition (this->mesh->tree ().root ().data ().center ());\n      }\n    }\n\n    this->mesh = nullptr;\n    this->node = nullptr;\n    this->parent = nullptr;\n\n    return ToolResponse::Redraw;\n  }\n};\n\nDELEGATE_TOOL (ToolEditSketch)\nDELEGATE_TOOL_RUN_MOVE_EVENT (ToolEditSketch)\nDELEGATE_TOOL_RUN_PRESS_EVENT (ToolEditSketch)\nDELEGATE_TOOL_RUN_RELEASE_EVENT (ToolEditSketch)\nDELEGATE_TOOL_RUN_COMMIT (ToolEditSketch)\n"
  },
  {
    "path": "lib/src/tool/key.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_KEY\n#define DILAY_TOOL_KEY\n\n#include <functional>\n\nenum class ToolKey\n{\n  TransformMesh,\n  DeleteMesh,\n  NewMesh,\n  SculptDraw,\n  SculptGrab,\n  SculptSmooth,\n  SculptFlatten,\n  SculptCrease,\n  SculptPinch,\n  SculptReduce,\n  EditSketch,\n  DeleteSketch,\n  ConvertSketch,\n  SketchSpheres,\n  TrimMesh,\n  Remesh,\n  MoveCamera\n};\n\nnamespace std\n{\n  template <> struct hash<ToolKey>\n  {\n    size_t operator() (const ToolKey& key) const { return std::hash<int> () (int(key)); }\n  };\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/move-camera.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QWheelEvent>\n#include <glm/gtc/constants.hpp>\n#include \"camera.hpp\"\n#include \"config.hpp\"\n#include \"dimension.hpp\"\n#include \"intersection.hpp\"\n#include \"state.hpp\"\n#include \"tools.hpp\"\n#include \"view/floor-plane.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/shortcut.hpp\"\n#include \"view/tool-tip.hpp\"\n\nstruct ToolMoveCamera::Impl\n{\n  ToolMoveCamera* self;\n  bool            isImmediateTool;\n  glm::ivec2      oldPos;\n  float           rotationFactor;\n  float           movementFactor;\n  float           zoomInMouseWheelFactor;\n\n  Impl (ToolMoveCamera* s, bool i)\n    : self (s)\n    , isImmediateTool (i)\n    , oldPos (s->state ().mainWindow ().glWidget ().cursorPosition ())\n  {\n  }\n\n  Impl (ToolMoveCamera* s)\n    : Impl (s, false)\n  {\n  }\n\n  ToolResponse runInitialize ()\n  {\n    if (this->isImmediateTool == false)\n    {\n      this->setupToolTip ();\n    }\n    return ToolResponse::None;\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Drag to rotate\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift, QObject::tr (\"Drag to move\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Ctrl, QObject::tr (\"Drag to zoom\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Alt, QObject::tr (\"Gaze\"));\n    toolTip.add (ViewInputEvent::C, ViewInputModifier::Shift, QObject::tr (\"Snap camera\"));\n    toolTip.add (ViewInputEvent::C, ViewInputModifier::Alt, QObject::tr (\"Reset gaze point\"));\n\n    const auto exitShortcut = ViewShortcut (ViewInputEvent::Space, QObject::tr (\"Exit camera mode\"),\n                                            [this]() { this->self->state ().setPreviousTool (); });\n\n    this->self->state ().setToolTip (&toolTip, {exitShortcut});\n  }\n\n  bool mouseButton (const ViewPointingEvent& e)\n  {\n    return this->isImmediateTool ? e.middleButton () : e.leftButton ();\n  }\n\n  ToolResponse runMoveEvent (const ViewPointingEvent& e)\n  {\n    if (this->mouseButton (e))\n    {\n      Camera&          cam = this->self->state ().camera ();\n      const glm::vec2& resolution = glm::vec2 (cam.resolution ());\n      const glm::vec2  delta = glm::vec2 (e.position ()) - glm::vec2 (this->oldPos);\n\n      if (e.modifiers () == Qt::NoModifier)\n      {\n        if (delta.x != 0.0f)\n        {\n          cam.verticalRotation (2.0f * glm::pi<float> () * this->rotationFactor * -delta.x /\n                                resolution.x);\n        }\n        if (delta.y != 0.0f)\n        {\n          cam.horizontalRotation (2.0f * glm::pi<float> () * this->rotationFactor * -delta.y /\n                                  resolution.y);\n        }\n      }\n      else if (e.modifiers () == Qt::ShiftModifier)\n      {\n        cam.setGaze (cam.gazePoint () + (this->movementFactor * delta.x * cam.right ()) +\n                     (this->movementFactor * -delta.y * cam.realUp ()));\n      }\n      else if (e.modifiers () == Qt::ControlModifier)\n      {\n        const float y = glm::clamp (delta.y, -50.0f, 50.0f);\n\n        if (y < 0.0f)\n        {\n          cam.stepAlongGaze (1.0f - (-y / 100.0f));\n        }\n        else if (y > 0.0f)\n        {\n          cam.stepAlongGaze (1.0f / (1.0f - (y / 100.0f)));\n        }\n        this->self->state ().mainWindow ().glWidget ().floorPlane ().update (cam);\n      }\n      this->oldPos = e.position ();\n      return ToolResponse::Redraw;\n    }\n    else\n    {\n      this->oldPos = e.position ();\n      return ToolResponse::None;\n    }\n  }\n\n  ToolResponse runPressEvent (const ViewPointingEvent& e)\n  {\n    if (this->mouseButton (e) && e.modifiers () == Qt::AltModifier)\n    {\n      Intersection intersection;\n      if (this->self->intersectsScene (e.position (), intersection))\n      {\n        Camera& camera = this->self->state ().camera ();\n        camera.set (intersection.position (), camera.position () - intersection.position ());\n        return ToolResponse::Redraw;\n      }\n    }\n    return ToolResponse::None;\n  }\n\n  void runFromConfig ()\n  {\n    const Config& config = this->self->config ();\n\n    this->rotationFactor = config.get<float> (\"editor/camera/rotation-factor\");\n    this->movementFactor = config.get<float> (\"editor/camera/movement-factor\");\n    this->zoomInMouseWheelFactor = config.get<float> (\"editor/camera/zoom-in-mouse-wheel-factor\");\n  }\n\n  ToolResponse wheelEvent (const QWheelEvent& e)\n  {\n    if (this->isImmediateTool && e.modifiers () == Qt::NoModifier &&\n        e.orientation () == Qt::Vertical)\n    {\n      Camera& camera = this->self->state ().camera ();\n\n      if (e.delta () > 0)\n      {\n        camera.stepAlongGaze (this->zoomInMouseWheelFactor);\n      }\n      else if (e.delta () < 0)\n      {\n        camera.stepAlongGaze (1.0f / this->zoomInMouseWheelFactor);\n      }\n      this->self->state ().mainWindow ().glWidget ().floorPlane ().update (camera);\n      return ToolResponse::Redraw;\n    }\n    return ToolResponse::None;\n  }\n\n  void snap ()\n  {\n    Camera& cam = this->self->state ().camera ();\n\n    auto snapTo = [&cam](Dimension d, bool forcePositive) {\n      const float gazeLength = glm::length (cam.toEyePoint ());\n      const float side =\n        (forcePositive || cam.toEyePoint ()[DimensionUtil::index (d)] > 0.0f) ? 1.0f : -1.0f;\n\n      const glm::vec3 toEyePoint = side * gazeLength * DimensionUtil::vector (d);\n\n      cam.set (cam.gazePoint (), toEyePoint);\n    };\n\n    auto isSnapped = [&cam](Dimension d) -> bool {\n      const float dot =\n        glm::abs (glm::dot (glm::normalize (cam.toEyePoint ()), DimensionUtil::vector (d)));\n      return dot > 1.0f - Util::epsilon ();\n    };\n\n    if (isSnapped (Dimension::X))\n    {\n      snapTo (Dimension::Y, true);\n    }\n    else if (isSnapped (Dimension::Y))\n    {\n      snapTo (Dimension::Z, true);\n    }\n    else if (isSnapped (Dimension::Z))\n    {\n      snapTo (Dimension::X, true);\n    }\n    else\n    {\n      snapTo (cam.primaryDimension (), false);\n    }\n    this->self->state ().mainWindow ().glWidget ().update ();\n  }\n\n  void resetGazePoint ()\n  {\n    Camera& cam = this->self->state ().camera ();\n\n    cam.set (glm::vec3 (0.0f), cam.position ());\n    this->self->state ().mainWindow ().glWidget ().update ();\n  }\n};\n\nDELEGATE_CONSTRUCTOR_BASE (ToolMoveCamera, (State & s, bool i), (this, i), Tool,\n                           (s, \"ToolMoveCamera\"))\nDELEGATE_TOOL (ToolMoveCamera)\nDELEGATE_TOOL_RUN_MOVE_EVENT (ToolMoveCamera)\nDELEGATE_TOOL_RUN_PRESS_EVENT (ToolMoveCamera)\nDELEGATE_TOOL_RUN_FROM_CONFIG (ToolMoveCamera)\nDELEGATE1 (ToolResponse, ToolMoveCamera, wheelEvent, const QWheelEvent&)\nDELEGATE (void, ToolMoveCamera, snap)\nDELEGATE (void, ToolMoveCamera, resetGazePoint)\n"
  },
  {
    "path": "lib/src/tool/move-camera.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_MOVE_CAMERA\n#define DILAY_TOOL_MOVE_CAMERA\n\n#include \"tool.hpp\"\n\nclass QWheelEvent;\n\nclass ToolMoveCamera : public Tool\n{\npublic:\n  DECLARE_BIG2 (ToolMoveCamera, State&)\n\n  ToolMoveCamera (State&, bool);\n\n  ToolKey getKey () const { return ToolKey::MoveCamera; }\n\n  ToolResponse wheelEvent (const QWheelEvent&);\n  void         snap ();\n  void         resetGazePoint ();\n\nprivate:\n  IMPLEMENTATION\n\n  ToolResponse runInitialize ();\n  ToolResponse runMoveEvent (const ViewPointingEvent&);\n  ToolResponse runPressEvent (const ViewPointingEvent&);\n  void         runFromConfig ();\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/new-mesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QSlider>\n#include \"cache.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"mesh-util.hpp\"\n#include \"mesh.hpp\"\n#include \"render-mode.hpp\"\n#include \"scene.hpp\"\n#include \"state.hpp\"\n#include \"tools.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  enum class MeshType\n  {\n    Icosphere,\n    Cube\n  };\n}\n\nstruct ToolNewMesh::Impl\n{\n  ToolNewMesh*                 self;\n  std::unique_ptr<DynamicMesh> mesh;\n  int                          subdivision;\n  MeshType                     meshType;\n\n  Impl (ToolNewMesh* s)\n    : self (s)\n    , subdivision (s->cache ().get<int> (\"subdivision\", 4))\n    , meshType (MeshType (s->cache ().get<int> (\"mesh-type\", int(MeshType::Icosphere))))\n  {\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->setupProperties ();\n    this->makeCurrentMesh ();\n    return ToolResponse::Redraw;\n  }\n\n  void runRender () const\n  {\n    if (this->mesh)\n    {\n      this->mesh->renderMode () = this->self->state ().scene ().commonRenderMode ();\n      this->mesh->render (this->self->state ().camera ());\n    }\n  }\n\n  ToolResponse runCommit ()\n  {\n    if (this->mesh)\n    {\n      this->self->snapshotDynamicMeshes ();\n      this->self->state ().scene ().newDynamicMesh (this->self->state ().config (), *this->mesh);\n    }\n    return ToolResponse::None;\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    QSlider& subdivisionEdit = ViewUtil::slider (1, this->subdivision, 6);\n    ViewUtil::connect (subdivisionEdit, [this](int r) {\n      this->subdivision = r;\n      this->self->cache ().set (\"subdivision\", r);\n      this->makeCurrentMesh ();\n    });\n    properties.addStacked (QObject::tr (\"Subdivisions\"), subdivisionEdit);\n\n    QButtonGroup& meshTypeEdit =\n      ViewUtil::buttonGroup ({QObject::tr (\"Icosphere\"), QObject::tr (\"Cube\")});\n    ViewUtil::connect (meshTypeEdit, int(this->meshType), [this](int id) {\n      this->meshType = MeshType (id);\n      this->self->cache ().set (\"mesh-type\", id);\n      this->makeCurrentMesh ();\n    });\n    properties.add (meshTypeEdit);\n  }\n\n  void makeCurrentMesh ()\n  {\n    switch (this->meshType)\n    {\n      case MeshType::Icosphere:\n        this->mesh = std::make_unique<DynamicMesh> (MeshUtil::icosphere (this->subdivision));\n        break;\n\n      case MeshType::Cube:\n        this->mesh = std::make_unique<DynamicMesh> (MeshUtil::cube (this->subdivision));\n        break;\n    }\n    this->self->state ().scene ().setupMesh (this->self->state ().config (), *this->mesh);\n    this->self->updateGlWidget ();\n  }\n};\n\nDELEGATE_TOOL (ToolNewMesh)\nDELEGATE_TOOL_RUN_RENDER (ToolNewMesh)\nDELEGATE_TOOL_RUN_COMMIT (ToolNewMesh)\n"
  },
  {
    "path": "lib/src/tool/remesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QPainter>\n#include \"cache.hpp\"\n#include \"color.hpp\"\n#include \"config.hpp\"\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"isosurface-extraction.hpp\"\n#include \"maybe.hpp\"\n#include \"mesh.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"scene.hpp\"\n#include \"state.hpp\"\n#include \"tool/sculpt/util/action.hpp\"\n#include \"tools.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/resolution-slider.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  enum class Mode\n  {\n    Normal,\n    Union,\n    Difference,\n    Intersection\n  };\n}\n\nstruct ToolRemesh::Impl\n{\n  ToolRemesh*       self;\n  float             resolution;\n  Mode              mode;\n  Maybe<glm::ivec2> pressPoint;\n\n  Impl (ToolRemesh* s)\n    : self (s)\n    , resolution (s->cache ().get<float> (\"resolution\", 0.06))\n    , mode (Mode (s->cache ().get<int> (\"mode\", int(Mode::Normal))))\n  {\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    QButtonGroup& modeEdit =\n      ViewUtil::buttonGroup ({QObject::tr (\"Normal\"), QObject::tr (\"Union\"),\n                              QObject::tr (\"Difference\"), QObject::tr (\"Intersection\")});\n    ViewUtil::connect (modeEdit, int(this->mode), [this](int id) {\n      this->mode = Mode (id);\n      this->self->cache ().set (\"mode\", id);\n    });\n    properties.add (modeEdit);\n\n    ViewResolutionSlider& resolutionEdit =\n      ViewUtil::resolutionSlider (0.02f, this->resolution, 0.1f);\n    ViewUtil::connect (resolutionEdit, [this](float r) {\n      this->resolution = r;\n      this->self->cache ().set (\"resolution\", r);\n    });\n    properties.addStacked (QObject::tr (\"Resolution\"), resolutionEdit);\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Remesh selection\"));\n    this->self->state ().setToolTip (&toolTip);\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->setupProperties ();\n    this->setupToolTip ();\n\n    return ToolResponse::None;\n  }\n\n  ToolResponse runMoveEvent (const ViewPointingEvent&)\n  {\n    return this->mode == Mode::Normal ? ToolResponse::None : ToolResponse::Redraw;\n  }\n\n  void remesh (DynamicMesh& mesh)\n  {\n    const IsosurfaceExtraction::IntersectionCallback getIntersection =\n      [&mesh](const PrimRay& ray, Intersection& intersection) {\n        if (mesh.intersects (ray, intersection, true))\n        {\n          return IsosurfaceExtraction::Intersection::Sample;\n        }\n        else\n        {\n          return IsosurfaceExtraction::Intersection::None;\n        }\n      };\n\n    const IsosurfaceExtraction::DistanceCallback getDistance = [&mesh](const glm::vec3& pos) {\n      return mesh.unsignedDistance (pos);\n    };\n\n    const PrimAABox bounds = mesh.mesh ().bounds ();\n    DynamicMesh     extractedMesh;\n    IsosurfaceExtraction::extract (getDistance, getIntersection, bounds, this->resolution,\n                                   extractedMesh);\n\n    State& state = this->self->state ();\n    state.scene ().deleteMesh (mesh);\n    DynamicMesh& dMesh = state.scene ().newDynamicMesh (state.config (), extractedMesh);\n    ToolSculptAction::smoothMesh (dMesh);\n  }\n\n  void remesh (DynamicMesh& meshA, DynamicMesh& meshB)\n  {\n    const IsosurfaceExtraction::IntersectionCallback getCommutativeIntersection =\n      [this, &meshA, &meshB](const PrimRay& ray, Intersection& intersection) {\n        assert (this->mode == Mode::Union || this->mode == Mode::Intersection);\n\n        Intersection intersectionA, intersectionB;\n        meshA.intersects (ray, intersectionA, true);\n        meshB.intersects (ray, intersectionB, true);\n\n        Intersection::sort (intersectionA, intersectionB);\n        intersection = intersectionA;\n\n        const bool intersectsA = intersectionA.isIntersection ();\n        const bool intersectsB = intersectionB.isIntersection ();\n\n        if (intersectsA && intersectsB)\n        {\n          const bool insideA = glm::dot (ray.direction (), intersectionA.normal ()) > 0.0f;\n          const bool insideB = glm::dot (ray.direction (), intersectionB.normal ()) > 0.0f;\n\n          if (insideA && insideB)\n          {\n            // (B (A o-> A) B)\n            // (A (B o-> A) B)\n            if (this->mode == Mode::Union)\n            {\n              return IsosurfaceExtraction::Intersection::Continue;\n            }\n            else\n            {\n              assert (this->mode == Mode::Intersection);\n              return IsosurfaceExtraction::Intersection::Sample;\n            }\n          }\n          else if (insideA && insideB == false)\n          {\n            // (A o-> A) (B B)\n            if (this->mode == Mode::Union)\n            {\n              return IsosurfaceExtraction::Intersection::Sample;\n            }\n            else\n            {\n              assert (this->mode == Mode::Intersection);\n              return IsosurfaceExtraction::Intersection::Continue;\n            }\n          }\n          else if (insideA == false && insideB)\n          {\n            // (B o-> (A A) B)\n            // (B o-> (A B) A)\n            if (this->mode == Mode::Union)\n            {\n              return IsosurfaceExtraction::Intersection::Continue;\n            }\n            else\n            {\n              assert (this->mode == Mode::Intersection);\n              return IsosurfaceExtraction::Intersection::Sample;\n            }\n          }\n          else if (insideA == false && insideB == false)\n          {\n            // o-> (A (B B) A)\n            // o-> (A (B A) B)\n            // o-> (A A) (B B)\n            if (this->mode == Mode::Union)\n            {\n              return IsosurfaceExtraction::Intersection::Sample;\n            }\n            else\n            {\n              assert (this->mode == Mode::Intersection);\n              return IsosurfaceExtraction::Intersection::Continue;\n            }\n          }\n          DILAY_IMPOSSIBLE\n        }\n        else if (intersectsA)\n        {\n          if (this->mode == Mode::Union)\n          {\n            return IsosurfaceExtraction::Intersection::Sample;\n          }\n          else\n          {\n            assert (this->mode == Mode::Intersection);\n            return IsosurfaceExtraction::Intersection::Continue;\n          }\n        }\n        else\n        {\n          assert (intersectsB == false);\n          return IsosurfaceExtraction::Intersection::None;\n        }\n        DILAY_IMPOSSIBLE\n      };\n\n    const IsosurfaceExtraction::IntersectionCallback getDifferenceIntersection =\n      [this, &meshA, &meshB](const PrimRay& ray, Intersection& intersection) {\n        assert (this->mode == Mode::Difference);\n\n        Intersection intersectionA, intersectionB;\n        const bool   intersectsA = meshA.intersects (ray, intersectionA, true);\n        const bool   intersectsB = meshB.intersects (ray, intersectionB, true);\n\n        if (intersectsA && intersectsB)\n        {\n          const bool insideA = glm::dot (ray.direction (), intersectionA.normal ()) > 0.0f;\n          const bool insideB = glm::dot (ray.direction (), intersectionB.normal ()) > 0.0f;\n          const bool aBeforeB = intersectionA.distance () < intersectionB.distance ();\n\n          intersection = aBeforeB ? intersectionA : intersectionB;\n\n          if (insideA && insideB)\n          {\n            if (aBeforeB)\n            {\n              // (B (A o-> A) B)\n              // (A (B o-> A) B)\n              return IsosurfaceExtraction::Intersection::Continue;\n            }\n            else\n            {\n              // (A (B o-> B) A)\n              // (B (A o-> B) A)\n              return IsosurfaceExtraction::Intersection::Sample;\n            }\n          }\n          else if (insideA && insideB == false)\n          {\n            // (A o-> A) (B B)\n            // (A o-> (B B) A)\n            // (A o-> (B A) B)\n            return IsosurfaceExtraction::Intersection::Sample;\n          }\n          else if (insideA == false && insideB)\n          {\n            // (B o-> B) (A A)\n            // (B o-> (A A) B)\n            // (B o-> (A B) A)\n            return IsosurfaceExtraction::Intersection::Continue;\n          }\n          else if (insideA == false && insideB == false)\n          {\n            if (aBeforeB)\n            {\n              // o-> (A (B B) A)\n              // o-> (A (B A) B)\n              // o-> (A A) (B B)\n              return IsosurfaceExtraction::Intersection::Sample;\n            }\n            else\n            {\n              // o-> (B (A A) B)\n              // o-> (B (A B) A)\n              // o-> (B B) (A A)\n              return IsosurfaceExtraction::Intersection::Continue;\n            }\n          }\n          DILAY_IMPOSSIBLE\n        }\n        else if (intersectsA)\n        {\n          intersection = intersectionA;\n          return IsosurfaceExtraction::Intersection::Sample;\n        }\n        else if (intersectsB)\n        {\n          intersection = intersectionB;\n          return IsosurfaceExtraction::Intersection::Continue;\n        }\n        else\n        {\n          return IsosurfaceExtraction::Intersection::None;\n        }\n        DILAY_IMPOSSIBLE\n      };\n\n    const IsosurfaceExtraction::DistanceCallback getDistance = [&meshA,\n                                                                &meshB](const glm::vec3& pos) {\n      return glm::min (meshA.unsignedDistance (pos), meshB.unsignedDistance (pos));\n    };\n\n    const PrimAABox boundsA = meshA.mesh ().bounds ();\n    const PrimAABox boundsB = meshB.mesh ().bounds ();\n    const glm::vec3 min = glm::min (boundsA.minimum (), boundsB.minimum ());\n    const glm::vec3 max = glm::max (boundsA.maximum (), boundsB.maximum ());\n    const PrimAABox bounds (min, max);\n\n    DynamicMesh extractedMesh;\n    if (this->mode == Mode::Difference)\n    {\n      IsosurfaceExtraction::extract (getDistance, getDifferenceIntersection, bounds,\n                                     this->resolution, extractedMesh);\n    }\n    else\n    {\n      IsosurfaceExtraction::extract (getDistance, getCommutativeIntersection, bounds,\n                                     this->resolution, extractedMesh);\n    }\n\n    State& state = this->self->state ();\n    state.scene ().deleteMesh (meshA);\n    state.scene ().deleteMesh (meshB);\n\n    if (extractedMesh.isEmpty () == false)\n    {\n      DynamicMesh& dMesh = state.scene ().newDynamicMesh (state.config (), extractedMesh);\n      ToolSculptAction::smoothMesh (dMesh);\n    }\n  }\n\n  ToolResponse runPressEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton () == false || this->mode == Mode::Normal)\n    {\n      return ToolResponse::None;\n    }\n    else\n    {\n      this->pressPoint = e.position ();\n      return ToolResponse::Redraw;\n    }\n  }\n\n  ToolResponse runReleaseEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton () == false)\n    {\n      return ToolResponse::None;\n    }\n    else\n    {\n      if (this->mode == Mode::Normal)\n      {\n        DynamicMeshIntersection intersection;\n        if (this->self->intersectsScene (e.position (), intersection))\n        {\n          this->self->snapshotDynamicMeshes ();\n          this->remesh (intersection.mesh ());\n          return ToolResponse::Redraw;\n        }\n        else\n        {\n          return ToolResponse::None;\n        }\n      }\n      else if (this->pressPoint)\n      {\n        DynamicMeshIntersection intersectionA;\n        DynamicMeshIntersection intersectionB;\n        const bool intersectsA = this->self->intersectsScene (*this->pressPoint, intersectionA);\n        const bool intersectsB = this->self->intersectsScene (e.position (), intersectionB);\n\n        this->pressPoint.reset ();\n\n        if (intersectsA && intersectsB)\n        {\n          this->self->snapshotDynamicMeshes ();\n          if (&intersectionA.mesh () == &intersectionB.mesh ())\n          {\n            this->remesh (intersectionA.mesh ());\n          }\n          else\n          {\n            this->remesh (intersectionA.mesh (), intersectionB.mesh ());\n          }\n          return ToolResponse::Redraw;\n        }\n        else\n        {\n          return ToolResponse::None;\n        }\n      }\n      else\n      {\n        return ToolResponse::None;\n      }\n    }\n  }\n\n  void runPaint (QPainter& painter) const\n  {\n    if (this->mode != Mode::Normal && this->pressPoint)\n    {\n      const QPoint cursorPos (ViewUtil::toQPoint (this->self->cursorPosition ()));\n\n      QPen pen (this->self->config ().get<Color> (\"editor/on-screen-color\").qColor ());\n      pen.setCapStyle (Qt::FlatCap);\n      pen.setWidth (2);\n\n      painter.setPen (pen);\n      painter.drawLine (ViewUtil::toQPoint (*this->pressPoint), cursorPos);\n    }\n  }\n\n  ToolResponse runCommit () { return ToolResponse::Redraw; }\n};\n\nDELEGATE_TOOL (ToolRemesh)\nDELEGATE_TOOL_RUN_MOVE_EVENT (ToolRemesh)\nDELEGATE_TOOL_RUN_PRESS_EVENT (ToolRemesh)\nDELEGATE_TOOL_RUN_RELEASE_EVENT (ToolRemesh)\nDELEGATE_TOOL_RUN_PAINT (ToolRemesh)\nDELEGATE_TOOL_RUN_COMMIT (ToolRemesh)\n"
  },
  {
    "path": "lib/src/tool/sculpt/crease.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include \"cache.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tools.hpp\"\n#include \"view/double-slider.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolSculptCrease::Impl\n{\n  ToolSculptCrease* self;\n\n  Impl (ToolSculptCrease* s)\n    : self (s)\n  {\n  }\n\n  void runSetupBrush (SculptBrush& brush)\n  {\n    auto& params = brush.initParameters<SBCreaseParameters> ();\n\n    params.intensity (this->self->cache ().get<float> (\"intensity\", 0.5f));\n    params.invert (this->self->cache ().get<bool> (\"invert\", false));\n  }\n\n  void runSetupCursor (ViewCursor&) {}\n\n  void runSetupProperties (ViewTwoColumnGrid& properties)\n  {\n    auto& params = this->self->brush ().parameters<SBCreaseParameters> ();\n\n    ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.1f, params.intensity (), 0.9f);\n    ViewUtil::connect (intensityEdit, [this, &params](float i) {\n      params.intensity (i);\n      this->self->cache ().set (\"intensity\", i);\n    });\n    properties.addStacked (QObject::tr (\"Intensity\"), intensityEdit);\n    this->self->registerSecondarySlider (intensityEdit);\n\n    QCheckBox& invertEdit = ViewUtil::checkBox (QObject::tr (\"Invert\"), params.invert ());\n    ViewUtil::connect (invertEdit, [this, &params](bool i) {\n      params.invert (i);\n      this->self->cache ().set (\"invert\", i);\n    });\n    properties.add (invertEdit);\n  }\n\n  void runSetupToolTip (ViewToolTip& toolTip)\n  {\n    this->self->addDefaultToolTip (toolTip, true, true);\n  }\n\n  bool runSculptPointingEvent (const ViewPointingEvent& e)\n  {\n    const std::function<void()> toggleInvert = [this]() {\n      this->self->brush ().parameters<SBCreaseParameters> ().toggleInvert ();\n    };\n    return this->self->drawlikeStroke (e, true, &toggleInvert);\n  }\n};\n\nDELEGATE_TOOL_SCULPT (ToolSculptCrease)\n"
  },
  {
    "path": "lib/src/tool/sculpt/draw.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include \"cache.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tools.hpp\"\n#include \"view/double-slider.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolSculptDraw::Impl\n{\n  ToolSculptDraw* self;\n\n  Impl (ToolSculptDraw* s)\n    : self (s)\n  {\n  }\n\n  void runSetupBrush (SculptBrush& brush)\n  {\n    auto& params = brush.initParameters<SBDrawParameters> ();\n\n    params.intensity (this->self->cache ().get<float> (\"intensity\", 0.5f));\n    params.invert (this->self->cache ().get<bool> (\"invert\", false));\n    params.constantHeight (this->self->cache ().get<bool> (\"constant-height\", false));\n  }\n\n  void runSetupCursor (ViewCursor&) {}\n\n  void runSetupProperties (ViewTwoColumnGrid& properties)\n  {\n    auto& params = this->self->brush ().parameters<SBDrawParameters> ();\n\n    ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.0f, params.intensity (), 1.0f);\n    ViewUtil::connect (intensityEdit, [this, &params](float i) {\n      params.intensity (i);\n      this->self->cache ().set (\"intensity\", i);\n    });\n    properties.addStacked (QObject::tr (\"Intensity\"), intensityEdit);\n    this->self->registerSecondarySlider (intensityEdit);\n\n    QCheckBox& invertEdit = ViewUtil::checkBox (QObject::tr (\"Invert\"), params.invert ());\n    ViewUtil::connect (invertEdit, [this, &params](bool i) {\n      params.invert (i);\n      this->self->cache ().set (\"invert\", i);\n    });\n    properties.add (invertEdit);\n\n    QCheckBox& constantHeightEdit =\n      ViewUtil::checkBox (QObject::tr (\"Constant height\"), params.constantHeight ());\n    ViewUtil::connect (constantHeightEdit, [this, &params](bool v) {\n      params.constantHeight (v);\n      this->self->cache ().set (\"constant-height\", v);\n    });\n    properties.add (constantHeightEdit);\n  }\n\n  void runSetupToolTip (ViewToolTip& toolTip)\n  {\n    this->self->addDefaultToolTip (toolTip, true, true);\n  }\n\n  bool runSculptPointingEvent (const ViewPointingEvent& e)\n  {\n    SBDrawParameters& params = this->self->brush ().parameters<SBDrawParameters> ();\n\n    const std::function<void()> toggleInvert = [&params]() { params.toggleInvert (); };\n    return this->self->drawlikeStroke (e, params.constantHeight (), &toggleInvert);\n  }\n};\n\nDELEGATE_TOOL_SCULPT (ToolSculptDraw)\n"
  },
  {
    "path": "lib/src/tool/sculpt/flatten.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include \"cache.hpp\"\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"state.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tool/util/movement.hpp\"\n#include \"tools.hpp\"\n#include \"view/double-slider.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolSculptFlatten::Impl\n{\n  ToolSculptFlatten* self;\n  ToolUtilMovement   movement;\n\n  Impl (ToolSculptFlatten* s)\n    : self (s)\n    , movement (this->self->state ().camera (), glm::vec3 (0.0f))\n  {\n  }\n\n  void runSetupBrush (SculptBrush& brush)\n  {\n    auto& params = brush.initParameters<SBFlattenParameters> ();\n\n    params.intensity (this->self->cache ().get<float> (\"intensity\", 0.5f));\n    params.lockPlane (this->self->cache ().get<bool> (\"lock-plane\", false));\n\n    brush.subdivide (false);\n  }\n\n  void runSetupCursor (ViewCursor&) {}\n\n  void runSetupProperties (ViewTwoColumnGrid& properties)\n  {\n    auto& params = this->self->brush ().parameters<SBFlattenParameters> ();\n\n    ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.1f, params.intensity (), 1.0f);\n    ViewUtil::connect (intensityEdit, [this, &params](float i) {\n      params.intensity (i);\n      this->self->cache ().set (\"intensity\", i);\n    });\n    properties.addStacked (QObject::tr (\"Intensity\"), intensityEdit);\n    this->self->registerSecondarySlider (intensityEdit);\n\n    QCheckBox& lockPlaneEdit = ViewUtil::checkBox (QObject::tr (\"Lock plane\"), params.lockPlane ());\n    ViewUtil::connect (lockPlaneEdit, [this, &params](bool v) {\n      params.lockPlane (v);\n      params.resetLockedPlane ();\n      this->self->cache ().set (\"lock-plane\", v);\n    });\n    properties.add (lockPlaneEdit);\n  }\n\n  void runSetupToolTip (ViewToolTip& toolTip)\n  {\n    this->self->addDefaultToolTip (toolTip, false, true);\n  }\n\n  bool runSculptPointingEvent (const ViewPointingEvent& e)\n  {\n    auto& params = this->self->brush ().parameters<SBFlattenParameters> ();\n\n    if (params.lockPlane ())\n    {\n      if (e.pressEvent ())\n      {\n        DynamicMeshIntersection intersection;\n        if (this->self->intersectsScene (e, intersection))\n        {\n          params.lockedPlane (PrimPlane (intersection.position (), intersection.normal ()));\n          this->movement.onFreePlane (intersection.normal ());\n        }\n        else\n        {\n          params.resetLockedPlane ();\n        }\n      }\n      return this->self->grablikeStroke (e, this->movement);\n    }\n    else\n    {\n      return this->self->drawlikeStroke (e, false);\n    }\n  }\n};\n\nDELEGATE_TOOL_SCULPT (ToolSculptFlatten)\n"
  },
  {
    "path": "lib/src/tool/sculpt/grab.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include \"cache.hpp\"\n#include \"state.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tool/util/movement.hpp\"\n#include \"tools.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolSculptGrab::Impl\n{\n  ToolSculptGrab*  self;\n  ToolUtilMovement movement;\n\n  Impl (ToolSculptGrab* s)\n    : self (s)\n    , movement (this->self->state ().camera (), false)\n  {\n  }\n\n  void runSetupBrush (SculptBrush& brush)\n  {\n    auto& params = brush.initParameters<SBGrablikeParameters> ();\n\n    params.discardBack (this->self->cache ().get<bool> (\"discard-back\", false));\n  }\n\n  void runSetupCursor (ViewCursor&) {}\n\n  void runSetupProperties (ViewTwoColumnGrid& properties)\n  {\n    auto& params = this->self->brush ().parameters<SBGrablikeParameters> ();\n\n    this->self->addMoveOnPrimaryPlaneProperties (this->movement);\n\n    QCheckBox& discardEdit =\n      ViewUtil::checkBox (QObject::tr (\"Discard backfaces\"), params.discardBack ());\n    ViewUtil::connect (discardEdit, [this, &params](bool d) {\n      params.discardBack (d);\n      this->self->cache ().set (\"discard-back\", d);\n    });\n    properties.add (discardEdit);\n  }\n\n  void runSetupToolTip (ViewToolTip& toolTip)\n  {\n    this->self->addDefaultToolTip (toolTip, false, false);\n  }\n\n  bool runSculptPointingEvent (const ViewPointingEvent& e)\n  {\n    return this->self->grablikeStroke (e, this->movement);\n  }\n};\n\nDELEGATE_TOOL_SCULPT (ToolSculptGrab)\n"
  },
  {
    "path": "lib/src/tool/sculpt/pinch.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include \"cache.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tools.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolSculptPinch::Impl\n{\n  ToolSculptPinch* self;\n\n  Impl (ToolSculptPinch* s)\n    : self (s)\n  {\n  }\n\n  void runSetupBrush (SculptBrush& brush)\n  {\n    auto& params = brush.initParameters<SBPinchParameters> ();\n\n    params.invert (this->self->cache ().get<bool> (\"invert\", false));\n  }\n\n  void runSetupCursor (ViewCursor&) {}\n\n  void runSetupProperties (ViewTwoColumnGrid& properties)\n  {\n    auto& params = this->self->brush ().parameters<SBPinchParameters> ();\n\n    QCheckBox& invertEdit = ViewUtil::checkBox (QObject::tr (\"Invert\"), params.invert ());\n    ViewUtil::connect (invertEdit, [this, &params](bool i) {\n      params.invert (i);\n      this->self->cache ().set (\"invert\", i);\n    });\n    properties.add (invertEdit);\n  }\n\n  void runSetupToolTip (ViewToolTip& toolTip)\n  {\n    this->self->addDefaultToolTip (toolTip, true, false);\n  }\n\n  bool runSculptPointingEvent (const ViewPointingEvent& e)\n  {\n    const std::function<void()> toggleInvert = [this]() {\n      this->self->brush ().parameters<SBPinchParameters> ().toggleInvert ();\n    };\n    return this->self->drawlikeStroke (e, false, &toggleInvert);\n  }\n};\n\nDELEGATE_TOOL_SCULPT (ToolSculptPinch)\n"
  },
  {
    "path": "lib/src/tool/sculpt/reduce.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"cache.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tools.hpp\"\n#include \"view/double-slider.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolSculptReduce::Impl\n{\n  ToolSculptReduce* self;\n\n  Impl (ToolSculptReduce* s)\n    : self (s)\n  {\n  }\n\n  void runSetupBrush (SculptBrush& brush)\n  {\n    auto& params = brush.initParameters<SBReduceParameters> ();\n\n    params.intensity (this->self->cache ().get<float> (\"intensity\", 0.5f));\n\n    brush.subdivide (false);\n  }\n\n  void runSetupCursor (ViewCursor&) {}\n\n  void runSetupProperties (ViewTwoColumnGrid& properties)\n  {\n    auto& params = this->self->brush ().parameters<SBReduceParameters> ();\n\n    ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.1f, params.intensity (), 0.9f);\n    ViewUtil::connect (intensityEdit, [this, &params](float i) {\n      params.intensity (i);\n      this->self->cache ().set (\"intensity\", i);\n    });\n    properties.addStacked (QObject::tr (\"Intensity\"), intensityEdit);\n    this->self->registerSecondarySlider (intensityEdit);\n  }\n\n  void runSetupToolTip (ViewToolTip& toolTip)\n  {\n    this->self->addDefaultToolTip (toolTip, false, true);\n  }\n\n  bool runSculptPointingEvent (const ViewPointingEvent& e)\n  {\n    return this->self->drawlikeStroke (e, false);\n  }\n};\n\nDELEGATE_TOOL_SCULPT (ToolSculptReduce)\n"
  },
  {
    "path": "lib/src/tool/sculpt/smooth.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include \"cache.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tools.hpp\"\n#include \"view/double-slider.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolSculptSmooth::Impl\n{\n  ToolSculptSmooth* self;\n\n  Impl (ToolSculptSmooth* s)\n    : self (s)\n  {\n  }\n\n  void runSetupBrush (SculptBrush& brush)\n  {\n    auto& params = brush.initParameters<SBSmoothParameters> ();\n\n    params.intensity (this->self->cache ().get<float> (\"intensity\", 0.5f));\n\n    brush.subdivide (false);\n  }\n\n  void runSetupCursor (ViewCursor&) {}\n\n  void runSetupProperties (ViewTwoColumnGrid& properties)\n  {\n    auto& params = this->self->brush ().parameters<SBSmoothParameters> ();\n\n    ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.1f, params.intensity (), 1.0f);\n    ViewUtil::connect (intensityEdit, [this, &params](float i) {\n      params.intensity (i);\n      this->self->cache ().set (\"intensity\", i);\n    });\n    properties.addStacked (QObject::tr (\"Intensity\"), intensityEdit);\n    this->self->registerSecondarySlider (intensityEdit);\n  }\n\n  void runSetupToolTip (ViewToolTip& toolTip)\n  {\n    this->self->addDefaultToolTip (toolTip, false, true);\n  }\n\n  bool runSculptPointingEvent (const ViewPointingEvent& e)\n  {\n    return this->self->drawlikeStroke (e, false);\n  }\n};\n\nDELEGATE_TOOL_SCULPT (ToolSculptSmooth)\n"
  },
  {
    "path": "lib/src/tool/sculpt/util/action.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <functional>\n#include <glm/glm.hpp>\n#include <glm/gtx/norm.hpp>\n#include \"dynamic/faces.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"intersection.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"tool/sculpt/util/action.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tool/sculpt/util/edge-collection.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  constexpr float minEdgeLength = 0.001f;\n\n  struct NewFaces\n  {\n    std::vector<unsigned int>        vertexIndices;\n    std::unordered_set<unsigned int> facesToDelete;\n\n    void reset ()\n    {\n      this->vertexIndices.clear ();\n      this->facesToDelete.clear ();\n    }\n\n    void addFace (unsigned int i1, unsigned int i2, unsigned int i3)\n    {\n      this->vertexIndices.push_back (i1);\n      this->vertexIndices.push_back (i2);\n      this->vertexIndices.push_back (i3);\n    }\n\n    void deleteFace (unsigned int i) { this->facesToDelete.insert (i); }\n\n    bool applyToMesh (DynamicMesh& mesh, DynamicFaces& faces) const\n    {\n      assert (this->vertexIndices.size () % 3 == 0);\n\n      for (unsigned int i : this->facesToDelete)\n      {\n        mesh.deleteFace (i);\n      }\n\n      for (unsigned int i = 0; i < this->vertexIndices.size (); i += 3)\n      {\n        const unsigned int f = mesh.addFace (this->vertexIndices[i + 0], this->vertexIndices[i + 1],\n                                             this->vertexIndices[i + 2]);\n\n        if (i >= this->facesToDelete.size () * 3)\n        {\n          faces.insert (f);\n        }\n      }\n      return this->facesToDelete.size () <= (this->vertexIndices.size () / 3);\n    }\n  };\n\n  void extendAndFilterDomain (const SculptBrush& brush, DynamicFaces& faces, unsigned int numRings)\n  {\n    assert (faces.hasUncomitted () == false);\n    const DynamicMesh& mesh = brush.mesh ();\n    const PrimSphere   sphere = brush.sphere ();\n\n    std::unordered_set<unsigned int> frontier;\n\n    faces.filter ([&mesh, &sphere, &frontier](unsigned int i) {\n      const PrimTriangle face = mesh.face (i);\n\n      if (IntersectionUtil::intersects (sphere, face) == false)\n      {\n        return false;\n      }\n      else if (sphere.contains (face) == false)\n      {\n        frontier.insert (i);\n      }\n      return true;\n    });\n\n    for (unsigned int ring = 0; ring < numRings; ring++)\n    {\n      std::unordered_set<unsigned int> extendedFrontier;\n\n      for (unsigned int i : frontier)\n      {\n        mesh.forEachVertexAdjacentToFace (\n          i, [&mesh, &faces, &frontier, &extendedFrontier](unsigned int v) {\n            for (unsigned int a : mesh.adjacentFaces (v))\n            {\n              if (faces.contains (a) == false && frontier.find (a) == frontier.end ())\n              {\n                faces.insert (a);\n                extendedFrontier.insert (a);\n              }\n            }\n          });\n      }\n      faces.commit ();\n      frontier = std::move (extendedFrontier);\n    }\n  }\n\n  void extendDomain (DynamicMesh& mesh, DynamicFaces& faces, unsigned int numRings)\n  {\n    assert (faces.hasUncomitted () == false);\n\n    for (unsigned int ring = 0; ring < numRings; ring++)\n    {\n      for (unsigned int i : faces)\n      {\n        mesh.forEachVertexAdjacentToFace (i, [&mesh, &faces](unsigned int v) {\n          for (unsigned int a : mesh.adjacentFaces (v))\n          {\n            if (faces.contains (a) == false)\n            {\n              faces.insert (a);\n            }\n          }\n        });\n      }\n      faces.commit ();\n    }\n  }\n\n  void extendDomainByPoles (DynamicMesh& mesh, DynamicFaces& faces)\n  {\n    assert (faces.hasUncomitted () == false);\n\n    mesh.forEachVertex (faces, [&mesh, &faces](unsigned int i) {\n      if (mesh.valence (i) > 6)\n      {\n        for (unsigned int a : mesh.adjacentFaces (i))\n        {\n          if (faces.contains (a) == false)\n          {\n            faces.insert (a);\n          }\n        }\n      }\n    });\n    faces.commit ();\n  }\n\n  glm::vec3 getSplitPosition (const DynamicMesh& mesh, unsigned int i1, unsigned int i2)\n  {\n    const glm::vec3& p1 = mesh.vertex (i1);\n    const glm::vec3& n1 = mesh.vertexNormal (i1);\n    const glm::vec3& p2 = mesh.vertex (i2);\n    const glm::vec3& n2 = mesh.vertexNormal (i2);\n\n    if (Util::colinearUnit (n1, n2))\n    {\n      return 0.5f * (p1 + p2);\n    }\n    else\n    {\n      const glm::vec3 n3 = glm::normalize (glm::cross (n1, n2));\n      const float     d1 = glm::dot (p1, n1);\n      const float     d2 = glm::dot (p2, n2);\n      const float     d3 = glm::dot (p1, n3);\n      const glm::vec3 p3 =\n        ((d1 * glm::cross (n2, n3)) + (d2 * glm::cross (n3, n1)) + (d3 * glm::cross (n1, n2))) /\n        (glm::dot (n1, glm::cross (n2, n3)));\n\n      return (p1 * 0.25f) + (p3 * 0.5f) + (p2 * 0.25f);\n    }\n  }\n\n  void splitEdges (DynamicMesh& mesh, ToolSculptEdgeMap& newE, float maxLength, DynamicFaces& faces)\n  {\n    assert (faces.hasUncomitted () == false);\n\n    const auto split = [&mesh, &newE, maxLength](unsigned int i1, unsigned int i2) {\n      if (glm::distance2 (mesh.vertex (i1), mesh.vertex (i2)) > maxLength * maxLength)\n      {\n        const glm::vec3 normal = glm::normalize (mesh.vertexNormal (i1) + mesh.vertexNormal (i2));\n        const unsigned int i3 = mesh.addVertex (getSplitPosition (mesh, i1, i2), normal);\n        newE.insert (i1, i2, i3);\n        return true;\n      }\n      else\n      {\n        return false;\n      }\n    };\n\n    faces.filter ([&mesh, &newE, &split](unsigned int f) {\n      bool wasSplit = false;\n\n      unsigned int i1, i2, i3;\n      mesh.vertexIndices (f, i1, i2, i3);\n\n      if (newE.contains (i1, i2) == false)\n      {\n        wasSplit = split (i1, i2) || wasSplit;\n      }\n\n      if (newE.contains (i1, i3) == false)\n      {\n        wasSplit = split (i1, i3) || wasSplit;\n      }\n\n      if (newE.contains (i2, i3) == false)\n      {\n        wasSplit = split (i2, i3) || wasSplit;\n      }\n      return wasSplit;\n    });\n  }\n\n  void triangulate (DynamicMesh& mesh, const ToolSculptEdgeMap& newE, DynamicFaces& faces)\n  {\n    assert (faces.hasUncomitted () == false);\n\n    NewFaces newF;\n\n    mesh.forEachFaceExt (faces, [&mesh, &newE, &newF](unsigned int f) {\n      unsigned int i1, i2, i3;\n      mesh.vertexIndices (f, i1, i2, i3);\n\n      const unsigned int e12 = newE.find (i1, i2);\n      const unsigned int e13 = newE.find (i1, i3);\n      const unsigned int e23 = newE.find (i2, i3);\n      const unsigned int invalid = Util::invalidIndex ();\n\n      const unsigned int v1 = mesh.valence (i1);\n      const unsigned int v2 = mesh.valence (i2);\n      const unsigned int v3 = mesh.valence (i3);\n\n      if (e12 == invalid && e13 == invalid && e23 == invalid)\n      {\n      }\n      // One new vertex\n      else if (e12 != invalid && e13 == invalid && e23 == invalid)\n      {\n        newF.deleteFace (f);\n        newF.addFace (i1, e12, i3);\n        newF.addFace (i3, e12, i2);\n      }\n      else if (e12 == invalid && e13 != invalid && e23 == invalid)\n      {\n        newF.deleteFace (f);\n        newF.addFace (i3, e13, i2);\n        newF.addFace (i2, e13, i1);\n      }\n      else if (e12 == invalid && e13 == invalid && e23 != invalid)\n      {\n        newF.deleteFace (f);\n        newF.addFace (i2, e23, i1);\n        newF.addFace (i1, e23, i3);\n      }\n      // Two new vertices\n      else if (e12 != invalid && e13 != invalid && e23 == invalid)\n      {\n        newF.deleteFace (f);\n        newF.addFace (e12, e13, i1);\n\n        if (v2 < v3)\n        {\n          newF.addFace (i2, i3, e13);\n          newF.addFace (i2, e13, e12);\n        }\n        else\n        {\n          newF.addFace (i3, e12, i2);\n          newF.addFace (i3, e13, e12);\n        }\n      }\n      else if (e12 != invalid && e13 == invalid && e23 != invalid)\n      {\n        newF.deleteFace (f);\n        newF.addFace (e23, e12, i2);\n\n        if (v1 < v3)\n        {\n          newF.addFace (i1, e23, i3);\n          newF.addFace (i1, e12, e23);\n        }\n        else\n        {\n          newF.addFace (i3, i1, e12);\n          newF.addFace (i3, e12, e23);\n        }\n      }\n      else if (e12 == invalid && e13 != invalid && e23 != invalid)\n      {\n        newF.deleteFace (f);\n        newF.addFace (e13, e23, i3);\n\n        if (v1 < v2)\n        {\n          newF.addFace (i1, i2, e23);\n          newF.addFace (i1, e23, e13);\n        }\n        else\n        {\n          newF.addFace (i2, e13, i1);\n          newF.addFace (i2, e23, e13);\n        }\n      }\n      // Three new vertices\n      else if (e12 != invalid && e13 != invalid && e23 != invalid)\n      {\n        newF.deleteFace (f);\n        newF.addFace (e12, e23, e13);\n        newF.addFace (i1, e12, e13);\n        newF.addFace (i2, e23, e12);\n        newF.addFace (i3, e13, e23);\n      }\n      else\n      {\n        DILAY_IMPOSSIBLE\n      }\n    });\n    const bool increasing = newF.applyToMesh (mesh, faces);\n    assert (increasing);\n    unused (increasing);\n\n    faces.commit ();\n  }\n\n  void relaxEdges (DynamicMesh& mesh, const DynamicFaces& faces)\n  {\n    assert (faces.hasUncomitted () == false);\n\n    const auto isRelaxable = [&mesh](const ui_pair& edge, unsigned int leftVertex,\n                                     unsigned int rightVertex) {\n      const int vE1 = int(mesh.valence (edge.first));\n      const int vE2 = int(mesh.valence (edge.second));\n      const int vL = int(mesh.valence (leftVertex));\n      const int vR = int(mesh.valence (rightVertex));\n\n      const int pre =\n        glm::abs (vE1 - 6) + glm::abs (vE2 - 6) + glm::abs (vL - 6) + glm::abs (vR - 6);\n      const int post = glm::abs (vE1 - 6 - 1) + glm::abs (vE2 - 6 - 1) + glm::abs (vL - 6 + 1) +\n                       glm::abs (vR - 6 + 1);\n\n      return (vE1 > 3) && (vE2 > 3) && (post < pre);\n    };\n\n    ToolSculptEdgeSet edgeSet;\n    mesh.forEachVertex (faces, [&mesh, &edgeSet](unsigned int i) {\n      if (mesh.valence (i) > 6)\n      {\n        mesh.forEachVertexAdjacentToVertex (\n          i, [i, &edgeSet](unsigned int j) { edgeSet.insert (i, j); });\n      }\n    });\n\n    for (const ui_pair& edge : edgeSet)\n    {\n      unsigned int leftFace, leftVertex, rightFace, rightVertex;\n      mesh.findAdjacent (edge.first, edge.second, leftFace, leftVertex, rightFace, rightVertex);\n\n      if (isRelaxable (edge, leftVertex, rightVertex))\n      {\n        mesh.deleteFace (leftFace);\n        mesh.deleteFace (rightFace);\n\n        const unsigned int newLeftFace = mesh.addFace (leftVertex, edge.first, rightVertex);\n        const unsigned int newRightFace = mesh.addFace (rightVertex, edge.second, leftVertex);\n\n        assert (newLeftFace == rightFace);\n        assert (newRightFace == leftFace);\n        unused (newLeftFace);\n        unused (newRightFace);\n      }\n    }\n  }\n\n  void smooth (DynamicMesh& mesh, DynamicFaces& faces)\n  {\n    std::unordered_map<unsigned int, glm::vec3> newPosition;\n\n    mesh.forEachVertex (faces, [&mesh, &newPosition](unsigned int i) {\n      const glm::vec3  avgPos = mesh.averagePosition (i);\n      const glm::vec3& normal = mesh.vertexNormal (i);\n      const glm::vec3  delta = avgPos - mesh.vertex (i);\n      const glm::vec3  tangentialPos = avgPos - (normal * glm::dot (normal, delta));\n\n      constexpr float lo = -Util::epsilon ();\n      constexpr float hi = 1.0f + Util::epsilon ();\n\n      float     minDistance = Util::maxFloat ();\n      glm::vec3 projectedPos (0.0f);\n\n      for (unsigned int a : mesh.adjacentFaces (i))\n      {\n        unsigned int i1, i2, i3;\n        mesh.vertexIndices (a, i1, i2, i3);\n\n        const glm::vec3& p1 = mesh.vertex (i1);\n        const glm::vec3& p2 = mesh.vertex (i2);\n        const glm::vec3& p3 = mesh.vertex (i3);\n\n        const glm::vec3 u = p2 - p1;\n        const glm::vec3 v = p3 - p1;\n        const glm::vec3 w = tangentialPos - p1;\n        const glm::vec3 n = glm::cross (u, v);\n\n        const float b1 = glm::dot (glm::cross (u, w), n) / (glm::dot (n, n));\n        const float b2 = glm::dot (glm::cross (w, v), n) / (glm::dot (n, n));\n        const float b3 = 1.0f - b1 - b2;\n\n        if (lo < b1 && b1 < hi && lo < b2 && b2 < hi && lo < b3 && b3 < hi)\n        {\n          const glm::vec3 proj = (b3 * p1) + (b2 * p2) + (b1 * p3);\n          const float     d = glm::distance2 (tangentialPos, proj);\n\n          if (d < minDistance)\n          {\n            minDistance = d;\n            projectedPos = proj;\n          }\n        }\n      }\n      if (minDistance != Util::maxFloat ())\n      {\n        newPosition.emplace (i, projectedPos);\n      }\n      else\n      {\n        newPosition.emplace (i, tangentialPos);\n      }\n    });\n\n    for (const auto& it : newPosition)\n    {\n      mesh.vertex (it.first, it.second);\n    }\n  }\n\n  bool deleteValence3Vertex (DynamicMesh& mesh, unsigned int i, DynamicFaces& faces)\n  {\n    assert (mesh.isFreeVertex (i) == false);\n    assert (mesh.valence (i) == 3);\n\n    const unsigned int adj1 = mesh.adjacentFaces (i)[0];\n    const unsigned int adj2 = mesh.adjacentFaces (i)[1];\n    const unsigned int adj3 = mesh.adjacentFaces (i)[2];\n\n    unsigned int adj11, adj12, adj13;\n    mesh.vertexIndices (adj1, adj11, adj12, adj13);\n\n    unsigned int adj21, adj22, adj23;\n    mesh.vertexIndices (adj2, adj21, adj22, adj23);\n\n    unsigned int newI1, newI2, newI3;\n\n    if (i == adj11)\n    {\n      newI1 = adj12;\n      newI2 = adj13;\n    }\n    else if (i == adj12)\n    {\n      newI1 = adj13;\n      newI2 = adj11;\n    }\n    else if (i == adj13)\n    {\n      newI1 = adj11;\n      newI2 = adj12;\n    }\n    else\n    {\n      DILAY_IMPOSSIBLE\n    }\n\n    if (adj21 != newI1 && adj21 != newI2)\n    {\n      newI3 = adj21;\n    }\n    else if (adj22 != newI1 && adj22 != newI2)\n    {\n      newI3 = adj22;\n    }\n    else if (adj23 != newI1 && adj23 != newI2)\n    {\n      newI3 = adj23;\n    }\n    else\n    {\n      DILAY_IMPOSSIBLE\n    }\n    assert (newI1 != newI2);\n    assert (newI1 != newI3);\n    assert (newI2 != newI3);\n\n    if (mesh.valence (newI1) > 3 && mesh.valence (newI2) > 3 && mesh.valence (newI3) > 3)\n    {\n      mesh.deleteFace (adj1);\n      mesh.deleteFace (adj2);\n      mesh.deleteFace (adj3);\n      mesh.deleteVertex (i);\n\n      faces.insert (mesh.addFace (newI1, newI2, newI3));\n\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  };\n\n  bool collapseEdge (DynamicMesh& mesh, unsigned int i1, unsigned int i2, DynamicFaces faces)\n  {\n    const unsigned int v1 = mesh.valence (i1);\n    const unsigned int v2 = mesh.valence (i2);\n\n    assert (v1 >= 3);\n    assert (v2 >= 3);\n\n#ifndef NDEBUG\n    const auto isValidEdge = [&mesh](unsigned int i1, unsigned int i2) {\n      assert (i1 != i2);\n      assert (mesh.isFreeVertex (i1) == false);\n      assert (mesh.isFreeVertex (i2) == false);\n\n      for (unsigned int a : mesh.adjacentFaces (i1))\n      {\n        unsigned int a1, a2, a3;\n        mesh.vertexIndices (a, a1, a2, a3);\n\n        if (i2 == a1 || i2 == a2 || i2 == a3)\n        {\n          return true;\n        }\n      }\n      return false;\n    };\n    assert (isValidEdge (i1, i2));\n#endif\n\n    NewFaces newFaces;\n\n    const auto addFaces = [&mesh, &newFaces](unsigned int newI, unsigned int i1, unsigned int i2) {\n      for (unsigned int a : mesh.adjacentFaces (i1))\n      {\n        unsigned int a1, a2, a3;\n        mesh.vertexIndices (a, a1, a2, a3);\n\n        const bool a1IsAdjacent = (a1 != i1) && (a1 != i2);\n        const bool a2IsAdjacent = (a2 != i1) && (a2 != i2);\n        const bool a3IsAdjacent = (a3 != i1) && (a3 != i2);\n\n        assert (a1IsAdjacent || a2IsAdjacent || a3IsAdjacent);\n        assert (a1IsAdjacent == false || a2IsAdjacent == false || a3IsAdjacent == false);\n\n        if (a1IsAdjacent && a2IsAdjacent)\n        {\n          newFaces.addFace (newI, a1, a2);\n        }\n        else if (a2IsAdjacent && a3IsAdjacent)\n        {\n          newFaces.addFace (newI, a2, a3);\n        }\n        else if (a3IsAdjacent && a1IsAdjacent)\n        {\n          newFaces.addFace (newI, a3, a1);\n        }\n        newFaces.deleteFace (a);\n      }\n    };\n\n    const auto numCommonAdjacentVertices = [&mesh, &i1, &i2]() -> unsigned int {\n      const auto getSuccessor = [&mesh](unsigned int i, unsigned int a) {\n        unsigned int a1, a2, a3;\n        mesh.vertexIndices (a, a1, a2, a3);\n\n        if (i == a1)\n        {\n          return a2;\n        }\n        else if (i == a2)\n        {\n          return a3;\n        }\n        else if (i == a3)\n        {\n          return a1;\n        }\n        else\n        {\n          DILAY_IMPOSSIBLE\n        }\n      };\n\n      unsigned int n = 0;\n      for (unsigned int a1 : mesh.adjacentFaces (i1))\n      {\n        const unsigned int succI1 = getSuccessor (i1, a1);\n\n        if (succI1 != i2)\n        {\n          for (unsigned int a2 : mesh.adjacentFaces (i2))\n          {\n            if (succI1 == getSuccessor (i2, a2))\n            {\n              n++;\n            }\n          }\n        }\n      }\n      return n;\n    };\n\n    const glm::vec3 newPos = Util::midpoint (mesh.vertex (i1), mesh.vertex (i2));\n\n    if (v1 == 3)\n    {\n      if (deleteValence3Vertex (mesh, i1, faces))\n      {\n        mesh.vertex (i2, newPos);\n        return true;\n      }\n      else\n      {\n        return false;\n      }\n    }\n    if (v2 == 3)\n    {\n      if (deleteValence3Vertex (mesh, i2, faces))\n      {\n        mesh.vertex (i1, newPos);\n        return true;\n      }\n      else\n      {\n        return false;\n      }\n    }\n\n    unsigned int leftFace, leftVertex, rightFace, rightVertex;\n    mesh.findAdjacent (i1, i2, leftFace, leftVertex, rightFace, rightVertex);\n\n    const unsigned int vLeftVertex = mesh.valence (leftVertex);\n    const unsigned int vRightVertex = mesh.valence (rightVertex);\n\n    assert (vLeftVertex >= 3);\n    assert (vRightVertex >= 3);\n\n    if (leftVertex == rightVertex)\n    {\n      return false;\n    }\n    else if (vLeftVertex == 3 || vRightVertex == 3)\n    {\n      return false;\n    }\n    else if (numCommonAdjacentVertices () == 2)\n    {\n      const unsigned int newI = mesh.addVertex (newPos, glm::vec3 (0.0f));\n\n      addFaces (newI, i1, i2);\n      addFaces (newI, i2, i1);\n\n      newFaces.applyToMesh (mesh, faces);\n\n      assert (mesh.adjacentFaces (i1).empty ());\n      assert (mesh.adjacentFaces (i2).empty ());\n\n      mesh.deleteVertex (i1);\n      mesh.deleteVertex (i2);\n\n      assert (mesh.isFreeVertex (i1));\n      assert (mesh.isFreeVertex (i2));\n      assert (mesh.valence (newI) == v1 + v2 - 4);\n\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  typedef std::function<bool(unsigned int, unsigned int)> CollapsePredicate;\n  bool collapseEdges (DynamicMesh& mesh, const CollapsePredicate& doCollapse, DynamicFaces& faces)\n  {\n    bool         collapsed = false;\n    DynamicFaces current;\n    current.insert (faces.indices ());\n\n    do\n    {\n      faces.insert (current.uncommitted ());\n      current.commit ();\n\n      for (unsigned int i : current)\n      {\n        if (mesh.isFreeFace (i) == false)\n        {\n          unsigned int i1, i2, i3;\n          mesh.vertexIndices (i, i1, i2, i3);\n\n          if (doCollapse (i1, i2))\n          {\n            collapsed = collapseEdge (mesh, i1, i2, current) || collapsed;\n          }\n          else if (doCollapse (i1, i3))\n          {\n            collapsed = collapseEdge (mesh, i1, i3, current) || collapsed;\n          }\n          else if (doCollapse (i2, i3))\n          {\n            collapsed = collapseEdge (mesh, i2, i3, current) || collapsed;\n          }\n        }\n      }\n    } while (current.uncommitted ().empty () == false);\n\n    faces.filter ([&mesh](unsigned int f) { return mesh.isFreeFace (f) == false; });\n    faces.commit ();\n    return collapsed;\n  }\n\n  bool collapseEdgesByLength (DynamicMesh& mesh, float maxEdgeLengthSqr, DynamicFaces& faces)\n  {\n    const auto isCollapsable = [&mesh, maxEdgeLengthSqr](unsigned int i1, unsigned i2) -> bool {\n      assert (mesh.isFreeVertex (i1) == false);\n      assert (mesh.isFreeVertex (i2) == false);\n\n      return glm::distance2 (mesh.vertex (i1), mesh.vertex (i2)) < maxEdgeLengthSqr;\n    };\n    return collapseEdges (mesh, isCollapsable, faces);\n  }\n\n  bool collapseAllEdges (DynamicMesh& mesh, DynamicFaces& faces)\n  {\n    return collapseEdges (mesh, [](unsigned int, unsigned int) { return true; }, faces);\n  }\n\n  void finalize (DynamicMesh& mesh, const DynamicFaces& faces)\n  {\n    mesh.forEachVertex (faces, [&mesh](unsigned int i) { mesh.setVertexNormal (i); });\n\n    for (unsigned int i : faces)\n    {\n      mesh.realignFace (i);\n    }\n  }\n}\n\nnamespace ToolSculptAction\n{\n  void sculpt (const SculptBrush& brush)\n  {\n    DynamicFaces faces = brush.getAffectedFaces ();\n\n    if (faces.numElements () > 0)\n    {\n      DynamicMesh& mesh = brush.mesh ();\n\n      if (brush.parameters ().reduce ())\n      {\n        const float maxEdgeLengthSqr =\n          mesh.averageEdgeLengthSqr (faces) * brush.parameters ().intensity ();\n        collapseEdgesByLength (mesh, maxEdgeLengthSqr, faces);\n\n        if (mesh.isEmpty ())\n        {\n          mesh.reset ();\n          return;\n        }\n        else\n        {\n          extendDomain (mesh, faces, 1);\n          smooth (mesh, faces);\n          finalize (mesh, faces);\n        }\n        assert (mesh.pruneAndCheckConsistency ());\n      }\n      else\n      {\n        if (brush.subdivide ())\n        {\n          ToolSculptEdgeMap newEdges;\n          do\n          {\n            newEdges.reset ();\n\n            extendAndFilterDomain (brush, faces, 1);\n            extendDomainByPoles (mesh, faces);\n\n            const float maxLength = glm::max (brush.subdivThreshold (), 2.0f * minEdgeLength);\n            splitEdges (mesh, newEdges, maxLength, faces);\n\n            if (newEdges.isEmpty () == false)\n            {\n              triangulate (mesh, newEdges, faces);\n            }\n            extendDomain (mesh, faces, 1);\n            relaxEdges (mesh, faces);\n            smooth (mesh, faces);\n            finalize (mesh, faces);\n          } while (faces.numElements () > 0 && newEdges.isEmpty () == false);\n        }\n        faces = brush.getAffectedFaces ();\n        brush.sculpt (faces);\n        collapseEdgesByLength (mesh, minEdgeLength * minEdgeLength, faces);\n        finalize (mesh, faces);\n      }\n    }\n  }\n\n  void smoothMesh (DynamicMesh& mesh)\n  {\n    DynamicFaces faces;\n\n    mesh.forEachFace ([&faces](unsigned int i) { faces.insert (i); });\n    faces.commit ();\n    relaxEdges (mesh, faces);\n    smooth (mesh, faces);\n    finalize (mesh, faces);\n    mesh.bufferData ();\n  }\n\n  bool deleteFaces (DynamicMesh& mesh, DynamicFaces& faces)\n  {\n    bool collapsed = collapseAllEdges (mesh, faces);\n    collapsed = collapseEdgesByLength (mesh, minEdgeLength * minEdgeLength, faces) || collapsed;\n    finalize (mesh, faces);\n    mesh.bufferData ();\n    return collapsed;\n  }\n}\n"
  },
  {
    "path": "lib/src/tool/sculpt/util/action.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_SCULPT_ACTION\n#define DILAY_TOOL_SCULPT_ACTION\n\nclass DynamicMesh;\nclass SculptBrush;\n\nnamespace ToolSculptAction\n{\n  void sculpt (const SculptBrush&);\n  void smoothMesh (DynamicMesh&);\n  bool deleteFaces (DynamicMesh&, DynamicFaces&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/sculpt/util/brush.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <memory>\n#include \"dynamic/faces.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"util.hpp\"\n\nSBFlattenParameters::SBFlattenParameters ()\n  : _lockPlane (false)\n{\n}\n\nbool SBFlattenParameters::hasLockedPlane () const { return bool(this->_lockedPlane); }\n\nconst PrimPlane& SBFlattenParameters::lockedPlane () const { return *this->_lockedPlane; }\n\nvoid SBFlattenParameters::lockedPlane (const PrimPlane& p) { this->_lockedPlane = p; }\n\nvoid SBFlattenParameters::resetLockedPlane () { this->_lockedPlane.reset (); }\n\nvoid SBFlattenParameters::mirror (const PrimPlane& m)\n{\n  if (this->hasLockedPlane ())\n  {\n    this->_lockedPlane->point (m.mirror (this->_lockedPlane->point ()));\n    this->_lockedPlane->normal (m.mirrorDirection (this->_lockedPlane->normal ()));\n  }\n}\n\nvoid SBDrawParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const\n{\n  if (faces.isEmpty () == false)\n  {\n    const float     intensity = 0.3f * this->intensity ();\n    const glm::vec3 planeNormal = this->invert (brush.normal ());\n    const glm::vec3 planePos = brush.position () + (planeNormal * intensity * brush.radius ());\n    const PrimPlane plane (planePos, planeNormal);\n\n    brush.mesh ().forEachVertex (faces, [&brush, &plane, intensity](unsigned int i) {\n      const glm::vec3& oldPos = brush.mesh ().vertex (i);\n      const float      factor = intensity * Util::linearStep (oldPos, brush.position (),\n                                                         0.5f * brush.radius (), brush.radius ());\n      const float      distance = glm::min (0.0f, plane.distance (oldPos));\n      const glm::vec3  newPos = oldPos - (plane.normal () * factor * distance);\n\n      brush.mesh ().vertex (i, newPos);\n    });\n  }\n}\n\nvoid SBGrablikeParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const\n{\n  brush.mesh ().forEachVertex (faces, [&brush](unsigned int i) {\n    const glm::vec3& oldPos = brush.mesh ().vertex (i);\n    const float factor = Util::linearStep (oldPos, brush.lastPosition (), 0.0f, brush.radius ());\n    const glm::vec3 newPos = oldPos + (factor * brush.delta ());\n\n    brush.mesh ().vertex (i, newPos);\n  });\n}\n\nvoid SBSmoothParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const\n{\n  brush.mesh ().forEachVertex (faces, [this, &brush](unsigned int i) {\n    const glm::vec3  avgPos = brush.mesh ().averagePosition (i);\n    const glm::vec3& oldPos = brush.mesh ().vertex (i);\n    const glm::vec3  newPos = oldPos + (this->intensity () * (avgPos - oldPos));\n\n    brush.mesh ().vertex (i, newPos);\n  });\n}\n\nvoid SBReduceParameters::sculpt (const SculptBrush&, const DynamicFaces&) const {}\n\nvoid SBFlattenParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const\n{\n  if (faces.isEmpty () == false)\n  {\n    PrimPlane plane (glm::vec3 (0.0f), glm::vec3 (1.0f));\n\n    if (this->hasLockedPlane ())\n    {\n      plane = this->lockedPlane ();\n    }\n    else\n    {\n      glm::vec3 avgPos, avgNormal;\n      brush.mesh ().average (faces, avgPos, avgNormal);\n      plane = PrimPlane (avgPos, avgNormal);\n    }\n\n    brush.mesh ().forEachVertex (faces, [this, &brush, &plane](unsigned int i) {\n      const glm::vec3& oldPos = brush.mesh ().vertex (i);\n      const float      distance = plane.distance (oldPos);\n\n      float factor =\n        this->intensity () * Util::linearStep (oldPos, brush.position (), 0.0f, brush.radius ());\n      factor *= this->hasLockedPlane () ? distance : glm::max (0.0f, distance);\n\n      const glm::vec3 newPos = oldPos - (plane.normal () * factor);\n      brush.mesh ().vertex (i, newPos);\n    });\n  }\n}\n\nvoid SBCreaseParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const\n{\n  if (faces.isEmpty () == false && brush.position () != brush.lastPosition ())\n  {\n    const glm::vec3 normal = this->invert (brush.normal ());\n\n    brush.mesh ().forEachVertex (faces, [this, &brush, &normal](unsigned int i) {\n      const glm::vec3& oldPos = brush.mesh ().vertex (i);\n      const glm::vec3  delta = brush.position () - oldPos;\n      const float      distance = glm::length (delta) / brush.radius ();\n\n      if (distance <= 1.0f)\n      {\n        const float invDistance2 = (distance - 1.0f) * (distance - 1.0f);\n        const float hFactor = invDistance2 * this->intensity ();\n        float vFactor = invDistance2 * invDistance2 * brush.radius () * this->intensity () * 0.5f;\n        const glm::vec3 newPos = (oldPos + (hFactor * delta)) + (normal * vFactor);\n\n        brush.mesh ().vertex (i, newPos);\n      }\n    });\n  }\n}\n\nvoid SBPinchParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const\n{\n  brush.mesh ().forEachVertex (faces, [&brush](unsigned int i) {\n    const glm::vec3& oldPos = brush.mesh ().vertex (i);\n    const glm::vec3  delta = brush.position () - oldPos;\n    const float      distance = glm::length (delta) / brush.radius ();\n\n    if (distance <= 1.0f)\n    {\n      const float     invDistance2 = (distance - 1.0f) * (distance - 1.0f);\n      const float     hFactor = invDistance2 * 0.5f;\n      const glm::vec3 newPos = oldPos + (hFactor * delta);\n\n      brush.mesh ().vertex (i, newPos);\n    }\n  });\n}\n\nstruct SculptBrush::Impl\n{\n  SculptBrush* self;\n  float        radius;\n  float        detailFactor;\n  float        stepWidthFactor;\n  bool         subdivide;\n  DynamicMesh* _mesh;\n  bool         hasPointOfAction;\n  glm::vec3    _prevPosition;\n  glm::vec3    _position;\n  glm::vec3    _normal;\n\n  std::unique_ptr<SBParameters> _parameters;\n\n  Impl (SculptBrush* s)\n    : self (s)\n    , radius (0.0f)\n    , detailFactor (0.0f)\n    , stepWidthFactor (0.0f)\n    , subdivide (true)\n    , _mesh (nullptr)\n    , hasPointOfAction (false)\n  {\n  }\n\n  DynamicMesh& mesh () const\n  {\n    assert (this->hasPointOfAction);\n    assert (this->_mesh);\n    return *this->_mesh;\n  }\n\n  void mesh (DynamicMesh& m) { this->_mesh = &m; }\n\n  float subdivThreshold () const\n  {\n    assert (this->detailFactor > 0.0f);\n    assert (this->detailFactor < 1.0f);\n\n    return (1.0f - this->detailFactor) * this->radius;\n  }\n\n  const glm::vec3& lastPosition () const\n  {\n    assert (this->hasPointOfAction);\n    return this->_prevPosition;\n  }\n\n  const glm::vec3& position () const\n  {\n    assert (this->hasPointOfAction);\n    return this->_position;\n  }\n\n  const glm::vec3& normal () const\n  {\n    assert (this->hasPointOfAction);\n    return this->_normal;\n  }\n\n  glm::vec3 delta () const\n  {\n    assert (this->hasPointOfAction);\n    return this->_position - this->_prevPosition;\n  }\n\n  PrimSphere sphere () const\n  {\n    assert (this->_parameters);\n\n    const glm::vec3& pos =\n      this->_parameters->useLastPos () ? this->lastPosition () : this->position ();\n    return PrimSphere (pos, this->radius);\n  }\n\n  float stepWidth () const { return this->stepWidthFactor * glm::log (this->self->radius () + 1); }\n\n  void setPointOfAction (DynamicMesh& mesh, const glm::vec3& p, const glm::vec3& n)\n  {\n    this->_mesh = &mesh;\n    this->_prevPosition = this->hasPointOfAction ? this->_position : p;\n    this->_position = p;\n    this->_normal = n;\n    this->hasPointOfAction = true;\n  }\n\n  void resetPointOfAction ()\n  {\n    this->hasPointOfAction = false;\n    this->_mesh = nullptr;\n  }\n\n  void mirror (const PrimPlane& plane)\n  {\n    if (this->_parameters)\n    {\n      this->_parameters->mirror (plane);\n    }\n\n    if (this->hasPointOfAction)\n    {\n      this->_prevPosition = plane.mirror (this->_prevPosition);\n      this->_position = plane.mirror (this->_position);\n      this->_normal = plane.mirrorDirection (this->_normal);\n    }\n  }\n\n  DynamicFaces getAffectedFaces () const\n  {\n    assert (this->hasPointOfAction);\n    assert (this->_parameters);\n\n    DynamicFaces faces;\n    this->_mesh->intersects (this->sphere (), faces);\n\n    if (this->_parameters->discardBack ())\n    {\n      faces.filter ([this](unsigned int i) {\n        return glm::dot (this->normal (), this->_mesh->face (i).cross ()) > 0.0f;\n      });\n    }\n    return faces;\n  }\n\n  void sculpt (const DynamicFaces& faces) const\n  {\n    assert (this->_parameters);\n    this->_parameters->sculpt (*this->self, faces);\n  }\n\n  SBParameters* parametersPointer () const { return this->_parameters.get (); }\n\n  void parametersPointer (SBParameters* p) { this->_parameters.reset (p); }\n};\n\nDELEGATE_BIG3_SELF (SculptBrush)\n\nGETTER_CONST (float, SculptBrush, radius)\nGETTER_CONST (float, SculptBrush, detailFactor)\nGETTER_CONST (float, SculptBrush, stepWidthFactor)\nGETTER_CONST (bool, SculptBrush, subdivide)\nDELEGATE_CONST (DynamicMesh&, SculptBrush, mesh)\nSETTER (float, SculptBrush, radius)\nSETTER (float, SculptBrush, detailFactor)\nSETTER (float, SculptBrush, stepWidthFactor)\nSETTER (bool, SculptBrush, subdivide)\nDELEGATE_CONST (float, SculptBrush, subdivThreshold)\nDELEGATE_CONST (const glm::vec3&, SculptBrush, lastPosition)\nDELEGATE_CONST (const glm::vec3&, SculptBrush, position)\nDELEGATE_CONST (const glm::vec3&, SculptBrush, normal)\nDELEGATE_CONST (glm::vec3, SculptBrush, delta)\nDELEGATE_CONST (PrimSphere, SculptBrush, sphere)\nDELEGATE_CONST (float, SculptBrush, stepWidth)\nGETTER_CONST (bool, SculptBrush, hasPointOfAction)\nDELEGATE3 (void, SculptBrush, setPointOfAction, DynamicMesh&, const glm::vec3&, const glm::vec3&)\nDELEGATE (void, SculptBrush, resetPointOfAction)\nDELEGATE1 (void, SculptBrush, mirror, const PrimPlane&)\nDELEGATE_CONST (DynamicFaces, SculptBrush, getAffectedFaces)\nDELEGATE1_CONST (void, SculptBrush, sculpt, const DynamicFaces&)\nDELEGATE_CONST (SBParameters*, SculptBrush, parametersPointer)\nDELEGATE1 (void, SculptBrush, parametersPointer, SBParameters*)\n"
  },
  {
    "path": "lib/src/tool/sculpt/util/brush.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_SCULPT_BRUSH\n#define DILAY_TOOL_SCULPT_BRUSH\n\n#include <glm/glm.hpp>\n#include \"macro.hpp\"\n#include \"maybe.hpp\"\n\nclass DynamicFaces;\nclass DynamicMesh;\nclass PrimPlane;\nclass PrimSphere;\nclass SculptBrush;\n\nclass SBParameters\n{\npublic:\n  virtual ~SBParameters () {}\n\n  virtual float intensity () const { return 0.0f; }\n\n  virtual void intensity (float) {}\n\n  virtual bool useLastPos () const { return false; }\n\n  virtual bool discardBack () const { return true; }\n\n  virtual bool reduce () const { return false; }\n\n  virtual void mirror (const PrimPlane&) {}\n\n  virtual void sculpt (const SculptBrush&, const DynamicFaces&) const = 0;\n};\n\nclass SBIntensityParameter : virtual public SBParameters\n{\npublic:\n  SBIntensityParameter ()\n    : _intensity (0.0f)\n  {\n  }\n\n  MEMBER_GETTER_SETTER (float, intensity);\n};\n\nclass SBInvertParameter : virtual public SBParameters\n{\npublic:\n  SBInvertParameter ()\n    : _invert (false)\n  {\n  }\n\n  void toggleInvert () { this->_invert = !this->_invert; }\n\n  glm::vec3 invert (const glm::vec3& v) const { return this->_invert ? -v : v; }\n\n  MEMBER_GETTER_SETTER (bool, invert);\n};\n\nclass SBDiscardBackParameter : virtual public SBParameters\n{\npublic:\n  SBDiscardBackParameter ()\n    : _discardBack (true)\n  {\n  }\n\n  bool discardBack () const override { return this->_discardBack; }\n  void discardBack (bool d) { this->_discardBack = d; }\n\nprivate:\n  bool _discardBack;\n};\n\nclass SBDrawParameters : public SBIntensityParameter, public SBInvertParameter\n{\npublic:\n  SBDrawParameters ()\n    : _constantHeight (false)\n  {\n  }\n\n  void sculpt (const SculptBrush&, const DynamicFaces&) const;\n\n  MEMBER_GETTER_SETTER (bool, constantHeight);\n};\n\nclass SBGrablikeParameters : public SBDiscardBackParameter\n{\npublic:\n  void sculpt (const SculptBrush&, const DynamicFaces&) const override;\n\n  bool useLastPos () const override { return true; }\n};\n\nclass SBSmoothParameters : public SBIntensityParameter\n{\npublic:\n  void sculpt (const SculptBrush&, const DynamicFaces&) const;\n};\n\nclass SBReduceParameters : public SBIntensityParameter\n{\npublic:\n  bool reduce () const override { return true; }\n\n  void sculpt (const SculptBrush&, const DynamicFaces&) const override;\n};\n\nclass SBFlattenParameters : public SBIntensityParameter\n{\npublic:\n  SBFlattenParameters ();\n\n  void sculpt (const SculptBrush&, const DynamicFaces&) const override;\n\n  bool             hasLockedPlane () const;\n  const PrimPlane& lockedPlane () const;\n  void             lockedPlane (const PrimPlane& p);\n  void             resetLockedPlane ();\n  void             mirror (const PrimPlane&) override;\n\n  MEMBER_GETTER_SETTER (bool, lockPlane);\n\nprivate:\n  Maybe<PrimPlane> _lockedPlane;\n};\n\nclass SBCreaseParameters : public SBIntensityParameter, public SBInvertParameter\n{\npublic:\n  void sculpt (const SculptBrush&, const DynamicFaces&) const;\n};\n\nclass SBPinchParameters : public SBInvertParameter\n{\npublic:\n  void sculpt (const SculptBrush&, const DynamicFaces&) const;\n};\n\nclass SculptBrush\n{\npublic:\n  DECLARE_BIG3 (SculptBrush)\n\n  float        radius () const;\n  float        detailFactor () const;\n  float        stepWidthFactor () const;\n  bool         subdivide () const;\n  bool         hasMesh () const;\n  DynamicMesh& mesh () const;\n\n  void radius (float);\n  void detailFactor (float);\n  void stepWidthFactor (float);\n  void subdivide (bool);\n\n  float            subdivThreshold () const;\n  const glm::vec3& lastPosition () const;\n  const glm::vec3& position () const;\n  const glm::vec3& normal () const;\n  glm::vec3        delta () const;\n  PrimSphere       sphere () const;\n  float            stepWidth () const;\n  bool             hasPointOfAction () const;\n  void             setPointOfAction (DynamicMesh&, const glm::vec3&, const glm::vec3&);\n  void             resetPointOfAction ();\n  void             mirror (const PrimPlane&);\n\n  DynamicFaces getAffectedFaces () const;\n  void         sculpt (const DynamicFaces&) const;\n\n  template <typename T> T& initParameters ()\n  {\n    this->parametersPointer (new T ());\n    return this->parameters<T> ();\n  }\n\n  template <typename T> T& parameters () { return dynamic_cast<T&> (*this->parametersPointer ()); }\n\n  const SBParameters& parameters () const { return *this->parametersPointer (); }\n\nprivate:\n  SBParameters* parametersPointer () const;\n  void          parametersPointer (SBParameters*);\n\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/sculpt/util/edge-collection.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"tool/sculpt/util/edge-collection.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  ui_pair makeUiKey (unsigned int i1, unsigned int i2)\n  {\n    assert (i1 != i2);\n    return ui_pair (glm::min (i1, i2), glm::max (i1, i2));\n  }\n}\n\nvoid ToolSculptEdgeMap::insert (unsigned int i1, unsigned int i2, unsigned int value)\n{\n  assert (this->contains (i1, i2) == false);\n  this->map.emplace (makeUiKey (i1, i2), value);\n}\n\nunsigned int ToolSculptEdgeMap::find (unsigned int i1, unsigned int i2) const\n{\n  const auto it = this->map.find (makeUiKey (i1, i2));\n\n  return it == this->map.end () ? Util::invalidIndex () : it->second;\n}\n\nbool ToolSculptEdgeMap::contains (unsigned int i1, unsigned int i2) const\n{\n  return this->find (i1, i2) != Util::invalidIndex ();\n}\n\nbool ToolSculptEdgeMap::isEmpty () const { return this->map.empty (); }\n\nvoid ToolSculptEdgeMap::reset () { this->map.clear (); }\n\nvoid ToolSculptEdgeSet::insert (unsigned int i1, unsigned int i2)\n{\n  this->set.emplace (makeUiKey (i1, i2));\n}\n\nbool ToolSculptEdgeSet::contains (unsigned int i1, unsigned int i2) const\n{\n  return this->set.find (makeUiKey (i1, i2)) != this->set.end ();\n}\n\nbool ToolSculptEdgeSet::isEmpty () const { return this->set.empty (); }\n\nvoid ToolSculptEdgeSet::reset () { this->set.clear (); }\n"
  },
  {
    "path": "lib/src/tool/sculpt/util/edge-collection.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_SCULPT_EDGE_COLLECTION\n#define DILAY_TOOL_SCULPT_EDGE_COLLECTION\n\n#include <unordered_map>\n#include <unordered_set>\n#include \"hash.hpp\"\n\nclass ToolSculptEdgeMap\n{\npublic:\n  typedef std::unordered_map<std::pair<unsigned int, unsigned int>, unsigned int> Map;\n\n  void         insert (unsigned int, unsigned int, unsigned int);\n  unsigned int find (unsigned int, unsigned int) const;\n  bool         contains (unsigned int, unsigned int) const;\n  bool         isEmpty () const;\n  void         reset ();\n\nprivate:\n  Map map;\n};\n\nclass ToolSculptEdgeSet\n{\npublic:\n  typedef std::unordered_set<std::pair<unsigned int, unsigned int>> Set;\n\n  void insert (unsigned int, unsigned int);\n  bool contains (unsigned int, unsigned int) const;\n  bool isEmpty () const;\n  void reset ();\n\n  Set::const_iterator begin () const { return this->set.begin (); }\n  Set::const_iterator end () const { return this->set.end (); }\n\nprivate:\n  Set set;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/sculpt.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include <QFrame>\n#include <QWheelEvent>\n#include \"cache.hpp\"\n#include \"camera.hpp\"\n#include \"config.hpp\"\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"history.hpp\"\n#include \"maybe.hpp\"\n#include \"mirror.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"scene.hpp\"\n#include \"state.hpp\"\n#include \"tool/sculpt.hpp\"\n#include \"tool/sculpt/util/action.hpp\"\n#include \"tool/sculpt/util/brush.hpp\"\n#include \"tool/util/movement.hpp\"\n#include \"tool/util/step.hpp\"\n#include \"view/cursor.hpp\"\n#include \"view/double-slider.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  enum class SculptState\n  {\n    None,\n    Started,\n    Sculpted,\n    Ended\n  };\n}\n\nstruct ToolSculpt::Impl\n{\n  ToolSculpt*       self;\n  SculptBrush       brush;\n  ViewCursor        cursor;\n  CacheProxy        commonCache;\n  ViewDoubleSlider& radiusEdit;\n  ViewDoubleSlider* secondarySlider;\n  bool              absoluteRadius;\n  SculptState       sculptState;\n  ToolUtilStep      step;\n\n  Impl (ToolSculpt* s)\n    : self (s)\n    , commonCache (this->self->cache (\"sculpt\"))\n    , radiusEdit (\n        ViewUtil::slider (2, 0.01f, this->commonCache.get<float> (\"radius\", 0.1f), 1.0f, 3))\n    , secondarySlider (nullptr)\n    , absoluteRadius (this->commonCache.get<bool> (\"absolute-radius\", true))\n    , sculptState (SculptState::None)\n  {\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->self->supportsMirror ();\n\n    this->setupBrush ();\n    this->setupCursor ();\n    this->setupProperties ();\n    this->setupToolTip ();\n\n    return ToolResponse::Redraw;\n  }\n\n  void setupBrush ()\n  {\n    this->brush.subdivide (this->commonCache.get<bool> (\"subdivide\", true));\n\n    if (this->absoluteRadius)\n    {\n      this->setAbsoluteRadius ();\n    }\n    else\n    {\n      this->setRelativeRadius ();\n    }\n    this->self->runSetupBrush (this->brush);\n  }\n\n  void setupCursor ()\n  {\n    assert (this->brush.radius () > 0.0f);\n\n    DynamicMeshIntersection intersection;\n    if (this->self->intersectsScene (this->self->cursorPosition (), intersection))\n    {\n      this->cursor.enable ();\n      this->cursor.position (intersection.position ());\n    }\n    else\n    {\n      this->cursor.disable ();\n    }\n    this->cursor.radius (this->brush.radius ());\n\n    this->self->runSetupCursor (this->cursor);\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    ViewUtil::connect (this->radiusEdit, [this](float r) {\n      if (this->absoluteRadius)\n      {\n        this->setAbsoluteRadius ();\n      }\n      else\n      {\n        this->setRelativeRadius ();\n      }\n      this->commonCache.set (\"radius\", r);\n      this->self->updateGlWidget ();\n    });\n    properties.addStacked (QObject::tr (\"Radius\"), this->radiusEdit);\n\n    QCheckBox& absRadiusEdit =\n      ViewUtil::checkBox (QObject::tr (\"Absolute radius\"), this->absoluteRadius);\n    ViewUtil::connect (absRadiusEdit, [this](bool a) {\n      if (a)\n      {\n        this->setAbsoluteRadius ();\n      }\n      else\n      {\n        this->setRelativeRadius ();\n      }\n      this->commonCache.set (\"absolute-radius\", a);\n      this->self->updateGlWidget ();\n    });\n    properties.add (absRadiusEdit);\n\n    this->self->addMirrorProperties ();\n    properties.add (ViewUtil::horizontalLine ());\n\n    this->self->runSetupProperties (properties);\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n\n    this->self->runSetupToolTip (toolTip);\n    toolTip.add (ViewInputEvent::R, QObject::tr (\"Move to change radius\"));\n\n    this->self->state ().setToolTip (&toolTip);\n  }\n\n  void runRender () const\n  {\n    Camera& camera = this->self->state ().camera ();\n\n    if (this->cursor.isEnabled ())\n    {\n      this->cursor.render (camera);\n    }\n  }\n\n  ToolResponse runPointingEvent (const ViewPointingEvent& e)\n  {\n    if (this->self->onKeymap ('r') && e.moveEvent ())\n    {\n      this->radiusEdit.setIntValue (this->radiusEdit.intValue () + e.delta ().x);\n    }\n    else if (this->secondarySlider && this->self->onKeymap ('i') && e.moveEvent ())\n    {\n      this->secondarySlider->setIntValue (this->secondarySlider->intValue () + e.delta ().x);\n    }\n    else if (e.leftButton ())\n    {\n      if (e.pressEvent ())\n      {\n        this->self->snapshotDynamicMeshes ();\n        this->sculptState = SculptState::Started;\n      }\n\n      const bool doSculpt =\n        this->sculptState == SculptState::Started || this->sculptState == SculptState::Sculpted;\n      if (doSculpt && this->self->runSculptPointingEvent (e))\n      {\n        this->sculptState = SculptState::Sculpted;\n      }\n\n      if (e.releaseEvent ())\n      {\n        this->runCommit ();\n      }\n    }\n    else\n    {\n      this->self->runSculptPointingEvent (e);\n    }\n    return ToolResponse::Redraw;\n  }\n\n  ToolResponse runCursorUpdate (const glm::ivec2& pos)\n  {\n    DynamicMeshIntersection cursorIntersection;\n    this->setCursorByIntersection (pos, cursorIntersection);\n    return ToolResponse::Redraw;\n  }\n\n  ToolResponse runCommit ()\n  {\n    this->brush.resetPointOfAction ();\n\n    if (this->sculptState == SculptState::Started)\n    {\n      this->self->state ().history ().dropPastSnapshot ();\n    }\n    this->sculptState = SculptState::None;\n    return ToolResponse::None;\n  }\n\n  void runFromConfig ()\n  {\n    const Config& config = this->self->config ();\n\n    this->brush.detailFactor (config.get<float> (\"editor/tool/sculpt/detail-factor\"));\n    this->brush.stepWidthFactor (config.get<float> (\"editor/tool/sculpt/step-width-factor\"));\n\n    this->cursor.color (this->self->config ().get<Color> (\"editor/tool/cursor-color\"));\n  }\n\n  void addDefaultToolTip (ViewToolTip& toolTip, bool hasInvertedMode, bool hasIntensity)\n  {\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Drag to sculpt\"));\n\n    if (hasInvertedMode)\n    {\n      toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift,\n                   QObject::tr (\"Drag to sculpt inverted\"));\n    }\n\n    if (hasIntensity)\n    {\n      toolTip.add (ViewInputEvent::I, QObject::tr (\"Move to change intensity\"));\n    }\n  }\n\n  void sculpt ()\n  {\n    assert (this->brush.hasPointOfAction ());\n\n    ToolSculptAction::sculpt (this->brush);\n    if (this->self->mirrorEnabled () && this->brush.mesh ().isEmpty () == false)\n    {\n      this->brush.mirror (this->self->mirror ().plane ());\n      ToolSculptAction::sculpt (this->brush);\n      this->brush.mirror (this->self->mirror ().plane ());\n    }\n\n    if (this->brush.mesh ().isEmpty ())\n    {\n      this->self->state ().scene ().deleteEmptyMeshes ();\n      this->brush.resetPointOfAction ();\n    }\n  }\n\n  bool setCursorByIntersection (const glm::ivec2& pos, DynamicMeshIntersection& intersection)\n  {\n    if (this->self->intersectsScene (pos, intersection))\n    {\n      if (this->absoluteRadius == false)\n      {\n        this->setRelativeRadius (intersection.distance ());\n      }\n      this->cursor.enable ();\n      this->cursor.position (intersection.position ());\n      return true;\n    }\n    else\n    {\n      this->cursor.disable ();\n      return false;\n    }\n  }\n\n  bool updateBrushByIntersection (bool useRecentMesh, const glm::vec3& cursorStep)\n  {\n    const glm::vec3 from = this->self->state ().camera ().position ();\n    const PrimRay   ray = PrimRay (from, cursorStep - from);\n\n    DynamicMeshIntersection intersection;\n\n    if (this->self->intersectsScene (ray, intersection))\n    {\n      if (this->brush.hasPointOfAction () && (&this->brush.mesh () != &intersection.mesh ()))\n      {\n        this->brush.mesh ().bufferData ();\n      }\n\n      if (useRecentMesh)\n      {\n        Intersection rIntersection;\n        if (this->self->intersectsRecentDynamicMesh (ray, rIntersection))\n        {\n          this->brush.setPointOfAction (intersection.mesh (), rIntersection.position (),\n                                        rIntersection.normal ());\n        }\n        else\n        {\n          this->brush.mesh ().bufferData ();\n          this->brush.resetPointOfAction ();\n          return false;\n        }\n      }\n      else\n      {\n        this->brush.setPointOfAction (intersection.mesh (), intersection.position (),\n                                      intersection.normal ());\n      }\n      return true;\n    }\n    else\n    {\n      this->brush.mesh ().bufferData ();\n      this->brush.resetPointOfAction ();\n      return false;\n    }\n  }\n\n  bool drawlikeStroke (const ViewPointingEvent& e, bool useRecentMesh,\n                       const std::function<void()>* toggle)\n  {\n    DynamicMeshIntersection cursorIntersection;\n\n    if (this->setCursorByIntersection (e.position (), cursorIntersection) && e.leftButton ())\n    {\n      SBParameters& parameters = this->brush.parameters<SBParameters> ();\n      const float   defaultIntesity = parameters.intensity ();\n      const bool    doToggle = toggle && e.modifiers () == Qt::ShiftModifier;\n\n      parameters.intensity (defaultIntesity * e.intensity ());\n\n      if (doToggle)\n      {\n        (*toggle) ();\n      }\n\n      if (this->brush.hasPointOfAction ())\n      {\n        this->step.stepWidth (this->brush.stepWidth ());\n        this->step.position (this->brush.position ());\n        this->step.step (cursorIntersection.position (),\n                         [this, useRecentMesh](const glm::vec3& brushStep) {\n                           if (this->brush.hasPointOfAction ())\n                           {\n                             if (this->updateBrushByIntersection (useRecentMesh, brushStep))\n                             {\n                               this->sculpt ();\n                             }\n                             return true;\n                           }\n                           else\n                           {\n                             return false;\n                           }\n                         });\n      }\n      else\n      {\n        if (this->updateBrushByIntersection (useRecentMesh, cursorIntersection.position ()))\n        {\n          this->sculpt ();\n        }\n      }\n\n      if (this->brush.hasPointOfAction ())\n      {\n        assert (this->brush.mesh ().isEmpty () == false);\n        this->brush.mesh ().bufferData ();\n      }\n\n      if (doToggle)\n      {\n        (*toggle) ();\n      }\n      parameters.intensity (defaultIntesity);\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  bool grablikeStroke (const ViewPointingEvent& e, ToolUtilMovement& movement)\n  {\n    DynamicMeshIntersection cursorIntersection;\n\n    if (e.pressEvent ())\n    {\n      if (e.leftButton ())\n      {\n        if (this->setCursorByIntersection (e.position (), cursorIntersection))\n        {\n          this->brush.setPointOfAction (cursorIntersection.mesh (), cursorIntersection.position (),\n                                        cursorIntersection.normal ());\n          this->cursor.disable ();\n          movement.reset (cursorIntersection.position ());\n          return true;\n        }\n        else\n        {\n          this->brush.resetPointOfAction ();\n          return false;\n        }\n      }\n      else\n      {\n        this->cursor.enable ();\n        this->brush.resetPointOfAction ();\n        return false;\n      }\n    }\n    else\n    {\n      if (e.leftButton () == false)\n      {\n        this->setCursorByIntersection (e.position (), cursorIntersection);\n        return false;\n      }\n      else if (this->brush.hasPointOfAction ())\n      {\n        if (e.moveEvent () && movement.move (e))\n        {\n          this->brush.setPointOfAction (this->brush.mesh (), movement.position (),\n                                        this->brush.normal ());\n          this->sculpt ();\n          if (this->brush.hasPointOfAction ())\n          {\n            assert (this->brush.mesh ().isEmpty () == false);\n            this->brush.mesh ().bufferData ();\n          }\n          return true;\n        }\n        else\n        {\n          return false;\n        }\n      }\n      else\n      {\n        return false;\n      }\n    }\n  }\n\n  void registerSecondarySlider (ViewDoubleSlider& slider) { this->secondarySlider = &slider; }\n\n  void setRelativeRadius (float distance)\n  {\n    const Camera& cam = this->self->state ().camera ();\n    const float   factor = this->radiusEdit.doubleValue ();\n    const float   radius = cam.toWorld (float(cam.resolution ().x) * factor, distance);\n\n    this->absoluteRadius = false;\n    this->cursor.radius (radius);\n    this->brush.radius (radius);\n  }\n\n  void setRelativeRadius ()\n  {\n    this->setRelativeRadius (\n      glm::distance (this->cursor.position (), this->self->state ().camera ().position ()));\n  }\n\n  void setAbsoluteRadius ()\n  {\n    const float max = this->self->config ().get<float> (\"editor/tool/sculpt/max-absolute-radius\");\n    const float factor = this->radiusEdit.doubleValue ();\n\n    this->absoluteRadius = true;\n    this->brush.radius (factor * max);\n    this->cursor.radius (factor * max);\n  }\n};\n\nDELEGATE_BIG2_BASE (ToolSculpt, (State & s, const char* c), (this), Tool, (s, c))\nGETTER (SculptBrush&, ToolSculpt, brush)\nGETTER (ViewCursor&, ToolSculpt, cursor)\nDELEGATE3_CONST (void, ToolSculpt, addDefaultToolTip, ViewToolTip&, bool, bool)\nDELEGATE (void, ToolSculpt, sculpt)\nDELEGATE3 (bool, ToolSculpt, drawlikeStroke, const ViewPointingEvent&, bool,\n           const std::function<void()>*)\nDELEGATE2 (bool, ToolSculpt, grablikeStroke, const ViewPointingEvent&, ToolUtilMovement&)\nDELEGATE1 (void, ToolSculpt, registerSecondarySlider, ViewDoubleSlider&)\nDELEGATE (ToolResponse, ToolSculpt, runInitialize)\nDELEGATE_CONST (void, ToolSculpt, runRender)\nDELEGATE1 (ToolResponse, ToolSculpt, runPointingEvent, const ViewPointingEvent&)\nDELEGATE1 (ToolResponse, ToolSculpt, runCursorUpdate, const glm::ivec2&)\nDELEGATE (ToolResponse, ToolSculpt, runCommit)\nDELEGATE (void, ToolSculpt, runFromConfig)\n"
  },
  {
    "path": "lib/src/tool/sculpt.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_SCULPT\n#define DILAY_TOOL_SCULPT\n\n#include \"tool.hpp\"\n\nclass QString;\nclass SculptBrush;\nclass ToolUtilMovement;\nclass ViewCursor;\nclass ViewDoubleSlider;\nclass ViewTwoColumnGrid;\n\nclass ToolSculpt : public Tool\n{\npublic:\n  DECLARE_BIG2 (ToolSculpt, State&, const char*)\n\nprotected:\n  SculptBrush& brush ();\n  ViewCursor&  cursor ();\n  void         addDefaultToolTip (ViewToolTip&, bool, bool) const;\n  void         sculpt ();\n  bool drawlikeStroke (const ViewPointingEvent&, bool, const std::function<void()>* = nullptr);\n  bool grablikeStroke (const ViewPointingEvent&, ToolUtilMovement&);\n  void registerSecondarySlider (ViewDoubleSlider&);\n\nprivate:\n  IMPLEMENTATION\n\n  ToolResponse runInitialize ();\n  void         runRender () const;\n  ToolResponse runPointingEvent (const ViewPointingEvent&);\n  ToolResponse runCursorUpdate (const glm::ivec2&);\n  ToolResponse runCommit ();\n  void         runFromConfig ();\n\n  virtual void runSetupBrush (SculptBrush&) = 0;\n  virtual void runSetupCursor (ViewCursor&) = 0;\n  virtual void runSetupProperties (ViewTwoColumnGrid&) = 0;\n  virtual void runSetupToolTip (ViewToolTip&) = 0;\n  virtual bool runSculptPointingEvent (const ViewPointingEvent&) = 0;\n};\n\n#define DECLARE_TOOL_SCULPT(keyName)                        \\\n  class Tool##keyName : public ToolSculpt                   \\\n  {                                                         \\\n  public:                                                   \\\n    DECLARE_BIG2 (Tool##keyName, State&)                    \\\n                                                            \\\n    ToolKey getKey () const { return ToolKey::keyName; }    \\\n                                                            \\\n  private:                                                  \\\n    IMPLEMENTATION                                          \\\n    void runSetupBrush (SculptBrush&);                      \\\n    void runSetupCursor (ViewCursor&);                      \\\n    void runSetupProperties (ViewTwoColumnGrid&);           \\\n    void runSetupToolTip (ViewToolTip&);                    \\\n    bool runSculptPointingEvent (const ViewPointingEvent&); \\\n  };\n\n#define DELEGATE_TOOL_SCULPT(name)                                       \\\n  DELEGATE_BIG2_BASE (name, (State & s), (this), ToolSculpt, (s, #name)) \\\n  DELEGATE1 (void, name, runSetupBrush, SculptBrush&);                   \\\n  DELEGATE1 (void, name, runSetupCursor, ViewCursor&);                   \\\n  DELEGATE1 (void, name, runSetupProperties, ViewTwoColumnGrid&);        \\\n  DELEGATE1 (void, name, runSetupToolTip, ViewToolTip&);                 \\\n  DELEGATE1 (bool, name, runSculptPointingEvent, const ViewPointingEvent&)\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/sketch-spheres.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QFrame>\n#include \"cache.hpp\"\n#include \"camera.hpp\"\n#include \"config.hpp\"\n#include \"dimension.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/mesh-intersection.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/path-intersection.hpp\"\n#include \"sketch/path.hpp\"\n#include \"state.hpp\"\n#include \"tool/util/step.hpp\"\n#include \"tools.hpp\"\n#include \"view/cursor.hpp\"\n#include \"view/double-slider.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ToolSketchSpheres::Impl\n{\n  ToolSketchSpheres*     self;\n  ViewCursor             cursor;\n  ViewDoubleSlider&      radiusEdit;\n  ViewDoubleSlider&      heightEdit;\n  SketchPathSmoothEffect smoothEffect;\n  float                  stepWidthFactor;\n  SketchMesh*            mesh;\n  ToolUtilStep           step;\n\n  Impl (ToolSketchSpheres* s)\n    : self (s)\n    , radiusEdit (ViewUtil::slider (2, 0.01f, s->cache ().get<float> (\"radius\", 0.1f), 1.0f))\n    , heightEdit (ViewUtil::slider (2, 0.01f, s->cache ().get<float> (\"height\", 0.2f), 0.45f))\n    , smoothEffect (SketchPathSmoothEffect (\n        s->cache ().get<int> (\"smooth-effect\", int(SketchPathSmoothEffect::Embed))))\n    , stepWidthFactor (0.0f)\n    , mesh (nullptr)\n  {\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    this->self->addMirrorProperties ();\n\n    ViewUtil::connect (this->radiusEdit, [this](float r) {\n      this->cursor.radius (r);\n      this->self->cache ().set (\"radius\", r);\n    });\n    properties.addStacked (QObject::tr (\"Radius\"), this->radiusEdit);\n\n    ViewUtil::connect (this->heightEdit,\n                       [this](float d) { this->self->cache ().set (\"height\", d); });\n    properties.addStacked (QObject::tr (\"Height\"), this->heightEdit);\n\n    properties.add (ViewUtil::horizontalLine ());\n\n    QButtonGroup& smoothEffectEdit =\n      ViewUtil::buttonGroup ({QObject::tr (\"None\"), QObject::tr (\"Embed\"),\n                              QObject::tr (\"Embed and adjust\"), QObject::tr (\"Pinch\")});\n    ViewUtil::connect (smoothEffectEdit, int(this->smoothEffect), [this](int id) {\n      this->smoothEffect = SketchPathSmoothEffect (id);\n      this->self->cache ().set (\"smooth-effect\", id);\n    });\n    properties.addStacked (QObject::tr (\"Smoothing effect\"), smoothEffectEdit);\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Drag to sketch\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift,\n                 QObject::tr (\"Drag to smooth\"));\n    toolTip.add (ViewInputEvent::R, QObject::tr (\"Move to change radius\"));\n    this->self->state ().setToolTip (&toolTip);\n  }\n\n  void setupCursor ()\n  {\n    this->cursor.disable ();\n    this->cursor.radius (this->radiusEdit.doubleValue ());\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->self->supportsMirror ();\n\n    this->setupProperties ();\n    this->setupToolTip ();\n    this->setupCursor ();\n\n    return ToolResponse::None;\n  }\n\n  void runRender () const\n  {\n    Camera& camera = this->self->state ().camera ();\n\n    if (this->cursor.isEnabled ())\n    {\n      this->cursor.render (camera);\n    }\n  }\n\n  glm::vec3 newSpherePosition (bool considerHeight, const glm::vec3& position,\n                               const glm::vec3& normal)\n  {\n    if (considerHeight)\n    {\n      const float factor =\n        float(this->radiusEdit.doubleValue () * (1.0f - (2.0f * this->heightEdit.doubleValue ())));\n      return position - (normal * factor);\n    }\n    else\n    {\n      return position;\n    }\n  }\n\n  ToolResponse runMoveEvent (const ViewPointingEvent& e)\n  {\n    this->step.stepWidth (this->radiusEdit.doubleValue () * this->stepWidthFactor);\n\n    if (e.leftButton ())\n    {\n      if (e.modifiers () == Qt::ShiftModifier)\n      {\n        SketchPathIntersection intersection;\n\n        if (this->self->intersectsScene (e, intersection))\n        {\n          this->cursor.enable ();\n          this->cursor.position (intersection.position ());\n\n          this->step.step (intersection.position (), [this,\n                                                      &intersection](const glm::vec3& position) {\n            intersection.mesh ().smoothPath (intersection.path (),\n                                             PrimSphere (position, this->radiusEdit.doubleValue ()),\n                                             1, this->smoothEffect, this->self->mirrorDimension ());\n            return true;\n          });\n\n          this->mesh = &intersection.mesh ();\n        }\n      }\n      else if (this->mesh)\n      {\n        SketchMeshIntersection intersection;\n        const unsigned int     numExcludedLastPaths = this->self->mirrorEnabled () ? 2 : 1;\n        bool                   considerHeight = true;\n\n        if (this->self->intersectsScene (e, intersection, numExcludedLastPaths) == false)\n        {\n          const Camera&   camera = this->self->state ().camera ();\n          const PrimRay   ray = camera.ray (e.position ());\n          const PrimPlane plane =\n            PrimPlane (this->step.position (), DimensionUtil::vector (camera.primaryDimension ()));\n          float t;\n          if (IntersectionUtil::intersects (ray, plane, &t))\n          {\n            intersection.update (t, ray.pointAt (t), plane.normal (), *this->mesh);\n            considerHeight = false;\n          }\n        }\n\n        if (intersection.isIntersection ())\n        {\n          this->cursor.enable ();\n          this->cursor.position (intersection.position ());\n\n          this->step.step (intersection.position (), [this, considerHeight,\n                                                      &intersection](const glm::vec3& position) {\n            this->mesh->addSphere (\n              false, intersection.position (),\n              this->newSpherePosition (considerHeight, position, intersection.normal ()),\n              this->radiusEdit.doubleValue (), this->self->mirrorDimension ());\n\n            return true;\n          });\n        }\n      }\n      return ToolResponse::Redraw;\n    }\n    else\n    {\n      if (this->self->onKeymap ('r'))\n      {\n        this->radiusEdit.setIntValue (this->radiusEdit.intValue () + e.delta ().x);\n      }\n      return this->runCursorUpdate (e.position ());\n    }\n  }\n\n  ToolResponse runPressEvent (const ViewPointingEvent& e)\n  {\n    auto setupOnIntersection = [this](const SketchMeshIntersection& intersection) {\n      this->cursor.enable ();\n      this->cursor.position (intersection.position ());\n\n      this->self->snapshotSketchMeshes ();\n      this->self->mirrorPosition (intersection.mesh ().tree ().root ().data ().center ());\n\n      this->mesh = &intersection.mesh ();\n      this->step.position (intersection.position ());\n    };\n\n    if (e.leftButton ())\n    {\n      if (e.modifiers () == Qt::ShiftModifier)\n      {\n        SketchPathIntersection intersection;\n        if (this->self->intersectsScene (e, intersection))\n        {\n          setupOnIntersection (intersection);\n\n          this->mesh->smoothPath (\n            intersection.path (),\n            PrimSphere (intersection.position (), this->radiusEdit.doubleValue ()), 1,\n            this->smoothEffect, this->self->mirrorDimension ());\n        }\n      }\n      else\n      {\n        SketchMeshIntersection intersection;\n        if (this->self->intersectsScene (e, intersection))\n        {\n          setupOnIntersection (intersection);\n\n          const glm::vec3 spherePosition =\n            this->newSpherePosition (true, intersection.position (), intersection.normal ());\n\n          this->mesh->addSphere (true, intersection.position (), spherePosition,\n                                 this->radiusEdit.doubleValue (), this->self->mirrorDimension ());\n        }\n        else\n        {\n          this->cursor.disable ();\n        }\n      }\n      return ToolResponse::Redraw;\n    }\n    else\n    {\n      return ToolResponse::None;\n    }\n  }\n\n  ToolResponse runReleaseEvent (const ViewPointingEvent&) { return this->runCommit (); }\n\n  ToolResponse runCursorUpdate (const glm::ivec2& pos)\n  {\n    SketchMeshIntersection intersection;\n    if (this->self->intersectsScene (pos, intersection))\n    {\n      this->cursor.enable ();\n      this->cursor.position (intersection.position ());\n    }\n    else\n    {\n      this->cursor.disable ();\n    }\n    return ToolResponse::Redraw;\n  }\n\n  ToolResponse runCommit ()\n  {\n    this->mesh = nullptr;\n    return ToolResponse::None;\n  }\n\n  void runFromConfig ()\n  {\n    const Config& config = this->self->config ();\n\n    this->cursor.color (config.get<Color> (\"editor/tool/cursor-color\"));\n    this->stepWidthFactor = config.get<float> (\"editor/tool/sketch-spheres/step-width-factor\");\n  }\n};\n\nDELEGATE_TOOL (ToolSketchSpheres)\nDELEGATE_TOOL_RUN_RENDER (ToolSketchSpheres)\nDELEGATE_TOOL_RUN_MOVE_EVENT (ToolSketchSpheres)\nDELEGATE_TOOL_RUN_PRESS_EVENT (ToolSketchSpheres)\nDELEGATE_TOOL_RUN_RELEASE_EVENT (ToolSketchSpheres)\nDELEGATE_TOOL_RUN_CURSOR_UPDATE (ToolSketchSpheres)\nDELEGATE_TOOL_RUN_COMMIT (ToolSketchSpheres)\nDELEGATE_TOOL_RUN_FROM_CONFIG (ToolSketchSpheres)\n"
  },
  {
    "path": "lib/src/tool/transform-mesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QAbstractButton>\n#include <QButtonGroup>\n#include <glm/glm.hpp>\n#include \"cache.hpp\"\n#include \"camera.hpp\"\n#include \"dimension.hpp\"\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"mesh.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"state.hpp\"\n#include \"tool/util/movement.hpp\"\n#include \"tool/util/rotation.hpp\"\n#include \"tool/util/scaling.hpp\"\n#include \"tools.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/shortcut.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  enum class Mode\n  {\n    Move,\n    Rotate,\n    Scale\n  };\n\n  enum class RotationOrigin\n  {\n    Intersection,\n    Center,\n    Origin\n  };\n\n  enum class ScalingMode\n  {\n    Uniform,\n    PrimaryPlane\n  };\n}\n\nstruct ToolTransformMesh::Impl\n{\n  ToolTransformMesh* self;\n  DynamicMesh*       mesh;\n  Mode               mode;\n  ToolUtilMovement   movement;\n  ToolUtilScaling    scaling;\n  ScalingMode        scalingMode;\n  glm::vec3          scalingSize;\n  ToolUtilRotation   rotation;\n  RotationOrigin     rotationOrigin;\n\n  Impl (ToolTransformMesh* s)\n    : self (s)\n    , mesh (nullptr)\n    , movement (s->state ().camera (), false)\n    , scaling (s->state ().camera ())\n    , scalingMode (ScalingMode (s->cache ().get<int> (\"scaling-mode\", int(ScalingMode::Uniform))))\n    , rotation (s->state ().camera ())\n    , rotationOrigin (\n        RotationOrigin (s->cache ().get<int> (\"rotation-origin\", int(RotationOrigin::Center))))\n  {\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->setupProperties ();\n    this->setupToolTip ();\n\n    return ToolResponse::None;\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    this->self->addMoveOnPrimaryPlaneProperties (this->movement);\n\n    properties.addSeparator ();\n\n    QButtonGroup& scalingModeEdit = ViewUtil::buttonGroup (\n      {QObject::tr (\"Scale uniformly\"), QObject::tr (\"Scale on primary plane\")});\n    ViewUtil::connect (scalingModeEdit, int(this->scalingMode), [this](int id) {\n      this->scalingMode = ScalingMode (id);\n      this->self->cache ().set (\"scaling-mode\", id);\n    });\n    properties.add (scalingModeEdit);\n\n    properties.addSeparator ();\n\n    QButtonGroup& rotationOriginEdit =\n      ViewUtil::buttonGroup ({QObject::tr (\"Rotate at intersection\"),\n                              QObject::tr (\"Rotate at center\"), QObject::tr (\"Rotate at origin\")});\n    ViewUtil::connect (rotationOriginEdit, int(this->rotationOrigin), [this](int id) {\n      this->rotationOrigin = RotationOrigin (id);\n      this->self->cache ().set (\"rotation-origin\", id);\n    });\n    properties.add (rotationOriginEdit);\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Drag to move\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift,\n                 QObject::tr (\"Drag to scale\"));\n    toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Ctrl,\n                 QObject::tr (\"Drag to rotate\"));\n\n    this->self->state ().setToolTip (&toolTip);\n  }\n\n  glm::vec3 scalingVector () const\n  {\n    assert (this->mesh);\n\n    const float     minExtent = 0.01f;\n    const glm::vec3 extent = this->scalingSize * this->mesh->scaling ();\n    glm::vec3       scaling = glm::vec3 (1.0f);\n\n    switch (this->scalingMode)\n    {\n      case ScalingMode::Uniform:\n        scaling = glm::vec3 (this->scaling.factor ());\n        break;\n\n      case ScalingMode::PrimaryPlane:\n        switch (this->self->state ().camera ().primaryDimension ())\n        {\n          case Dimension::X:\n            scaling.z = this->scaling.factorRight ();\n            scaling.y = this->scaling.factorUp ();\n            break;\n          case Dimension::Y:\n            scaling.x = this->scaling.factorRight ();\n            scaling.z = this->scaling.factorUp ();\n            break;\n          case Dimension::Z:\n            scaling.x = this->scaling.factorRight ();\n            scaling.y = this->scaling.factorUp ();\n            break;\n        }\n    }\n\n    if (scaling.x * extent.x < minExtent)\n    {\n      scaling.x = 1.0f;\n    }\n    if (scaling.y * extent.y < minExtent)\n    {\n      scaling.y = 1.0f;\n    }\n    if (scaling.z * extent.z < minExtent)\n    {\n      scaling.z = 1.0f;\n    }\n    return scaling;\n  }\n\n  ToolResponse runMoveEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton () && this->mesh)\n    {\n      if (this->mode == Mode::Move && this->movement.move (e))\n      {\n        this->mesh->translate (this->movement.delta ());\n        return ToolResponse::Redraw;\n      }\n      else if (this->mode == Mode::Scale && this->scaling.move (e))\n      {\n        this->mesh->scale (this->scalingVector ());\n        return ToolResponse::Redraw;\n      }\n      else if (this->mode == Mode::Rotate && this->rotation.rotate (e))\n      {\n        this->mesh->rotate (this->rotation.matrix ());\n        return ToolResponse::Redraw;\n      }\n    }\n    return ToolResponse::None;\n  }\n\n  ToolResponse runPressEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton ())\n    {\n      DynamicMeshIntersection intersection;\n      if (this->self->intersectsScene (e, intersection))\n      {\n        this->mesh = &intersection.mesh ();\n        if (e.modifiers () == Qt::NoModifier)\n        {\n          this->self->snapshotDynamicMeshes ();\n\n          this->movement.reset (intersection.position ());\n          this->mode = Mode::Move;\n        }\n        else if (e.modifiers () == Qt::ShiftModifier)\n        {\n          this->self->snapshotDynamicMeshes ();\n\n          const PrimAABox bounds = this->mesh->mesh ().bounds ();\n          this->scalingSize = bounds.maximum () - bounds.minimum ();\n          this->scaling.reset (bounds.center (), intersection.position ());\n\n          this->mesh->position (-bounds.center ());\n          this->mesh->normalize ();\n          this->mesh->bufferData ();\n          this->mesh->position (bounds.center ());\n\n          this->mode = Mode::Scale;\n        }\n        else if (e.modifiers () == Qt::ControlModifier)\n        {\n          this->self->snapshotDynamicMeshes ();\n\n          switch (this->rotationOrigin)\n          {\n            case RotationOrigin::Intersection:\n              this->rotation.reset (intersection.position ());\n              break;\n            case RotationOrigin::Center:\n              this->rotation.reset (this->mesh->mesh ().bounds ().center ());\n              break;\n            case RotationOrigin::Origin:\n              this->rotation.reset (glm::vec3 (0.0f));\n              break;\n          }\n          this->mode = Mode::Rotate;\n        }\n      }\n    }\n    return ToolResponse::None;\n  }\n\n  ToolResponse runReleaseEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton ())\n    {\n      return this->runCommit ();\n    }\n    return ToolResponse::None;\n  }\n\n  ToolResponse runCommit ()\n  {\n    if (this->mesh)\n    {\n      this->mesh->normalize ();\n      this->mesh->bufferData ();\n      this->mesh = nullptr;\n    }\n    return ToolResponse::None;\n  }\n};\n\nDELEGATE_TOOL (ToolTransformMesh)\nDELEGATE_TOOL_RUN_MOVE_EVENT (ToolTransformMesh)\nDELEGATE_TOOL_RUN_PRESS_EVENT (ToolTransformMesh)\nDELEGATE_TOOL_RUN_RELEASE_EVENT (ToolTransformMesh)\nDELEGATE_TOOL_RUN_COMMIT (ToolTransformMesh)\n"
  },
  {
    "path": "lib/src/tool/trim-mesh/action.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <functional>\n#include <glm/glm.hpp>\n#include <glm/gtx/norm.hpp>\n#include <list>\n#include <unordered_set>\n#include \"dynamic/mesh.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"tool/trim-mesh/action.hpp\"\n#include \"tool/trim-mesh/border.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  constexpr float scalingFactor = 100.0f;\n  constexpr float minSquareSize = 0.02f * scalingFactor;\n\n  namespace Simple\n  {\n    enum class Location\n    {\n      On,\n      Left,\n      Right\n    };\n\n    Location location (const glm::vec2& pos, const glm::vec2& from, const glm::vec2& to)\n    {\n      const float c = Util::cross (from - pos, to - pos);\n\n      if (c < 0.0f)\n      {\n        return Location::Right;\n      }\n      else if (c < Util::epsilon ())\n      {\n        return Location::On;\n      }\n      else\n      {\n        return Location::Left;\n      }\n    }\n\n    bool isLeft (const glm::vec2& pos, const glm::vec2& from, const glm::vec2& to)\n    {\n      return location (pos, from, to) == Location::Left;\n    }\n\n    bool isRight (const glm::vec2& pos, const glm::vec2& from, const glm::vec2& to)\n    {\n      return location (pos, from, to) == Location::Right;\n    }\n\n    struct TwoDSquare\n    {\n      enum class State\n      {\n        Outside,\n        Inside,\n        Border,\n      };\n\n      unsigned int vertexIndex;\n      glm::uvec2   position;\n      glm::vec2    center;\n      float        halfWidth;\n      State        state;\n      bool         visited;\n\n      TwoDSquare (const glm::uvec2& p, const glm::vec2& c, float width)\n        : vertexIndex (Util::invalidIndex ())\n        , position (p)\n        , center (c)\n        , halfWidth (width * 0.5f)\n        , state (State::Outside)\n        , visited (false)\n      {\n      }\n\n      bool intersects (const glm::vec2& square1, const glm::vec2& square2,\n                       const glm::vec2& segment1, const glm::vec2& segment2) const\n      {\n        const glm::vec2 square = square2 - square1;\n        const glm::vec2 segment = segment2 - segment1;\n        const float     denom = Util::cross (square, segment);\n\n        if (Util::almostEqual (0.0f, denom))\n        {\n          return false;\n        }\n\n        const float t1 = Util::cross (segment1 - square1, segment) / denom;\n        const float t2 = Util::cross (segment1 - square1, square) / denom;\n        const bool  validT1 = 0.0f <= t1 && t1 <= 1.0f;\n        const bool  validT2 = 0.0f <= t2 && t2 <= 1.0f;\n\n        return validT1 && validT2;\n      }\n\n      bool inside (const glm::vec2& v) const\n      {\n        const bool less = glm::all (glm::lessThanEqual (this->center - halfWidth, v));\n        const bool greater = glm::all (glm::greaterThanEqual (this->center + halfWidth, v));\n\n        return less && greater;\n      }\n\n      bool intersects (const glm::vec2& segment1, const glm::vec2& segment2) const\n      {\n        const glm::vec2 v1 (this->center.x - this->halfWidth, this->center.y - this->halfWidth);\n        const glm::vec2 v2 (this->center.x - this->halfWidth, this->center.y + this->halfWidth);\n        const glm::vec2 v3 (this->center.x + this->halfWidth, this->center.y - this->halfWidth);\n        const glm::vec2 v4 (this->center.x + this->halfWidth, this->center.y + this->halfWidth);\n\n        const bool inside = this->inside (segment1) && this->inside (segment2);\n        const bool inter1 = this->intersects (v1, v2, segment1, segment2);\n        const bool inter2 = this->intersects (v1, v3, segment1, segment2);\n        const bool inter3 = this->intersects (v2, v4, segment1, segment2);\n        const bool inter4 = this->intersects (v3, v4, segment1, segment2);\n\n        return inside || inter1 || inter2 || inter3 || inter4;\n      }\n    };\n\n    enum class Curvature\n    {\n      Straight,\n      Convex,\n      Concave\n    };\n\n    struct TwoDVertex\n    {\n      unsigned int index;\n      glm::vec2    position;\n      Curvature    curvature;\n      bool         isEar;\n      float        angle;\n      float        distanceToPrev;\n      float        distanceToNext;\n\n      TwoDVertex (unsigned int i, const glm::vec2& p)\n        : index (i)\n        , position (p)\n        , curvature (Curvature::Straight)\n        , isEar (false)\n        , angle (0.0f)\n        , distanceToPrev (0.0f)\n        , distanceToNext (0.0f)\n      {\n      }\n\n      Location location (const glm::vec2& from, const glm::vec2& to) const\n      {\n        return Simple::location (this->position, from, to);\n      }\n\n      bool isLeft (const glm::vec2& from, const glm::vec2& to) const\n      {\n        return Simple::isLeft (this->position, from, to);\n      }\n\n      bool isRight (const glm::vec2& from, const glm::vec2& to) const\n      {\n        return Simple::isRight (this->position, from, to);\n      }\n\n      bool isInsideTriangle (const glm::vec2& v1, const glm::vec2& v2, const glm::vec2& v3) const\n      {\n        return this->isLeft (v1, v2) && this->isLeft (v2, v3) && this->isLeft (v3, v1);\n      }\n    };\n\n    typedef std::list<TwoDVertex>        TwoDVertices;\n    typedef TwoDVertices::iterator       TwoDVertexRef;\n    typedef TwoDVertices::const_iterator TwoDVertexCRef;\n\n    struct TwoDPolyline;\n    typedef std::vector<TwoDPolyline> TwoDPolylines;\n\n    struct TwoDPolyline\n    {\n      TwoDVertices  vertices;\n      TwoDVertexRef maxX;\n      bool          isCCW;\n\n      TwoDPolyline (const TwoDVertices& vs)\n        : vertices (vs)\n        , maxX (this->vertices.end ())\n        , isCCW (false)\n      {\n      }\n\n      TwoDVertexRef  begin () { return this->vertices.begin (); }\n      TwoDVertexCRef begin () const { return this->vertices.begin (); }\n      TwoDVertexRef  end () { return this->vertices.end (); }\n      TwoDVertexCRef end () const { return this->vertices.end (); }\n      unsigned int   size () const { return this->vertices.size (); }\n\n      TwoDVertexRef prev (TwoDVertexRef v)\n      {\n        return std::prev (v == this->begin () ? this->end () : v);\n      }\n\n      TwoDVertexCRef prev (TwoDVertexCRef v) const\n      {\n        return std::prev (v == this->begin () ? this->end () : v);\n      }\n\n      TwoDVertexRef next (TwoDVertexRef v)\n      {\n        return v == std::prev (this->end ()) ? this->begin () : std::next (v);\n      }\n\n      TwoDVertexCRef next (TwoDVertexCRef v) const\n      {\n        return v == std::prev (this->end ()) ? this->begin () : std::next (v);\n      }\n\n      void setCurvature (TwoDVertexRef v) const\n      {\n        switch (v->location (this->prev (v)->position, this->next (v)->position))\n        {\n          case Location::On:\n            v->curvature = Curvature::Straight;\n            break;\n          case Location::Right:\n            v->curvature = Curvature::Convex;\n            break;\n          case Location::Left:\n            v->curvature = Curvature::Concave;\n            break;\n        }\n      }\n\n      void setIsEar (TwoDVertexRef v) const\n      {\n        if (v->curvature == Curvature::Convex)\n        {\n          const TwoDVertexCRef p = this->prev (v);\n          const TwoDVertexCRef n = this->next (v);\n\n          for (TwoDVertexCRef it = this->begin (); it != this->end (); ++it)\n          {\n            if (it != p && it != v && it != n)\n            {\n              if (it->isInsideTriangle (p->position, v->position, n->position))\n              {\n                v->isEar = false;\n                return;\n              }\n            }\n          }\n          v->isEar = true;\n        }\n        else\n        {\n          v->isEar = false;\n        }\n      }\n\n      void setAngle (TwoDVertexRef v)\n      {\n        TwoDVertexRef p = this->prev (v);\n        TwoDVertexRef n = this->next (v);\n\n        v->distanceToPrev = glm::distance (v->position, p->position);\n        v->distanceToNext = glm::distance (v->position, n->position);\n\n        p->distanceToNext = v->distanceToPrev;\n        n->distanceToPrev = v->distanceToNext;\n\n        const glm::vec2 toP = (p->position - v->position) / v->distanceToPrev;\n        const glm::vec2 toN = (n->position - v->position) / v->distanceToNext;\n\n        v->angle = glm::acos (glm::clamp (glm::dot (toP, toN), -1.0f, 1.0f));\n      }\n\n      void setProperties ()\n      {\n        int n = 0;\n        this->maxX = this->vertices.end ();\n\n        for (TwoDVertexRef v = this->begin (); v != this->end (); ++v)\n        {\n          this->setCurvature (v);\n\n          if (v->curvature == Curvature::Convex)\n          {\n            n++;\n          }\n          else if (v->curvature == Curvature::Concave)\n          {\n            n--;\n          }\n\n          if (this->maxX == this->vertices.end () || v->position.x > this->maxX->position.x)\n          {\n            this->maxX = v;\n          }\n        }\n        assert (this->maxX != this->vertices.end ());\n\n        this->isCCW = n > 0;\n\n        for (TwoDVertexRef v = this->begin (); v != this->end (); ++v)\n        {\n          this->setIsEar (v);\n          this->setAngle (v);\n        }\n      }\n\n      void removeEar (TwoDVertexRef v)\n      {\n        assert (v->isEar);\n        assert (this->size () > 3);\n\n        TwoDVertexRef p = this->prev (v);\n        TwoDVertexRef n = this->next (v);\n\n        this->vertices.erase (v);\n        this->setCurvature (p);\n        this->setCurvature (n);\n        this->setIsEar (p);\n        this->setIsEar (n);\n        this->setAngle (p);\n        this->setAngle (n);\n      }\n\n      bool updateEarCandidate (TwoDVertexCRef v, float& weight) const\n      {\n        assert (v->isEar);\n\n        const bool nearPrev = Util::almostEqual (0.0f, v->distanceToPrev);\n        const bool nearNext = Util::almostEqual (0.0f, v->distanceToNext);\n\n        if (nearPrev || nearNext)\n        {\n          weight = Util::minFloat ();\n          return true;\n        }\n        else\n        {\n          const float bestAngle = glm::cos (glm::radians (60.0f));\n          const float w = glm::abs (v->angle - bestAngle);\n\n          if (w < weight)\n          {\n            weight = w;\n            return true;\n          }\n          else\n          {\n            return false;\n          }\n        }\n      }\n\n      bool fillHole (DynamicMesh& mesh)\n      {\n        const auto addFace = [&mesh](TwoDVertexCRef a, TwoDVertexCRef b, TwoDVertexCRef c) {\n          mesh.addFace (a->index, b->index, c->index);\n        };\n\n        while (this->size () > 3)\n        {\n          TwoDVertexRef earCandidate = this->end ();\n          float         weight = Util::maxFloat ();\n\n          for (TwoDVertexRef v = this->begin (); v != this->end (); ++v)\n          {\n            if (v->isEar && updateEarCandidate (v, weight))\n            {\n              earCandidate = v;\n            }\n          }\n\n          if (earCandidate != this->end ())\n          {\n            addFace (this->prev (earCandidate), earCandidate, this->next (earCandidate));\n            this->removeEar (earCandidate);\n          }\n          else\n          {\n            DILAY_WARN (\"Could not find ear candidate\");\n            return false;\n          }\n        }\n        assert (this->size () == 3);\n        addFace (this->vertices.begin (), std::next (this->vertices.begin (), 1),\n                 std::next (this->vertices.begin (), 2));\n\n        return true;\n      }\n\n      bool contains (const glm::vec2& v) const\n      {\n        assert (this->size () >= 3);\n        int windingNumber = 0;\n\n        for (TwoDVertexCRef v0 = this->begin (); v0 != this->end (); ++v0)\n        {\n          TwoDVertexCRef v1 = this->next (v0);\n          const float    v0Y = v0->position.y;\n          const float    v1Y = v1->position.y;\n\n          if (v0Y <= v.y && v.y < v1Y && isLeft (v, v0->position, v1->position))\n          {\n            windingNumber++;\n          }\n          else if (v1Y <= v.y && v.y < v0Y && isRight (v, v0->position, v1->position))\n          {\n            windingNumber--;\n          }\n        }\n        return windingNumber != 0;\n      }\n\n      bool contains (const TwoDPolyline& poly) const\n      {\n        for (TwoDVertexCRef v = poly.begin (); v != poly.end (); ++v)\n        {\n          if (this->contains (v->position) == false)\n          {\n            return false;\n          }\n        }\n        return true;\n      }\n\n      bool intersects (const TwoDSquare& square) const\n      {\n        for (TwoDVertexCRef v = this->begin (); v != this->end (); ++v)\n        {\n          if (square.intersects (v->position, this->next (v)->position))\n          {\n            return true;\n          }\n        }\n        return false;\n      }\n    };\n\n    struct TwoDGrid\n    {\n      glm::uvec2              dimension;\n      std::vector<TwoDSquare> squares;\n\n      unsigned int index (unsigned int x, unsigned int y) const\n      {\n        assert (x < this->dimension.x);\n        assert (y < this->dimension.y);\n        assert ((y * this->dimension.x) + x < this->squares.size ());\n        return (y * this->dimension.x) + x;\n      }\n\n      unsigned int index (glm::uvec2 pos) const { return this->index (pos.x, pos.y); }\n\n      TwoDSquare& advanceNeighbor (const TwoDSquare& p, const TwoDSquare& n)\n      {\n        const int x = int(n.position.x) - int(p.position.x);\n        const int y = int(n.position.y) - int(p.position.y);\n\n        if (x == 0 && y == 1)\n        {\n          return this->squares[this->index (glm::uvec2 (n.position.x + 1, n.position.y))];\n        }\n        else if (x == 1 && y == 1)\n        {\n          return this->squares[this->index (glm::uvec2 (n.position.x, n.position.y - 1))];\n        }\n        else if (x == 1 && y == 0)\n        {\n          return this->squares[this->index (glm::uvec2 (n.position.x, n.position.y - 1))];\n        }\n        else if (x == 1 && y == -1)\n        {\n          return this->squares[this->index (glm::uvec2 (n.position.x - 1, n.position.y))];\n        }\n        else if (x == 0 && y == -1)\n        {\n          return this->squares[this->index (glm::uvec2 (n.position.x - 1, n.position.y))];\n        }\n        else if (x == -1 && y == -1)\n        {\n          return this->squares[this->index (glm::uvec2 (n.position.x, n.position.y + 1))];\n        }\n        else if (x == -1 && y == 0)\n        {\n          return this->squares[this->index (glm::uvec2 (n.position.x, n.position.y + 1))];\n        }\n        else if (x == -1 && y == 1)\n        {\n          return this->squares[this->index (glm::uvec2 (n.position.x + 1, n.position.y))];\n        }\n        else\n        {\n          DILAY_IMPOSSIBLE\n        }\n      }\n\n      TwoDGrid (const ToolTrimMeshBorder& trimBorder, TwoDPolylines& ps)\n      {\n        constexpr TwoDSquare::State border = TwoDSquare::State::Border;\n        constexpr TwoDSquare::State inside = TwoDSquare::State::Inside;\n        constexpr TwoDSquare::State outside = TwoDSquare::State::Outside;\n\n        glm::vec2    min = glm::vec2 (Util::maxFloat ());\n        glm::vec2    max = glm::vec2 (Util::minFloat ());\n        float        avgLength = 0.0f;\n        unsigned int numSegments = 0;\n\n        for (TwoDPolyline& p : ps)\n        {\n          for (TwoDVertexCRef v = p.begin (); v != p.end (); ++v)\n          {\n            min = glm::min (min, v->position);\n            max = glm::max (max, v->position);\n\n            numSegments++;\n            avgLength += glm::distance (v->position, p.next (v)->position);\n          }\n        }\n        avgLength = glm::max (minSquareSize, avgLength / float(numSegments));\n\n        min -= avgLength;\n        max += avgLength;\n\n        this->dimension.x = (unsigned int) (glm::ceil ((max.x - min.x) / avgLength));\n        this->dimension.y = (unsigned int) (glm::ceil ((max.y - min.y) / avgLength));\n\n        if (this->dimension.x == 0 || this->dimension.y == 0)\n        {\n          return;\n        }\n        this->squares.reserve (this->dimension.x * this->dimension.y);\n\n        for (unsigned int y = 0; y < this->dimension.y; y++)\n        {\n          for (unsigned int x = 0; x < this->dimension.x; x++)\n          {\n            const glm::vec2 pos = min + (glm::vec2 (float(x), float(y)) * avgLength);\n            this->squares.emplace_back (glm::uvec2 (x, y), pos, avgLength);\n            TwoDSquare& square = this->squares.back ();\n\n            unsigned int numContains = 0;\n            for (const TwoDPolyline& p : ps)\n            {\n              if (p.contains (pos))\n              {\n                numContains++;\n              }\n            }\n\n            if (numContains % 2 == 1)\n            {\n              square.state = inside;\n            }\n            assert (y > 0 || square.state == outside);\n            assert (y < this->dimension.y - 1 || square.state == outside);\n            assert (x > 0 || square.state == outside);\n            assert (x < this->dimension.x - 1 || square.state == outside);\n          }\n        }\n        for (unsigned int y = 1; y < this->dimension.y - 1; y++)\n        {\n          for (unsigned int x = 1; x < this->dimension.x - 1; x++)\n          {\n            TwoDSquare& square = this->squares[this->index (x, y)];\n            if (square.state == inside)\n            {\n              for (const TwoDPolyline& p : ps)\n              {\n                if (p.intersects (square))\n                {\n                  square.state = outside;\n                  break;\n                }\n              }\n            }\n          }\n        }\n        for (unsigned int y = 1; y < this->dimension.y - 1; y++)\n        {\n          for (unsigned int x = 1; x < this->dimension.x - 1; x++)\n          {\n            if (this->squares[this->index (x, y)].state == inside)\n            {\n              const bool o1 = this->squares[this->index (x - 1, y)].state == outside;\n              const bool o2 = this->squares[this->index (x + 1, y)].state == outside;\n              const bool o3 = this->squares[this->index (x, y - 1)].state == outside;\n              const bool o4 = this->squares[this->index (x, y + 1)].state == outside;\n\n              const bool isBorder = o1 || o2 || o3 || o4;\n              if (isBorder)\n              {\n                this->squares[this->index (x, y)].state = border;\n              }\n            }\n          }\n        }\n        for (unsigned int y = 1; y < this->dimension.y - 1; y++)\n        {\n          for (unsigned int x = 1; x < this->dimension.x - 1; x++)\n          {\n            if (this->squares[this->index (x, y)].state == border)\n            {\n              const bool i1 = this->squares[this->index (x - 1, y)].state == inside;\n              const bool i2 = this->squares[this->index (x + 1, y)].state == inside;\n              const bool i3 = this->squares[this->index (x, y - 1)].state == inside;\n              const bool i4 = this->squares[this->index (x, y + 1)].state == inside;\n\n              const bool hasInsideNeighbor4 = i1 || i2 || i3 || i4;\n              if (hasInsideNeighbor4 == false)\n              {\n                this->squares[this->index (x, y)].state = outside;\n              }\n            }\n          }\n        }\n        for (unsigned int y = 1; y < this->dimension.y - 1; y++)\n        {\n          for (unsigned int x = 1; x < this->dimension.x - 1; x++)\n          {\n            TwoDSquare& square = this->squares[this->index (x, y)];\n\n            if (square.state != outside)\n            {\n              const glm::vec2 position2d = square.center / scalingFactor;\n              const glm::vec3 position = trimBorder.plane ().project (position2d);\n              const glm::vec3 normal = trimBorder.plane ().normal ();\n              square.vertexIndex = trimBorder.mesh ().addVertex (position, normal);\n            }\n          }\n        }\n        for (unsigned int y = 1; y < this->dimension.y - 1; y++)\n        {\n          TwoDSquare* prev = &this->squares[this->index (0, y)];\n          assert (prev->state == outside);\n\n          for (unsigned int x = 1; x < this->dimension.x - 1; x++)\n          {\n            TwoDSquare& start = this->squares[this->index (x, y)];\n\n            if (prev->state == outside && start.state == border && start.visited == false)\n            {\n              assert (start.vertexIndex != Util::invalidIndex ());\n\n              TwoDVertices vertices;\n              TwoDSquare*  current = &start;\n              TwoDSquare*  candidate = &this->advanceNeighbor (*current, *prev);\n\n              vertices.emplace_back (current->vertexIndex, current->center);\n              current->visited = true;\n\n              while (candidate != &start)\n              {\n                if (candidate->state == border)\n                {\n                  assert (candidate->vertexIndex != Util::invalidIndex ());\n                  assert (candidate->visited == false);\n                  vertices.emplace_back (candidate->vertexIndex, candidate->center);\n                  candidate->visited = true;\n\n                  prev = current;\n                  current = candidate;\n                  candidate = &this->advanceNeighbor (*current, *prev);\n                }\n                else\n                {\n                  prev = candidate;\n                  candidate = &this->advanceNeighbor (*current, *prev);\n                }\n              }\n              assert (vertices.size () >= 3);\n              ps.emplace_back (std::move (vertices));\n            }\n            prev = &start;\n          }\n        }\n      }\n\n      void fill (DynamicMesh& mesh) const\n      {\n        constexpr TwoDSquare::State out = TwoDSquare::State::Outside;\n\n        for (unsigned int y = 1; y < this->dimension.y - 2; y++)\n        {\n          for (unsigned int x = 1; x < this->dimension.x - 2; x++)\n          {\n            const TwoDSquare& s = this->squares[this->index (x, y)];\n            const TwoDSquare& sX = this->squares[this->index (x + 1, y)];\n            const TwoDSquare& sY = this->squares[this->index (x, y + 1)];\n            const TwoDSquare& sXY = this->squares[this->index (x + 1, y + 1)];\n\n            if (s.state != out && sX.state != out && sY.state != out && sXY.state != out)\n            {\n              assert (s.vertexIndex != Util::invalidIndex ());\n              assert (sX.vertexIndex != Util::invalidIndex ());\n              assert (sY.vertexIndex != Util::invalidIndex ());\n              assert (sXY.vertexIndex != Util::invalidIndex ());\n\n              mesh.addFace (s.vertexIndex, sX.vertexIndex, sY.vertexIndex);\n              mesh.addFace (sXY.vertexIndex, sY.vertexIndex, sX.vertexIndex);\n            }\n            else if (s.state != out && sX.state == out && sY.state != out && sXY.state != out)\n            {\n              assert (s.vertexIndex != Util::invalidIndex ());\n              assert (sY.vertexIndex != Util::invalidIndex ());\n              assert (sXY.vertexIndex != Util::invalidIndex ());\n\n              mesh.addFace (s.vertexIndex, sXY.vertexIndex, sY.vertexIndex);\n            }\n            else if (s.state != out && sX.state != out && sY.state == out && sXY.state != out)\n            {\n              assert (s.vertexIndex != Util::invalidIndex ());\n              assert (sX.vertexIndex != Util::invalidIndex ());\n              assert (sXY.vertexIndex != Util::invalidIndex ());\n\n              mesh.addFace (s.vertexIndex, sX.vertexIndex, sXY.vertexIndex);\n            }\n            else if (s.state != out && sX.state != out && sY.state != out && sXY.state == out)\n            {\n              assert (s.vertexIndex != Util::invalidIndex ());\n              assert (sX.vertexIndex != Util::invalidIndex ());\n              assert (sY.vertexIndex != Util::invalidIndex ());\n\n              mesh.addFace (s.vertexIndex, sX.vertexIndex, sY.vertexIndex);\n            }\n            else if (s.state == out && sX.state != out && sY.state != out && sXY.state != out)\n            {\n              assert (sX.vertexIndex != Util::invalidIndex ());\n              assert (sY.vertexIndex != Util::invalidIndex ());\n              assert (sXY.vertexIndex != Util::invalidIndex ());\n\n              mesh.addFace (sXY.vertexIndex, sY.vertexIndex, sX.vertexIndex);\n            }\n          }\n        }\n      }\n\n      void smooth (DynamicMesh& mesh) const\n      {\n        for (unsigned int i = 0; i < 3; i++)\n        {\n          for (unsigned int y = 1; y < this->dimension.y - 1; y++)\n          {\n            for (unsigned int x = 1; x < this->dimension.x - 1; x++)\n            {\n              const TwoDSquare& square = this->squares[this->index (x, y)];\n              if (square.state == TwoDSquare::State::Inside)\n              {\n                mesh.vertex (square.vertexIndex, mesh.averagePosition (square.vertexIndex));\n              }\n            }\n          }\n        }\n      }\n    };\n\n    TwoDVertexCRef findMutuallyVisibleVertex (const TwoDPolyline& outer, const TwoDPolyline& inner)\n    {\n      auto getIntersection = [&outer, &inner](TwoDVertexCRef v0,\n                                              glm::vec2&     intersection) -> TwoDVertexCRef {\n        TwoDVertexCRef   noCandidate = outer.end ();\n        TwoDVertexCRef   v1 = outer.next (v0);\n        TwoDVertexCRef   m = inner.maxX;\n        const glm::vec2& p0 = v0->position;\n        const glm::vec2& p1 = v1->position;\n        const glm::vec2& pm = m->position;\n\n        if (Util::almostEqual (pm.y, p0.y) && Util::almostEqual (pm.y, p1.y))\n        {\n          if (p0.x <= pm.x && p1.x <= pm.x)\n          {\n            return noCandidate;\n          }\n          else if (p0.x <= pm.x && pm.x < p1.x)\n          {\n            intersection = p1;\n            return v1;\n          }\n          else if (p1.x <= pm.x && pm.x < p0.x)\n          {\n            intersection = p0;\n            return v0;\n          }\n          else if (p0.x <= p1.x)\n          {\n            intersection = p0;\n            return v0;\n          }\n          else if (p1.x <= p0.x)\n          {\n            intersection = p1;\n            return v1;\n          }\n          else\n          {\n            DILAY_IMPOSSIBLE;\n          }\n        }\n        else if (m->isLeft (p0, p1) && p0.y <= pm.y && pm.y <= p1.y)\n        {\n          if (Util::almostEqual (p0.x, p1.x))\n          {\n            intersection = p0;\n            return v0;\n          }\n          else\n          {\n            const float slope = (p1.y - p0.y) / (p1.x - p0.x);\n            const float x = ((pm.y - p0.y) / slope) + p0.x;\n\n            intersection = glm::vec2 (x, pm.y);\n\n            return p0.x >= p1.x ? v0 : v1;\n          }\n        }\n        else\n        {\n          return noCandidate;\n        }\n      };\n\n      auto findInitialCandidate = [&getIntersection, &outer,\n                                   &inner](glm::vec2& minIntersection) -> TwoDVertexCRef {\n        TwoDVertexCRef candidate = outer.end ();\n        float          minDistance = Util::maxFloat ();\n\n        for (TwoDVertexCRef v = outer.begin (); v != outer.end (); ++v)\n        {\n          glm::vec2 intersection;\n\n          if (getIntersection (v, intersection) != outer.end ())\n          {\n            const float distance = glm::distance2 (inner.maxX->position, intersection);\n\n            if (distance < minDistance)\n            {\n              candidate = v;\n              minDistance = distance;\n              minIntersection = intersection;\n            }\n          }\n        }\n        assert (candidate != outer.end ());\n        return candidate;\n      };\n\n      auto findClosestContainedConcaveVertex =\n        [&outer, &inner](const glm::vec2& intersection,\n                         TwoDVertexCRef   candidate) -> TwoDVertexCRef {\n        const glm::vec2 toCandidate = glm::normalize (candidate->position - inner.maxX->position);\n\n        TwoDVertexCRef closest = outer.end ();\n        float          minDistance = Util::maxFloat ();\n        float          minAngle = Util::maxFloat ();\n\n        for (TwoDVertexCRef v = outer.begin (); v != outer.end (); ++v)\n        {\n          if (v != candidate && v->curvature == Curvature::Concave)\n          {\n            if (v->isInsideTriangle (candidate->position, intersection, inner.maxX->position))\n            {\n              const float     d = glm::distance (v->position, inner.maxX->position);\n              const glm::vec2 toV = (v->position - inner.maxX->position) / d;\n              const float     a = glm::acos (glm::clamp (glm::dot (toCandidate, toV), -1.0f, 1.0f));\n\n              if (a < minAngle || (Util::almostEqual (a, minAngle) && d < minDistance))\n              {\n                closest = v;\n                minAngle = a;\n                minDistance = d;\n              }\n            }\n          }\n        }\n        return closest;\n      };\n\n      glm::vec2      intersection;\n      TwoDVertexCRef candidate = findInitialCandidate (intersection);\n\n      if (intersection == candidate->position)\n      {\n        return candidate;\n      }\n      else\n      {\n        TwoDVertexCRef r = findClosestContainedConcaveVertex (intersection, candidate);\n        return r == outer.end () ? candidate : r;\n      }\n    }\n\n    TwoDPolyline combine (const TwoDPolyline& outer, const TwoDPolyline& inner)\n    {\n      TwoDVertices   vertices;\n      TwoDVertexCRef visible = findMutuallyVisibleVertex (outer, inner);\n      TwoDVertexCRef v = inner.maxX;\n\n      vertices.push_back (*visible);\n      do\n      {\n        vertices.push_back (*v);\n        v = inner.next (v);\n      } while (v != inner.maxX);\n\n      vertices.push_back (*inner.maxX);\n\n      v = visible;\n      do\n      {\n        vertices.push_back (*v);\n        v = outer.next (v);\n      } while (v != visible);\n\n      return TwoDPolyline (vertices);\n    }\n\n    void combine (TwoDPolyline& outer, TwoDPolylines& inner)\n    {\n      for (TwoDPolyline& i : inner)\n      {\n        i.setProperties ();\n      }\n      std::sort (inner.begin (), inner.end (), [](const TwoDPolyline& a, const TwoDPolyline& b) {\n        return a.maxX->position.x > b.maxX->position.x;\n      });\n\n      for (TwoDPolyline& i : inner)\n      {\n        outer.setProperties ();\n        outer = combine (outer, i);\n      }\n      inner.clear ();\n    }\n  }\n\n  namespace Nested\n  {\n    struct TwoDPolyline;\n    typedef std::vector<TwoDPolyline> TwoDPolylines;\n\n    struct TwoDPolyline\n    {\n      Simple::TwoDPolyline outer;\n      TwoDPolylines        inner;\n\n      TwoDPolyline (const Simple::TwoDPolyline& o)\n        : outer (o)\n      {\n      }\n\n      TwoDPolyline (const Simple::TwoDPolyline& o, const TwoDPolylines& i)\n        : outer (o)\n        , inner (i)\n      {\n      }\n    };\n\n    bool fillHole (TwoDPolylines& polys, DynamicMesh& mesh)\n    {\n      while (polys.empty () == false)\n      {\n        TwoDPolyline poly (std::move (polys.back ()));\n        polys.pop_back ();\n\n        Simple::TwoDPolylines simpleInner;\n\n        for (TwoDPolyline& i : poly.inner)\n        {\n          for (TwoDPolyline& oi : i.inner)\n          {\n            polys.push_back (std::move (oi));\n          }\n          i.inner.clear ();\n          simpleInner.push_back (std::move (i.outer));\n        }\n        poly.inner.clear ();\n\n        Simple::combine (poly.outer, simpleInner);\n\n        poly.outer.setProperties ();\n        if (poly.outer.fillHole (mesh) == false)\n        {\n          return false;\n        }\n      }\n      return true;\n    }\n\n    TwoDPolylines nest (const Simple::TwoDPolylines& ss)\n    {\n      TwoDPolylines ns;\n\n      std::function<bool(TwoDPolyline&, const Simple::TwoDPolyline&)> insert =\n        [&insert](TwoDPolyline& n, const Simple::TwoDPolyline& s) {\n          if (n.outer.contains (s))\n          {\n            for (TwoDPolyline& i : n.inner)\n            {\n              if (insert (i, s))\n              {\n                return true;\n              }\n            }\n            n.inner.push_back (TwoDPolyline (s));\n            return true;\n          }\n          else if (s.contains (n.outer))\n          {\n            TwoDPolylines is (std::move (n.inner));\n            n.inner.clear ();\n            n.inner.push_back (TwoDPolyline (std::move (n.outer), std::move (is)));\n            n.outer = s;\n            return true;\n          }\n          else\n          {\n            return false;\n          }\n        };\n\n      for (const Simple::TwoDPolyline& s : ss)\n      {\n        bool wasInserted = false;\n\n        for (TwoDPolyline& n : ns)\n        {\n          if (insert (n, s))\n          {\n            wasInserted = true;\n            break;\n          }\n        }\n        if (wasInserted == false)\n        {\n          ns.push_back (TwoDPolyline (s));\n        }\n      }\n      return ns;\n    }\n  }\n\n  bool fillHole (ToolTrimMeshBorder& border)\n  {\n    border.deleteEmptyPolylines ();\n    Simple::TwoDPolylines polylines;\n\n    for (const ToolTrimMeshBorder::Polyline& p : border.polylines ())\n    {\n      assert (p.size () >= 3);\n      Simple::TwoDVertices vertices;\n\n      for (unsigned int i : p)\n      {\n        const glm::vec2 position = border.plane ().project2d (border.mesh ().vertex (i));\n        vertices.emplace_back (i, scalingFactor * position);\n      }\n      polylines.emplace_back (vertices);\n    }\n    Simple::TwoDGrid      grid (border, polylines);\n    Nested::TwoDPolylines nested = Nested::nest (polylines);\n    if (Nested::fillHole (nested, border.mesh ()) == false)\n    {\n      return false;\n    }\n    else\n    {\n      grid.fill (border.mesh ());\n      grid.smooth (border.mesh ());\n    }\n    return true;\n  }\n\n  void trimVertices (const ToolTrimMeshBorder& border)\n  {\n    const auto isAboveBorder = [&border](unsigned int i) {\n      const glm::vec3& p = border.mesh ().vertex (i);\n      return border.onBorder (p) == false && border.plane ().distance (p) > 0.0f;\n    };\n\n    std::unordered_set<unsigned int> set;\n    const auto addAdjacentAboveBorder = [&border, &isAboveBorder, &set](unsigned int i) {\n      border.mesh ().forEachVertexAdjacentToVertex (i, [&isAboveBorder, &set](unsigned int a) {\n        if (isAboveBorder (a))\n        {\n          set.insert (a);\n        }\n      });\n    };\n\n    DynamicMesh& mesh = border.mesh ();\n    for (const ToolTrimMeshBorder::Polyline& p : border.polylines ())\n    {\n      for (unsigned int i : p)\n      {\n        addAdjacentAboveBorder (i);\n      }\n    }\n\n    while (set.empty () == false)\n    {\n      const unsigned int i = *set.begin ();\n      set.erase (set.begin ());\n\n      addAdjacentAboveBorder (i);\n      mesh.deleteVertex (i);\n    }\n  }\n}\n\nnamespace ToolTrimMeshAction\n{\n  bool trimMesh (ToolTrimMeshBorder& border)\n  {\n    trimVertices (border);\n\n    std::vector<unsigned int> newIndices;\n    border.mesh ().prune (&newIndices);\n    if (newIndices.empty () == false)\n    {\n      border.setNewIndices (newIndices);\n    }\n\n    if (fillHole (border) && border.mesh ().pruneAndCheckConsistency ())\n    {\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n}\n"
  },
  {
    "path": "lib/src/tool/trim-mesh/action.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_TRIM_MESH_ACTION\n#define DILAY_TOOL_TRIM_MESH_ACTION\n\nclass ToolTrimMeshBorder;\n\nnamespace ToolTrimMeshAction\n{\n  bool trimMesh (ToolTrimMeshBorder&);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/trim-mesh/border.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"intersection.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"tool/trim-mesh/border.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  typedef ToolTrimMeshBorder::Polyline  Polyline;\n  typedef ToolTrimMeshBorder::Polylines Polylines;\n}\n\nstruct ToolTrimMeshBorder::Impl\n{\n  DynamicMesh&    mesh;\n  Polylines       polylines;\n  const PrimRay   edge1;\n  const PrimRay   edge2;\n  const PrimPlane plane;\n\n  Impl (DynamicMesh& m, const PrimRay& r1, const PrimRay& r2)\n    : mesh (m)\n    , edge1 (r1)\n    , edge2 (r2)\n    , plane (r1.origin (), glm::cross (r2.direction (), r1.direction ()))\n  {\n  }\n\n  void addVertex (unsigned int index, const glm::vec3& p)\n  {\n    assert (this->onBorder (p));\n    assert (this->polylines.empty () == false);\n    unused (p);\n\n    this->polylines.back ().emplace_back (index);\n  }\n\n  void addPolyline () { this->polylines.emplace_back (); }\n\n  void setNewIndices (const std::vector<unsigned int>& newIndices)\n  {\n    for (Polyline& p : this->polylines)\n    {\n      for (unsigned int& i : p)\n      {\n        assert (newIndices.at (i) != Util::invalidIndex ());\n\n        i = newIndices.at (i);\n      }\n    }\n  }\n\n  bool isValidProjection (const glm::vec3& p) const\n  {\n    // assert (this->plane.onPlane (p)); // Occasionally fails due to rounding errors (?)\n\n    const bool c1 = 0.0f < glm::dot (this->plane.normal (), glm::cross (p - this->edge1.origin (),\n                                                                        this->edge1.direction ()));\n\n    const bool c2 = 0.0f < glm::dot (this->plane.normal (), glm::cross (this->edge2.direction (),\n                                                                        p - this->edge2.origin ()));\n    return c1 && c2;\n  }\n\n  bool onBorder (const glm::vec3& p) const\n  {\n    if (this->edge1.onRay (p))\n    {\n      return true;\n    }\n    else if (this->edge2.onRay (p))\n    {\n      return true;\n    }\n    else if (this->plane.onPlane (p))\n    {\n      return this->isValidProjection (p);\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  bool intersects (const PrimRay& ray, float& t) const\n  {\n    if (IntersectionUtil::intersects (ray, this->plane, &t))\n    {\n      return this->isValidProjection (ray.pointAt (t));\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  void deleteEmptyPolylines ()\n  {\n    this->polylines.erase (std::remove_if (this->polylines.begin (), this->polylines.end (),\n                                           [](Polyline& p) { return p.empty (); }),\n                           this->polylines.end ());\n  }\n\n  bool hasVertices () const\n  {\n    for (const Polyline& p : this->polylines)\n    {\n      if (p.empty () == false)\n      {\n        return true;\n      }\n    }\n    return false;\n  }\n};\n\nDELEGATE3_BIG2 (ToolTrimMeshBorder, DynamicMesh&, const PrimRay&, const PrimRay&)\nGETTER_CONST (DynamicMesh&, ToolTrimMeshBorder, mesh)\nGETTER_CONST (const Polylines&, ToolTrimMeshBorder, polylines)\nGETTER_CONST (const PrimPlane&, ToolTrimMeshBorder, plane)\nDELEGATE2 (void, ToolTrimMeshBorder, addVertex, unsigned int, const glm::vec3&)\nDELEGATE (void, ToolTrimMeshBorder, addPolyline)\nDELEGATE1 (void, ToolTrimMeshBorder, setNewIndices, const std::vector<unsigned int>&)\nDELEGATE1_CONST (bool, ToolTrimMeshBorder, onBorder, const glm::vec3&)\nDELEGATE2_CONST (bool, ToolTrimMeshBorder, intersects, const PrimRay&, float&)\nDELEGATE (void, ToolTrimMeshBorder, deleteEmptyPolylines)\nDELEGATE_CONST (bool, ToolTrimMeshBorder, hasVertices)\n"
  },
  {
    "path": "lib/src/tool/trim-mesh/border.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_TRIM_MESH_BORDER\n#define DILAY_TOOL_TRIM_MESH_BORDER\n\n#include <glm/fwd.hpp>\n#include <vector>\n#include \"macro.hpp\"\n\nclass DynamicMesh;\nclass PrimPlane;\nclass PrimRay;\n\nclass ToolTrimMeshBorder\n{\npublic:\n  typedef std::vector<unsigned int> Polyline;\n  typedef std::vector<Polyline>     Polylines;\n\n  DECLARE_BIG2 (ToolTrimMeshBorder, DynamicMesh&, const PrimRay&, const PrimRay&)\n\n  DynamicMesh&     mesh () const;\n  const Polylines& polylines () const;\n  const PrimPlane& plane () const;\n  void             addVertex (unsigned int, const glm::vec3&);\n  void             addPolyline ();\n  void             setNewIndices (const std::vector<unsigned int>&);\n  bool             onBorder (const glm::vec3&) const;\n  bool             intersects (const PrimRay&, float&) const;\n  void             deleteEmptyPolylines ();\n  bool             hasVertices () const;\n\nprivate:\n  IMPLEMENTATION\n};\n#endif\n"
  },
  {
    "path": "lib/src/tool/trim-mesh/split-mesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <unordered_set>\n#include \"dynamic/faces.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"hash.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"tool/trim-mesh/border.hpp\"\n#include \"tool/trim-mesh/split-mesh.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  typedef std::unordered_set<unsigned int> BorderVertices;\n\n  unsigned int splitEdge (DynamicMesh& mesh, unsigned int e1, unsigned e2, const glm::vec3& point)\n  {\n    unsigned int leftFace, leftVertex, rightFace, rightVertex;\n    mesh.findAdjacent (e1, e2, leftFace, leftVertex, rightFace, rightVertex);\n\n    const glm::vec3    normal = glm::normalize (mesh.vertexNormal (e1) + mesh.vertexNormal (e2));\n    const unsigned int newI = mesh.addVertex (point, normal);\n\n    mesh.deleteFace (leftFace);\n    mesh.deleteFace (rightFace);\n\n    mesh.addFace (e1, newI, leftVertex);\n    mesh.addFace (newI, e2, leftVertex);\n    mesh.addFace (e2, newI, rightVertex);\n    mesh.addFace (newI, e1, rightVertex);\n\n    return newI;\n  }\n\n  unsigned int splitEdge (const ToolTrimMeshBorder& border, unsigned int e1, unsigned int e2,\n\n                          BorderVertices& borderVertices)\n  {\n    const glm::vec3 v1 (border.mesh ().vertex (e1));\n    const glm::vec3 v2 (border.mesh ().vertex (e2));\n    const PrimRay   line (v1, v2 - v1);\n\n    bool checkIntersection = true;\n\n    if (border.onBorder (v1))\n    {\n      borderVertices.insert (e1);\n      checkIntersection = false;\n    }\n\n    if (border.onBorder (v2))\n    {\n      borderVertices.insert (e2);\n      checkIntersection = false;\n    }\n\n    if (checkIntersection)\n    {\n      float t;\n      if (border.intersects (line, t) && t > 0.0f && t < glm::distance (v1, v2))\n      {\n        const unsigned int i = splitEdge (border.mesh (), e1, e2, line.pointAt (t));\n        borderVertices.insert (i);\n        return i;\n      }\n    }\n    return Util::invalidIndex ();\n  }\n\n  void splitMesh (const ToolTrimMeshBorder& border, BorderVertices& borderVertices)\n  {\n    DynamicFaces faces;\n    border.mesh ().intersects (border.plane (), faces);\n\n    std::unordered_set<ui_pair> edges;\n    while (faces.isEmpty () == false)\n    {\n      edges.clear ();\n      for (unsigned int f : faces)\n      {\n        unsigned int i1, i2, i3;\n        border.mesh ().vertexIndices (f, i1, i2, i3);\n\n        edges.emplace (glm::min (i1, i2), glm::max (i1, i2));\n        edges.emplace (glm::min (i1, i3), glm::max (i1, i3));\n        edges.emplace (glm::min (i2, i3), glm::max (i2, i3));\n      }\n\n      for (const auto e : edges)\n      {\n        const unsigned int newI = splitEdge (border, e.first, e.second, borderVertices);\n        if (newI != Util::invalidIndex ())\n        {\n          for (unsigned int a : border.mesh ().adjacentFaces (newI))\n          {\n            faces.insert (a);\n          }\n        }\n      }\n      faces.resetCommitted ();\n      faces.commit ();\n    }\n  }\n\n  bool checkBorderVertices (const DynamicMesh& mesh, const BorderVertices& borderVertices)\n  {\n    for (unsigned int v : borderVertices)\n    {\n      unsigned int n = 0;\n      mesh.forEachVertexAdjacentToVertex (v, [&borderVertices, &n](unsigned int a) {\n        BorderVertices::const_iterator bIt = borderVertices.find (a);\n\n        if (bIt != borderVertices.cend ())\n        {\n          n++;\n        }\n      });\n      if (n != 2)\n      {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  bool traverseAlongEdge (const ToolTrimMeshBorder& border, unsigned int e1, unsigned int e2)\n  {\n    unsigned int leftFace, leftVertex, rightFace, rightVertex;\n    border.mesh ().findAdjacent (e1, e2, leftFace, leftVertex, rightFace, rightVertex);\n\n    const glm::vec3& vL = border.mesh ().vertex (leftVertex);\n    return border.onBorder (vL) ? false : border.plane ().distance (vL) > 0.0f;\n  }\n\n  void addPolylinesToBorder (ToolTrimMeshBorder& border, BorderVertices& borderVertices)\n  {\n    BorderVertices::iterator vIt = borderVertices.end ();\n\n    while (borderVertices.empty () == false)\n    {\n      if (vIt == borderVertices.end ())\n      {\n        border.addPolyline ();\n        vIt = borderVertices.begin ();\n      }\n\n      bool foundNext = false;\n\n      border.mesh ().forEachVertexAdjacentToVertex (\n        *vIt, [&border, &borderVertices, &vIt, &foundNext](unsigned int a) {\n          if (foundNext == false)\n          {\n            BorderVertices::iterator bIt = borderVertices.find (a);\n\n            if (bIt != borderVertices.end ())\n            {\n              if (traverseAlongEdge (border, *vIt, *bIt))\n              {\n                border.addVertex (*vIt, border.mesh ().vertex (*vIt));\n                borderVertices.erase (vIt);\n                vIt = bIt;\n                foundNext = true;\n                return;\n              }\n            }\n          }\n        });\n      if (foundNext == false)\n      {\n        border.addVertex (*vIt, border.mesh ().vertex (*vIt));\n        borderVertices.erase (vIt);\n        vIt = borderVertices.end ();\n      }\n    }\n  }\n}\n\nbool ToolTrimMeshSplitMesh::splitMesh (ToolTrimMeshBorder& border)\n{\n  BorderVertices borderVertices;\n  ::splitMesh (border, borderVertices);\n\n  if (borderVertices.empty ())\n  {\n    return true;\n  }\n  else if (checkBorderVertices (border.mesh (), borderVertices))\n  {\n    addPolylinesToBorder (border, borderVertices);\n    return true;\n  }\n  else\n  {\n    DILAY_WARN (\"Could not split mesh\");\n    return false;\n  }\n}\n"
  },
  {
    "path": "lib/src/tool/trim-mesh/split-mesh.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_TRIM_MESH_SPLIT_MESH\n#define DILAY_TOOL_TRIM_MESH_SPLIT_MESH\n\nclass ToolTrimMeshBorder;\n\nnamespace ToolTrimMeshSplitMesh\n{\n  bool splitMesh (ToolTrimMeshBorder&);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/trim-mesh.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QPainter>\n#include <QSlider>\n#include <QWheelEvent>\n#include \"cache.hpp\"\n#include \"camera.hpp\"\n#include \"color.hpp\"\n#include \"config.hpp\"\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"history.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"scene.hpp\"\n#include \"state.hpp\"\n#include \"tool/trim-mesh/action.hpp\"\n#include \"tool/trim-mesh/border.hpp\"\n#include \"tool/trim-mesh/split-mesh.hpp\"\n#include \"tools.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  enum class TrimStatus\n  {\n    Trimmed,\n    NotTrimmed,\n    Failed\n  };\n\n  enum class TrimMode\n  {\n    Normal,\n    Slice,\n    Cut\n  };\n}\n\nstruct ToolTrimMesh::Impl\n{\n  ToolTrimMesh*           self;\n  std::vector<glm::ivec2> points;\n  TrimMode                trimMode;\n  QSlider&                widthEdit;\n\n  Impl (ToolTrimMesh* s)\n    : self (s)\n    , trimMode (TrimMode (s->cache ().get<int> (\"trim-mode\", int(TrimMode::Normal))))\n    , widthEdit (ViewUtil::slider (1, s->cache ().get<int> (\"trim-width\", 10), 200))\n  {\n  }\n\n  void setupProperties ()\n  {\n    ViewTwoColumnGrid& properties = this->self->properties ();\n\n    this->widthEdit.setSingleStep (10);\n    ViewUtil::connect (this->widthEdit,\n                       [this](int w) { this->self->cache ().set (\"trim-width\", w); });\n\n    QButtonGroup& trimModeEdit =\n      ViewUtil::buttonGroup ({QObject::tr (\"Normal\"), QObject::tr (\"Slice\"), QObject::tr (\"Cut\")});\n    ViewUtil::connect (trimModeEdit, int(this->trimMode), [this](int id) {\n      this->trimMode = TrimMode (id);\n      this->self->cache ().set (\"trim-mode\", id);\n      this->widthEdit.setEnabled (this->trimMode != TrimMode::Normal);\n      this->setupToolTip ();\n    });\n    properties.add (trimModeEdit);\n\n    properties.addStacked (QObject::tr (\"Width\"), this->widthEdit);\n  }\n\n  void setupToolTip ()\n  {\n    ViewToolTip toolTip;\n    toolTip.add (ViewInputEvent::MouseLeft, QObject::tr (\"Drag to trim\"));\n    if (this->widthEdit.isEnabled ())\n    {\n      toolTip.add (ViewInputEvent::R, QObject::tr (\"Drag to change width\"));\n    }\n    this->self->state ().setToolTip (&toolTip);\n  }\n\n  ToolResponse runInitialize ()\n  {\n    this->setupProperties ();\n    this->setupToolTip ();\n\n    return ToolResponse::None;\n  }\n\n  ToolResponse runMoveEvent (const ViewPointingEvent& e)\n  {\n    if (this->widthEdit.isEnabled () && this->self->onKeymap ('r') && e.moveEvent ())\n    {\n      this->widthEdit.setValue (this->widthEdit.value () + e.delta ().x);\n    }\n    else if (e.rightButton () && e.modifiers () == Qt::ShiftModifier)\n    {\n      this->widthEdit.setValue (this->widthEdit.value () + e.delta ().x);\n    }\n    return this->points.empty () ? ToolResponse::None : ToolResponse::Redraw;\n  }\n\n  TrimStatus trimMesh (DynamicMesh& mesh, int offset, bool reverse)\n  {\n    assert (this->points.size () == 2);\n\n    const glm::ivec2& p1 = reverse ? this->points[1] : this->points[0];\n    const glm::ivec2& p2 = reverse ? this->points[0] : this->points[1];\n    const float       fOffset = 0.5f * float(offset);\n    const glm::vec2   normOrth = glm::normalize (glm::vec2 (Util::orthogonalRight (p2 - p1)));\n    const glm::ivec2  orth = glm::ivec2 (glm::ceil (normOrth * fOffset));\n    const PrimRay     ray1 = this->self->state ().camera ().ray (p1 + orth);\n    const PrimRay     ray2 = this->self->state ().camera ().ray (p2 + orth);\n\n    ToolTrimMeshBorder border (mesh, ray1, ray2);\n\n    if (ToolTrimMeshSplitMesh::splitMesh (border))\n    {\n      if (border.hasVertices ())\n      {\n        if (ToolTrimMeshAction::trimMesh (border))\n        {\n          return TrimStatus::Trimmed;\n        }\n        else\n        {\n          return TrimStatus::Failed;\n        }\n      }\n      else\n      {\n        return TrimStatus::NotTrimmed;\n      }\n    }\n    else\n    {\n      return TrimStatus::Failed;\n    }\n  }\n\n  TrimStatus trimMesh (DynamicMesh& mesh)\n  {\n    if (this->trimMode == TrimMode::Normal)\n    {\n      return this->trimMesh (mesh, 0.0f, false);\n    }\n    else if (this->trimMode == TrimMode::Slice)\n    {\n      const TrimStatus status = this->trimMesh (mesh, this->widthEdit.value (), false);\n      if (status != TrimStatus::Failed)\n      {\n        switch (this->trimMesh (mesh, this->widthEdit.value (), true))\n        {\n          case TrimStatus::Trimmed:\n            return TrimStatus::Trimmed;\n\n          case TrimStatus::NotTrimmed:\n            return status;\n\n          case TrimStatus::Failed:\n            return TrimStatus::Failed;\n\n          default:\n            DILAY_IMPOSSIBLE\n        }\n      }\n      else\n      {\n        return status;\n      }\n    }\n    else if (this->trimMode == TrimMode::Cut)\n    {\n      DynamicMesh& mesh2 =\n        this->self->state ().scene ().newDynamicMesh (this->self->config (), mesh);\n\n      switch (this->trimMesh (mesh, -this->widthEdit.value (), false))\n      {\n        case TrimStatus::Failed:\n          this->self->state ().scene ().deleteMesh (mesh2);\n          return TrimStatus::Failed;\n\n        case TrimStatus::NotTrimmed:\n          this->self->state ().scene ().deleteMesh (mesh2);\n          return this->trimMesh (mesh, -this->widthEdit.value (), true);\n\n        case TrimStatus::Trimmed:\n          switch (this->trimMesh (mesh2, -this->widthEdit.value (), true))\n          {\n            case TrimStatus::Trimmed:\n              return TrimStatus::Trimmed;\n\n            case TrimStatus::NotTrimmed:\n              this->self->state ().scene ().deleteMesh (mesh2);\n              return TrimStatus::Trimmed;\n\n            case TrimStatus::Failed:\n              this->self->state ().scene ().deleteMesh (mesh2);\n              return TrimStatus::Failed;\n\n            default:\n              DILAY_IMPOSSIBLE\n          }\n        default:\n          DILAY_IMPOSSIBLE\n      }\n    }\n    else\n    {\n      DILAY_IMPOSSIBLE\n    }\n  }\n\n  ToolResponse runReleaseEvent (const ViewPointingEvent& e)\n  {\n    if (e.leftButton () == false)\n    {\n      return ToolResponse::None;\n    }\n    else\n    {\n      DynamicMeshIntersection intersection;\n      if (this->self->intersectsScene (e.position (), intersection) == false)\n      {\n        this->points.push_back (e.position ());\n      }\n\n      if (this->points.size () == 2)\n      {\n        this->self->snapshotDynamicMeshes ();\n\n        TrimStatus status = TrimStatus::NotTrimmed;\n        this->self->state ().scene ().forEachMesh ([&status, this](DynamicMesh& mesh) {\n          if (status != TrimStatus::Failed)\n          {\n            const TrimStatus s = this->trimMesh (mesh);\n            if (s != TrimStatus::NotTrimmed)\n            {\n              status = s;\n            }\n          }\n        });\n\n        switch (status)\n        {\n          case TrimStatus::Trimmed:\n            this->self->state ().scene ().deleteEmptyMeshes ();\n            break;\n\n          case TrimStatus::NotTrimmed:\n            this->self->state ().history ().dropPastSnapshot ();\n            break;\n\n          case TrimStatus::Failed:\n            this->self->state ().undo ();\n            this->self->state ().history ().dropFutureSnapshot ();\n            ViewUtil::error (this->self->state ().mainWindow (),\n                             QObject::tr (\"Could not trim mesh.\"));\n            break;\n        }\n        this->points.clear ();\n      }\n      return ToolResponse::Redraw;\n    }\n  }\n\n  void runPaint (QPainter& painter) const\n  {\n    const QPoint cursorPos (ViewUtil::toQPoint (this->self->cursorPosition ()));\n\n    QPen pen (this->self->config ().get<Color> (\"editor/on-screen-color\").qColor ());\n    pen.setCapStyle (Qt::FlatCap);\n    pen.setWidth (this->trimMode == TrimMode::Normal ? 2 : this->widthEdit.value ());\n\n    painter.setPen (pen);\n\n    if (this->points.empty () == false)\n    {\n      for (unsigned int i = 0; i < this->points.size () - 1; i++)\n      {\n        painter.drawLine (ViewUtil::toQPoint (this->points[i + 0]),\n                          ViewUtil::toQPoint (this->points[i + 1]));\n      }\n      painter.drawLine (ViewUtil::toQPoint (this->points[this->points.size () - 1]), cursorPos);\n    }\n  }\n\n  ToolResponse runCommit ()\n  {\n    this->points.clear ();\n    return ToolResponse::Redraw;\n  }\n};\n\nDELEGATE_TOOL (ToolTrimMesh)\nDELEGATE_TOOL_RUN_MOVE_EVENT (ToolTrimMesh)\nDELEGATE_TOOL_RUN_RELEASE_EVENT (ToolTrimMesh)\nDELEGATE_TOOL_RUN_PAINT (ToolTrimMesh)\nDELEGATE_TOOL_RUN_COMMIT (ToolTrimMesh)\n"
  },
  {
    "path": "lib/src/tool/util/movement.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"camera.hpp\"\n#include \"dimension.hpp\"\n#include \"intersection.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"tool/util/movement.hpp\"\n#include \"view/pointing-event.hpp\"\n\nnamespace\n{\n  enum class MovementPlane\n  {\n    Camera,\n    Primary,\n    Free\n  };\n}\n\nstruct ToolUtilMovement::Impl\n{\n  const Camera& camera;\n  MovementPlane plane;\n  glm::vec3     planeNormal;\n  glm::vec3     previousPosition;\n  glm::vec3     position;\n\n  Impl (const Camera& cam, bool p)\n    : camera (cam)\n    , previousPosition (glm::vec3 (0.0f))\n    , position (glm::vec3 (0.0f))\n  {\n    this->onPrimaryPlane (p);\n  }\n\n  Impl (const Camera& cam, const glm::vec3& n)\n    : camera (cam)\n    , previousPosition (glm::vec3 (0.0f))\n    , position (glm::vec3 (0.0f))\n  {\n    this->onFreePlane (n);\n  }\n\n  void setPlaneNormal ()\n  {\n    if (this->plane == MovementPlane::Camera)\n    {\n      this->planeNormal = this->camera.toEyePoint ();\n    }\n    else if (this->plane == MovementPlane::Primary)\n    {\n      this->planeNormal = DimensionUtil::vector (this->camera.primaryDimension ());\n    }\n  }\n\n  bool onPrimaryPlane () const { return this->plane == MovementPlane::Primary; }\n\n  void onPrimaryPlane (bool yes)\n  {\n    this->plane = yes ? MovementPlane::Primary : MovementPlane::Camera;\n    this->setPlaneNormal ();\n  }\n\n  void onFreePlane (const glm::vec3& n)\n  {\n    this->plane = MovementPlane::Free;\n    this->planeNormal = n;\n  }\n\n  glm::vec3 delta () const { return this->position - this->previousPosition; }\n\n  bool intersects (const glm::ivec2& p, glm::vec3& i)\n  {\n    this->setPlaneNormal ();\n\n    const PrimRay   ray = this->camera.ray (p);\n    const PrimPlane plane (this->position, this->planeNormal);\n    float           t;\n\n    if (IntersectionUtil::intersects (ray, plane, &t))\n    {\n      i = ray.pointAt (t);\n      return true;\n    }\n    return false;\n  }\n\n  bool move (const ViewPointingEvent& e)\n  {\n    glm::vec3 i;\n    if (this->intersects (e.position (), i))\n    {\n      this->previousPosition = this->position;\n      this->position = i;\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  void reset (const glm::vec3& p)\n  {\n    this->previousPosition = p;\n    this->position = p;\n  }\n};\n\nDELEGATE2_BIG3 (ToolUtilMovement, const Camera&, bool)\nDELEGATE2_CONSTRUCTOR (ToolUtilMovement, const Camera&, const glm::vec3&)\nDELEGATE_CONST (bool, ToolUtilMovement, onPrimaryPlane)\nDELEGATE1 (void, ToolUtilMovement, onPrimaryPlane, bool)\nDELEGATE1 (void, ToolUtilMovement, onFreePlane, const glm::vec3&)\nDELEGATE_CONST (glm::vec3, ToolUtilMovement, delta)\nGETTER_CONST (const glm::vec3&, ToolUtilMovement, position)\nDELEGATE1 (bool, ToolUtilMovement, move, const ViewPointingEvent&)\nDELEGATE1 (void, ToolUtilMovement, reset, const glm::vec3&)\n"
  },
  {
    "path": "lib/src/tool/util/movement.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_UTIL_MOVEMENT\n#define DILAY_TOOL_UTIL_MOVEMENT\n\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n\nclass Camera;\nclass ViewPointingEvent;\n\nclass ToolUtilMovement\n{\npublic:\n  DECLARE_BIG3 (ToolUtilMovement, const Camera&, bool)\n  ToolUtilMovement (const Camera&, const glm::vec3&);\n\n  bool onPrimaryPlane () const;\n  void onPrimaryPlane (bool);\n  void onFreePlane (const glm::vec3&);\n\n  glm::vec3        delta () const;\n  const glm::vec3& position () const;\n  bool             move (const ViewPointingEvent&);\n  void             reset (const glm::vec3&);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/util/rotation.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/gtc/constants.hpp>\n#include \"camera.hpp\"\n#include \"tool/util/rotation.hpp\"\n#include \"util.hpp\"\n#include \"view/pointing-event.hpp\"\n\nstruct ToolUtilRotation::Impl\n{\n  const Camera& camera;\n  glm::vec3     origin;\n  glm::vec3     axis;\n  glm::vec2     position;\n  glm::vec2     direction;\n  float         angle;\n\n  Impl (const Camera& cam)\n    : camera (cam)\n  {\n  }\n\n  glm::mat4x4 matrix () const { return Util::rotation (this->origin, this->axis, this->angle); }\n\n  bool rotate (const ViewPointingEvent& e)\n  {\n    const glm::vec2 fPoint = glm::vec2 (e.position ());\n    const float     threshold = 10.0f;\n\n    if (glm::distance (this->position, fPoint) < threshold)\n    {\n      this->direction = glm::vec2 (0.0f);\n      return false;\n    }\n    else if (this->direction == glm::vec2 (0.0f))\n    {\n      this->direction = glm::normalize (fPoint - this->position);\n      return false;\n    }\n    else\n    {\n      const glm::vec2 newDirection = glm::normalize (fPoint - this->position);\n      const float     dot = glm::dot (this->direction, newDirection);\n\n      if (Util::almostEqual (dot, 1.0f))\n      {\n        this->angle = 0.0f;\n      }\n      else if (Util::almostEqual (dot, -1.0f))\n      {\n        this->angle = glm::pi<float> ();\n      }\n      else\n      {\n        this->angle = glm::acos (dot);\n\n        if (Util::cross (this->direction, newDirection) > 0.0f)\n        {\n          this->angle = (2.0f * glm::pi<float> ()) - this->angle;\n        }\n      }\n      this->direction = newDirection;\n      return true;\n    }\n  }\n\n  void reset (const glm::vec3& o)\n  {\n    this->origin = o;\n    this->axis = this->camera.toEyePoint ();\n    this->position = this->camera.fromWorld (o, glm::mat4x4 (1.0f), false);\n    this->direction = glm::vec2 (0.0f);\n  }\n\n  void reset (const glm::vec3& o, const glm::vec3& a)\n  {\n    this->origin = o;\n    this->axis = glm::normalize (a);\n    this->position = this->camera.fromWorld (o, glm::mat4x4 (1.0f), false);\n    this->direction = glm::vec2 (0.0f);\n  }\n};\n\nDELEGATE1_BIG3 (ToolUtilRotation, const Camera&)\nGETTER_CONST (const glm::vec3&, ToolUtilRotation, axis)\nGETTER_CONST (float, ToolUtilRotation, angle)\nDELEGATE_CONST (glm::mat4x4, ToolUtilRotation, matrix)\nDELEGATE1 (bool, ToolUtilRotation, rotate, const ViewPointingEvent&)\nDELEGATE1 (void, ToolUtilRotation, reset, const glm::vec3&)\nDELEGATE2 (void, ToolUtilRotation, reset, const glm::vec3&, const glm::vec3&)\n"
  },
  {
    "path": "lib/src/tool/util/rotation.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_UTIL_ROTATION\n#define DILAY_TOOL_UTIL_ROTATION\n\n#include <functional>\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n\nclass Camera;\nclass ViewPointingEvent;\n\nclass ToolUtilRotation\n{\npublic:\n  DECLARE_BIG3 (ToolUtilRotation, const Camera&)\n\n  const glm::vec3& axis () const;\n  float            angle () const;\n  glm::mat4x4      matrix () const;\n  bool             rotate (const ViewPointingEvent&);\n  void             reset (const glm::vec3&);\n  void             reset (const glm::vec3&, const glm::vec3&);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/util/scaling.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"camera.hpp\"\n#include \"intersection.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"tool/util/scaling.hpp\"\n#include \"util.hpp\"\n#include \"view/pointing-event.hpp\"\n\nstruct ToolUtilScaling::Impl\n{\n  const Camera&              camera;\n  std::unique_ptr<PrimPlane> plane;\n  glm::vec3                  previousPosition;\n  glm::vec3                  position;\n\n  Impl (const Camera& cam)\n    : camera (cam)\n  {\n  }\n\n  float factor (float previousDistance, float distance) const\n  {\n    if (Util::almostEqual (previousDistance, 0.0f))\n    {\n      return 1.0f;\n    }\n    else\n    {\n      return glm::clamp (distance / previousDistance, 0.75f, 1.25f);\n    }\n  }\n\n  float factor () const\n  {\n    assert (this->plane);\n\n    const float pd = glm::distance (this->previousPosition, this->plane->point ());\n    const float d = glm::distance (this->position, this->plane->point ());\n\n    return this->factor (pd, d);\n  }\n\n  float factorRight () const\n  {\n    const glm::vec3  prevDelta = this->previousPosition - this->plane->point ();\n    const glm::vec3  delta = this->position - this->plane->point ();\n    const glm::vec3& right = this->camera.right ();\n\n    return this->factor (glm::dot (right, prevDelta), glm::dot (right, delta));\n  }\n\n  float factorUp () const\n  {\n    const glm::vec3  prevDelta = this->previousPosition - this->plane->point ();\n    const glm::vec3  delta = this->position - this->plane->point ();\n    const glm::vec3& up = this->camera.realUp ();\n\n    return this->factor (glm::dot (up, prevDelta), glm::dot (up, delta));\n  }\n\n  bool intersects (const glm::ivec2& p, glm::vec3& i) const\n  {\n    assert (this->plane);\n\n    const PrimRay ray = this->camera.ray (p);\n    float         t;\n\n    if (IntersectionUtil::intersects (ray, *this->plane, &t))\n    {\n      i = ray.pointAt (t);\n      return true;\n    }\n    return false;\n  }\n\n  bool move (const ViewPointingEvent& e)\n  {\n    glm::vec3 p;\n    if (this->plane && this->intersects (e.position (), p))\n    {\n      this->previousPosition = this->position;\n      this->position = p;\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  void reset (const glm::vec3& origin, const glm::vec3& reference)\n  {\n    this->plane = std::make_unique<PrimPlane> (origin, this->camera.toEyePoint ());\n\n    const PrimRay ray (this->camera.position (),\n                       glm::normalize (reference - this->camera.position ()));\n    float         t;\n\n    if (IntersectionUtil::intersects (ray, *this->plane, &t))\n    {\n      this->previousPosition = ray.pointAt (t);\n      this->position = ray.pointAt (t);\n    }\n    else\n    {\n      this->plane.reset ();\n    }\n  }\n};\n\nDELEGATE1_BIG3 (ToolUtilScaling, const Camera&)\nDELEGATE_CONST (float, ToolUtilScaling, factor)\nDELEGATE_CONST (float, ToolUtilScaling, factorRight)\nDELEGATE_CONST (float, ToolUtilScaling, factorUp)\nDELEGATE1 (bool, ToolUtilScaling, move, const ViewPointingEvent&)\nDELEGATE2 (void, ToolUtilScaling, reset, const glm::vec3&, const glm::vec3&)\n"
  },
  {
    "path": "lib/src/tool/util/scaling.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_UTIL_SCALING\n#define DILAY_TOOL_UTIL_SCALING\n\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n\nclass Camera;\nclass ViewPointingEvent;\n\nclass ToolUtilScaling\n{\npublic:\n  DECLARE_BIG3 (ToolUtilScaling, const Camera&)\n\n  float factor () const;\n  float factorRight () const;\n  float factorUp () const;\n  bool  move (const ViewPointingEvent&);\n  void  reset (const glm::vec3&, const glm::vec3&);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/tool/util/step.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"tool/util/step.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  const glm::vec3 invalidPosition (Util::maxFloat ());\n}\n\nstruct ToolUtilStep::Impl\n{\n  glm::vec3 position;\n  float     stepWidth;\n\n  Impl ()\n    : position (invalidPosition)\n    , stepWidth (0.0f)\n  {\n  }\n\n  void step (const glm::vec3& to, const std::function<bool(const glm::vec3&)>& f)\n  {\n    assert (this->position != invalidPosition);\n    assert (this->stepWidth >= 0.0f);\n\n    do\n    {\n      const glm::vec3 direction = to - this->position;\n      const float     distance = glm::length (direction);\n\n      if (distance < this->stepWidth)\n      {\n        break;\n      }\n      this->position += direction * (this->stepWidth / distance);\n    } while (f (this->position));\n  }\n};\n\nDELEGATE_BIG3 (ToolUtilStep)\nGETTER_CONST (const glm::vec3&, ToolUtilStep, position)\nSETTER (const glm::vec3&, ToolUtilStep, position)\nSETTER (float, ToolUtilStep, stepWidth)\nDELEGATE2 (void, ToolUtilStep, step, const glm::vec3&, const std::function<bool(const glm::vec3&)>&)\n"
  },
  {
    "path": "lib/src/tool/util/step.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL_UTIL_STEP\n#define DILAY_TOOL_UTIL_STEP\n\n#include <functional>\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n\nclass ToolUtilStep\n{\npublic:\n  DECLARE_BIG3 (ToolUtilStep)\n\n  const glm::vec3& position () const;\n  void             position (const glm::vec3&);\n  void             stepWidth (float);\n  void             step (const glm::vec3&, const std::function<bool(const glm::vec3&)>&);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/tool.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include <QPushButton>\n#include <array>\n#include \"cache.hpp\"\n#include \"camera.hpp\"\n#include \"config.hpp\"\n#include \"dimension.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"history.hpp\"\n#include \"intersection.hpp\"\n#include \"mesh.hpp\"\n#include \"mirror.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"state.hpp\"\n#include \"tool.hpp\"\n#include \"tool/util/movement.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/key-event.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/tool-pane.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct Tool::Impl\n{\n  Tool*                self;\n  State&               state;\n  CacheProxy           _cache;\n  Maybe<Mirror>        _mirror;\n  QCheckBox*           mirrorCheckBox;\n  QPushButton*         mirrorSyncButton;\n  glm::ivec2           prevPointingEventPosition;\n  std::array<bool, 26> keymap;\n\n  Impl (Tool* s, State& st, const char* cacheKey)\n    : self (s)\n    , state (st)\n    , _cache (this->cache (cacheKey))\n    , mirrorCheckBox (nullptr)\n    , mirrorSyncButton (nullptr)\n  {\n    this->keymap.fill (false);\n  }\n\n  ToolResponse initialize ()\n  {\n    this->fromConfig ();\n#ifndef NDEBUG\n    const ToolResponse response = this->self->runInitialize ();\n    assert (bool(this->_mirror) == false || (this->mirrorCheckBox && this->mirrorSyncButton));\n    return response;\n#else\n    return this->self->runInitialize ();\n#endif\n  }\n\n  void render () const\n  {\n    this->self->runRender ();\n    if (this->mirrorEnabled () && this->config ().get<bool> (\"editor/tool/sculpt/mirror/render\"))\n    {\n      this->_mirror->render (this->state.camera ());\n    }\n  }\n\n  void paint (QPainter& painter) const { this->self->runPaint (painter); }\n\n  void keyEvent (const ViewKeyEvent& e)\n  {\n    const int index = int(e.key ()) - int(Qt::Key_A);\n    if (index >= 0 && size_t (index) < this->keymap.size ())\n    {\n      this->keymap[index] = e.pressEvent ();\n    }\n  }\n\n  ToolResponse pointingEvent (const ViewPointingEvent& e)\n  {\n    if (e.pressEvent ())\n    {\n      this->prevPointingEventPosition = e.position ();\n    }\n\n    const ViewPointingEvent eWithDelta (e, this->prevPointingEventPosition);\n    ToolResponse            response = this->self->runPointingEvent (eWithDelta);\n\n    if (e.releaseEvent ())\n    {\n      this->state.scene ().sanitizeMeshes ();\n    }\n    this->prevPointingEventPosition = e.position ();\n    return response;\n  }\n\n  ToolResponse cursorUpdate (const glm::ivec2& pos) { return this->self->runCursorUpdate (pos); }\n\n  ToolResponse commit () { return this->self->runCommit (); }\n\n  void fromConfig ()\n  {\n    if (this->_mirror)\n    {\n      this->_mirror->fromConfig (this->config ());\n    }\n    this->self->runFromConfig ();\n  }\n\n  void updateGlWidget () { this->state.mainWindow ().glWidget ().update (); }\n\n  ViewTwoColumnGrid& properties () const\n  {\n    return this->state.mainWindow ().toolPane ().properties ();\n  }\n\n  Config& config () const { return this->state.config (); }\n\n  CacheProxy& cache () { return this->_cache; }\n\n  CacheProxy cache (const char* key) const\n  {\n    return CacheProxy (this->state.cache (), \"editor/tool/\" + std::string (key) + \"/\");\n  }\n\n  glm::ivec2 cursorPosition () { return this->state.mainWindow ().glWidget ().cursorPosition (); }\n\n  void snapshotAll () { this->state.history ().snapshotAll (this->state.scene ()); }\n\n  void snapshotDynamicMeshes ()\n  {\n    this->state.history ().snapshotDynamicMeshes (this->state.scene ());\n  }\n\n  void snapshotSketchMeshes ()\n  {\n    this->state.history ().snapshotSketchMeshes (this->state.scene ());\n  }\n\n  bool intersectsRecentDynamicMesh (const PrimRay& ray, Intersection& intersection) const\n  {\n    assert (this->state.history ().hasRecentDynamicMesh ());\n\n    this->state.history ().forEachRecentDynamicMesh (\n      [&ray, &intersection](const DynamicMesh& mesh) { mesh.intersects (ray, intersection); });\n    return intersection.isIntersection ();\n  }\n\n  bool intersectsRecentDynamicMesh (const glm::ivec2& pos, Intersection& intersection) const\n  {\n    return this->intersectsRecentDynamicMesh (this->state.camera ().ray (pos), intersection);\n  }\n\n  void supportsMirror ()\n  {\n    assert (bool(this->_mirror) == false);\n    this->_mirror = Maybe<Mirror>::make (this->config (), Dimension::X);\n    this->mirrorDefaultPosition ();\n  }\n\n  bool mirrorEnabled () const\n  {\n    return this->_mirror && this->state.cache ().get (\"editor/tool/mirror\", true);\n  }\n\n  void mirrorPosition (const glm::vec3& p)\n  {\n    assert (this->_mirror);\n    this->_mirror->position (p);\n  }\n\n  void mirrorDefaultPosition ()\n  {\n    switch (this->state.mainWindow ().toolPane ().selection ())\n    {\n      case ViewToolPaneSelection::Sculpt:\n        this->mirrorPosition (glm::vec3 (0.0f));\n        break;\n      case ViewToolPaneSelection::Sketch:\n        if (this->state.scene ().numSketchMeshes () == 1)\n        {\n          this->state.scene ().forEachMesh ([this](const SketchMesh& mesh) {\n            this->mirrorPosition (mesh.tree ().root ().data ().center ());\n          });\n        }\n        else\n        {\n          this->mirrorPosition (glm::vec3 (0.0f));\n        }\n        break;\n    }\n  }\n\n  const Mirror& mirror () const\n  {\n    assert (this->mirrorEnabled ());\n    return *this->_mirror;\n  }\n\n  const Dimension* mirrorDimension () const\n  {\n    const static Dimension d = Dimension::X;\n\n    return this->mirrorEnabled () ? &d : nullptr;\n  }\n\n  void mirrorDynamicMeshes ()\n  {\n    assert (this->mirrorEnabled ());\n\n    this->snapshotDynamicMeshes ();\n    this->state.scene ().forEachMesh ([this](DynamicMesh& mesh) {\n      if (mesh.mirrorPositive (this->mirror ().plane ()) == false)\n      {\n        ViewUtil::error (this->state.mainWindow (), QObject::tr (\"Could not mirror mesh.\"));\n      }\n      mesh.bufferData ();\n    });\n  }\n\n  void mirrorSketchMeshes ()\n  {\n    assert (this->mirrorEnabled ());\n\n    this->snapshotSketchMeshes ();\n    this->state.scene ().forEachMesh (\n      [this](SketchMesh& mesh) { mesh.mirrorPositive (*this->mirrorDimension ()); });\n  }\n\n  void addMirrorProperties ()\n  {\n    assert (this->_mirror);\n\n    this->mirrorCheckBox = &ViewUtil::checkBox (QObject::tr (\"Mirror\"), this->mirrorEnabled ());\n    ViewUtil::connect (*this->mirrorCheckBox, [this](bool m) {\n      this->state.cache ().set (\"editor/tool/mirror\", m);\n      this->mirrorSyncButton->setEnabled (m);\n      this->updateGlWidget ();\n    });\n\n    this->mirrorSyncButton = &ViewUtil::pushButton (QObject::tr (\"Sync\"));\n    ViewUtil::connect (*this->mirrorSyncButton, [this]() {\n      switch (this->state.mainWindow ().toolPane ().selection ())\n      {\n        case ViewToolPaneSelection::Sculpt:\n          this->mirrorDynamicMeshes ();\n          break;\n        case ViewToolPaneSelection::Sketch:\n          this->mirrorSketchMeshes ();\n          break;\n      }\n      this->updateGlWidget ();\n    });\n    this->mirrorSyncButton->setEnabled (this->mirrorEnabled ());\n\n    this->properties ().add (*this->mirrorCheckBox, *this->mirrorSyncButton);\n  }\n\n  void enableMirrorProperties (bool state)\n  {\n    assert (this->mirrorCheckBox);\n    assert (this->mirrorSyncButton);\n\n    this->mirrorCheckBox->setEnabled (state);\n    this->mirrorSyncButton->setEnabled (state);\n  }\n\n  void addMoveOnPrimaryPlaneProperties (ToolUtilMovement& movement)\n  {\n    const bool init =\n      this->cache ().get<bool> (\"move-on-primary-plane\", movement.onPrimaryPlane ());\n    movement.onPrimaryPlane (init);\n\n    QCheckBox& edit = ViewUtil::checkBox (QObject::tr (\"Move on primary plane\"), init);\n    ViewUtil::connect (edit, [this, &movement](bool p) {\n      movement.onPrimaryPlane (p);\n      this->cache ().set (\"move-on-primary-plane\", p);\n    });\n    this->properties ().add (edit);\n  }\n\n  bool onKeymap (char c) const\n  {\n    const int index = int(c) - int('a');\n    if (index >= 0 && size_t (index) < this->keymap.size ())\n    {\n      return this->keymap[index];\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  template <typename T, typename... Ts>\n  bool intersectsScene (const PrimRay& ray, T& intersection, Ts... args)\n  {\n    return this->state.scene ().intersects (ray, intersection, std::forward<Ts> (args)...);\n  }\n\n  template <typename T, typename... Ts>\n  bool intersectsScene (const glm::ivec2& pos, T& intersection, Ts... args)\n  {\n    return this->intersectsScene (this->state.camera ().ray (pos), intersection,\n                                  std::forward<Ts> (args)...);\n  }\n\n  template <typename T, typename... Ts>\n  bool intersectsScene (const ViewPointingEvent& e, T& intersection, Ts... args)\n  {\n    return this->intersectsScene (e.position (), intersection, std::forward<Ts> (args)...);\n  }\n\n  ToolResponse runPointingEvent (const ViewPointingEvent& e)\n  {\n    if (e.pressEvent ())\n    {\n      return this->self->runPressEvent (e);\n    }\n    else if (e.moveEvent ())\n    {\n      return this->self->runMoveEvent (e);\n    }\n    else if (e.releaseEvent ())\n    {\n      return this->self->runReleaseEvent (e);\n    }\n    return ToolResponse::None;\n  }\n};\n\nDELEGATE2_BIG3_SELF (Tool, State&, const char*)\nDELEGATE (ToolResponse, Tool, initialize)\nDELEGATE_CONST (void, Tool, render)\nDELEGATE1_CONST (void, Tool, paint, QPainter&)\nDELEGATE1 (void, Tool, keyEvent, const ViewKeyEvent&)\nDELEGATE1 (ToolResponse, Tool, pointingEvent, const ViewPointingEvent&)\nDELEGATE1 (ToolResponse, Tool, cursorUpdate, const glm::ivec2&)\nDELEGATE (ToolResponse, Tool, commit)\nDELEGATE (void, Tool, fromConfig)\nGETTER_CONST (State&, Tool, state)\nDELEGATE (void, Tool, updateGlWidget)\nDELEGATE_CONST (ViewTwoColumnGrid&, Tool, properties)\nDELEGATE_CONST (Config&, Tool, config)\nDELEGATE (CacheProxy&, Tool, cache)\nDELEGATE1_CONST (CacheProxy, Tool, cache, const char*)\nDELEGATE_CONST (glm::ivec2, Tool, cursorPosition)\nDELEGATE (void, Tool, snapshotAll)\nDELEGATE (void, Tool, snapshotDynamicMeshes)\nDELEGATE (void, Tool, snapshotSketchMeshes)\nDELEGATE2_CONST (bool, Tool, intersectsRecentDynamicMesh, const PrimRay&, Intersection&)\nDELEGATE2_CONST (bool, Tool, intersectsRecentDynamicMesh, const glm::ivec2&, Intersection&)\nDELEGATE (void, Tool, supportsMirror)\nDELEGATE_CONST (bool, Tool, mirrorEnabled)\nDELEGATE1 (void, Tool, mirrorPosition, const glm::vec3&)\nDELEGATE (void, Tool, mirrorDefaultPosition)\nDELEGATE_CONST (const Mirror&, Tool, mirror)\nDELEGATE_CONST (const Dimension*, Tool, mirrorDimension)\nDELEGATE (void, Tool, addMirrorProperties)\nDELEGATE1 (void, Tool, enableMirrorProperties, bool)\nDELEGATE1 (void, Tool, addMoveOnPrimaryPlaneProperties, ToolUtilMovement&)\nDELEGATE1_CONST (bool, Tool, onKeymap, char)\nDELEGATE1 (ToolResponse, Tool, runPointingEvent, const ViewPointingEvent&)\n\ntemplate <typename T, typename... Ts>\nbool Tool::intersectsScene (const PrimRay& ray, T& intersection, Ts... args)\n{\n  return this->impl->intersectsScene (ray, intersection, std::forward<Ts> (args)...);\n}\n\ntemplate <typename T, typename... Ts>\nbool Tool::intersectsScene (const glm::ivec2& pos, T& intersection, Ts... args)\n{\n  return this->impl->intersectsScene (pos, intersection, std::forward<Ts> (args)...);\n}\n\ntemplate <typename T, typename... Ts>\nbool Tool::intersectsScene (const ViewPointingEvent& e, T& intersection, Ts... args)\n{\n  return this->impl->intersectsScene (e, intersection, std::forward<Ts> (args)...);\n}\n\n#define TOOL_INTERSECTS_SCENE(...)                                      \\\n  template bool Tool::intersectsScene (const PrimRay&, __VA_ARGS__);    \\\n  template bool Tool::intersectsScene (const glm::ivec2&, __VA_ARGS__); \\\n  template bool Tool::intersectsScene (const ViewPointingEvent&, __VA_ARGS__);\n\nTOOL_INTERSECTS_SCENE (DynamicMeshIntersection&)\nTOOL_INTERSECTS_SCENE (SketchNodeIntersection&)\nTOOL_INTERSECTS_SCENE (SketchNodeIntersection&, const SketchNode*)\nTOOL_INTERSECTS_SCENE (SketchBoneIntersection&)\nTOOL_INTERSECTS_SCENE (SketchMeshIntersection&)\nTOOL_INTERSECTS_SCENE (SketchMeshIntersection&, unsigned int)\nTOOL_INTERSECTS_SCENE (SketchPathIntersection&)\nTOOL_INTERSECTS_SCENE (Intersection&)\n\n#undef TOOL_INTERSECTS_SCENE\n"
  },
  {
    "path": "lib/src/tool.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOL\n#define DILAY_TOOL\n\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n#include \"sketch/fwd.hpp\"\n#include \"tool/key.hpp\"\n\nclass CacheProxy;\nclass Config;\nenum class Dimension;\nclass Intersection;\nclass Mirror;\nclass PrimRay;\nclass QPainter;\nclass QWidget;\nclass State;\nclass ToolUtilMovement;\nclass ViewKeyEvent;\nclass ViewPointingEvent;\nclass ViewToolTip;\nclass ViewTwoColumnGrid;\n\nenum class ToolResponse\n{\n  None,\n  Terminate,\n  Redraw\n};\n\nclass Tool\n{\npublic:\n  DECLARE_BIG3_VIRTUAL (Tool, State&, const char*)\n\n  virtual ToolKey getKey () const = 0;\n\n  ToolResponse initialize ();\n  void         render () const;\n  void         paint (QPainter&) const;\n  void         keyEvent (const ViewKeyEvent&);\n  ToolResponse pointingEvent (const ViewPointingEvent&);\n  ToolResponse cursorUpdate (const glm::ivec2&);\n  ToolResponse commit ();\n  void         fromConfig ();\n\nprotected:\n  State&             state () const;\n  void               updateGlWidget ();\n  ViewTwoColumnGrid& properties () const;\n  Config&            config () const;\n  CacheProxy&        cache ();\n  CacheProxy         cache (const char*) const;\n  glm::ivec2         cursorPosition () const;\n  void               snapshotAll ();\n  void               snapshotDynamicMeshes ();\n  void               snapshotSketchMeshes ();\n  bool               intersectsRecentDynamicMesh (const PrimRay&, Intersection&) const;\n  bool               intersectsRecentDynamicMesh (const glm::ivec2&, Intersection&) const;\n  void               supportsMirror ();\n  bool               mirrorEnabled () const;\n  void               mirrorPosition (const glm::vec3&);\n  void               mirrorDefaultPosition ();\n  const Mirror&      mirror () const;\n  const Dimension*   mirrorDimension () const;\n  void               addMirrorProperties ();\n  void               enableMirrorProperties (bool = true);\n  void               addMoveOnPrimaryPlaneProperties (ToolUtilMovement&);\n  bool               onKeymap (char) const;\n\n  template <typename T, typename... Ts> bool intersectsScene (const PrimRay&, T&, Ts...);\n  template <typename T, typename... Ts> bool intersectsScene (const glm::ivec2&, T&, Ts...);\n  template <typename T, typename... Ts> bool intersectsScene (const ViewPointingEvent&, T&, Ts...);\n\nprivate:\n  IMPLEMENTATION\n\n  virtual ToolResponse runInitialize () = 0;\n\n  virtual void runRender () const {}\n\n  virtual void runPaint (QPainter&) const {}\n\n  virtual ToolResponse runPointingEvent (const ViewPointingEvent&);\n\n  virtual ToolResponse runPressEvent (const ViewPointingEvent&) { return ToolResponse::None; }\n\n  virtual ToolResponse runMoveEvent (const ViewPointingEvent&) { return ToolResponse::None; }\n\n  virtual ToolResponse runReleaseEvent (const ViewPointingEvent&) { return ToolResponse::None; }\n\n  virtual ToolResponse runCursorUpdate (const glm::ivec2&) { return ToolResponse::None; }\n\n  virtual ToolResponse runCommit () { return ToolResponse::None; }\n\n  virtual void runFromConfig () {}\n};\n\n#define DECLARE_TOOL(keyName, otherMethods)              \\\n  class Tool##keyName : public Tool                      \\\n  {                                                      \\\n  public:                                                \\\n    DECLARE_BIG2 (Tool##keyName, State&)                 \\\n                                                         \\\n    ToolKey getKey () const { return ToolKey::keyName; } \\\n                                                         \\\n  private:                                               \\\n    IMPLEMENTATION                                       \\\n    ToolResponse runInitialize ();                       \\\n    otherMethods                                         \\\n  };\n\n#define DECLARE_TOOL_RUN_RENDER void runRender () const;\n#define DECLARE_TOOL_RUN_PAINT void runPaint (QPainter&) const;\n#define DECLARE_TOOL_RUN_POINTING_EVENT ToolResponse runPointingEvent (const ViewPointingEvent&);\n#define DECLARE_TOOL_RUN_PRESS_EVENT ToolResponse runPressEvent (const ViewPointingEvent&);\n#define DECLARE_TOOL_RUN_MOVE_EVENT ToolResponse runMoveEvent (const ViewPointingEvent&);\n#define DECLARE_TOOL_RUN_RELEASE_EVENT ToolResponse runReleaseEvent (const ViewPointingEvent&);\n#define DECLARE_TOOL_RUN_CURSOR_UPDATE ToolResponse runCursorUpdate (const glm::ivec2&);\n#define DECLARE_TOOL_RUN_COMMIT ToolResponse runCommit ();\n#define DECLARE_TOOL_RUN_FROM_CONFIG void runFromConfig ();\n\n#define DELEGATE_TOOL(name)                                        \\\n  DELEGATE_BIG2_BASE (name, (State & s), (this), Tool, (s, #name)) \\\n  DELEGATE (ToolResponse, name, runInitialize)\n\n#define DELEGATE_TOOL_RUN_RENDER(n) DELEGATE_CONST (void, n, runRender)\n#define DELEGATE_TOOL_RUN_PAINT(n) DELEGATE1_CONST (void, n, runPaint, QPainter&)\n#define DELEGATE_TOOL_RUN_POINTING_EVENT(n) \\\n  DELEGATE1 (ToolResponse, n, runPointingEvent, const ViewPointingEvent&)\n#define DELEGATE_TOOL_RUN_PRESS_EVENT(n) \\\n  DELEGATE1 (ToolResponse, n, runPressEvent, const ViewPointingEvent&)\n#define DELEGATE_TOOL_RUN_MOVE_EVENT(n) \\\n  DELEGATE1 (ToolResponse, n, runMoveEvent, const ViewPointingEvent&)\n#define DELEGATE_TOOL_RUN_RELEASE_EVENT(n) \\\n  DELEGATE1 (ToolResponse, n, runReleaseEvent, const ViewPointingEvent&)\n#define DELEGATE_TOOL_RUN_CURSOR_UPDATE(n) \\\n  DELEGATE1 (ToolResponse, n, runCursorUpdate, const glm::ivec2&)\n#define DELEGATE_TOOL_RUN_COMMIT(n) DELEGATE (ToolResponse, n, runCommit)\n#define DELEGATE_TOOL_RUN_FROM_CONFIG(n) DELEGATE (void, n, runFromConfig)\n\n#endif\n"
  },
  {
    "path": "lib/src/tools.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TOOLS\n#define DILAY_TOOLS\n\n#include \"tool.hpp\"\n#include \"tool/move-camera.hpp\"\n#include \"tool/sculpt.hpp\"\n\nDECLARE_TOOL (TransformMesh, DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_PRESS_EVENT\n                               DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_COMMIT)\n\nDECLARE_TOOL (DeleteMesh, DECLARE_TOOL_RUN_RELEASE_EVENT)\n\nDECLARE_TOOL (NewMesh, DECLARE_TOOL_RUN_RENDER DECLARE_TOOL_RUN_COMMIT)\n\nDECLARE_TOOL_SCULPT (SculptDraw)\nDECLARE_TOOL_SCULPT (SculptGrab)\nDECLARE_TOOL_SCULPT (SculptSmooth)\nDECLARE_TOOL_SCULPT (SculptFlatten)\nDECLARE_TOOL_SCULPT (SculptCrease)\nDECLARE_TOOL_SCULPT (SculptPinch)\nDECLARE_TOOL_SCULPT (SculptReduce)\n\nDECLARE_TOOL (EditSketch, DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_PRESS_EVENT\n                            DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_COMMIT)\n\nDECLARE_TOOL (DeleteSketch, DECLARE_TOOL_RUN_RELEASE_EVENT)\n\nDECLARE_TOOL (ConvertSketch, DECLARE_TOOL_RUN_RELEASE_EVENT)\n\nDECLARE_TOOL (SketchSpheres,\n              DECLARE_TOOL_RUN_RENDER DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_PRESS_EVENT\n                DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_CURSOR_UPDATE\n                  DECLARE_TOOL_RUN_COMMIT DECLARE_TOOL_RUN_FROM_CONFIG)\n\nDECLARE_TOOL (TrimMesh, DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_RELEASE_EVENT\n                          DECLARE_TOOL_RUN_PAINT DECLARE_TOOL_RUN_COMMIT)\n\nDECLARE_TOOL (Remesh,\n              DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_PRESS_EVENT\n                DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_PAINT DECLARE_TOOL_RUN_COMMIT)\n\n#endif\n"
  },
  {
    "path": "lib/src/tree.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TREE\n#define DILAY_TREE\n\n#include <list>\n#include \"maybe.hpp\"\n#include \"util.hpp\"\n\ntemplate <typename T> class TreeNode\n{\npublic:\n  TreeNode (const T& d, TreeNode* p = nullptr)\n    : _data (d)\n    , _parent (p)\n  {\n  }\n\n  TreeNode (T&& d, TreeNode* p = nullptr)\n    : _data (std::move (d))\n    , _parent (p)\n  {\n  }\n\n  TreeNode (const TreeNode& o)\n    : _data (o._data)\n    , _parent (nullptr)\n    , _children (o._children)\n  {\n    this->forEachChild ([this](TreeNode& c) { c._parent = this; });\n  }\n\n  template <typename... Args> static TreeNode make (Args&&... args)\n  {\n    return TreeNode (T (std::forward<Args> (args)...));\n  }\n\n  T& data () { return this->_data; }\n\n  const T& data () const { return this->_data; }\n\n  void data (const T& d) { this->_data = d; }\n\n  TreeNode* parent () const { return this->_parent; }\n\n  template <typename... Args> TreeNode& emplaceChild (Args&&... args)\n  {\n    this->_children.emplace_back (make (std::forward<Args> (args)...));\n    this->_children.back ()._parent = this;\n\n    return this->_children.back ();\n  }\n\n  TreeNode& addChild (const TreeNode& node)\n  {\n    this->_children.emplace_back (node);\n    this->_children.back ()._parent = this;\n\n    return this->_children.back ();\n  }\n\n  void deleteChild (TreeNode& child)\n  {\n    for (auto it = this->_children.begin (); it != this->_children.end (); ++it)\n    {\n      if (&*it == &child)\n      {\n        this->_children.erase (it);\n        return;\n      }\n    }\n    DILAY_IMPOSSIBLE\n  }\n\n  void forEachChild (const std::function<void(TreeNode&)>& f)\n  {\n    for (TreeNode& c : this->_children)\n    {\n      f (c);\n    }\n  }\n\n  void forEachConstChild (const std::function<void(const TreeNode&)>& f) const\n  {\n    for (const TreeNode& c : this->_children)\n    {\n      f (c);\n    }\n  }\n\n  void forEachNode (const std::function<void(TreeNode&)>& f)\n  {\n    f (*this);\n\n    this->forEachChild ([&f](TreeNode& c) { c.forEachNode (f); });\n  }\n\n  void forEachConstNode (const std::function<void(const TreeNode&)>& f) const\n  {\n    f (*this);\n\n    this->forEachConstChild ([&f](const TreeNode& c) { c.forEachConstNode (f); });\n  }\n\n  TreeNode& lastChild ()\n  {\n    assert (this->numChildren () > 0);\n    return this->_children.back ();\n  }\n\n  const TreeNode& lastChild () const\n  {\n    assert (this->numChildren () > 0);\n    return this->_children.back ();\n  }\n\n  unsigned int numChildren () const { return this->_children.size (); }\n\n  unsigned int numNodes () const\n  {\n    unsigned int n = 0;\n    this->forEachConstNode ([&n](const TreeNode<T>&) { n++; });\n    return n;\n  }\n\n  void deleteChildIf (const std::function<bool(const TreeNode&)>& f)\n  {\n    for (auto it = this->_children.begin (); it != this->_children.end ();)\n    {\n      if (f (*it))\n      {\n        it = this->_children.erase (it);\n      }\n      else\n      {\n        ++it;\n      }\n    }\n  }\n\nprivate:\n  T                   _data;\n  TreeNode*           _parent;\n  std::list<TreeNode> _children;\n};\n\ntemplate <typename T> class Tree\n{\npublic:\n  bool hasRoot () const { return bool(this->_root); }\n\n  TreeNode<T>& root ()\n  {\n    assert (this->hasRoot ());\n    return *this->_root;\n  }\n\n  const TreeNode<T>& root () const\n  {\n    assert (this->hasRoot ());\n    return *this->_root;\n  }\n\n  template <typename... Args> TreeNode<T>& emplaceRoot (Args&&... args)\n  {\n    this->_root = Maybe<TreeNode<T>>::make (TreeNode<T>::make (std::forward<Args> (args)...));\n    return this->root ();\n  }\n\n  void reset () { this->_root.reset (); }\n\n  void rebalance (TreeNode<T>& node)\n  {\n    const std::function<void(const TreeNode<T>&, TreeNode<T>&)> go = [&go](const auto& child,\n                                                                           auto& rebalancedChild) {\n      if (child.parent ())\n      {\n        const auto& parent = *child.parent ();\n        auto&       rebalancedParent = rebalancedChild.emplaceChild (parent.data ());\n\n        parent.forEachConstChild ([&rebalancedParent, &child](const auto& c) {\n          if (&c != &child)\n          {\n            rebalancedParent.addChild (c);\n          }\n        });\n        go (parent, rebalancedParent);\n      }\n    };\n\n    TreeNode<T>& newRoot (node);\n    go (node, newRoot);\n    this->_root = std::move (newRoot);\n  }\n\n  Tree<T> split (TreeNode<T>& node)\n  {\n    Tree<T> tree;\n    tree._root = node;\n\n    if (node.parent ())\n    {\n      node.parent ()->deleteChild (node);\n    }\n    else if (&node == this->_root.get ())\n    {\n      this->reset ();\n    }\n    return tree;\n  }\n\nprivate:\n  Maybe<TreeNode<T>> _root;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/util.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <fstream>\n#include <glm/glm.hpp>\n#include <glm/gtc/epsilon.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <vector>\n#include \"util.hpp\"\n\nnamespace\n{\n  template <typename T> bool colinearUnitT (const T& v1, const T& v2)\n  {\n    return Util::almostEqual (glm::abs (glm::dot (v1, v2)), 1.0f);\n  }\n\n  template <typename T> bool colinearT (const T& v1, const T& v2)\n  {\n    return colinearUnitT<T> (glm::normalize (v1), glm::normalize (v2));\n  }\n}\n\nglm::vec3 Util::midpoint (const glm::vec3& a, const glm::vec3& b)\n{\n  return (a + b) * (glm::vec3 (0.5f));\n}\n\nglm::vec3 Util::transformPosition (const glm::mat4x4& m, const glm::vec3& v)\n{\n  return glm::vec3 (m * glm::vec4 (v, 1.0f));\n}\n\nglm::vec3 Util::transformDirection (const glm::mat4x4& m, const glm::vec3& v)\n{\n  return glm::vec3 (m * glm::vec4 (v, 0.0f));\n}\n\nglm::vec3 Util::orthogonal (const glm::vec3& v)\n{\n  return glm::abs (v.x) > glm::abs (v.z) ? glm::vec3 (-v.y, v.x, 0.0f)\n                                         : glm::vec3 (0.0f, -v.z, v.y);\n}\n\nglm::ivec2 Util::orthogonalRight (const glm::ivec2& v) { return glm::ivec2 (v.y, -v.x); }\n\nglm::mat4x4 Util::rotation (const glm::vec3& origin, const glm::vec3& axis, float angle)\n{\n  const glm::mat4x4 translate = glm::translate (glm::mat4x4 (1.0f), origin);\n  const glm::mat4x4 rotate = glm::rotate (translate, angle, axis);\n  return glm::translate (rotate, -origin);\n}\n\nbool Util::colinear (const glm::vec2& v1, const glm::vec2& v2)\n{\n  return colinearT<glm::vec2> (v1, v2);\n}\n\nbool Util::colinear (const glm::vec3& v1, const glm::vec3& v2)\n{\n  return colinearT<glm::vec3> (v1, v2);\n}\n\nbool Util::colinearUnit (const glm::vec2& v1, const glm::vec2& v2)\n{\n  return colinearUnitT<glm::vec2> (v1, v2);\n}\n\nbool Util::colinearUnit (const glm::vec3& v1, const glm::vec3& v2)\n{\n  return colinearUnitT<glm::vec3> (v1, v2);\n}\n\nfloat Util::smoothStep (const glm::vec3& v, const glm::vec3& center, float innerRadius,\n                        float radius)\n{\n  assert (innerRadius <= radius);\n\n  const float d = glm::distance (v, center);\n\n  if (radius - innerRadius < Util::epsilon ())\n  {\n    return d > radius ? 0.0f : 1.0f;\n  }\n  else\n  {\n    const float x = glm::clamp ((radius - d) / (radius - innerRadius), 0.0f, 1.0f);\n    return x * x * x * (x * (x * 6.0f - 15.0f) + 10.0f);\n  }\n}\n\nfloat Util::linearStep (const glm::vec3& v, const glm::vec3& center, float innerRadius,\n                        float radius)\n{\n  assert (innerRadius <= radius);\n\n  const float d = glm::distance (v, center);\n\n  if (radius - innerRadius < Util::epsilon ())\n  {\n    return d > radius ? 0.0f : 1.0f;\n  }\n  else\n  {\n    return glm::clamp ((radius - d) / (radius - innerRadius), 0.0f, 1.0f);\n  }\n}\n\nfloat Util::cross (const glm::vec2& v1, const glm::vec2& v2)\n{\n  return (v1.x * v2.y) - (v1.y * v2.x);\n}\n\nstd::string Util::readFile (const std::string& filePath)\n{\n  std::string   content;\n  std::ifstream stream (filePath, std::ios::in);\n  if (stream.is_open ())\n  {\n    std::string line (\"\");\n    while (getline (stream, line))\n      content += \"\\n\" + line;\n    stream.close ();\n  }\n  return content;\n}\n\nunsigned int Util::solveQuadraticEq (float a, float b, float c, float& s1, float& s2)\n{\n  const float radicand = (b * b) - (4.0f * a * c);\n\n  if (radicand < Util::epsilon ())\n    return 0;\n\n  const float root = glm::sqrt (radicand);\n\n  if (b < -Util::epsilon ())\n  {\n    s1 = (-b + root) / (2.0f * a);\n    s2 = (2.0f * c) / (-b + root);\n    return 2;\n  }\n  else if (b > Util::epsilon ())\n  {\n    s1 = (-b - root) / (2.0f * a);\n    s2 = (2.0f * c) / (-b - root);\n    return 2;\n  }\n  else\n  {\n    s1 = root / (2.0f * a);\n    return 1;\n  }\n}\n\nunsigned int Util::solveCubicEq (float a, float b, float c, float d, float& s1, float& s2,\n                                 float& s3)\n{\n  return Util::solveCubicEq (b / a, c / a, d / a, s1, s2, s3);\n}\n\nunsigned int Util::solveCubicEq (float a, float b, float c, float& s1, float& s2, float& s3)\n{\n  const float q = ((a * a) - (3.0f * b)) / 9.0f;\n  const float r = ((2.0f * a * a * a) - (9.0f * a * b) + (27.0f * c)) / 54.0f;\n  const float w = (r * r) - (q * q * q);\n  const float s = a / 3.0f;\n\n  if (w < 0.0f)\n  {\n    const float theta = glm::acos (r / glm::sqrt (q * q * q));\n    const float f = -2.0f * glm::sqrt (q);\n\n    s1 = (f * glm::cos (theta / 3.0f)) - s;\n    s2 = (f * glm::cos ((theta + (2.0f * glm::pi<float> ())) / 3.0f)) - s;\n    s3 = (f * glm::cos ((theta - (2.0f * glm::pi<float> ())) / 3.0f)) - s;\n    return 3;\n  }\n  else\n  {\n    const float x = -glm::sign (r) * glm::pow (glm::abs (r) + glm::sqrt (w), 1.0f / 3.0f);\n    const float y = Util::almostEqual (x, 0.0f) ? 0.0f : q / x;\n\n    s1 = x + y - s;\n    return 1;\n  }\n}\n\nbool Util::isNaN (float v) { return glm::isnan (v); }\n\nbool Util::isNaN (const glm::vec3& v) { return glm::any (glm::isnan (v)); }\n\nbool Util::isNotNull (const glm::vec3& v)\n{\n  const bool bx = Util::almostEqual (v.x, 0.0f) == false;\n  const bool by = Util::almostEqual (v.y, 0.0f) == false;\n  const bool bz = Util::almostEqual (v.z, 0.0f) == false;\n\n  return bx || by || bz;\n}\n\nbool Util::almostEqual (float a, float b) { return glm::epsilonEqual (a, b, Util::epsilon ()); }\n\nbool Util::fromString (const std::string& string, int& value)\n{\n  try\n  {\n    value = std::stoi (string);\n    return true;\n  }\n  catch (const std::invalid_argument&)\n  {\n    return false;\n  }\n  catch (const std::out_of_range&)\n  {\n    return false;\n  }\n}\n\nbool Util::fromString (const std::string& string, unsigned int& value)\n{\n  try\n  {\n    value = (unsigned int) (std::stoul (string));\n    return true;\n  }\n  catch (const std::invalid_argument&)\n  {\n    return false;\n  }\n  catch (const std::out_of_range&)\n  {\n    return false;\n  }\n}\n\nbool Util::fromString (const std::string& string, float& value)\n{\n  try\n  {\n    value = std::stof (string);\n    return true;\n  }\n  catch (const std::invalid_argument&)\n  {\n    return false;\n  }\n  catch (const std::out_of_range&)\n  {\n    return false;\n  }\n}\n\nunsigned int Util::countOnes (unsigned int x)\n{\n  unsigned int n = 0;\n  for (; x > 0; n++)\n  {\n    x &= x - 1;\n  }\n  return n;\n}\n\nbool Util::hasSuffix (const std::string& string, const std::string& suffix)\n{\n  if (string.size () >= suffix.size ())\n  {\n    return string.compare (string.size () - suffix.size (), suffix.size (), suffix) == 0;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nnamespace Util\n{\n  template <> void withCLocale (const std::function<void()>& f)\n  {\n    const std::locale prev = std::locale::global (std::locale::classic ());\n    f ();\n    std::locale::global (prev);\n  }\n}\n"
  },
  {
    "path": "lib/src/util.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_UTIL\n#define DILAY_UTIL\n\n#include <algorithm>\n#include <functional>\n#include <glm/fwd.hpp>\n#include <limits>\n#include <locale>\n#include <vector>\n#include \"log.hpp\"\n\n#define DILAY_INFO(fmt, ...) Log::log (Log::Level::Info, __FILE__, __LINE__, fmt, ##__VA_ARGS__);\n#define DILAY_WARN(fmt, ...) Log::log (Log::Level::Warning, __FILE__, __LINE__, fmt, ##__VA_ARGS__);\n#define DILAY_PANIC(fmt, ...)                                                              \\\n  {                                                                                        \\\n    Log::log (Log::Level::Panic, __FILE__, __LINE__, fmt, ##__VA_ARGS__);                  \\\n    Log::log (Log::Level::Panic, __FILE__, __LINE__, \"aborting due to previous error...\"); \\\n    std::abort ();                                                                         \\\n  }\n#define DILAY_IMPOSSIBLE DILAY_PANIC (\"the impossible happend\")\n\n#define unused(x) ((void) (x))\n\ntypedef std::pair<unsigned int, unsigned int> ui_pair;\n\nnamespace Util\n{\n  glm::vec3    midpoint (const glm::vec3&, const glm::vec3&);\n  glm::vec3    transformPosition (const glm::mat4x4&, const glm::vec3&);\n  glm::vec3    transformDirection (const glm::mat4x4&, const glm::vec3&);\n  glm::vec3    orthogonal (const glm::vec3&);\n  glm::ivec2   orthogonalRight (const glm::ivec2&);\n  glm::mat4x4  rotation (const glm::vec3&, const glm::vec3&, float);\n  bool         colinear (const glm::vec2&, const glm::vec2&);\n  bool         colinear (const glm::vec3&, const glm::vec3&);\n  bool         colinearUnit (const glm::vec2&, const glm::vec2&);\n  bool         colinearUnit (const glm::vec3&, const glm::vec3&);\n  float        smoothStep (const glm::vec3&, const glm::vec3&, float, float);\n  float        linearStep (const glm::vec3&, const glm::vec3&, float, float);\n  float        cross (const glm::vec2&, const glm::vec2&);\n  std::string  readFile (const std::string&);\n  unsigned int solveQuadraticEq (float, float, float, float&, float&);\n  unsigned int solveCubicEq (float, float, float, float&, float&, float&);\n  unsigned int solveCubicEq (float, float, float, float, float&, float&, float&);\n  bool         isNaN (float);\n  bool         isNaN (const glm::vec3&);\n  bool         isNotNull (const glm::vec3&);\n  bool         almostEqual (float, float);\n  void         warn (const char*, unsigned int, const char*, ...);\n  bool         fromString (const std::string&, int&);\n  bool         fromString (const std::string&, unsigned int&);\n  bool         fromString (const std::string&, float&);\n  unsigned int countOnes (unsigned int);\n  bool         hasSuffix (const std::string&, const std::string&);\n\n  constexpr float epsilon () { return 0.0001f; }\n\n  constexpr float minFloat () { return std::numeric_limits<float>::lowest (); }\n\n  constexpr float maxFloat () { return std::numeric_limits<float>::max (); }\n\n  constexpr int minInt () { return std::numeric_limits<int>::lowest (); }\n\n  constexpr int maxInt () { return std::numeric_limits<int>::max (); }\n\n  constexpr int maxUnsignedInt () { return std::numeric_limits<unsigned int>::max (); }\n\n  constexpr unsigned int invalidIndex () { return std::numeric_limits<unsigned int>::max (); }\n\n  template <typename T> void setIfNotNull (T* ptr, const T& value)\n  {\n    if (ptr)\n    {\n      *ptr = value;\n    }\n  }\n\n  template <typename T> unsigned int findIndexByReference (const std::vector<T>& vec, const T& obj)\n  {\n    return &obj - &vec.at (0);\n  }\n\n  template <typename T> T withCLocale (const std::function<T ()>& f)\n  {\n    const std::locale prev = std::locale::global (std::locale::classic ());\n    T                 result = f ();\n    std::locale::global (prev);\n    return result;\n  }\n  template <> void withCLocale (const std::function<void()>& f);\n\n  template <typename T>\n  void prune (std::vector<T>& v, const std::function<bool(const T&)>& p,\n              std::vector<unsigned int>* indexMap = nullptr)\n  {\n    if (indexMap)\n    {\n      indexMap->resize (v.size (), Util::invalidIndex ());\n    }\n    auto lastIt = std::find_if_not (v.rbegin (), v.rend (), p);\n\n    if (lastIt == v.rend ())\n    {\n      v.clear ();\n    }\n    else\n    {\n      unsigned int last = v.size () - (lastIt - v.rbegin ()) - 1;\n\n      for (unsigned int i = 0; i <= last; i++)\n      {\n        if (p (v[i]))\n        {\n          v[i] = v[last];\n\n          if (indexMap)\n          {\n            (*indexMap)[i] = Util::invalidIndex ();\n            (*indexMap)[last] = i;\n          }\n\n          do\n          {\n            last--;\n          } while (p (v[last]));\n        }\n        else\n        {\n          if (indexMap)\n          {\n            (*indexMap)[i] = i;\n          }\n        }\n      }\n      v.resize (last + 1);\n    }\n  }\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/variant.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef VARIANT_35425680_d10a_41c7_b91e_2e48cfe545da\n#define VARIANT_35425680_d10a_41c7_b91e_2e48cfe545da\n\n#include <cassert>\n#include <functional>\n#include <type_traits>\n\n// `VariantDetails` encapsulates internal details of the variant implementation\nnamespace VariantDetails\n{\n  template <typename...> union VariantUnion;\n\n  // Utility structure to initialize value in a union using its default constructor\n  template <unsigned int, typename, typename...> struct InitValue;\n\n  template <typename U, typename T, typename... Ts> struct InitValue<0, U, T, Ts...>\n  {\n    static void run (VariantUnion<T, Ts...>& variant)\n    {\n      static_assert (std::is_same<T, U>::value, \"variant type mismatch\");\n      variant.t = new U ();\n    }\n  };\n\n  template <unsigned int i, typename U, typename T, typename... Ts> struct InitValue<i, U, T, Ts...>\n  {\n    static void run (VariantUnion<T, Ts...>& variant)\n    {\n      InitValue<i - 1, U, Ts...>::run (variant.ts);\n    }\n  };\n\n  // Utility structure to set value in a union\n  template <unsigned int, typename, typename...> struct SetValue;\n\n  template <typename U, typename T, typename... Ts> struct SetValue<0, U, T, Ts...>\n  {\n    static void run (VariantUnion<T, Ts...>& variant, const U& u)\n    {\n      static_assert (std::is_same<T, U>::value, \"variant type mismatch\");\n      variant.t = new U (u);\n    }\n  };\n\n  template <unsigned int i, typename U, typename T, typename... Ts> struct SetValue<i, U, T, Ts...>\n  {\n    static void run (VariantUnion<T, Ts...>& variant, const U& u)\n    {\n      SetValue<i - 1, U, Ts...>::run (variant.ts, u);\n    }\n  };\n\n  // Utility structure to get the type of the i-th variant\n  template <unsigned int, typename...> struct GetType;\n\n  template <typename T, typename... Ts> struct GetType<0, T, Ts...>\n  {\n    typedef T type;\n  };\n\n  template <unsigned int i, typename T, typename... Ts> struct GetType<i, T, Ts...>\n  {\n    typedef typename GetType<i - 1, Ts...>::type type;\n  };\n\n  // Utility structure to get the index of the variant of a certain type\n  template <unsigned int, typename, typename...> struct GetIndex;\n\n  template <unsigned int i, typename U, typename T> struct GetIndex<i, U, T>\n  {\n    static constexpr bool         found = std::is_same<T, U>::value;\n    static constexpr unsigned int index = i;\n  };\n\n  template <unsigned int i, typename U, typename T, typename... Ts> struct GetIndex<i, U, T, Ts...>\n  {\n    static constexpr bool found =\n      std::is_same<T, U>::value ? true : GetIndex<i + 1, U, Ts...>::found;\n\n    static constexpr unsigned int index =\n      std::is_same<T, U>::value ? i : GetIndex<i + 1, U, Ts...>::index;\n  };\n\n  // `VariantUnion <T1,T2,...,Tn>` implements union over pointers of type `T1,T2,...,Tn`\n  //\n  // Case n == 1;\n  template <typename T> union VariantUnion<T> {\n    static_assert (std::is_object<T>::value, \"non-object types are not supported\");\n    static_assert (!std::is_const<T>::value, \"const-qualified types are not supported\");\n    static_assert (!std::is_volatile<T>::value, \"volatile-qualified types are not supported\");\n\n    T* t;\n\n    VariantUnion ()\n      : t (nullptr)\n    {\n    }\n    VariantUnion (const VariantUnion&) = delete;\n    VariantUnion (VariantUnion&&) = delete;\n\n    const VariantUnion& operator= (const VariantUnion&) = delete;\n    const VariantUnion& operator= (VariantUnion&&) = delete;\n\n    void copy (unsigned int i, const VariantUnion& other)\n    {\n      assert (i == 0);\n      (void) i;\n      this->t = new T (*other.t);\n    }\n\n    void move (unsigned int i, VariantUnion&& other)\n    {\n      assert (i == 0);\n      (void) i;\n      this->t = other.t;\n      other.t = nullptr;\n    }\n\n    void release (unsigned int i)\n    {\n      assert (i == 0);\n      (void) i;\n      delete this->t;\n    }\n\n    template <unsigned int i, typename U> void init () { InitValue<i, U, T>::run (*this); }\n\n    template <unsigned int i, typename U> void set (const U& u)\n    {\n      SetValue<i, U, T>::run (*this, u);\n    }\n\n    template <typename U> U& get (unsigned int i)\n    {\n      assert (i == 0);\n      assert ((std::is_same<T, U>::value));\n      (void) i;\n      return *reinterpret_cast<U*> (this->t);\n    }\n\n    template <typename U> const U& get (unsigned int i) const\n    {\n      assert (i == 0);\n      assert ((std::is_same<T, U>::value));\n      (void) i;\n      return *reinterpret_cast<U*> (this->t);\n    }\n\n    template <typename U> U caseOf (unsigned int i, const std::function<U (T&)>& branch) const\n    {\n      assert (i == 0);\n      (void) i;\n      return branch (*this->t);\n    }\n  };\n\n  // Case n > 1;\n  template <typename T, typename... Ts> union VariantUnion<T, Ts...> {\n    static_assert (std::is_object<T>::value, \"non-object types are not supported\");\n    static_assert (!std::is_const<T>::value, \"const-qualified types are not supported\");\n    static_assert (!std::is_volatile<T>::value, \"volatile-qualified types are not supported\");\n\n    T*                  t;\n    VariantUnion<Ts...> ts;\n\n    VariantUnion ()\n      : t (nullptr)\n    {\n    }\n    VariantUnion (const VariantUnion&) = delete;\n    VariantUnion (VariantUnion&&) = delete;\n\n    const VariantUnion& operator= (const VariantUnion&) = delete;\n    const VariantUnion& operator= (VariantUnion&&) = delete;\n\n    void copy (unsigned int i, const VariantUnion& other)\n    {\n      if (i == 0)\n      {\n        this->t = new T (*other.t);\n      }\n      else\n      {\n        this->ts.copy (i - 1, other.ts);\n      }\n    }\n\n    void move (unsigned int i, VariantUnion&& other)\n    {\n      if (i == 0)\n      {\n        this->t = other.t;\n        other.t = nullptr;\n      }\n      else\n      {\n        this->ts.move (i - 1, std::move (other.ts));\n      }\n    }\n\n    void release (unsigned int i)\n    {\n      if (i == 0)\n      {\n        delete this->t;\n      }\n      else\n      {\n        this->ts.release (i - 1);\n      }\n    }\n\n    template <unsigned int i, typename U> void init () { InitValue<i, U, T, Ts...>::run (*this); }\n\n    template <unsigned int i, typename U> void set (const U& u)\n    {\n      SetValue<i, U, T, Ts...>::run (*this, u);\n    }\n\n    template <typename U> U& get (unsigned int i)\n    {\n      if (i == 0)\n      {\n        assert ((std::is_same<U, T>::value));\n        return *reinterpret_cast<U*> (this->t);\n      }\n      else\n      {\n        return this->ts.template get<U> (i - 1);\n      }\n    }\n\n    template <typename U> const U& get (unsigned int i) const\n    {\n      if (i == 0)\n      {\n        assert ((std::is_same<U, T>::value));\n        return *reinterpret_cast<U*> (this->t);\n      }\n      else\n      {\n        return this->ts.template get<U> (i - 1);\n      }\n    }\n\n    template <typename U>\n    U caseOf (unsigned int i, const std::function<U (T&)>& branch,\n              const std::function<U (Ts&)>&... branches) const\n    {\n      if (i == 0)\n      {\n        return branch (*this->t);\n      }\n      else\n      {\n        return this->ts.template caseOf<U> (i - 1, branches...);\n      }\n    }\n  };\n};\n\n// `Variant` wraps `VariantUnion` and handles construction, access and destruction\ntemplate <typename... Ts> class Variant\n{\npublic:\n  Variant ()\n    : _varUnion ()\n    , _isSet (false)\n    , _setTo (0)\n  {\n  }\n\n  Variant (const Variant& other)\n    : _varUnion ()\n    , _isSet (other._isSet)\n    , _setTo (other._setTo)\n  {\n    if (this->isSet ())\n    {\n      this->_varUnion.copy (this->_setTo, other._varUnion);\n    }\n  }\n\n  Variant (Variant&& other)\n    : _varUnion ()\n    , _isSet (other._isSet)\n    , _setTo (other._setTo)\n  {\n    other._isSet = false;\n\n    if (this->isSet ())\n    {\n      this->_varUnion.move (this->_setTo, std::move (other._varUnion));\n    }\n  }\n\n  const Variant& operator= (const Variant& other)\n  {\n    if (this == &other)\n    {\n      return *this;\n    }\n    this->release ();\n    this->_isSet = other._isSet;\n    this->_setTo = other._setTo;\n\n    if (this->isSet ())\n    {\n      this->_varUnion.copy (this->_setTo, other._varUnion);\n    }\n    return *this;\n  }\n\n  const Variant& operator= (Variant&& other)\n  {\n    if (this == &other)\n    {\n      return *this;\n    }\n    this->release ();\n    this->_isSet = other._isSet;\n    this->_setTo = other._setTo;\n\n    other._isSet = false;\n\n    if (this->isSet ())\n    {\n      this->_varUnion.move (this->_setTo, std::move (other._varUnion));\n    }\n    return *this;\n  }\n\n  ~Variant () { this->release (); }\n\n  void release ()\n  {\n    if (this->isSet ())\n    {\n      this->_varUnion.release (this->_setTo);\n      this->_isSet = false;\n    }\n  }\n\n  template <typename U> U& get ()\n  {\n    assert (this->isSet ());\n    return this->_varUnion.template get<U> (this->_setTo);\n  }\n\n  template <typename U> const U& get () const\n  {\n    assert (this->isSet ());\n    return this->_varUnion.template get<U> (this->_setTo);\n  }\n\n  template <unsigned int i, typename U = VariantDetails::GetType<i, Ts...>> void initAt ()\n  {\n    this->template resetTo<i> ();\n    this->_varUnion.template init<i, U> ();\n  }\n\n  template <typename U> void init ()\n  {\n    constexpr bool         found = VariantDetails::GetIndex<0, U, Ts...>::found;\n    constexpr unsigned int index = VariantDetails::GetIndex<0, U, Ts...>::index;\n    static_assert (found, \"variant type not found\");\n    this->template initAt<index, U> ();\n  }\n\n  template <unsigned int i, typename U = VariantDetails::GetType<i, Ts...>> void setAt (const U& u)\n  {\n    this->template resetTo<i> ();\n    this->_varUnion.template set<i, U> (u);\n  }\n\n  template <typename U> void set (const U& u)\n  {\n    constexpr bool         found = VariantDetails::GetIndex<0, U, Ts...>::found;\n    constexpr unsigned int index = VariantDetails::GetIndex<0, U, Ts...>::index;\n    static_assert (found, \"variant type not found\");\n    this->template setAt<index, U> (u);\n  }\n\n  template <typename U> bool is () const\n  {\n    if (this->isSet ())\n    {\n      constexpr bool         found = VariantDetails::GetIndex<0, U, Ts...>::found;\n      constexpr unsigned int index = VariantDetails::GetIndex<0, U, Ts...>::index;\n      static_assert (found, \"variant type not found\");\n      return this->_setTo == index;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  template <typename U> U caseOf (const std::function<U (Ts&)>&... branches) const\n  {\n    assert (this->isSet ());\n    return this->_varUnion.template caseOf<U> (this->_setTo, branches...);\n  }\n\n  bool isSet () const { return this->_isSet; }\n\nprivate:\n  VariantDetails::VariantUnion<Ts...> _varUnion;\n  bool                                _isSet;\n  unsigned int                        _setTo;\n\n  template <unsigned int i> void resetTo ()\n  {\n    if (this->isSet ())\n    {\n      this->release ();\n    }\n    this->_isSet = true;\n    this->_setTo = i;\n  }\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/axis.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QPainter>\n#include <glm/glm.hpp>\n#include <glm/gtc/constants.hpp>\n#include \"camera.hpp\"\n#include \"color.hpp\"\n#include \"config.hpp\"\n#include \"dimension.hpp\"\n#include \"mesh-util.hpp\"\n#include \"mesh.hpp\"\n#include \"opengl.hpp\"\n#include \"render-mode.hpp\"\n#include \"view/axis.hpp\"\n\nstruct ViewAxis::Impl\n{\n  Mesh         coneMesh;\n  Mesh         cylinderMesh;\n  Mesh         gridMesh;\n  glm::uvec2   axisResolution;\n  Color        axisColor;\n  Color        axisLabelColor;\n  glm::vec3    axisScaling;\n  glm::vec3    axisArrowScaling;\n  unsigned int gridResolution;\n\n  Impl (const Config& config)\n  {\n    this->runFromConfig (config);\n\n    this->axisResolution = glm::uvec2 (200, 200);\n    this->gridResolution = 6;\n\n    this->coneMesh = MeshUtil::cone (10);\n    this->cylinderMesh = MeshUtil::cylinder (10);\n\n    this->cylinderMesh.renderMode ().constantShading (true);\n    this->cylinderMesh.renderMode ().cameraRotationOnly (true);\n    this->cylinderMesh.bufferData ();\n\n    this->coneMesh.renderMode ().constantShading (true);\n    this->coneMesh.renderMode ().cameraRotationOnly (true);\n    this->coneMesh.bufferData ();\n\n    this->initializeGrid ();\n  }\n\n  void initializeGrid ()\n  {\n    float gridSpace = 1.0f / float(gridResolution - 1);\n\n    for (unsigned int j = 0; j < gridResolution; j++)\n    {\n      for (unsigned int i = 0; i < gridResolution; i++)\n      {\n        this->gridMesh.addVertex (glm::vec3 (float(i) * gridSpace, float(j) * gridSpace, 0.0f));\n      }\n    }\n    for (unsigned int j = 1; j < gridResolution; j++)\n    {\n      for (unsigned int i = 1; i < gridResolution; i++)\n      {\n        this->gridMesh.addIndex ((j * gridResolution) + i - 1);\n        this->gridMesh.addIndex ((j * gridResolution) + i);\n        this->gridMesh.addIndex (((j - 1) * gridResolution) + i);\n        this->gridMesh.addIndex ((j * gridResolution) + i);\n      }\n    }\n    this->gridMesh.renderMode ().constantShading (true);\n    this->gridMesh.renderMode ().cameraRotationOnly (true);\n    this->gridMesh.bufferData ();\n  }\n\n  void render (Camera& camera)\n  {\n    OpenGL::glClear (OpenGL::DepthBufferBit ());\n\n    const glm::uvec2 resolution = camera.resolution ();\n    camera.updateResolution (glm::uvec2 (200, 200));\n\n    this->cylinderMesh.scaling (this->axisScaling);\n\n    this->cylinderMesh.position (glm::vec3 (0.0f, this->axisScaling.y * 0.5f, 0.0f));\n    this->cylinderMesh.rotationMatrix (glm::mat4x4 (1.0f));\n    this->cylinderMesh.color (this->axisColor);\n    this->cylinderMesh.render (camera);\n\n    this->cylinderMesh.position (glm::vec3 (this->axisScaling.y * 0.5f, 0.0f, 0.0f));\n    this->cylinderMesh.rotationZ (0.5f * glm::pi<float> ());\n    this->cylinderMesh.render (camera);\n\n    this->cylinderMesh.position (glm::vec3 (0.0f, 0.0f, this->axisScaling.y * 0.5f));\n    this->cylinderMesh.rotationX (0.5f * glm::pi<float> ());\n    this->cylinderMesh.render (camera);\n\n    this->coneMesh.scaling (this->axisArrowScaling);\n\n    this->coneMesh.position (glm::vec3 (0.0f, this->axisScaling.y, 0.0f));\n    this->coneMesh.rotationMatrix (glm::mat4x4 (1.0f));\n    this->coneMesh.color (this->axisColor);\n    this->coneMesh.render (camera);\n\n    this->coneMesh.position (glm::vec3 (this->axisScaling.y, 0.0f, 0.0f));\n    this->coneMesh.rotationZ (-0.5f * glm::pi<float> ());\n    this->coneMesh.render (camera);\n\n    this->coneMesh.position (glm::vec3 (0.0f, 0.0f, this->axisScaling.y));\n    this->coneMesh.rotationX (0.5f * glm::pi<float> ());\n    this->coneMesh.render (camera);\n\n    this->renderGrid (camera);\n\n    camera.updateResolution (resolution);\n  }\n\n  void renderGrid (Camera& camera)\n  {\n    switch (camera.primaryDimension ())\n    {\n      case Dimension::X:\n        this->gridMesh.rotationY (-0.5f * glm::pi<float> ());\n        break;\n      case Dimension::Y:\n        this->gridMesh.rotationX (0.5f * glm::pi<float> ());\n        break;\n      case Dimension::Z:\n        this->gridMesh.rotationMatrix (glm::mat4x4 (1.0f));\n        break;\n    }\n    this->gridMesh.scaling (glm::vec3 (this->axisScaling.y));\n    this->gridMesh.color (this->axisColor);\n    this->gridMesh.renderLines (camera);\n  }\n\n  void render (Camera& camera, QPainter& painter)\n  {\n    this->coneMesh.rotationMatrix (glm::mat4x4 (1.0f));\n\n    QFont font;\n    font.setWeight (QFont::Bold);\n\n    QFontMetrics metrics (font);\n    int          w = glm::max (metrics.maxWidth (), metrics.height ());\n    glm::uvec2   resolution = camera.resolution ();\n    camera.updateResolution (this->axisResolution);\n\n    auto renderLabel = [this, &resolution, &painter, w, &camera](const glm::vec3& p,\n                                                                 const QString&   l) {\n      this->coneMesh.position (p);\n\n      glm::vec2 pos = camera.fromWorld (glm::vec3 (0.0f), this->coneMesh.modelMatrix (), true);\n      QRect     rect (int(pos.x) - (w / 2),\n                      resolution.y - this->axisResolution.y + int(pos.y) - (w / 2), w, w);\n\n      painter.drawText (rect, Qt::AlignCenter, l);\n    };\n\n    painter.setPen (this->axisLabelColor.qColor ());\n    painter.setFont (font);\n\n    const float labelPosition = this->axisScaling.y + (this->axisArrowScaling.y * 0.5f);\n\n    renderLabel (glm::vec3 (labelPosition, 0.0f, 0.0f), \"X\");\n    renderLabel (glm::vec3 (0.0f, labelPosition, 0.0f), \"Y\");\n    renderLabel (glm::vec3 (0.0f, 0.0f, labelPosition), \"Z\");\n\n    camera.updateResolution (resolution);\n  }\n\n  void runFromConfig (const Config& config)\n  {\n    this->axisLabelColor = config.get<Color> (\"editor/axis/color/label\");\n    this->axisColor = config.get<Color> (\"editor/axis/color/normal\");\n    this->axisScaling = config.get<glm::vec3> (\"editor/axis/scaling\");\n    this->axisArrowScaling = config.get<glm::vec3> (\"editor/axis/arrow-scaling\");\n  }\n};\n\nDELEGATE1_BIG3 (ViewAxis, const Config&)\nDELEGATE1 (void, ViewAxis, render, Camera&)\nDELEGATE2 (void, ViewAxis, render, Camera&, QPainter&)\nDELEGATE1 (void, ViewAxis, runFromConfig, const Config&)\n"
  },
  {
    "path": "lib/src/view/axis.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_AXIS\n#define DILAY_VIEW_AXIS\n\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n\nclass Camera;\nclass Config;\nclass QPainter;\n\nclass ViewAxis : public Configurable\n{\npublic:\n  DECLARE_BIG3 (ViewAxis, const Config&)\n\n  void render (Camera&);\n  void render (Camera&, QPainter&);\n\nprivate:\n  IMPLEMENTATION\n\n  void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/color-button.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QColorDialog>\n#include <QPainter>\n#include \"color.hpp\"\n#include \"view/color-button.hpp\"\n#include \"view/util.hpp\"\n\nstruct ViewColorButton::Impl\n{\n  ViewColorButton* self;\n  Color            color;\n\n  Impl (ViewColorButton* s, const Color& c, bool alpha)\n    : self (s)\n    , color (c)\n  {\n    ViewUtil::connect (*this->self, [this, alpha]() {\n      QColorDialog::ColorDialogOptions options;\n      options.setFlag (QColorDialog::DontUseNativeDialog);\n\n      if (alpha)\n      {\n        options.setFlag (QColorDialog::ShowAlphaChannel);\n      }\n\n      QColor selected = QColorDialog::getColor (this->color.qColor (), this->self->parentWidget (),\n                                                QObject::tr (\"Select color\"), options);\n      if (selected.isValid ())\n      {\n        this->color = Color (selected);\n        this->self->update ();\n        emit this->self->colorChanged (this->color);\n      }\n    });\n  }\n\n  void paintEvent (QPaintEvent* event)\n  {\n    this->self->QPushButton::paintEvent (event);\n\n    QPainter painter (this->self);\n    QRect    rect (this->self->rect ());\n\n    const int dw = this->self->width () / 10;\n    const int dh = this->self->height () / 5;\n\n    rect.setLeft (rect.left () + dw);\n    rect.setRight (rect.right () - dw);\n    rect.setTop (rect.top () + dh);\n    rect.setBottom (rect.bottom () - dh);\n\n    painter.fillRect (rect, this->color.qColor ());\n  }\n};\n\nDELEGATE_BIG2_BASE (ViewColorButton, (const Color& c, bool a, QWidget* p), (this, c, a),\n                    QPushButton, (p))\nDELEGATE1 (void, ViewColorButton, paintEvent, QPaintEvent*)\n"
  },
  {
    "path": "lib/src/view/color-button.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_COLOR_BUTTON\n#define DILAY_COLOR_BUTTON\n\n#include <QPushButton>\n#include \"macro.hpp\"\n\nclass Color;\n\nclass ViewColorButton : public QPushButton\n{\n  Q_OBJECT\npublic:\n  DECLARE_BIG2 (ViewColorButton, const Color&, bool = false, QWidget* = nullptr)\n\nsignals:\n  void colorChanged (const Color&);\n\nprotected:\n  void paintEvent (QPaintEvent*);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/configuration.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCheckBox>\n#include <QDialog>\n#include <QDialogButtonBox>\n#include <QLineEdit>\n#include <QVBoxLayout>\n#include <algorithm>\n#include <array>\n#include <functional>\n#include \"../util.hpp\"\n#include \"color.hpp\"\n#include \"config.hpp\"\n#include \"state.hpp\"\n#include \"view/color-button.hpp\"\n#include \"view/configuration.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n#include \"view/vector-edit.hpp\"\n\nnamespace\n{\n  const std::array<std::string, 1> requireRestart = {\"editor/use-geometry-shader\"};\n\n  struct DialogData\n  {\n    ViewGlWidget& glWidget;\n    bool          requireRestart;\n\n    DialogData (ViewGlWidget& w)\n      : glWidget (w)\n      , requireRestart (false)\n    {\n    }\n\n    void checkIfRestartIsRequired (const std::string& path)\n    {\n      const auto it = std::find (::requireRestart.begin (), ::requireRestart.end (), path);\n      if (it != ::requireRestart.end ())\n      {\n        this->requireRestart = true;\n      }\n    }\n  };\n\n  template <typename T>\n  void setAndUpdate (DialogData& data, const std::string& path, const T& value)\n  {\n    data.glWidget.state ().config ().set (path, value);\n    data.glWidget.fromConfig ();\n    data.glWidget.update ();\n    data.checkIfRestartIsRequired (path);\n  }\n\n  void addColorButton (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path,\n                       const QString& label, bool alpha = false)\n  {\n    const Color&     color = data.glWidget.state ().config ().get<Color> (path);\n    ViewColorButton& button = *new ViewColorButton (color, alpha, &data.glWidget);\n\n    QObject::connect (&button, &ViewColorButton::colorChanged,\n                      [&data, path](const Color& c) { setAndUpdate (data, path, c); });\n    grid.add (label, button);\n  }\n\n  void addVectorEdit (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path,\n                      const QString& label)\n  {\n    const glm::vec3& vector = data.glWidget.state ().config ().get<glm::vec3> (path);\n    ViewVectorEdit&  edit = *new ViewVectorEdit (vector);\n    QObject::connect (&edit, &ViewVectorEdit::vectorEdited,\n                      [&data, path](const glm::vec3& v) { setAndUpdate (data, path, v); });\n    grid.add (label, edit);\n  }\n\n  void addFloatEdit (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path,\n                     const QString& label, float min, float max)\n  {\n    const float value = data.glWidget.state ().config ().get<float> (path);\n    QLineEdit&  edit = ViewUtil::lineEdit (min, value, max);\n    ViewUtil::connectFloat (edit, [&data, path](float f) { setAndUpdate (data, path, f); });\n    grid.add (label, edit);\n  }\n\n  void addIntEdit (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path,\n                   const QString& label, int min, int max)\n  {\n    const int  value = data.glWidget.state ().config ().get<int> (path);\n    QLineEdit& edit = ViewUtil::lineEdit (min, value, max);\n    ViewUtil::connectInt (edit, [&data, path](int i) { setAndUpdate (data, path, i); });\n    grid.add (label, edit);\n  }\n\n  void addBoolEdit (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path,\n                    const QString& label)\n  {\n    const bool value = data.glWidget.state ().config ().get<bool> (path);\n    QCheckBox& edit = ViewUtil::checkBox (label, value);\n    ViewUtil::connect (edit, [&data, path](bool b) { setAndUpdate (data, path, b); });\n    grid.add (edit);\n  }\n\n  QWidget* makeColorsPage (DialogData& data)\n  {\n    ViewTwoColumnGrid* grid = new ViewTwoColumnGrid;\n\n    addColorButton (data, *grid, \"editor/background\", QObject::tr (\"Background\"));\n    addColorButton (data, *grid, \"editor/on-screen-color\", QObject::tr (\"On-Screen\"), true);\n    addColorButton (data, *grid, \"editor/axis/color/normal\", QObject::tr (\"Axis\"));\n    addColorButton (data, *grid, \"editor/axis/color/label\", QObject::tr (\"Axis label\"));\n    addColorButton (data, *grid, \"editor/floor-plane/color\", QObject::tr (\"Floor-plane\"));\n    addColorButton (data, *grid, \"editor/mesh/color/normal\", QObject::tr (\"Mesh\"));\n    addColorButton (data, *grid, \"editor/mesh/color/wireframe\", QObject::tr (\"Wireframe\"));\n    addColorButton (data, *grid, \"editor/sketch/bubble/color\", QObject::tr (\"Sketch\"));\n    addColorButton (data, *grid, \"editor/sketch/node/color\", QObject::tr (\"Sketch-node\"));\n    addColorButton (data, *grid, \"editor/sketch/sphere/color\", QObject::tr (\"Sketch-sphere\"));\n\n    grid->addStretcher ();\n\n    return grid;\n  }\n\n  QWidget* makeLightsPage (DialogData& data)\n  {\n    QWidget*     widget = new QWidget;\n    QHBoxLayout* layout = new QHBoxLayout;\n\n    widget->setLayout (layout);\n\n    ViewTwoColumnGrid* grid1 = new ViewTwoColumnGrid;\n    grid1->addCenter (QObject::tr (\"Light 1\"));\n    addVectorEdit (data, *grid1, \"editor/light/light1/direction\", QObject::tr (\"Direction\"));\n    addColorButton (data, *grid1, \"editor/light/light1/color\", QObject::tr (\"Color\"));\n    grid1->addStretcher ();\n\n    ViewTwoColumnGrid* grid2 = new ViewTwoColumnGrid;\n    grid2->addCenter (QObject::tr (\"Light 2\"));\n    addVectorEdit (data, *grid2, \"editor/light/light2/direction\", QObject::tr (\"Direction\"));\n    addColorButton (data, *grid2, \"editor/light/light2/color\", QObject::tr (\"Color\"));\n    grid2->addStretcher ();\n\n    layout->addWidget (grid1);\n    layout->addWidget (grid2);\n\n    return widget;\n  }\n\n  QWidget* makeCameraPage (DialogData& data)\n  {\n    ViewTwoColumnGrid* grid = new ViewTwoColumnGrid;\n\n    addFloatEdit (data, *grid, \"editor/camera/near-clipping\", QObject::tr (\"Near clipping plane\"),\n                  Util::epsilon (), 1.0f);\n    addFloatEdit (data, *grid, \"editor/camera/far-clipping\", QObject::tr (\"Far clipping plane\"),\n                  100.0f, Util::maxFloat ());\n    addFloatEdit (data, *grid, \"editor/camera/rotation-factor\", QObject::tr (\"Rotation factor\"),\n                  Util::epsilon (), 100.0f);\n    addFloatEdit (data, *grid, \"editor/camera/movement-factor\", QObject::tr (\"Movement factor\"),\n                  Util::epsilon (), 100.0f);\n    addFloatEdit (data, *grid, \"editor/camera/zoom-in-mouse-wheel-factor\",\n                  QObject::tr (\"Zoom factor (mouse wheel)\"), Util::epsilon (), 1.0f);\n    addFloatEdit (data, *grid, \"editor/camera/field-of-view\", QObject::tr (\"Field of view\"),\n                  Util::epsilon (), 120.0f);\n\n    grid->addStretcher ();\n\n    return grid;\n  }\n\n  QWidget* makeToolsPage (DialogData& data)\n  {\n    QWidget*     widget = new QWidget;\n    QHBoxLayout* layout = new QHBoxLayout;\n\n    widget->setLayout (layout);\n\n    ViewTwoColumnGrid* gridSculpt = new ViewTwoColumnGrid;\n    gridSculpt->addCenter (QObject::tr (\"General\"));\n    addColorButton (data, *gridSculpt, \"editor/tool/cursor-color\", QObject::tr (\"Cursor color\"));\n    gridSculpt->addCenter (QObject::tr (\"Sculpt\"));\n    addFloatEdit (data, *gridSculpt, \"editor/tool/sculpt/detail-factor\",\n                  QObject::tr (\"Detail factor\"), Util::epsilon (), 1.0f);\n    addFloatEdit (data, *gridSculpt, \"editor/tool/sculpt/step-width-factor\",\n                  QObject::tr (\"Step width factor\"), Util::epsilon (), 1.0f);\n    addFloatEdit (data, *gridSculpt, \"editor/tool/sculpt/max-absolute-radius\",\n                  QObject::tr (\"Maximum absolute radius\"), Util::epsilon (), 100.0f);\n    addBoolEdit (data, *gridSculpt, \"editor/tool/sculpt/mirror/render\",\n                 QObject::tr (\"Render mirror\"));\n    addFloatEdit (data, *gridSculpt, \"editor/tool/sculpt/mirror/width\",\n                  QObject::tr (\"Mirror width\"), Util::epsilon (), 1.0f);\n    addColorButton (data, *gridSculpt, \"editor/tool/sculpt/mirror/color\",\n                    QObject::tr (\"Mirror color\"));\n    gridSculpt->addStretcher ();\n\n    ViewTwoColumnGrid* gridSketch = new ViewTwoColumnGrid;\n    gridSketch->addCenter (QObject::tr (\"Sketch\"));\n    addFloatEdit (data, *gridSketch, \"editor/tool/sketch-spheres/step-width-factor\",\n                  QObject::tr (\"Step width factor\"), Util::epsilon (), 1.0f);\n    gridSketch->addStretcher ();\n\n    layout->addWidget (gridSculpt);\n    layout->addWidget (gridSketch);\n\n    return widget;\n  }\n\n  QWidget* makeMiscPage (DialogData& data)\n  {\n    ViewTwoColumnGrid* grid = new ViewTwoColumnGrid;\n\n    addIntEdit (data, *grid, \"editor/undo-depth\", QObject::tr (\"Undo depth\"), 1, Util::maxInt ());\n    addIntEdit (data, *grid, \"window/initial-width\", QObject::tr (\"Initial window width\"), 1,\n                Util::maxInt ());\n    addIntEdit (data, *grid, \"window/initial-height\", QObject::tr (\"Initial window height\"), 1,\n                Util::maxInt ());\n\n    addVectorEdit (data, *grid, \"editor/axis/scaling\", QObject::tr (\"Axis scaling\"));\n    addVectorEdit (data, *grid, \"editor/axis/arrow-scaling\", QObject::tr (\"Axis-arrow scaling\"));\n\n    addFloatEdit (data, *grid, \"editor/floor-plane/tile-width\",\n                  QObject::tr (\"Floor-plane tile-width\"), Util::epsilon (), 10.0f);\n\n    addFloatEdit (data, *grid, \"editor/tablet-pressure-intensity\",\n                  QObject::tr (\"Table pressure intensity\"), Util::epsilon (), 10.0f);\n\n    addBoolEdit (data, *grid, \"editor/use-geometry-shader\", QObject::tr (\"Use geometry shader\"));\n\n    grid->addStretcher ();\n\n    return grid;\n  }\n}\n\nvoid ViewConfiguration::show (ViewMainWindow& window, ViewGlWidget& glWidget)\n{\n  QDialog    dialog (&window);\n  DialogData data (glWidget);\n\n  std::function<void()> setup = [&dialog, &data, &setup]() {\n    delete dialog.layout ();\n\n    QTabWidget* widget = new QTabWidget;\n\n    widget->addTab (makeColorsPage (data), QObject::tr (\"&Colors\"));\n    widget->addTab (makeLightsPage (data), QObject::tr (\"&Lights\"));\n    widget->addTab (makeCameraPage (data), QObject::tr (\"C&amera\"));\n    widget->addTab (makeToolsPage (data), QObject::tr (\"&Tools\"));\n    widget->addTab (makeMiscPage (data), QObject::tr (\"&Misc\"));\n\n    QDialogButtonBox* buttons =\n      new QDialogButtonBox (QDialogButtonBox::Ok | QDialogButtonBox::RestoreDefaults);\n\n    QObject::connect (buttons, &QDialogButtonBox::accepted, [&dialog]() { dialog.accept (); });\n    QObject::connect (&dialog, &QDialog::accepted, [&data]() {\n      data.glWidget.fromConfig ();\n      data.glWidget.update ();\n    });\n    QObject::connect (buttons->button (QDialogButtonBox::RestoreDefaults), &QPushButton::clicked,\n                      [&data, &setup]() {\n                        data.glWidget.state ().config ().restoreDefaults ();\n                        data.glWidget.fromConfig ();\n                        data.glWidget.update ();\n                        setup ();\n                      });\n\n    QVBoxLayout* layout = new QVBoxLayout;\n\n    layout->addWidget (widget);\n    layout->addWidget (buttons);\n\n    dialog.setLayout (layout);\n  };\n\n  setup ();\n\n  dialog.setWindowTitle (QObject::tr (\"Configuration\"));\n  dialog.exec ();\n\n  if (data.requireRestart)\n  {\n    ViewUtil::info (glWidget,\n                    QObject::tr (\"A restart is required for some changes to come into effect.\"));\n  }\n}\n"
  },
  {
    "path": "lib/src/view/configuration.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_CONFIGURATION\n#define DILAY_VIEW_CONFIGURATION\n\nclass ViewGlWidget;\nclass ViewMainWindow;\n\nnamespace ViewConfiguration\n{\n  void show (ViewMainWindow&, ViewGlWidget&);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/view/context-menu.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"camera.hpp\"\n#include \"dimension.hpp\"\n#include \"dynamic/mesh-intersection.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"mesh.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"scene.hpp\"\n#include \"sketch/mesh-intersection.hpp\"\n#include \"state.hpp\"\n#include \"view/context-menu.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  void addActions (QMenu& menu, ViewMainWindow& mainWindow, DynamicMesh& mesh)\n  {\n    Scene&  scene = mainWindow.glWidget ().state ().scene ();\n    Config& config = mainWindow.glWidget ().state ().config ();\n\n    ViewUtil::addAction (menu, QObject::tr (\"Copy mesh\"), QKeySequence (),\n                         [&mainWindow, &scene, &config, &mesh]() {\n                           scene.newDynamicMesh (config, mesh);\n                           mainWindow.update ();\n                         });\n\n    ViewUtil::addAction (\n      menu, QObject::tr (\"Mirror mesh\"), QKeySequence (), [&mainWindow, &mesh]() {\n        const PrimAABox bounds = mesh.mesh ().bounds ();\n        const PrimPlane plane (bounds.center (), DimensionUtil::vector (Dimension::X));\n        mesh.mirror (plane);\n        mainWindow.update ();\n      });\n\n    ViewUtil::addAction (menu, QObject::tr (\"Move mesh to center\"), QKeySequence (),\n                         [&mainWindow, &mesh]() {\n                           mesh.moveToCenter ();\n                           mainWindow.update ();\n                         });\n\n    ViewUtil::addAction (menu, QObject::tr (\"Normalize mesh scaling\"), QKeySequence (),\n                         [&mainWindow, &mesh]() {\n                           mesh.normalizeScaling ();\n                           mainWindow.update ();\n                         });\n\n    ViewUtil::addAction (menu, QObject::tr (\"Delete mesh\"), QKeySequence (),\n                         [&mainWindow, &scene, &mesh]() {\n                           scene.deleteMesh (mesh);\n                           mainWindow.update ();\n                         });\n  }\n\n  void addActions (QMenu& menu, ViewMainWindow& mainWindow, SketchMesh& sketch)\n  {\n    Scene&  scene = mainWindow.glWidget ().state ().scene ();\n    Config& config = mainWindow.glWidget ().state ().config ();\n\n    ViewUtil::addAction (menu, QObject::tr (\"Copy sketch\"), QKeySequence (),\n                         [&mainWindow, &scene, &config, &sketch]() {\n                           scene.newSketchMesh (config, sketch);\n                           mainWindow.update ();\n                         });\n\n    ViewUtil::addAction (menu, QObject::tr (\"Delete sketch\"), QKeySequence (),\n                         [&mainWindow, &scene, &sketch]() {\n                           scene.deleteMesh (sketch);\n                           mainWindow.update ();\n                         });\n  }\n}\n\nViewContextMenu::ViewContextMenu (ViewMainWindow& mainWindow, DynamicMesh& mesh)\n{\n  ::addActions (*this, mainWindow, mesh);\n}\n\nViewContextMenu::ViewContextMenu (ViewMainWindow& mainWindow, SketchMesh& sketch)\n{\n  ::addActions (*this, mainWindow, sketch);\n}\n\nViewContextMenu::ViewContextMenu (ViewMainWindow& mainWindow, const glm::ivec2& pos)\n{\n  Scene&        scene = mainWindow.glWidget ().state ().scene ();\n  const PrimRay ray = mainWindow.glWidget ().state ().camera ().ray (pos);\n\n  DynamicMeshIntersection mIntersection;\n  SketchMeshIntersection  sIntersection;\n\n  if (scene.intersects (ray, mIntersection))\n  {\n    ::addActions (*this, mainWindow, mIntersection.mesh ());\n  }\n  else if (scene.intersects (ray, sIntersection))\n  {\n    ::addActions (*this, mainWindow, sIntersection.mesh ());\n  }\n}\n"
  },
  {
    "path": "lib/src/view/context-menu.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_CONTEXT_MENU\n#define DILAY_VIEW_CONTEXT_MENU\n\n#include <QMenu>\n#include <glm/fwd.hpp>\n\nclass DynamicMesh;\nclass SketchMesh;\nclass ViewMainWindow;\n\nclass ViewContextMenu : public QMenu\n{\npublic:\n  ViewContextMenu (ViewMainWindow&, DynamicMesh&);\n  ViewContextMenu (ViewMainWindow&, SketchMesh&);\n  ViewContextMenu (ViewMainWindow&, const glm::ivec2&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/cursor.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"mesh-util.hpp\"\n#include \"mesh.hpp\"\n#include \"opengl.hpp\"\n#include \"render-mode.hpp\"\n#include \"view/cursor.hpp\"\n\nstruct ViewCursor::Impl\n{\n  Mesh  radiusMesh;\n  float _radius;\n  bool  isEnabled;\n\n  static const unsigned int numSectors = 40;\n\n  Impl ()\n    : _radius (0.0f)\n    , isEnabled (false)\n  {\n    this->radiusMesh = MeshUtil::icosphere (2);\n    this->radiusMesh.renderMode ().constantShading (true);\n    this->radiusMesh.bufferData ();\n  }\n\n  float radius () const { return this->_radius; }\n\n  glm::vec3 position () const { return this->radiusMesh.position (); }\n\n  const Color& color () const { return this->radiusMesh.color (); }\n\n  void radius (float r)\n  {\n    this->_radius = r;\n    this->update ();\n  }\n\n  void position (const glm::vec3& p) { this->radiusMesh.position (p); }\n\n  void color (const Color& color) { this->radiusMesh.color (color); }\n\n  void enable () { this->isEnabled = true; }\n\n  void disable () { this->isEnabled = false; }\n\n  void render (Camera& camera) const\n  {\n    if (this->isEnabled)\n    {\n      OpenGL::glClear (OpenGL::StencilBufferBit ());\n\n      OpenGL::glDepthMask (false);\n      OpenGL::glColorMask (false, false, false, false);\n      OpenGL::glEnable (OpenGL::StencilTest ());\n\n      OpenGL::glCullFace (OpenGL::Front ());\n\n      OpenGL::glEnable (OpenGL::StencilTest ());\n      OpenGL::glStencilFunc (OpenGL::Always (), 1, 255);\n      OpenGL::glStencilOp (OpenGL::Keep (), OpenGL::Replace (), OpenGL::Keep ());\n\n      this->radiusMesh.render (camera);\n\n      OpenGL::glCullFace (OpenGL::Back ());\n      OpenGL::glColorMask (true, true, true, true);\n\n      OpenGL::glStencilFunc (OpenGL::Equal (), 1, 255);\n      OpenGL::glStencilOp (OpenGL::Keep (), OpenGL::Keep (), OpenGL::Keep ());\n\n      OpenGL::glEnable (OpenGL::Blend ());\n      OpenGL::glBlendEquation (OpenGL::FuncAdd ());\n      OpenGL::glBlendFunc (OpenGL::DstColor (), OpenGL::Zero ());\n\n      this->radiusMesh.render (camera);\n\n      OpenGL::glDisable (OpenGL::Blend ());\n      OpenGL::glDisable (OpenGL::StencilTest ());\n      OpenGL::glDepthMask (true);\n    }\n  }\n\n  void update () { this->radiusMesh.scaling (glm::vec3 (this->radius ())); }\n};\n\nDELEGATE_BIG6 (ViewCursor)\nDELEGATE_CONST (float, ViewCursor, radius)\nDELEGATE_CONST (glm::vec3, ViewCursor, position)\nDELEGATE_CONST (const Color&, ViewCursor, color)\nGETTER_CONST (bool, ViewCursor, isEnabled)\nDELEGATE1 (void, ViewCursor, radius, float)\nDELEGATE1 (void, ViewCursor, position, const glm::vec3&)\nDELEGATE1 (void, ViewCursor, color, const Color&)\nDELEGATE (void, ViewCursor, enable)\nDELEGATE (void, ViewCursor, disable)\nDELEGATE1_CONST (void, ViewCursor, render, Camera&)\n"
  },
  {
    "path": "lib/src/view/cursor.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_CURSOR\n#define DILAY_VIEW_CURSOR\n\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n\nclass Camera;\nclass Color;\nclass Mesh;\n\nclass ViewCursor\n{\npublic:\n  DECLARE_BIG6 (ViewCursor)\n\n  float        radius () const;\n  glm::vec3    position () const;\n  const Color& color () const;\n  bool         isEnabled () const;\n\n  void radius (float);\n  void position (const glm::vec3&);\n  void color (const Color&);\n  void enable ();\n  void disable ();\n  void render (Camera&) const;\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/double-slider.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"../util.hpp\"\n#include \"view/double-slider.hpp\"\n\nstruct ViewDoubleSlider::Impl\n{\n  ViewDoubleSlider*    self;\n  const unsigned int   factor;\n  const unsigned short order;\n\n  Impl (ViewDoubleSlider* s, unsigned short numDecimals, unsigned short o)\n    : self (s)\n    , factor (glm::pow (10.0f, float(numDecimals)))\n    , order (o)\n  {\n    assert (this->order > 0);\n\n    QObject::connect (this->self, &QSlider::valueChanged, [this](int i) {\n      emit this->self->doubleValueChanged (this->toDouble (i, false));\n    });\n  }\n\n  double toDouble (int value, bool forceLinear) const\n  {\n    const unsigned short o = forceLinear ? 1 : this->order;\n\n    if (o == 1)\n    {\n      return double(value) / this->factor;\n    }\n    else\n    {\n      const double min = double(this->self->minimum ()) / this->factor;\n      const double max = double(this->self->maximum ()) / this->factor;\n      const double d = double(value) / this->factor;\n      const double norm = (d - min) / (max - min);\n      const double result = min + (glm::pow (float(norm), float(o)) * (max - min));\n\n      return result;\n    }\n  }\n\n  int toInt (double value, bool forceLinear) const\n  {\n    const unsigned short o = forceLinear ? 1 : this->order;\n\n    if (o == 1)\n    {\n      return int(std::round (value * this->factor));\n    }\n    else\n    {\n      const double min = double(this->self->minimum ()) / this->factor;\n      const double max = double(this->self->maximum ()) / this->factor;\n      const double norm = (value - min) / (max - min);\n      const double slope =\n        norm <= Util::epsilon () ? 0.0f : glm::pow (float(norm), 1.0f / float(o));\n\n      return int(std::round (this->factor * (min + (slope * (max - min)))));\n    }\n  }\n\n  double doubleValue () const { return this->toDouble (this->self->value (), false); }\n\n  double doubleSingleStep () const { return this->toDouble (this->self->singleStep (), true); }\n\n  void setDoubleValue (double v) { this->self->setValue (this->toInt (v, false)); }\n\n  void setDoubleRange (double min, double max)\n  {\n    this->self->setRange (this->toInt (min, true), this->toInt (max, true));\n  }\n\n  void setDoubleSingleStep (double v) { this->self->setSingleStep (this->toInt (v, true)); }\n\n  void setDoublePageStep (double v) { this->self->setPageStep (this->toInt (v, true)); }\n\n  int intValue () const { return this->self->QSlider::value (); }\n\n  int intSingleStep () const { return this->self->QSlider::singleStep (); }\n\n  void setIntValue (int v) { this->self->QSlider::setValue (v); }\n\n  void setIntRange (int min, int max) { this->self->QSlider::setRange (min, max); }\n\n  void setIntSingleStep (int v) { this->self->QSlider::setSingleStep (v); }\n\n  void setIntPageStep (int v) { this->self->QSlider::setPageStep (v); }\n\n  int value () const { return this->intValue (); }\n\n  int singleStep () const { return this->intSingleStep (); }\n\n  void setValue (int v) { this->setIntValue (v); }\n\n  void setRange (int min, int max) { this->setIntRange (min, max); }\n\n  void setSingleStep (int v) { this->setIntSingleStep (v); }\n\n  void setPageStep (int v) { this->setIntPageStep (v); }\n};\n\nDELEGATE2_BIG2_SELF (ViewDoubleSlider, unsigned short, unsigned short)\nDELEGATE_CONST (double, ViewDoubleSlider, doubleValue)\nDELEGATE_CONST (double, ViewDoubleSlider, doubleSingleStep)\nDELEGATE1 (void, ViewDoubleSlider, setDoubleValue, double)\nDELEGATE2 (void, ViewDoubleSlider, setDoubleRange, double, double)\nDELEGATE1 (void, ViewDoubleSlider, setDoubleSingleStep, double)\nDELEGATE1 (void, ViewDoubleSlider, setDoublePageStep, double)\nDELEGATE_CONST (int, ViewDoubleSlider, intValue)\nDELEGATE_CONST (int, ViewDoubleSlider, intSingleStep)\nDELEGATE1 (void, ViewDoubleSlider, setIntValue, int)\nDELEGATE2 (void, ViewDoubleSlider, setIntRange, int, int)\nDELEGATE1 (void, ViewDoubleSlider, setIntSingleStep, int)\nDELEGATE1 (void, ViewDoubleSlider, setIntPageStep, int)\nDELEGATE_CONST (int, ViewDoubleSlider, value)\nDELEGATE_CONST (int, ViewDoubleSlider, singleStep)\nDELEGATE1 (void, ViewDoubleSlider, setValue, int)\nDELEGATE2 (void, ViewDoubleSlider, setRange, int, int)\nDELEGATE1 (void, ViewDoubleSlider, setSingleStep, int)\nDELEGATE1 (void, ViewDoubleSlider, setPageStep, int)\n"
  },
  {
    "path": "lib/src/view/double-slider.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_DOUBLE_SLIDER\n#define DILAY_DOUBLE_SLIDER\n\n#include <QSlider>\n#include \"macro.hpp\"\n\nclass ViewDoubleSlider : public QSlider\n{\n  Q_OBJECT\npublic:\n  DECLARE_BIG2 (ViewDoubleSlider, unsigned short, unsigned short)\n\n  double doubleValue () const;\n  double doubleSingleStep () const;\n\n  void setDoubleValue (double);\n  void setDoubleRange (double, double);\n  void setDoubleSingleStep (double);\n  void setDoublePageStep (double);\n\n  int intValue () const;\n  int intSingleStep () const;\n\n  void setIntValue (int);\n  void setIntRange (int, int);\n  void setIntSingleStep (int);\n  void setIntPageStep (int);\n\nsignals:\n  void doubleValueChanged (double);\n\nprivate:\n  int value () const;\n  int singleStep () const;\n\n  void setValue (int);\n  void setRange (int, int);\n  void setSingleStep (int);\n  void setPageStep (int);\n\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/floor-plane.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"camera.hpp\"\n#include \"color.hpp\"\n#include \"config.hpp\"\n#include \"mesh.hpp\"\n#include \"render-mode.hpp\"\n#include \"view/floor-plane.hpp\"\n\nstruct ViewFloorPlane::Impl\n{\n  Mesh         mesh;\n  float        tileWidth;\n  unsigned int resolution;\n  bool         isActive;\n\n  Impl (const Config& config, const Camera& camera)\n    : resolution (0)\n    , isActive (false)\n  {\n    this->runFromConfig (config);\n    this->update (camera);\n  }\n\n  void render (Camera& camera) const\n  {\n    if (this->isActive)\n    {\n      this->mesh.renderLines (camera);\n    }\n  }\n\n  void update (const Camera& cam)\n  {\n    const float        w = cam.toWorld (float(cam.resolution ().x), glm::length (cam.position ()));\n    const unsigned int r = (unsigned int) (w / this->tileWidth) + 2;\n\n    if (r != this->resolution)\n    {\n      this->resolution = r;\n\n      this->mesh.reset ();\n      for (unsigned int j = 0; j < r; j++)\n      {\n        for (unsigned int i = 0; i < r; i++)\n        {\n          this->mesh.addVertex (\n            glm::vec3 (float(i) * this->tileWidth, 0.0f, float(j) * this->tileWidth));\n        }\n      }\n      for (unsigned int j = 1; j < r; j++)\n      {\n        this->mesh.addIndex (j - 1);\n        this->mesh.addIndex (j);\n        this->mesh.addIndex ((j - 1) * r);\n        this->mesh.addIndex (j * r);\n\n        for (unsigned int i = 1; i < r; i++)\n        {\n          this->mesh.addIndex ((j * r) + i - 1);\n          this->mesh.addIndex ((j * r) + i);\n          this->mesh.addIndex (((j - 1) * r) + i);\n          this->mesh.addIndex ((j * r) + i);\n        }\n      }\n      const float center = -0.5f * float(r - 1) * this->tileWidth;\n\n      this->mesh.position (glm::vec3 (center, 0.0f, center));\n      this->mesh.renderMode ().constantShading (true);\n      this->mesh.bufferData ();\n    }\n  }\n\n  void runFromConfig (const Config& config)\n  {\n    this->mesh.color (config.get<Color> (\"editor/floor-plane/color\"));\n\n    this->tileWidth = config.get<float> (\"editor/floor-plane/tile-width\");\n  }\n};\n\nDELEGATE2_BIG3 (ViewFloorPlane, const Config&, const Camera&)\nDELEGATE1_CONST (void, ViewFloorPlane, render, Camera&)\nDELEGATE1 (void, ViewFloorPlane, update, const Camera&)\nGETTER_CONST (bool, ViewFloorPlane, isActive)\nSETTER (bool, ViewFloorPlane, isActive)\nDELEGATE1 (void, ViewFloorPlane, runFromConfig, const Config&)\n"
  },
  {
    "path": "lib/src/view/floor-plane.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_FLOORPLANE\n#define DILAY_VIEW_FLOORPLANE\n\n#include \"configurable.hpp\"\n#include \"macro.hpp\"\n\nclass Camera;\nclass Config;\n\nclass ViewFloorPlane : public Configurable {\n  public:\n    DECLARE_BIG3 (ViewFloorPlane, const Config&, const Camera&)\n\n    void render   (Camera&) const;\n    void update   (const Camera&);\n    bool isActive () const;\n    void isActive (bool);\n\n  private:\n    IMPLEMENTATION\n\n    void runFromConfig (const Config&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/gl-widget.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCoreApplication>\n#include <QMouseEvent>\n#include <QPainter>\n#include <glm/glm.hpp>\n#include \"camera.hpp\"\n#include \"config.hpp\"\n#include \"mesh-util.hpp\"\n#include \"mesh.hpp\"\n#include \"opengl.hpp\"\n#include \"renderer.hpp\"\n#include \"scene.hpp\"\n#include \"state.hpp\"\n#include \"tool/move-camera.hpp\"\n#include \"view/axis.hpp\"\n#include \"view/context-menu.hpp\"\n#include \"view/floor-plane.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/info-pane.hpp\"\n#include \"view/info-pane/scene.hpp\"\n#include \"view/key-event.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/pointing-event.hpp\"\n#include \"view/tool-pane.hpp\"\n#include \"view/util.hpp\"\n\nstruct ViewGlWidget::Impl\n{\n  typedef std::unique_ptr<ToolMoveCamera> ToolMoveCameraPtr;\n  typedef std::unique_ptr<State>          StatePtr;\n  typedef std::unique_ptr<ViewAxis>       AxisPtr;\n  typedef std::unique_ptr<ViewFloorPlane> FloorPlanePtr;\n\n  ViewGlWidget*     self;\n  ViewMainWindow&   mainWindow;\n  Config&           config;\n  Cache&            cache;\n  ToolMoveCameraPtr _immediateMoveCamera;\n  StatePtr          _state;\n  AxisPtr           axis;\n  FloorPlanePtr     _floorPlane;\n  bool              tabletPressed;\n\n  Impl (ViewGlWidget* s, ViewMainWindow& mW, Config& cfg, Cache& cch)\n    : self (s)\n    , mainWindow (mW)\n    , config (cfg)\n    , cache (cch)\n    , tabletPressed (false)\n  {\n    this->self->setAutoFillBackground (false);\n  }\n\n  ~Impl ()\n  {\n    this->self->makeCurrent ();\n\n    this->_state.reset (nullptr);\n    this->axis.reset (nullptr);\n    this->_floorPlane.reset (nullptr);\n\n    this->self->doneCurrent ();\n  }\n\n  ToolMoveCamera& immediateMoveCamera ()\n  {\n    assert (this->_immediateMoveCamera);\n    return *this->_immediateMoveCamera;\n  }\n\n  State& state ()\n  {\n    assert (this->_state);\n    return *this->_state;\n  }\n\n  ViewFloorPlane& floorPlane ()\n  {\n    assert (this->_floorPlane);\n    return *this->_floorPlane;\n  }\n\n  glm::ivec2 cursorPosition ()\n  {\n    return ViewUtil::toIVec2 (this->self->mapFromGlobal (QCursor::pos ()));\n  }\n\n  void fromConfig ()\n  {\n    assert (this->axis);\n    assert (this->_immediateMoveCamera);\n\n    this->state ().fromConfig ();\n    this->axis->fromConfig (this->config);\n\n    this->floorPlane ().fromConfig (this->config);\n    this->floorPlane ().update (this->state ().camera ());\n\n    this->_immediateMoveCamera->fromConfig ();\n  }\n\n  void initializeGL ()\n  {\n    OpenGL::initializeFunctions (this->config.get<bool> (\"editor/use-geometry-shader\"));\n\n    this->_state.reset (new State (this->mainWindow, this->config, this->cache));\n    this->axis.reset (new ViewAxis (this->config));\n    this->_floorPlane.reset (new ViewFloorPlane (this->config, this->state ().camera ()));\n    this->_immediateMoveCamera.reset (new ToolMoveCamera (this->state (), true));\n    this->_immediateMoveCamera->initialize ();\n\n    this->self->setMouseTracking (true);\n    this->self->setTabletTracking (true);\n    this->initializeScene ();\n    this->mainWindow.toolPane ().forceWidth ();\n  }\n\n  void initializeScene ()\n  {\n    const QStringList arguments = QCoreApplication::arguments ();\n    if (arguments.size () > 1)\n    {\n      const std::string fileName = arguments.at (1).toStdString ();\n      if (this->state ().scene ().fromDlyFile (this->state ().config (), fileName) == false)\n      {\n        ViewUtil::error (this->mainWindow, QObject::tr (\"Could not open file.\"));\n      }\n    }\n    else\n    {\n      this->state ().scene ().newDynamicMesh (this->config, MeshUtil::icosphere (4));\n    }\n    this->mainWindow.update ();\n  }\n\n  void paintGL ()\n  {\n    QPainter painter (this->self);\n    painter.beginNativePainting ();\n\n    this->state ().camera ().renderer ().setupRendering ();\n    this->state ().scene ().render (this->state ().camera ());\n    this->floorPlane ().render (this->state ().camera ());\n\n    if (this->state ().hasTool ())\n    {\n      this->state ().tool ().render ();\n    }\n    this->axis->render (this->state ().camera ());\n\n    this->state ().camera ().renderer ().shutdownRendering ();\n    painter.endNativePainting ();\n\n    this->axis->render (this->state ().camera (), painter);\n    if (this->state ().hasTool ())\n    {\n      this->state ().tool ().paint (painter);\n    }\n  }\n\n  void resizeGL (int w, int h) { this->state ().camera ().updateResolution (glm::uvec2 (w, h)); }\n\n  void pointingEvent (const ViewPointingEvent& e)\n  {\n    if (e.valid ())\n    {\n      if (this->_immediateMoveCamera->pointingEvent (e) == ToolResponse::Redraw)\n      {\n        this->state ().handleToolResponse (ToolResponse::Redraw);\n        this->updateCursorInTool ();\n      }\n\n      if (this->state ().hasTool ())\n      {\n        this->state ().handleToolResponse (this->state ().tool ().pointingEvent (e));\n      }\n    }\n  }\n\n  void mouseMoveEvent (QMouseEvent* e)\n  {\n    if (this->tabletPressed == false)\n    {\n      this->pointingEvent (ViewPointingEvent (*e));\n    }\n  }\n\n  void mousePressEvent (QMouseEvent* e)\n  {\n    if (this->tabletPressed == false)\n    {\n      this->pointingEvent (ViewPointingEvent (*e));\n    }\n  }\n\n  void mouseReleaseEvent (QMouseEvent* e)\n  {\n    if (this->tabletPressed == false)\n    {\n      this->pointingEvent (ViewPointingEvent (*e));\n    }\n  }\n\n  void wheelEvent (QWheelEvent* e)\n  {\n    if (this->_immediateMoveCamera->wheelEvent (*e) == ToolResponse::Redraw)\n    {\n      this->state ().handleToolResponse (ToolResponse::Redraw);\n      this->updateCursorInTool ();\n    }\n  }\n\n  void tabletEvent (QTabletEvent* e)\n  {\n    const ViewPointingEvent pointingEvent (this->state ().config (), *e);\n\n    if (pointingEvent.pressEvent ())\n    {\n      this->tabletPressed = true;\n    }\n    else if (pointingEvent.releaseEvent ())\n    {\n      this->tabletPressed = false;\n    }\n    this->pointingEvent (pointingEvent);\n  }\n\n  void keyPressEvent (QKeyEvent* e)\n  {\n    const ViewKeyEvent keyEvent (*e, true);\n\n    if (this->state ().hasTool ())\n    {\n      this->state ().tool ().keyEvent (keyEvent);\n    }\n    this->self->QOpenGLWidget::keyPressEvent (e);\n  }\n\n  void keyReleaseEvent (QKeyEvent* e)\n  {\n    const ViewKeyEvent keyEvent (*e, false);\n\n    if (this->state ().hasTool ())\n    {\n      this->state ().tool ().keyEvent (keyEvent);\n    }\n    this->self->QOpenGLWidget::keyReleaseEvent (e);\n  }\n\n  void enterEvent (QEvent*) { this->self->setFocus (); }\n\n  void contextMenuEvent (QContextMenuEvent* event)\n  {\n    this->state ().resetTool ();\n\n    ViewContextMenu menu (this->mainWindow, ViewUtil::toIVec2 (event->pos ()));\n    menu.exec (this->self->mapToGlobal (event->pos ()));\n  }\n\n  void updateCursorInTool ()\n  {\n    if (this->state ().hasTool ())\n    {\n      this->state ().handleToolResponse (\n        this->state ().tool ().cursorUpdate (this->cursorPosition ()));\n    }\n  }\n};\n\nDELEGATE3_BIG2_SELF (ViewGlWidget, ViewMainWindow&, Config&, Cache&)\nDELEGATE (ToolMoveCamera&, ViewGlWidget, immediateMoveCamera)\nDELEGATE (State&, ViewGlWidget, state)\nDELEGATE (ViewFloorPlane&, ViewGlWidget, floorPlane)\nDELEGATE (glm::ivec2, ViewGlWidget, cursorPosition)\nDELEGATE (void, ViewGlWidget, fromConfig)\nDELEGATE (void, ViewGlWidget, initializeGL)\nDELEGATE2 (void, ViewGlWidget, resizeGL, int, int)\nDELEGATE (void, ViewGlWidget, paintGL)\nDELEGATE1 (void, ViewGlWidget, mouseMoveEvent, QMouseEvent*)\nDELEGATE1 (void, ViewGlWidget, mousePressEvent, QMouseEvent*)\nDELEGATE1 (void, ViewGlWidget, mouseReleaseEvent, QMouseEvent*)\nDELEGATE1 (void, ViewGlWidget, wheelEvent, QWheelEvent*)\nDELEGATE1 (void, ViewGlWidget, tabletEvent, QTabletEvent*)\nDELEGATE1 (void, ViewGlWidget, keyPressEvent, QKeyEvent*)\nDELEGATE1 (void, ViewGlWidget, keyReleaseEvent, QKeyEvent*)\nDELEGATE1 (void, ViewGlWidget, enterEvent, QEvent*)\nDELEGATE1 (void, ViewGlWidget, contextMenuEvent, QContextMenuEvent*)\n"
  },
  {
    "path": "lib/src/view/gl-widget.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_GL_WIDGET\n#define DILAY_VIEW_GL_WIDGET\n\n#include <QOpenGLWidget>\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n\nclass Cache;\nclass Config;\nclass State;\nclass ToolMoveCamera;\nclass ViewFloorPlane;\nclass ViewMainWindow;\n\nclass ViewGlWidget : public QOpenGLWidget\n{\n  Q_OBJECT\npublic:\n  DECLARE_BIG2 (ViewGlWidget, ViewMainWindow&, Config&, Cache&)\n\n  ToolMoveCamera& immediateMoveCamera ();\n  State&          state ();\n  ViewFloorPlane& floorPlane ();\n  glm::ivec2      cursorPosition ();\n  void            fromConfig ();\n\nprotected:\n  void initializeGL ();\n  void resizeGL (int, int);\n  void paintGL ();\n\n  void mouseMoveEvent (QMouseEvent*);\n  void mousePressEvent (QMouseEvent*);\n  void mouseReleaseEvent (QMouseEvent*);\n  void wheelEvent (QWheelEvent*);\n  void tabletEvent (QTabletEvent*);\n  void keyPressEvent (QKeyEvent*);\n  void keyReleaseEvent (QKeyEvent*);\n  void enterEvent (QEvent*);\n  void contextMenuEvent (QContextMenuEvent*);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/info-pane/scene.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QMenu>\n#include <QTreeWidget>\n#include <QVBoxLayout>\n#include \"../../scene.hpp\"\n#include \"dynamic/mesh.hpp\"\n#include \"sketch/mesh.hpp\"\n#include \"sketch/path.hpp\"\n#include \"state.hpp\"\n#include \"view/context-menu.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/info-pane/scene.hpp\"\n#include \"view/main-window.hpp\"\n\nnamespace\n{\n  static const int MeshType = QTreeWidgetItem::UserType + 0;\n  static const int SketchType = QTreeWidgetItem::UserType + 1;\n\n  struct MeshItem : public QTreeWidgetItem\n  {\n    DynamicMesh* mesh;\n\n    MeshItem (QTreeWidgetItem& parent, const QStringList& labels, DynamicMesh& m)\n      : QTreeWidgetItem (&parent, labels, MeshType)\n    {\n      this->mesh = &m;\n    }\n\n    MeshItem (QTreeWidget& parent, const QStringList& labels, DynamicMesh& m)\n      : QTreeWidgetItem (&parent, labels, MeshType)\n    {\n      this->mesh = &m;\n    }\n  };\n\n  struct SketchItem : public QTreeWidgetItem\n  {\n    SketchMesh* sketch;\n\n    SketchItem (QTreeWidgetItem& parent, const QStringList& labels, SketchMesh& s)\n      : QTreeWidgetItem (&parent, labels, SketchType)\n    {\n      this->sketch = &s;\n    }\n\n    SketchItem (QTreeWidget& parent, const QStringList& labels, SketchMesh& s)\n      : QTreeWidgetItem (&parent, labels, SketchType)\n    {\n      this->sketch = &s;\n    }\n  };\n}\n\nstruct ViewInfoPaneScene::Impl\n{\n  ViewInfoPaneScene* self;\n  ViewMainWindow&    mainWindow;\n  QTreeWidget*       tree;\n\n  Impl (ViewInfoPaneScene* s, ViewMainWindow& m)\n    : self (s)\n    , mainWindow (m)\n    , tree (new QTreeWidget (this->self))\n  {\n    this->self->setLayout (new QVBoxLayout);\n\n    this->tree->setHeaderLabels ({QObject::tr (\"Object\"), QObject::tr (\"Value\")});\n    this->tree->setRootIsDecorated (false);\n    this->tree->setContextMenuPolicy (Qt::CustomContextMenu);\n\n    QObject::connect (this->tree, &QTreeWidget::customContextMenuRequested,\n                      [this](const QPoint& p) { this->showMenu (p); });\n  }\n\n  void updateInfo ()\n  {\n    const auto showMesh = [this](DynamicMesh& mesh) {\n      MeshItem& item = *new MeshItem (*this->tree, {QObject::tr (\"Mesh\")}, mesh);\n\n      new MeshItem (item, {QObject::tr (\"Faces\"), QString::number (mesh.numFaces ())}, mesh);\n      new MeshItem (item, {QObject::tr (\"Vertices\"), QString::number (mesh.numVertices ())}, mesh);\n    };\n\n    const auto showSketch = [this](SketchMesh& sketch) {\n      SketchItem& item = *new SketchItem (*this->tree, {QObject::tr (\"Sketch\")}, sketch);\n\n      if (sketch.tree ().hasRoot ())\n      {\n        const unsigned int numNodes = sketch.tree ().root ().numNodes ();\n        const unsigned int numPaths = sketch.paths ().size ();\n        new SketchItem (item, {QObject::tr (\"Nodes\"), QString::number (numNodes)}, sketch);\n        new SketchItem (item, {QObject::tr (\"Paths\"), QString::number (numPaths)}, sketch);\n      }\n    };\n\n    this->tree->clear ();\n    this->mainWindow.glWidget ().state ().scene ().forEachMesh (showMesh);\n    this->mainWindow.glWidget ().state ().scene ().forEachMesh (showSketch);\n    this->tree->expandAll ();\n    this->tree->setItemsExpandable (false);\n\n    this->self->layout ()->addWidget (this->tree);\n  }\n\n  void showMenu (const QPoint& point)\n  {\n    QTreeWidgetItem* item = this->tree->itemAt (point);\n\n    if (item && item->type () == MeshType)\n    {\n      this->mainWindow.glWidget ().state ().resetTool ();\n\n      ViewContextMenu menu (this->mainWindow, *static_cast<MeshItem*> (item)->mesh);\n      menu.exec (this->tree->viewport ()->mapToGlobal (point));\n    }\n    else if (item && item->type () == SketchType)\n    {\n      this->mainWindow.glWidget ().state ().resetTool ();\n\n      ViewContextMenu menu (this->mainWindow, *static_cast<SketchItem*> (item)->sketch);\n      menu.exec (this->tree->viewport ()->mapToGlobal (point));\n    }\n  }\n};\n\nDELEGATE_BIG2_BASE (ViewInfoPaneScene, (ViewMainWindow & m, QWidget* p), (this, m), QWidget, (p))\nDELEGATE (void, ViewInfoPaneScene, updateInfo)\n"
  },
  {
    "path": "lib/src/view/info-pane/scene.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_INFO_PANE_SCENE\n#define DILAY_VIEW_INFO_PANE_SCENE\n\n#include <QWidget>\n#include \"macro.hpp\"\n\nclass ViewMainWindow;\n\nclass ViewInfoPaneScene : public QWidget\n{\npublic:\n  DECLARE_BIG2 (ViewInfoPaneScene, ViewMainWindow&, QWidget* = nullptr)\n\n  void updateInfo ();\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/info-pane.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QScrollArea>\n#include <QTabWidget>\n#include <QVBoxLayout>\n#include \"view/info-pane.hpp\"\n#include \"view/info-pane/scene.hpp\"\n#include \"view/tool-tip.hpp\"\n#include \"view/two-column-grid.hpp\"\n\nstruct ViewInfoPane::Impl\n{\n  ViewInfoPane*      self;\n  ViewMainWindow&    mainWindow;\n  ViewTwoColumnGrid& toolTip;\n  ViewInfoPaneScene& scene;\n\n  Impl (ViewInfoPane* s, ViewMainWindow& m)\n    : self (s)\n    , mainWindow (m)\n    , toolTip (*new ViewTwoColumnGrid)\n    , scene (*new ViewInfoPaneScene (m))\n  {\n    QScrollArea* scrollArea = new QScrollArea;\n    QTabWidget*  tabWidget = new QTabWidget;\n\n    tabWidget->addTab (this->initializeToolTipTab (), QObject::tr (\"Keys\"));\n    tabWidget->addTab (&this->scene, QObject::tr (\"Scene\"));\n\n    scrollArea->setWidgetResizable (true);\n    scrollArea->setWidget (tabWidget);\n\n    this->self->setWindowTitle (QObject::tr (\"Info\"));\n    this->self->setWidget (scrollArea);\n    this->self->setFeatures (DockWidgetMovable | DockWidgetClosable);\n    this->self->setAllowedAreas (Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);\n\n    this->resetToolTip ();\n  }\n\n  QWidget* initializeToolTipTab ()\n  {\n    ViewToolTip dummyTip;\n    dummyTip.add (ViewInputEvent::MouseMiddle, ViewInputModifier::Shift, \"01234567890123456789\");\n    this->addToolTip (dummyTip);\n    this->toolTip.setEqualColumnStretch ();\n\n    QWidget*     pane = new QWidget;\n    QVBoxLayout* layout = new QVBoxLayout (pane);\n\n    layout->setContentsMargins (0, 0, 0, 0);\n    layout->setSpacing (0);\n    layout->addWidget (&this->toolTip);\n    layout->addStretch (1);\n\n    return pane;\n  }\n\n  void addToolTip (const ViewToolTip& tip)\n  {\n    if (tip.isEmpty ())\n    {\n      return;\n    }\n    else if (this->toolTip.numRows () > 0)\n    {\n      this->toolTip.addSeparator ();\n    }\n    tip.render (\n      [this](const QString& action, const QString& tip) { this->toolTip.add (action, tip); });\n  }\n\n  void resetToolTip () { this->toolTip.reset (); }\n};\n\nDELEGATE_BIG2_BASE (ViewInfoPane, (ViewMainWindow & m, QWidget* p), (this, m), QDockWidget, (p))\nGETTER (ViewInfoPaneScene&, ViewInfoPane, scene)\nDELEGATE1 (void, ViewInfoPane, addToolTip, const ViewToolTip&)\nDELEGATE (void, ViewInfoPane, resetToolTip)\n"
  },
  {
    "path": "lib/src/view/info-pane.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_INFO_PANE\n#define DILAY_VIEW_INFO_PANE\n\n#include <QDockWidget>\n#include \"macro.hpp\"\n\nclass ViewInfoPaneScene;\nclass ViewMainWindow;\nclass ViewToolTip;\n\nclass ViewInfoPane : public QDockWidget\n{\npublic:\n  DECLARE_BIG2 (ViewInfoPane, ViewMainWindow&, QWidget* = nullptr)\n\n  ViewInfoPaneScene& scene ();\n  void               addToolTip (const ViewToolTip&);\n  void               resetToolTip ();\n  void               reset ();\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/input.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QKeySequence>\n#include <QObject>\n#include \"../util.hpp\"\n#include \"view/input.hpp\"\n\nnamespace ViewInput\n{\n  QKeySequence toQKeySequence (ViewInputEvent event, ViewInputModifier modifier)\n  {\n    unsigned int value = 0;\n\n    switch (modifier)\n    {\n      case ViewInputModifier::None:\n        break;\n      case ViewInputModifier::Ctrl:\n        value += Qt::CTRL;\n        break;\n      case ViewInputModifier::Shift:\n        value += Qt::SHIFT;\n        break;\n      case ViewInputModifier::Alt:\n        value += Qt::ALT;\n        break;\n    }\n\n    switch (event)\n    {\n      case ViewInputEvent::A:\n        value += Qt::Key_A;\n        break;\n      case ViewInputEvent::B:\n        value += Qt::Key_B;\n        break;\n      case ViewInputEvent::C:\n        value += Qt::Key_C;\n        break;\n      case ViewInputEvent::D:\n        value += Qt::Key_D;\n        break;\n      case ViewInputEvent::E:\n        value += Qt::Key_E;\n        break;\n      case ViewInputEvent::F:\n        value += Qt::Key_F;\n        break;\n      case ViewInputEvent::G:\n        value += Qt::Key_G;\n        break;\n      case ViewInputEvent::H:\n        value += Qt::Key_H;\n        break;\n      case ViewInputEvent::I:\n        value += Qt::Key_I;\n        break;\n      case ViewInputEvent::J:\n        value += Qt::Key_J;\n        break;\n      case ViewInputEvent::K:\n        value += Qt::Key_K;\n        break;\n      case ViewInputEvent::L:\n        value += Qt::Key_L;\n        break;\n      case ViewInputEvent::M:\n        value += Qt::Key_M;\n        break;\n      case ViewInputEvent::N:\n        value += Qt::Key_N;\n        break;\n      case ViewInputEvent::O:\n        value += Qt::Key_O;\n        break;\n      case ViewInputEvent::P:\n        value += Qt::Key_P;\n        break;\n      case ViewInputEvent::Q:\n        value += Qt::Key_Q;\n        break;\n      case ViewInputEvent::R:\n        value += Qt::Key_R;\n        break;\n      case ViewInputEvent::S:\n        value += Qt::Key_S;\n        break;\n      case ViewInputEvent::T:\n        value += Qt::Key_T;\n        break;\n      case ViewInputEvent::U:\n        value += Qt::Key_U;\n        break;\n      case ViewInputEvent::V:\n        value += Qt::Key_V;\n        break;\n      case ViewInputEvent::W:\n        value += Qt::Key_W;\n        break;\n      case ViewInputEvent::X:\n        value += Qt::Key_X;\n        break;\n      case ViewInputEvent::Y:\n        value += Qt::Key_Y;\n        break;\n      case ViewInputEvent::Z:\n        value += Qt::Key_Z;\n        break;\n      case ViewInputEvent::Esc:\n        value += Qt::Key_Escape;\n        break;\n      case ViewInputEvent::Space:\n        value += Qt::Key_Space;\n        break;\n      default:\n        DILAY_IMPOSSIBLE;\n    }\n    return QKeySequence (value);\n  }\n\n  QString toQString (ViewInputEvent event)\n  {\n    switch (event)\n    {\n      case ViewInputEvent::A:\n        return QObject::tr (\"A\");\n      case ViewInputEvent::B:\n        return QObject::tr (\"B\");\n      case ViewInputEvent::C:\n        return QObject::tr (\"C\");\n      case ViewInputEvent::D:\n        return QObject::tr (\"D\");\n      case ViewInputEvent::E:\n        return QObject::tr (\"E\");\n      case ViewInputEvent::F:\n        return QObject::tr (\"F\");\n      case ViewInputEvent::G:\n        return QObject::tr (\"G\");\n      case ViewInputEvent::H:\n        return QObject::tr (\"H\");\n      case ViewInputEvent::I:\n        return QObject::tr (\"I\");\n      case ViewInputEvent::J:\n        return QObject::tr (\"J\");\n      case ViewInputEvent::K:\n        return QObject::tr (\"K\");\n      case ViewInputEvent::L:\n        return QObject::tr (\"L\");\n      case ViewInputEvent::M:\n        return QObject::tr (\"M\");\n      case ViewInputEvent::N:\n        return QObject::tr (\"N\");\n      case ViewInputEvent::O:\n        return QObject::tr (\"O\");\n      case ViewInputEvent::P:\n        return QObject::tr (\"P\");\n      case ViewInputEvent::Q:\n        return QObject::tr (\"Q\");\n      case ViewInputEvent::R:\n        return QObject::tr (\"R\");\n      case ViewInputEvent::S:\n        return QObject::tr (\"S\");\n      case ViewInputEvent::T:\n        return QObject::tr (\"T\");\n      case ViewInputEvent::U:\n        return QObject::tr (\"U\");\n      case ViewInputEvent::V:\n        return QObject::tr (\"V\");\n      case ViewInputEvent::W:\n        return QObject::tr (\"W\");\n      case ViewInputEvent::X:\n        return QObject::tr (\"X\");\n      case ViewInputEvent::Y:\n        return QObject::tr (\"Y\");\n      case ViewInputEvent::Z:\n        return QObject::tr (\"Z\");\n      case ViewInputEvent::Esc:\n        return QObject::tr (\"Esc\");\n      case ViewInputEvent::Space:\n        return QObject::tr (\"Space\");\n      case ViewInputEvent::MouseLeft:\n        return QObject::tr (\"Left\");\n      case ViewInputEvent::MouseMiddle:\n        return QObject::tr (\"Middle\");\n      case ViewInputEvent::MouseWheel:\n        return QObject::tr (\"Wheel\");\n      case ViewInputEvent::MouseRight:\n        return QObject::tr (\"Right\");\n      default:\n        DILAY_IMPOSSIBLE;\n    }\n  }\n\n  QString toQString (ViewInputModifier modifier)\n  {\n    switch (modifier)\n    {\n      case ViewInputModifier::None:\n        return \"\";\n      case ViewInputModifier::Ctrl:\n        return QObject::tr (\"Ctrl\");\n      case ViewInputModifier::Shift:\n        return QObject::tr (\"Shift\");\n      case ViewInputModifier::Alt:\n        return QObject::tr (\"Alt\");\n      default:\n        DILAY_IMPOSSIBLE;\n    }\n  }\n\n  QString toQString (ViewInputEvent event, ViewInputModifier modifier)\n  {\n    const QString sEvent = toQString (event);\n    const QString sModifier = toQString (modifier);\n\n    if (sModifier.isEmpty ())\n    {\n      return sEvent;\n    }\n    else\n    {\n      return sModifier + QString (\"+\") + sEvent;\n    }\n  }\n}\n"
  },
  {
    "path": "lib/src/view/input.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_INPUT\n#define DILAY_VIEW_INPUT\n\nclass QKeySequence;\nclass QString;\n\nenum class ViewInputEvent\n{\n  A,\n  B,\n  C,\n  D,\n  E,\n  F,\n  G,\n  H,\n  I,\n  J,\n  K,\n  L,\n  M,\n  N,\n  O,\n  P,\n  Q,\n  R,\n  S,\n  T,\n  U,\n  V,\n  W,\n  X,\n  Y,\n  Z,\n  Esc,\n  Space,\n  MouseLeft,\n  MouseMiddle,\n  MouseWheel,\n  MouseRight\n};\n\nenum class ViewInputModifier\n{\n  None,\n  Ctrl,\n  Shift,\n  Alt\n};\n\nnamespace ViewInput\n{\n  QKeySequence toQKeySequence (ViewInputEvent, ViewInputModifier);\n  QString      toQString (ViewInputEvent);\n  QString      toQString (ViewInputModifier);\n  QString      toQString (ViewInputEvent, ViewInputModifier);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/view/key-event.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QKeyEvent>\n#include \"view/key-event.hpp\"\n\nViewKeyEvent::ViewKeyEvent (const QKeyEvent& event, bool press)\n  : _key (Qt::Key (event.key ()))\n  , _pressEvent (press)\n  , _releaseEvent (not press)\n{\n}\n"
  },
  {
    "path": "lib/src/view/key-event.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_KEY_EVENT\n#define DILAY_VIEW_KEY_EVENT\n\n#include <Qt>\n\nclass QKeyEvent;\n\nclass ViewKeyEvent\n{\npublic:\n  explicit ViewKeyEvent (const QKeyEvent&, bool);\n\n  Qt::Key key () const { return this->_key; }\n\n  bool pressEvent () const { return this->_pressEvent; }\n\n  bool releaseEvent () const { return this->_releaseEvent; }\n\nprivate:\n  Qt::Key _key;\n  bool    _pressEvent;\n  bool    _releaseEvent;\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/light.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"color.hpp\"\n#include \"view/light.hpp\"\n\nstruct ViewLight::Impl\n{\n  glm::vec3 position;\n  Color     color;\n  float     irradiance;\n\n  Impl (const glm::vec3& p, const Color& c, float i)\n    : position (p)\n    , color (c)\n    , irradiance (i)\n  {\n  }\n};\n\nDELEGATE3_BIG6 (ViewLight, const glm::vec3&, const Color&, float)\n\nGETTER_CONST (const glm::vec3&, ViewLight, position)\nGETTER_CONST (const Color&, ViewLight, color)\nGETTER_CONST (float, ViewLight, irradiance)\n\nSETTER (const glm::vec3&, ViewLight, position)\nSETTER (const Color&, ViewLight, color)\nSETTER (float, ViewLight, irradiance)\n"
  },
  {
    "path": "lib/src/view/light.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_LIGHT\n#define DILAY_VIEW_LIGHT\n\n#include <glm/fwd.hpp>\n#include \"macro.hpp\"\n\nclass Color;\n\nclass ViewLight\n{\npublic:\n  DECLARE_BIG6 (ViewLight, const glm::vec3&, const Color&, float);\n\n  const glm::vec3& position () const;\n  const Color&     color () const;\n  float            irradiance () const;\n\n  void position (const glm::vec3&);\n  void color (const Color&);\n  void irradiance (float);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/log.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QClipboard>\n#include <QDialog>\n#include <QDialogButtonBox>\n#include <QDir>\n#include <QGuiApplication>\n#include <QTextEdit>\n#include <QVBoxLayout>\n#include \"../util.hpp\"\n#include \"view/log.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/util.hpp\"\n\nQString ViewLog::logPath () { return QDir::temp ().filePath (\"dilay.log\"); }\n\nQString ViewLog::crashLogPath () { return QDir::temp ().filePath (\"dilay-crash.log\"); }\n\nvoid ViewLog::show (ViewMainWindow& window)\n{\n  QDialog      dialog (&window);\n  QVBoxLayout* layout = new QVBoxLayout;\n  QTextEdit*   textEdit = new QTextEdit (&dialog);\n\n  textEdit->setReadOnly (true);\n  textEdit->setLineWrapMode (QTextEdit::NoWrap);\n\n  if (QFile (ViewLog::logPath ()).exists ())\n  {\n    const std::string content = Util::readFile (ViewLog::logPath ().toStdString ());\n    textEdit->setPlainText (\"-- LOG ----------------------------------\");\n    textEdit->append (QString::fromStdString (content));\n    textEdit->append (\"\");\n  }\n\n  if (QFile (ViewLog::crashLogPath ()).exists ())\n  {\n    const std::string content = Util::readFile (ViewLog::crashLogPath ().toStdString ());\n    textEdit->append (\"-- CRASH LOG ----------------------------\");\n    textEdit->append (QString::fromStdString (content));\n    textEdit->append (\"\");\n  }\n\n  QDialogButtonBox* buttons = new QDialogButtonBox (QDialogButtonBox::Close);\n  QPushButton*      ctc =\n    buttons->addButton (QObject::tr (\"Copy to clipboard\"), QDialogButtonBox::ActionRole);\n\n  QObject::connect (buttons, &QDialogButtonBox::rejected, [&dialog]() { dialog.reject (); });\n\n  ViewUtil::connect (*ctc, [textEdit]() {\n    if (QGuiApplication::clipboard ())\n    {\n      QGuiApplication::clipboard ()->setText (textEdit->toPlainText ());\n    }\n    else\n    {\n      DILAY_WARN (\"Could not access clipboard\");\n    }\n  });\n\n  layout->addWidget (textEdit);\n  layout->addWidget (buttons);\n\n  dialog.setFixedWidth (100 * QFontMetrics (textEdit->currentFont ()).width (\"x\"));\n  dialog.setFixedHeight (25 * QFontMetrics (textEdit->currentFont ()).height ());\n  dialog.setLayout (layout);\n  dialog.setWindowTitle (QObject::tr (\"Log\"));\n  dialog.exec ();\n}\n"
  },
  {
    "path": "lib/src/view/log.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_LOG\n#define DILAY_VIEW_LOG\n\n#include <QString>\n\nclass ViewMainWindow;\n\nnamespace ViewLog\n{\n  QString logPath ();\n  QString crashLogPath ();\n  void    show (ViewMainWindow&);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/view/main-window.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCloseEvent>\n#include \"view/gl-widget.hpp\"\n#include \"view/info-pane.hpp\"\n#include \"view/info-pane/scene.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/menu-bar.hpp\"\n#include \"view/tool-pane.hpp\"\n#include \"view/util.hpp\"\n\nstruct ViewMainWindow::Impl\n{\n  ViewMainWindow* self;\n  ViewGlWidget&   glWidget;\n  ViewToolPane&   toolPane;\n  ViewInfoPane&   infoPane;\n\n  Impl (ViewMainWindow* s, Config& config, Cache& cache)\n    : self (s)\n    , glWidget (*new ViewGlWidget (*this->self, config, cache))\n    , toolPane (*new ViewToolPane (this->glWidget))\n    , infoPane (*new ViewInfoPane (*this->self))\n  {\n    this->self->setCentralWidget (&this->glWidget);\n    this->self->addDockWidget (Qt::LeftDockWidgetArea, &this->toolPane);\n    this->self->addDockWidget (Qt::RightDockWidgetArea, &this->infoPane);\n\n    ViewMenuBar::setup (*this->self, this->glWidget);\n  }\n\n  void update ()\n  {\n    this->self->QMainWindow::update ();\n    this->glWidget.update ();\n    this->infoPane.scene ().updateInfo ();\n  }\n\n  void closeEvent (QCloseEvent* e)\n  {\n#ifndef NDEBUG\n    e->accept ();\n#else\n    if (ViewUtil::question (*this->self, QObject::tr (\"Do you want to quit?\")))\n    {\n      e->accept ();\n    }\n    else\n    {\n      e->ignore ();\n    }\n#endif\n  }\n};\n\nDELEGATE2_BIG2_SELF (ViewMainWindow, Config&, Cache&)\nGETTER (ViewGlWidget&, ViewMainWindow, glWidget)\nGETTER (ViewToolPane&, ViewMainWindow, toolPane)\nGETTER (ViewInfoPane&, ViewMainWindow, infoPane)\nDELEGATE (void, ViewMainWindow, update)\nDELEGATE1 (void, ViewMainWindow, closeEvent, QCloseEvent*)\n"
  },
  {
    "path": "lib/src/view/main-window.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_MAIN_WINDOW\n#define DILAY_VIEW_MAIN_WINDOW\n\n#include <QMainWindow>\n#include \"macro.hpp\"\n\nclass Cache;\nclass Config;\nclass QCloseEvent;\nclass ViewGlWidget;\nclass ViewInfoPane;\nclass ViewToolPane;\n\nclass ViewMainWindow : public QMainWindow\n{\n  Q_OBJECT\npublic:\n  DECLARE_BIG2 (ViewMainWindow, Config&, Cache&)\n\n  ViewGlWidget& glWidget ();\n  ViewToolPane& toolPane ();\n  ViewInfoPane& infoPane ();\n  void          update ();\n\nprotected:\n  void closeEvent (QCloseEvent*);\n\nprivate:\n  IMPLEMENTATION\n};\n#endif\n"
  },
  {
    "path": "lib/src/view/menu-bar.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QDesktopServices>\n#include <QFileDialog>\n#include <QMenuBar>\n#include \"../util.hpp\"\n#include \"history.hpp\"\n#include \"scene.hpp\"\n#include \"state.hpp\"\n#include \"tool/move-camera.hpp\"\n#include \"view/configuration.hpp\"\n#include \"view/floor-plane.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/info-pane.hpp\"\n#include \"view/info-pane/scene.hpp\"\n#include \"view/log.hpp\"\n#include \"view/main-window.hpp\"\n#include \"view/menu-bar.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  QString getFileDialogPath (const Scene& scene)\n  {\n    return scene.hasFileName ()\n             ? QString (scene.fileName ().c_str ())\n             : QStandardPaths::standardLocations (QStandardPaths::HomeLocation).front ();\n  }\n\n  QString filterAllFiles () { return QObject::tr (\"All files (*.*)\"); }\n\n  QString filterDlyFiles () { return QObject::tr (\"Dilay files (*.dly)\"); }\n\n  QString filterObjFiles () { return QObject::tr (\"Wavefront files (*.obj)\"); }\n\n  QString fileDialogFilters ()\n  {\n    return filterAllFiles () + \";;\" + filterDlyFiles () + \";;\" + filterObjFiles ();\n  }\n\n  QString selectedFilter (const Scene& scene)\n  {\n    if (scene.hasFileName ())\n    {\n      if (Util::hasSuffix (scene.fileName (), \".dly\"))\n      {\n        return filterDlyFiles ();\n      }\n      else if (Util::hasSuffix (scene.fileName (), \".obj\"))\n      {\n        return filterObjFiles ();\n      }\n    }\n    return filterAllFiles ();\n  }\n}\n\nvoid ViewMenuBar::setup (ViewMainWindow& mainWindow, ViewGlWidget& glWidget)\n{\n  QMenuBar& menuBar = *mainWindow.menuBar ();\n  QMenu&    fileMenu = *menuBar.addMenu (QObject::tr (\"&File\"));\n  QMenu&    editMenu = *menuBar.addMenu (QObject::tr (\"&Edit\"));\n  QMenu&    viewMenu = *menuBar.addMenu (QObject::tr (\"&View\"));\n  QMenu&    helpMenu = *menuBar.addMenu (QObject::tr (\"&Help\"));\n\n  ViewUtil::addAction (\n    fileMenu, QObject::tr (\"&Open...\"), QKeySequence::Open, [&mainWindow, &glWidget]() {\n      Scene&            scene = glWidget.state ().scene ();\n      QString           filter = filterAllFiles ();\n      const std::string fileName =\n        QFileDialog::getOpenFileName (&mainWindow, QObject::tr (\"Open\"), getFileDialogPath (scene),\n                                      fileDialogFilters (), &filter,\n                                      QFileDialog::DontUseNativeDialog)\n          .toStdString ();\n      if (fileName.empty () == false)\n      {\n#ifndef NDEBUG\n        scene.reset ();\n        glWidget.state ().history ().reset ();\n#else\n      if (scene.isEmpty () == false) {\n        if (ViewUtil::question (mainWindow, QObject::tr (\"Replace existent scene?\"))) {\n          scene.reset ();\n          glWidget.state ().history ().reset ();\n        }\n        else {\n          glWidget.state ().history ().snapshotAll (scene);\n        }\n      }\n#endif\n        if (scene.fromDlyFile (glWidget.state ().config (), fileName) == false)\n        {\n          ViewUtil::error (mainWindow, QObject::tr (\"Could not open file.\"));\n        }\n        mainWindow.update ();\n      }\n    });\n\n  QAction& saveAsAction = ViewUtil::addAction (\n    fileMenu, QObject::tr (\"Save &as...\"), QKeySequence::SaveAs, [&mainWindow, &glWidget]() {\n      Scene&            scene = glWidget.state ().scene ();\n      QString           filter = selectedFilter (scene);\n      const std::string fileName =\n        QFileDialog::getSaveFileName (&mainWindow, QObject::tr (\"Save as\"),\n                                      getFileDialogPath (scene), fileDialogFilters (), &filter,\n                                      QFileDialog::DontUseNativeDialog)\n          .toStdString ();\n      if (fileName.empty () == false)\n      {\n        const bool saveAsObj = Util::hasSuffix (fileName, \".obj\") || filter == filterObjFiles ();\n\n        if (scene.toDlyFile (fileName, saveAsObj) == false)\n        {\n          ViewUtil::error (mainWindow, QObject::tr (\"Could not save to file.\"));\n        }\n        else if (saveAsObj && scene.numSketchMeshes () > 0)\n        {\n          ViewUtil::info (mainWindow,\n                          QObject::tr (\"Sketches are omitted when saving Wavefront files.\"));\n        }\n      }\n    });\n\n  ViewUtil::addAction (fileMenu, QObject::tr (\"&Save\"), QKeySequence::Save,\n                       [&mainWindow, &glWidget, &saveAsAction]() {\n                         Scene& scene = glWidget.state ().scene ();\n                         if (scene.hasFileName ())\n                         {\n                           const bool saveAsObj = Util::hasSuffix (scene.fileName (), \".obj\");\n\n                           if (scene.toDlyFile (saveAsObj) == false)\n                           {\n                             ViewUtil::error (mainWindow, QObject::tr (\"Could not save to file.\"));\n                           }\n                         }\n                         else\n                         {\n                           saveAsAction.trigger ();\n                         }\n                       });\n\n  fileMenu.addSeparator ();\n\n  ViewUtil::addAction (fileMenu, QObject::tr (\"&Quit\"), QKeySequence::Quit,\n                       [&mainWindow]() { mainWindow.close (); });\n\n  ViewUtil::addAction (editMenu, QObject::tr (\"&Undo\"), QKeySequence::Undo,\n                       [&glWidget]() { glWidget.state ().undo (); });\n\n  ViewUtil::addAction (editMenu, QObject::tr (\"&Redo\"), QKeySequence::Redo,\n                       [&glWidget]() { glWidget.state ().redo (); });\n\n  ViewUtil::addAction (\n    editMenu, QObject::tr (\"&Configuration...\"), QKeySequence (),\n    [&mainWindow, &glWidget]() { ViewConfiguration::show (mainWindow, glWidget); });\n\n  ViewUtil::addAction (viewMenu, QObject::tr (\"Toggle &info pane\"), Qt::CTRL + Qt::Key_I,\n                       [&mainWindow]() {\n                         if (mainWindow.infoPane ().isVisible ())\n                         {\n                           mainWindow.infoPane ().close ();\n                         }\n                         else\n                         {\n                           mainWindow.infoPane ().show ();\n                         }\n                       });\n\n  viewMenu.addSeparator ();\n\n  ViewUtil::addAction (viewMenu, QObject::tr (\"&Snap camera\"), Qt::SHIFT + Qt::Key_C,\n                       [&glWidget]() { glWidget.immediateMoveCamera ().snap (); });\n\n  ViewUtil::addAction (viewMenu, QObject::tr (\"Reset &gaze point\"), Qt::ALT + Qt::Key_C,\n                       [&glWidget]() { glWidget.immediateMoveCamera ().resetGazePoint (); });\n\n  viewMenu.addSeparator ();\n\n  ViewUtil::addAction (viewMenu, QObject::tr (\"Toggle &wireframe\"), Qt::Key_W,\n                       [&mainWindow, &glWidget]() {\n                         glWidget.state ().scene ().toggleWireframe ();\n                         mainWindow.update ();\n                       });\n\n  ViewUtil::addAction (viewMenu, QObject::tr (\"Toggle &shading\"), Qt::SHIFT + Qt::Key_W,\n                       [&mainWindow, &glWidget]() {\n                         glWidget.state ().scene ().toggleShading ();\n                         mainWindow.update ();\n                       });\n\n  ViewUtil::addCheckableAction (viewMenu, QObject::tr (\"Show &floor plane\"), QKeySequence (), false,\n                                [&mainWindow, &glWidget](bool a) {\n                                  glWidget.floorPlane ().isActive (a);\n                                  mainWindow.update ();\n                                });\n\n  ViewUtil::addAction (helpMenu, QObject::tr (\"&Manual...\"), QKeySequence (), [&mainWindow]() {\n    if (QDesktopServices::openUrl (QUrl (\"http://abau.org/dilay/manual.html\")) == false)\n    {\n      ViewUtil::error (mainWindow, QObject::tr (\"Could not open manual.\"));\n    }\n  });\n\n  ViewUtil::addAction (helpMenu, QObject::tr (\"&View log...\"), QKeySequence (),\n                       [&mainWindow]() { ViewLog::show (mainWindow); });\n\n  ViewUtil::addAction (helpMenu, QObject::tr (\"&About Dilay...\"), QKeySequence (), [&mainWindow]() {\n    ViewUtil::about (\n      mainWindow,\n      QString (\"Dilay \" DILAY_VERSION \" - \") + QObject::tr (\"a 3D sculpting application\") +\n        QString (\"\\n\\n\") + QString (\"Copyright © 2015-2018 Alexander Bau\") + QString (\"\\n\\n\") +\n        QObject::tr (\"Use and redistribute under the terms of the GNU General Public License\"));\n  });\n}\n"
  },
  {
    "path": "lib/src/view/menu-bar.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_MENU_BAR\n#define DILAY_VIEW_MENU_BAR\n\nclass ViewGlWidget;\nclass ViewMainWindow;\n\nnamespace ViewMenuBar\n{\n  void setup (ViewMainWindow&, ViewGlWidget&);\n}\n\n#endif\n"
  },
  {
    "path": "lib/src/view/pointing-event.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QGuiApplication>\n#include <QMouseEvent>\n#include <QTabletEvent>\n#include \"config.hpp\"\n#include \"view/pointing-event.hpp\"\n\nnamespace\n{\n  Qt::MouseButton fromButtons (const Qt::MouseButtons& buttons)\n  {\n    if (buttons.testFlag (Qt::LeftButton))\n    {\n      return Qt::LeftButton;\n    }\n    else if (buttons.testFlag (Qt::MiddleButton))\n    {\n      return Qt::MiddleButton;\n    }\n    else if (buttons.testFlag (Qt::RightButton))\n    {\n      return Qt::RightButton;\n    }\n    else\n    {\n      return Qt::NoButton;\n    }\n  }\n}\n\nViewPointingEvent::ViewPointingEvent (const QMouseEvent& event)\n  : _modifiers (event.modifiers ())\n  , _pressEvent (event.type () == QEvent::MouseButtonPress)\n  , _moveEvent (event.type () == QEvent::MouseMove)\n  , _releaseEvent (event.type () == QEvent::MouseButtonRelease)\n  , _button (fromButtons (this->_moveEvent ? event.buttons () : event.button ()))\n  , _position (glm::ivec2 (event.x (), event.y ()))\n  , _prevPosition (_position)\n  , _intensity (1.0f)\n{\n}\n\nViewPointingEvent::ViewPointingEvent (const Config& config, const QTabletEvent& event)\n  : _modifiers (QGuiApplication::queryKeyboardModifiers ())\n  , _pressEvent (event.type () == QEvent::TabletPress)\n  , _moveEvent (event.type () == QEvent::TabletMove)\n  , _releaseEvent (event.type () == QEvent::TabletRelease)\n  , _button (fromButtons (this->_moveEvent ? event.buttons () : event.button ()))\n  , _position (glm::ivec2 (event.x (), event.y ()))\n  , _prevPosition (_position)\n  , _intensity (config.get<float> (\"editor/tablet-pressure-intensity\") * event.pressure ())\n{\n}\n\nViewPointingEvent::ViewPointingEvent (const ViewPointingEvent& e, const glm::ivec2& prevPos)\n  : _modifiers (e._modifiers)\n  , _pressEvent (e._pressEvent)\n  , _moveEvent (e._moveEvent)\n  , _releaseEvent (e._releaseEvent)\n  , _button (e._button)\n  , _position (e._position)\n  , _prevPosition (prevPos)\n  , _intensity (e._intensity)\n{\n}\n\nbool ViewPointingEvent::valid () const\n{\n  return this->pressEvent () || this->moveEvent () || this->releaseEvent ();\n}\n\nbool ViewPointingEvent::leftButton () const { return this->_button == Qt::LeftButton; }\n\nbool ViewPointingEvent::middleButton () const { return this->_button == Qt::MiddleButton; }\n\nbool ViewPointingEvent::rightButton () const { return this->_button == Qt::RightButton; }\n"
  },
  {
    "path": "lib/src/view/pointing-event.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_POINTING_EVENT\n#define DILAY_VIEW_POINTING_EVENT\n\n#include <Qt>\n#include <glm/glm.hpp>\n\nclass Config;\nclass QMouseEvent;\nclass QTabletEvent;\n\nclass ViewPointingEvent\n{\npublic:\n  explicit ViewPointingEvent (const QMouseEvent&);\n  explicit ViewPointingEvent (const Config&, const QTabletEvent&);\n  explicit ViewPointingEvent (const ViewPointingEvent&, const glm::ivec2&);\n\n  bool valid () const;\n  bool leftButton () const;\n  bool middleButton () const;\n  bool rightButton () const;\n\n  Qt::KeyboardModifiers modifiers () const { return this->_modifiers; }\n\n  bool pressEvent () const { return this->_pressEvent; }\n\n  bool moveEvent () const { return this->_moveEvent; }\n\n  bool releaseEvent () const { return this->_releaseEvent; }\n\n  const glm::ivec2& position () const { return this->_position; }\n\n  glm::ivec2 delta () const { return this->_position - this->_prevPosition; }\n\n  float intensity () const { return this->_intensity; }\n\nprivate:\n  Qt::KeyboardModifiers _modifiers;\n  bool                  _pressEvent;\n  bool                  _moveEvent;\n  bool                  _releaseEvent;\n  Qt::MouseButton       _button;\n  glm::ivec2            _position;\n  glm::ivec2            _prevPosition;\n  float                 _intensity;\n};\n#endif\n"
  },
  {
    "path": "lib/src/view/resolution-slider.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"view/resolution-slider.hpp\"\n#include \"view/util.hpp\"\n\nstruct ViewResolutionSlider::Impl\n{\n  Impl (ViewResolutionSlider* s, float min, float max)\n  {\n    ViewDoubleSlider* doubleSlider = s;\n    ViewUtil::connect (*doubleSlider,\n                       [s, min, max](float r) { emit s->resolutionChanged (max + min - r); });\n  }\n};\n\nDELEGATE_BIG2_BASE (ViewResolutionSlider, (float min, float max), (this, min, max),\n                    ViewDoubleSlider, (2, 1))\n"
  },
  {
    "path": "lib/src/view/resolution-slider.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_RESOLUTION_SLIDER\n#define DILAY_VIEW_RESOLUTION_SLIDER\n\n#include \"view/double-slider.hpp\"\n\nclass ViewResolutionSlider : public ViewDoubleSlider\n{\n  Q_OBJECT\n\npublic:\n  DECLARE_BIG2 (ViewResolutionSlider, float, float)\n\nsignals:\n  void resolutionChanged (float);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/shortcut.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QShortcut>\n#include <QString>\n#include \"view/input.hpp\"\n#include \"view/shortcut.hpp\"\n\nnamespace\n{\n  typedef ViewShortcut::Call Call;\n}\n\nstruct ViewShortcut::Impl\n{\n  ViewInputEvent    event;\n  ViewInputModifier modifier;\n  QString           label;\n  Call              call;\n\n  Impl (const ViewInputEvent& e, const ViewInputModifier& m, const QString& l, Call&& c)\n    : event (e)\n    , modifier (m)\n    , label (l)\n    , call (std::move (c))\n  {\n  }\n\n  Impl (const ViewInputEvent& e, const QString& l, Call&& c)\n    : Impl (e, ViewInputModifier::None, l, std::move (c))\n  {\n  }\n\n  QShortcut& toQShortcut (QWidget& parent) const\n  {\n    const QKeySequence keys = ViewInput::toQKeySequence (this->event, this->modifier);\n    QShortcut&         shortcut = *new QShortcut (keys, &parent);\n\n    QObject::connect (&shortcut, &QShortcut::activated, this->call);\n\n    return shortcut;\n  }\n};\n\nDELEGATE3_BIG6 (ViewShortcut, const ViewInputEvent&, const QString&, Call&&)\nDELEGATE4_CONSTRUCTOR (ViewShortcut, const ViewInputEvent&, const ViewInputModifier&,\n                       const QString&, Call&&)\nGETTER_CONST (ViewInputEvent, ViewShortcut, event)\nGETTER_CONST (ViewInputModifier, ViewShortcut, modifier)\nGETTER_CONST (const QString&, ViewShortcut, label)\nGETTER_CONST (const Call&, ViewShortcut, call)\nDELEGATE1_CONST (QShortcut&, ViewShortcut, toQShortcut, QWidget&)\n"
  },
  {
    "path": "lib/src/view/shortcut.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_SHORTCUT\n#define DILAY_VIEW_SHORTCUT\n\n#include <functional>\n#include \"macro.hpp\"\n\nenum class ViewInputEvent;\nenum class ViewInputModifier;\nclass QShortcut;\nclass QString;\nclass QWidget;\n\nclass ViewShortcut\n{\npublic:\n  typedef std::function<void()> Call;\n\n  DECLARE_BIG6 (ViewShortcut, const ViewInputEvent&, const QString&, Call&&)\n\n  ViewShortcut (const ViewInputEvent&, const ViewInputModifier&, const QString&, Call&&);\n\n  ViewInputEvent    event () const;\n  ViewInputModifier modifier () const;\n  const QString&    label () const;\n  const Call&       call () const;\n  QShortcut&        toQShortcut (QWidget&) const;\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/tool-pane.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QPushButton>\n#include <QScrollArea>\n#include <QTabWidget>\n#include <QVBoxLayout>\n#include <unordered_map>\n#include \"state.hpp\"\n#include \"tools.hpp\"\n#include \"view/gl-widget.hpp\"\n#include \"view/tool-pane.hpp\"\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ViewToolPane::Impl\n{\n  typedef std::unordered_map<ToolKey, QPushButton*> Buttons;\n\n  ViewToolPane*      self;\n  ViewGlWidget&      glWidget;\n  QVBoxLayout&       layout;\n  QTabWidget&        toolSelection;\n  ViewTwoColumnGrid& properties;\n  Buttons            buttons;\n\n  Impl (ViewToolPane* s, ViewGlWidget& g)\n    : self (s)\n    , glWidget (g)\n    , layout (*new QVBoxLayout)\n    , toolSelection (*new QTabWidget)\n    , properties (*new ViewTwoColumnGrid)\n  {\n    QScrollArea* scrollArea = new QScrollArea;\n    QWidget*     pane = new QWidget;\n\n    this->initializeToolSelection ();\n\n    this->layout.setContentsMargins (0, 0, 0, 0);\n    this->layout.setSpacing (0);\n    this->layout.addWidget (&this->toolSelection);\n    this->layout.addWidget (&this->properties);\n    this->layout.addStretch (1);\n\n    scrollArea->setWidgetResizable (true);\n    scrollArea->setWidget (pane);\n    pane->setLayout (&this->layout);\n\n    this->self->setWindowTitle (QObject::tr (\"Tools\"));\n    this->self->setWidget (scrollArea);\n    this->self->setFeatures (DockWidgetMovable);\n    this->self->setAllowedAreas (Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);\n  }\n\n  void initializeToolSelection ()\n  {\n    this->toolSelection.addTab (this->initalizeSculptSelection (), QObject::tr (\"Sculpt\"));\n    this->toolSelection.addTab (this->initalizeSketchSelection (), QObject::tr (\"Sketch\"));\n\n    QObject::connect (&this->toolSelection, &QTabWidget::currentChanged, [this](int) {\n      this->glWidget.state ().resetTool ();\n      ViewUtil::adjustSize (this->toolSelection);\n    });\n  }\n\n  void addToolButton (ToolKey key, QLayout* layout, const QString& name)\n  {\n    QPushButton& button = ViewUtil::pushButton (name);\n    this->buttons.emplace (key, &button);\n    button.setCheckable (true);\n\n    ViewUtil::connect (button, [this, key]() { this->glWidget.state ().setTool (key); });\n    layout->addWidget (&button);\n  }\n\n  QWidget* initalizeSculptSelection ()\n  {\n    QWidget*     toolPane = new QWidget;\n    QVBoxLayout* toolPaneLayout = new QVBoxLayout;\n\n    toolPane->setLayout (toolPaneLayout);\n    this->addToolButton (ToolKey::NewMesh, toolPaneLayout, QObject::tr (\"01234567890123456789\"));\n    this->addToolButton (ToolKey::DeleteMesh, toolPaneLayout, QObject::tr (\"Delete mesh\"));\n    this->addToolButton (ToolKey::TransformMesh, toolPaneLayout, QObject::tr (\"Transform mesh\"));\n    toolPaneLayout->addWidget (&ViewUtil::horizontalLine ());\n    this->addToolButton (ToolKey::SculptDraw, toolPaneLayout, QObject::tr (\"Draw\"));\n    this->addToolButton (ToolKey::SculptCrease, toolPaneLayout, QObject::tr (\"Crease\"));\n    this->addToolButton (ToolKey::SculptGrab, toolPaneLayout, QObject::tr (\"Grab\"));\n    this->addToolButton (ToolKey::SculptPinch, toolPaneLayout, QObject::tr (\"Pinch\"));\n    toolPaneLayout->addWidget (&ViewUtil::horizontalLine ());\n    this->addToolButton (ToolKey::SculptSmooth, toolPaneLayout, QObject::tr (\"Smooth\"));\n    this->addToolButton (ToolKey::SculptFlatten, toolPaneLayout, QObject::tr (\"Flatten\"));\n    this->addToolButton (ToolKey::SculptReduce, toolPaneLayout, QObject::tr (\"Reduce\"));\n    toolPaneLayout->addWidget (&ViewUtil::horizontalLine ());\n    this->addToolButton (ToolKey::Remesh, toolPaneLayout, QObject::tr (\"Remesh\"));\n    this->addToolButton (ToolKey::TrimMesh, toolPaneLayout, QObject::tr (\"Trim\"));\n\n    toolPaneLayout->addStretch (1);\n\n    return toolPane;\n  }\n\n  QWidget* initalizeSketchSelection ()\n  {\n    QWidget*     toolPane = new QWidget;\n    QVBoxLayout* toolPaneLayout = new QVBoxLayout;\n\n    toolPane->setLayout (toolPaneLayout);\n    this->addToolButton (ToolKey::EditSketch, toolPaneLayout, QObject::tr (\"Edit sketch\"));\n    this->addToolButton (ToolKey::DeleteSketch, toolPaneLayout, QObject::tr (\"Delete sketch\"));\n    toolPaneLayout->addWidget (&ViewUtil::horizontalLine ());\n    this->addToolButton (ToolKey::SketchSpheres, toolPaneLayout, QObject::tr (\"Sketch spheres\"));\n    toolPaneLayout->addWidget (&ViewUtil::horizontalLine ());\n    this->addToolButton (ToolKey::ConvertSketch, toolPaneLayout, QObject::tr (\"Convert sketch\"));\n\n    toolPaneLayout->addStretch (1);\n\n    return toolPane;\n  }\n\n  void forceWidth ()\n  {\n    const auto it = this->buttons.find (ToolKey::NewMesh);\n    assert (it != this->buttons.end ());\n\n    it->second->setText (QObject::tr (\"New mesh\"));\n  }\n\n  ViewToolPaneSelection selection () const\n  {\n    switch (this->toolSelection.currentIndex ())\n    {\n      case 0:\n        return ViewToolPaneSelection::Sculpt;\n      case 1:\n        return ViewToolPaneSelection::Sketch;\n      default:\n        DILAY_IMPOSSIBLE\n    }\n  }\n\n  void setButtonState (ToolKey key, bool state)\n  {\n    auto it = this->buttons.find (key);\n    if (it != this->buttons.end ())\n    {\n      it->second->setChecked (state);\n    }\n  }\n\n  QString buttonText (ToolKey key) const\n  {\n    auto it = this->buttons.find (key);\n    assert (it != this->buttons.end ());\n    return it->second->text ();\n  }\n};\n\nDELEGATE_BIG2_BASE (ViewToolPane, (ViewGlWidget & g, QWidget* p), (this, g), QDockWidget, (p))\nGETTER (ViewTwoColumnGrid&, ViewToolPane, properties)\nDELEGATE (void, ViewToolPane, forceWidth)\nDELEGATE_CONST (ViewToolPaneSelection, ViewToolPane, selection)\nDELEGATE2 (void, ViewToolPane, setButtonState, ToolKey, bool)\nDELEGATE1_CONST (QString, ViewToolPane, buttonText, ToolKey)\n"
  },
  {
    "path": "lib/src/view/tool-pane.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_TOOL_PANE\n#define DILAY_VIEW_TOOL_PANE\n\n#include <QDockWidget>\n#include \"macro.hpp\"\n\nenum class ToolKey;\nclass QPushButton;\nclass ViewGlWidget;\nclass ViewTwoColumnGrid;\n\nenum class ViewToolPaneSelection\n{\n  Sculpt,\n  Sketch\n};\n\nclass ViewToolPane : public QDockWidget\n{\npublic:\n  DECLARE_BIG2 (ViewToolPane, ViewGlWidget&, QWidget* = nullptr)\n\n  ViewTwoColumnGrid&    properties ();\n  void                  forceWidth ();\n  ViewToolPaneSelection selection () const;\n  void                  setButtonState (ToolKey, bool);\n  QString               buttonText (ToolKey) const;\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/tool-tip.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QKeySequence>\n#include <QObject>\n#include \"../util.hpp\"\n#include \"view/tool-tip.hpp\"\n\nstruct ViewToolTip::Impl\n{\n  typedef std::tuple<ViewInputEvent, ViewInputModifier, QString> Tip;\n  std::vector<Tip>                                               tips;\n\n  void render (const std::function<void(const QString&, const QString&)>& f) const\n  {\n    for (auto& t : this->tips)\n    {\n      f (ViewInput::toQString (std::get<0> (t), std::get<1> (t)), std::get<2> (t));\n    }\n  }\n\n  void add (ViewInputEvent event, ViewInputModifier modifier, const QString& tip)\n  {\n    this->tips.push_back (std::make_tuple (event, modifier, tip));\n  }\n\n  void add (ViewInputEvent event, const QString& tip)\n  {\n    this->add (event, ViewInputModifier::None, tip);\n  }\n\n  void reset () { this->tips.clear (); }\n\n  bool isEmpty () const { return this->tips.empty (); }\n};\n\nDELEGATE_BIG6 (ViewToolTip)\nDELEGATE1_CONST (void, ViewToolTip, render,\n                 const std::function<void(const QString&, const QString&)>&)\nDELEGATE3 (void, ViewToolTip, add, ViewInputEvent, ViewInputModifier, const QString&)\nDELEGATE2 (void, ViewToolTip, add, ViewInputEvent, const QString&)\nDELEGATE (void, ViewToolTip, reset)\nDELEGATE_CONST (bool, ViewToolTip, isEmpty)\n"
  },
  {
    "path": "lib/src/view/tool-tip.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_TOOL_TIP\n#define DILAY_VIEW_TOOL_TIP\n\n#include <functional>\n#include \"macro.hpp\"\n#include \"view/input.hpp\"\n\nclass ViewToolTip\n{\npublic:\n  DECLARE_BIG6 (ViewToolTip)\n\n  void render (const std::function<void(const QString&, const QString&)>&) const;\n\n  void add (ViewInputEvent, ViewInputModifier, const QString&);\n  void add (ViewInputEvent, const QString&);\n  void reset ();\n  bool isEmpty () const;\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/two-column-grid.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QButtonGroup>\n#include <QGridLayout>\n#include <QLabel>\n#include <QRadioButton>\n#include <QVBoxLayout>\n#include \"view/two-column-grid.hpp\"\n#include \"view/util.hpp\"\n\nstruct ViewTwoColumnGrid::Impl\n{\n  ViewTwoColumnGrid* self;\n  QGridLayout&       layout;\n  unsigned int       numRows;\n\n  Impl (ViewTwoColumnGrid* s)\n    : self (s)\n    , layout (*new QGridLayout (this->self))\n    , numRows (0)\n  {\n    this->layout.setColumnStretch (0, 0);\n    this->layout.setColumnStretch (1, 1);\n  }\n\n  void setEqualColumnStretch ()\n  {\n    this->layout.setColumnStretch (0, 1);\n    this->layout.setColumnStretch (1, 1);\n  }\n\n  void add (QWidget& widget)\n  {\n    this->layout.addWidget (&widget, this->numRows, 0, 1, 2);\n    this->layout.setRowStretch (this->numRows, 0);\n    this->numRows++;\n  }\n\n  void add (const QString& labelLeft, const QString& labelRight)\n  {\n    this->add (*new QLabel (labelLeft), *new QLabel (labelRight));\n  }\n\n  void add (const QString& label, QWidget& widget) { this->add (*new QLabel (label), widget); }\n\n  void add (QWidget& w1, QWidget& w2)\n  {\n    this->layout.addWidget (&w1, this->numRows, 0);\n    this->layout.addWidget (&w2, this->numRows, 1);\n    this->layout.setRowStretch (this->numRows, 0);\n    this->numRows++;\n  }\n\n  void add (QButtonGroup& group)\n  {\n    for (QAbstractButton* button : group.buttons ())\n    {\n      this->add (*button);\n    }\n  }\n\n  void addStacked (const QString& labelText, QWidget& widget)\n  {\n    QVBoxLayout& stack = *new QVBoxLayout;\n    QLabel&      label = *new QLabel (labelText);\n\n    label.setAlignment (Qt::AlignHCenter);\n    stack.addWidget (&label);\n    stack.addWidget (&widget);\n\n    this->layout.addLayout (&stack, this->numRows, 0, 1, 2);\n    this->layout.setRowStretch (this->numRows, 0);\n    this->numRows++;\n  }\n\n  void addStacked (const QString& labelText, QButtonGroup& group)\n  {\n    QVBoxLayout& stack = *new QVBoxLayout;\n    QLabel&      label = *new QLabel (labelText);\n\n    label.setAlignment (Qt::AlignHCenter);\n    stack.addWidget (&label);\n\n    for (QAbstractButton* button : group.buttons ())\n    {\n      stack.addWidget (button);\n    }\n\n    this->layout.addLayout (&stack, this->numRows, 0, 1, 2);\n    this->layout.setRowStretch (this->numRows, 0);\n    this->numRows++;\n  }\n\n  void addLeft (const QString& label) { this->add (label, *new QWidget); }\n\n  void addCenter (const QString& labelText)\n  {\n    QLabel& label = *new QLabel (labelText);\n    label.setAlignment (Qt::AlignHCenter);\n\n    this->add (label);\n  }\n\n  void addStretcher ()\n  {\n    this->add (*new QWidget, *new QWidget);\n    this->layout.setRowStretch (this->numRows, 1);\n  }\n\n  void addSeparator () { this->add (ViewUtil::horizontalLine ()); }\n\n  void reset ()\n  {\n    QWidget* widget = nullptr;\n    while ((widget = this->self->findChild<QWidget*> ()))\n    {\n      delete widget;\n    }\n    this->numRows = 0;\n  }\n};\n\nDELEGATE_BIG2_BASE (ViewTwoColumnGrid, (QWidget * p), (this), QWidget, (p))\nGETTER_CONST (unsigned int, ViewTwoColumnGrid, numRows)\nDELEGATE (void, ViewTwoColumnGrid, setEqualColumnStretch)\nDELEGATE1 (void, ViewTwoColumnGrid, add, QWidget&)\nDELEGATE2 (void, ViewTwoColumnGrid, add, const QString&, const QString&)\nDELEGATE2 (void, ViewTwoColumnGrid, add, const QString&, QWidget&)\nDELEGATE2 (void, ViewTwoColumnGrid, add, QWidget&, QWidget&)\nDELEGATE1 (void, ViewTwoColumnGrid, add, QButtonGroup&)\nDELEGATE2 (void, ViewTwoColumnGrid, addStacked, const QString&, QWidget&)\nDELEGATE2 (void, ViewTwoColumnGrid, addStacked, const QString&, QButtonGroup&)\nDELEGATE1 (void, ViewTwoColumnGrid, addLeft, const QString&)\nDELEGATE1 (void, ViewTwoColumnGrid, addCenter, const QString&)\nDELEGATE (void, ViewTwoColumnGrid, addStretcher)\nDELEGATE (void, ViewTwoColumnGrid, addSeparator)\nDELEGATE (void, ViewTwoColumnGrid, reset)\n"
  },
  {
    "path": "lib/src/view/two-column-grid.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_TWO_COLUMN_GRID\n#define DILAY_VIEW_TWO_COLUMN_GRID\n\n#include <QWidget>\n#include <vector>\n#include \"macro.hpp\"\n\nclass QButtonGroup;\nclass QString;\n\nclass ViewTwoColumnGrid : public QWidget\n{\npublic:\n  DECLARE_BIG2 (ViewTwoColumnGrid, QWidget* = nullptr)\n\n  unsigned int numRows () const;\n  void         setEqualColumnStretch ();\n\n  void add (QWidget&);\n  void add (const QString&, const QString&);\n  void add (const QString&, QWidget&);\n  void add (QWidget&, QWidget&);\n  void add (QButtonGroup&);\n  void addStacked (const QString&, QWidget&);\n  void addStacked (const QString&, QButtonGroup&);\n  void addLeft (const QString&);\n  void addCenter (const QString&);\n  void addStretcher ();\n  void addSeparator ();\n  void reset ();\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/util.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QAction>\n#include <QButtonGroup>\n#include <QCheckBox>\n#include <QDoubleSpinBox>\n#include <QDoubleValidator>\n#include <QIntValidator>\n#include <QLineEdit>\n#include <QMenu>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QRadioButton>\n#include <QSlider>\n#include <QTabWidget>\n#include <QToolButton>\n#include <glm/glm.hpp>\n#include \"../util.hpp\"\n#include \"view/double-slider.hpp\"\n#include \"view/resolution-slider.hpp\"\n#include \"view/util.hpp\"\n\nnamespace\n{\n  void setupDoubleSlider (ViewDoubleSlider& slider, float min, float value, float max)\n  {\n    slider.setDoubleRange (min, max);\n    slider.setDoubleValue (value);\n    slider.setDoubleSingleStep ((max - min) / 10.0f);\n    slider.setDoublePageStep ((max - min) / 10.0f);\n    slider.setTracking (true);\n    slider.setOrientation (Qt::Horizontal);\n  }\n}\n\nQSpinBox& ViewUtil::spinBox (int min, int value, int max, int stepSize)\n{\n  QSpinBox& spinBox = *new QSpinBox;\n  spinBox.setRange (min, max);\n  spinBox.setValue (value);\n  spinBox.setSingleStep (stepSize);\n  return spinBox;\n}\n\nQDoubleSpinBox& ViewUtil::spinBox (float min, float value, float max, float stepSize)\n{\n  QDoubleSpinBox& spinBox = *new QDoubleSpinBox;\n  spinBox.setValue (double(value));\n  spinBox.setRange (min, max);\n  spinBox.setSingleStep (stepSize);\n  spinBox.setDecimals (2);\n  return spinBox;\n}\n\nQPushButton& ViewUtil::pushButton (const QString& label, bool isDefaultButton)\n{\n  QPushButton& button = *new QPushButton (label);\n  button.setDefault (isDefaultButton);\n  return button;\n}\n\nQToolButton& ViewUtil::toolButton (const QString& label)\n{\n  QToolButton& button = *new QToolButton ();\n  button.setText (label);\n  return button;\n}\n\nQRadioButton& ViewUtil::radioButton (const QString& label, bool isChecked)\n{\n  QRadioButton& button = *new QRadioButton (label);\n  button.setChecked (isChecked);\n  return button;\n}\n\nQCheckBox& ViewUtil::checkBox (const QString& label, bool isChecked)\n{\n  QCheckBox& box = *new QCheckBox (label);\n  box.setChecked (isChecked);\n  return box;\n}\n\nQSlider& ViewUtil::slider (int min, int value, int max)\n{\n  QSlider& slider = *new QSlider;\n  slider.setRange (min, max);\n  slider.setValue (value);\n  slider.setSingleStep (1);\n  slider.setPageStep (1);\n  slider.setTracking (true);\n  slider.setOrientation (Qt::Horizontal);\n  return slider;\n}\n\nViewDoubleSlider& ViewUtil::slider (unsigned short numDecimals, float min, float value, float max,\n                                    unsigned short order)\n{\n  ViewDoubleSlider& slider = *new ViewDoubleSlider (numDecimals, order);\n  setupDoubleSlider (slider, min, value, max);\n  return slider;\n}\n\nViewResolutionSlider& ViewUtil::resolutionSlider (float min, float value, float max)\n{\n  ViewResolutionSlider& slider = *new ViewResolutionSlider (min, max);\n  setupDoubleSlider (slider, min, max + min - value, max);\n  return slider;\n}\n\nQButtonGroup& ViewUtil::buttonGroup (const std::vector<QString>& labels)\n{\n  QButtonGroup& group = *new QButtonGroup;\n  int           id = 0;\n  for (const QString& label : labels)\n  {\n    QRadioButton& button = ViewUtil::radioButton (label);\n\n    group.addButton (&button, id);\n    id++;\n  }\n  return group;\n}\n\nQFrame& ViewUtil::horizontalLine ()\n{\n  QFrame& frame = *new QFrame;\n  frame.setFrameShape (QFrame::HLine);\n  frame.setFrameShadow (QFrame::Sunken);\n  return frame;\n}\n\nQWidget& ViewUtil::emptyWidget () { return *new QWidget; }\n\nQLineEdit& ViewUtil::lineEdit (float value, unsigned short numDecimals)\n{\n  return ViewUtil::lineEdit (Util::minFloat (), value, Util::maxFloat (), numDecimals);\n}\n\nQLineEdit& ViewUtil::lineEdit (float min, float value, float max, unsigned short numDecimals)\n{\n  QLineEdit&        edit = *new QLineEdit;\n  QDoubleValidator& validator = *new QDoubleValidator (&edit);\n\n  validator.setRange (min, max, numDecimals);\n  edit.setValidator (&validator);\n  edit.setText (QString::number (value, 'f', numDecimals));\n\n  return edit;\n}\n\nQLineEdit& ViewUtil::lineEdit (int value)\n{\n  QLineEdit& edit = *new QLineEdit;\n\n  edit.setText (QString::number (value));\n\n  return edit;\n}\n\nQLineEdit& ViewUtil::lineEdit (int min, int value, int max)\n{\n  QLineEdit&     edit = ViewUtil::lineEdit (value);\n  QIntValidator& validator = *new QIntValidator (&edit);\n\n  validator.setRange (min, max);\n  edit.setValidator (&validator);\n\n  return edit;\n}\n\nglm::uvec2 ViewUtil::toUVec2 (const QPoint& p)\n{\n  assert (p.x () >= 0);\n  assert (p.y () >= 0);\n  return glm::uvec2 (p.x (), p.y ());\n}\n\nglm::ivec2 ViewUtil::toIVec2 (const QPoint& p) { return glm::ivec2 (p.x (), p.y ()); }\n\nQPoint ViewUtil::toQPoint (const glm::uvec2& p) { return QPoint (int(p.x), int(p.y)); }\n\nQPoint ViewUtil::toQPoint (const glm::ivec2& p) { return QPoint (p.x, p.y); }\n\nvoid ViewUtil::connect (const QSpinBox& s, const std::function<void(int)>& f)\n{\n  void (QSpinBox::*ptr) (int) = &QSpinBox::valueChanged;\n  QObject::connect (&s, ptr, f);\n}\n\nvoid ViewUtil::connect (const QDoubleSpinBox& s, const std::function<void(double)>& f)\n{\n  void (QDoubleSpinBox::*ptr) (double) = &QDoubleSpinBox::valueChanged;\n  QObject::connect (&s, ptr, f);\n}\n\nvoid ViewUtil::connect (const QPushButton& b, const std::function<void()>& f)\n{\n  QObject::connect (&b, &QPushButton::released, f);\n}\n\nvoid ViewUtil::connect (const QButtonGroup& g, int initial, const std::function<void(int)>& f)\n{\n  void (QButtonGroup::*ptr) (int) = &QButtonGroup::buttonReleased;\n  QObject::connect (&g, ptr, f);\n  g.button (initial)->click ();\n}\n\nvoid ViewUtil::connect (const QCheckBox& c, const std::function<void(bool)>& f)\n{\n  QObject::connect (&c, &QCheckBox::stateChanged, [f](int state) {\n    if (state == Qt::Unchecked)\n    {\n      f (false);\n    }\n    else if (state == Qt::Checked)\n    {\n      f (true);\n    }\n  });\n}\n\nvoid ViewUtil::connect (const QRadioButton& r, const std::function<void(bool)>& f)\n{\n  QObject::connect (&r, &QRadioButton::clicked, f);\n}\n\nvoid ViewUtil::connect (const QSlider& s, const std::function<void(int)>& f)\n{\n  QObject::connect (&s, &QSlider::valueChanged, f);\n}\n\nvoid ViewUtil::connect (const ViewResolutionSlider& s, const std::function<void(float)>& f)\n{\n  QObject::connect (&s, &ViewResolutionSlider::resolutionChanged, f);\n}\n\nvoid ViewUtil::connect (const ViewDoubleSlider& s, const std::function<void(float)>& f)\n{\n  QObject::connect (&s, &ViewDoubleSlider::doubleValueChanged, f);\n}\n\nvoid ViewUtil::connect (const QAction& a, const std::function<void()>& f)\n{\n  QObject::connect (&a, &QAction::triggered, f);\n}\n\nvoid ViewUtil::connectFloat (const QLineEdit& e, const std::function<void(float)>& f)\n{\n  QObject::connect (&e, &QLineEdit::textEdited, [&e, f](const QString& text) {\n    if (e.hasAcceptableInput ())\n    {\n      bool  ok;\n      float value = text.toFloat (&ok);\n      assert (ok);\n      f (value);\n    }\n  });\n}\n\nvoid ViewUtil::connectInt (const QLineEdit& e, const std::function<void(int)>& f)\n{\n  QObject::connect (&e, &QLineEdit::textEdited, [&e, f](const QString& text) {\n    if (e.hasAcceptableInput ())\n    {\n      bool  ok;\n      float value = text.toInt (&ok);\n      assert (ok);\n      f (value);\n    }\n  });\n}\n\nQWidget& ViewUtil::stretcher (bool horizontal, bool vertical)\n{\n  assert (horizontal || vertical);\n  QWidget& widget = *new QWidget ();\n  widget.setSizePolicy (horizontal ? QSizePolicy::Expanding : QSizePolicy::Preferred,\n                        vertical ? QSizePolicy::Expanding : QSizePolicy::Preferred);\n  return widget;\n}\n\nvoid ViewUtil::deselect (QAbstractSpinBox& spinBox)\n{\n  spinBox.findChild<QLineEdit*> ()->deselect ();\n}\n\nvoid ViewUtil::adjustSize (QTabWidget& tab)\n{\n  const int current = tab.currentIndex ();\n\n  for (int i = 0; i < tab.count (); i++)\n  {\n    if (i == current)\n    {\n      tab.widget (i)->setSizePolicy (QSizePolicy::Preferred, QSizePolicy::Preferred);\n    }\n    else\n    {\n      tab.widget (i)->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);\n    }\n  }\n}\n\nbool ViewUtil::question (QWidget& parent, const QString& label)\n{\n  return QMessageBox::question (&parent, label, label) == QMessageBox::Yes;\n}\n\nvoid ViewUtil::error (QWidget& parent, const QString& label)\n{\n  QMessageBox::critical (&parent, QObject::tr (\"Error\"), label);\n}\n\nvoid ViewUtil::about (QWidget& parent, const QString& label)\n{\n  QMessageBox::about (&parent, QObject::tr (\"About Dilay\"), label);\n}\n\nvoid ViewUtil::info (QWidget& parent, const QString& label)\n{\n  QMessageBox::information (&parent, QObject::tr (\"Information\"), label);\n}\n\nQAction& ViewUtil::addAction (QMenu& menu, const QString& label, const QKeySequence& keySequence,\n                              const std::function<void()>& f)\n{\n  QAction* a = new QAction (label, &menu);\n  a->setShortcut (keySequence);\n  menu.addAction (a);\n  QObject::connect (a, &QAction::triggered, f);\n  return *a;\n}\n\nQAction& ViewUtil::addCheckableAction (QMenu& menu, const QString& label,\n                                       const QKeySequence& keySequence, bool state,\n                                       const std::function<void(bool)>& f)\n{\n  QAction* a = new QAction (label, &menu);\n  a->setShortcut (keySequence);\n  a->setCheckable (true);\n  a->setChecked (state);\n  menu.addAction (a);\n  QObject::connect (a, &QAction::toggled, f);\n  return *a;\n}\n"
  },
  {
    "path": "lib/src/view/util.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef VIEW_UTIL\n#define VIEW_UTIL\n\n#include <functional>\n#include <glm/fwd.hpp>\n#include <vector>\n\nclass ViewDoubleSlider;\nclass ViewResolutionSlider;\nclass QAbstractSpinBox;\nclass QAction;\nclass QButtonGroup;\nclass QCheckBox;\nclass QDoubleSpinBox;\nclass QFrame;\nclass QKeySequence;\nclass QLineEdit;\nclass QMenu;\nclass QPoint;\nclass QPushButton;\nclass QRadioButton;\nclass QSlider;\nclass QSpinBox;\nclass QString;\nclass QTabWidget;\nclass QToolButton;\nclass QWidget;\n\nnamespace ViewUtil\n{\n  QSpinBox&             spinBox (int, int, int, int = 1);\n  QDoubleSpinBox&       spinBox (float, float, float, float);\n  QPushButton&          pushButton (const QString&, bool = false);\n  QToolButton&          toolButton (const QString&);\n  QRadioButton&         radioButton (const QString&, bool = false);\n  QCheckBox&            checkBox (const QString&, bool = false);\n  QSlider&              slider (int, int, int);\n  ViewDoubleSlider&     slider (unsigned short, float, float, float, unsigned short = 1);\n  ViewResolutionSlider& resolutionSlider (float, float, float);\n  QButtonGroup&         buttonGroup (const std::vector<QString>&);\n  QFrame&               horizontalLine ();\n  QWidget&              emptyWidget ();\n  QLineEdit&            lineEdit (float, unsigned short = 2);\n  QLineEdit&            lineEdit (float, float, float, unsigned short = 2);\n  QLineEdit&            lineEdit (int);\n  QLineEdit&            lineEdit (int, int, int);\n  glm::uvec2            toUVec2 (const QPoint&);\n  glm::ivec2            toIVec2 (const QPoint&);\n  QPoint                toQPoint (const glm::uvec2&);\n  QPoint                toQPoint (const glm::ivec2&);\n  void                  connect (const QSpinBox&, const std::function<void(int)>&);\n  void                  connect (const QDoubleSpinBox&, const std::function<void(double)>&);\n  void                  connect (const QPushButton&, const std::function<void()>&);\n  void                  connect (const QButtonGroup&, int, const std::function<void(int)>&);\n  void                  connect (const QCheckBox&, const std::function<void(bool)>&);\n  void                  connect (const QRadioButton&, const std::function<void(bool)>&);\n  void                  connect (const QSlider&, const std::function<void(int)>&);\n  void                  connect (const ViewResolutionSlider&, const std::function<void(float)>&);\n  void                  connect (const ViewDoubleSlider&, const std::function<void(float)>&);\n  void                  connect (const QAction&, const std::function<void()>&);\n  void                  connectFloat (const QLineEdit&, const std::function<void(float)>&);\n  void                  connectInt (const QLineEdit&, const std::function<void(int)>&);\n  QWidget&              stretcher (bool, bool);\n  void                  select (QButtonGroup&, int);\n  void                  deselect (QAbstractSpinBox&);\n  void                  adjustSize (QTabWidget&);\n  bool                  question (QWidget&, const QString&);\n  void                  error (QWidget&, const QString&);\n  void                  about (QWidget&, const QString&);\n  void                  info (QWidget&, const QString&);\n  QAction& addAction (QMenu&, const QString&, const QKeySequence&, const std::function<void()>&);\n  QAction& addCheckableAction (QMenu&, const QString&, const QKeySequence&, bool,\n                               const std::function<void(bool)>&);\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/view/vector-edit.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QLineEdit>\n#include <QVBoxLayout>\n#include \"view/util.hpp\"\n#include \"view/vector-edit.hpp\"\n\nstruct ViewVectorEdit::Impl\n{\n  ViewVectorEdit* self;\n  glm::vec3       vectorData;\n  QLineEdit*      edit[3];\n\n  static const int numDecimals = 2;\n\n  Impl (ViewVectorEdit* s, const glm::vec3& v)\n    : self (s)\n    , vectorData (v)\n  {\n    QVBoxLayout* layout = new QVBoxLayout;\n    layout->setSpacing (0);\n    layout->setContentsMargins (0, 11, 0, 11);\n    this->self->setLayout (layout);\n\n    for (int i = 0; i <= 2; i++)\n    {\n      this->edit[i] = &ViewUtil::lineEdit (v[i], Impl::numDecimals);\n\n      ViewUtil::connectFloat (*this->edit[i], [this, i](float v) {\n        this->vectorData[i] = v;\n        emit this->self->vectorEdited (this->vectorData);\n      });\n\n      layout->addWidget (this->edit[i]);\n    }\n  };\n\n  void vector (const glm::vec3& v)\n  {\n    this->x (v.x);\n    this->y (v.y);\n    this->z (v.z);\n  }\n\n  void x (float v) { this->changeComponent (0, v); }\n\n  void y (float v) { this->changeComponent (1, v); }\n\n  void z (float v) { this->changeComponent (2, v); }\n\n  void changeComponent (int i, float v)\n  {\n    this->vectorData[i] = v;\n    this->edit[i]->setText (QString::number (v, 'f', Impl::numDecimals));\n  }\n};\n\nDELEGATE_BIG2_BASE (ViewVectorEdit, (const glm::vec3& v, QWidget* p), (this, v), QWidget, (p))\nDELEGATE1 (void, ViewVectorEdit, vector, const glm::vec3&)\nDELEGATE1 (void, ViewVectorEdit, x, float)\nDELEGATE1 (void, ViewVectorEdit, y, float)\nDELEGATE1 (void, ViewVectorEdit, z, float)\n"
  },
  {
    "path": "lib/src/view/vector-edit.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_VIEW_VECTOR_EDIT\n#define DILAY_VIEW_VECTOR_EDIT\n\n#include <QWidget>\n#include <glm/glm.hpp>\n#include \"macro.hpp\"\n\nclass ViewVectorEdit : public QWidget\n{\n  Q_OBJECT\npublic:\n  DECLARE_BIG2 (ViewVectorEdit, const glm::vec3&, QWidget* = nullptr)\n\n  void vector (const glm::vec3&);\n  void x (float);\n  void y (float);\n  void z (float);\n\nsignals:\n  void vectorEdited (const glm::vec3&);\n\nprivate:\n  IMPLEMENTATION\n};\n\n#endif\n"
  },
  {
    "path": "lib/src/xml-conversion.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QDomElement>\n#include <glm/glm.hpp>\n#include \"color.hpp\"\n#include \"xml-conversion.hpp\"\n\nbool XmlConversion::fromDomElement (QDomElement e, float& v)\n{\n  assert (e.attributeNode (\"type\").value () == \"float\");\n  bool ok = true;\n  v = e.text ().toFloat (&ok);\n  return ok;\n}\n\nbool XmlConversion::fromDomElement (QDomElement e, int& v)\n{\n  assert (e.attributeNode (\"type\").value () == \"integer\");\n  bool ok = true;\n  v = e.text ().toInt (&ok);\n  return ok;\n}\n\nbool XmlConversion::fromDomElement (QDomElement e, bool& v)\n{\n  assert (e.attributeNode (\"type\").value () == \"boolean\");\n  bool ok = true;\n  v = e.text ().toInt (&ok) != 0;\n  return ok;\n}\n\nbool XmlConversion::fromDomElement (QDomElement e, glm::vec3& v)\n{\n  assert (e.attributeNode (\"type\").value () == \"vector3f\");\n\n  const bool okX = XmlConversion::fromDomElement (e.firstChildElement (\"x\"), v.x);\n  const bool okY = XmlConversion::fromDomElement (e.firstChildElement (\"y\"), v.y);\n  const bool okZ = XmlConversion::fromDomElement (e.firstChildElement (\"z\"), v.z);\n\n  return okX && okY && okZ;\n}\n\nbool XmlConversion::fromDomElement (QDomElement e, glm::ivec2& v)\n{\n  assert (e.attributeNode (\"type\").value () == \"vector2i\");\n\n  const bool okX = XmlConversion::fromDomElement (e.firstChildElement (\"x\"), v.x);\n  const bool okY = XmlConversion::fromDomElement (e.firstChildElement (\"y\"), v.y);\n\n  return okX && okY;\n}\n\nbool XmlConversion::fromDomElement (QDomElement e, Color& v)\n{\n  assert (e.attributeNode (\"type\").value () == \"color\");\n\n  float tmp;\n\n  bool okR = XmlConversion::fromDomElement (e.firstChildElement (\"r\"), tmp);\n  v.r (tmp);\n  bool okG = XmlConversion::fromDomElement (e.firstChildElement (\"g\"), tmp);\n  v.g (tmp);\n  bool okB = XmlConversion::fromDomElement (e.firstChildElement (\"b\"), tmp);\n  v.b (tmp);\n\n  bool okOpacity = true;\n  if (e.firstChildElement (\"opacity\").isNull () == false)\n  {\n    okOpacity = XmlConversion::fromDomElement (e.firstChildElement (\"opacity\"), tmp);\n    v.opacity (tmp);\n  }\n  return okR && okG && okB && okOpacity;\n}\n\nQDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const float& v)\n{\n  elem.setAttribute (\"type\", \"float\");\n  elem.appendChild (doc.createTextNode (std::to_string (v).c_str ()));\n  return elem;\n}\n\nQDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const int& v)\n{\n  elem.setAttribute (\"type\", \"integer\");\n  elem.appendChild (doc.createTextNode (std::to_string (v).c_str ()));\n  return elem;\n}\n\nQDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const bool& v)\n{\n  elem.setAttribute (\"type\", \"boolean\");\n  elem.appendChild (doc.createTextNode (std::to_string (v ? 1 : 0).c_str ()));\n  return elem;\n}\n\nQDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const glm::vec3& v)\n{\n  elem.setAttribute (\"type\", \"vector3f\");\n  QDomElement x = doc.createElement (\"x\");\n  QDomElement y = doc.createElement (\"y\");\n  QDomElement z = doc.createElement (\"z\");\n  elem.appendChild (XmlConversion::toDomElement (doc, x, v.x));\n  elem.appendChild (XmlConversion::toDomElement (doc, y, v.y));\n  elem.appendChild (XmlConversion::toDomElement (doc, z, v.z));\n  return elem;\n}\n\nQDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const glm::ivec2& v)\n{\n  elem.setAttribute (\"type\", \"vector2i\");\n  QDomElement x = doc.createElement (\"x\");\n  QDomElement y = doc.createElement (\"y\");\n  elem.appendChild (XmlConversion::toDomElement (doc, x, v.x));\n  elem.appendChild (XmlConversion::toDomElement (doc, y, v.y));\n  return elem;\n}\n\nQDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const Color& v)\n{\n  elem.setAttribute (\"type\", \"color\");\n  QDomElement r = doc.createElement (\"r\");\n  QDomElement g = doc.createElement (\"g\");\n  QDomElement b = doc.createElement (\"b\");\n  elem.appendChild (XmlConversion::toDomElement (doc, r, v.r ()));\n  elem.appendChild (XmlConversion::toDomElement (doc, g, v.g ()));\n  elem.appendChild (XmlConversion::toDomElement (doc, b, v.b ()));\n\n  if (v.isOpaque () == false)\n  {\n    QDomElement opacity = doc.createElement (\"opacity\");\n    elem.appendChild (XmlConversion::toDomElement (doc, opacity, v.opacity ()));\n  }\n  return elem;\n}\n"
  },
  {
    "path": "lib/src/xml-conversion.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_CONFIG_CONVERSION\n#define DILAY_CONFIG_CONVERSION\n\n#include <glm/fwd.hpp>\n\nclass QDomDocument;\nclass QDomElement;\nclass Color;\n\nnamespace XmlConversion\n{\n  bool fromDomElement (QDomElement, float&);\n  bool fromDomElement (QDomElement, int&);\n  bool fromDomElement (QDomElement, bool&);\n  bool fromDomElement (QDomElement, glm::vec3&);\n  bool fromDomElement (QDomElement, glm::ivec2&);\n  bool fromDomElement (QDomElement, Color&);\n\n  QDomElement& toDomElement (QDomDocument&, QDomElement&, const float&);\n  QDomElement& toDomElement (QDomDocument&, QDomElement&, const int&);\n  QDomElement& toDomElement (QDomDocument&, QDomElement&, const bool&);\n  QDomElement& toDomElement (QDomDocument&, QDomElement&, const glm::vec3&);\n  QDomElement& toDomElement (QDomDocument&, QDomElement&, const glm::ivec2&);\n  QDomElement& toDomElement (QDomDocument&, QDomElement&, const Color&);\n}\n\n#endif\n"
  },
  {
    "path": "test/src/main.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <QCoreApplication>\n#include <iostream>\n#include \"test-bitset.hpp\"\n#include \"test-distance.hpp\"\n#include \"test-intersection.hpp\"\n#include \"test-maybe.hpp\"\n#include \"test-misc.hpp\"\n#include \"test-octree.hpp\"\n#include \"test-prune.hpp\"\n#include \"test-tree.hpp\"\n\nint main ()\n{\n  QCoreApplication::setApplicationName (\"dilay\");\n\n  TestIntersection::test1 ();\n  TestIntersection::test2 ();\n  TestMaybe::test1 ();\n  TestMaybe::test2 ();\n  TestMaybe::test3 ();\n  TestOctree::test ();\n  TestBitset::test ();\n  TestTree::test1 ();\n  TestTree::test2 ();\n  TestTree::test3 ();\n  TestMisc::test ();\n  TestDistance::test ();\n  TestPrune::test ();\n\n  std::cout << \"all tests ran successfully\\n\";\n  return 0;\n}\n"
  },
  {
    "path": "test/src/test-bitset.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <cassert>\n#include \"bitset.hpp\"\n#include \"test-bitset.hpp\"\n\nvoid TestBitset::test ()\n{\n  Bitset<unsigned int> bs;\n\n  assert (bs.get<0> () == false);\n  assert (bs.get<8 * sizeof (unsigned int) - 1> () == false);\n\n  bs.toggle<0> ();\n  bs.toggle<8 * sizeof (unsigned int) - 1> ();\n  // bs.toggle <8 * sizeof (unsigned int)> ();      // must not compile\n\n  assert (bs.get<0> ());\n  assert (bs.get<1> () == false);\n  assert (bs.get<8 * sizeof (unsigned int) - 1> ());\n  assert (bs.value () == std::pow (2, 8 * sizeof (unsigned int) - 1) + 1);\n\n  bs.reset ();\n  assert (bs.none ());\n\n  bs.set<0> ();\n  bs.set<1> ();\n  bs.set<2> ();\n  assert (bs.none () == false);\n  assert (bs.all<2> ());\n  assert (bs.all<3> ());\n  assert (bs.all<4> () == false);\n  assert (bs.value () == 7);\n}\n"
  },
  {
    "path": "test/src/test-bitset.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TEST_BITSET\n#define DILAY_TEST_BITSET\n\nnamespace TestBitset\n{\n  void test ();\n}\n\n#endif\n"
  },
  {
    "path": "test/src/test-distance.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include <glm/gtc/epsilon.hpp>\n#include \"distance.hpp\"\n#include \"primitive/cylinder.hpp\"\n#include \"test-distance.hpp\"\n#include \"util.hpp\"\n\nvoid TestDistance::test ()\n{\n  using Distance::distance;\n\n  const float eps = Util::epsilon ();\n\n  PrimCylinder cyl (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (1.0f, 0.0f, 0.0f), 0.5f);\n\n  assert (glm::epsilonEqual (distance (cyl, glm::vec3 (0.5f, 1.3f, 0.0f)), 0.8f, eps));\n\n  assert (glm::epsilonEqual (distance (cyl, glm::vec3 (0.1f, 0.0f, 0.0f)), -0.1f, eps));\n\n  assert (glm::epsilonEqual (distance (cyl, glm::vec3 (0.9f, 0.0f, 0.0f)), -0.1f, eps));\n\n  assert (glm::epsilonEqual (distance (cyl, glm::vec3 (0.5f, 0.4f, 0.0f)), -0.1f, eps));\n\n  assert (glm::epsilonEqual (distance (cyl, glm::vec3 (-0.3f, 0.3f, 0.0f)), 0.3f, eps));\n  assert (glm::epsilonEqual (distance (cyl, glm::vec3 (1.7f, 0.3f, 0.0f)), 0.7f, eps));\n  assert (glm::epsilonEqual (distance (cyl, glm::vec3 (-2.0f, 2.0f, 0.0f)),\n                             glm::sqrt ((1.5f * 1.5f) + (2.0f * 2.0f)), eps));\n  assert (glm::epsilonEqual (distance (cyl, glm::vec3 (2.0f, 2.0f, 0.0f)),\n                             glm::sqrt ((1.5f * 1.5f) + (1.0f * 1.0f)), eps));\n  unused (eps);\n}\n"
  },
  {
    "path": "test/src/test-distance.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TEST_DISTANCE\n#define DILAY_TEST_DISTANCE\n\nnamespace TestDistance\n{\n  void test ();\n}\n\n#endif\n"
  },
  {
    "path": "test/src/test-intersection.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include \"intersection.hpp\"\n#include \"primitive/aabox.hpp\"\n#include \"primitive/cone.hpp\"\n#include \"primitive/cylinder.hpp\"\n#include \"primitive/plane.hpp\"\n#include \"primitive/ray.hpp\"\n#include \"primitive/sphere.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"test-intersection.hpp\"\n#include \"util.hpp\"\n\nvoid TestIntersection::test1 ()\n{\n  using IntersectionUtil::intersects;\n\n  const glm::vec3 v1 (0.0f, 0.0f, 0.0f);\n  const glm::vec3 v2 (2.0f, 0.0f, 0.0f);\n  const glm::vec3 v3 (0.0f, 2.0f, 0.0f);\n\n  PrimTriangle tri (v1, v2, v3);\n  PrimSphere   sph (glm::vec3 (0.0f, 0.0f, 0.0f), 1.0f);\n  PrimPlane    pln (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f));\n  PrimAABox    abx (glm::vec3 (0.0f, 0.0f, 0.0f), 1.0f);\n  PrimCylinder cyl (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f), 1.0f);\n  PrimCone     cne (glm::vec3 (0.0f, 0.0f, 0.0f), 1.0f, glm::vec3 (0.0f, 1.0f, 0.0f), 0.5f);\n\n  float t = 0.0f;\n\n  assert (intersects (PrimRay (glm::vec3 (0.1f, 0.1f, 1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), tri,\n                      false, nullptr));\n  assert (intersects (PrimRay (glm::vec3 (0.1f, 0.1f, -1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), tri,\n                      false, nullptr) == false);\n  assert (intersects (PrimRay (true, glm::vec3 (0.1f, 0.1f, -1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)),\n                      tri, false, nullptr));\n\n  assert (\n    intersects (PrimRay (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), sph, &t));\n  assert (t > 0.0f);\n  assert (\n    intersects (PrimRay (glm::vec3 (0.0f, 0.0f, 2.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), sph, &t));\n  assert (t > 0.0f && t < 2.0f);\n  assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, -2.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), sph,\n                      &t) == false);\n  assert (intersects (PrimRay (true, glm::vec3 (0.0f, 0.0f, -2.0f), glm::vec3 (0.0f, 0.0f, -1.0f)),\n                      sph, &t));\n  assert (t < 0.0f && t > -2.0f);\n\n  assert (\n    intersects (PrimRay (glm::vec3 (0.0f, 1.0f, 0.0f), glm::vec3 (0.0f, -1.0f, 0.0f)), pln, &t));\n  assert (t > 0.0f);\n  assert (\n    intersects (PrimRay (glm::vec3 (0.0f, -1.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), pln, &t));\n  assert (t > 0.0f);\n  assert (intersects (PrimRay (glm::vec3 (0.0f, 1.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), pln,\n                      &t) == false);\n  assert (intersects (PrimRay (true, glm::vec3 (0.0f, 1.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)),\n                      pln, &t));\n  assert (t < 0.0f);\n\n  assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, 1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), abx,\n                      nullptr));\n  assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, -1.0f), glm::vec3 (0.0f, 0.0f, 1.0f)), abx,\n                      nullptr));\n  assert (intersects (PrimRay (glm::vec3 (1.5f, 0.0f, 1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), abx,\n                      nullptr) == false);\n  assert (intersects (PrimRay (glm::vec3 (1.5f, 0.0f, -1.0f), glm::vec3 (0.0f, 0.0f, 1.0f)), abx,\n                      nullptr) == false);\n  assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, -1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), abx,\n                      nullptr) == false);\n  assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, 1.0f), glm::vec3 (0.0f, 0.0f, 1.0f)), abx,\n                      nullptr) == false);\n  assert (intersects (PrimRay (true, glm::vec3 (0.0f, 0.0f, -1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)),\n                      abx, nullptr));\n\n  assert (intersects (PrimPlane (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), abx));\n  assert (intersects (PrimPlane (glm::vec3 (0.0f, 0.4f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), abx));\n  assert (intersects (PrimPlane (glm::vec3 (0.0f, 0.6f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)),\n                      abx) == false);\n\n  assert (intersects (PrimPlane (glm::vec3 (0.0f, 2.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), tri));\n\n  assert (intersects (cyl, glm::vec3 (0.0f, -0.1f, 0.0f)) == false);\n  assert (intersects (cyl, glm::vec3 (0.0f, 1.1f, 0.0f)) == false);\n  assert (intersects (cyl, glm::vec3 (1.1f, 0.1f, 0.0f)) == false);\n  assert (intersects (cyl, glm::vec3 (1.0f, 0.0f, 0.0f)));\n  assert (intersects (cyl, glm::vec3 (1.0f, 1.0f, 0.0f)));\n  assert (intersects (cyl, glm::vec3 (0.9f, 0.1f, 0.0f)));\n  assert (intersects (cyl, glm::vec3 (0.1f, 0.9f, 0.0f)));\n\n  assert (intersects (cne, glm::vec3 (0.0f, -0.1f, 0.0f)) == false);\n  assert (intersects (cne, glm::vec3 (1.0f, 0.1f, 0.0f)) == false);\n  assert (intersects (cne, glm::vec3 (1.0f, 0.0f, 0.0f)));\n  assert (intersects (cne, glm::vec3 (0.5f, 1.0f, 0.0f)));\n  assert (intersects (cne, glm::vec3 (0.8f, 0.1f, 0.0f)));\n  unused (t);\n}\n\nvoid TestIntersection::test2 ()\n{\n  Intersection i1, i2;\n\n  i1.update (2.0f, glm::vec3 (2.0f), glm::vec3 (2.0f));\n  i2.update (1.0f, glm::vec3 (1.0f), glm::vec3 (1.0f));\n\n  Intersection::sort (i1, i2);\n\n  assert (i1.distance () == 1.0f);\n  assert (i1.position () == glm::vec3 (1.0f));\n  assert (i1.normal () == glm::vec3 (1.0f));\n\n  assert (i2.distance () == 2.0f);\n  assert (i2.position () == glm::vec3 (2.0f));\n  assert (i2.normal () == glm::vec3 (2.0f));\n}\n"
  },
  {
    "path": "test/src/test-intersection.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TEST_INTERSECTION\n#define DILAY_TEST_INTERSECTION\n\nnamespace TestIntersection\n{\n  void test1 ();\n  void test2 ();\n}\n\n#endif\n"
  },
  {
    "path": "test/src/test-maybe.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"maybe.hpp\"\n#include \"test-maybe.hpp\"\n\nvoid TestMaybe::test1 ()\n{\n  Maybe<int> m1 (5);\n\n  assert (m1.hasValue ());\n  assert (*m1 == 5);\n\n  Maybe<int> m2 (m1);\n\n  assert (*m1 == 5);\n  assert (*m2 == 5);\n\n  Maybe<int> m3 (std::move (m1));\n\n  assert (m1.hasValue () == false);\n  assert (*m3 == 5);\n\n  m2 = 12;\n  m3 = std::move (m2);\n\n  assert (m2.hasValue () == false);\n  assert (*m3 == 12);\n\n  m3 = std::move (m2);\n\n  assert (m3.hasValue () == false);\n\n  m3 = 12;\n  m3 = m2;\n\n  assert (m3.hasValue () == false);\n\n  m3 = 44;\n  assert (*m3 == 44);\n\n  int* i = new int(55);\n  m3 = i;\n\n  assert (*m3 == 55);\n\n  m3 = nullptr;\n\n  assert (m3.hasValue () == false);\n}\n\nnamespace\n{\n  class Foo\n  {\n  public:\n    Foo (int d)\n      : _data (d)\n    {\n    }\n\n    int data () const { return this->_data; }\n\n  private:\n    int _data;\n  };\n}\n\nvoid TestMaybe::test2 ()\n{\n  Maybe<Foo> m = Maybe<Foo>::make (5);\n\n  assert (m.hasValue ());\n  assert (m->data () == 5);\n}\n\nvoid TestMaybe::test3 ()\n{\n  Maybe<int> m1 = 5;\n  Maybe<int> m2;\n\n  assert (m1.hasValue ());\n  assert (m2.hasValue () == false);\n\n  m2 = m1.release ();\n\n  assert (m1.hasValue () == false);\n  assert (m2.hasValue ());\n  assert (*m2 == 5);\n}\n"
  },
  {
    "path": "test/src/test-maybe.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TEST_MAYBE\n#define DILAY_TEST_MAYBE\n\nnamespace TestMaybe\n{\n  void test1 ();\n  void test2 ();\n  void test3 ();\n}\n\n#endif\n"
  },
  {
    "path": "test/src/test-misc.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <cassert>\n#include <limits>\n#include \"test-misc.hpp\"\n#include \"util.hpp\"\n\nvoid TestMisc::test ()\n{\n  assert (Util::countOnes (0) == 0);\n  assert (Util::countOnes (1) == 1);\n  assert (Util::countOnes (2) == 1);\n  assert (Util::countOnes (3) == 2);\n  assert (Util::countOnes (127) == 7);\n  assert (Util::countOnes (128) == 1);\n  assert (Util::countOnes (255) == 8);\n  assert (Util::countOnes (256) == 1);\n\n  assert (Util::countOnes (std::numeric_limits<unsigned int>::max ()) == sizeof (unsigned int) * 8);\n}\n"
  },
  {
    "path": "test/src/test-misc.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TEST_MISC\n#define DILAY_TEST_MISC\n\nnamespace TestMisc\n{\n  void test ();\n}\n\n#endif\n"
  },
  {
    "path": "test/src/test-octree.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <glm/glm.hpp>\n#include <glm/gtc/constants.hpp>\n#include <glm/gtc/matrix_transform.hpp>\n#include <random>\n#include \"dynamic/octree.hpp\"\n#include \"primitive/triangle.hpp\"\n#include \"test-octree.hpp\"\n\nvoid TestOctree::test ()\n{\n  const unsigned int numSamples = 10000;\n\n  DynamicOctree octree;\n  octree.setupRoot (glm::vec3 (0.0f), 10.0f);\n\n  std::default_random_engine            gen;\n  std::uniform_real_distribution<float> unitD (0.0f, 1.0f);\n  std::uniform_real_distribution<float> posD (-10.0f, 10.0f);\n  std::uniform_real_distribution<float> scaleD (0.00001f, 10.0f);\n  std::uniform_real_distribution<float> twoPiD (0.0f, 2.0f * glm::pi<float> ());\n\n  for (unsigned int i = 0; i < numSamples; i++)\n  {\n    const glm::vec3 m1 (-1.0f, 0.0f, 0.0f);\n    const glm::vec3 m2 (1.0f, 0.0f, 0.0f);\n    const glm::vec3 m3 (0.0f, -1.0f, 0.0f);\n\n    const glm::mat4x4 translationMatrix =\n      glm::translate (glm::mat4x4 (1.0f), glm::vec3 (posD (gen), posD (gen), posD (gen)));\n    const glm::mat4x4 rotationMatrix =\n      glm::rotate (glm::mat4x4 (1.0f), twoPiD (gen),\n                   glm::normalize (glm::vec3 (unitD (gen), unitD (gen), unitD (gen))));\n\n    const glm::mat4x4 scalingMatrix =\n      glm::scale (glm::mat4x4 (1.0f), glm::vec3 (scaleD (gen), scaleD (gen), scaleD (gen)));\n\n    const glm::mat4x4 modelMatrix = translationMatrix * rotationMatrix * scalingMatrix;\n\n    const glm::vec3    w1 = glm::vec3 (modelMatrix * glm::vec4 (m1, 1.0f));\n    const glm::vec3    w2 = glm::vec3 (modelMatrix * glm::vec4 (m2, 1.0f));\n    const glm::vec3    w3 = glm::vec3 (modelMatrix * glm::vec4 (m3, 1.0f));\n    const PrimTriangle tri = PrimTriangle (w1, w2, w3);\n\n    octree.addElement (i, tri.center (), tri.maxDimExtent ());\n  }\n  for (unsigned int i = 0; i < numSamples; i++)\n  {\n    octree.deleteElement (i);\n  }\n}\n"
  },
  {
    "path": "test/src/test-octree.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TEST_OCTREE\n#define DILAY_TEST_OCTREE\n\nnamespace TestOctree\n{\n  void test ();\n}\n\n#endif\n"
  },
  {
    "path": "test/src/test-prune.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include \"test-prune.hpp\"\n#include \"util.hpp\"\n\nnamespace\n{\n  bool equals (std::vector<int> prune, const std::vector<int>& vec,\n               const std::vector<unsigned int>& indices)\n  {\n    std::vector<unsigned int> pruneIndices;\n\n    Util::prune<int> (prune, [](int i) { return i < 0; }, &pruneIndices);\n\n    return std::equal (prune.begin (), prune.end (), vec.begin (), vec.end ()) &&\n           std::equal (pruneIndices.begin (), pruneIndices.end (), indices.begin (),\n                       indices.end ());\n  }\n}\n\nvoid TestPrune::test ()\n{\n  const unsigned int x = Util::invalidIndex ();\n\n  assert (\n    equals ({1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 1, 2, 3, 4, 5, 6, 7, 8}));\n  assert (equals ({-1, 2, -3, 4, -5, 6, -7, 8, -9}, {8, 2, 6, 4}, {x, 1, x, 3, x, 2, x, 0, x}));\n  assert (equals ({-1, -2, -3, -4, -5, -6, -7, -8, -9}, {}, {x, x, x, x, x, x, x, x, x}));\n  assert (equals ({-1, -2, -3, -4, -5, -6, -7, -8, 9}, {9}, {x, x, x, x, x, x, x, x, 0}));\n  assert (equals ({1, -2, -3, -4, -5, -6, -7, -8, 9}, {1, 9}, {0, x, x, x, x, x, x, x, 1}));\n  assert (equals ({-1, 2, -3, -4, -5, -6, -7, -8, 9}, {9, 2}, {x, 1, x, x, x, x, x, x, 0}));\n  assert (equals ({-1, -2, -3, -4, -5, -6, 7, 8, 9}, {9, 8, 7}, {x, x, x, x, x, x, 2, 1, 0}));\n  unused (x);\n  unused (equals);\n}\n"
  },
  {
    "path": "test/src/test-prune.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TEST_PRUNE\n#define DILAY_TEST_PRUNE\n\nnamespace TestPrune\n{\n  void test ();\n}\n\n#endif\n"
  },
  {
    "path": "test/src/test-tree.cpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#include <cassert>\n#include \"test-tree.hpp\"\n#include \"tree.hpp\"\n\nnamespace\n{\n  struct Foo\n  {\n    int i;\n\n    Foo (int v)\n      : i (v)\n    {\n    }\n  };\n}\n\nvoid TestTree::test1 ()\n{\n  Tree<Foo> tree;\n\n  auto& n0 = tree.emplaceRoot (0);\n  auto& n1 = n0.emplaceChild (100);\n  auto& n2 = n1.emplaceChild (200);\n\n  assert (n1.data ().i == 100);\n  assert (n2.parent () == &n1);\n  assert (tree.root ().numNodes () == 3);\n  assert (n1.lastChild ().data ().i == n2.data ().i);\n\n  n0.deleteChild (n1);\n  assert (tree.root ().numNodes () == 1);\n\n  n0.emplaceChild (5);\n  n0.emplaceChild (6).emplaceChild (7);\n\n  assert (tree.root ().numNodes () == 4);\n\n  n0.deleteChildIf ([](const auto& c) { return c.data ().i == 6; });\n\n  assert (tree.root ().numNodes () == 2);\n  assert (n0.lastChild ().data ().i == 5);\n\n  Tree<Foo> copy (tree);\n\n  tree.reset ();\n\n  assert (copy.root ().numNodes () == 2);\n  assert (copy.root ().data ().i == 0);\n  assert (copy.root ().lastChild ().data ().i == 5);\n  assert (copy.root ().lastChild ().parent () == &copy.root ());\n  unused (n2);\n}\n\nvoid TestTree::test2 ()\n{\n  Tree<int> t;\n\n  t.emplaceRoot (1).emplaceChild (2).emplaceChild (3).emplaceChild (4);\n\n  assert (t.root ().numNodes () == 4);\n  assert (t.root ().data () == 1);\n  assert (t.root ().lastChild ().data () == 2);\n  assert (t.root ().lastChild ().lastChild ().data () == 3);\n  assert (t.root ().lastChild ().lastChild ().lastChild ().data () == 4);\n\n  t.rebalance (t.root ().lastChild ().lastChild ().lastChild ());\n\n  assert (t.root ().numNodes () == 4);\n  assert (t.root ().data () == 4);\n  assert (t.root ().lastChild ().data () == 3);\n  assert (t.root ().lastChild ().lastChild ().data () == 2);\n  assert (t.root ().lastChild ().lastChild ().lastChild ().data () == 1);\n}\n\nvoid TestTree::test3 ()\n{\n  Tree<int> t1;\n\n  TreeNode<int>& node1 = t1.emplaceRoot (1).emplaceChild (2).emplaceChild (3);\n  node1.emplaceChild (4);\n\n  Tree<int> t2 = t1.split (node1);\n\n  assert (t1.root ().numNodes () == 2);\n  assert (t1.root ().data () == 1);\n  assert (t1.root ().lastChild ().data () == 2);\n\n  assert (t2.root ().numNodes () == 2);\n  assert (t2.root ().data () == 3);\n  assert (t2.root ().lastChild ().data () == 4);\n\n  Tree<int> t3 = t1.split (t1.root ());\n\n  assert (t1.hasRoot () == false);\n\n  assert (t3.root ().numNodes () == 2);\n  assert (t3.root ().data () == 1);\n  assert (t3.root ().lastChild ().data () == 2);\n}\n"
  },
  {
    "path": "test/src/test-tree.hpp",
    "content": "/* This file is part of Dilay\n * Copyright © 2015-2018 Alexander Bau\n * Use and redistribute under the terms of the GNU General Public License\n */\n#ifndef DILAY_TEST_TREE\n#define DILAY_TEST_TREE\n\nnamespace TestTree\n{\n  void test1 ();\n  void test2 ();\n  void test3 ();\n}\n\n#endif\n"
  },
  {
    "path": "test/test.pro",
    "content": "include (../common.pri)\n\nTEMPLATE        = app\nTARGET          = run-tests\nDESTDIR         = $$OUT_PWD/..\nDEPENDPATH     += src \nINCLUDEPATH    += src $$PWD/../lib/src\n\nSOURCES += \\\n           src/main.cpp \\\n           src/test-bitset.cpp \\\n           src/test-distance.cpp \\\n           src/test-intersection.cpp \\\n           src/test-maybe.cpp \\\n           src/test-misc.cpp \\\n           src/test-octree.cpp \\\n           src/test-prune.cpp \\\n           src/test-tree.cpp\n\nHEADERS += \\\n           src/test-bitset.hpp \\\n           src/test-distance.hpp \\\n           src/test-intersection.hpp \\\n           src/test-maybe.hpp \\\n           src/test-misc.hpp \\\n           src/test-octree.hpp \\\n           src/test-prune.hpp \\\n           src/test-tree.hpp\n\nwin32:CONFIG(release, debug|release):    LIBS += -L$$OUT_PWD/../lib/release/ -ldilay\nelse:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../lib/debug/ -ldilay\nelse:unix:                               LIBS += -L$$OUT_PWD/../lib/ -ldilay\n\nwin32-g++:CONFIG(release, debug|release):             PRE_TARGETDEPS += $$OUT_PWD/../lib/release/libdilay.a\nelse:win32-g++:CONFIG(debug, debug|release):          PRE_TARGETDEPS += $$OUT_PWD/../lib/debug/libdilay.a\nelse:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../lib/release/dilay.lib\nelse:win32:!win32-g++:CONFIG(debug, debug|release):   PRE_TARGETDEPS += $$OUT_PWD/../lib/debug/dilay.lib\nelse:unix:                                            PRE_TARGETDEPS += $$OUT_PWD/../lib/libdilay.a\n\nunix {\n  format.commands = clang-format -style=file -i $$SOURCES $$HEADERS\n  QMAKE_EXTRA_TARGETS += format\n}\n"
  },
  {
    "path": "unix/dilay.desktop",
    "content": "[Desktop Entry]\nType=Application\nVersion=1.0\nName=Dilay\nComment=A 3D sculpting application\nExec=dilay\nIcon=dilay\nTerminal=false\nCategories=Graphics;3DGraphics;\n"
  },
  {
    "path": "unix/docker/appimage/Dockerfile",
    "content": "FROM ubuntu:trusty\n\nRUN apt-get update\nRUN apt-get install -y software-properties-common\n\nRUN add-apt-repository -y ppa:ubuntu-toolchain-r/test\nRUN add-apt-repository -y ppa:beineri/opt-qt592-trusty\nRUN apt-get update\n\nRUN apt-get install -y build-essential git qt59base libglm-dev g++-5 libgl1-mesa-dev wget\n\nRUN update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 20\n\nCOPY entrypoint.sh /usr/bin/\n\nENTRYPOINT entrypoint.sh\n"
  },
  {
    "path": "unix/docker/appimage/entrypoint.sh",
    "content": "#!/bin/bash\n\ncd /tmp\ngit clone --depth=1 file:///dilay \n\ncd /tmp/dilay\nsource /opt/qt*/bin/qt*-env.sh\nqmake -r PREFIX=/usr\nmake release -j$(nproc)\nmake INSTALL_ROOT=appdir install\n\nwget -c -q \"https://github.com/probonopd/linuxdeployqt/releases/download/continuous/linuxdeployqt-continuous-x86_64.AppImage\"\nunset QTDIR\nunset QT_PLUGIN_PATH\nunset LD_LIBRARY_PATH\nexport VERSION=$(git describe --dirty --tags) # linuxdeployqt uses this for naming the file\nchmod a+x linuxdeployqt*.AppImage\n./linuxdeployqt*.AppImage --appimage-extract\n./squashfs-root/AppRun ./app/appdir/usr/share/applications/*.desktop -bundle-non-qt-libs\n./squashfs-root/AppRun ./app/appdir/usr/share/applications/*.desktop -appimage\nmv Dilay*.AppImage /dilay\n"
  },
  {
    "path": "unix/docker/debian-sid/Dockerfile",
    "content": "FROM debian:sid\n\nRUN apt-get update\nRUN apt-get install -y build-essential git qt5-default qt5-qmake libglm-dev\n\nCOPY entrypoint.sh /usr/bin/\n\nENTRYPOINT entrypoint.sh\n"
  },
  {
    "path": "unix/docker/debian-sid/entrypoint.sh",
    "content": "#!/bin/bash\n\ncd /tmp\ngit clone --depth=1 file:///dilay \n\ncd /tmp/dilay\nqmake -r\nmake release -j$(nproc)\n"
  },
  {
    "path": "unix/docker/ubuntu-bionic/Dockerfile",
    "content": "FROM ubuntu:bionic\n\nRUN apt-get update\nRUN apt-get install -y build-essential git qt5-default qt5-qmake libglm-dev\n\nCOPY entrypoint.sh /usr/bin/\n\nENTRYPOINT entrypoint.sh\n"
  },
  {
    "path": "unix/docker/ubuntu-bionic/entrypoint.sh",
    "content": "#!/bin/bash\n\ncd /tmp\ngit clone --depth=1 file:///dilay \n\ncd /tmp/dilay\nqmake -r\nmake release -j$(nproc)\n"
  },
  {
    "path": "unix/docker/ubuntu-trusty/Dockerfile",
    "content": "FROM ubuntu:trusty\n\nRUN apt-get update\nRUN apt-get install -y software-properties-common\n\nRUN add-apt-repository -y ppa:ubuntu-toolchain-r/test\nRUN add-apt-repository -y ppa:beineri/opt-qt592-trusty\nRUN apt-get update\n\nRUN apt-get install -y build-essential git qt59base libglm-dev g++-5 libgl1-mesa-dev\n\nRUN update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 20\n\nCOPY entrypoint.sh /usr/bin/\n\nENTRYPOINT entrypoint.sh\n"
  },
  {
    "path": "unix/docker/ubuntu-trusty/entrypoint.sh",
    "content": "#!/bin/bash\n\ncd /tmp\ngit clone --depth=1 file:///dilay \n\ncd /tmp/dilay\nsource /opt/qt*/bin/qt*-env.sh\nqmake -r\nmake release -j$(nproc)\n"
  },
  {
    "path": "unix/docker/ubuntu-xenial/Dockerfile",
    "content": "FROM ubuntu:xenial\n\nRUN apt-get update\nRUN apt-get install -y software-properties-common\n\nRUN add-apt-repository -y ppa:beineri/opt-qt592-xenial\nRUN apt-get update\n\nRUN apt-get update\nRUN apt-get install -y build-essential git qt59base libglm-dev libgl1-mesa-dev\n\nCOPY entrypoint.sh /usr/bin/\n\nENTRYPOINT entrypoint.sh\n"
  },
  {
    "path": "unix/docker/ubuntu-xenial/entrypoint.sh",
    "content": "#!/bin/bash\n\ncd /tmp\ngit clone --depth=1 file:///dilay \n\ncd /tmp/dilay\nsource /opt/qt*/bin/qt*-env.sh\nqmake -r\nmake release -j$(nproc)\n"
  },
  {
    "path": "win32/LICENSE.rtf",
    "content": "{\\rtf1\\ansi\\deff0{\\fonttbl{\\f0\\fnil\\fcharset0 Courier New;}}\r\n{\\*\\generator Msftedit 5.41.21.2510;}\\viewkind4\\uc1\\pard\\lang1031\\f0\\fs18                     GNU GENERAL PUBLIC LICENSE\\par\r\n                       Version 3, 29 June 2007\\par\r\n\\par\r\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>  \\par\r\nEveryone is permitted to copy and distribute verbatim copies  of this license document, but changing it is not allowed.\\par\r\n\\par\r\n                            Preamble\\par\r\n\\par\r\n  The GNU General Public License is a free, copyleft license for software and other kinds of works.\\par\r\n\\par\r\n  The licenses for most software and other practical works are designed to take away your freedom to share and change the works.  By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.  We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors.  You can apply it to your programs, too.\\par\r\n\\par\r\n  When we speak of free software, we are referring to freedom, not price.  Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.\\par\r\n\\par\r\n  To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights.  Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.\\par\r\n\\par\r\n  For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received.  You must make sure that they, too, receive or can get the source code.  And you must show them these terms so they know their rights.\\par\r\n\\par\r\n  Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.\\par\r\n\\par\r\n  For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software.  For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.\\par\r\n\\par\r\n  Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so.  This is fundamentally incompatible with the aim of protecting users' freedom to change the software.  The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable.  Therefore, we have designed this version of the GPL to prohibit the practice for those products.  If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.\\par\r\n\\par\r\n  Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary.  To prevent this, the GPL assures that patents cannot be used to render the program non-free.\\par\r\n\\par\r\n  The precise terms and conditions for copying, distribution and modification follow.\\par\r\n\\par\r\n                       TERMS AND CONDITIONS\\par\r\n\\par\r\n  0. Definitions.\\par\r\n\\par\r\n  \"This License\" refers to version 3 of the GNU General Public License.\\par\r\n\\par\r\n  \"Copyright\" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\\par\r\n\\par\r\n  \"The Program\" refers to any copyrightable work licensed under this License.  Each licensee is addressed as \"you\".  \"Licensees\" and \"recipients\" may be individuals or organizations.\\par\r\n\\par\r\n  To \"modify\" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy.  The resulting work is called a \"modified version\" of the earlier work or a work \"based on\" the earlier work.\\par\r\n\\par\r\n  A \"covered work\" means either the unmodified Program or a work based on the Program.\\par\r\n\\par\r\n  To \"propagate\" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy.  Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.\\par\r\n\\par\r\n  To \"convey\" a work means any kind of propagation that enables other parties to make or receive copies.  Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.\\par\r\n\\par\r\n  An interactive user interface displays \"Appropriate Legal Notices\" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License.  If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.\\par\r\n\\par\r\n  1. Source Code.\\par\r\n\\par\r\n  The \"source code\" for a work means the preferred form of the work for making modifications to it.  \"Object code\" means any non-source form of a work.\\par\r\n\\par\r\n  A \"Standard Interface\" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.\\par\r\n\\par\r\n  The \"System Libraries\" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form.  A \"Major Component\", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.\\par\r\n\\par\r\n  The \"Corresponding Source\" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities.  However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work.  For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.\\par\r\n\\par\r\n  The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\\par\r\n\\par\r\n  The Corresponding Source for a work in source code form is that same work.\\par\r\n\\par\r\n  2. Basic Permissions.\\par\r\n\\par\r\n  All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met.  This License explicitly affirms your unlimited permission to run the unmodified Program.  The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work.  This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.\\par\r\n\\par\r\n  You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force.  You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright.  Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.\\par\r\n\\par\r\n  Conveying under any other circumstances is permitted solely under the conditions stated below.  Sublicensing is not allowed; section 10 makes it unnecessary.\\par\r\n\\par\r\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\\par\r\n\\par\r\n  No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.\\par\r\n\\par\r\n  When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.\\par\r\n\\par\r\n  4. Conveying Verbatim Copies.\\par\r\n\\par\r\n  You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.\\par\r\n\\par\r\n  You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.\\par\r\n\\par\r\n  5. Conveying Modified Source Versions.\\par\r\n\\par\r\n  You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:\\par\r\n\\par\r\n    a) The work must carry prominent notices stating that you modified     it, and giving a relevant date.\\par\r\n\\par\r\n    b) The work must carry prominent notices stating that it is     released under this License and any conditions added under section     7.  This requirement modifies the requirement in section 4 to     \"keep intact all notices\".\\par\r\n\\par\r\n    c) You must license the entire work, as a whole, under this     License to anyone who comes into possession of a copy.  This     License will therefore apply, along with any applicable section 7     additional terms, to the whole of the work, and all its parts,     regardless of how they are packaged.  This License gives no     permission to license the work in any other way, but it does not     invalidate such permission if you have separately received it.\\par\r\n\\par\r\n    d) If the work has interactive user interfaces, each must display     Appropriate Legal Notices; however, if the Program has interactive     interfaces that do not display Appropriate Legal Notices, your     work need not make them do so.\\par\r\n\\par\r\n  A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an \"aggregate\" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit.  Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.\\par\r\n\\par\r\n  6. Conveying Non-Source Forms.\\par\r\n\\par\r\n  You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:\\par\r\n\\par\r\n    a) Convey the object code in, or embodied in, a physical product     (including a physical distribution medium), accompanied by the     Corresponding Source fixed on a durable physical medium     customarily used for software interchange.\\par\r\n\\par\r\n    b) Convey the object code in, or embodied in, a physical product     (including a physical distribution medium), accompanied by a     written offer, valid for at least three years and valid for as     long as you offer spare parts or customer support for that product     model, to give anyone who possesses the object code either (1) a     copy of the Corresponding Source for all the software in the     product that is covered by this License, on a durable physical     medium customarily used for software interchange, for a price no     more than your reasonable cost of physically performing this     conveying of source, or (2) access to copy the     Corresponding Source from a network server at no charge.\\par\r\n\\par\r\n    c) Convey individual copies of the object code with a copy of the     written offer to provide the Corresponding Source.  This     alternative is allowed only occasionally and noncommercially, and     only if you received the object code with such an offer, in accord     with subsection 6b.\\par\r\n\\par\r\n    d) Convey the object code by offering access from a designated     place (gratis or for a charge), and offer equivalent access to the     Corresponding Source in the same way through the same place at no     further charge.  You need not require recipients to copy the     Corresponding Source along with the object code.  If the place to     copy the object code is a network server, the Corresponding Source     may be on a different server (operated by you or a third party)     that supports equivalent copying facilities, provided you maintain     clear directions next to the object code saying where to find the     Corresponding Source.  Regardless of what server hosts the     Corresponding Source, you remain obligated to ensure that it is     available for as long as needed to satisfy these requirements.\\par\r\n\\par\r\n    e) Convey the object code using peer-to-peer transmission, provided     you inform other peers where the object code and Corresponding     Source of the work are being offered to the general public at no     charge under subsection 6d.\\par\r\n\\par\r\n  A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.\\par\r\n\\par\r\n  A \"User Product\" is either (1) a \"consumer product\", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling.  In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage.  For a particular product received by a particular user, \"normally used\" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product.  A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.\\par\r\n\\par\r\n  \"Installation Information\" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source.  The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.\\par\r\n\\par\r\n  If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information.  But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).\\par\r\n\\par\r\n  The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed.  Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.\\par\r\n\\par\r\n  Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.\\par\r\n\\par\r\n  7. Additional Terms.\\par\r\n\\par\r\n  \"Additional permissions\" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law.  If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.\\par\r\n\\par\r\n  When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it.  (Additional permissions may be written to require their own removal in certain cases when you modify the work.)  You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.\\par\r\n\\par\r\n  Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:\\par\r\n\\par\r\n    a) Disclaiming warranty or limiting liability differently from the     terms of sections 15 and 16 of this License; or\\par\r\n\\par\r\n    b) Requiring preservation of specified reasonable legal notices or     author attributions in that material or in the Appropriate Legal     Notices displayed by works containing it; or\\par\r\n\\par\r\n    c) Prohibiting misrepresentation of the origin of that material, or     requiring that modified versions of such material be marked in     reasonable ways as different from the original version; or\\par\r\n\\par\r\n    d) Limiting the use for publicity purposes of names of licensors or     authors of the material; or\\par\r\n\\par\r\n    e) Declining to grant rights under trademark law for use of some     trade names, trademarks, or service marks; or\\par\r\n\\par\r\n    f) Requiring indemnification of licensors and authors of that     material by anyone who conveys the material (or modified versions of     it) with contractual assumptions of liability to the recipient, for     any liability that these contractual assumptions directly impose on     those licensors and authors.\\par\r\n\\par\r\n  All other non-permissive additional terms are considered \"further restrictions\" within the meaning of section 10.  If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term.  If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.\\par\r\n\\par\r\n  If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.\\par\r\n\\par\r\n  Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.\\par\r\n\\par\r\n  8. Termination.\\par\r\n\\par\r\n  You may not propagate or modify a covered work except as expressly provided under this License.  Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).\\par\r\n\\par\r\n  However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.\\par\r\n\\par\r\n  Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.\\par\r\n\\par\r\n  Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License.  If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.\\par\r\n\\par\r\n  9. Acceptance Not Required for Having Copies.\\par\r\n\\par\r\n  You are not required to accept this License in order to receive or run a copy of the Program.  Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance.  However, nothing other than this License grants you permission to propagate or modify any covered work.  These actions infringe copyright if you do not accept this License.  Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.\\par\r\n\\par\r\n  10. Automatic Licensing of Downstream Recipients.\\par\r\n\\par\r\n  Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License.  You are not responsible for enforcing compliance by third parties with this License.\\par\r\n\\par\r\n  An \"entity transaction\" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations.  If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.\\par\r\n\\par\r\n  You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License.  For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.\\par\r\n\\par\r\n  11. Patents.\\par\r\n\\par\r\n  A \"contributor\" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based.  The work thus licensed is called the contributor's \"contributor version\".\\par\r\n\\par\r\n  A contributor's \"essential patent claims\" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version.  For purposes of this definition, \"control\" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.\\par\r\n\\par\r\n  Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.\\par\r\n\\par\r\n  In the following three paragraphs, a \"patent license\" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement).  To \"grant\" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.\\par\r\n\\par\r\n  If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients.  \"Knowingly relying\" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.\\par\r\n\\par\r\n  If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.\\par\r\n\\par\r\n  A patent license is \"discriminatory\" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License.  You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.\\par\r\n\\par\r\n  Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.\\par\r\n\\par\r\n  12. No Surrender of Others' Freedom.\\par\r\n\\par\r\n  If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License.  If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all.  For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.\\par\r\n\\par\r\n  13. Use with the GNU Affero General Public License.\\par\r\n\\par\r\n  Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work.  The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.\\par\r\n\\par\r\n  14. Revised Versions of this License.\\par\r\n\\par\r\n  The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time.  Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\\par\r\n\\par\r\n  Each version is given a distinguishing version number.  If the Program specifies that a certain numbered version of the GNU General Public License \"or any later version\" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation.  If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.\\par\r\n\\par\r\n  If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.\\par\r\n\\par\r\n  Later license versions may give you additional or different permissions.  However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.\\par\r\n\\par\r\n  15. Disclaimer of Warranty.\\par\r\n\\par\r\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\\par\r\n\\par\r\n  16. Limitation of Liability.\\par\r\n\\par\r\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\\par\r\n\\par\r\n  17. Interpretation of Sections 15 and 16.\\par\r\n\\par\r\n  If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.\\par\r\n\\par\r\n                     END OF TERMS AND CONDITIONS\\par\r\n}\r\n\u0000"
  },
  {
    "path": "win32/deploy.bat",
    "content": "REM Qt's install directory: %1\nREM compilation's target directory: %2\nREM Dilay's source directory: %3\nREM Dilay's version: %4\n@echo off\n\nif exist win32deploy ( rmdir /s /q win32deploy )\n\nmkdir win32deploy\nmkdir win32deploy\\Dilay\n\nxcopy %2\\dilay.exe                         win32deploy\\Dilay\nxcopy %1\\bin\\libgcc_s_dw2-1.dll            win32deploy\\Dilay\nxcopy %1\\bin\\libstdc++-6.dll               win32deploy\\Dilay\nxcopy %1\\bin\\libwinpthread-1.dll           win32deploy\\Dilay\nxcopy %1\\bin\\Qt5Core.dll                   win32deploy\\Dilay\nxcopy %1\\bin\\Qt5Gui.dll                    win32deploy\\Dilay\nxcopy %1\\bin\\Qt5Widgets.dll                win32deploy\\Dilay\nxcopy %1\\bin\\Qt5Xml.dll                    win32deploy\\Dilay\nxcopy %3\\win32\\icon.ico      \t           win32deploy\\Dilay\nxcopy %3\\win32\\LICENSE.rtf                 win32deploy\\Dilay\n    \nmkdir win32deploy\\Dilay\\platforms\n\nxcopy %1\\plugins\\platforms\\qwindows.dll win32deploy\\Dilay\\platforms\n\n\"%ProgramFiles(x86)%\\WiX Toolset v3.11\\bin\\candle.exe\" -dDilayVersion=%4 -out win32deploy/dilay.wixobj %3\\win32\\installer.wix\n\"%ProgramFiles(x86)%\\WiX Toolset v3.11\\bin\\light.exe\" -ext WixUIExtension -b win32deploy -cultures:en-US -out win32deploy/dilay-%4.msi win32deploy/dilay.wixobj\n"
  },
  {
    "path": "win32/installer.wix",
    "content": "<Wix xmlns=\"http://schemas.microsoft.com/wix/2006/wi\">\n  <Product Id=\"*\" UpgradeCode=\"8e37a957-2019-4b44-b5b8-15e128f47df3\"\n           Name=\"Dilay\" Manufacturer=\"A. Bau\" Language=\"1033\"\n           Version=\"$(var.DilayVersion)\">\n    <Package Compressed=\"yes\"/>\n    <Media Id=\"1\" Cabinet=\"dilay.cab\" EmbedCab=\"yes\"/>\n    <UIRef Id=\"WixUI_InstallDir\" />\n    <UIRef Id=\"WixUI_ErrorProgressText\" />\n    <Property Id=\"WIXUI_INSTALLDIR\" Value=\"INSTALLDIR\" />\n    <WixVariable Id=\"WixUILicenseRtf\" Value=\"Dilay\\LICENSE.rtf\" />\n        \n    <Icon Id=\"icon.ico\" SourceFile=\"Dilay\\icon.ico\"/>\n    <Property Id=\"ARPPRODUCTICON\" Value=\"icon.ico\" />\n    \n    <MajorUpgrade AllowDowngrades=\"yes\" />\n     \n    <Directory Id=\"TARGETDIR\" Name=\"SourceDir\">\n      <Directory Id=\"ProgramFilesFolder\">\n        <Directory Id=\"INSTALLDIR\" Name=\"Dilay\">\n          <Component Id=\"compExe\" Guid=\"*\">\n            <File Name=\"dilay.exe\" KeyPath=\"yes\">\n              <Shortcut Id=\"shortcutStartmenu\" Directory=\"dirProgramMenu\" Name=\"Dilay\"\n                Icon=\"icon.ico\" WorkingDirectory=\"INSTALLDIR\" Advertise=\"yes\" />\n              <Shortcut Id=\"shortcutDesktop\" Directory=\"DesktopFolder\" Name=\"Dilay\"\n                Icon=\"icon.ico\" WorkingDirectory=\"INSTALLDIR\" Advertise=\"yes\" />\n            </File>\n          </Component>\n          <Component Id=\"compLibGCC\" Guid=\"*\">\n            <File Name=\"libgcc_s_dw2-1.dll\" KeyPath=\"yes\" />\n          </Component>\n          <Component Id=\"compLibStdCpp\" Guid=\"*\">\n            <File Name=\"libstdc++-6.dll\" KeyPath=\"yes\" />\n          </Component>\n          <Component Id=\"compLibWinPThread\" Guid=\"*\">\n            <File Name=\"libwinpthread-1.dll\" KeyPath=\"yes\" />\n          </Component>\n          <Component Id=\"compQt5Core\" Guid=\"*\">\n            <File Name=\"Qt5Core.dll\" KeyPath=\"yes\" />\n          </Component>\n          <Component Id=\"compQt5Gui\" Guid=\"*\">\n            <File Name=\"Qt5Gui.dll\" KeyPath=\"yes\" />\n          </Component>\n          <Component Id=\"compQt5Widgets\" Guid=\"*\">\n            <File Name=\"Qt5Widgets.dll\" KeyPath=\"yes\" />\n          </Component>\n          <Component Id=\"compQt5Xml\" Guid=\"*\">\n            <File Name=\"Qt5Xml.dll\" KeyPath=\"yes\" />\n          </Component>\n          \n          <Directory Id=\"dirPlatforms\" Name=\"platforms\">\n            <Component Id=\"compQWindows\" Guid=\"*\">\n              <File Name=\"qwindows.dll\" KeyPath=\"yes\" />\n            </Component>\n          </Directory>\n        </Directory>\n      </Directory>\n      \n      <Directory Id=\"ProgramMenuFolder\">\n        <Directory Id=\"dirProgramMenu\" Name=\"Dilay\">\n          <Component Id=\"compProgramMenu\" Guid=\"*\">\n            <RemoveFolder Id=\"removeProgramMenu\" On=\"uninstall\" />\n            <RegistryValue Root=\"HKCU\" Key=\"Software\\[Manufacturer]\\[ProductName]\" Name=\"programMenu\" Type=\"integer\" Value=\"1\" KeyPath=\"yes\" />\n          </Component>\n        </Directory>\n      </Directory>\n      \n      <Directory Id=\"DesktopFolder\" Name=\"Desktop\" />\n    </Directory>    \n    \n    <Feature Id=\"Complete\" Level=\"1\" ConfigurableDirectory=\"INSTALLDIR\">\n      <ComponentRef Id=\"compProgramMenu\"/>\n      <ComponentRef Id=\"compExe\"/>\n      <ComponentRef Id=\"compLibGCC\"/>\n      <ComponentRef Id=\"compLibStdCpp\"/>\n      <ComponentRef Id=\"compLibWinPThread\"/>\n      <ComponentRef Id=\"compQt5Core\"/>\n      <ComponentRef Id=\"compQt5Gui\"/>\n      <ComponentRef Id=\"compQt5Widgets\"/>\n      <ComponentRef Id=\"compQt5Xml\"/>\n      <ComponentRef Id=\"compQWindows\"/>\n    </Feature>\n  </Product>\n</Wix>\n"
  }
]