Repository: abau/dilay Branch: master Commit: 50038bf3431f Files: 232 Total size: 874.3 KB Directory structure: gitextract_luuhfc7x/ ├── .clang-format ├── .gitignore ├── LICENSE.txt ├── README.md ├── app/ │ ├── app.pro │ └── src/ │ └── main.cpp ├── common.pri ├── dilay.pro ├── icon.tex ├── lib/ │ ├── lib.pro │ └── src/ │ ├── IsosurfaceExtractionConfigurations.hs │ ├── bitset.hpp │ ├── cache.hpp │ ├── camera.cpp │ ├── camera.hpp │ ├── color.cpp │ ├── color.hpp │ ├── config.cpp │ ├── config.hpp │ ├── configurable.cpp │ ├── configurable.hpp │ ├── dimension.cpp │ ├── dimension.hpp │ ├── distance.cpp │ ├── distance.hpp │ ├── dynamic/ │ │ ├── faces.cpp │ │ ├── faces.hpp │ │ ├── mesh-intersection.cpp │ │ ├── mesh-intersection.hpp │ │ ├── mesh.cpp │ │ ├── mesh.hpp │ │ ├── octree.cpp │ │ └── octree.hpp │ ├── hash.hpp │ ├── history.cpp │ ├── history.hpp │ ├── import-export.cpp │ ├── import-export.hpp │ ├── intersection.cpp │ ├── intersection.hpp │ ├── isosurface-extraction/ │ │ ├── IsosurfaceExtractionConfigurations.hs │ │ ├── grid.cpp │ │ └── grid.hpp │ ├── isosurface-extraction.cpp │ ├── isosurface-extraction.hpp │ ├── kvstore.cpp │ ├── kvstore.hpp │ ├── log.cpp │ ├── log.hpp │ ├── macro.hpp │ ├── maybe.hpp │ ├── mesh-util.cpp │ ├── mesh-util.hpp │ ├── mesh.cpp │ ├── mesh.hpp │ ├── mirror.cpp │ ├── mirror.hpp │ ├── opengl-buffer-id.cpp │ ├── opengl-buffer-id.hpp │ ├── opengl.cpp │ ├── opengl.hpp │ ├── primitive/ │ │ ├── aabox.cpp │ │ ├── aabox.hpp │ │ ├── cone-sphere.cpp │ │ ├── cone-sphere.hpp │ │ ├── cone.cpp │ │ ├── cone.hpp │ │ ├── cylinder.cpp │ │ ├── cylinder.hpp │ │ ├── plane.cpp │ │ ├── plane.hpp │ │ ├── ray.cpp │ │ ├── ray.hpp │ │ ├── sphere.cpp │ │ ├── sphere.hpp │ │ ├── triangle.cpp │ │ └── triangle.hpp │ ├── render-mode.cpp │ ├── render-mode.hpp │ ├── renderer.cpp │ ├── renderer.hpp │ ├── scene.cpp │ ├── scene.hpp │ ├── shader.cpp │ ├── shader.hpp │ ├── sketch/ │ │ ├── bone-intersection.cpp │ │ ├── bone-intersection.hpp │ │ ├── fwd.hpp │ │ ├── mesh-intersection.cpp │ │ ├── mesh-intersection.hpp │ │ ├── mesh.cpp │ │ ├── mesh.hpp │ │ ├── node-intersection.cpp │ │ ├── node-intersection.hpp │ │ ├── path-intersection.cpp │ │ ├── path-intersection.hpp │ │ ├── path.cpp │ │ └── path.hpp │ ├── state.cpp │ ├── state.hpp │ ├── time-delta.cpp │ ├── time-delta.hpp │ ├── tool/ │ │ ├── convert-sketch.cpp │ │ ├── delete-mesh.cpp │ │ ├── delete-sketch.cpp │ │ ├── edit-sketch.cpp │ │ ├── key.hpp │ │ ├── move-camera.cpp │ │ ├── move-camera.hpp │ │ ├── new-mesh.cpp │ │ ├── remesh.cpp │ │ ├── sculpt/ │ │ │ ├── crease.cpp │ │ │ ├── draw.cpp │ │ │ ├── flatten.cpp │ │ │ ├── grab.cpp │ │ │ ├── pinch.cpp │ │ │ ├── reduce.cpp │ │ │ ├── smooth.cpp │ │ │ └── util/ │ │ │ ├── action.cpp │ │ │ ├── action.hpp │ │ │ ├── brush.cpp │ │ │ ├── brush.hpp │ │ │ ├── edge-collection.cpp │ │ │ └── edge-collection.hpp │ │ ├── sculpt.cpp │ │ ├── sculpt.hpp │ │ ├── sketch-spheres.cpp │ │ ├── transform-mesh.cpp │ │ ├── trim-mesh/ │ │ │ ├── action.cpp │ │ │ ├── action.hpp │ │ │ ├── border.cpp │ │ │ ├── border.hpp │ │ │ ├── split-mesh.cpp │ │ │ └── split-mesh.hpp │ │ ├── trim-mesh.cpp │ │ └── util/ │ │ ├── movement.cpp │ │ ├── movement.hpp │ │ ├── rotation.cpp │ │ ├── rotation.hpp │ │ ├── scaling.cpp │ │ ├── scaling.hpp │ │ ├── step.cpp │ │ └── step.hpp │ ├── tool.cpp │ ├── tool.hpp │ ├── tools.hpp │ ├── tree.hpp │ ├── util.cpp │ ├── util.hpp │ ├── variant.hpp │ ├── view/ │ │ ├── axis.cpp │ │ ├── axis.hpp │ │ ├── color-button.cpp │ │ ├── color-button.hpp │ │ ├── configuration.cpp │ │ ├── configuration.hpp │ │ ├── context-menu.cpp │ │ ├── context-menu.hpp │ │ ├── cursor.cpp │ │ ├── cursor.hpp │ │ ├── double-slider.cpp │ │ ├── double-slider.hpp │ │ ├── floor-plane.cpp │ │ ├── floor-plane.hpp │ │ ├── gl-widget.cpp │ │ ├── gl-widget.hpp │ │ ├── info-pane/ │ │ │ ├── scene.cpp │ │ │ └── scene.hpp │ │ ├── info-pane.cpp │ │ ├── info-pane.hpp │ │ ├── input.cpp │ │ ├── input.hpp │ │ ├── key-event.cpp │ │ ├── key-event.hpp │ │ ├── light.cpp │ │ ├── light.hpp │ │ ├── log.cpp │ │ ├── log.hpp │ │ ├── main-window.cpp │ │ ├── main-window.hpp │ │ ├── menu-bar.cpp │ │ ├── menu-bar.hpp │ │ ├── pointing-event.cpp │ │ ├── pointing-event.hpp │ │ ├── resolution-slider.cpp │ │ ├── resolution-slider.hpp │ │ ├── shortcut.cpp │ │ ├── shortcut.hpp │ │ ├── tool-pane.cpp │ │ ├── tool-pane.hpp │ │ ├── tool-tip.cpp │ │ ├── tool-tip.hpp │ │ ├── two-column-grid.cpp │ │ ├── two-column-grid.hpp │ │ ├── util.cpp │ │ ├── util.hpp │ │ ├── vector-edit.cpp │ │ └── vector-edit.hpp │ ├── xml-conversion.cpp │ └── xml-conversion.hpp ├── test/ │ ├── src/ │ │ ├── main.cpp │ │ ├── test-bitset.cpp │ │ ├── test-bitset.hpp │ │ ├── test-distance.cpp │ │ ├── test-distance.hpp │ │ ├── test-intersection.cpp │ │ ├── test-intersection.hpp │ │ ├── test-maybe.cpp │ │ ├── test-maybe.hpp │ │ ├── test-misc.cpp │ │ ├── test-misc.hpp │ │ ├── test-octree.cpp │ │ ├── test-octree.hpp │ │ ├── test-prune.cpp │ │ ├── test-prune.hpp │ │ ├── test-tree.cpp │ │ └── test-tree.hpp │ └── test.pro ├── unix/ │ ├── dilay.desktop │ └── docker/ │ ├── appimage/ │ │ ├── Dockerfile │ │ └── entrypoint.sh │ ├── debian-sid/ │ │ ├── Dockerfile │ │ └── entrypoint.sh │ ├── ubuntu-bionic/ │ │ ├── Dockerfile │ │ └── entrypoint.sh │ ├── ubuntu-trusty/ │ │ ├── Dockerfile │ │ └── entrypoint.sh │ └── ubuntu-xenial/ │ ├── Dockerfile │ └── entrypoint.sh └── win32/ ├── LICENSE.rtf ├── deploy.bat └── installer.wix ================================================ FILE CONTENTS ================================================ ================================================ FILE: .clang-format ================================================ Language: Cpp AccessModifierOffset: -2 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: true AlignEscapedNewlinesLeft: true AlignOperands: true AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: false BinPackArguments: true BinPackParameters: true BreakBeforeBinaryOperators: None BreakBeforeBraces: Allman BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: true BreakStringLiterals: false ColumnLimit: 100 CommentPragmas: '^ IWYU pragma:' ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 2 ContinuationIndentWidth: 2 Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false FixNamespaceComments: false ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] IncludeCategories: - Regex: '^"' Priority: 0 - Regex: '^<' Priority: -1 - Regex: '.*' Priority: 1 IncludeIsMainRegex: '$' IndentCaseLabels: true IndentWidth: 2 IndentWrappedFunctionNames: false KeepEmptyLinesAtTheStartOfBlocks: false MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: All PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Left ReflowComments: true SortIncludes: true SpaceAfterCStyleCast: true SpaceBeforeAssignmentOperators: true SpaceBeforeParens: Always SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 2 SpacesInAngles: false SpacesInContainerLiterals: false SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp11 UseTab: Never ================================================ FILE: .gitignore ================================================ obj/ moc/ dilay dilay_debug Makefile archive/ i18n/*.qm run-tests lib/Makefile lib/Makefile.Release lib/Makefile.Debug lib/libdilay.a app/Makefile app/Makefile.Release app/Makefile.Debug app/translations test/Makefile test/Makefile.Release test/Makefile.Debug valgrind.log .qmake.stash icon.pdf icon.png ================================================ FILE: LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. 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. 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. 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. 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. 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. 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. 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. 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. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "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. 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. A "covered work" means either the unmodified Program or a work based on the Program. 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. 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. 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. 1. Source Code. 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. 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. 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. 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. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. 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. 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. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 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. 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. 4. Conveying Verbatim Copies. 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. 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. 5. Conveying Modified Source Versions. 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: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 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". 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. 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. 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. 6. Conveying Non-Source Forms. 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: 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. 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. 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. 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. 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. 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. 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. "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. 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). 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. 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. 7. Additional Terms. "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. 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. 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: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 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 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 d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 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. 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. 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. 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. 8. Termination. 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). 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. 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. 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. 9. Acceptance Not Required for Having Copies. 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. 10. Automatic Licensing of Downstream Recipients. 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. 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. 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. 11. Patents. 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". 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. 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. 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. 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. 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. 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. 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. 12. No Surrender of Others' Freedom. 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. 13. Use with the GNU Affero General Public License. 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. 14. Revised Versions of this License. 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. 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. 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. 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. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. 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. 17. Interpretation of Sections 15 and 16. 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. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Dilay - a 3D sculpting application **Project website:** https://abau.org/dilay **Building instructions:** https://abau.org/dilay/manual.html#installing ================================================ FILE: app/app.pro ================================================ include (../common.pri) TEMPLATE = app DESTDIR = $$OUT_PWD/.. DEPENDPATH += src INCLUDEPATH += src $$PWD/../lib/src SOURCES += src/main.cpp CONFIG(release, debug|release): TARGET = dilay CONFIG(debug , debug|release): TARGET = dilay_debug win32 { CONFIG(release, debug|release) { LIBS += -L$$OUT_PWD/../lib/release/ -ldilay win32-g++ { PRE_TARGETDEPS += $$OUT_PWD/../lib/release/libdilay.a } else { PRE_TARGETDEPS += $$OUT_PWD/../lib/release/dilay.lib } } CONFIG(debug, debug|release) { LIBS += -L$$OUT_PWD/../lib/debug/ -ldilay win32-g++ { PRE_TARGETDEPS += $$OUT_PWD/../lib/debug/libdilay.a } else { PRE_TARGETDEPS += $$OUT_PWD/../lib/debug/dilay.lib } } RC_ICONS = $$PWD/../win32/icon.ico QMAKE_POST_LINK += $$PWD/../win32/deploy.bat $$shell_path($$[QT_INSTALL_PREFIX]) \ $$shell_path($$DESTDIR) \ $$shell_path($$PWD/../) \ $$VERSION } unix { LIBS += -L$$OUT_PWD/../lib/ -ldilay PRE_TARGETDEPS += $$OUT_PWD/../lib/libdilay.a target.path = $$PREFIX/bin/ INSTALLS += target desktop.path = $$PREFIX/share/applications/ desktop.files = ../unix/dilay.desktop INSTALLS += desktop icon16.path = $$PREFIX/share/icons/hicolor/16x16/apps/ icon16.files = ../unix/icon/16x16/dilay.png INSTALLS += icon16 icon32.path = $$PREFIX/share/icons/hicolor/32x32/apps/ icon32.files = ../unix/icon/32x32/dilay.png INSTALLS += icon32 icon48.path = $$PREFIX/share/icons/hicolor/48x48/apps/ icon48.files = ../unix/icon/48x48/dilay.png INSTALLS += icon48 icon256.path = $$PREFIX/share/icons/hicolor/256x256/apps/ icon256.files = ../unix/icon/256x256/dilay.png INSTALLS += icon256 format.commands = clang-format -style=file -i $$SOURCES $$HEADERS QMAKE_EXTRA_TARGETS += format } ================================================ FILE: app/src/main.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include "cache.hpp" #include "config.hpp" #include "opengl.hpp" #include "time-delta.hpp" #include "util.hpp" #include "view/log.hpp" #include "view/main-window.hpp" namespace { QString configPath () { return QStandardPaths::locate (QStandardPaths::ConfigLocation, "dilay.config"); } void backupCrashLog () { QFile log (ViewLog::logPath ()); QFile crashLog (ViewLog::crashLogPath ()); if (log.exists ()) { if (crashLog.exists ()) { crashLog.remove (); } log.rename (ViewLog::crashLogPath ()); } } } int main (int argv, char** args) { backupCrashLog (); Log::initialize (ViewLog::logPath ().toStdString ()); DILAY_INFO ("Version: %s", DILAY_VERSION); DILAY_INFO ("Architecture: %s", QSysInfo::buildCpuArchitecture ().toStdString ().c_str ()); DILAY_INFO ("OS: %s", QSysInfo::prettyProductName ().toStdString ().c_str ()); DILAY_INFO ("Qt: %s", QLibraryInfo::version ().toString ().toStdString ().c_str ()); QCoreApplication::setApplicationName ("Dilay"); QCoreApplication::setAttribute (Qt::AA_UseDesktopOpenGL); OpenGL::setDefaultFormat (); QApplication app (argv, args); Config config; Cache cache; if (configPath ().isEmpty () == false) { config.fromFile (configPath ().toStdString ()); } ViewMainWindow mainWindow (config, cache); mainWindow.resize (config.get ("window/initial-width"), config.get ("window/initial-height")); mainWindow.show (); QObject::connect (&app, &QApplication::aboutToQuit, [&config]() { const QString configDirName (QStandardPaths::writableLocation (QStandardPaths::ConfigLocation)); const QDir configDir (configDirName); if (configDirName.isEmpty () == false) { if (configDir.exists () == false) { configDir.mkpath ("."); } config.toFile (configDir.filePath ("dilay.config").toStdString ()); } }); TimeDelta::initialize (); return app.exec (); } ================================================ FILE: common.pri ================================================ VERSION = 1.9.0 CONFIG += debug_and_release warn_on object_parallel_to_source ordered c++14 QT += widgets opengl openglextensions xml MOC_DIR = moc OBJECTS_DIR = obj QMAKE_CXXFLAGS += -DDILAY_VERSION=\\\"$$VERSION\\\" -DGLM_FORCE_RADIANS -DGLM_ENABLE_EXPERIMENTAL QMAKE_CXXFLAGS_RELEASE += -DNDEBUG QMAKE_CXXFLAGS_DEBUG += -Wall # -pg # -DDILAY_RENDER_OCTREE QMAKE_LFLAGS_DEBUG += # -pg win32:INCLUDEPATH += $$PWD/glm/ unix { isEmpty (PREFIX) { PREFIX = /usr/local } } ================================================ FILE: dilay.pro ================================================ CONFIG += debug_and_release TEMPLATE = subdirs SUBDIRS = lib app test app.depends = lib test.depends = lib disable-test { SUBDIRS -= test } disable-app { SUBDIRS -= app } unix { gdb.commands = gdb -ex run ./dilay_debug valgrind.commands = valgrind ./dilay_debug &> valgrind.log leak.commands = valgrind --leak-check=yes ./dilay_debug &> valgrind.log format.CONFIG = recursive copyright.commands = find $$SUBDIRS \\( -name "*.cpp" -o -name "*.hpp" -o -name "*.hs" \\) -print0 | \ xargs -0 sed -i 's/Copyright\ ©\ 2015-2017/Copyright\ ©\ 2015-2018/' docker.commands = docker build -t dilay-$(IMAGE) unix/docker/$(IMAGE) && \ docker run --rm --mount type=bind,src=$$(PWD),dst=/dilay dilay-$(IMAGE) QMAKE_EXTRA_TARGETS += gdb valgrind leak format copyright icon docker } ================================================ FILE: icon.tex ================================================ \documentclass[crop,tikz,convert={size=512x512,outext=.png}]{standalone} \usetikzlibrary{shapes.geometric} \begin{document} \begin{tikzpicture} [linestyle/.style={draw=black!80,line width=5pt,transform shape}, emptylinestyle/.style={transform shape}, circlestyle/.style={fill=black!80,circle,minimum size=10pt}] \begin{scope}[rotate=-10] \shadedraw [shading=ball, ball color=black!10] (0,0) circle (101pt); \node[linestyle,circle,minimum size=201pt] {}; \node[emptylinestyle,regular polygon, regular polygon sides=9,rotate=20, minimum size=200pt] (p) {}; \node[emptylinestyle, regular polygon, regular polygon sides=3,minimum size=120pt] (t) {}; \node[linestyle, regular polygon, regular polygon sides=3,minimum size=120pt] {}; \draw [linestyle] (t.corner 1) -- (p.corner 1); \draw [linestyle] (t.corner 1) -- (p.corner 2); \draw [linestyle] (t.corner 1) -- (p.corner 8); \draw [linestyle] (t.corner 1) -- (p.corner 9); \draw [linestyle] (t.corner 2) -- (p.corner 2); \draw [linestyle] (t.corner 2) -- (p.corner 3); \draw [linestyle] (t.corner 2) -- (p.corner 4); \draw [linestyle] (t.corner 2) -- (p.corner 5); \draw [linestyle] (t.corner 3) -- (p.corner 5); \draw [linestyle] (t.corner 3) -- (p.corner 6); \draw [linestyle] (t.corner 3) -- (p.corner 7); \draw [linestyle] (t.corner 3) -- (p.corner 8); \node [circlestyle] at (t.corner 1) {}; \node [circlestyle] at (t.corner 2) {}; \node [circlestyle] at (t.corner 3) {}; \node [circlestyle] at (p.corner 1) {}; \node [circlestyle] at (p.corner 2) {}; \node [circlestyle] at (p.corner 3) {}; \node [circlestyle] at (p.corner 4) {}; \node [circlestyle] at (p.corner 5) {}; \node [circlestyle] at (p.corner 6) {}; \node [circlestyle] at (p.corner 7) {}; \node [circlestyle] at (p.corner 8) {}; \node [circlestyle] at (p.corner 9) {}; \end{scope} \end{tikzpicture} \end{document} ================================================ FILE: lib/lib.pro ================================================ include (../common.pri) TEMPLATE = lib TARGET = dilay DEPENDPATH += src INCLUDEPATH += src CONFIG += staticlib SOURCES += \ src/camera.cpp \ src/color.cpp \ src/config.cpp \ src/configurable.cpp \ src/dimension.cpp \ src/distance.cpp \ src/dynamic/faces.cpp \ src/dynamic/mesh.cpp \ src/dynamic/mesh-intersection.cpp \ src/dynamic/octree.cpp \ src/history.cpp \ src/import-export.cpp \ src/intersection.cpp \ src/isosurface-extraction.cpp \ src/isosurface-extraction/grid.cpp \ src/kvstore.cpp \ src/log.cpp \ src/mesh.cpp \ src/mesh-util.cpp \ src/mirror.cpp \ src/opengl.cpp \ src/opengl-buffer-id.cpp \ src/primitive/aabox.cpp \ src/primitive/cone.cpp \ src/primitive/cone-sphere.cpp \ src/primitive/cylinder.cpp \ src/primitive/plane.cpp \ src/primitive/ray.cpp \ src/primitive/sphere.cpp \ src/primitive/triangle.cpp \ src/render-mode.cpp \ src/renderer.cpp \ src/scene.cpp \ src/shader.cpp \ src/sketch/bone-intersection.cpp \ src/sketch/mesh.cpp \ src/sketch/mesh-intersection.cpp \ src/sketch/node-intersection.cpp \ src/sketch/path.cpp \ src/sketch/path-intersection.cpp \ src/state.cpp \ src/time-delta.cpp \ src/tool.cpp \ src/tool/convert-sketch.cpp \ src/tool/delete-mesh.cpp \ src/tool/delete-sketch.cpp \ src/tool/edit-sketch.cpp \ src/tool/move-camera.cpp \ src/tool/new-mesh.cpp \ src/tool/remesh.cpp \ src/tool/sculpt.cpp \ src/tool/sculpt/draw.cpp \ src/tool/sculpt/crease.cpp \ src/tool/sculpt/flatten.cpp \ src/tool/sculpt/grab.cpp \ src/tool/sculpt/pinch.cpp \ src/tool/sculpt/reduce.cpp \ src/tool/sculpt/smooth.cpp \ src/tool/sculpt/util/action.cpp \ src/tool/sculpt/util/brush.cpp \ src/tool/sculpt/util/edge-collection.cpp \ src/tool/sketch-spheres.cpp \ src/tool/transform-mesh.cpp \ src/tool/trim-mesh.cpp \ src/tool/trim-mesh/action.cpp \ src/tool/trim-mesh/border.cpp \ src/tool/trim-mesh/split-mesh.cpp \ src/tool/util/movement.cpp \ src/tool/util/rotation.cpp \ src/tool/util/scaling.cpp \ src/tool/util/step.cpp \ src/util.cpp \ src/view/axis.cpp \ src/view/color-button.cpp \ src/view/configuration.cpp \ src/view/context-menu.cpp \ src/view/cursor.cpp \ src/view/double-slider.cpp \ src/view/floor-plane.cpp \ src/view/gl-widget.cpp \ src/view/info-pane.cpp \ src/view/info-pane/scene.cpp \ src/view/input.cpp \ src/view/key-event.cpp \ src/view/light.cpp \ src/view/log.cpp \ src/view/main-window.cpp \ src/view/menu-bar.cpp \ src/view/pointing-event.cpp \ src/view/resolution-slider.cpp \ src/view/shortcut.cpp \ src/view/tool-pane.cpp \ src/view/tool-tip.cpp \ src/view/two-column-grid.cpp \ src/view/util.cpp \ src/view/vector-edit.cpp \ src/xml-conversion.cpp \ HEADERS += \ src/bitset.hpp \ src/cache.hpp \ src/camera.hpp \ src/color.hpp \ src/config.hpp \ src/configurable.hpp \ src/dimension.hpp \ src/distance.hpp \ src/dynamic/faces.hpp \ src/dynamic/mesh.hpp \ src/dynamic/mesh-intersection.hpp \ src/dynamic/octree.hpp \ src/hash.hpp \ src/history.hpp \ src/import-export.hpp \ src/intersection.hpp \ src/isosurface-extraction.hpp \ src/isosurface-extraction/grid.hpp \ src/kvstore.hpp \ src/log.hpp \ src/macro.hpp \ src/maybe.hpp \ src/mesh.hpp \ src/mesh-util.hpp \ src/mirror.hpp \ src/opengl.hpp \ src/opengl-buffer-id.hpp \ src/primitive/aabox.hpp \ src/primitive/cone.hpp \ src/primitive/cone-sphere.hpp \ src/primitive/cylinder.hpp \ src/primitive/plane.hpp \ src/primitive/ray.hpp \ src/primitive/sphere.hpp \ src/primitive/triangle.hpp \ src/render-mode.hpp \ src/renderer.hpp \ src/scene.hpp \ src/shader.hpp \ src/sketch/bone-intersection.hpp \ src/sketch/fwd.hpp \ src/sketch/mesh.hpp \ src/sketch/mesh-intersection.hpp \ src/sketch/node-intersection.hpp \ src/sketch/path.hpp \ src/sketch/path-intersection.hpp \ src/state.hpp \ src/time-delta.hpp \ src/tool.hpp \ src/tool/key.hpp \ src/tool/move-camera.hpp \ src/tool/sculpt.hpp \ src/tool/sculpt/util/action.hpp \ src/tool/sculpt/util/brush.hpp \ src/tool/sculpt/util/edge-collection.hpp \ src/tool/trim-mesh/action.hpp \ src/tool/trim-mesh/border.hpp \ src/tool/trim-mesh/split-mesh.hpp \ src/tool/util/movement.hpp \ src/tool/util/rotation.hpp \ src/tool/util/scaling.hpp \ src/tool/util/step.hpp \ src/tools.hpp \ src/tree.hpp \ src/util.hpp \ src/variant.hpp \ src/view/axis.hpp \ src/view/color-button.hpp \ src/view/configuration.hpp \ src/view/context-menu.hpp \ src/view/cursor.hpp \ src/view/double-slider.hpp \ src/view/floor-plane.cpp \ src/view/gl-widget.hpp \ src/view/info-pane.hpp \ src/view/info-pane/scene.hpp \ src/view/input.hpp \ src/view/key-event.hpp \ src/view/light.hpp \ src/view/log.hpp \ src/view/main-window.hpp \ src/view/menu-bar.hpp \ src/view/pointing-event.hpp \ src/view/resolution-slider.hpp \ src/view/shortcut.hpp \ src/view/tool-pane.hpp \ src/view/tool-tip.hpp \ src/view/two-column-grid.hpp \ src/view/util.hpp \ src/view/vector-edit.hpp \ src/xml-conversion.hpp \ unix { format.commands = clang-format -style=file -i $$SOURCES $$HEADERS QMAKE_EXTRA_TARGETS += format } ================================================ FILE: lib/src/IsosurfaceExtractionConfigurations.hs ================================================ {- This file is part of Dilay - Copyright © 2015-2018 Alexander Bau - Use and redistribute under the terms of the GNU General Public License -} import Control.Exception (assert) import Control.Monad (forM_) import Data.Char (toLower) import Data.Function (on) import Data.List (intercalate,nubBy,sortBy) data Configuration = Configuration { base :: Int , vertices :: [Bool] , vertexIndices :: [Int] , nonManifoldConfig :: Bool } deriving Show set :: Int -> a -> [a] -> [a] set 0 x (y:ys) = x:ys set i x (y:ys) = y:(set (i - 1) x ys) setList :: [Int] -> a -> [a] -> [a] setList is value xs = foldl (\xs i -> set i value xs) xs is baseConfigurations :: [Configuration] baseConfigurations = [ go 0 [] [] False , go 1 [4] [[2, 6, 7]] False , go 2 [4, 5] [[2, 5, 7, 10]] False , go 3 [4, 7] [[2, 6, 7], [9, 10, 11]] False , go 4 [3, 4] [[2, 6, 7], [3, 4, 11]] False , go 5 [0, 1, 5] [[1, 2, 4, 6, 10]] False , go 6 [3, 4, 5] [[2, 5, 7, 10], [3, 4, 11]] False , go 7 [3, 5, 6] [[7, 8, 9], [3, 4, 11], [5, 6, 10]] False , go 8 [0, 1, 4, 5] [[1, 4, 7, 10]] False , go 9 [0, 1, 2, 4] [[3, 4, 5, 6, 7, 8]] False , go 10 [1, 3, 4, 6] [[2, 6, 8, 9], [0, 3, 5, 11]] False , go 11 [0, 1, 3, 4] [[1, 3, 5, 6, 7, 11]] False , go 12 [0, 1, 5, 6] [[7, 8, 9], [1, 2, 4, 6, 10]] False , go 13 [1, 2, 4, 7] [[2, 6, 7], [9, 10, 11], [1, 3, 8], [0, 4, 5]] False , go 14 [0, 1, 2, 5] [[2, 3, 4, 6, 8, 10]] False , go 15 [0, 1, 2, 4, 7] [[3, 4, 5, 6, 7, 8], [9, 10, 11]] False , go 16 [0, 1, 2, 6, 7] [[2, 5, 7, 10], [3, 4, 11]] True , go 17 [2, 3, 4, 6, 7] [[1, 2, 4, 6, 10]] False , go 18 [0, 1, 2, 5, 6, 7] [[2, 6, 7], [3, 4, 11]] False , go 19 [0, 1, 2, 3, 5, 6] [[2, 6, 7], [9, 10, 11]] True , go 20 [0, 1, 2, 3, 6, 7] [[2, 5, 7, 10]] False , go 21 [0, 1, 2, 3, 5, 6, 7] [[2, 6, 7]] False , go 22 [0, 1, 2, 3, 4, 5, 6, 7] [] False ] where go base vertices vertexIndices nonManifold = Configuration base (setList vertices True $ replicate 8 False) (mkVertexIndices 0 vertexIndices) nonManifold mkVertexIndices :: Int -> [[Int]] -> [Int] mkVertexIndices vertexIndex [] = replicate 12 (-1) mkVertexIndices vertexIndex (edgeGroup:edgeGroups) = setList edgeGroup vertexIndex rest where rest = mkVertexIndices (vertexIndex + 1) edgeGroups allConfigurations :: [Configuration] allConfigurations = sortBy (sort `on` vertices) $ nubBy ((==) `on` vertices) $ concat $ do x <- [id, rotateX, rotateX . rotateX, rotateX . rotateX . rotateX] y <- [id, rotateY, rotateY . rotateY, rotateY . rotateY . rotateY] z <- [id, rotateZ, rotateZ . rotateZ, rotateZ . rotateZ . rotateZ] return $ map (($) (x . y . z)) baseConfigurations where rotateX (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7] [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold) = Configuration base [v4, v5, v0, v1, v6, v7, v2, v3] [e6, e2, e7, e0, e5, e10, e9, e8, e1, e3, e11, e4] nonManifold rotateY (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7] [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold) = Configuration base [v1, v5, v3, v7, v0, v4, v2, v6] [e5, e4, e0, e11, e10, e6, e2, e1, e3, e8, e7, e9] nonManifold rotateZ (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7] [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold) = Configuration base [v2, v0, v3, v1, v6, v4, v7, v5] [e1, e3, e8, e4, e0, e2, e7, e9, e11, e10, e6, e5] nonManifold sort xs ys = go (reverse xs) (reverse ys) where go (False:xs) (True:ys) = LT go (True:xs) (False:ys) = GT go (_:xs) (_:ys) = go xs ys main :: IO () main = assert (length allConfigurations == 256) $ printBases >> printNonManifold >> printVertexIndices where printBases = putStrLn $ toList (show . base) allConfigurations printNonManifold = putStrLn $ toList (map toLower . show . nonManifoldConfig) allConfigurations printVertexIndices = putStrLn $ toList (\c -> toList show (vertexIndices c) ++ "\n") allConfigurations toList xToString xs = unwords $ "{" : [ intercalate ", " $ map xToString xs ] ++ ["}"] ================================================ FILE: lib/src/bitset.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_BITSET #define DILAY_BITSET #include template class Bitset { public: Bitset () : _data (0) { } Bitset (const Bitset& other) : _data (other._data) { } template bool get () const { static_assert (N < sizeof (T) * 8, "invalid bitset index"); return this->_data & 1 << N; } template void set (bool value = true) { static_assert (N < sizeof (T) * 8, "invalid bitset index"); if (value) { this->_data = this->_data | 1 << N; } else { this->_data = this->_data & ~(1 << N); } } template void toggle () { this->set (!this->get ()); } template void reset () { this->set (false); } void reset () { this->_data = 0; } bool none () const { return this->_data == 0; } template bool all () const { static_assert (N < sizeof (T) * 8, "invalid bitset index"); const T allBits = std::pow (2, N) - 1; return (this->_data & allBits) == allBits; } T value () const { return this->_data; } private: T _data; }; #endif ================================================ FILE: lib/src/cache.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_CACHE #define DILAY_CACHE #include "kvstore.hpp" class Cache { public: Cache () : store ("cache") { } template const T& get (const std::string& path, const T& value) const { return this->store.get (path, value); } template void set (const std::string& path, const T& value) { this->store.set (path, value); } private: KVStore store; }; class CacheProxy { public: CacheProxy (Cache& c, const std::string& p) : _cache (c) , prefix (p) { assert (p.back () == '/'); } CacheProxy (CacheProxy& o, const std::string& path) : CacheProxy (o._cache, o.prefix + path) { } Cache& cache () const { return this->_cache; } std::string key (const std::string& path) const { return this->prefix + path; } template const T& get (const std::string& path, const T& v) const { return this->_cache.get (this->key (path), v); } template void set (const std::string& path, const T& v) const { return this->_cache.set (this->key (path), v); } private: Cache& _cache; const std::string prefix; }; #endif ================================================ FILE: lib/src/camera.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "camera.hpp" #include "config.hpp" #include "dimension.hpp" #include "intersection.hpp" #include "opengl.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "renderer.hpp" #include "util.hpp" struct Camera::Impl { Camera* self; Renderer renderer; glm::vec3 gazePoint; glm::vec3 toEyePoint; glm::vec3 right; glm::mat4x4 projection; glm::mat4x4 view; glm::mat4x4 viewRotation; glm::uvec2 resolution; float nearClipping; float farClipping; float fieldOfView; Impl (Camera* s, const Config& config) : self (s) , renderer (config) , resolution (config.get ("window/initial-width"), config.get ("window/initial-height")) { this->set (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 0.0f, 6.0f)); this->runFromConfig (config); } const glm::vec3& up () const { static const glm::vec3 up (0.0f, 1.0f, 0.0f); return up; } glm::vec3 realUp () const { return glm::normalize (glm::cross (this->toEyePoint, this->right)); } glm::vec3 position () const { return this->gazePoint + this->toEyePoint; } glm::mat4x4 world () const { const glm::vec3 x = this->right; const glm::vec3 z = glm::normalize (this->toEyePoint); const glm::vec3 y = glm::cross (z, x); const glm::vec3 p = this->position (); return glm::colMajor4 (glm::vec4 (x, 0.0f), glm::vec4 (y, 0.0f), glm::vec4 (z, 0.0f), glm::vec4 (p, 1.0f)); } void updateResolution (const glm::uvec2& dimension) { this->resolution = dimension; this->updateProjection (); } void setModelViewProjection (const glm::mat4x4& model, const glm::mat3x3& modelNormal, bool onlyRotation) { this->renderer.setModel (&model[0][0], &modelNormal[0][0]); this->renderer.setProjection (&this->projection[0][0]); if (onlyRotation) { this->renderer.setView (&this->viewRotation[0][0]); } else { this->renderer.setView (&this->view[0][0]); } } void set (const glm::vec3& g, const glm::vec3& e) { this->gazePoint = g; this->toEyePoint = e; if (Util::colinear (e, this->up ())) { this->right = glm::vec3 (1.0f, 0.0f, 0.0f); } else { this->right = glm::normalize (glm::cross (this->up (), this->toEyePoint)); } this->updateView (); } void setGaze (const glm::vec3& g) { this->gazePoint = g; this->updateView (); } void stepAlongGaze (float factor) { constexpr float minD = 0.01f; constexpr float maxD = 1000.0f; const float d = glm::length (this->toEyePoint); const float newD = d * factor; if (minD <= newD && newD <= maxD) { this->toEyePoint *= glm::vec3 (factor); } this->updateView (); } void verticalRotation (float angle) { const glm::quat q = glm::angleAxis (angle, this->up ()); this->right = glm::rotate (q, this->right); this->toEyePoint = glm::rotate (q, this->toEyePoint); this->updateView (); } void horizontalRotation (float angle) { const glm::quat q = glm::angleAxis (angle, this->right); this->toEyePoint = glm::rotate (q, this->toEyePoint); this->updateView (); } glm::vec4 viewport () const { return glm::vec4 (0, 0, this->resolution.x, this->resolution.y); } glm::vec2 fromWorld (const glm::vec3& p, const glm::mat4x4& model, bool onlyRotation) const { const glm::mat4x4 mv = onlyRotation ? this->viewRotation * model : this->view * model; const glm::vec3 w = glm::project (p, mv, this->projection, this->viewport ()); return glm::vec2 (w.x, float(resolution.y) - w.y); } glm::vec3 toWorld (const glm::ivec2& p, float z = 0.0f) const { const float invY = this->resolution.y - float(p.y); const float normZ = z / this->farClipping; return glm::unProject (glm::vec3 (float(p.x), invY, normZ), this->view, this->projection, this->viewport ()); } float toWorld (float length, float z) { const float onNearPlane = 2.0f * this->nearClipping * glm::tan (this->fieldOfView * 0.5f) * length / float(this->resolution.x); return onNearPlane * (this->nearClipping + z) / this->nearClipping; } PrimRay ray (const glm::ivec2& p) const { const glm::vec3 w = this->toWorld (p); const glm::vec3 eye = this->position (); return PrimRay (eye, w - eye); } void updateProjection () { OpenGL::glViewport (0, 0, this->resolution.x, this->resolution.y); this->projection = glm::perspective (this->fieldOfView, float(this->resolution.x) / float(this->resolution.y), this->nearClipping, this->farClipping); } void updateView () { const glm::vec3 up = this->realUp (); this->view = glm::lookAt (this->position (), this->gazePoint, up); this->viewRotation = glm::lookAt (glm::normalize (this->toEyePoint), glm::vec3 (0.0f), up); this->renderer.setEyePoint (this->position ()); } Dimension primaryDimension () const { const glm::vec3 t = glm::abs (this->toEyePoint); if (t.x > t.y && t.x > t.z) { return Dimension::X; } else if (t.y > t.z) { return Dimension::Y; } return Dimension::Z; } glm::vec3 planeIntersection (const glm::ivec2& p, const PrimPlane& plane) const { const PrimRay ray = this->ray (p); float t; if (IntersectionUtil::intersects (ray, plane, &t)) { return ray.pointAt (t); } else { DILAY_WARN ("No view-plane intersection"); return plane.point (); } } glm::vec3 viewPlaneIntersection (const glm::ivec2& p) const { const PrimPlane plane (this->gazePoint, this->toEyePoint); return this->planeIntersection (p, plane); } glm::vec3 primaryPlaneIntersection (const glm::ivec2& p) const { const PrimPlane plane (this->gazePoint, DimensionUtil::vector (this->primaryDimension ())); return this->planeIntersection (p, plane); } void runFromConfig (const Config& config) { this->renderer.fromConfig (config); this->nearClipping = config.get ("editor/camera/near-clipping"); this->farClipping = config.get ("editor/camera/far-clipping"); this->fieldOfView = glm::radians (config.get ("editor/camera/field-of-view")); this->updateProjection (); } }; DELEGATE1_BIG3_SELF (Camera, const Config&) GETTER_CONST (Renderer&, Camera, renderer) GETTER_CONST (const glm::uvec2&, Camera, resolution) GETTER_CONST (const glm::vec3&, Camera, gazePoint) GETTER_CONST (const glm::vec3&, Camera, toEyePoint) DELEGATE_CONST (glm::vec3, Camera, realUp) GETTER_CONST (const glm::vec3&, Camera, right) GETTER_CONST (const glm::mat4x4&, Camera, view) GETTER_CONST (const glm::mat4x4&, Camera, viewRotation) DELEGATE_CONST (glm::vec3, Camera, position) DELEGATE_CONST (glm::mat4x4, Camera, world) DELEGATE1 (void, Camera, updateResolution, const glm::uvec2&) DELEGATE3 (void, Camera, setModelViewProjection, const glm::mat4x4&, const glm::mat3x3&, bool) DELEGATE2 (void, Camera, set, const glm::vec3&, const glm::vec3&) DELEGATE1 (void, Camera, setGaze, const glm::vec3&) DELEGATE1 (void, Camera, stepAlongGaze, float) DELEGATE1 (void, Camera, verticalRotation, float) DELEGATE1 (void, Camera, horizontalRotation, float) DELEGATE3_CONST (glm::vec2, Camera, fromWorld, const glm::vec3&, const glm::mat4x4&, bool) DELEGATE2_CONST (glm::vec3, Camera, toWorld, const glm::ivec2&, float) DELEGATE2_CONST (float, Camera, toWorld, float, float) DELEGATE1_CONST (PrimRay, Camera, ray, const glm::ivec2&) DELEGATE_CONST (Dimension, Camera, primaryDimension) DELEGATE1_CONST (glm::vec3, Camera, viewPlaneIntersection, const glm::ivec2&) DELEGATE1_CONST (glm::vec3, Camera, primaryPlaneIntersection, const glm::ivec2&) DELEGATE1 (void, Camera, runFromConfig, const Config&) ================================================ FILE: lib/src/camera.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_CAMERA #define DILAY_CAMERA #include #include "configurable.hpp" #include "macro.hpp" enum class Dimension; class PrimRay; class Renderer; class Camera : public Configurable { public: DECLARE_BIG3 (Camera, const Config&) Renderer& renderer () const; const glm::uvec2& resolution () const; const glm::vec3& gazePoint () const; const glm::vec3& toEyePoint () const; glm::vec3 realUp () const; const glm::vec3& right () const; const glm::mat4x4& view () const; const glm::mat4x4& viewRotation () const; glm::vec3 position () const; glm::mat4x4 world () const; void updateResolution (const glm::uvec2&); void setModelViewProjection (const glm::mat4x4&, const glm::mat3x3&, bool); void set (const glm::vec3&, const glm::vec3&); void setGaze (const glm::vec3&); void stepAlongGaze (float); void verticalRotation (float); void horizontalRotation (float); glm::vec2 fromWorld (const glm::vec3&, const glm::mat4x4&, bool) const; glm::vec3 toWorld (const glm::ivec2&, float = 0.0f) const; float toWorld (float, float = 0.0f) const; PrimRay ray (const glm::ivec2&) const; Dimension primaryDimension () const; glm::vec3 viewPlaneIntersection (const glm::ivec2&) const; glm::vec3 primaryPlaneIntersection (const glm::ivec2&) const; private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/color.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "color.hpp" #include "util.hpp" Color::Color (float r, float g, float b, float o) : _r (r) , _g (g) , _b (b) , _opacity (o) { } Color::Color () : Color (0.0f, 0.0f, 0.0f, 1.0f) { } Color::Color (float v) : Color (v, v, v, 1.0f) { } Color::Color (float r, float g, float b) : Color (r, g, b, 1.0f) { } Color::Color (const glm::vec3& v) : Color (v.x, v.y, v.z) { } Color::Color (const glm::vec4& v) : Color (v.x, v.y, v.z, v.w) { } Color::Color (const QColor& c) : Color (c.redF (), c.greenF (), c.blueF (), c.alphaF ()) { } Color::Color (const Color& c, float f) : Color (c) { this->scale (f); } Color Color::Black () { return Color (0.0f, 0.0f, 0.0f); } Color Color::White () { return Color (1.0f, 1.0f, 1.0f); } Color Color::Red () { return Color (1.0f, 0.0f, 0.0f); } Color Color::Green () { return Color (0.0f, 1.0f, 0.0f); } Color Color::Blue () { return Color (0.0f, 0.0f, 1.0f); } float Color::r () const { return this->_r; } float Color::g () const { return this->_g; } float Color::b () const { return this->_b; } float Color::opacity () const { return this->_opacity; } void Color::r (float v) { this->_r = v; } void Color::g (float v) { this->_g = v; } void Color::b (float v) { this->_b = v; } void Color::opacity (float v) { this->_opacity = v; } void Color::scale (float f) { this->_r = f * this->_r; this->_g = f * this->_g; this->_b = f * this->_b; } glm::vec3 Color::vec3 () const { return glm::vec3 (this->_r, this->_g, this->_b); } glm::vec4 Color::vec4 () const { return glm::vec4 (this->_r, this->_g, this->_b, this->_opacity); } QColor Color::qColor () const { return QColor (glm::min (255, int(255.0f * this->_r)), glm::min (255, int(255.0f * this->_g)), glm::min (255, int(255.0f * this->_b)), glm::min (255, int(255.0f * this->_opacity))); } bool Color::isOpaque () const { return Util::almostEqual (this->_opacity, 1.0f); } ================================================ FILE: lib/src/color.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_COLOR #define DILAY_COLOR #include class QColor; class Color { public: Color (); Color (float); Color (float, float, float); Color (float, float, float, float); explicit Color (const glm::vec3&); explicit Color (const glm::vec4&); explicit Color (const QColor&); // copies and scales a color using `scale` Color (const Color&, float); static Color Black (); static Color White (); static Color Red (); static Color Green (); static Color Blue (); float r () const; float g () const; float b () const; float opacity () const; void r (float); void g (float); void b (float); void opacity (float); // `scale` does not scale opacity void scale (float); glm::vec3 vec3 () const; glm::vec4 vec4 () const; QColor qColor () const; bool isOpaque () const; private: float _r; float _g; float _b; float _opacity; }; #endif ================================================ FILE: lib/src/config.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "color.hpp" #include "config.hpp" namespace { static constexpr int latestVersion = 10; template void updateValue (Config& config, const std::string& path, const T& oldValue, const T& newValue) { if (config.get (path) == oldValue) { config.set (path, newValue); } } template void forceUpdateValue (Config& config, const std::string& path, const T& newValue) { config.set (path, newValue); } template void mapValue (Config& config, const std::string& path, const std::function& f) { config.set (path, f (config.get (path))); } } Config::Config () : store ("config") { this->restoreDefaults (); } void Config::restoreDefaults () { this->store.reset (); this->set ("version", latestVersion); this->set ("editor/axis/color/normal", Color (0.3f, 0.3f, 0.4f)); this->set ("editor/axis/color/label", Color (1.0f, 1.0f, 1.0f)); this->set ("editor/axis/scaling", glm::vec3 (0.01f, 0.3f, 0.01f)); this->set ("editor/axis/arrow-scaling", glm::vec3 (0.03f, 0.1f, 0.03f)); this->set ("editor/floor-plane/color", Color (0.3f, 0.3f, 0.4f)); this->set ("editor/floor-plane/tile-width", 1.0f); this->set ("editor/background", Color (0.1f, 0.1f, 0.2f)); this->set ("editor/on-screen-color", Color (0.4f, 0.4f, 0.9f, 0.6f)); this->set ("editor/camera/near-clipping", 0.01f); this->set ("editor/camera/far-clipping", 1000.0f); this->set ("editor/camera/rotation-factor", 1.0f); this->set ("editor/camera/movement-factor", 0.01f); this->set ("editor/camera/zoom-in-mouse-wheel-factor", 0.9f); this->set ("editor/camera/field-of-view", 45.0f); this->set ("editor/light/light1/direction", glm::vec3 (0.2f, -1.0f, -0.2f)); this->set ("editor/light/light1/color", Color (1.0f, 1.0f, 1.0f)); this->set ("editor/light/light1/irradiance", 0.7f); this->set ("editor/light/light2/direction", glm::vec3 (0.0f, 0.0f, -1.0f)); this->set ("editor/light/light2/color", Color (1.0f, 1.0f, 1.0f)); this->set ("editor/light/light2/irradiance", 0.8f); this->set ("editor/mesh/color/normal", Color (0.8f, 0.8f, 0.8f)); this->set ("editor/mesh/color/wireframe", Color (0.3f, 0.3f, 0.3f)); this->set ("editor/sketch/node/color", Color (0.5f, 0.5f, 0.9f)); this->set ("editor/sketch/bubble/color", Color (0.5f, 0.5f, 0.7f)); this->set ("editor/sketch/sphere/color", Color (0.7f, 0.7f, 0.9f)); this->set ("editor/tool/cursor-color", Color (1.0f, 0.9f, 0.9f)); this->set ("editor/tool/sculpt/detail-factor", 0.75f); this->set ("editor/tool/sculpt/step-width-factor", 0.3f); this->set ("editor/tool/sculpt/max-absolute-radius", 2.0f); this->set ("editor/tool/sculpt/mirror/render", false); this->set ("editor/tool/sculpt/mirror/width", 0.02f); this->set ("editor/tool/sculpt/mirror/color", Color (0.8f, 0.8f, 0.8f)); this->set ("editor/tool/sketch-spheres/step-width-factor", 0.3f); this->set ("editor/undo-depth", 15); this->set ("editor/tablet-pressure-intensity", 1.0f); this->set ("editor/use-geometry-shader", true); this->set ("window/initial-width", 1024); this->set ("window/initial-height", 768); } void Config::update () { const int version = this->get ("version"); switch (version) { case 1: break; case 2: break; case 3: updateValue (*this, "editor/undo-depth", 5, 15); break; case 4: this->remove ("editor/camera/gaze-point"); this->remove ("editor/camera/eye-point"); this->remove ("editor/camera/up"); break; case 5: mapValue (*this, "editor/light/light1/direction", [](const glm::vec3& v) { return -v; }); mapValue (*this, "editor/light/light2/direction", [](const glm::vec3& v) { return -v; }); break; case 6: forceUpdateValue (*this, "editor/tool/sculpt/step-width-factor", 0.3f); forceUpdateValue (*this, "editor/tool/sketch-spheres/step-width-factor", 0.3f); break; case 7: forceUpdateValue (*this, "editor/camera/zoom-in-factor", 0.95f); break; case 8: this->remove ("editor/tool/sculpt/cursor-color"); this->remove ("editor/tool/sketch-spheres/cursor-color"); break; case 9: this->remove ("editor/camera/zoom-in-factor"); break; case latestVersion: return; default: this->restoreDefaults (); return; } this->set ("version", version + 1); this->update (); } ================================================ FILE: lib/src/config.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_CONFIG #define DILAY_CONFIG #include "kvstore.hpp" class Config { public: Config (); template const T& get (const std::string& path) const { return this->store.get (path); } template void set (const std::string& path, const T& value) { this->store.set (path, value); } void fromFile (const std::string& fileName) { this->store.fromFile (fileName); this->update (); } void toFile (const std::string& fileName) const { this->store.toFile (fileName); } void remove (const std::string& path) { this->store.remove (path); } void restoreDefaults (); private: void update (); KVStore store; }; class ConfigProxy { public: ConfigProxy (const Config& c, const std::string& p) : _config (c) , prefix (p) { assert (p.back () == '/'); } ConfigProxy (const ConfigProxy& o, const std::string& path) : ConfigProxy (o._config, o.prefix + path) { } const Config& config () const { return this->_config; } std::string key (const std::string& path) const { return this->prefix + path; } template const T& get (const std::string& path) const { return this->_config.get (this->key (path)); } private: const Config& _config; const std::string prefix; }; #endif ================================================ FILE: lib/src/configurable.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "configurable.hpp" void Configurable::fromConfig (const Config& c) { this->runFromConfig (c); } void ProxyConfigurable::fromConfig (const ConfigProxy& c) { this->runFromConfig (c); } ================================================ FILE: lib/src/configurable.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_CONFIGURABLE #define DILAY_CONFIGURABLE class Config; class ConfigProxy; class Configurable { public: void fromConfig (const Config&); private: virtual void runFromConfig (const Config&) = 0; }; class ProxyConfigurable { public: void fromConfig (const ConfigProxy&); private: virtual void runFromConfig (const ConfigProxy&) = 0; }; #endif ================================================ FILE: lib/src/dimension.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "dimension.hpp" #include "util.hpp" unsigned int DimensionUtil::index (Dimension d) { switch (d) { case Dimension::X: return 0; case Dimension::Y: return 1; case Dimension::Z: return 2; } DILAY_IMPOSSIBLE } glm::vec3 DimensionUtil::vector (Dimension d) { switch (d) { case Dimension::X: return glm::vec3 (1.0f, 0.0f, 0.0f); case Dimension::Y: return glm::vec3 (0.0f, 1.0f, 0.0f); case Dimension::Z: return glm::vec3 (0.0f, 0.0f, 1.0f); } DILAY_IMPOSSIBLE } ================================================ FILE: lib/src/dimension.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_DIMENSION #define DILAY_DIMENSION #include enum class Dimension { X, Y, Z }; namespace DimensionUtil { unsigned int index (Dimension); glm::vec3 vector (Dimension); } #endif ================================================ FILE: lib/src/distance.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "distance.hpp" #include "primitive/cone-sphere.hpp" #include "primitive/cone.hpp" #include "primitive/cylinder.hpp" #include "primitive/sphere.hpp" #include "primitive/triangle.hpp" #include "util.hpp" namespace { float distanceToCylinder (const glm::vec3& center1, float radius, float length, const glm::vec3& direction, const glm::vec3& point) { const glm::vec3 toP = point - center1; const float x = glm::dot (toP, direction); const float ySqr = glm::dot (toP, toP) - (x * x); const float y = Util::almostEqual (0.0f, ySqr) ? 0.0f : glm::sqrt (ySqr); const float yr = y - radius; const float xl = x - length; const bool insideR = yr <= 0.0f; if (x <= 0.0f) { return insideR ? glm::abs (x) : glm::sqrt ((x * x) + (yr * yr)); } else if (x >= length) { return insideR ? xl : glm::sqrt ((xl * xl) + (yr * yr)); } else { return insideR ? glm::max (-x, glm::max (yr, xl)) : yr; } } } float Distance::distance (const PrimSphere& sphere, const glm::vec3& point) { return glm::distance (sphere.center (), point) - sphere.radius (); } float Distance::distance (const PrimCylinder& cylinder, const glm::vec3& point) { return distanceToCylinder (cylinder.center1 (), cylinder.radius (), cylinder.length (), cylinder.direction (), point); } float Distance::distance (const PrimCone& cone, const glm::vec3& point) { if (cone.isCylinder ()) { return distanceToCylinder (cone.center1 (), cone.radius1 (), cone.length (), cone.direction (), point); } else { const glm::vec3 toP = point - cone.center1 (); const float x = glm::dot (toP, cone.direction ()); const float ySqr = glm::dot (toP, toP) - (x * x); const float y = Util::almostEqual (0.0f, ySqr) ? 0.0f : glm::sqrt (ySqr); const float r1 = cone.radius1 (); const float r2 = cone.radius2 (); const float l = cone.length (); if (x <= 0.0f) { return y <= r1 ? -x : glm::sqrt ((x * x) + ((y - r1) * (y - r1))); } else if (x >= l && y <= r2) { return x - l; } else { const float xn = (x * cone.cosAlpha ()) - ((y - r1) * cone.sinAlpha ()); const float yn = (x * cone.sinAlpha ()) + ((y - r1) * cone.cosAlpha ()); const float delta = r1 - r2; const float s = glm::sqrt ((l * l) + (delta * delta)); if (xn <= 0.0f) { return glm::sqrt ((x * x) + ((y - r1) * (y - r1))); } else if (xn >= s) { if (x <= l) { assert (yn <= 0.0f); return x - l; } else { return glm::sqrt ((yn * yn) + ((xn - s) * (xn - s))); } } else if (yn >= 0.0f) { return yn; } else { return glm::max (-x, glm::max (yn, x - l)); } } } } float Distance::distance (const PrimConeSphere& coneSphere, const glm::vec3& point) { const glm::vec3 toP = point - coneSphere.sphere1 ().center (); const float x = glm::dot (toP, coneSphere.direction ()); const float ySqr = glm::dot (toP, toP) - (x * x); const float y = Util::almostEqual (0.0f, ySqr) ? 0.0f : glm::sqrt (ySqr); const float r1 = coneSphere.sphere1 ().radius (); const float r2 = coneSphere.sphere2 ().radius (); const float l = coneSphere.length (); if (coneSphere.sameRadii ()) { if (x <= 0.0f) { return glm::sqrt ((x * x) + (y * y)) - r1; } else if (x >= l) { return glm::sqrt (((x - l) * (x - l)) + (y * y)) - r1; } else { return y - r1; } } else if (coneSphere.hasCone ()) { const float s = coneSphere.coneSideLength (); const float h1 = r1 * coneSphere.delta () / l; const float h2 = r2 * coneSphere.delta () / l; const float r1c = r1 * s / l; const float r2c = r2 * s / l; if (x <= 0.0f) { return glm::sqrt ((x * x) + (y * y)) - r1; } else if (x >= l + h2 && y <= r2c) { return glm::sqrt (((x - l) * (x - l)) + (y * y)) - r2; } else { const float xn = ((x - h1) * coneSphere.cosAlpha ()) - ((y - r1c) * coneSphere.sinAlpha ()); const float yn = ((x - h1) * coneSphere.sinAlpha ()) + ((y - r1c) * coneSphere.cosAlpha ()); if (xn <= 0.0f) { return glm::sqrt ((x * x) + (y * y)) - r1; } else if (xn >= s) { return glm::sqrt (((x - l) * (x - l)) + (y * y)) - r2; } else { return yn; } } } else { return glm::sqrt ((x * x) + (y * y)) - r1; } } // cf. https://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf float Distance::distance (const PrimTriangle& tri, const glm::vec3& point) { const glm::vec3& P = point; const glm::vec3& B = tri.vertex1 (); const glm::vec3 E0 = tri.vertex2 () - tri.vertex1 (); const glm::vec3 E1 = tri.vertex3 () - tri.vertex1 (); const glm::vec3 D = B - P; const float a = glm::dot (E0, E0); const float b = glm::dot (E0, E1); const float c = glm::dot (E1, E1); const float d = glm::dot (E0, D); const float e = glm::dot (E1, D); float s = (b * e) - (c * d); float t = (b * d) - (a * e); const float det = (a * c) - (b * b); if (s + t <= det) { if (s < 0.0f) { if (t < 0.0f) { // region 4 if (d < 0.0f) { t = 0.0f; s = -d > a ? 1.0f : -d / a; } else { s = 0.0f; if (e >= 0.0f) { t = 0.0f; } else if (-e >= c) { t = 1.0f; } else { t = -e / c; } } } else { // region 3 s = 0.0f; if (e >= 0.0f) { t = 0.0f; } else if (-e >= c) { t = 1.0f; } else { t = -e / c; } } } else if (t < 0.0f) { // region 5 t = 0.0f; if (d >= 0.0f) { s = 0.0f; } else if (-d >= a) { s = 1.0f; } else { s = -d / a; } } else { // region 0 s /= det; t /= det; } } else { if (s < 0.0f) { // region 2 const float tmp0 = b + d; const float tmp1 = c + e; if (tmp1 > tmp0) { const float numer = tmp1 - tmp0; const float denom = a - (2.0f * b) + c; s = numer >= denom ? 1.0f : numer / denom; t = 1.0f - s; } else { s = 0.0f; if (tmp1 <= 0.0f) { t = 1.0f; } else if (e >= 0.0f) { t = 0.0f; } else { t = -e / c; } } } else if (t < 0.0f) { // region 6 const float tmp0 = b + e; const float tmp1 = a + d; if (tmp1 > tmp0) { const float numer = tmp1 - tmp0; const float denom = a - (2.0f * b) + c; t = numer >= denom ? 1.0f : numer / denom; s = 1.0f - t; } else { t = 0.0f; if (tmp1 <= 0.0f) { s = 1.0f; } else if (d >= 0.0f) { s = 0.0f; } else { s = -d / a; } } } else { // region 1 const float numer = (c + e) - (b + d); if (numer <= 0.0f) { s = 0.0f; } else { const float denom = a - (2.0f * b) + c; s = numer >= denom ? 1.0f : numer / denom; } t = 1.0f - s; } } return glm::distance (point, B + (s * E0) + (t * E1)); } ================================================ FILE: lib/src/distance.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_DISTANCE #define DILAY_DISTANCE #include class PrimCone; class PrimConeSphere; class PrimCylinder; class PrimSphere; class PrimTriangle; namespace Distance { float distance (const PrimSphere&, const glm::vec3&); float distance (const PrimCylinder&, const glm::vec3&); float distance (const PrimCone&, const glm::vec3&); float distance (const PrimConeSphere&, const glm::vec3&); float distance (const PrimTriangle&, const glm::vec3&); } #endif ================================================ FILE: lib/src/dynamic/faces.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "dynamic/faces.hpp" void DynamicFaces::insert (unsigned int i) { this->_uncommitted.insert (i); } void DynamicFaces::insert (const DynamicFaces::Container& v) { this->_uncommitted.insert (v.begin (), v.end ()); } void DynamicFaces::reset () { this->resetCommitted (); this->_uncommitted.clear (); } void DynamicFaces::resetCommitted () { this->_indices.clear (); } void DynamicFaces::commit () { if (this->_indices.empty ()) { this->_indices.swap (this->_uncommitted); } else { this->_indices.insert (this->_uncommitted.begin (), this->_uncommitted.end ()); this->_uncommitted.clear (); } } bool DynamicFaces::contains (unsigned int i) const { return this->_indices.find (i) != this->_indices.end (); } bool DynamicFaces::isEmpty () const { return this->_indices.empty () && this->_uncommitted.empty (); } bool DynamicFaces::hasUncomitted () const { return this->_uncommitted.empty () == false; } void DynamicFaces::filter (const std::function& f) { for (auto it = this->_indices.begin (); it != this->_indices.end ();) { if (f (*it) == false) { it = this->_indices.erase (it); } else { ++it; } } for (auto it = this->_uncommitted.begin (); it != this->_uncommitted.end ();) { if (f (*it) == false) { it = this->_uncommitted.erase (it); } else { ++it; } } } ================================================ FILE: lib/src/dynamic/faces.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_DYNAMIC_FACES #define DILAY_DYNAMIC_FACES #include #include class DynamicFaces { public: typedef std::unordered_set Container; const Container& indices () const { return this->_indices; } const Container& uncommitted () const { return this->_uncommitted; } unsigned int numElements () const { return this->_indices.size (); } Container::iterator begin () { return this->_indices.begin (); } Container::iterator end () { return this->_indices.end (); } Container::const_iterator begin () const { return this->_indices.begin (); } Container::const_iterator end () const { return this->_indices.end (); } void insert (unsigned int); void insert (const Container&); void reset (); void resetCommitted (); void commit (); bool contains (unsigned int) const; bool isEmpty () const; bool hasUncomitted () const; void filter (const std::function&); private: Container _indices; Container _uncommitted; }; #endif ================================================ FILE: lib/src/dynamic/mesh-intersection.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "dynamic/mesh-intersection.hpp" #include "dynamic/mesh.hpp" #include "util.hpp" DynamicMeshIntersection::DynamicMeshIntersection () : _faceIndex (Util::invalidIndex ()) , _mesh (nullptr) { } bool DynamicMeshIntersection::update (float d, const glm::vec3& p, const glm::vec3& n, unsigned int i, DynamicMesh& mesh) { if (this->Intersection::update (d, p, n)) { this->_mesh = &mesh; this->_faceIndex = i; return true; } else { return false; } } unsigned int DynamicMeshIntersection::faceIndex () const { assert (this->isIntersection ()); return this->_faceIndex; } DynamicMesh& DynamicMeshIntersection::mesh () const { assert (this->isIntersection ()); assert (this->_mesh); return *this->_mesh; } ================================================ FILE: lib/src/dynamic/mesh-intersection.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_DYNAMIC_MESH_INTERSECTION #define DILAY_DYNAMIC_MESH_INTERSECTION #include "intersection.hpp" class DynamicMesh; class DynamicMeshIntersection : public Intersection { public: DynamicMeshIntersection (); DynamicMesh& mesh () const; unsigned int faceIndex () const; bool update (float, const glm::vec3&, const glm::vec3&, unsigned int, DynamicMesh&); private: unsigned int _faceIndex; DynamicMesh* _mesh; }; #endif ================================================ FILE: lib/src/dynamic/mesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include "../mesh.hpp" #include "config.hpp" #include "distance.hpp" #include "dynamic/faces.hpp" #include "dynamic/mesh-intersection.hpp" #include "dynamic/mesh.hpp" #include "dynamic/octree.hpp" #include "intersection.hpp" #include "mesh-util.hpp" #include "primitive/aabox.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "primitive/triangle.hpp" #include "tool/sculpt/util/action.hpp" #include "util.hpp" namespace { struct VertexData { bool isFree; std::vector adjacentFaces; VertexData () { this->reset (); } void reset () { this->isFree = true; this->adjacentFaces.clear (); } void addAdjacentFace (unsigned int face) { this->adjacentFaces.push_back (face); } void deleteAdjacentFace (unsigned int face) { for (auto it = this->adjacentFaces.begin (); it != this->adjacentFaces.end (); ++it) { if (*it == face) { this->adjacentFaces.erase (it); return; } } DILAY_IMPOSSIBLE } }; struct FaceData { bool isFree; FaceData () { this->reset (); } void reset () { this->isFree = true; } }; } struct DynamicMesh::Impl { DynamicMesh* self; Mesh mesh; std::vector vertexData; std::vector vertexVisited; std::vector freeVertexIndices; std::vector faceData; std::vector faceVisited; std::vector freeFaceIndices; DynamicOctree octree; Impl (DynamicMesh* s) : self (s) { } Impl (DynamicMesh* s, const Mesh& m) : self (s) { this->fromMesh (m); } unsigned int numVertices () const { assert (this->mesh.numVertices () >= this->freeVertexIndices.size ()); assert (this->mesh.numVertices () == this->vertexData.size ()); return this->mesh.numVertices () - this->freeVertexIndices.size (); } unsigned int numFaces () const { assert (this->faceData.size () >= this->freeFaceIndices.size ()); return this->faceData.size () - this->freeFaceIndices.size (); } bool isEmpty () const { return this->numFaces () == 0; } bool isFreeVertex (unsigned int i) const { assert (i < this->vertexData.size ()); return this->vertexData[i].isFree; } bool isFreeFace (unsigned int i) const { assert (i < this->faceData.size ()); return this->faceData[i].isFree; } bool isPruned () const { return this->freeFaceIndices.empty () && this->freeVertexIndices.empty (); } unsigned int valence (unsigned int i) const { assert (this->isFreeVertex (i) == false); return this->vertexData[i].adjacentFaces.size (); } void vertexIndices (unsigned int i, unsigned int& i1, unsigned int& i2, unsigned int& i3) const { assert (this->isFreeFace (i) == false); i1 = this->mesh.index ((3 * i) + 0); i2 = this->mesh.index ((3 * i) + 1); i3 = this->mesh.index ((3 * i) + 2); } PrimTriangle face (unsigned int i) const { assert (this->isFreeFace (i) == false); return PrimTriangle (this->mesh.vertex (this->mesh.index ((3 * i) + 0)), this->mesh.vertex (this->mesh.index ((3 * i) + 1)), this->mesh.vertex (this->mesh.index ((3 * i) + 2))); } const glm::vec3& vertexNormal (unsigned int i) const { return this->mesh.normal (i); } glm::vec3 faceNormal (unsigned int i) const { assert (this->isFreeFace (i) == false); unsigned int i1, i2, i3; this->vertexIndices (i, i1, i2, i3); return glm::normalize (glm::cross (this->mesh.vertex (i2) - this->mesh.vertex (i1), this->mesh.vertex (i3) - this->mesh.vertex (i1))); } void findAdjacent (unsigned int e1, unsigned int e2, unsigned int& leftFace, unsigned int& leftVertex, unsigned int& rightFace, unsigned int& rightVertex) const { assert (this->isFreeVertex (e1) == false); assert (this->isFreeVertex (e2) == false); leftFace = Util::invalidIndex (); leftVertex = Util::invalidIndex (); rightFace = Util::invalidIndex (); rightVertex = Util::invalidIndex (); for (unsigned int a : this->vertexData[e1].adjacentFaces) { unsigned int i1, i2, i3; this->vertexIndices (a, i1, i2, i3); if (e1 == i1 && e2 == i2) { leftFace = a; leftVertex = i3; } else if (e1 == i2 && e2 == i1) { rightFace = a; rightVertex = i3; } else if (e1 == i2 && e2 == i3) { leftFace = a; leftVertex = i1; } else if (e1 == i3 && e2 == i2) { rightFace = a; rightVertex = i1; } else if (e1 == i3 && e2 == i1) { leftFace = a; leftVertex = i2; } else if (e1 == i1 && e2 == i3) { rightFace = a; rightVertex = i2; } } assert (leftFace != Util::invalidIndex ()); assert (leftVertex != Util::invalidIndex ()); assert (rightFace != Util::invalidIndex ()); assert (rightVertex != Util::invalidIndex ()); } const std::vector& adjacentFaces (unsigned int i) const { assert (this->isFreeVertex (i) == false); return this->vertexData[i].adjacentFaces; } void forEachVertex (const std::function& f) const { for (unsigned int i = 0; i < this->vertexData.size (); i++) { if (this->isFreeVertex (i) == false) { f (i); } } } void visitVertices (unsigned int i, const std::function& f) { assert (this->isFreeFace (i) == false); unsigned int i1, i2, i3; this->vertexIndices (i, i1, i2, i3); if (this->vertexVisited[i1] == 0) { this->vertexVisited[i1] = 1; f (i1); } if (this->vertexVisited[i2] == 0) { this->vertexVisited[i2] = 1; f (i2); } if (this->vertexVisited[i3] == 0) { this->vertexVisited[i3] = 1; f (i3); } this->faceVisited[i] = 1; } void unvisitVertices () { std::memset (this->vertexVisited.data (), 0, this->vertexVisited.size ()); } void unvisitFaces () { std::memset (this->faceVisited.data (), 0, this->faceVisited.size ()); } void forEachVertex (const DynamicFaces& faces, const std::function& f) { this->unvisitVertices (); for (unsigned int i : faces) { this->visitVertices (i, f); } } void forEachVertexExt (const DynamicFaces& faces, const std::function& f) { this->unvisitVertices (); this->unvisitFaces (); for (unsigned int i : faces) { this->visitVertices (i, [this, &f](unsigned int j) { f (j); for (unsigned int a : this->vertexData[j].adjacentFaces) { if (this->faceVisited[a] == 0) { this->visitVertices (a, f); } } }); } } void forEachVertexAdjacentToVertex (unsigned int i, const std::function& f) const { assert (this->isFreeVertex (i) == false); for (unsigned int a : this->vertexData[i].adjacentFaces) { unsigned int a1, a2, a3; this->vertexIndices (a, a1, a2, a3); if (i == a1) { f (a2); } else if (i == a2) { f (a3); } else if (i == a3) { f (a1); } else { DILAY_IMPOSSIBLE } } } void forEachVertexAdjacentToFace (unsigned int i, const std::function& f) const { assert (this->isFreeFace (i) == false); unsigned int i1, i2, i3; this->vertexIndices (i, i1, i2, i3); f (i1); f (i2); f (i3); } void forEachFace (const std::function& f) const { for (unsigned int i = 0; i < this->faceData.size (); i++) { if (this->isFreeFace (i) == false) { f (i); } } } void forEachFaceExt (const DynamicFaces& faces, const std::function& f) { this->unvisitVertices (); this->unvisitFaces (); for (unsigned int i : faces) { if (this->faceVisited[i] == 0) { f (i); this->faceVisited[i] = 1; } this->visitVertices (i, [this, &f](unsigned int j) { for (unsigned int a : this->vertexData[j].adjacentFaces) { if (this->faceVisited[a] == 0) { f (a); this->faceVisited[a] = 1; } } }); } } void average (const DynamicFaces& faces, glm::vec3& position, glm::vec3& normal) const { assert (faces.numElements () > 0); position = glm::vec3 (0.0f); normal = glm::vec3 (0.0f); for (unsigned int f : faces) { unsigned int i1, i2, i3; this->vertexIndices (f, i1, i2, i3); position += this->mesh.vertex (i1); position += this->mesh.vertex (i2); position += this->mesh.vertex (i3); normal += glm::cross (this->mesh.vertex (i2) - this->mesh.vertex (i1), this->mesh.vertex (i3) - this->mesh.vertex (i1)); } position /= float(faces.numElements () * 3); normal = glm::normalize (normal); } glm::vec3 averagePosition (const DynamicFaces& faces) const { assert (faces.numElements () > 0); glm::vec3 position = glm::vec3 (0.0f); for (unsigned int f : faces) { this->forEachVertexAdjacentToFace ( f, [this, &position](unsigned int v) { position += this->mesh.vertex (v); }); } return position / float(faces.numElements () * 3); } glm::vec3 averagePosition (unsigned int i) const { assert (this->isFreeVertex (i) == false); assert (this->vertexData[i].adjacentFaces.size () > 0); glm::vec3 position = glm::vec3 (0.0f); this->forEachVertexAdjacentToVertex ( i, [this, &position](unsigned int v) { position += this->mesh.vertex (v); }); return position / float(this->vertexData[i].adjacentFaces.size ()); } glm::vec3 averageNormal (const DynamicFaces& faces) const { assert (faces.numElements () > 0); glm::vec3 normal = glm::vec3 (0.0f); for (unsigned int f : faces) { unsigned int i1, i2, i3; this->vertexIndices (f, i1, i2, i3); normal += glm::cross (this->mesh.vertex (i2) - this->mesh.vertex (i1), this->mesh.vertex (i3) - this->mesh.vertex (i1)); } return glm::normalize (normal); } glm::vec3 averageNormal (unsigned int i) const { assert (this->isFreeVertex (i) == false); assert (this->vertexData[i].adjacentFaces.size () > 0); glm::vec3 normal = glm::vec3 (0.0f); for (unsigned int f : this->vertexData[i].adjacentFaces) { unsigned int i1, i2, i3; this->vertexIndices (f, i1, i2, i3); normal += glm::cross (this->mesh.vertex (i2) - this->mesh.vertex (i1), this->mesh.vertex (i3) - this->mesh.vertex (i1)); } return glm::normalize (normal); } float averageEdgeLengthSqr (const DynamicFaces& faces) const { assert (faces.numElements () > 0); float length = 0.0f; for (unsigned int i : faces) { length += this->averageEdgeLengthSqr (i); } return length / float(faces.numElements ()); } float averageEdgeLengthSqr (unsigned int i) const { assert (this->isFreeFace (i) == false); unsigned int i1, i2, i3; this->vertexIndices (i, i1, i2, i3); const glm::vec3& v1 = this->mesh.vertex (i1); const glm::vec3& v2 = this->mesh.vertex (i2); const glm::vec3& v3 = this->mesh.vertex (i3); return (glm::distance2 (v1, v2) + glm::distance2 (v1, v3) + glm::distance2 (v2, v3)) / 3.0f; } unsigned int addVertex (const glm::vec3& vertex, const glm::vec3& normal) { assert (this->vertexData.size () == this->mesh.numVertices ()); assert (this->vertexVisited.size () == this->mesh.numVertices ()); if (this->freeVertexIndices.empty ()) { this->vertexData.emplace_back (); this->vertexData.back ().isFree = false; this->vertexVisited.push_back (0); return this->mesh.addVertex (vertex, normal); } else { const unsigned int index = this->freeVertexIndices.back (); this->mesh.vertex (index, vertex); this->mesh.normal (index, normal); this->vertexData[index].reset (); this->vertexData[index].isFree = false; this->vertexVisited[index] = 0; this->freeVertexIndices.pop_back (); return index; } } unsigned int addFace (unsigned int i1, unsigned int i2, unsigned int i3) { assert (i1 < this->mesh.numVertices ()); assert (i2 < this->mesh.numVertices ()); assert (i3 < this->mesh.numVertices ()); assert (3 * this->faceData.size () == this->mesh.numIndices ()); assert (this->faceData.size () == this->faceVisited.size ()); unsigned int index = Util::invalidIndex (); if (this->freeFaceIndices.empty ()) { index = this->numFaces (); this->faceData.emplace_back (); this->faceVisited.push_back (0); this->mesh.addIndex (i1); this->mesh.addIndex (i2); this->mesh.addIndex (i3); } else { index = this->freeFaceIndices.back (); this->faceData[index].reset (); this->faceVisited[index] = 0; this->freeFaceIndices.pop_back (); this->mesh.index ((3 * index) + 0, i1); this->mesh.index ((3 * index) + 1, i2); this->mesh.index ((3 * index) + 2, i3); } this->faceData[index].isFree = false; this->vertexData[i1].addAdjacentFace (index); this->vertexData[i2].addAdjacentFace (index); this->vertexData[i3].addAdjacentFace (index); this->addFaceToOctree (index); return index; } void addFaceToOctree (unsigned int i) { const PrimTriangle tri = this->face (i); if (this->octree.hasRoot () == false) { this->octree.setupRoot (tri.center (), tri.maxDimExtent ()); } this->octree.addElement (i, tri.center (), tri.maxDimExtent ()); } void deleteVertex (unsigned int i) { assert (i < this->vertexData.size ()); assert (i < this->vertexVisited.size ()); std::vector adjacentFaces = this->vertexData[i].adjacentFaces; for (unsigned int f : adjacentFaces) { this->deleteFace (f); } this->vertexData[i].reset (); this->vertexVisited[i] = 0; this->freeVertexIndices.push_back (i); } void deleteFace (unsigned int i) { assert (i < this->faceData.size ()); assert (i < this->faceVisited.size ()); this->vertexData[this->mesh.index ((3 * i) + 0)].deleteAdjacentFace (i); this->vertexData[this->mesh.index ((3 * i) + 1)].deleteAdjacentFace (i); this->vertexData[this->mesh.index ((3 * i) + 2)].deleteAdjacentFace (i); this->faceData[i].reset (); this->faceVisited[i] = 0; this->freeFaceIndices.push_back (i); this->octree.deleteElement (i); } void vertexNormal (unsigned int i, const glm::vec3& n) { assert (this->isFreeVertex (i) == false); assert (this->mesh.numVertices () == this->vertexData.size ()); this->mesh.normal (i, n); } void setVertexNormal (unsigned int i) { const glm::vec3 avg = this->averageNormal (i); if (Util::isNaN (avg)) { this->mesh.normal (i, glm::vec3 (0.0f)); } else { this->mesh.normal (i, avg); } } void setAllNormals () { this->forEachVertex ([this](unsigned int i) { this->setVertexNormal (i); }); } void reset () { this->mesh.reset (); this->vertexData.clear (); this->vertexVisited.clear (); this->freeVertexIndices.clear (); this->faceData.clear (); this->faceVisited.clear (); this->freeFaceIndices.clear (); this->octree.reset (); } void fromMesh (const Mesh& mesh) { this->reset (); this->mesh.reserveVertices (mesh.numVertices ()); for (unsigned int i = 0; i < mesh.numVertices (); i++) { this->addVertex (mesh.vertex (i), mesh.normal (i)); } assert (mesh.numIndices () % 3 == 0); this->mesh.reserveIndices (mesh.numIndices ()); for (unsigned int i = 0; i < mesh.numIndices (); i += 3) { this->addFace (mesh.index (i), mesh.index (i + 1), mesh.index (i + 2)); } this->setAllNormals (); this->mesh.bufferData (); } void realignFace (unsigned int i) { assert (this->isFreeFace (i) == false); const PrimTriangle tri = this->face (i); this->octree.realignElement (i, tri.center (), tri.maxDimExtent ()); } void realignFaces (const DynamicFaces& faces) { for (unsigned int i : faces) { this->realignFace (i); } } void realignAllFaces () { this->forEachFace ([this](unsigned int i) { this->realignFace (i); }); } void sanitize () { this->octree.deleteEmptyChildren (); this->octree.shrinkRoot (); } void prune (std::vector* pVertexIndexMap, std::vector* pFaceIndexMap) { if (this->isPruned () == false) { std::vector defaultVertexIndexMap; std::vector defaultFaceIndexMap; if (pVertexIndexMap == nullptr) { pVertexIndexMap = &defaultVertexIndexMap; } if (pFaceIndexMap == nullptr) { pFaceIndexMap = &defaultFaceIndexMap; } Util::prune (this->vertexData, [](const VertexData& d) { return d.isFree; }, pVertexIndexMap); Util::prune (this->faceData, [](const FaceData& d) { return d.isFree; }, pFaceIndexMap); const unsigned int newNumVertices = this->vertexData.size (); const unsigned int newNumFaces = this->faceData.size (); for (VertexData& d : this->vertexData) { for (unsigned int& f : d.adjacentFaces) { assert (pFaceIndexMap->at (f) != Util::invalidIndex ()); f = pFaceIndexMap->at (f); } } for (unsigned int i = 0; i < pVertexIndexMap->size (); i++) { const unsigned int newV = pVertexIndexMap->at (i); if (newV != Util::invalidIndex ()) { this->mesh.vertex (newV, this->mesh.vertex (i)); this->mesh.normal (newV, this->mesh.normal (i)); } else { // Expensive (!) in debug builds assert (std::find (this->freeVertexIndices.begin (), this->freeVertexIndices.end (), i) != this->freeVertexIndices.end ()); } } this->freeVertexIndices.clear (); this->mesh.shrinkVertices (newNumVertices); this->vertexVisited.resize (newNumVertices); assert (this->numVertices () == newNumVertices); for (unsigned int i = 0; i < pFaceIndexMap->size (); i++) { const unsigned int newF = pFaceIndexMap->at (i); if (newF != Util::invalidIndex ()) { const unsigned int oldI1 = this->mesh.index ((3 * i) + 0); const unsigned int oldI2 = this->mesh.index ((3 * i) + 1); const unsigned int oldI3 = this->mesh.index ((3 * i) + 2); assert (pVertexIndexMap->at (oldI1) != Util::invalidIndex ()); assert (pVertexIndexMap->at (oldI2) != Util::invalidIndex ()); assert (pVertexIndexMap->at (oldI3) != Util::invalidIndex ()); this->mesh.index ((3 * newF) + 0, pVertexIndexMap->at (oldI1)); this->mesh.index ((3 * newF) + 1, pVertexIndexMap->at (oldI2)); this->mesh.index ((3 * newF) + 2, pVertexIndexMap->at (oldI3)); } else { // Expensive (!) in debug builds assert (std::find (this->freeFaceIndices.begin (), this->freeFaceIndices.end (), i) != this->freeFaceIndices.end ()); } } this->freeFaceIndices.clear (); this->mesh.shrinkIndices (3 * newNumFaces); this->faceVisited.resize (newNumFaces); assert (this->numFaces () == newNumFaces); this->octree.updateIndices (*pFaceIndexMap); } } bool pruneAndCheckConsistency (std::vector* pVertexIndexMap, std::vector* pFaceIndexMap) { this->prune (pVertexIndexMap, pFaceIndexMap); this->bufferData (); if (MeshUtil::checkConsistency (this->mesh)) { for (unsigned int i = 0; i < this->vertexData.size (); i++) { if (this->vertexData[i].isFree == false) { if (this->vertexData[i].adjacentFaces.empty ()) { DILAY_WARN ("vertex %u is not free but has no adjacent faces", i); return false; } } } return true; } else { return false; } } bool mirrorPositive (const PrimPlane& plane) { assert (this->pruneAndCheckConsistency (nullptr, nullptr)); const auto inBorder = [this, &plane](unsigned int f) { unsigned int i1, i2, i3; this->vertexIndices (f, i1, i2, i3); const float d1 = glm::abs (plane.distance (this->mesh.vertex (i1))); const float d2 = glm::abs (plane.distance (this->mesh.vertex (i2))); const float d3 = glm::abs (plane.distance (this->mesh.vertex (i3))); return d1 <= Util::epsilon () && d2 <= Util::epsilon () && d3 <= Util::epsilon (); }; DynamicFaces faces; do { faces.reset (); if (this->intersects (plane, faces) == false) { break; } faces.filter (inBorder); if (faces.isEmpty ()) { break; } } while (ToolSculptAction::deleteFaces (*this->self, faces)); assert (this->pruneAndCheckConsistency (nullptr, nullptr)); this->prune (nullptr, nullptr); Mesh mirrored = MeshUtil::mirrorPositive (this->mesh, plane); if (mirrored.numVertices () == 0) { this->setAllNormals (); return false; } else { this->fromMesh (mirrored); assert (this->pruneAndCheckConsistency (nullptr, nullptr)); return true; } } void mirror (const PrimPlane& plane) { MeshUtil::mirror (this->mesh, plane); this->realignAllFaces (); this->bufferData (); } void moveToCenter () { MeshUtil::moveToCenter (this->mesh); this->realignAllFaces (); this->bufferData (); } void normalizeScaling () { MeshUtil::normalizeScaling (this->mesh); this->realignAllFaces (); this->bufferData (); } void bufferData () { const auto findNonFreeFaceIndex = [this]() -> unsigned int { assert (this->numFaces () > 0); for (unsigned int i = 0; i < this->faceData.size (); i++) { if (this->isFreeFace (i) == false) { return i; } } DILAY_IMPOSSIBLE }; if (this->numFaces () > 0 && this->freeFaceIndices.empty () == false) { const unsigned int nonFree = findNonFreeFaceIndex (); for (unsigned int i : this->freeFaceIndices) { this->mesh.index ((3 * i) + 0, this->mesh.index ((3 * nonFree) + 0)); this->mesh.index ((3 * i) + 1, this->mesh.index ((3 * nonFree) + 1)); this->mesh.index ((3 * i) + 2, this->mesh.index ((3 * nonFree) + 2)); } } this->mesh.bufferData (); } void render (Camera& camera) const { this->mesh.render (camera); #ifdef DILAY_RENDER_OCTREE this->octree.render (camera); #endif } bool intersects (const PrimRay& ray, Intersection& intersection, bool bothSides) const { this->octree.intersects (ray, [this, &ray, &intersection, bothSides](unsigned int i) -> float { const PrimTriangle tri = this->face (i); float t; if (IntersectionUtil::intersects (ray, tri, bothSides, &t)) { intersection.update (t, ray.pointAt (t), tri.normal ()); return t; } else { return Util::maxFloat (); } }); return intersection.isIntersection (); } bool intersects (const PrimRay& ray, DynamicMeshIntersection& intersection) { this->octree.intersects (ray, [this, &ray, &intersection](unsigned int i) -> float { const PrimTriangle tri = this->face (i); float t; if (IntersectionUtil::intersects (ray, tri, false, &t)) { intersection.update (t, ray.pointAt (t), tri.normal (), i, *this->self); return intersection.distance (); } else { return Util::maxFloat (); } }); return intersection.isIntersection (); } template bool intersectsT (const T& t, DynamicFaces& faces, const Ts&... args) const { this->octree.intersects (t, [this, &t, &faces, &args...](unsigned int i) { if (IntersectionUtil::intersects (t, this->face (i), args...)) { faces.insert (i); } }); faces.commit (); return faces.isEmpty () == false; } template bool containsOrIntersectsT (const T& t, DynamicFaces& faces, const Ts&... args) const { this->octree.intersects (t, [this, &t, &faces, &args...](bool contains, unsigned int i) { if (contains || IntersectionUtil::intersects (t, this->face (i), args...)) { faces.insert (i); faces.commit (); } }); return faces.isEmpty () == false; } bool intersects (const PrimPlane& plane, DynamicFaces& faces) const { return this->intersectsT (plane, faces); } bool intersects (const PrimSphere& sphere, DynamicFaces& faces) const { return this->containsOrIntersectsT (sphere, faces); } bool intersects (const PrimAABox& box, DynamicFaces& faces) const { return this->containsOrIntersectsT (box, faces); } float unsignedDistance (const glm::vec3& pos) const { return this->octree.distance ( pos, [this, &pos](unsigned int i) { return Distance::distance (this->face (i), pos); }); } void normalize () { this->mesh.normalize (); this->octree.reset (); this->forEachFace ([this](unsigned int i) { this->addFaceToOctree (i); }); } void printStatistics () const { this->octree.printStatistics (); } void runFromConfig (const Config& config) { this->mesh.color (config.get ("editor/mesh/color/normal")); this->mesh.wireframeColor (config.get ("editor/mesh/color/wireframe")); } }; DELEGATE_BIG4_COPY_SELF (DynamicMesh) DELEGATE1_CONSTRUCTOR_SELF (DynamicMesh, const Mesh&) DELEGATE_CONST (unsigned int, DynamicMesh, numVertices) DELEGATE_CONST (unsigned int, DynamicMesh, numFaces) DELEGATE_CONST (bool, DynamicMesh, isEmpty) DELEGATE1_CONST (bool, DynamicMesh, isFreeVertex, unsigned int) DELEGATE1_CONST (bool, DynamicMesh, isFreeFace, unsigned int) DELEGATE1_MEMBER_CONST (const glm::vec3&, DynamicMesh, vertex, mesh, unsigned int) DELEGATE1_CONST (unsigned int, DynamicMesh, valence, unsigned int) DELEGATE4_CONST (void, DynamicMesh, vertexIndices, unsigned int, unsigned int&, unsigned int&, unsigned int&) DELEGATE1_CONST (PrimTriangle, DynamicMesh, face, unsigned int) DELEGATE1_CONST (const glm::vec3&, DynamicMesh, vertexNormal, unsigned int) DELEGATE1_CONST (glm::vec3, DynamicMesh, faceNormal, unsigned int) DELEGATE1_CONST (const std::vector&, DynamicMesh, adjacentFaces, unsigned int) GETTER_CONST (const Mesh&, DynamicMesh, mesh) DELEGATE1_CONST (void, DynamicMesh, forEachVertex, const std::function&) DELEGATE2 (void, DynamicMesh, forEachVertex, const DynamicFaces&, const std::function&) DELEGATE2 (void, DynamicMesh, forEachVertexExt, const DynamicFaces&, const std::function&) DELEGATE2_CONST (void, DynamicMesh, forEachVertexAdjacentToVertex, unsigned int, const std::function&) DELEGATE2_CONST (void, DynamicMesh, forEachVertexAdjacentToFace, unsigned int, const std::function&) DELEGATE1_CONST (void, DynamicMesh, forEachFace, const std::function&) DELEGATE2 (void, DynamicMesh, forEachFaceExt, const DynamicFaces&, const std::function&) DELEGATE3_CONST (void, DynamicMesh, average, const DynamicFaces&, glm::vec3&, glm::vec3&) DELEGATE1_CONST (glm::vec3, DynamicMesh, averagePosition, const DynamicFaces&) DELEGATE1_CONST (glm::vec3, DynamicMesh, averagePosition, unsigned int) DELEGATE1_CONST (glm::vec3, DynamicMesh, averageNormal, const DynamicFaces&) DELEGATE1_CONST (glm::vec3, DynamicMesh, averageNormal, unsigned int) DELEGATE1_CONST (float, DynamicMesh, averageEdgeLengthSqr, const DynamicFaces&) DELEGATE1_CONST (float, DynamicMesh, averageEdgeLengthSqr, unsigned int) DELEGATE2 (unsigned int, DynamicMesh, addVertex, const glm::vec3&, const glm::vec3&) DELEGATE3 (unsigned int, DynamicMesh, addFace, unsigned int, unsigned int, unsigned int) DELEGATE1 (void, DynamicMesh, deleteVertex, unsigned int) DELEGATE1 (void, DynamicMesh, deleteFace, unsigned int) DELEGATE2_MEMBER (void, DynamicMesh, vertex, mesh, unsigned int, const glm::vec3&) DELEGATE2 (void, DynamicMesh, vertexNormal, unsigned int, const glm::vec3&) DELEGATE1 (void, DynamicMesh, setVertexNormal, unsigned int) DELEGATE (void, DynamicMesh, setAllNormals) DELEGATE (void, DynamicMesh, reset) DELEGATE1 (void, DynamicMesh, fromMesh, const Mesh&) DELEGATE1 (void, DynamicMesh, realignFace, unsigned int) DELEGATE1 (void, DynamicMesh, realignFaces, const DynamicFaces&) DELEGATE (void, DynamicMesh, realignAllFaces) DELEGATE (void, DynamicMesh, sanitize) DELEGATE2 (void, DynamicMesh, prune, std::vector*, std::vector*) DELEGATE2 (bool, DynamicMesh, pruneAndCheckConsistency, std::vector*, std::vector*) DELEGATE1 (bool, DynamicMesh, mirrorPositive, const PrimPlane&) DELEGATE1 (void, DynamicMesh, mirror, const PrimPlane&) DELEGATE (void, DynamicMesh, moveToCenter) DELEGATE (void, DynamicMesh, normalizeScaling) DELEGATE (void, DynamicMesh, bufferData) DELEGATE1_CONST (void, DynamicMesh, render, Camera&) DELEGATE_MEMBER_CONST (const RenderMode&, DynamicMesh, renderMode, mesh) DELEGATE_MEMBER (RenderMode&, DynamicMesh, renderMode, mesh) DELEGATE3_CONST (bool, DynamicMesh, intersects, const PrimRay&, Intersection&, bool) DELEGATE2 (bool, DynamicMesh, intersects, const PrimRay&, DynamicMeshIntersection&) DELEGATE2_CONST (bool, DynamicMesh, intersects, const PrimPlane&, DynamicFaces&) DELEGATE2_CONST (bool, DynamicMesh, intersects, const PrimSphere&, DynamicFaces&) DELEGATE2_CONST (bool, DynamicMesh, intersects, const PrimAABox&, DynamicFaces&) DELEGATE1_CONST (float, DynamicMesh, unsignedDistance, const glm::vec3&) DELEGATE (void, DynamicMesh, normalize) DELEGATE1_MEMBER (void, DynamicMesh, scale, mesh, const glm::vec3&) DELEGATE1_MEMBER (void, DynamicMesh, scaling, mesh, const glm::vec3&) DELEGATE_MEMBER_CONST (glm::vec3, DynamicMesh, scaling, mesh) DELEGATE1_MEMBER (void, DynamicMesh, translate, mesh, const glm::vec3&) DELEGATE1_MEMBER (void, DynamicMesh, position, mesh, const glm::vec3&) DELEGATE_MEMBER_CONST (glm::vec3, DynamicMesh, position, mesh) DELEGATE1_MEMBER (void, DynamicMesh, rotationMatrix, mesh, const glm::mat4x4&) DELEGATE_MEMBER_CONST (const glm::mat4x4&, DynamicMesh, rotationMatrix, mesh) DELEGATE2_MEMBER (void, DynamicMesh, rotation, mesh, const glm::vec3&, float) DELEGATE1_MEMBER (void, DynamicMesh, rotationX, mesh, float) DELEGATE1_MEMBER (void, DynamicMesh, rotationY, mesh, float) DELEGATE1_MEMBER (void, DynamicMesh, rotationZ, mesh, float) DELEGATE1_MEMBER (void, DynamicMesh, rotate, mesh, const glm::mat4x4&) DELEGATE2_MEMBER (void, DynamicMesh, rotate, mesh, const glm::vec3&, float) DELEGATE1_MEMBER (void, DynamicMesh, rotateX, mesh, float) DELEGATE1_MEMBER (void, DynamicMesh, rotateY, mesh, float) DELEGATE1_MEMBER (void, DynamicMesh, rotateZ, mesh, float) DELEGATE_MEMBER_CONST (const Color&, DynamicMesh, color, mesh) DELEGATE1_MEMBER (void, DynamicMesh, color, mesh, const Color&) DELEGATE_MEMBER_CONST (const Color&, DynamicMesh, wireframeColor, mesh) DELEGATE1_MEMBER (void, DynamicMesh, wireframeColor, mesh, const Color&) DELEGATE_CONST (void, DynamicMesh, printStatistics) DELEGATE1 (void, DynamicMesh, runFromConfig, const Config&) void DynamicMesh::findAdjacent (unsigned int e1, unsigned int e2, unsigned int& leftFace, unsigned int& leftVertex, unsigned int& rightFace, unsigned int& rightVertex) const { return this->impl->findAdjacent (e1, e2, leftFace, leftVertex, rightFace, rightVertex); } ================================================ FILE: lib/src/dynamic/mesh.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_DYNAMIC_MESH #define DILAY_DYNAMIC_MESH #include #include #include #include "configurable.hpp" #include "macro.hpp" class Camera; class Color; class DynamicFaces; class DynamicMeshIntersection; class Intersection; class Mesh; class PrimAABox; class PrimPlane; class PrimRay; class PrimSphere; class PrimTriangle; class RenderMode; class DynamicMesh : public Configurable { public: DECLARE_BIG4_EXPLICIT_COPY (DynamicMesh); DynamicMesh (const Mesh&); unsigned int numVertices () const; unsigned int numFaces () const; bool isEmpty () const; bool isFreeVertex (unsigned int) const; bool isFreeFace (unsigned int) const; const glm::vec3& vertex (unsigned int) const; unsigned int valence (unsigned int) const; void vertexIndices (unsigned int, unsigned int&, unsigned int&, unsigned int&) const; PrimTriangle face (unsigned int) const; const glm::vec3& vertexNormal (unsigned int) const; glm::vec3 faceNormal (unsigned int) const; void findAdjacent (unsigned int, unsigned int, unsigned int&, unsigned int&, unsigned int&, unsigned int&) const; const std::vector& adjacentFaces (unsigned int) const; void forEachVertex (const std::function&) const; void forEachVertex (const DynamicFaces&, const std::function&); void forEachVertexExt (const DynamicFaces&, const std::function&); void forEachVertexAdjacentToVertex (unsigned int, const std::function&) const; void forEachVertexAdjacentToFace (unsigned int, const std::function&) const; void forEachFace (const std::function&) const; void forEachFaceExt (const DynamicFaces&, const std::function&); void average (const DynamicFaces&, glm::vec3&, glm::vec3&) const; glm::vec3 averagePosition (const DynamicFaces&) const; glm::vec3 averagePosition (unsigned int) const; glm::vec3 averageNormal (const DynamicFaces&) const; glm::vec3 averageNormal (unsigned int) const; float averageEdgeLengthSqr (const DynamicFaces&) const; float averageEdgeLengthSqr (unsigned int) const; const Mesh& mesh () const; unsigned int addVertex (const glm::vec3&, const glm::vec3&); unsigned int addFace (unsigned int, unsigned int, unsigned int); void deleteVertex (unsigned int); void deleteFace (unsigned int); void vertex (unsigned int, const glm::vec3&); void vertexNormal (unsigned int, const glm::vec3&); void setVertexNormal (unsigned int); void setAllNormals (); void reset (); void fromMesh (const Mesh&); void realignFace (unsigned int); void realignFaces (const DynamicFaces&); void realignAllFaces (); void sanitize (); void prune (std::vector* = nullptr, std::vector* = nullptr); bool pruneAndCheckConsistency (std::vector* = nullptr, std::vector* = nullptr); bool mirrorPositive (const PrimPlane&); void mirror (const PrimPlane&); void moveToCenter (); void normalizeScaling (); void bufferData (); void render (Camera&) const; const RenderMode& renderMode () const; RenderMode& renderMode (); bool intersects (const PrimRay&, Intersection&, bool = false) const; bool intersects (const PrimRay&, DynamicMeshIntersection&); bool intersects (const PrimPlane&, DynamicFaces&) const; bool intersects (const PrimSphere&, DynamicFaces&) const; bool intersects (const PrimAABox&, DynamicFaces&) const; float unsignedDistance (const glm::vec3&) const; void normalize (); void scale (const glm::vec3&); void scaling (const glm::vec3&); glm::vec3 scaling () const; void translate (const glm::vec3&); void position (const glm::vec3&); glm::vec3 position () const; void rotationMatrix (const glm::mat4x4&); const glm::mat4x4& rotationMatrix () const; void rotation (const glm::vec3&, float); void rotationX (float); void rotationY (float); void rotationZ (float); void rotate (const glm::mat4x4&); void rotate (const glm::vec3&, float); void rotateX (float); void rotateY (float); void rotateZ (float); const Color& color () const; void color (const Color&); const Color& wireframeColor () const; void wireframeColor (const Color&); void printStatistics () const; private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/dynamic/octree.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include #include "dynamic/octree.hpp" #include "intersection.hpp" #include "maybe.hpp" #include "primitive/aabox.hpp" #include "primitive/plane.hpp" #include "primitive/sphere.hpp" #include "util.hpp" #ifdef DILAY_RENDER_OCTREE #include "../mesh.hpp" #include "color.hpp" #include "render-mode.hpp" #endif namespace { struct IndexOctreeNode; typedef Maybe Child; struct IndexOctreeStatistics { typedef std::unordered_map DepthMap; unsigned int numNodes; unsigned int numElements; int minDepth; int maxDepth; unsigned int maxElementsPerNode; DepthMap numElementsPerDepth; DepthMap numNodesPerDepth; }; struct IndexOctreeNode { const glm::vec3 center; const float width; const int depth; const PrimAABox looseAABox; std::array children; std::unordered_set indices; static constexpr float relativeMinElementExtent = 0.25f; IndexOctreeNode (const glm::vec3& c, float w, int d) : center (c) , width (w) , depth (d) , looseAABox (c, 2.0f * w, 2.0f * w, 2.0f * w) { static_assert (IndexOctreeNode::relativeMinElementExtent < 0.5f, "relativeMinElementExtent must be smaller than 0.5f"); assert (w > 0.0f); } bool approxContains (const glm::vec3& position, float maxDimExtent) const { const glm::vec3 min = this->center - glm::vec3 (Util::epsilon () + (this->width * 0.5f)); const glm::vec3 max = this->center + glm::vec3 (Util::epsilon () + (this->width * 0.5f)); return glm::all (glm::lessThanEqual (min, position)) && glm::all (glm::lessThanEqual (position, max)) && maxDimExtent <= this->width; } /* node indices: * (-,-,-) -> 0 * (-,-,+) -> 1 * (-,+,-) -> 2 * (-,+,+) -> 3 * (+,-,-) -> 4 * (+,-,+) -> 5 * (+,+,-) -> 6 * (+,+,+) -> 7 */ unsigned int childIndex (const glm::vec3& position) const { unsigned int index = 0; if (this->center.x < position.x) { index += 4; } if (this->center.y < position.y) { index += 2; } if (this->center.z < position.z) { index += 1; } return index; } bool hasChildren () const { return bool(this->children[0]) || bool(this->children[1]) || bool(this->children[2]) || bool(this->children[3]) || bool(this->children[4]) || bool(this->children[5]) || bool(this->children[6]) || bool(this->children[7]); } bool insertIntoChild (float maxDimExtent) const { return maxDimExtent <= this->width * IndexOctreeNode::relativeMinElementExtent; } IndexOctreeNode& insertIntoChild (unsigned int index, const glm::vec3& position, float maxDimExtent) { const unsigned int childIndex = this->childIndex (position); if (this->children[childIndex] == false) { const float q = this->width * 0.25f; const float width = this->width * 0.5f; const int depth = this->depth + 1; switch (childIndex) { case 0: this->children[0] = Child::make (this->center + glm::vec3 (-q, -q, -q), width, depth); break; case 1: this->children[1] = Child::make (this->center + glm::vec3 (-q, -q, +q), width, depth); break; case 2: this->children[2] = Child::make (this->center + glm::vec3 (-q, +q, -q), width, depth); break; case 3: this->children[3] = Child::make (this->center + glm::vec3 (-q, +q, +q), width, depth); break; case 4: this->children[4] = Child::make (this->center + glm::vec3 (+q, -q, -q), width, depth); break; case 5: this->children[5] = Child::make (this->center + glm::vec3 (+q, -q, +q), width, depth); break; case 6: this->children[6] = Child::make (this->center + glm::vec3 (+q, +q, -q), width, depth); break; case 7: this->children[7] = Child::make (this->center + glm::vec3 (+q, +q, +q), width, depth); break; } } return this->children[childIndex]->addElement (index, position, maxDimExtent); } IndexOctreeNode& addElement (unsigned int index, const glm::vec3& position, float maxDimExtent) { assert (this->approxContains (position, maxDimExtent)); if (this->insertIntoChild (maxDimExtent)) { return this->insertIntoChild (index, position, maxDimExtent); } else { this->indices.insert (index); return *this; } } bool isEmpty () const { return this->indices.empty () && this->hasChildren () == false; } void deleteElement (unsigned int index) { unsigned int n = this->indices.erase (index); assert (n > 0); unused (n); } bool deleteEmptyChildren () { bool allChildrenEmpty = true; for (unsigned int i = 0; i < 8; i++) { if (this->children[i]) { if (this->children[i]->deleteEmptyChildren ()) { this->children[i].reset (); } else { allChildrenEmpty = false; } } } if (allChildrenEmpty) { assert (this->hasChildren () == false); return this->indices.empty (); } else { return false; } } #ifdef DILAY_RENDER_OCTREE void render (Camera& camera, Mesh& nodeMesh) const { nodeMesh.position (this->center); nodeMesh.scaling (glm::vec3 (this->width * 0.5f)); nodeMesh.renderLines (camera); for (unsigned int i = 0; i < 8; i++) { if (this->children[i]) { this->children[i]->render (camera, nodeMesh); } } } #endif template void containsOrIntersectsT (const T& t, const DynamicOctree::ContainsIntersectionCallback& f) const { const bool contains = t.contains (this->looseAABox); if (contains || IntersectionUtil::intersects (t, this->looseAABox)) { for (unsigned int index : this->indices) { f (contains, index); } for (unsigned int i = 0; i < 8; i++) { if (this->children[i]) { this->children[i]->containsOrIntersectsT (t, f); } } } } template void intersectsT (const T& t, const DynamicOctree::IntersectionCallback& f) const { if (IntersectionUtil::intersects (t, this->looseAABox)) { for (unsigned int index : this->indices) { f (index); } for (unsigned int i = 0; i < 8; i++) { if (this->children[i]) { this->children[i]->intersectsT (t, f); } } } } void intersects (const PrimRay& ray, float& distance, const DynamicOctree::RayIntersectionCallback& f) const { float t; if (IntersectionUtil::intersects (ray, this->looseAABox, &t) && t < distance) { for (unsigned int index : this->indices) { distance = glm::min (f (index), distance); } for (unsigned int i = 0; i < 8; i++) { if (this->children[i]) { this->children[i]->intersects (ray, distance, f); } } } } void distance (PrimSphere& sphere, const DynamicOctree::DistanceCallback& getDistance) const { for (unsigned int i : this->indices) { const float distance = getDistance (i); if (distance < sphere.radius ()) { sphere.radius (distance); } } const unsigned int first = this->childIndex (sphere.center ()); const bool hasFirst = bool(this->children[first]); if (hasFirst && IntersectionUtil::intersects (sphere, this->children[first]->looseAABox)) { this->children[first]->distance (sphere, getDistance); } for (unsigned int i = 0; i < 8; i++) { const bool hasChild = i != first && bool(this->children[i]); if (hasChild && IntersectionUtil::intersects (sphere, this->children[i]->looseAABox)) { this->children[i]->distance (sphere, getDistance); } } } unsigned int numElements () const { return this->indices.size (); } void updateIndices (const std::vector& indexMap) { std::unordered_set newIndices; for (unsigned int i : this->indices) { assert (indexMap[i] != Util::invalidIndex ()); newIndices.insert (indexMap[i]); } this->indices = std::move (newIndices); for (unsigned int i = 0; i < 8; i++) { if (this->children[i]) { this->children[i]->updateIndices (indexMap); } } } void updateStatistics (IndexOctreeStatistics& stats) const { stats.numNodes += 1; stats.numElements += this->numElements (); stats.minDepth = glm::min (stats.minDepth, this->depth); stats.maxDepth = glm::max (stats.maxDepth, this->depth); stats.maxElementsPerNode = glm::max (stats.maxElementsPerNode, this->numElements ()); auto e = stats.numElementsPerDepth.find (this->depth); if (e == stats.numElementsPerDepth.end ()) { stats.numElementsPerDepth.emplace (this->depth, this->numElements ()); } else { e->second = e->second + this->numElements (); } e = stats.numNodesPerDepth.find (this->depth); if (e == stats.numNodesPerDepth.end ()) { stats.numNodesPerDepth.emplace (this->depth, 1); } else { e->second = e->second + 1; } for (unsigned int i = 0; i < 8; i++) { if (this->children[i]) { this->children[i]->updateStatistics (stats); } } } }; } struct DynamicOctree::Impl { Child root; std::vector elementNodeMap; Impl () {} Impl (const Impl& other) : root (other.root) { this->makeElementNodeMap (); } bool hasRoot () const { return bool(this->root); } void setupRoot (const glm::vec3& position, float width) { assert (this->hasRoot () == false); this->root = IndexOctreeNode (position, width, 0); } void makeElementNodeMap () { std::function traverse = [this, &traverse](IndexOctreeNode& node) { for (unsigned i : node.indices) { this->addToElementNodeMap (i, node); } for (unsigned int i = 0; i < 8; i++) { if (node.children[i]) { traverse (*node.children[i]); } } }; if (this->root) { traverse (*this->root); } } void addToElementNodeMap (unsigned int index, IndexOctreeNode& node) { if (index >= this->elementNodeMap.size ()) { this->elementNodeMap.resize (index + 1, nullptr); } assert (this->elementNodeMap[index] == nullptr); this->elementNodeMap[index] = &node; } void makeParent (const glm::vec3& position) { assert (this->hasRoot ()); const glm::vec3 rootCenter = this->root->center; const float rootWidth = this->root->width; const float halfRootWidth = this->root->width * 0.5f; glm::vec3 parentCenter; int index = 0; if (rootCenter.x < position.x) parentCenter.x = rootCenter.x + halfRootWidth; else { parentCenter.x = rootCenter.x - halfRootWidth; index += 4; } if (rootCenter.y < position.y) parentCenter.y = rootCenter.y + halfRootWidth; else { parentCenter.y = rootCenter.y - halfRootWidth; index += 2; } if (rootCenter.z < position.z) parentCenter.z = rootCenter.z + halfRootWidth; else { parentCenter.z = rootCenter.z - halfRootWidth; index += 1; } IndexOctreeNode* newRoot = new IndexOctreeNode (parentCenter, rootWidth * 2.0f, this->root->depth - 1); newRoot->children[index] = std::move (this->root); this->root.reset (newRoot); } void addElement (unsigned int index, const glm::vec3& position, float maxDimExtent) { assert (this->hasRoot ()); if (this->root->approxContains (position, maxDimExtent)) { IndexOctreeNode& node = this->root->addElement (index, position, maxDimExtent); this->addToElementNodeMap (index, node); } else { this->makeParent (position); this->addElement (index, position, maxDimExtent); } } void realignElement (unsigned int index, const glm::vec3& position, float maxDimExtent) { assert (this->hasRoot ()); assert (index < this->elementNodeMap.size ()); assert (this->elementNodeMap[index]); IndexOctreeNode* node = this->elementNodeMap[index]; if (node->approxContains (position, maxDimExtent) == false || node->insertIntoChild (maxDimExtent)) { this->deleteElement (index); this->addElement (index, position, maxDimExtent); } } void deleteElement (unsigned int index) { assert (index < this->elementNodeMap.size ()); assert (this->elementNodeMap[index]); this->elementNodeMap[index]->deleteElement (index); this->elementNodeMap[index] = nullptr; if (this->hasRoot ()) { if (this->root->isEmpty ()) { this->root.reset (); } else { this->shrinkRoot (); } } } void deleteEmptyChildren () { if (this->hasRoot ()) { if (this->root->deleteEmptyChildren ()) { this->root.reset (); } } } void updateIndices (const std::vector& newIndices) { for (unsigned int i = 0; i < newIndices.size (); i++) { const unsigned int newI = newIndices[i]; if (newI != Util::invalidIndex () && newI != i) { assert (i < this->elementNodeMap.size ()); assert (newI < this->elementNodeMap.size ()); assert (this->elementNodeMap[i]); assert (this->elementNodeMap[newI] == nullptr); this->elementNodeMap[newI] = this->elementNodeMap[i]; this->elementNodeMap[i] = nullptr; } } this->elementNodeMap.resize (newIndices.size ()); if (this->hasRoot ()) { this->root->updateIndices (newIndices); } } void shrinkRoot () { if (this->hasRoot () && this->root->indices.empty () && this->root->hasChildren ()) { int singleNonEmptyChildIndex = -1; for (int i = 0; i < 8; i++) { if (this->root->children[i] && this->root->children[i]->isEmpty () == false) { if (singleNonEmptyChildIndex == -1) { singleNonEmptyChildIndex = i; } else { return; } } } if (singleNonEmptyChildIndex != -1) { this->root = std::move (this->root->children[singleNonEmptyChildIndex]); this->shrinkRoot (); } } } void reset () { this->root.reset (); this->elementNodeMap.clear (); } #ifdef DILAY_RENDER_OCTREE void render (Camera& camera) const { Mesh nodeMesh; nodeMesh.addVertex (glm::vec3 (-1.0f, -1.0f, -1.0f)); nodeMesh.addVertex (glm::vec3 (-1.0f, -1.0f, 1.0f)); nodeMesh.addVertex (glm::vec3 (-1.0f, 1.0f, -1.0f)); nodeMesh.addVertex (glm::vec3 (-1.0f, 1.0f, 1.0f)); nodeMesh.addVertex (glm::vec3 (1.0f, -1.0f, -1.0f)); nodeMesh.addVertex (glm::vec3 (1.0f, -1.0f, 1.0f)); nodeMesh.addVertex (glm::vec3 (1.0f, 1.0f, -1.0f)); nodeMesh.addVertex (glm::vec3 (1.0f, 1.0f, 1.0f)); nodeMesh.addIndex (0); nodeMesh.addIndex (1); nodeMesh.addIndex (1); nodeMesh.addIndex (3); nodeMesh.addIndex (3); nodeMesh.addIndex (2); nodeMesh.addIndex (2); nodeMesh.addIndex (0); nodeMesh.addIndex (4); nodeMesh.addIndex (5); nodeMesh.addIndex (5); nodeMesh.addIndex (7); nodeMesh.addIndex (7); nodeMesh.addIndex (6); nodeMesh.addIndex (6); nodeMesh.addIndex (4); nodeMesh.addIndex (1); nodeMesh.addIndex (5); nodeMesh.addIndex (5); nodeMesh.addIndex (7); nodeMesh.addIndex (7); nodeMesh.addIndex (3); nodeMesh.addIndex (3); nodeMesh.addIndex (1); nodeMesh.addIndex (4); nodeMesh.addIndex (6); nodeMesh.addIndex (6); nodeMesh.addIndex (2); nodeMesh.addIndex (2); nodeMesh.addIndex (0); nodeMesh.addIndex (0); nodeMesh.addIndex (4); nodeMesh.renderMode ().constantShading (true); nodeMesh.renderMode ().noDepthTest (true); nodeMesh.color (Color (1.0f, 1.0f, 0.0f)); nodeMesh.bufferData (); if (this->hasRoot ()) { this->root->render (camera, nodeMesh); } } #else void render (Camera&) const { DILAY_IMPOSSIBLE } #endif void intersects (const PrimRay& ray, const DynamicOctree::RayIntersectionCallback& f) const { if (this->hasRoot ()) { float distance = Util::maxFloat (); return this->root->intersects (ray, distance, f); } } void intersects (const PrimPlane& plane, const DynamicOctree::IntersectionCallback& f) const { if (this->hasRoot ()) { return this->root->intersectsT (plane, f); } } void intersects (const PrimSphere& sphere, const DynamicOctree::ContainsIntersectionCallback& f) const { if (this->hasRoot ()) { return this->root->containsOrIntersectsT (sphere, f); } } void intersects (const PrimAABox& box, const DynamicOctree::ContainsIntersectionCallback& f) const { if (this->hasRoot ()) { return this->root->containsOrIntersectsT (box, f); } } float distance (const glm::vec3& p, const DistanceCallback& getDistance) const { assert (this->hasRoot ()); PrimSphere sphere (p, Util::maxFloat ()); this->root->distance (sphere, getDistance); return sphere.radius (); } void printStatistics () const { IndexOctreeStatistics stats{0, 0, Util::maxInt (), Util::minInt (), 0, IndexOctreeStatistics::DepthMap (), IndexOctreeStatistics::DepthMap ()}; if (this->hasRoot ()) { this->root->updateStatistics (stats); } std::cout << "octree:" << "\n\tnum nodes:\t\t\t" << stats.numNodes << "\n\tnum elements:\t\t\t" << stats.numElements << "\n\tmax elements per node:\t\t" << stats.maxElementsPerNode << "\n\tmin depth:\t\t\t" << stats.minDepth << "\n\tmax depth:\t\t\t" << stats.maxDepth << "\n\telements per node:\t\t" << float(stats.numElements) / float(stats.numNodes) << std::endl; } }; DELEGATE_BIG4_COPY (DynamicOctree) DELEGATE_CONST (bool, DynamicOctree, hasRoot) DELEGATE2 (void, DynamicOctree, setupRoot, const glm::vec3&, float) DELEGATE3 (void, DynamicOctree, addElement, unsigned int, const glm::vec3&, float) DELEGATE3 (void, DynamicOctree, realignElement, unsigned int, const glm::vec3&, float) DELEGATE1 (void, DynamicOctree, deleteElement, unsigned int) DELEGATE (void, DynamicOctree, deleteEmptyChildren) DELEGATE1 (void, DynamicOctree, updateIndices, const std::vector&) DELEGATE (void, DynamicOctree, shrinkRoot) DELEGATE (void, DynamicOctree, reset) DELEGATE1_CONST (void, DynamicOctree, render, Camera&) DELEGATE2_CONST (void, DynamicOctree, intersects, const PrimRay&, const DynamicOctree::RayIntersectionCallback&) DELEGATE2_CONST (void, DynamicOctree, intersects, const PrimPlane&, const DynamicOctree::IntersectionCallback&) DELEGATE2_CONST (void, DynamicOctree, intersects, const PrimSphere&, const DynamicOctree::ContainsIntersectionCallback&) DELEGATE2_CONST (void, DynamicOctree, intersects, const PrimAABox&, const DynamicOctree::ContainsIntersectionCallback&) DELEGATE2_CONST (float, DynamicOctree, distance, const glm::vec3&, const DynamicOctree::DistanceCallback&) DELEGATE_CONST (void, DynamicOctree, printStatistics) ================================================ FILE: lib/src/dynamic/octree.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_DYNAMIC_OCTREE #define DILAY_DYNAMIC_OCTREE #include #include #include #include "macro.hpp" class Camera; class PrimAABox; class PrimPlane; class PrimRay; class PrimSphere; class DynamicOctree { public: DECLARE_BIG4_EXPLICIT_COPY (DynamicOctree) typedef std::function IntersectionCallback; typedef std::function RayIntersectionCallback; typedef std::function ContainsIntersectionCallback; typedef std::function DistanceCallback; bool hasRoot () const; void setupRoot (const glm::vec3&, float); void addElement (unsigned int, const glm::vec3&, float); void realignElement (unsigned int, const glm::vec3&, float); void deleteElement (unsigned int); void deleteEmptyChildren (); void updateIndices (const std::vector&); void shrinkRoot (); void reset (); void render (Camera&) const; void intersects (const PrimRay&, const RayIntersectionCallback&) const; void intersects (const PrimPlane&, const IntersectionCallback&) const; void intersects (const PrimSphere&, const ContainsIntersectionCallback&) const; void intersects (const PrimAABox&, const ContainsIntersectionCallback&) const; float distance (const glm::vec3&, const DistanceCallback&) const; void printStatistics () const; private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/hash.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_HASH #define DILAY_HASH #include #include namespace Hash { // cf. `http://www.boost.org/doc/libs/1_55_0/boost/functional/hash/hash.hpp` template void combine (std::size_t& seed, const T& value) { seed ^= std::hash () (value) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } } namespace std { template struct hash> { size_t operator() (const std::pair& pair) const { size_t seed = 0; Hash::combine (seed, pair.first); Hash::combine (seed, pair.second); return seed; } }; } #endif ================================================ FILE: lib/src/history.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "config.hpp" #include "dynamic/mesh.hpp" #include "history.hpp" #include "maybe.hpp" #include "mesh.hpp" #include "scene.hpp" #include "sketch/mesh.hpp" #include "sketch/path.hpp" #include "state.hpp" namespace { struct SnapshotConfig { bool snapshotDynamicMeshes; bool snapshotSketchMeshes; SnapshotConfig (bool d, bool s) : snapshotDynamicMeshes (d) , snapshotSketchMeshes (s) { assert (this->snapshotDynamicMeshes || this->snapshotSketchMeshes); } }; struct SceneSnapshot { const SnapshotConfig config; std::list dynamicMeshes; std::list sketchMeshes; SceneSnapshot (const SnapshotConfig& c) : config (c) { } }; typedef std::list Timeline; SceneSnapshot sceneSnapshot (const Scene& scene, const SnapshotConfig& config) { SceneSnapshot snapshot (config); if (config.snapshotDynamicMeshes) { scene.forEachConstMesh ( [&snapshot](const DynamicMesh& mesh) { snapshot.dynamicMeshes.emplace_back (mesh); }); } if (config.snapshotSketchMeshes) { scene.forEachConstMesh ( [&snapshot](const SketchMesh& mesh) { snapshot.sketchMeshes.emplace_back (mesh); }); } return snapshot; } void resetToSnapshot (const SceneSnapshot& snapshot, State& state) { Scene& scene = state.scene (); if (snapshot.config.snapshotDynamicMeshes) { scene.deleteDynamicMeshes (); for (const DynamicMesh& mesh : snapshot.dynamicMeshes) { scene.newDynamicMesh (state.config (), mesh); } } if (snapshot.config.snapshotSketchMeshes) { scene.deleteSketchMeshes (); for (const SketchMesh& mesh : snapshot.sketchMeshes) { scene.newSketchMesh (state.config (), mesh); } } } } struct History::Impl { unsigned int undoDepth; Timeline past; Timeline future; Impl (const Config& config) { this->runFromConfig (config); } void snapshotAll (const Scene& scene) { this->snapshot (scene, SnapshotConfig (true, true)); } void snapshotDynamicMeshes (const Scene& scene) { this->snapshot (scene, SnapshotConfig (true, false)); } void snapshotSketchMeshes (const Scene& scene) { this->snapshot (scene, SnapshotConfig (false, true)); } void snapshot (const Scene& scene, const SnapshotConfig& config) { assert (undoDepth > 0); this->future.clear (); while (this->past.size () >= this->undoDepth) { this->past.pop_back (); } this->past.push_front (sceneSnapshot (scene, config)); } void dropPastSnapshot () { if (this->past.empty () == false) { this->past.pop_front (); } } void dropFutureSnapshot () { if (this->future.empty () == false) { this->future.pop_front (); } } void undo (State& state) { if (this->past.empty () == false) { const SnapshotConfig& config = this->past.front ().config; this->future.push_front (sceneSnapshot (state.scene (), config)); resetToSnapshot (this->past.front (), state); this->past.pop_front (); } } void redo (State& state) { if (this->future.empty () == false) { const SnapshotConfig& config = this->future.front ().config; this->past.push_front (sceneSnapshot (state.scene (), config)); resetToSnapshot (this->future.front (), state); this->future.pop_front (); } } bool hasRecentDynamicMesh () const { return this->past.empty () == false && this->past.front ().config.snapshotDynamicMeshes; } void forEachRecentDynamicMesh (const std::function& f) const { assert (this->hasRecentDynamicMesh ()); for (const DynamicMesh& m : this->past.front ().dynamicMeshes) { f (m); } } void reset () { this->past.clear (); this->future.clear (); } void runFromConfig (const Config& config) { this->undoDepth = config.get ("editor/undo-depth"); } }; DELEGATE1_BIG3 (History, const Config&) DELEGATE1 (void, History, snapshotAll, const Scene&) DELEGATE1 (void, History, snapshotDynamicMeshes, const Scene&) DELEGATE1 (void, History, snapshotSketchMeshes, const Scene&) DELEGATE (void, History, dropPastSnapshot) DELEGATE (void, History, dropFutureSnapshot) DELEGATE1 (void, History, undo, State&) DELEGATE1 (void, History, redo, State&) DELEGATE_CONST (bool, History, hasRecentDynamicMesh) DELEGATE1_CONST (void, History, forEachRecentDynamicMesh, const std::function&) DELEGATE (void, History, reset) DELEGATE1 (void, History, runFromConfig, const Config&) ================================================ FILE: lib/src/history.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_HISTORY #define DILAY_HISTORY #include #include "configurable.hpp" #include "macro.hpp" class DynamicMesh; class Scene; class State; class History : public Configurable { public: DECLARE_BIG3 (History, const Config&) void snapshotAll (const Scene&); void snapshotDynamicMeshes (const Scene&); void snapshotSketchMeshes (const Scene&); void dropPastSnapshot (); void dropFutureSnapshot (); void undo (State&); void redo (State&); bool hasRecentDynamicMesh () const; void forEachRecentDynamicMesh (const std::function&) const; void reset (); private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/import-export.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "dynamic/mesh.hpp" #include "import-export.hpp" #include "mesh-util.hpp" #include "mesh.hpp" #include "scene.hpp" #include "sketch/fwd.hpp" #include "sketch/mesh.hpp" #include "sketch/path.hpp" #include "util.hpp" namespace { std::ostream& operator<< (std::ostream& os, const glm::vec3& v) { os << v.x << " " << v.y << " " << v.z; return os; } std::istream& operator>> (std::istream& is, glm::vec3& v) { is >> v.x >> v.y >> v.z; return is; } void toDlyFile (std::ostream& stream, const Mesh& mesh) { stream << "o\n"; for (unsigned int i = 0; i < mesh.numVertices (); i++) { stream << "v " << mesh.vertex (i) << std::endl; } for (unsigned int i = 0; i < mesh.numIndices (); i += 3) { stream << "f " << mesh.index (i + 0) + 1 << " " << mesh.index (i + 1) + 1 << " " << mesh.index (i + 2) + 1 << std::endl; } } unsigned int toDlyFile (std::ostream& stream, const SketchNode& node, unsigned int parentIndex, unsigned nodeIndex) { stream << "dly_sketch_node " << nodeIndex << " " << parentIndex << " " << node.data ().center () << " " << node.data ().radius () << std::endl; unsigned int childIndex = nodeIndex; node.forEachConstChild ([&stream, nodeIndex, &childIndex](const SketchNode& child) { childIndex = toDlyFile (stream, child, nodeIndex, childIndex + 1); }); return childIndex; } void toDlyFile (std::ostream& stream, const SketchPath& path) { if (path.isEmpty () == false) { stream << "dly_sketch_path" << " " << path.intersectionFirst () << " " << path.intersectionLast () << std::endl; for (const PrimSphere& s : path.spheres ()) { stream << "dly_sketch_sphere" << " " << s.center () << " " << s.radius () << std::endl; } } } void toDlyFile (std::ostream& stream, const SketchMesh& mesh) { if (mesh.isEmpty () == false) { stream << "dly_sketch_mesh\n"; if (mesh.tree ().hasRoot ()) { toDlyFile (stream, mesh.tree ().root (), Util::invalidIndex (), 0); } for (const SketchPath& p : mesh.paths ()) { toDlyFile (stream, p); } } } }; namespace ImportExport { void toDlyFile (std::ostream& stream, Scene& scene, bool isObjFile) { scene.forEachMesh ([&stream](DynamicMesh& mesh) { mesh.prune (); ::toDlyFile (stream, mesh.mesh ()); }); if (isObjFile == false) { scene.forEachConstMesh ([&stream](const SketchMesh& mesh) { ::toDlyFile (stream, mesh); }); } } bool toDlyFile (const std::string& fileName, Scene& scene, bool isObjFile) { std::ofstream file (fileName); if (file.is_open ()) { ImportExport::toDlyFile (file, scene, isObjFile); file.close (); return true; } else { return false; } } bool fromDlyFile (std::istream& stream, const Config& config, Scene& scene) { unsigned int lineNumber = 0; std::istringstream lineStream; std::vector meshes; std::vector nodes; SketchMesh* sketch = nullptr; SketchPath* sketchPath = nullptr; glm::vec3 intersectionFirst, intersectionLast; auto extractFirst = [](const std::string& string, unsigned int& value) -> bool { auto slashPos = string.find ('/'); return Util::fromString (string.substr (0, slashPos), value); }; auto nextLine = [&stream, &lineNumber, &lineStream]() -> bool { std::string line; std::getline (stream, line); if (stream) { lineNumber++; lineStream.clear (); lineStream.str (line); return true; } else { return false; } }; while (nextLine ()) { std::string keyword; lineStream >> keyword; if (lineStream.fail () == false) { if (keyword == "o") { meshes.push_back (Mesh ()); } else if (keyword == "v") { glm::vec3 vertex; lineStream >> vertex; if (lineStream.fail ()) { DILAY_WARN ("could not parse vertex at line %u", lineNumber) return false; } else { if (meshes.empty ()) { meshes.push_back (Mesh ()); } meshes.back ().addVertex (vertex); } } else if (keyword == "f") { std::string v1String, v2String, v3String; unsigned int v1, v2, v3; lineStream >> v1String >> v2String >> v3String; if (lineStream.fail () || extractFirst (v1String, v1) == false || extractFirst (v2String, v2) == false || extractFirst (v3String, v3) == false) { DILAY_WARN ("could not parse face at line %u", lineNumber) return false; } else { std::string v4String; unsigned int v4; lineStream >> v4String; if (lineStream.fail ()) { lineStream.clear (); if (meshes.empty ()) { meshes.push_back (Mesh ()); } MeshUtil::addFace (meshes.back (), v1 - 1, v2 - 1, v3 - 1); } else if (extractFirst (v4String, v4) == false) { DILAY_WARN ("could not parse face at line %u", lineNumber) return false; } else { if (meshes.empty ()) { meshes.push_back (Mesh ()); } MeshUtil::addFace (meshes.back (), v1 - 1, v2 - 1, v3 - 1, v4 - 1); } } } else if (keyword == "dly_sketch_mesh") { nodes.clear (); sketch = &scene.newSketchMesh (config, SketchTree ()); } else if (keyword == "dly_sketch_node") { if (sketch == nullptr) { DILAY_WARN ("could not parse sketch node: no sketch found at line %u", lineNumber) return false; } unsigned int nodeIndex; unsigned int parentIndex; glm::vec3 center; float radius; lineStream >> nodeIndex >> parentIndex >> center >> radius; if (lineStream.fail ()) { DILAY_WARN ("could not parse sketch node at line %u", lineNumber) return false; } if (nodeIndex == nodes.size ()) { if (nodeIndex == 0) { nodes.push_back (&sketch->tree ().emplaceRoot (PrimSphere (center, radius))); } else if (parentIndex < nodes.size ()) { nodes.push_back (&nodes.at (parentIndex)->emplaceChild (PrimSphere (center, radius))); } else { DILAY_WARN ("invalid parent index at line %u", lineNumber) return false; } } else { DILAY_WARN ("invalid node index at line %u", lineNumber) return false; } } else if (keyword == "dly_sketch_path") { lineStream >> intersectionFirst >> intersectionLast; if (lineStream.fail ()) { DILAY_WARN ("could not parse sketch path at line %u", lineNumber) return false; } if (sketch) { sketchPath = &sketch->addPath (SketchPath ()); } else { DILAY_WARN ("could not parse sketch path: no sketch found at line %u", lineNumber) return false; } } else if (keyword == "dly_sketch_sphere") { glm::vec3 center; float radius; lineStream >> center >> radius; if (lineStream.fail ()) { DILAY_WARN ("could not parse sketch sphere at line %u", lineNumber) return false; } if (sketchPath) { if (sketchPath->isEmpty ()) { sketchPath->addSphere (intersectionFirst, center, radius); } else { sketchPath->addSphere (intersectionLast, center, radius); } } else { DILAY_WARN ("could not parse sketch sphere: no sketch path found at line %u", lineNumber) return false; } } } } meshes.erase (std::remove_if (meshes.begin (), meshes.end (), [](Mesh& m) { return m.numVertices () == 0; }), meshes.end ()); if (std::all_of (meshes.begin (), meshes.end (), [](Mesh& m) { return MeshUtil::checkConsistency (m); })) { for (Mesh& m : meshes) { scene.newDynamicMesh (config, m); } return true; } else { return false; } } bool fromDlyFile (const std::string& fileName, const Config& config, Scene& scene) { std::ifstream file (fileName); if (file.is_open ()) { const bool success = ImportExport::fromDlyFile (file, config, scene); file.close (); return success; } else { return false; } } }; ================================================ FILE: lib/src/import-export.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_IMPORT_EXPORT #define DILAY_IMPORT_EXPORT #include #include class Config; class Scene; namespace ImportExport { void toDlyFile (std::ostream&, Scene&, bool); bool toDlyFile (const std::string&, Scene&, bool); bool fromDlyFile (std::istream&, const Config&, Scene&); bool fromDlyFile (const std::string&, const Config&, Scene&); }; #endif ================================================ FILE: lib/src/intersection.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "intersection.hpp" #include "primitive/aabox.hpp" #include "primitive/cone.hpp" #include "primitive/cylinder.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "primitive/sphere.hpp" #include "primitive/triangle.hpp" #include "util.hpp" Intersection ::Intersection () : _isIntersection (false) , _distance (Util::maxFloat ()) { } bool Intersection::isIntersection () const { return this->_isIntersection; } const glm::vec3& Intersection::position () const { assert (this->_isIntersection); return this->_position; } const glm::vec3& Intersection::normal () const { assert (this->_isIntersection); return this->_normal; } float Intersection::distance () const { assert (this->_isIntersection); return this->_distance; } void Intersection::reset () { this->_isIntersection = false; } bool Intersection::update (float d, const glm::vec3& p, const glm::vec3& n) { if (this->_isIntersection == false || d < this->_distance) { this->_isIntersection = true; this->_distance = d; this->_position = p; this->_normal = n; return true; } return false; } Intersection& Intersection::min (Intersection& a, Intersection& b) { if (a._isIntersection && (b._isIntersection == false || a._distance < b._distance)) { return a; } else { return b; } } void Intersection::sort (Intersection& a, Intersection& b) { if (b._isIntersection && (a._isIntersection == false || b._distance < a._distance)) { std::swap (a, b); } } namespace { bool intersectsQuadric (float a, float b, float c, bool alongLine, float* t) { float s1, s2; const unsigned int n = Util::solveQuadraticEq (a, b, c, s1, s2); switch (n) { case 0: return false; case 1: if (s1 >= 0.0f || alongLine) { Util::setIfNotNull (t, s1); return true; } else { return false; } case 2: { const float sMin = glm::min (s1, s2); const float sMax = glm::max (s1, s2); if (sMin >= 0.0f) { Util::setIfNotNull (t, sMin); return true; } else if (sMax >= 0.0f || alongLine) { Util::setIfNotNull (t, sMax); return true; } return false; } default: DILAY_IMPOSSIBLE } } } // see http://realtimecollisiondetection.net/blog/?p=103 bool IntersectionUtil::intersects (const PrimSphere& sphere, const PrimTriangle& tri) { const glm::vec3 A = tri.vertex1 () - sphere.center (); const glm::vec3 B = tri.vertex2 () - sphere.center (); const glm::vec3 C = tri.vertex3 () - sphere.center (); const float rr = sphere.radius () * sphere.radius (); const glm::vec3 V = glm::cross (B - A, C - A); const float d = glm::dot (A, V); const float e = glm::dot (V, V); const bool sep1 = d * d > rr * e; const float aa = glm::dot (A, A); const float ab = glm::dot (A, B); const float ac = glm::dot (A, C); const float bb = glm::dot (B, B); const float bc = glm::dot (B, C); const float cc = glm::dot (C, C); const bool sep2 = (aa > rr) && (ab > aa) && (ac > aa); const bool sep3 = (bb > rr) && (ab > bb) && (bc > bb); const bool sep4 = (cc > rr) && (ac > cc) && (bc > cc); const glm::vec3 AB = B - A; const glm::vec3 BC = C - B; const glm::vec3 CA = A - C; const float d1 = ab - aa; const float d2 = bc - bb; const float d3 = ac - cc; const float e1 = glm::dot (AB, AB); const float e2 = glm::dot (BC, BC); const float e3 = glm::dot (CA, CA); const glm::vec3 Q1 = (A * e1) - (d1 * AB); const glm::vec3 Q2 = (B * e2) - (d2 * BC); const glm::vec3 Q3 = (C * e3) - (d3 * CA); const glm::vec3 QC = (C * e1) - Q1; const glm::vec3 QA = (A * e2) - Q2; const glm::vec3 QB = (B * e3) - Q3; const bool sep5 = (glm::dot (Q1, Q1) > rr * e1 * e1) && (glm::dot (Q1, QC) > 0.0f); const bool sep6 = (glm::dot (Q2, Q2) > rr * e2 * e2) && (glm::dot (Q2, QA) > 0.0f); const bool sep7 = (glm::dot (Q3, Q3) > rr * e3 * e3) && (glm::dot (Q3, QB) > 0.0f); return (sep1 || sep2 || sep3 || sep4 || sep5 || sep6 || sep7) == false; } bool IntersectionUtil::intersects (const PrimSphere& sphere, const PrimAABox& box) { const glm::vec3 c = sphere.center (); const glm::vec3& min = box.minimum (); const glm::vec3& max = box.maximum (); float d = 0.0f; for (unsigned int i = 0; i < 3; i++) { if (c[i] < min[i]) { const float s = c[i] - min[i]; d += s * s; } else if (c[i] > max[i]) { const float s = c[i] - max[i]; d += s * s; } } return d <= sphere.radius () * sphere.radius (); } bool IntersectionUtil::intersects (const PrimSphere& sphere1, const PrimSphere& sphere2) { return glm::distance2 (sphere1.center (), sphere2.center ()) < ((sphere1.radius () + sphere2.radius ()) * (sphere1.radius () + sphere2.radius ())); } bool IntersectionUtil::intersects (const PrimRay& ray, const PrimSphere& sphere, float* t) { const glm::vec3& dir = ray.direction (); const glm::vec3& origin = ray.origin () - sphere.center (); const float radius2 = sphere.radius () * sphere.radius (); return intersectsQuadric (glm::dot (dir, dir), 2.0f * glm::dot (dir, origin), glm::dot (origin, origin) - radius2, ray.isLine (), t); } bool IntersectionUtil::intersects (const PrimRay& ray, const PrimPlane& plane, float* t) { const float d = glm::dot (ray.direction (), plane.normal ()); if (Util::almostEqual (d, 0.0f)) { return false; } const float s = glm::dot (plane.point () - ray.origin (), plane.normal ()) / d; if (s >= 0.0f || ray.isLine ()) { Util::setIfNotNull (t, s); return true; } else { return false; } } // see // http://www.cs.virginia.edu/~gfx/Courses/2003/ImageSynthesis/papers/Acceleration/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf bool IntersectionUtil::intersects (const PrimRay& ray, const PrimTriangle& tri, bool both, float* t) { const float dot = glm::dot (ray.direction (), tri.normal ()); if (both == false && dot > -Util::epsilon ()) { return false; } else if (both && dot < Util::epsilon () && dot > -Util::epsilon ()) { return false; } const glm::vec3 e1 = tri.vertex2 () - tri.vertex1 (); const glm::vec3 e2 = tri.vertex3 () - tri.vertex1 (); const glm::vec3 s1 = glm::cross (ray.direction (), e2); const float invDet = 1.0f / glm::dot (s1, e1); const glm::vec3 d = ray.origin () - tri.vertex1 (); const glm::vec3 s2 = glm::cross (d, e1); const float b1 = glm::dot (d, s1) * invDet; const float b2 = glm::dot (ray.direction (), s2) * invDet; const float tRay = glm::dot (e2, s2) * invDet; if (b1 < 0.0f || b2 < 0.0f || b1 + b2 > 1.0f || (tRay < 0.0f && ray.isLine () == false)) { return false; } else { Util::setIfNotNull (t, tRay); return true; } } bool IntersectionUtil::intersects (const PrimRay& ray, const PrimAABox& box, float* t) { const glm::vec3 invDir = glm::vec3 (1.0f) / ray.direction (); const glm::vec3 lowerTs = (box.minimum () - ray.origin ()) * invDir; const glm::vec3 upperTs = (box.maximum () - ray.origin ()) * invDir; const glm::vec3 min = glm::min (lowerTs, upperTs); const glm::vec3 max = glm::max (lowerTs, upperTs); const float tMin = glm::max (glm::max (min.x, min.y), min.z); const float tMax = glm::min (glm::min (max.x, max.y), max.z); if ((tMax >= 0.0f || ray.isLine ()) && tMin <= tMax) { Util::setIfNotNull (t, tMin); return true; } else { return false; } } bool IntersectionUtil::intersects (const PrimRay& ray, const PrimCylinder& cylinder, float* tRay, float* tCyl) { const glm::vec3& dir = ray.direction (); const glm::vec3& cylDir = cylinder.direction (); const glm::vec3 offset = ray.origin () - cylinder.center1 (); const glm::vec3 d = dir - (cylDir * glm::dot (cylDir, dir)); const glm::vec3 c = offset - (cylDir * glm::dot (cylDir, offset)); const float radius2 = cylinder.radius () * cylinder.radius (); float tmpRay; if (intersectsQuadric (glm::dot (d, d), 2.0f * glm::dot (c, d), glm::dot (c, c) - radius2, ray.isLine (), &tmpRay)) { const glm::vec3 p = ray.pointAt (tmpRay); const float tmpCyl = glm::dot (cylDir, p - cylinder.center1 ()); if (tmpCyl >= 0.0f && tmpCyl <= cylinder.length ()) { Util::setIfNotNull (tRay, tmpRay); Util::setIfNotNull (tCyl, tmpCyl); return true; } else { return false; } } else { return false; } } bool IntersectionUtil::intersects (const PrimRay& ray, const PrimCone& cone, float* tRay, float* tCone) { if (cone.isCylinder ()) { return IntersectionUtil::intersects (ray, PrimCylinder (cone), tRay, tCone); } else { const glm::vec3& dir = ray.direction (); const glm::vec3& coneDir = cone.direction (); const glm::vec3 offset = ray.origin () - cone.apex (); const float dotD = glm::dot (coneDir, dir); const float dotO = glm::dot (coneDir, offset); const glm::vec3 d = dir - (coneDir * dotD); const glm::vec3 c = offset - (coneDir * glm::dot (coneDir, offset)); const float sinSqr = cone.sinAlpha () * cone.sinAlpha (); const float cosSqr = cone.cosAlpha () * cone.cosAlpha (); float tmpRay; if (intersectsQuadric ((cosSqr * glm::dot (d, d)) - (sinSqr * dotD * dotD), (2.0f * cosSqr * glm::dot (c, d)) - (2.0f * sinSqr * dotD * dotO), (cosSqr * glm::dot (c, c)) - (sinSqr * dotO * dotO), ray.isLine (), &tmpRay)) { const glm::vec3 p = ray.pointAt (tmpRay); const float tmpCone = glm::dot (coneDir, p - cone.center1 ()); if (tmpCone >= 0.0f && tmpCone <= cone.length ()) { Util::setIfNotNull (tRay, tmpRay); Util::setIfNotNull (tCone, tmpCone); return true; } else { return false; } } else { return false; } } } bool IntersectionUtil::intersects (const PrimPlane& plane, const PrimAABox& box) { const glm::vec3& max = box.maximum (); const glm::vec3& min = box.minimum (); const glm::vec3 p = glm::vec3 (plane.normal ().x >= 0.0f ? max.x : min.x, plane.normal ().y >= 0.0f ? max.y : min.y, plane.normal ().z >= 0.0f ? max.z : min.z); const glm::vec3 n = glm::vec3 (plane.normal ().x >= 0.0f ? min.x : max.x, plane.normal ().y >= 0.0f ? min.y : max.y, plane.normal ().z >= 0.0f ? min.z : max.z); return plane.distance (p) * plane.distance (n) < 0.0f; } bool IntersectionUtil::intersects (const PrimPlane& plane, const PrimTriangle& tri) { const float d1 = plane.distance (tri.vertex1 ()); const float d2 = plane.distance (tri.vertex2 ()); const float d3 = plane.distance (tri.vertex3 ()); const bool oneLess = d1 < Util::epsilon () || d2 < Util::epsilon () || d3 < Util::epsilon (); const bool oneGreater = d1 > -Util::epsilon () || d2 > -Util::epsilon () || d3 > -Util::epsilon (); return oneLess && oneGreater; } bool IntersectionUtil::intersects (const PrimCylinder& cylinder, const glm::vec3& point) { const glm::vec3 d = point - cylinder.center1 (); const float dot = glm::dot (cylinder.direction (), d); const glm::vec3 t = d - (cylinder.direction () * dot); return dot >= 0.0f && dot <= cylinder.length () && glm::dot (t, t) <= cylinder.radius () * cylinder.radius (); } bool IntersectionUtil::intersects (const PrimCone& cone, const glm::vec3& point) { if (cone.isCylinder ()) { return IntersectionUtil::intersects (PrimCylinder (cone), point); } else { const glm::vec3 d = point - cone.center1 (); const float dot = glm::dot (cone.direction (), d); const glm::vec3 t = d - (cone.direction () * dot); const float r = glm::mix (cone.radius1 (), cone.radius2 (), dot / cone.length ()); return dot >= 0.0f && dot <= cone.length () && glm::dot (t, t) <= r * r; } } bool IntersectionUtil::intersects (const PrimAABox& a, const PrimAABox& b) { const bool overlap1 = glm::all (glm::greaterThanEqual (a.minimum (), b.maximum ())); const bool overlap2 = glm::all (glm::greaterThanEqual (b.minimum (), a.maximum ())); const bool contain1 = glm::all (glm::greaterThan (a.maximum (), b.maximum ())) && glm::all (glm::lessThan (a.minimum (), b.minimum ())); const bool contain2 = glm::all (glm::greaterThan (b.maximum (), a.maximum ())) && glm::all (glm::lessThan (b.minimum (), a.minimum ())); return overlap1 || overlap2 || contain1 || contain2; } // http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/code/tribox_tam.pdf bool IntersectionUtil::intersects (const PrimAABox& box, const PrimTriangle& tri) { const glm::vec3 v0 = tri.vertex1 () - box.center (); const glm::vec3 v1 = tri.vertex2 () - box.center (); const glm::vec3 v2 = tri.vertex3 () - box.center (); const glm::vec3 e0 = v1 - v0; const glm::vec3 e1 = v2 - v1; const glm::vec3 e2 = v0 - v2; const glm::vec3 hw = box.halfWidth (); const glm::vec3 x = glm::vec3 (1.0f, 0.0f, 0.0f); const glm::vec3 y = glm::vec3 (0.0f, 1.0f, 0.0f); const glm::vec3 z = glm::vec3 (0.0f, 0.0f, 1.0f); auto sepAxis = [&v0, &v1, &v2, &hw](const glm::vec3& a) -> bool { const float radius = glm::dot (hw, glm::abs (a)); const float p0 = glm::dot (a, v0); const float p1 = glm::dot (a, v1); const float p2 = glm::dot (a, v2); const float min = glm::min (p0, glm::min (p1, p2)); const float max = glm::max (p0, glm::max (p1, p2)); return min > radius || max < -radius; }; const bool sep1 = glm::min (v0.x, glm::min (v1.x, v2.x)) > hw.x; const bool sep2 = glm::max (v0.x, glm::max (v1.x, v2.x)) < -hw.x; const bool sep3 = glm::min (v0.y, glm::min (v1.y, v2.y)) > hw.y; const bool sep4 = glm::max (v0.y, glm::max (v1.y, v2.y)) < -hw.y; const bool sep5 = glm::min (v0.z, glm::min (v1.z, v2.z)) > hw.z; const bool sep6 = glm::max (v0.z, glm::max (v1.z, v2.z)) < -hw.z; if (sep1 || sep2 || sep3 || sep4 || sep5 || sep6) { return false; } const bool sep7 = sepAxis (glm::cross (x, e0)); const bool sep8 = sepAxis (glm::cross (x, e1)); const bool sep9 = sepAxis (glm::cross (x, e2)); const bool sep10 = sepAxis (glm::cross (y, e0)); const bool sep11 = sepAxis (glm::cross (y, e1)); const bool sep12 = sepAxis (glm::cross (y, e2)); const bool sep13 = sepAxis (glm::cross (z, e0)); const bool sep14 = sepAxis (glm::cross (z, e1)); const bool sep15 = sepAxis (glm::cross (z, e2)); if (sep7 || sep8 || sep9 || sep10 || sep11 || sep12 || sep13 || sep14 || sep15) { return false; } else { return IntersectionUtil::intersects (PrimPlane (tri.vertex1 (), tri.normal ()), box); } } ================================================ FILE: lib/src/intersection.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_INTERSECTION #define DILAY_INTERSECTION #include class PrimAABox; class PrimCone; class PrimCylinder; class PrimPlane; class PrimRay; class PrimSphere; class PrimTriangle; class Intersection { public: Intersection (); bool isIntersection () const; const glm::vec3& position () const; const glm::vec3& normal () const; float distance () const; void reset (); bool update (float, const glm::vec3&, const glm::vec3&); static Intersection& min (Intersection&, Intersection&); static void sort (Intersection&, Intersection&); private: bool _isIntersection; float _distance; glm::vec3 _position; glm::vec3 _normal; }; namespace IntersectionUtil { bool intersects (const PrimSphere&, const PrimTriangle&); bool intersects (const PrimSphere&, const PrimAABox&); bool intersects (const PrimSphere&, const PrimSphere&); bool intersects (const PrimRay&, const PrimSphere&, float*); bool intersects (const PrimRay&, const PrimPlane&, float*); bool intersects (const PrimRay&, const PrimTriangle&, bool, float*); bool intersects (const PrimRay&, const PrimAABox&, float*); bool intersects (const PrimRay&, const PrimCylinder&, float*, float*); bool intersects (const PrimRay&, const PrimCone&, float*, float*); bool intersects (const PrimPlane&, const PrimAABox&); bool intersects (const PrimPlane&, const PrimTriangle&); bool intersects (const PrimCylinder&, const glm::vec3&); bool intersects (const PrimCone&, const glm::vec3&); bool intersects (const PrimAABox&, const PrimAABox&); bool intersects (const PrimAABox&, const PrimTriangle&); } #endif ================================================ FILE: lib/src/isosurface-extraction/IsosurfaceExtractionConfigurations.hs ================================================ {- This file is part of Dilay - Copyright © 2015-2018 Alexander Bau - Use and redistribute under the terms of the GNU General Public License -} import Control.Exception (assert) import Control.Monad (forM_) import Data.Char (toLower) import Data.Function (on) import Data.List (intercalate,nubBy,sortBy) data Configuration = Configuration { base :: Int , vertices :: [Bool] , vertexIndices :: [Int] , nonManifoldConfig :: Bool } deriving Show set :: Int -> a -> [a] -> [a] set 0 x (y:ys) = x:ys set i x (y:ys) = y:(set (i - 1) x ys) setList :: [Int] -> a -> [a] -> [a] setList is value xs = foldl (\xs i -> set i value xs) xs is baseConfigurations :: [Configuration] baseConfigurations = [ go 0 [] [] False , go 1 [4] [[2, 6, 7]] False , go 2 [4, 5] [[2, 5, 7, 10]] False , go 3 [4, 7] [[2, 6, 7], [9, 10, 11]] False , go 4 [3, 4] [[2, 6, 7], [3, 4, 11]] False , go 5 [0, 1, 5] [[1, 2, 4, 6, 10]] False , go 6 [3, 4, 5] [[2, 5, 7, 10], [3, 4, 11]] False , go 7 [3, 5, 6] [[7, 8, 9], [3, 4, 11], [5, 6, 10]] False , go 8 [0, 1, 4, 5] [[1, 4, 7, 10]] False , go 9 [0, 1, 2, 4] [[3, 4, 5, 6, 7, 8]] False , go 10 [1, 3, 4, 6] [[2, 6, 8, 9], [0, 3, 5, 11]] False , go 11 [0, 1, 3, 4] [[1, 3, 5, 6, 7, 11]] False , go 12 [0, 1, 5, 6] [[7, 8, 9], [1, 2, 4, 6, 10]] False , go 13 [1, 2, 4, 7] [[2, 6, 7], [9, 10, 11], [1, 3, 8], [0, 4, 5]] False , go 14 [0, 1, 2, 5] [[2, 3, 4, 6, 8, 10]] False , go 15 [0, 1, 2, 4, 7] [[3, 4, 5, 6, 7, 8], [9, 10, 11]] False , go 16 [0, 1, 2, 6, 7] [[2, 5, 7, 10], [3, 4, 11]] True , go 17 [2, 3, 4, 6, 7] [[1, 2, 4, 6, 10]] False , go 18 [0, 1, 2, 5, 6, 7] [[2, 6, 7], [3, 4, 11]] False , go 19 [0, 1, 2, 3, 5, 6] [[2, 6, 7], [9, 10, 11]] True , go 20 [0, 1, 2, 3, 6, 7] [[2, 5, 7, 10]] False , go 21 [0, 1, 2, 3, 5, 6, 7] [[2, 6, 7]] False , go 22 [0, 1, 2, 3, 4, 5, 6, 7] [] False ] where go base vertices vertexIndices nonManifold = Configuration base (setList vertices True $ replicate 8 False) (mkVertexIndices 0 vertexIndices) nonManifold mkVertexIndices :: Int -> [[Int]] -> [Int] mkVertexIndices vertexIndex [] = replicate 12 (-1) mkVertexIndices vertexIndex (edgeGroup:edgeGroups) = setList edgeGroup vertexIndex rest where rest = mkVertexIndices (vertexIndex + 1) edgeGroups allConfigurations :: [Configuration] allConfigurations = sortBy (sort `on` vertices) $ nubBy ((==) `on` vertices) $ concat $ do x <- [id, rotateX, rotateX . rotateX, rotateX . rotateX . rotateX] y <- [id, rotateY, rotateY . rotateY, rotateY . rotateY . rotateY] z <- [id, rotateZ, rotateZ . rotateZ, rotateZ . rotateZ . rotateZ] return $ map (($) (x . y . z)) baseConfigurations where rotateX (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7] [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold) = Configuration base [v4, v5, v0, v1, v6, v7, v2, v3] [e6, e2, e7, e0, e5, e10, e9, e8, e1, e3, e11, e4] nonManifold rotateY (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7] [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold) = Configuration base [v1, v5, v3, v7, v0, v4, v2, v6] [e5, e4, e0, e11, e10, e6, e2, e1, e3, e8, e7, e9] nonManifold rotateZ (Configuration base [v0, v1, v2, v3, v4, v5, v6, v7] [e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11] nonManifold) = Configuration base [v2, v0, v3, v1, v6, v4, v7, v5] [e1, e3, e8, e4, e0, e2, e7, e9, e11, e10, e6, e5] nonManifold sort xs ys = go (reverse xs) (reverse ys) where go (False:xs) (True:ys) = LT go (True:xs) (False:ys) = GT go (_:xs) (_:ys) = go xs ys main :: IO () main = assert (length allConfigurations == 256) $ printBases >> printNonManifold >> printVertexIndices where printBases = putStrLn $ toList (show . base) allConfigurations printNonManifold = putStrLn $ toList (map toLower . show . nonManifoldConfig) allConfigurations printVertexIndices = putStrLn $ toList (\c -> toList show (vertexIndices c) ++ "\n") allConfigurations toList xToString xs = unwords $ "{" : [ intercalate ", " $ map xToString xs ] ++ ["}"] ================================================ FILE: lib/src/isosurface-extraction/grid.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "dynamic/mesh.hpp" #include "isosurface-extraction/grid.hpp" #include "mesh.hpp" #include "primitive/aabox.hpp" #include "util.hpp" /* vertex layout: edge layout: face layout: * * 2------------3 o-----3------o - 0: bottom * /| /| /| /| - 1: top * / | / | 8 1 11 | - 2: left * / | / | / | / 4 - 3: right * 6------------7 | o-----9------o | - 4: back * | | | | | | | | - 5: front * | 0--------|---1 | o----0---|---o * | / | / 7 / 10 / * | / | / | 2 | 5 * |/ |/ |/ |/ * 4------------5 o-----6------o */ namespace { static const glm::vec3 invalidVec3 = glm::vec3 (Util::minFloat ()); static bool nonManifoldConfig[256] = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, true, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, true, true, false, false, false, false, false, false, true, false, false, false, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false, true, false, false, false, false, false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, false, false, true, false, true, false, true, false, false, true, false, true, false, false, false, false, false, false, false, false, true, false, false, false, true, false, false, false, false, false, false, false, true, false, false, false, true, false, true, true, false, false, false, true, false, false, false, false, true, false, true, true, false, false, false, false, true, false, true, false, false, false, false, false, false, false, false, true, false, false, true, false, false, false, false, false, false}; static char vertexIndicesByConfiguration[256][12] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, -1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1}, {-1, 0, 0, -1, 0, 0, -1, -1, -1, -1, -1, -1}, {-1, 0, -1, 0, -1, -1, -1, -1, 0, -1, -1, -1}, {0, -1, 0, 0, -1, -1, -1, -1, 0, -1, -1, -1}, {0, 1, -1, 1, 0, 0, -1, -1, 1, -1, -1, -1}, {-1, -1, 0, 0, 0, 0, -1, -1, 0, -1, -1, -1}, {-1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1, 0}, {0, 0, 0, 1, 1, -1, -1, -1, -1, -1, -1, 1}, {0, -1, -1, 0, -1, 0, -1, -1, -1, -1, -1, 0}, {-1, 0, 0, 0, -1, 0, -1, -1, -1, -1, -1, 0}, {-1, 0, -1, -1, 0, -1, -1, -1, 0, -1, -1, 0}, {0, -1, 0, -1, 0, -1, -1, -1, 0, -1, -1, 0}, {0, 0, -1, -1, -1, 0, -1, -1, 0, -1, -1, 0}, {-1, -1, 0, -1, -1, 0, -1, -1, 0, -1, -1, 0}, {-1, -1, 0, -1, -1, -1, 0, 0, -1, -1, -1, -1}, {0, 0, -1, -1, -1, -1, 0, 0, -1, -1, -1, -1}, {0, -1, 1, -1, 0, 0, 1, 1, -1, -1, -1, -1}, {-1, 0, -1, -1, 0, 0, 0, 0, -1, -1, -1, -1}, {-1, 1, 0, 1, -1, -1, 0, 0, 1, -1, -1, -1}, {0, -1, -1, 0, -1, -1, 0, 0, 0, -1, -1, -1}, {2, 0, 1, 0, 2, 2, 1, 1, 0, -1, -1, -1}, {-1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, -1}, {-1, -1, 0, 1, 1, -1, 0, 0, -1, -1, -1, 1}, {0, 0, -1, 1, 1, -1, 0, 0, -1, -1, -1, 1}, {0, -1, 1, 0, -1, 0, 1, 1, -1, -1, -1, 0}, {-1, 0, -1, 0, -1, 0, 0, 0, -1, -1, -1, 0}, {-1, 0, 1, -1, 0, -1, 1, 1, 0, -1, -1, 0}, {0, -1, -1, -1, 0, -1, 0, 0, 0, -1, -1, 0}, {1, 1, 0, -1, -1, 1, 0, 0, 1, -1, -1, 1}, {-1, -1, -1, -1, -1, 0, 0, 0, 0, -1, -1, 0}, {-1, -1, -1, -1, -1, 0, 0, -1, -1, -1, 0, -1}, {0, 0, 0, -1, -1, 1, 1, -1, -1, -1, 1, -1}, {0, -1, -1, -1, 0, -1, 0, -1, -1, -1, 0, -1}, {-1, 0, 0, -1, 0, -1, 0, -1, -1, -1, 0, -1}, {-1, 1, -1, 1, -1, 0, 0, -1, 1, -1, 0, -1}, {0, -1, 0, 0, -1, 1, 1, -1, 0, -1, 1, -1}, {0, 1, -1, 1, 0, -1, 0, -1, 1, -1, 0, -1}, {-1, -1, 0, 0, 0, -1, 0, -1, 0, -1, 0, -1}, {-1, -1, -1, 1, 1, 0, 0, -1, -1, -1, 0, 1}, {1, 1, 1, 0, 0, 2, 2, -1, -1, -1, 2, 0}, {0, -1, -1, 0, -1, -1, 0, -1, -1, -1, 0, 0}, {-1, 0, 0, 0, -1, -1, 0, -1, -1, -1, 0, 0}, {-1, 0, -1, -1, 0, 1, 1, -1, 0, -1, 1, 0}, {1, -1, 1, -1, 1, 0, 0, -1, 1, -1, 0, 1}, {0, 0, -1, -1, -1, -1, 0, -1, 0, -1, 0, 0}, {-1, -1, 0, -1, -1, -1, 0, -1, 0, -1, 0, 0}, {-1, -1, 0, -1, -1, 0, -1, 0, -1, -1, 0, -1}, {0, 0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1}, {0, -1, 0, -1, 0, -1, -1, 0, -1, -1, 0, -1}, {-1, 0, -1, -1, 0, -1, -1, 0, -1, -1, 0, -1}, {-1, 1, 0, 1, -1, 0, -1, 0, 1, -1, 0, -1}, {0, -1, -1, 0, -1, 0, -1, 0, 0, -1, 0, -1}, {1, 0, 1, 0, 1, -1, -1, 1, 0, -1, 1, -1}, {-1, -1, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1}, {-1, -1, 0, 1, 1, 0, -1, 0, -1, -1, 0, 1}, {1, 1, -1, 0, 0, 1, -1, 1, -1, -1, 1, 0}, {0, -1, 0, 0, -1, -1, -1, 0, -1, -1, 0, 0}, {-1, 0, -1, 0, -1, -1, -1, 0, -1, -1, 0, 0}, {-1, 1, 0, -1, 1, 0, -1, 0, 1, -1, 0, 1}, {1, -1, -1, -1, 1, 1, -1, 0, 0, -1, 0, 0}, {1, 1, 1, -1, -1, -1, -1, 0, 0, -1, 0, 0}, {-1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, 0}, {-1, -1, -1, -1, -1, -1, -1, 0, 0, 0, -1, -1}, {0, 0, 0, -1, -1, -1, -1, 1, 1, 1, -1, -1}, {1, -1, -1, -1, 1, 1, -1, 0, 0, 0, -1, -1}, {-1, 0, 0, -1, 0, 0, -1, 1, 1, 1, -1, -1}, {-1, 0, -1, 0, -1, -1, -1, 0, -1, 0, -1, -1}, {0, -1, 0, 0, -1, -1, -1, 0, -1, 0, -1, -1}, {1, 0, -1, 0, 1, 1, -1, 0, -1, 0, -1, -1}, {-1, -1, 0, 0, 0, 0, -1, 0, -1, 0, -1, -1}, {-1, -1, -1, 0, 0, -1, -1, 1, 1, 1, -1, 0}, {2, 2, 2, 0, 0, -1, -1, 1, 1, 1, -1, 0}, {0, -1, -1, 0, -1, 0, -1, 1, 1, 1, -1, 0}, {-1, 1, 1, 1, -1, 1, -1, 0, 0, 0, -1, 1}, {-1, 0, -1, -1, 0, -1, -1, 0, -1, 0, -1, 0}, {0, -1, 0, -1, 0, -1, -1, 0, -1, 0, -1, 0}, {0, 0, -1, -1, -1, 0, -1, 0, -1, 0, -1, 0}, {-1, -1, 0, -1, -1, 0, -1, 0, -1, 0, -1, 0}, {-1, -1, 0, -1, -1, -1, 0, -1, 0, 0, -1, -1}, {0, 0, -1, -1, -1, -1, 0, -1, 0, 0, -1, -1}, {1, -1, 0, -1, 1, 1, 0, -1, 0, 0, -1, -1}, {-1, 0, -1, -1, 0, 0, 0, -1, 0, 0, -1, -1}, {-1, 0, 0, 0, -1, -1, 0, -1, -1, 0, -1, -1}, {0, -1, -1, 0, -1, -1, 0, -1, -1, 0, -1, -1}, {0, 1, 1, 1, 0, 0, 1, -1, -1, 1, -1, -1}, {-1, -1, -1, 0, 0, 0, 0, -1, -1, 0, -1, -1}, {-1, -1, 0, 1, 1, -1, 0, -1, 0, 0, -1, 1}, {1, 1, -1, 0, 0, -1, 1, -1, 1, 1, -1, 0}, {1, -1, 0, 1, -1, 1, 0, -1, 0, 0, -1, 1}, {-1, 1, -1, 1, -1, 0, 0, -1, 1, 0, -1, 0}, {-1, 0, 0, -1, 0, -1, 0, -1, -1, 0, -1, 0}, {0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1, 0}, {1, 1, 1, -1, -1, 0, 0, -1, -1, 0, -1, 0}, {-1, -1, -1, -1, -1, 0, 0, -1, -1, 0, -1, 0}, {-1, -1, -1, -1, -1, 0, 0, 1, 1, 1, 0, -1}, {1, 1, 1, -1, -1, 0, 0, 2, 2, 2, 0, -1}, {0, -1, -1, -1, 0, -1, 0, 1, 1, 1, 0, -1}, {-1, 1, 1, -1, 1, -1, 1, 0, 0, 0, 1, -1}, {-1, 0, -1, 0, -1, 1, 1, 0, -1, 0, 1, -1}, {1, -1, 1, 1, -1, 0, 0, 1, -1, 1, 0, -1}, {0, 1, -1, 1, 0, -1, 0, 1, -1, 1, 0, -1}, {-1, -1, 1, 0, 0, -1, 1, 1, -1, 0, 0, -1}, {-1, -1, -1, 1, 1, 2, 2, 0, 0, 0, 2, 1}, {2, 2, 2, 3, 3, 0, 0, 1, 1, 1, 0, 3}, {1, -1, -1, 1, -1, -1, 1, 0, 0, 0, 1, 1}, {-1, 0, 0, 0, -1, -1, 0, 1, 1, 1, 0, 0}, {-1, 1, -1, -1, 1, 0, 0, 1, -1, 1, 0, 1}, {0, -1, 0, -1, 0, 1, 1, 0, -1, 0, 1, 0}, {0, 0, -1, -1, -1, -1, 0, 0, -1, 1, 1, 1}, {-1, -1, 0, -1, -1, -1, 0, 0, -1, 1, 1, 1}, {-1, -1, 0, -1, -1, 0, -1, -1, 0, 0, 0, -1}, {0, 0, -1, -1, -1, 0, -1, -1, 0, 0, 0, -1}, {0, -1, 0, -1, 0, -1, -1, -1, 0, 0, 0, -1}, {-1, 0, -1, -1, 0, -1, -1, -1, 0, 0, 0, -1}, {-1, 0, 0, 0, -1, 0, -1, -1, -1, 0, 0, -1}, {0, -1, -1, 0, -1, 0, -1, -1, -1, 0, 0, -1}, {1, 1, 1, 0, 0, -1, -1, -1, -1, 0, 0, -1}, {-1, -1, -1, 0, 0, -1, -1, -1, -1, 0, 0, -1}, {-1, -1, 1, 0, 0, 1, -1, -1, 1, 1, 1, 0}, {0, 0, -1, 1, 1, 0, -1, -1, 0, 0, 0, 1}, {0, -1, 0, 0, -1, -1, -1, -1, 0, 1, 1, 1}, {-1, 0, -1, 0, -1, -1, -1, -1, 0, 1, 1, 1}, {-1, 0, 0, -1, 0, 0, -1, -1, -1, 1, 1, 1}, {0, -1, -1, -1, 0, 0, -1, -1, -1, 1, 1, 1}, {1, 1, 1, -1, -1, -1, -1, -1, -1, 0, 0, 0}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0}, {1, 1, 1, -1, -1, -1, -1, -1, -1, 0, 0, 0}, {0, -1, -1, -1, 0, 0, -1, -1, -1, 1, 1, 1}, {-1, 0, 0, -1, 0, 0, -1, -1, -1, 1, 1, 1}, {-1, 0, -1, 0, -1, -1, -1, -1, 0, 1, 1, 1}, {0, -1, 0, 0, -1, -1, -1, -1, 0, 1, 1, 1}, {2, 1, -1, 1, 2, 2, -1, -1, 1, 0, 0, 0}, {-1, -1, 1, 1, 1, 1, -1, -1, 1, 0, 0, 0}, {-1, -1, -1, 0, 0, -1, -1, -1, -1, 0, 0, -1}, {1, 1, 1, 0, 0, -1, -1, -1, -1, 0, 0, -1}, {0, -1, -1, 0, -1, 0, -1, -1, -1, 0, 0, -1}, {-1, 0, 0, 0, -1, 0, -1, -1, -1, 0, 0, -1}, {-1, 0, -1, -1, 0, -1, -1, -1, 0, 0, 0, -1}, {0, -1, 0, -1, 0, -1, -1, -1, 0, 0, 0, -1}, {0, 0, -1, -1, -1, 0, -1, -1, 0, 0, 0, -1}, {-1, -1, 0, -1, -1, 0, -1, -1, 0, 0, 0, -1}, {-1, -1, 0, -1, -1, -1, 0, 0, -1, 1, 1, 1}, {0, 0, -1, -1, -1, -1, 0, 0, -1, 1, 1, 1}, {1, -1, 2, -1, 1, 1, 2, 2, -1, 0, 0, 0}, {-1, 1, -1, -1, 1, 1, 1, 1, -1, 0, 0, 0}, {-1, 1, 0, 1, -1, -1, 0, 0, 1, 2, 2, 2}, {1, -1, -1, 1, -1, -1, 1, 1, 1, 0, 0, 0}, {3, 2, 0, 2, 3, 3, 0, 0, 2, 1, 1, 1}, {-1, -1, -1, 0, 0, 0, 0, 0, 0, 1, 1, 1}, {-1, -1, 1, 0, 0, -1, 1, 1, -1, 0, 0, -1}, {1, 1, -1, 0, 0, -1, 1, 1, -1, 0, 0, -1}, {1, -1, 0, 1, -1, 1, 0, 0, -1, 1, 1, -1}, {-1, 0, -1, 0, -1, 1, 1, 0, -1, 0, 1, -1}, {-1, 1, 0, -1, 1, -1, 0, 0, 1, 1, 1, -1}, {0, -1, -1, -1, 0, -1, 0, 1, 1, 1, 0, -1}, {0, 0, 1, -1, -1, 0, 1, 1, 0, 0, 0, -1}, {-1, -1, -1, -1, -1, 0, 0, 1, 1, 1, 0, -1}, {-1, -1, -1, -1, -1, 0, 0, -1, -1, 0, -1, 0}, {1, 1, 1, -1, -1, 0, 0, -1, -1, 0, -1, 0}, {0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1, 0}, {-1, 0, 0, -1, 0, -1, 0, -1, -1, 0, -1, 0}, {-1, 1, -1, 1, -1, 0, 0, -1, 1, 0, -1, 0}, {1, -1, 1, 1, -1, 0, 0, -1, 1, 0, -1, 0}, {1, 0, -1, 0, 1, -1, 1, -1, 0, 1, -1, 1}, {-1, -1, 0, 1, 1, -1, 0, -1, 0, 0, -1, 1}, {-1, -1, -1, 0, 0, 0, 0, -1, -1, 0, -1, -1}, {0, 0, 0, 1, 1, 1, 1, -1, -1, 1, -1, -1}, {0, -1, -1, 0, -1, -1, 0, -1, -1, 0, -1, -1}, {-1, 0, 0, 0, -1, -1, 0, -1, -1, 0, -1, -1}, {-1, 0, -1, -1, 0, 0, 0, -1, 0, 0, -1, -1}, {1, -1, 0, -1, 1, 1, 0, -1, 0, 0, -1, -1}, {0, 0, -1, -1, -1, -1, 0, -1, 0, 0, -1, -1}, {-1, -1, 0, -1, -1, -1, 0, -1, 0, 0, -1, -1}, {-1, -1, 0, -1, -1, 0, -1, 0, -1, 0, -1, 0}, {0, 0, -1, -1, -1, 0, -1, 0, -1, 0, -1, 0}, {0, -1, 0, -1, 0, -1, -1, 0, -1, 0, -1, 0}, {-1, 0, -1, -1, 0, -1, -1, 0, -1, 0, -1, 0}, {-1, 0, 1, 0, -1, 1, -1, 1, 0, 1, -1, 1}, {0, -1, -1, 0, -1, 0, -1, 1, 1, 1, -1, 0}, {0, 1, 0, 1, 0, -1, -1, 0, 1, 0, -1, 0}, {-1, -1, -1, 0, 0, -1, -1, 1, 1, 1, -1, 0}, {-1, -1, 0, 0, 0, 0, -1, 0, -1, 0, -1, -1}, {1, 0, -1, 0, 1, 1, -1, 0, -1, 0, -1, -1}, {0, -1, 0, 0, -1, -1, -1, 0, -1, 0, -1, -1}, {-1, 0, -1, 0, -1, -1, -1, 0, -1, 0, -1, -1}, {-1, 0, 0, -1, 0, 0, -1, 1, 1, 1, -1, -1}, {1, -1, -1, -1, 1, 1, -1, 0, 0, 0, -1, -1}, {0, 0, 0, -1, -1, -1, -1, 1, 1, 1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, 0, 0, 0, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, 0}, {1, 1, 1, -1, -1, -1, -1, 0, 0, -1, 0, 0}, {1, -1, -1, -1, 1, 1, -1, 0, 0, -1, 0, 0}, {-1, 1, 1, -1, 1, 1, -1, 0, 0, -1, 0, 0}, {-1, 0, -1, 0, -1, -1, -1, 0, -1, -1, 0, 0}, {0, -1, 0, 0, -1, -1, -1, 0, -1, -1, 0, 0}, {0, 1, -1, 1, 0, 0, -1, 1, -1, -1, 1, 1}, {-1, -1, 0, 1, 1, 0, -1, 0, -1, -1, 0, 1}, {-1, -1, -1, 0, 0, -1, -1, 0, 0, -1, 0, -1}, {0, 0, 0, 1, 1, -1, -1, 1, 1, -1, 1, -1}, {0, -1, -1, 0, -1, 0, -1, 0, 0, -1, 0, -1}, {-1, 1, 0, 1, -1, 0, -1, 0, 1, -1, 0, -1}, {-1, 0, -1, -1, 0, -1, -1, 0, -1, -1, 0, -1}, {0, -1, 0, -1, 0, -1, -1, 0, -1, -1, 0, -1}, {0, 0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1}, {-1, -1, 0, -1, -1, 0, -1, 0, -1, -1, 0, -1}, {-1, -1, 0, -1, -1, -1, 0, -1, 0, -1, 0, 0}, {0, 0, -1, -1, -1, -1, 0, -1, 0, -1, 0, 0}, {0, -1, 1, -1, 0, 0, 1, -1, 1, -1, 1, 1}, {-1, 0, -1, -1, 0, 1, 1, -1, 0, -1, 1, 0}, {-1, 0, 0, 0, -1, -1, 0, -1, -1, -1, 0, 0}, {0, -1, -1, 0, -1, -1, 0, -1, -1, -1, 0, 0}, {1, 0, 0, 0, 1, 1, 0, -1, -1, -1, 0, 0}, {-1, -1, -1, 1, 1, 0, 0, -1, -1, -1, 0, 1}, {-1, -1, 0, 0, 0, -1, 0, -1, 0, -1, 0, -1}, {0, 1, -1, 1, 0, -1, 0, -1, 1, -1, 0, -1}, {0, -1, 0, 0, -1, 1, 1, -1, 0, -1, 1, -1}, {-1, 1, -1, 1, -1, 0, 0, -1, 1, -1, 0, -1}, {-1, 0, 0, -1, 0, -1, 0, -1, -1, -1, 0, -1}, {0, -1, -1, -1, 0, -1, 0, -1, -1, -1, 0, -1}, {0, 0, 0, -1, -1, 1, 1, -1, -1, -1, 1, -1}, {-1, -1, -1, -1, -1, 0, 0, -1, -1, -1, 0, -1}, {-1, -1, -1, -1, -1, 0, 0, 0, 0, -1, -1, 0}, {0, 0, 0, -1, -1, 1, 1, 1, 1, -1, -1, 1}, {0, -1, -1, -1, 0, -1, 0, 0, 0, -1, -1, 0}, {-1, 0, 1, -1, 0, -1, 1, 1, 0, -1, -1, 0}, {-1, 0, -1, 0, -1, 0, 0, 0, -1, -1, -1, 0}, {0, -1, 1, 0, -1, 0, 1, 1, -1, -1, -1, 0}, {0, 0, -1, 1, 1, -1, 0, 0, -1, -1, -1, 1}, {-1, -1, 0, 1, 1, -1, 0, 0, -1, -1, -1, 1}, {-1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, -1}, {1, 1, 1, 0, 0, 0, 0, 0, 0, -1, -1, -1}, {0, -1, -1, 0, -1, -1, 0, 0, 0, -1, -1, -1}, {-1, 1, 0, 1, -1, -1, 0, 0, 1, -1, -1, -1}, {-1, 0, -1, -1, 0, 0, 0, 0, -1, -1, -1, -1}, {0, -1, 1, -1, 0, 0, 1, 1, -1, -1, -1, -1}, {0, 0, -1, -1, -1, -1, 0, 0, -1, -1, -1, -1}, {-1, -1, 0, -1, -1, -1, 0, 0, -1, -1, -1, -1}, {-1, -1, 0, -1, -1, 0, -1, -1, 0, -1, -1, 0}, {0, 0, -1, -1, -1, 0, -1, -1, 0, -1, -1, 0}, {0, -1, 0, -1, 0, -1, -1, -1, 0, -1, -1, 0}, {-1, 0, -1, -1, 0, -1, -1, -1, 0, -1, -1, 0}, {-1, 0, 0, 0, -1, 0, -1, -1, -1, -1, -1, 0}, {0, -1, -1, 0, -1, 0, -1, -1, -1, -1, -1, 0}, {0, 0, 0, 1, 1, -1, -1, -1, -1, -1, -1, 1}, {-1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1, 0}, {-1, -1, 0, 0, 0, 0, -1, -1, 0, -1, -1, -1}, {0, 1, -1, 1, 0, 0, -1, -1, 1, -1, -1, -1}, {0, -1, 0, 0, -1, -1, -1, -1, 0, -1, -1, -1}, {-1, 0, -1, 0, -1, -1, -1, -1, 0, -1, -1, -1}, {-1, 0, 0, -1, 0, 0, -1, -1, -1, -1, -1, -1}, {0, -1, -1, -1, 0, 0, -1, -1, -1, -1, -1, -1}, {0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}; static unsigned char edgeIndicesByFace[6][4] = {{0, 2, 5, 6}, {3, 8, 9, 11}, {1, 2, 7, 8}, {4, 5, 10, 11}, {0, 1, 3, 4}, {6, 7, 9, 10}}; unsigned char numVertices (unsigned char configuration) { char n = -1; for (unsigned char i = 0; i < 12; i++) { n = std::max (n, vertexIndicesByConfiguration[configuration][i]); } return (unsigned char) (n + 1); } bool isIntersecting (float s1, float s2) { return (s1 < 0.0f && s2 >= 0.0f) || (s1 >= 0.0f && s2 < 0.0f); } struct Cube { unsigned char configuration; glm::vec3 vertex; unsigned char numVertexIndicesInMesh; std::array vertexIndicesInMesh; bool nonManifold; Cube () : configuration (0) , vertex (invalidVec3) , numVertexIndicesInMesh (0) , nonManifold (false) { } bool nonManifoldConfig () const { return ::nonManifoldConfig[this->configuration]; } bool collapseNonManifoldConfig () const { return this->nonManifoldConfig () && this->nonManifold == false; } unsigned int vertexIndex (unsigned char edge) const { assert (edge < 12); assert (vertexIndicesByConfiguration[this->configuration][edge] >= 0); assert (this->nonManifold == false || this->nonManifoldConfig ()); const unsigned char i = this->collapseNonManifoldConfig () ? 0 : vertexIndicesByConfiguration[this->configuration][edge]; assert (i < this->vertexIndicesInMesh.size ()); assert (i < this->numVertexIndicesInMesh); return this->vertexIndicesInMesh[i]; } unsigned char getAmbiguousFaceOfNonManifoldConfig () const { assert (this->nonManifoldConfig ()); for (unsigned int i = 0; i < 6; i++) { const unsigned char edge1 = edgeIndicesByFace[i][0]; const unsigned char edge2 = edgeIndicesByFace[i][1]; const unsigned char edge3 = edgeIndicesByFace[i][2]; const unsigned char edge4 = edgeIndicesByFace[i][3]; const char vertex1 = vertexIndicesByConfiguration[this->configuration][edge1]; const char vertex2 = vertexIndicesByConfiguration[this->configuration][edge2]; const char vertex3 = vertexIndicesByConfiguration[this->configuration][edge3]; const char vertex4 = vertexIndicesByConfiguration[this->configuration][edge4]; if (vertex1 != -1 && vertex2 != -1 && vertex3 != -1 && vertex4 != -1) { return (unsigned char) i; } } DILAY_IMPOSSIBLE } }; } const unsigned char IsosurfaceExtractionGrid::vertexIndicesByEdge[12][2] = { {0, 1}, {0, 2}, {0, 4}, {2, 3}, {1, 3}, {1, 5}, {4, 5}, {4, 6}, {2, 6}, {6, 7}, {5, 7}, {3, 7}}; struct IsosurfaceExtractionGrid::Impl { float resolution; glm::vec3 sampleMin; glm::vec3 sampleMax; glm::uvec3 numSamples; std::vector samples; glm::uvec3 numCubes; std::vector cubes; Impl (const PrimAABox& bounds, float r) : resolution (r) { const glm::vec3 min = bounds.minimum () - glm::vec3 (Util::epsilon () + r); const glm::vec3 max = bounds.maximum () + glm::vec3 (Util::epsilon () + r); this->sampleMin = min; this->numSamples = glm::vec3 (1.0f) + glm::ceil ((max - min) / glm::vec3 (r)); this->numCubes = this->numSamples - glm::uvec3 (1); const unsigned int totalNumSamples = this->numSamples.x * this->numSamples.y * this->numSamples.z; const unsigned int totalNumCubes = this->numCubes.x * this->numCubes.y * this->numCubes.z; this->samples.resize (totalNumSamples, Util::maxFloat ()); this->cubes.resize (totalNumCubes); } glm::vec3 samplePos (unsigned int x, unsigned int y, unsigned int z) const { assert (x < (unsigned int) this->numSamples.x); assert (y < (unsigned int) this->numSamples.y); assert (z < (unsigned int) this->numSamples.z); return this->sampleMin + (glm::vec3 (this->resolution) * glm::vec3 (float(x), float(y), float(z))); } glm::vec3 samplePos (unsigned int i) const { const std::div_t divZ = std::div (int(i), int(this->numSamples.x * this->numSamples.y)); const std::div_t divY = std::div (divZ.rem, int(this->numSamples.x)); const unsigned int x = (unsigned int) (divY.rem); const unsigned int y = (unsigned int) (divY.quot); const unsigned int z = (unsigned int) (divZ.quot); assert (this->sampleIndex (x, y, z) == i); return this->samplePos (x, y, z); } unsigned int sampleIndex (unsigned int x, unsigned int y, unsigned int z) const { return (z * this->numSamples.x * this->numSamples.y) + (y * this->numSamples.x) + x; } unsigned int sampleIndex (unsigned int cubeIndex, unsigned char vertex) const { assert (vertex < 8); const std::div_t divZ = std::div (int(cubeIndex), int(this->numCubes.x * this->numCubes.y)); const std::div_t divY = std::div (divZ.rem, int(this->numCubes.x)); const unsigned int x = (unsigned int) (divY.rem); const unsigned int y = (unsigned int) (divY.quot); const unsigned int z = (unsigned int) (divZ.quot); assert (this->cubeIndex (x, y, z) == cubeIndex); switch (vertex) { case 0: return this->sampleIndex (x, y, z); case 1: return this->sampleIndex (x + 1, y, z); case 2: return this->sampleIndex (x, y + 1, z); case 3: return this->sampleIndex (x + 1, y + 1, z); case 4: return this->sampleIndex (x, y, z + 1); case 5: return this->sampleIndex (x + 1, y, z + 1); case 6: return this->sampleIndex (x, y + 1, z + 1); case 7: return this->sampleIndex (x + 1, y + 1, z + 1); default: DILAY_IMPOSSIBLE } } unsigned int cubeIndex (unsigned int x, unsigned int y, unsigned int z) const { return (z * this->numCubes.x * this->numCubes.y) + (y * this->numCubes.x) + x; } unsigned int cubeVertexIndex (unsigned int cubeIndex, unsigned char edge) const { return this->cubes[cubeIndex].vertexIndex (edge); } void setCubeVertex (unsigned int cubeIndex) { glm::vec3 vertex = glm::vec3 (0.0f); unsigned int numCrossedEdges = 0; Cube& cube = this->cubes[cubeIndex]; const unsigned int indices[] = { this->sampleIndex (cubeIndex, 0), this->sampleIndex (cubeIndex, 1), this->sampleIndex (cubeIndex, 2), this->sampleIndex (cubeIndex, 3), this->sampleIndex (cubeIndex, 4), this->sampleIndex (cubeIndex, 5), this->sampleIndex (cubeIndex, 6), this->sampleIndex (cubeIndex, 7)}; const float samples[] = {this->samples[indices[0]], this->samples[indices[1]], this->samples[indices[2]], this->samples[indices[3]], this->samples[indices[4]], this->samples[indices[5]], this->samples[indices[6]], this->samples[indices[7]]}; const glm::vec3 positions[] = {this->samplePos (indices[0]), this->samplePos (indices[1]), this->samplePos (indices[2]), this->samplePos (indices[3]), this->samplePos (indices[4]), this->samplePos (indices[5]), this->samplePos (indices[6]), this->samplePos (indices[7])}; cube.configuration = 0; for (unsigned char edge = 0; edge < 12; edge++) { const unsigned char vertex1 = vertexIndicesByEdge[edge][0]; const unsigned char vertex2 = vertexIndicesByEdge[edge][1]; cube.configuration |= ((samples[vertex1] < 0.0f) << vertex1); cube.configuration |= ((samples[vertex2] < 0.0f) << vertex2); if (isIntersecting (samples[vertex1], samples[vertex2])) { const float factor = samples[vertex1] / (samples[vertex1] - samples[vertex2]); const glm::vec3 delta = positions[vertex2] - positions[vertex1]; vertex += positions[vertex1] + (delta * factor); numCrossedEdges++; } } #ifndef NDEBUG for (unsigned char edge = 0; edge < 12; edge++) { const unsigned char vertex1 = vertexIndicesByEdge[edge][0]; const unsigned char vertex2 = vertexIndicesByEdge[edge][1]; if (samples[vertex1] < 0.0f) { assert ((cube.configuration & (1 << vertex1)) != 0); } else { assert ((cube.configuration & (1 << vertex1)) == 0); } if (samples[vertex2] < 0.0f) { assert ((cube.configuration & (1 << vertex2)) != 0); } else { assert ((cube.configuration & (1 << vertex2)) == 0); } if (isIntersecting (samples[vertex1], samples[vertex2])) { assert (vertexIndicesByConfiguration[cube.configuration][edge] != -1); } } #endif if (numCrossedEdges > 0) { cube.vertex = vertex / float(numCrossedEdges); } else { assert (numVertices (cube.configuration) == 0); } } void setCubeVertices () { for (unsigned int z = 0; z < this->numCubes.z; z++) { for (unsigned int y = 0; y < this->numCubes.y; y++) { for (unsigned int x = 0; x < this->numCubes.x; x++) { this->setCubeVertex (this->cubeIndex (x, y, z)); } } } #ifndef NDEBUG for (unsigned int z = 0; z < this->numCubes.z; z++) { for (unsigned int y = 0; y < this->numCubes.y; y++) { for (unsigned int x = 0; x < this->numCubes.x; x++) { unsigned char config = this->cubes[this->cubeIndex (x, y, z)].configuration; if (x > 0) { unsigned char left = this->cubes[this->cubeIndex (x - 1, y, z)].configuration; assert (((config & (1 << 0)) == 0) == ((left & (1 << 1)) == 0)); assert (((config & (1 << 2)) == 0) == ((left & (1 << 3)) == 0)); assert (((config & (1 << 4)) == 0) == ((left & (1 << 5)) == 0)); assert (((config & (1 << 6)) == 0) == ((left & (1 << 7)) == 0)); } if (y > 0) { unsigned char below = this->cubes[this->cubeIndex (x, y - 1, z)].configuration; assert (((config & (1 << 0)) == 0) == ((below & (1 << 2)) == 0)); assert (((config & (1 << 1)) == 0) == ((below & (1 << 3)) == 0)); assert (((config & (1 << 4)) == 0) == ((below & (1 << 6)) == 0)); assert (((config & (1 << 5)) == 0) == ((below & (1 << 7)) == 0)); } if (z > 0) { unsigned char behind = this->cubes[this->cubeIndex (x, y, z - 1)].configuration; assert (((config & (1 << 0)) == 0) == ((behind & (1 << 4)) == 0)); assert (((config & (1 << 1)) == 0) == ((behind & (1 << 5)) == 0)); assert (((config & (1 << 2)) == 0) == ((behind & (1 << 6)) == 0)); assert (((config & (1 << 3)) == 0) == ((behind & (1 << 7)) == 0)); } } } } #endif } bool hasAmbiguousNeighbor (const Cube& cube, unsigned int x, unsigned int y, unsigned int z, unsigned char ambiguousFace, char dim) { assert (cube.nonManifoldConfig ()); assert (dim == -3 || dim == -2 || dim == -1 || dim == 1 || dim == 2 || dim == 3); unused (cube); Cube& other = this->cubes[this->cubeIndex (dim == -1 ? x - 1 : (dim == 1 ? x + 1 : x), dim == -2 ? y - 1 : (dim == 2 ? y + 1 : y), dim == -3 ? z - 1 : (dim == 3 ? z + 1 : z))]; if (other.nonManifoldConfig ()) { const unsigned char otherAmbiguousFace = other.getAmbiguousFaceOfNonManifoldConfig (); const bool nx = dim == -1 && ambiguousFace == 2 && otherAmbiguousFace == 3; const bool px = dim == 1 && ambiguousFace == 3 && otherAmbiguousFace == 2; const bool ny = dim == -2 && ambiguousFace == 0 && otherAmbiguousFace == 1; const bool py = dim == 2 && ambiguousFace == 1 && otherAmbiguousFace == 0; const bool nz = dim == -3 && ambiguousFace == 4 && otherAmbiguousFace == 5; const bool pz = dim == 3 && ambiguousFace == 5 && otherAmbiguousFace == 4; return nx || px || ny || py || nz || pz; } else { return false; } } void resolveNonManifold (unsigned int x, unsigned int y, unsigned int z) { Cube& cube = this->cubes[this->cubeIndex (x, y, z)]; if (cube.nonManifoldConfig ()) { const unsigned char ambiguousFace = cube.getAmbiguousFaceOfNonManifoldConfig (); const bool nx = x > 0 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, -1); const bool px = x < this->numCubes.x - 1 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, 1); const bool ny = y > 0 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, -2); const bool py = y < this->numCubes.y - 1 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, 2); const bool nz = z > 0 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, -3); const bool pz = z < this->numCubes.z - 1 && this->hasAmbiguousNeighbor (cube, x, y, z, ambiguousFace, 3); cube.nonManifold = nx || px || ny || py || nz || pz; } else { cube.nonManifold = false; } } void resolveNonManifolds () { for (unsigned int z = 0; z < this->numCubes.z; z++) { for (unsigned int y = 0; y < this->numCubes.y; y++) { for (unsigned int x = 0; x < this->numCubes.x; x++) { this->resolveNonManifold (x, y, z); } } } } void addCubeVerticesToMesh (Cube& cube, DynamicMesh& mesh) { cube.numVertexIndicesInMesh = cube.collapseNonManifoldConfig () ? 1 : numVertices (cube.configuration); for (unsigned char i = 0; i < cube.numVertexIndicesInMesh; i++) { cube.vertexIndicesInMesh[i] = mesh.addVertex (cube.vertex, glm::vec3 (0.0f)); } #ifndef NDEBUG for (unsigned char i = cube.numVertexIndicesInMesh; i < cube.vertexIndicesInMesh.size (); i++) { cube.vertexIndicesInMesh[i] = Util::invalidIndex (); } #endif } void addQuadToMesh (DynamicMesh& mesh, unsigned int i, unsigned int iu, unsigned int iv, unsigned int iuv) { if (glm::distance2 (mesh.vertex (i), mesh.vertex (iuv)) <= glm::distance2 (mesh.vertex (iu), mesh.vertex (iv))) { mesh.addFace (i, iu, iuv); mesh.addFace (i, iuv, iv); } else { mesh.addFace (iu, iuv, iv); mesh.addFace (iu, iv, i); } } void makeFaces (DynamicMesh& mesh, unsigned char edge, unsigned int x, unsigned int y, unsigned int z) { assert (edge == 0 || edge == 1 || edge == 2); const float s1 = this->samples[this->sampleIndex (x, y, z)]; const float s2 = this->samples[this->sampleIndex (edge == 0 ? x + 1 : x, edge == 1 ? y + 1 : y, edge == 2 ? z + 1 : z)]; if (isIntersecting (s1, s2)) { unsigned int i, iu, iv, iuv; if (edge == 0) { i = this->cubeVertexIndex (this->cubeIndex (x, y, z), 0); iu = this->cubeVertexIndex (this->cubeIndex (x, y - 1, z), 3); iuv = this->cubeVertexIndex (this->cubeIndex (x, y - 1, z - 1), 9); iv = this->cubeVertexIndex (this->cubeIndex (x, y, z - 1), 6); } else if (edge == 1) { i = this->cubeVertexIndex (this->cubeIndex (x, y, z), 1); iu = this->cubeVertexIndex (this->cubeIndex (x, y, z - 1), 7); iuv = this->cubeVertexIndex (this->cubeIndex (x - 1, y, z - 1), 10); iv = this->cubeVertexIndex (this->cubeIndex (x - 1, y, z), 4); } else if (edge == 2) { i = this->cubeVertexIndex (this->cubeIndex (x, y, z), 2); iu = this->cubeVertexIndex (this->cubeIndex (x - 1, y, z), 5); iuv = this->cubeVertexIndex (this->cubeIndex (x - 1, y - 1, z), 11); iv = this->cubeVertexIndex (this->cubeIndex (x, y - 1, z), 8); } else { DILAY_IMPOSSIBLE } if (s1 >= 0.0f) { std::swap (iu, iv); } this->addQuadToMesh (mesh, i, iu, iv, iuv); } } void makeFaces (DynamicMesh& mesh, unsigned int x, unsigned int y, unsigned int z) { if (y > 0 && z > 0) { this->makeFaces (mesh, 0, x, y, z); } if (x > 0 && z > 0) { this->makeFaces (mesh, 1, x, y, z); } if (x > 0 && y > 0) { this->makeFaces (mesh, 2, x, y, z); } } void makeMesh (DynamicMesh& mesh) { this->setCubeVertices (); this->resolveNonManifolds (); mesh.reset (); for (Cube& cube : this->cubes) { this->addCubeVerticesToMesh (cube, mesh); } for (unsigned int z = 0; z < this->numCubes.z; z++) { for (unsigned int y = 0; y < this->numCubes.y; y++) { for (unsigned int x = 0; x < this->numCubes.x; x++) { this->makeFaces (mesh, x, y, z); } } } mesh.setAllNormals (); #ifndef NDEBUG std::vector vertexIndexMap, faceIndexMap; assert (mesh.numFaces () == 0 || mesh.pruneAndCheckConsistency (&vertexIndexMap, nullptr)); for (Cube& c : this->cubes) { if (vertexIndexMap.empty () == false) { for (unsigned char i = 0; i < c.numVertexIndicesInMesh; i++) { c.vertexIndicesInMesh[i] = vertexIndexMap[c.vertexIndicesInMesh[i]]; assert (c.vertexIndicesInMesh[i] != Util::invalidIndex ()); } } } #endif mesh.bufferData (); } }; DELEGATE2_BIG4_COPY (IsosurfaceExtractionGrid, const PrimAABox&, float) GETTER_CONST (float, IsosurfaceExtractionGrid, resolution) GETTER_CONST (const glm::uvec3&, IsosurfaceExtractionGrid, numSamples) GETTER_CONST (const glm::uvec3&, IsosurfaceExtractionGrid, numCubes) GETTER (std::vector&, IsosurfaceExtractionGrid, samples) DELEGATE3_CONST (glm::vec3, IsosurfaceExtractionGrid, samplePos, unsigned int, unsigned int, unsigned int) DELEGATE1_CONST (glm::vec3, IsosurfaceExtractionGrid, samplePos, unsigned int) DELEGATE3_CONST (unsigned int, IsosurfaceExtractionGrid, sampleIndex, unsigned int, unsigned int, unsigned int) DELEGATE2_CONST (unsigned int, IsosurfaceExtractionGrid, sampleIndex, unsigned int, unsigned char) DELEGATE3_CONST (unsigned int, IsosurfaceExtractionGrid, cubeIndex, unsigned int, unsigned int, unsigned int) DELEGATE1 (void, IsosurfaceExtractionGrid, makeMesh, DynamicMesh&) ================================================ FILE: lib/src/isosurface-extraction/grid.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_ISOSURFACE_EXTRACTION_GRID #define DILAY_ISOSURFACE_EXTRACTION_GRID #include #include #include "macro.hpp" class DynamicMesh; class PrimAABox; class IsosurfaceExtractionGrid { public: static const unsigned char vertexIndicesByEdge[12][2]; DECLARE_BIG4_EXPLICIT_COPY (IsosurfaceExtractionGrid, const PrimAABox&, float) float resolution () const; const glm::uvec3& numSamples () const; const glm::uvec3& numCubes () const; std::vector& samples (); glm::vec3 samplePos (unsigned int, unsigned int, unsigned int) const; glm::vec3 samplePos (unsigned int) const; unsigned int sampleIndex (unsigned int, unsigned int, unsigned int) const; unsigned int sampleIndex (unsigned int, unsigned char) const; unsigned int cubeIndex (unsigned int, unsigned int, unsigned int) const; void makeMesh (DynamicMesh&); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/isosurface-extraction.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include "distance.hpp" #include "dynamic/mesh.hpp" #include "intersection.hpp" #include "isosurface-extraction.hpp" #include "isosurface-extraction/grid.hpp" #include "mesh.hpp" #include "primitive/ray.hpp" #include "util.hpp" namespace { typedef IsosurfaceExtraction::DistanceCallback DistanceCallback; typedef IsosurfaceExtraction::IntersectionCallback IntersectionCallback; static const float markInside = -0.5f; static const float markOutside = 0.5f; static const float markInsideToSample = -0.6f; static const float markOutsideToSample = 0.6f; struct Parameters { const DistanceCallback& getDistance; const IntersectionCallback* getIntersection; IsosurfaceExtractionGrid grid; Parameters (const DistanceCallback& d, const IntersectionCallback* i, const PrimAABox& b, float r) : getDistance (d) , getIntersection (i) , grid (b, r) { } }; void sampleDistancesThread (Parameters& params, unsigned int numThreads, unsigned int threadId) { std::vector& samples = params.grid.samples (); for (unsigned int z = 0; z < params.grid.numSamples ().z; z++) { for (unsigned int y = 0; y < params.grid.numSamples ().y; y++) { for (unsigned int x = 0; x < params.grid.numSamples ().x; x++) { const unsigned int index = params.grid.sampleIndex (x, y, z); if (index % numThreads == threadId) { const glm::vec3 pos = params.grid.samplePos (x, y, z); if (params.getIntersection) { if (samples[index] == markInsideToSample) { samples[index] = -params.getDistance (pos); } else if (samples[index] == markOutsideToSample) { samples[index] = params.getDistance (pos); } else { continue; } } else { assert (samples[index] == Util::maxFloat ()); samples[index] = params.getDistance (pos); } assert (Util::isNaN (samples[index]) == false); assert (samples[index] != Util::maxFloat ()); assert ((x > 0 && x < params.grid.numSamples ().x - 1) || samples[index] > 0.0f); assert ((y > 0 && y < params.grid.numSamples ().y - 1) || samples[index] > 0.0f); assert ((z > 0 && z < params.grid.numSamples ().z - 1) || samples[index] > 0.0f); } } } } } void sampleDistances (Parameters& params) { const unsigned int numThreads = std::thread::hardware_concurrency (); std::vector threads; for (unsigned int i = 0; i < numThreads; i++) { threads.emplace_back (sampleDistancesThread, std::ref (params), numThreads, i); } for (unsigned int i = 0; i < numThreads; i++) { threads.at (i).join (); } } void sampleIntersectionsThread (Parameters& params, unsigned int numThreads, unsigned int threadId) { assert (params.getIntersection); std::vector& samples = params.grid.samples (); for (unsigned int y = 0; y < params.grid.numSamples ().y; y++) { for (unsigned int x = 0; x < params.grid.numSamples ().x; x++) { if (params.grid.sampleIndex (x, y, 0) % numThreads == threadId) { const glm::vec3 dir (0.0f, 0.0f, 1.0f); bool inside = false; unsigned int z = 0; Intersection intersection; PrimRay ray (params.grid.samplePos (x, y, 0.0f) - (dir * Util::epsilon ()), dir); while (true) { intersection.reset (); IsosurfaceExtraction::Intersection i = (*params.getIntersection) (ray, intersection); if (i == IsosurfaceExtraction::Intersection::None) { break; } else { const float d2 = intersection.distance () * intersection.distance (); while (glm::distance2 (params.grid.samplePos (x, y, z), ray.origin ()) < d2) { const unsigned int index = params.grid.sampleIndex (x, y, z); assert (samples[index] == Util::maxFloat ()); samples[index] = inside ? markInside : markOutside; z++; } ray.origin (intersection.position () + (dir * Util::epsilon ())); if (i == IsosurfaceExtraction::Intersection::Sample) { inside = not inside; } } } assert (z < params.grid.numSamples ().z - 1); for (; z < params.grid.numSamples ().z; z++) { const unsigned int index = params.grid.sampleIndex (x, y, z); assert (samples[index] == Util::maxFloat ()); samples[index] = markOutside; } } } } } void sampleIntersections (Parameters& params) { const unsigned int numThreads = std::thread::hardware_concurrency (); std::vector threads; for (unsigned int i = 0; i < numThreads; i++) { threads.emplace_back (sampleIntersectionsThread, std::ref (params), numThreads, i); } for (unsigned int i = 0; i < numThreads; i++) { threads.at (i).join (); } } bool isIntersecting (float s1, float s2) { return (s1 < 0.0f && s2 >= 0.0f) || (s1 >= 0.0f && s2 < 0.0f); } void markSamplePositions (Parameters& params) { std::vector& samples = params.grid.samples (); for (unsigned int z = 0; z < params.grid.numCubes ().z; z++) { for (unsigned int y = 0; y < params.grid.numCubes ().y; y++) { for (unsigned int x = 0; x < params.grid.numCubes ().x; x++) { const unsigned int cubeIndex = params.grid.cubeIndex (x, y, z); const unsigned int cubeSampleIndices[] = { params.grid.sampleIndex (cubeIndex, 0), params.grid.sampleIndex (cubeIndex, 1), params.grid.sampleIndex (cubeIndex, 2), params.grid.sampleIndex (cubeIndex, 3), params.grid.sampleIndex (cubeIndex, 4), params.grid.sampleIndex (cubeIndex, 5), params.grid.sampleIndex (cubeIndex, 6), params.grid.sampleIndex (cubeIndex, 7)}; const float cubeSamples[] = { samples[cubeSampleIndices[0]], samples[cubeSampleIndices[1]], samples[cubeSampleIndices[2]], samples[cubeSampleIndices[3]], samples[cubeSampleIndices[4]], samples[cubeSampleIndices[5]], samples[cubeSampleIndices[6]], samples[cubeSampleIndices[7]]}; for (unsigned int edge = 0; edge < 12; edge++) { const unsigned char vertex1 = IsosurfaceExtractionGrid::vertexIndicesByEdge[edge][0]; const unsigned char vertex2 = IsosurfaceExtractionGrid::vertexIndicesByEdge[edge][1]; if (isIntersecting (cubeSamples[vertex1], cubeSamples[vertex2])) { for (unsigned int i = 0; i < 8; i++) { if (cubeSamples[i] == markInside) { samples[cubeSampleIndices[i]] = markInsideToSample; } else if (cubeSamples[i] == markOutside) { samples[cubeSampleIndices[i]] = markOutsideToSample; } } break; } } } } } } } void IsosurfaceExtraction::extract (const DistanceCallback& getDistance, const PrimAABox& bounds, float resolution, DynamicMesh& mesh) { Parameters params (getDistance, nullptr, bounds, resolution); IsosurfaceExtractionGrid& grid = params.grid; if (grid.numSamples ().x > 0 && grid.numSamples ().y > 0 && grid.numSamples ().z > 0) { sampleDistances (params); grid.makeMesh (mesh); } } void IsosurfaceExtraction::extract (const DistanceCallback& getDistance, const IntersectionCallback& getIntersection, const PrimAABox& bounds, float resolution, DynamicMesh& mesh) { Parameters params (getDistance, &getIntersection, bounds, resolution); IsosurfaceExtractionGrid& grid = params.grid; if (grid.numSamples ().x > 0 && grid.numSamples ().y > 0 && grid.numSamples ().z > 0) { sampleIntersections (params); markSamplePositions (params); sampleDistances (params); grid.makeMesh (mesh); } } ================================================ FILE: lib/src/isosurface-extraction.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_ISOSURFACE_EXTRACTION #define DILAY_ISOSURFACE_EXTRACTION #include #include class DynamicMesh; class Intersection; class PrimAABox; class PrimRay; namespace IsosurfaceExtraction { enum class Intersection { None, Sample, Continue }; typedef std::function DistanceCallback; typedef std::function IntersectionCallback; void extract (const DistanceCallback&, const IntersectionCallback&, const PrimAABox&, float, DynamicMesh&); void extract (const DistanceCallback&, const PrimAABox&, float, DynamicMesh&); }; #endif ================================================ FILE: lib/src/kvstore.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include "color.hpp" #include "kvstore.hpp" #include "util.hpp" #include "variant.hpp" #include "xml-conversion.hpp" struct KVStore::Impl { typedef Variant Value; typedef std::unordered_map Map; const std::string root; Map map; Impl (const std::string& r) : root (r) { assert (this->root.find ('/') == std::string::npos); } std::string path (const std::string& suffix) const { assert (suffix.back () != '/'); if (suffix.front () == '/') { assert (suffix.find ("/" + this->root + "/") == 0); return suffix; } else { return "/" + this->root + "/" + suffix; } } template const T& get (const std::string& p) const { Map::const_iterator value = this->map.find (this->path (p)); if (value == this->map.end ()) { throw (std::runtime_error ("Can not find path '" + this->path (p) + "' in kv-store")); } else { return value->second.get (); } } template const T& get (const std::string& p, const T& defaultV) const { Map::const_iterator value = this->map.find (this->path (p)); if (value == this->map.end ()) { return defaultV; } else { return value->second.get (); } } template void set (const std::string& p, const T& t) { this->remove (p); Value value; value.set (t); this->map.emplace (this->path (p), value); } void fromFile (const std::string& fileName) { Util::withCLocale ([this, &fileName]() { QFile file (fileName.c_str ()); if (file.open (QIODevice::ReadOnly | QIODevice::Text) == false) { throw (std::runtime_error ("Can not open kv-store file '" + fileName + "'")); } QDomDocument doc (fileName.c_str ()); QString errorMsg; int errorLine = -1; int errorColumn = -1; if (doc.setContent (&file, &errorMsg, &errorLine, &errorColumn) == false) { file.close (); throw (std::runtime_error ( "Error while loading kv-store file '" + fileName + "': " + errorMsg.toStdString () + " (" + std::to_string (errorLine) + "," + std::to_string (errorColumn) + ")")); } file.close (); try { this->loadNode ("", doc); } catch (std::runtime_error& e) { throw (std::runtime_error ("Error while parsing kv-store file '" + fileName + "': " + e.what ())); } }); } void loadNode (const QString& prefix, QDomNode& node) { QDomNode child = node.firstChild (); while (child.isNull () == false) { if (child.isElement ()) { QDomElement element = child.toElement (); QDomAttr attribute = element.attributeNode ("type"); Value value; if (attribute.isNull ()) { this->loadNode (prefix + "/" + element.tagName (), child); } else if (attribute.value () == "float") { this->loadElement (prefix, element); } else if (attribute.value () == "integer") { this->loadElement (prefix, element); } else if (attribute.value () == "boolean") { this->loadElement (prefix, element); } else if (attribute.value () == "vector3f") { this->loadElement (prefix, element); } else if (attribute.value () == "vector2i") { this->loadElement (prefix, element); } else if (attribute.value () == "color") { this->loadElement (prefix, element); } else { throw (std::runtime_error ("invalid type '" + attribute.value ().toStdString () + "' " + "(" + std::to_string (child.lineNumber ()) + "," + std::to_string (child.columnNumber ()) + ")")); } } else { throw (std::runtime_error ("invalid node (" + std::to_string (child.lineNumber ()) + "," + std::to_string (child.columnNumber ()) + ")")); } child = child.nextSibling (); } } template bool loadElement (const QString& prefix, QDomElement& element) { T t; const bool ok = XmlConversion::fromDomElement (element, t); const std::string suffix = element.tagName ().toStdString (); const std::string key = prefix.toStdString () + "/" + suffix; if (ok) { this->set (key, t); } else { throw (std::runtime_error ("can not parse value of key '" + key + "' " + "(" + std::to_string (element.lineNumber ()) + "," + std::to_string (element.columnNumber ()) + ")")); } return ok; } void toFile (const std::string& fileName) const { Util::withCLocale ([this, &fileName]() { QDomDocument doc; for (auto& c : this->map) { const std::string& key = c.first; const Value& value = c.second; QStringList path = QString (key.c_str ()).split ("/", QString::SkipEmptyParts); this->appendAsDomChild (doc, doc, path, value); } if (doc.isNull () == false) { QFile file (fileName.c_str ()); if (file.open (QIODevice::WriteOnly | QIODevice::Text)) { QTextStream stream (&file); doc.save (stream, 2); file.close (); } else { throw (std::runtime_error ("Can not save kv-store file '" + fileName + "'")); } } }); } void appendAsDomChild (QDomDocument& doc, QDomNode& parent, QStringList& path, const Value& value) const { if (path.empty ()) { assert (parent.isElement ()); QDomElement elem = parent.toElement (); if (value.is ()) { XmlConversion::toDomElement (doc, elem, value.get ()); } else if (value.is ()) { XmlConversion::toDomElement (doc, elem, value.get ()); } else if (value.is ()) { XmlConversion::toDomElement (doc, elem, value.get ()); } else if (value.is ()) { XmlConversion::toDomElement (doc, elem, value.get ()); } else if (value.is ()) { XmlConversion::toDomElement (doc, elem, value.get ()); } else if (value.is ()) { XmlConversion::toDomElement (doc, elem, value.get ()); } else DILAY_IMPOSSIBLE } else { const QString& head = path.first (); QDomElement child = parent.firstChildElement (head); if (child.isNull ()) { child = doc.createElement (head); if (parent.isNull ()) { doc.appendChild (child); } else { parent.appendChild (child); } } assert (child.hasAttribute ("type") == false); path.removeFirst (); this->appendAsDomChild (doc, child, path, value); } } void remove (const std::string& p) { this->map.erase (this->path (p)); } void reset () { this->map.clear (); } }; DELEGATE1_BIG2 (KVStore, const std::string&) DELEGATE1 (void, KVStore, fromFile, const std::string&); DELEGATE1_CONST (void, KVStore, toFile, const std::string&); DELEGATE1 (void, KVStore, remove, const std::string&); DELEGATE (void, KVStore, reset); template const T& KVStore::get (const std::string& path) const { return this->impl->get (path); } template const T& KVStore::get (const std::string& path, const T& defaultV) const { return this->impl->get (path, defaultV); } template void KVStore::set (const std::string& path, const T& value) { return this->impl->set (path, value); } template const float& KVStore::get (const std::string&) const; template const float& KVStore::get (const std::string&, const float&) const; template void KVStore::set (const std::string&, const float&); template const int& KVStore::get (const std::string&) const; template const int& KVStore::get (const std::string&, const int&) const; template void KVStore::set (const std::string&, const int&); template const bool& KVStore::get (const std::string&) const; template const bool& KVStore::get (const std::string&, const bool&) const; template void KVStore::set (const std::string&, const bool&); template const Color& KVStore::get (const std::string&) const; template const Color& KVStore::get (const std::string&, const Color&) const; template void KVStore::set (const std::string&, const Color&); template const glm::vec3& KVStore::get (const std::string&) const; template const glm::vec3& KVStore::get (const std::string&, const glm::vec3&) const; template void KVStore::set (const std::string&, const glm::vec3&); template const glm::ivec2& KVStore::get (const std::string&) const; template const glm::ivec2& KVStore::get (const std::string&, const glm::ivec2&) const; template void KVStore::set (const std::string&, const glm::ivec2&); ================================================ FILE: lib/src/kvstore.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_KVSTORE #define DILAY_KVSTORE #include #include "macro.hpp" class KVStore { public: DECLARE_BIG2 (KVStore, const std::string&) template const T& get (const std::string&) const; template const T& get (const std::string&, const T&) const; template void set (const std::string&, const T&); void fromFile (const std::string&); void toFile (const std::string&) const; void remove (const std::string&); void reset (); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/log.cpp ================================================ #include #include #include #include #include "log.hpp" #include "util.hpp" namespace { static std::FILE* fileHandle = nullptr; static std::string filePath; static std::time_t startTime; const char* levelToString (Log::Level level) { switch (level) { case Log::Level::Info: return "INFO"; case Log::Level::Warning: return "WARNING"; case Log::Level::Panic: return "PANIC"; } return nullptr; } void shutdown () { if (fileHandle) { std::fclose (fileHandle); std::remove (filePath.c_str ()); } } } namespace Log { void initialize (const std::string& path) { assert (fileHandle == nullptr); fileHandle = std::fopen (path.c_str (), "w"); if (fileHandle) { filePath = path; startTime = std::time (nullptr); std::atexit (shutdown); } else { DILAY_WARN ("Could not open log file %s", path.c_str ()); } } void log (Log::Level level, const char* file, unsigned int line, const char* format, ...) { const unsigned int secDiff = (unsigned int) std::difftime (std::time (nullptr), startTime); va_list args1; va_list args2; va_start (args1, format); va_copy (args2, args1); std::vector buffer (1 + std::vsnprintf (nullptr, 0, format, args1)); va_end (args1); std::vsnprintf (buffer.data (), buffer.size (), format, args2); va_end (args2); if (fileHandle) { std::fprintf (fileHandle, "%09u [%s] %s (%u): %s\n", secDiff, levelToString (level), file, line, buffer.data ()); std::fflush (fileHandle); } if (level != Log::Level::Info) { std::fprintf (stderr, "%09u [%s] %s (%u): %s\n", secDiff, levelToString (level), file, line, buffer.data ()); } } } ================================================ FILE: lib/src/log.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_LOG #define DILAY_LOG #include namespace Log { enum class Level { Info, Warning, Panic }; void initialize (const std::string&); void log (Level, const char*, unsigned int, const char*, ...); } #endif ================================================ FILE: lib/src/macro.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_MACRO #define DILAY_MACRO #include #include // delegators #define SET_SELF this->impl->self = this; #define DELEGATE_COPY_CONSTRUCTOR(from) \ from::from (const from& a1) \ : impl (new Impl (*a1.impl)) \ { \ } #define DELEGATE_COPY_CONSTRUCTOR_SELF(from) \ from::from (const from& a1) \ : impl (new Impl (*a1.impl)) \ { \ SET_SELF \ } #define DELEGATE_COPY_CONSTRUCTOR_BASE(from, base) \ from::from (const from& a1) \ : base (a1) \ , impl (new Impl (*a1.impl)) \ { \ SET_SELF \ } #define DELEGATE_MOVE_CONSTRUCTOR(from) \ from::from (from&& a1) \ : impl (new Impl (std::move (*a1.impl))) \ { \ } #define DELEGATE_MOVE_CONSTRUCTOR_SELF(from) \ from::from (from&& a1) \ : impl (new Impl (std::move (*a1.impl))) \ { \ SET_SELF \ } #define DELEGATE_MOVE_CONSTRUCTOR_BASE(from, base) \ from::from (from&& a1) \ : base (std::forward (a1)) \ , impl (new Impl (std::move (*a1.impl))) \ { \ SET_SELF \ } #define DELEGATE_ASSIGNMENT_OP(from) \ const from& from::operator= (const from& source) \ { \ this->impl->operator= (*source.impl); \ return *this; \ } #define DELEGATE_MOVE_ASSIGNMENT_OP(from) \ const from& from::operator= (from&& source) \ { \ this->impl->operator= (std::move (*source.impl)); \ return *this; \ } #define DELEGATE_MOVE_ASSIGNMENT_OP_SELF(from) \ const from& from::operator= (from&& source) \ { \ this->impl->operator= (std::move (*source.impl)); \ SET_SELF \ return *this; \ } #define DELEGATE_DESTRUCTOR(from) \ from::~from () {} #define DELEGATE_BIG3_WITHOUT_CONSTRUCTOR(from) \ DELEGATE_DESTRUCTOR (from) \ DELEGATE_MOVE_CONSTRUCTOR (from) #define DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF(from) \ DELEGATE_DESTRUCTOR (from) \ DELEGATE_MOVE_CONSTRUCTOR_SELF (from) #define DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR(from) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from) \ DELEGATE_COPY_CONSTRUCTOR (from) #define DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF(from) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from) \ DELEGATE_COPY_CONSTRUCTOR_SELF (from) #define DELEGATE_BIG6_WITHOUT_CONSTRUCTOR(from) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from) \ DELEGATE_MOVE_ASSIGNMENT_OP (from) \ DELEGATE_COPY_CONSTRUCTOR (from) \ DELEGATE_ASSIGNMENT_OP (from) #define DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF(from) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from) \ DELEGATE_MOVE_ASSIGNMENT_OP_SELF (from) \ DELEGATE_COPY_CONSTRUCTOR_SELF (from) \ DELEGATE_ASSIGNMENT_OP (from) #define DELEGATE_CONSTRUCTOR(from) \ from::from () \ : impl (new Impl ()) \ { \ } #define DELEGATE1_CONSTRUCTOR(from, t1) \ from::from (t1 a1) \ : impl (new Impl (std::forward (a1))) \ { \ } #define DELEGATE2_CONSTRUCTOR(from, t1, t2) \ from::from (t1 a1, t2 a2) \ : impl (new Impl (std::forward (a1), std::forward (a2))) \ { \ } #define DELEGATE3_CONSTRUCTOR(from, t1, t2, t3) \ from::from (t1 a1, t2 a2, t3 a3) \ : impl (new Impl (std::forward (a1), std::forward (a2), std::forward (a3))) \ { \ } #define DELEGATE4_CONSTRUCTOR(from, t1, t2, t3, t4) \ from::from (t1 a1, t2 a2, t3 a3, t4 a4) \ : impl (new Impl (std::forward (a1), std::forward (a2), std::forward (a3), \ std::forward (a4))) \ { \ } #define DELEGATE5_CONSTRUCTOR(from, t1, t2, t3, t4, t5) \ from::from (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) \ : impl (new Impl (std::forward (a1), std::forward (a2), std::forward (a3), \ std::forward (a4), std::forward (a5))) \ { \ } #define DELEGATE_CONSTRUCTOR_SELF(from) \ from::from () \ : impl (new Impl (this)) \ { \ } #define DELEGATE1_CONSTRUCTOR_SELF(from, t1) \ from::from (t1 a1) \ : impl (new Impl (this, a1)) \ { \ } #define DELEGATE2_CONSTRUCTOR_SELF(from, t1, t2) \ from::from (t1 a1, t2 a2) \ : impl (new Impl (this, a1, a2)) \ { \ } #define DELEGATE3_CONSTRUCTOR_SELF(from, t1, t2, t3) \ from::from (t1 a1, t2 a2, t3 a3) \ : impl (new Impl (this, a1, a2, a3)) \ { \ } #define DELEGATE4_CONSTRUCTOR_SELF(from, t1, t2, t3, t4) \ from::from (t1 a1, t2 a2, t3 a3, t4 a4) \ : impl (new Impl (this, a1, a2, a3, a4)) \ { \ } #define DELEGATE5_CONSTRUCTOR_SELF(from, t1, t2, t3, t4, t5) \ from::from (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) \ : impl (new Impl (this, a1, a2, a3, a4, a5)) \ { \ } #define DELEGATE_CONSTRUCTOR_BASE(from, params, fromArgs, base, baseArgs) \ from::from params : base baseArgs, impl (new Impl fromArgs) {} #define DELEGATE_IMPL(r, from, method, ifaceParams, implArgs) \ r from::method ifaceParams { return this->impl->method implArgs; } #define DELEGATE(r, from, method) DELEGATE_IMPL (r, from, method, (), ()) #define DELEGATE1(r, from, method, t1) \ DELEGATE_IMPL (r, from, method, (t1 a1), (std::forward (a1))) #define DELEGATE2(r, from, method, t1, t2) \ DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2), (std::forward (a1), std::forward (a2))) #define DELEGATE3(r, from, method, t1, t2, t3) \ DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2, t3 a3), \ (std::forward (a1), std::forward (a2), std::forward (a3))) #define DELEGATE4(r, from, method, t1, t2, t3, t4) \ DELEGATE_IMPL ( \ r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4), \ (std::forward (a1), std::forward (a2), std::forward (a3), std::forward (a4))) #define DELEGATE5(r, from, method, t1, t2, t3, t4, t5) \ DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5), \ (std::forward (a1), std::forward (a2), std::forward (a3), \ std::forward (a4), std::forward (a5))) #define DELEGATE_CONST(r, from, method) DELEGATE_IMPL (r, from, method, () const, ()) #define DELEGATE1_CONST(r, from, method, t1) \ DELEGATE_IMPL (r, from, method, (t1 a1) const, (std::forward (a1))) #define DELEGATE2_CONST(r, from, method, t1, t2) \ DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2) const, \ (std::forward (a1), std::forward (a2))) #define DELEGATE3_CONST(r, from, method, t1, t2, t3) \ DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2, t3 a3) const, \ (std::forward (a1), std::forward (a2), std::forward (a3))) #define DELEGATE4_CONST(r, from, method, t1, t2, t3, t4) \ DELEGATE_IMPL ( \ r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4) const, \ (std::forward (a1), std::forward (a2), std::forward (a3), std::forward (a4))) #define DELEGATE5_CONST(r, from, method, t1, t2, t3, t4, t5) \ DELEGATE_IMPL (r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) const, \ (std::forward (a1), std::forward (a2), std::forward (a3), \ std::forward (a4), std::forward (a5))) #define DELEGATE_BASE_STATIC(r, from, method, ifaceParams, implArgs) \ r from::method ifaceParams { return Impl::method implArgs; } #define DELEGATE_STATIC(r, from, method) DELEGATE_BASE_STATIC (r, from, method, (), ()) #define DELEGATE1_STATIC(r, from, method, t1) DELEGATE_BASE_STATIC (r, from, method, (t1 a1), (a1)) #define DELEGATE2_STATIC(r, from, method, t1, t2) \ DELEGATE_BASE_STATIC (r, from, method, (t1 a1, t2 a2), (a1, a2)) #define DELEGATE3_STATIC(r, from, method, t1, t2, t3) \ DELEGATE_BASE_STATIC (r, from, method, (t1 a1, t2 a2, t3 a3), (a1, a2, a3)) #define DELEGATE4_STATIC(r, from, method, t1, t2, t3, t4) \ DELEGATE_BASE_STATIC (r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4), (a1, a2, a3, a4)) #define DELEGATE5_STATIC(r, from, method, t1, t2, t3, t4, t5) \ DELEGATE_BASE_STATIC (r, from, method, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5), (a1, a2, a3, a4, a5)) #define DELEGATE_IMPL_MEMBER(r, from, method, member, ifaceParams, implArgs) \ r from::method ifaceParams { return this->impl->member.method implArgs; } #define DELEGATE_MEMBER(r, from, method, member) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (), ()) #define DELEGATE1_MEMBER(r, from, method, member, t1) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1), (std::forward (a1))) #define DELEGATE2_MEMBER(r, from, method, member, t1, t2) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2), \ (std::forward (a1), std::forward (a2))) #define DELEGATE3_MEMBER(r, from, method, member, t1, t2, t3) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2, t3 a3), \ (std::forward (a1), std::forward (a2), std::forward (a3))) #define DELEGATE4_MEMBER(r, from, method, member, t1, t2, t3, t4) \ DELEGATE_IMPL_MEMBER ( \ r, from, method, member, (t1 a1, t2 a2, t3 a3, t4 a4), \ (std::forward (a1), std::forward (a2), std::forward (a3), std::forward (a4))) #define DELEGATE5_MEMBER(r, from, method, member, t1, t2, t3, t4, t5) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5), \ (std::forward (a1), std::forward (a2), std::forward (a3), \ std::forward (a4), std::forward (a5))) #define DELEGATE_MEMBER_CONST(r, from, method, member) \ DELEGATE_IMPL_MEMBER (r, from, method, member, () const, ()) #define DELEGATE1_MEMBER_CONST(r, from, method, member, t1) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1) const, (std::forward (a1))) #define DELEGATE2_MEMBER_CONST(r, from, method, member, t1, t2) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2) const, \ (std::forward (a1), std::forward (a2))) #define DELEGATE3_MEMBER_CONST(r, from, method, member, t1, t2, t3) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2, t3 a3) const, \ (std::forward (a1), std::forward (a2), std::forward (a3))) #define DELEGATE4_MEMBER_CONST(r, from, method, member, t1, t2, t3, t4) \ DELEGATE_IMPL_MEMBER ( \ r, from, method, member, (t1 a1, t2 a2, t3 a3, t4 a4) const, \ (std::forward (a1), std::forward (a2), std::forward (a3), std::forward (a4))) #define DELEGATE5_MEMBER_CONST(r, from, method, member, t1, t2, t3, t4, t5) \ DELEGATE_IMPL_MEMBER (r, from, method, member, (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) const, \ (std::forward (a1), std::forward (a2), std::forward (a3), \ std::forward (a4), std::forward (a5))) // big 2 delegators #define DELEGATE_BIG2(from) \ DELEGATE_CONSTRUCTOR (from) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE1_BIG2(from, t1) \ DELEGATE1_CONSTRUCTOR (from, t1) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE2_BIG2(from, t1, t2) \ DELEGATE2_CONSTRUCTOR (from, t1, t2) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE3_BIG2(from, t1, t2, t3) \ DELEGATE3_CONSTRUCTOR (from, t1, t2, t3) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE4_BIG2(from, t1, t2, t3, t4) \ DELEGATE4_CONSTRUCTOR (from, t1, t2, t3, t4) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE5_BIG2(from, t1, t2, t3, t4, t5) \ DELEGATE5_CONSTRUCTOR (from, t1, t2, t3, t4, t5) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE_BIG2_SELF(from) \ DELEGATE_CONSTRUCTOR_SELF (from) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE1_BIG2_SELF(from, t1) \ DELEGATE1_CONSTRUCTOR_SELF (from, t1) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE2_BIG2_SELF(from, t1, t2) \ DELEGATE2_CONSTRUCTOR_SELF (from, t1, t2) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE3_BIG2_SELF(from, t1, t2, t3) \ DELEGATE3_CONSTRUCTOR_SELF (from, t1, t2, t3) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE4_BIG2_SELF(from, t1, t2, t3, t4) \ DELEGATE4_CONSTRUCTOR_SELF (from, t1, t2, t3, t4) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE5_BIG2_SELF(from, t1, t2, t3, t4, t5) \ DELEGATE5_CONSTRUCTOR_SELF (from, t1, t2, t3, t4, t5) \ DELEGATE_DESTRUCTOR (from) #define DELEGATE_BIG2_BASE(from, params, fromArgs, base, baseArgs) \ DELEGATE_CONSTRUCTOR_BASE (from, params, fromArgs, base, baseArgs) \ DELEGATE_DESTRUCTOR (from) // big 3 delegators #define DELEGATE_BIG3(from) \ DELEGATE_CONSTRUCTOR (from) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from) #define DELEGATE1_BIG3(from, t1) \ DELEGATE1_CONSTRUCTOR (from, t1) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from) #define DELEGATE2_BIG3(from, t1, t2) \ DELEGATE2_CONSTRUCTOR (from, t1, t2) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from) #define DELEGATE3_BIG3(from, t1, t2, t3) \ DELEGATE3_CONSTRUCTOR (from, t1, t2, t3) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from) #define DELEGATE4_BIG3(from, t1, t2, t3, t4) \ DELEGATE4_CONSTRUCTOR (from, t1, t2, t3, t4) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from) #define DELEGATE5_BIG3(from, t1, t2, t3, t4, t5) \ DELEGATE5_CONSTRUCTOR (from, t1, t2, t3, t4, t5) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR (from) #define DELEGATE_BIG3_SELF(from) \ DELEGATE_CONSTRUCTOR_SELF (from) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE1_BIG3_SELF(from, t1) \ DELEGATE1_CONSTRUCTOR_SELF (from, t1) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE2_BIG3_SELF(from, t1, t2) \ DELEGATE2_CONSTRUCTOR_SELF (from, t1, t2) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE3_BIG3_SELF(from, t1, t2, t3) \ DELEGATE3_CONSTRUCTOR_SELF (from, t1, t2, t3) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE4_BIG3_SELF(from, t1, t2, t3, t4) \ DELEGATE4_CONSTRUCTOR_SELF (from, t1, t2, t3, t4) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE5_BIG3_SELF(from, t1, t2, t3, t4, t5) \ DELEGATE5_CONSTRUCTOR_SELF (from, t1, t2, t3, t4, t5) \ DELEGATE_BIG3_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE_BIG3_BASE(from, params, fromArgs, base, baseArgs) \ DELEGATE_CONSTRUCTOR_BASE (from, params, fromArgs, base, baseArgs) \ DELEGATE_DESTRUCTOR (from) \ DELEGATE_MOVE_CONSTRUCTOR_BASE (from, base) // big 4 delegators #define DELEGATE_BIG4_COPY(from) \ DELEGATE_CONSTRUCTOR (from) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from) #define DELEGATE1_BIG4_COPY(from, t1) \ DELEGATE1_CONSTRUCTOR (from, t1) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from) #define DELEGATE2_BIG4_COPY(from, t1, t2) \ DELEGATE2_CONSTRUCTOR (from, t1, t2) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from) #define DELEGATE3_BIG4_COPY(from, t1, t2, t3) \ DELEGATE3_CONSTRUCTOR (from, t1, t2, t3) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from) #define DELEGATE4_BIG4_COPY(from, t1, t2, t3, t4) \ DELEGATE4_CONSTRUCTOR (from, t1, t2, t3, t4) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from) #define DELEGATE5_BIG4_COPY(from, t1, t2, t3, t4, t5) \ DELEGATE5_CONSTRUCTOR (from, t1, t2, t3, t4, t5) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR (from) #define DELEGATE_BIG4_COPY_SELF(from) \ DELEGATE_CONSTRUCTOR_SELF (from) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE1_BIG4_COPY_SELF(from, t1) \ DELEGATE1_CONSTRUCTOR_SELF (from, t1) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE2_BIG4_COPY_SELF(from, t1, t2) \ DELEGATE2_CONSTRUCTOR_SELF (from, t1, t2) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE3_BIG4_COPY_SELF(from, t1, t2, t3) \ DELEGATE3_CONSTRUCTOR_SELF (from, t1, t2, t3) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE4_BIG4_COPY_SELF(from, t1, t2, t3, t4) \ DELEGATE4_CONSTRUCTOR_SELF (from, t1, t2, t3, t4) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE5_BIG4_COPY_SELF(from, t1, t2, t3, t4, t5) \ DELEGATE5_CONSTRUCTOR_SELF (from, t1, t2, t3, t4, t5) \ DELEGATE_BIG4_COPY_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE_BIG4_COPY_BASE(from, params, fromArgs, base, baseArgs) \ DELEGATE_CONSTRUCTOR_BASE (from, params, fromArgs, base, baseArgs) \ DELEGATE_DESTRUCTOR (from) \ DELEGATE_MOVE_CONSTRUCTOR_BASE (from, base) \ DELEGATE_COPY_CONSTRUCTOR_BASE (from, base) // big 6 delegators #define DELEGATE_BIG6(from) \ DELEGATE_CONSTRUCTOR (from) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from) #define DELEGATE1_BIG6(from, t1) \ DELEGATE1_CONSTRUCTOR (from, t1) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from) #define DELEGATE2_BIG6(from, t1, t2) \ DELEGATE2_CONSTRUCTOR (from, t1, t2) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from) #define DELEGATE3_BIG6(from, t1, t2, t3) \ DELEGATE3_CONSTRUCTOR (from, t1, t2, t3) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from) #define DELEGATE4_BIG6(from, t1, t2, t3, t4) \ DELEGATE4_CONSTRUCTOR (from, t1, t2, t3, t4) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from) #define DELEGATE5_BIG6(from, t1, t2, t3, t4, t5) \ DELEGATE5_CONSTRUCTOR (from, t1, t2, t3, t4, t5) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR (from) #define DELEGATE_BIG6_SELF(from) \ DELEGATE_CONSTRUCTOR_SELF (from) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE1_BIG6_SELF(from, t1) \ DELEGATE1_CONSTRUCTOR_SELF (from, t1) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE2_BIG6_SELF(from, t1, t2) \ DELEGATE2_CONSTRUCTOR_SELF (from, t1, t2) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE3_BIG6_SELF(from, t1, t2, t3) \ DELEGATE3_CONSTRUCTOR_SELF (from, t1, t2, t3) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE4_BIG6_SELF(from, t1, t2, t3, t4) \ DELEGATE4_CONSTRUCTOR_SELF (from, t1, t2, t3, t4) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE5_BIG6_SELF(from, t1, t2, t3, t4, t5) \ DELEGATE5_CONSTRUCTOR_SELF (from, t1, t2, t3, t4, t5) \ DELEGATE_BIG6_WITHOUT_CONSTRUCTOR_SELF (from) #define DELEGATE_BIG6_BASE(from, params, fromArgs, base, baseArgs) \ DELEGATE_CONSTRUCTOR_BASE (from, params, fromArgs, base, baseArgs) \ DELEGATE_DESTRUCTOR (from) \ DELEGATE_COPY_CONSTRUCTOR_BASE (from, base) \ DELEGATE_MOVE_CONSTRUCTOR_BASE (from, base) \ DELEGATE_ASSIGNMENT_OP (from) \ DELEGATE_MOVE_ASSIGNMENT_OP_SELF (from) // getters/setters #define GETTER_CONST(r, from, member) \ r from::member () const { return this->impl->member; } #define GETTER(r, from, member) \ r from::member () { return this->impl->member; } #define SETTER(t, from, member) \ void from::member (t a) { this->impl->member = a; } #define _MEMBER_GETTER_SETTER(type, name, pass_type) \ public: \ pass_type name () const { return this->_##name; } \ void name (pass_type v) { this->_##name = v; } \ \ private: \ type _##name; #define MEMBER_GETTER_SETTER(type, name) _MEMBER_GETTER_SETTER (type, name, type) #define MEMBER_REF_GETTER_SETTER(type, name) _MEMBER_GETTER_SETTER (type, name, const type&) #define _MEMBER_GETTER_EXPLICIT_SETTER(type, name, pass_type) \ public: \ pass_type name () const { return this->_##name; } \ void name (pass_type v); \ \ private: \ type _##name; #define MEMBER_GETTER_EXPLICIT_SETTER(type, name) _MEMBER_GETTER_EXPLICIT_SETTER (type, name, type) #define MEMBER_REF_GETTER_EXPLICIT_SETTER(type, name) \ _MEMBER_GETTER_EXPLICIT_SETTER (type, name, const type&) #define _MEMBER_GETTER(type, name, pass_type) \ public: \ pass_type name () const { return this->_##name; } \ \ private: \ type _##name; #define MEMBER_GETTER(type, name) _MEMBER_GETTER (type, name, type) #define MEMBER_REF_GETTER(type, name) _MEMBER_GETTER (type, name, const type&) // safe references #define SAFE_REF(r, method) \ r& method##Ref () \ { \ r* ptr = this->method (); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF1(r, method, t1) \ r& method##Ref (t1 a1) \ { \ r* ptr = this->method (a1); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF2(r, method, t1, t2) \ r& method##Ref (t1 a1, t2 a2) \ { \ r* ptr = this->method (a1, a2); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF3(r, method, t1, t2, t3) \ r& method##Ref (t1 a1, t2 a2, t3 a3) \ { \ r* ptr = this->method (a1, a2, a3); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF4(r, method, t1, t2, t3, t4) \ r& method##Ref (t1 a1, t2 a2, t3 a3, t4 a4) \ { \ r* ptr = this->method (a1, a2, a3, a4); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF5(r, method, t1, t2, t3, t4, t5) \ r& method##Ref (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) \ { \ r* ptr = this->method (a1, a2, a3, a4, a5); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF_CONST(r, method) \ r& method##Ref () const \ { \ r* ptr = this->method (); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF1_CONST(r, method, t1) \ r& method##Ref (t1 a1) const \ { \ r* ptr = this->method (a1); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF2_CONST(r, method, t1, t2) \ r& method##Ref (t1 a1, t2 a2) const \ { \ r* ptr = this->method (a1, a2); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF3_CONST(r, method, t1, t2, t3) \ r& method##Ref (t1 a1, t2 a2, t3 a3) const \ { \ r* ptr = this->method (a1, a2, a3); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF4_CONST(r, method, t1, t2, t3, t4) \ r& method##Ref (t1 a1, t2 a2, t3 a3, t4 a4) const \ { \ r* ptr = this->method (a1, a2, a3, a4); \ assert (ptr); \ return *ptr; \ } #define SAFE_REF5_CONST(r, method, t1, t2, t3, t4, t5) \ r& method##Ref (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) const \ { \ r* ptr = this->method (a1, a2, a3, a4, a5); \ assert (ptr); \ return *ptr; \ } // big 2 declarations #define DECLARE_BIG2(t, ...) \ t (__VA_ARGS__); \ t (const t&) = delete; \ t (t&&) = delete; \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; \ ~t (); #define DECLARE_BIG2_VIRTUAL(t, ...) \ t (__VA_ARGS__); \ t (const t&) = delete; \ t (t&&) = delete; \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; \ virtual ~t (); // big 3 declarations #define DECLARE_BIG3(t, ...) \ t (__VA_ARGS__); \ t (const t&) = delete; \ t (t&&); \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; \ ~t (); #define DECLARE_BIG3_VIRTUAL(t, ...) \ t (__VA_ARGS__); \ t (const t&) = delete; \ t (t&&); \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; \ virtual ~t (); // big 4 declarations #define DECLARE_BIG4_COPY(t, ...) \ t (__VA_ARGS__); \ t (const t&); \ t (t&&); \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; \ ~t (); #define DECLARE_BIG4_COPY_VIRTUAL(t, ...) \ t (__VA_ARGS__); \ t (const t&); \ t (t&&); \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; \ virtual ~t (); #define DECLARE_BIG4_EXPLICIT_COPY(t, ...) \ t (__VA_ARGS__); \ explicit t (const t&); \ t (t&&); \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; \ ~t (); #define DECLARE_BIG4_EXPLICIT_COPY_VIRTUAL(t, ...) \ t (__VA_ARGS__); \ explicit t (const t&); \ t (t&&); \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; \ virtual ~t (); // big 6 declarations #define DECLARE_BIG6(t, ...) \ t (__VA_ARGS__); \ t (const t&); \ t (t&&); \ const t& operator= (const t&); \ const t& operator= (t&&); \ ~t (); #define DECLARE_BIG6_VIRTUAL(t, ...) \ t (__VA_ARGS__); \ t (const t&); \ t (t&&); \ const t& operator= (const t&); \ const t& operator= (t&&); \ virtual ~t (); // miscellaneous #define DELETE_COPYMOVEASSIGN(t) \ t (const t&) = delete; \ t (t&&) = delete; \ const t& operator= (const t&) = delete; \ const t& operator= (t&&) = delete; #define DEFAULT_COPYMOVEASSIGN(t) \ t (const t&) = default; \ t (t&&) = default; \ const t& operator= (const t&) = default; \ const t& operator= (t&&) = default; #define IMPLEMENTATION \ struct Impl; \ std::unique_ptr impl; #define ESC_PARENS(...) __VA_ARGS__ #endif ================================================ FILE: lib/src/maybe.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_MAYBE #define DILAY_MAYBE #include #include template class Maybe { static_assert (std::is_pointer::value == false, "Maybe does not support pointers"); static_assert (std::is_reference::value == false, "Maybe does not support references"); public: Maybe () = default; explicit Maybe (T* v) : value (v) { } Maybe (const T& v) : value (new T (v)) { } Maybe (const Maybe& o) : value (o.hasValue () ? new T (*o) : nullptr) { } Maybe (Maybe&&) = default; Maybe (std::unique_ptr&& v) : value (std::move (v)) { } template static Maybe make (Args&&... args) { return Maybe (std::make_unique (std::forward (args)...)); } ~Maybe () = default; Maybe& operator= (T* v) { if (this->get () != v) { this->value.reset (v); } return *this; } Maybe& operator= (const T& v) { if (this->get () != &v) { this->value.reset (new T (v)); } return *this; } Maybe& operator= (const Maybe& o) { if (this != &o) { this->value.reset (o.hasValue () ? new T (*o) : nullptr); } return *this; } Maybe& operator= (Maybe&&) = default; explicit operator bool () const { return this->hasValue (); } bool operator== (bool v) const { return this->operator bool () == v; } T& operator* () { assert (this->hasValue ()); return *this->value; } const T& operator* () const { assert (this->hasValue ()); return *this->value; } T* operator-> () { return this->get (); } const T* operator-> () const { return this->get (); } T* get () { return this->value.get (); } const T* get () const { return this->value.get (); } T* release () { return this->value.release (); } bool hasValue () const { return bool(this->value); } void reset (T* newValue = nullptr) { this->value.reset (newValue); } void swap (Maybe& o) { this->value.swap (o.value); } private: std::unique_ptr value; }; #endif ================================================ FILE: lib/src/mesh-util.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include #include "hash.hpp" #include "intersection.hpp" #include "mesh-util.hpp" #include "mesh.hpp" #include "primitive/aabox.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "util.hpp" namespace { struct VertexCache { typedef std::function MakeNewVertex; std::unordered_map cache; unsigned int lookup (unsigned int i1, unsigned int i2, const MakeNewVertex& f) { const ui_pair key = std::make_pair (glm::min (i1, i2), glm::max (i1, i2)); const auto it = this->cache.find (key); if (it == this->cache.end ()) { const unsigned int n = f (i1, i2); this->cache.emplace (key, n); return n; } else { return it->second; } } }; struct EdgeMap { EdgeMap (unsigned int numVertices) { this->elements.resize (numVertices - 1); } unsigned int* find (unsigned int i1, unsigned int i2) { const unsigned int minI = glm::min (i1, i2); const unsigned int maxI = glm::max (i1, i2); if (minI < this->elements.size ()) { return this->findInSequence (elements[minI], maxI); } else { return nullptr; } } void add (unsigned int i1, unsigned int i2, const unsigned int& element) { const unsigned int minI = glm::min (i1, i2); const unsigned int maxI = glm::max (i1, i2); assert (minI < this->elements.size ()); assert (this->findInSequence (this->elements[minI], maxI) == nullptr); if (this->elements[minI].empty ()) { this->elements[minI].reserve (6); } this->elements[minI].push_back (std::make_pair (maxI, element)); } void increase (unsigned int i1, unsigned int i2) { const unsigned int minI = glm::min (i1, i2); const unsigned int maxI = glm::max (i1, i2); assert (minI < this->elements.size ()); unsigned int* value = this->findInSequence (this->elements[minI], maxI); if (value) { (*value)++; } else { if (this->elements[minI].empty ()) { this->elements[minI].reserve (6); } this->elements[minI].push_back (std::make_pair (maxI, 1)); } } unsigned int* findInSequence (std::vector>& sequence, unsigned int i) { for (auto& p : sequence) { if (p.first == i) { return &p.second; } } return nullptr; } std::vector>> elements; }; Mesh& withDefaultNormals (Mesh& mesh) { for (unsigned int i = 0; i < mesh.numVertices (); i++) { mesh.normal (i, glm::normalize (mesh.vertex (i))); } return mesh; } } void MeshUtil::addFace (Mesh& mesh, unsigned int i1, unsigned int i2, unsigned int i3) { mesh.addIndex (i1); mesh.addIndex (i2); mesh.addIndex (i3); } void MeshUtil::addFace (Mesh& mesh, unsigned int i1, unsigned int i2, unsigned int i3, unsigned int i4) { mesh.addIndex (i1); mesh.addIndex (i2); mesh.addIndex (i3); mesh.addIndex (i4); mesh.addIndex (i1); mesh.addIndex (i3); } Mesh MeshUtil::cube (unsigned int numSubdivisions) { Mesh mesh; VertexCache vertexCache; const auto addStartVertex = [&mesh](const glm::vec3& v) -> unsigned int { return mesh.addVertex (v, glm::normalize (v)); }; const auto addRefinedVertex = [&mesh](unsigned int i1, unsigned int i2) -> unsigned int { return mesh.addVertex (Util::midpoint (mesh.vertex (i1), mesh.vertex (i2))); }; std::function subdivide = [&mesh, &subdivide, &addRefinedVertex, &vertexCache](unsigned int s, unsigned int i1, unsigned int i2, unsigned int i3, unsigned int i4) -> void { if (s == 0) { MeshUtil::addFace (mesh, i1, i2, i3); MeshUtil::addFace (mesh, i1, i3, i4); } else { const glm::vec3 v1 = mesh.vertex (i1); const glm::vec3 v2 = mesh.vertex (i2); const glm::vec3 v3 = mesh.vertex (i3); const glm::vec3 v4 = mesh.vertex (i4); const unsigned int iC = mesh.addVertex ((v1 + v2 + v3 + v4) / 4.0f); const unsigned int i12 = vertexCache.lookup (i1, i2, addRefinedVertex); const unsigned int i23 = vertexCache.lookup (i2, i3, addRefinedVertex); const unsigned int i34 = vertexCache.lookup (i3, i4, addRefinedVertex); const unsigned int i41 = vertexCache.lookup (i4, i1, addRefinedVertex); subdivide (s - 1, i1, i12, iC, i41); subdivide (s - 1, i2, i23, iC, i12); subdivide (s - 1, i3, i34, iC, i23); subdivide (s - 1, i4, i41, iC, i34); } }; addStartVertex (glm::vec3 (-0.5f, -0.5f, -0.5f)); addStartVertex (glm::vec3 (-0.5f, -0.5f, +0.5f)); addStartVertex (glm::vec3 (-0.5f, +0.5f, -0.5f)); addStartVertex (glm::vec3 (-0.5f, +0.5f, +0.5f)); addStartVertex (glm::vec3 (+0.5f, -0.5f, -0.5f)); addStartVertex (glm::vec3 (+0.5f, -0.5f, +0.5f)); addStartVertex (glm::vec3 (+0.5f, +0.5f, -0.5f)); addStartVertex (glm::vec3 (+0.5f, +0.5f, +0.5f)); subdivide (numSubdivisions, 0, 1, 3, 2); subdivide (numSubdivisions, 1, 5, 7, 3); subdivide (numSubdivisions, 5, 4, 6, 7); subdivide (numSubdivisions, 4, 0, 2, 6); subdivide (numSubdivisions, 3, 7, 6, 2); subdivide (numSubdivisions, 0, 4, 5, 1); for (unsigned int i = 0; i < mesh.numVertices (); i++) { const glm::vec3& vertex = mesh.vertex (i); glm::vec3 normal = glm::vec3 (0.0f); if (Util::almostEqual (vertex.x, 0.5f)) { normal.x = 1.0f; } else if (Util::almostEqual (vertex.x, -0.5f)) { normal.x = -1.0f; } if (Util::almostEqual (vertex.y, 0.5f)) { normal.y = 1.0f; } else if (Util::almostEqual (vertex.y, -0.5f)) { normal.y = -1.0f; } if (Util::almostEqual (vertex.z, 0.5f)) { normal.z = 1.0f; } else if (Util::almostEqual (vertex.z, -0.5f)) { normal.z = -1.0f; } mesh.normal (i, glm::normalize (normal)); } return mesh; } Mesh MeshUtil::sphere (unsigned int rings, unsigned int sectors) { assert (rings > 1 && sectors > 2); Mesh mesh; const float radius = 1.0f; const float ringStep = glm::pi () / float(rings); const float sectorStep = 2.0f * glm::pi () / float(sectors); float phi = ringStep; float theta = 0.0f; // inner rings vertices for (unsigned int r = 0; r < rings - 1; r++) { for (unsigned int s = 0; s < sectors; s++) { const float x = radius * sin (theta) * sin (phi); const float y = radius * cos (phi); const float z = radius * cos (theta) * sin (phi); mesh.addVertex (glm::vec3 (x, y, z)); theta += sectorStep; } phi += ringStep; } // caps vertices const unsigned int topCapIndex = mesh.addVertex (glm::vec3 (0.0f, radius, 0.0f)); const unsigned int botCapIndex = mesh.addVertex (glm::vec3 (0.0f, -radius, 0.0f)); // inner rings indices for (unsigned int r = 0; r < rings - 2; r++) { for (unsigned int s = 0; s < sectors; s++) { MeshUtil::addFace (mesh, (sectors * r) + s, (sectors * (r + 1)) + s, (sectors * (r + 1)) + ((s + 1) % sectors), (sectors * r) + ((s + 1) % sectors)); } } // caps indices for (unsigned int s = 0; s < sectors; s++) { MeshUtil::addFace (mesh, topCapIndex, s, (s + 1) % sectors); MeshUtil::addFace (mesh, botCapIndex, (sectors * (rings - 2)) + ((s + 1) % sectors), (sectors * (rings - 2)) + s); } return withDefaultNormals (mesh); } Mesh MeshUtil::icosphere (unsigned int numSubdivisions) { Mesh mesh; VertexCache vertexCache; const auto addStartVertex = [&mesh](const glm::vec3& v) -> unsigned int { return mesh.addVertex (glm::normalize (v), glm::normalize (v)); }; const auto addRefinedVertex = [&mesh](unsigned int i1, unsigned int i2) -> unsigned int { const glm::vec3 pos = glm::normalize (Util::midpoint (mesh.vertex (i1), mesh.vertex (i2))); const glm::vec3 normal = glm::normalize (pos); return mesh.addVertex (pos, normal); }; std::function subdivide = [&mesh, &subdivide, &addRefinedVertex, &vertexCache](unsigned int s, unsigned int i1, unsigned int i2, unsigned int i3) -> void { if (s == 0) { MeshUtil::addFace (mesh, i1, i2, i3); } else { const unsigned int i12 = vertexCache.lookup (i1, i2, addRefinedVertex); const unsigned int i23 = vertexCache.lookup (i2, i3, addRefinedVertex); const unsigned int i31 = vertexCache.lookup (i3, i1, addRefinedVertex); subdivide (s - 1, i1, i12, i31); subdivide (s - 1, i2, i23, i12); subdivide (s - 1, i3, i31, i23); subdivide (s - 1, i12, i23, i31); } }; const float t = (1.0f + glm::sqrt (5.0f)) * 0.5f; addStartVertex (glm::vec3 (-1.0f, +t, 0.0f)); addStartVertex (glm::vec3 (+1.0f, +t, 0.0f)); addStartVertex (glm::vec3 (-1.0f, -t, 0.0f)); addStartVertex (glm::vec3 (+1.0f, -t, 0.0f)); addStartVertex (glm::vec3 (0.0f, -1.0f, +t)); addStartVertex (glm::vec3 (0.0f, +1.0f, +t)); addStartVertex (glm::vec3 (0.0f, -1.0f, -t)); addStartVertex (glm::vec3 (0.0f, +1.0f, -t)); addStartVertex (glm::vec3 (+t, 0.0f, -1.0f)); addStartVertex (glm::vec3 (+t, 0.0f, +1.0f)); addStartVertex (glm::vec3 (-t, 0.0f, -1.0f)); addStartVertex (glm::vec3 (-t, 0.0f, +1.0f)); subdivide (numSubdivisions, 0, 11, 5); subdivide (numSubdivisions, 0, 5, 1); subdivide (numSubdivisions, 0, 1, 7); subdivide (numSubdivisions, 0, 7, 10); subdivide (numSubdivisions, 0, 10, 11); subdivide (numSubdivisions, 1, 5, 9); subdivide (numSubdivisions, 5, 11, 4); subdivide (numSubdivisions, 11, 10, 2); subdivide (numSubdivisions, 10, 7, 6); subdivide (numSubdivisions, 7, 1, 8); subdivide (numSubdivisions, 3, 9, 4); subdivide (numSubdivisions, 3, 4, 2); subdivide (numSubdivisions, 3, 2, 6); subdivide (numSubdivisions, 3, 6, 8); subdivide (numSubdivisions, 3, 8, 9); subdivide (numSubdivisions, 4, 9, 5); subdivide (numSubdivisions, 2, 4, 11); subdivide (numSubdivisions, 6, 2, 10); subdivide (numSubdivisions, 8, 6, 7); subdivide (numSubdivisions, 9, 8, 1); return mesh; } Mesh MeshUtil::cone (unsigned int numBaseVertices) { assert (numBaseVertices >= 3); Mesh mesh; const float c = 2.0f * glm::pi () / float(numBaseVertices); for (unsigned int i = 0; i < numBaseVertices; i++) { mesh.addVertex (glm::vec3 (glm::sin (float(i) * c), -0.5f, glm::cos (float(i) * c))); } mesh.addVertex (glm::vec3 (0.0f, -0.5f, 0.0f)); mesh.addVertex (glm::vec3 (0.0f, 0.5f, 0.0f)); for (unsigned int i = 0; i < numBaseVertices - 1; i++) { MeshUtil::addFace (mesh, i, i + 1, numBaseVertices + 1); MeshUtil::addFace (mesh, i + 1, i, numBaseVertices); } MeshUtil::addFace (mesh, numBaseVertices - 1, 0, numBaseVertices + 1); MeshUtil::addFace (mesh, 0, numBaseVertices - 1, numBaseVertices); return withDefaultNormals (mesh); } Mesh MeshUtil::cylinder (unsigned int numVertices) { assert (numVertices >= 3); Mesh mesh; const float c = 2.0f * glm::pi () / float(numVertices); for (unsigned int i = 0; i < numVertices; i++) { mesh.addVertex (glm::vec3 (glm::sin (float(i) * c), -0.5f, glm::cos (float(i) * c))); } for (unsigned int i = 0; i < numVertices; i++) { mesh.addVertex (glm::vec3 (glm::sin (float(i) * c), 0.5f, glm::cos (float(i) * c))); } mesh.addVertex (glm::vec3 (0.0f, -0.5f, 0.0f)); mesh.addVertex (glm::vec3 (0.0f, 0.5f, 0.0f)); for (unsigned int i = 0; i < numVertices - 1; i++) { MeshUtil::addFace (mesh, i, i + 1, i + numVertices + 1, i + numVertices); MeshUtil::addFace (mesh, i + 1, i, 2 * numVertices); MeshUtil::addFace (mesh, i + numVertices, i + numVertices + 1, (2 * numVertices) + 1); } MeshUtil::addFace (mesh, numVertices - 1, 0, numVertices, (2 * numVertices) - 1); MeshUtil::addFace (mesh, 0, numVertices - 1, 2 * numVertices); MeshUtil::addFace (mesh, (2 * numVertices) - 1, numVertices, (2 * numVertices) + 1); return withDefaultNormals (mesh); } Mesh MeshUtil::mirrorPositive (const Mesh& mesh, const PrimPlane& plane) { assert (MeshUtil::checkConsistency (mesh)); enum class Side { Negative, Border, Positive }; enum class BorderFlag { NoBorder, ConnectsNegative, ConnectsPositive, ConnectsBoth }; auto side = [&plane](const glm::vec3& v) -> Side { const float eps = Util::epsilon () * 0.5f; const float d = plane.distance (v); return d < -eps ? Side::Negative : (d > eps ? Side::Positive : Side::Border); }; Mesh m; std::vector sides; std::vector borderFlags; std::vector newIndices; EdgeMap newBorderVertices (mesh.numVertices ()); auto updateBorderFlag = [&borderFlags](unsigned int i, Side side) { BorderFlag& current = borderFlags[i]; if (side == Side::Border) { } else if (side == Side::Negative) { if (current == BorderFlag::NoBorder) { current = BorderFlag::ConnectsNegative; } else if (current == BorderFlag::ConnectsPositive) { current = BorderFlag::ConnectsBoth; } } else if (side == Side::Positive) { if (current == BorderFlag::NoBorder) { current = BorderFlag::ConnectsPositive; } else if (current == BorderFlag::ConnectsNegative) { current = BorderFlag::ConnectsBoth; } } }; auto newBorderVertex = [&mesh, &plane, &newBorderVertices, &m](unsigned int i1, unsigned int i2) -> unsigned int { const unsigned int* existentIndex = newBorderVertices.find (i1, i2); if (existentIndex) { return *existentIndex; } else { const glm::vec3 v1 (mesh.vertex (i1)); const glm::vec3 v2 (mesh.vertex (i2)); const PrimRay ray (true, v1, v2 - v1); float t; glm::vec3 position; if (IntersectionUtil::intersects (ray, plane, &t)) { position = ray.pointAt (t); } else { position = (v1 + v2) * 0.5f; } const unsigned int newIndex = m.addVertex (position); newBorderVertices.add (i1, i2, newIndex); return newIndex; } }; m.copyNonGeometry (mesh); sides.reserve (mesh.numVertices ()); borderFlags.reserve (mesh.numVertices ()); newIndices.resize (mesh.numVertices (), std::make_pair (Util::invalidIndex (), Util::invalidIndex ())); // cache data for (unsigned int i = 0; i < mesh.numVertices (); i++) { sides.push_back (side (mesh.vertex (i))); borderFlags.push_back (BorderFlag::NoBorder); } // update border flags for (unsigned int i = 0; i < mesh.numIndices (); i += 3) { const unsigned int i1 = mesh.index (i + 0); const unsigned int i2 = mesh.index (i + 1); const unsigned int i3 = mesh.index (i + 2); assert (sides[i1] != Side::Border || sides[i2] != Side::Border || sides[i3] != Side::Border); updateBorderFlag (i1, sides[i2]); updateBorderFlag (i1, sides[i3]); updateBorderFlag (i2, sides[i1]); updateBorderFlag (i2, sides[i3]); updateBorderFlag (i3, sides[i1]); updateBorderFlag (i3, sides[i2]); } // mirror vertices for (unsigned int i = 0; i < mesh.numVertices (); i++) { switch (sides[i]) { case Side::Negative: break; case Side::Border: { switch (borderFlags[i]) { case BorderFlag::NoBorder: DILAY_IMPOSSIBLE break; case BorderFlag::ConnectsNegative: break; case BorderFlag::ConnectsPositive: { const unsigned int index1 = m.addVertex (mesh.vertex (i)); const unsigned int index2 = m.addVertex (mesh.vertex (i)); newIndices[i] = std::make_pair (index1, index2); break; } case BorderFlag::ConnectsBoth: { const unsigned int index = m.addVertex (mesh.vertex (i)); newIndices[i] = std::make_pair (index, index); break; } } break; } case Side::Positive: { const unsigned int index1 = m.addVertex (mesh.vertex (i)); const unsigned int index2 = m.addVertex (plane.mirror (mesh.vertex (i))); newIndices[i] = std::make_pair (index1, index2); break; } } } // mirror faces for (unsigned int i = 0; i < mesh.numIndices (); i += 3) { const unsigned int oldIndex1 = mesh.index (i + 0); const unsigned int oldIndex2 = mesh.index (i + 1); const unsigned int oldIndex3 = mesh.index (i + 2); const Side s1 = sides[oldIndex1]; const Side s2 = sides[oldIndex2]; const Side s3 = sides[oldIndex3]; if (s1 == Side::Positive || s2 == Side::Positive || s3 == Side::Positive) { const ui_pair& new1 = newIndices[oldIndex1]; const ui_pair& new2 = newIndices[oldIndex2]; const ui_pair& new3 = newIndices[oldIndex3]; // 3 non-negative if (s1 != Side::Negative && s2 != Side::Negative && s3 != Side::Negative) { MeshUtil::addFace (m, new1.first, new2.first, new3.first); MeshUtil::addFace (m, new3.second, new2.second, new1.second); } // 1 negative - 2 positive else if (s1 == Side::Positive && s2 == Side::Positive && s3 == Side::Negative) { unsigned int b1 = newBorderVertex (oldIndex1, oldIndex3); unsigned int b2 = newBorderVertex (oldIndex2, oldIndex3); MeshUtil::addFace (m, new2.first, b2, new1.first); MeshUtil::addFace (m, new1.second, b2, new2.second); MeshUtil::addFace (m, new1.first, b2, b1); MeshUtil::addFace (m, b1, b2, new1.second); } else if (s1 == Side::Positive && s2 == Side::Negative && s3 == Side::Positive) { unsigned int b1 = newBorderVertex (oldIndex1, oldIndex2); unsigned int b2 = newBorderVertex (oldIndex2, oldIndex3); MeshUtil::addFace (m, new1.first, b1, new3.first); MeshUtil::addFace (m, new3.second, b1, new1.second); MeshUtil::addFace (m, new3.first, b1, b2); MeshUtil::addFace (m, b2, b1, new3.second); } else if (s1 == Side::Negative && s2 == Side::Positive && s3 == Side::Positive) { unsigned int b1 = newBorderVertex (oldIndex1, oldIndex2); unsigned int b2 = newBorderVertex (oldIndex1, oldIndex3); MeshUtil::addFace (m, new3.first, b2, new2.first); MeshUtil::addFace (m, new2.second, b2, new3.second); MeshUtil::addFace (m, new2.first, b2, b1); MeshUtil::addFace (m, b1, b2, new2.second); } // 1 positive - 2 negative else if (s1 == Side::Positive && s2 == Side::Negative && s3 == Side::Negative) { unsigned int b1 = newBorderVertex (oldIndex1, oldIndex2); unsigned int b2 = newBorderVertex (oldIndex1, oldIndex3); MeshUtil::addFace (m, new1.first, b1, b2); MeshUtil::addFace (m, b2, b1, new1.second); } else if (s1 == Side::Negative && s2 == Side::Positive && s3 == Side::Negative) { unsigned int b1 = newBorderVertex (oldIndex1, oldIndex2); unsigned int b2 = newBorderVertex (oldIndex2, oldIndex3); MeshUtil::addFace (m, new2.first, b2, b1); MeshUtil::addFace (m, b1, b2, new2.second); } else if (s1 == Side::Negative && s2 == Side::Negative && s3 == Side::Positive) { unsigned int b1 = newBorderVertex (oldIndex1, oldIndex3); unsigned int b2 = newBorderVertex (oldIndex2, oldIndex3); MeshUtil::addFace (m, new3.first, b1, b2); MeshUtil::addFace (m, b2, b1, new3.second); } // 1 positive - 1 border - 1 negative else if (s1 == Side::Positive && s2 == Side::Border && s3 == Side::Negative) { assert (borderFlags[oldIndex2] == BorderFlag::ConnectsBoth); unsigned int b = newBorderVertex (oldIndex1, oldIndex3); MeshUtil::addFace (m, new1.first, new2.first, b); MeshUtil::addFace (m, b, new2.second, new1.second); } else if (s1 == Side::Border && s2 == Side::Positive && s3 == Side::Negative) { assert (borderFlags[oldIndex1] == BorderFlag::ConnectsBoth); unsigned int b = newBorderVertex (oldIndex2, oldIndex3); MeshUtil::addFace (m, new1.first, new2.first, b); MeshUtil::addFace (m, b, new2.second, new1.second); } else if (s1 == Side::Positive && s2 == Side::Negative && s3 == Side::Border) { assert (borderFlags[oldIndex3] == BorderFlag::ConnectsBoth); unsigned int b = newBorderVertex (oldIndex1, oldIndex2); MeshUtil::addFace (m, new1.first, b, new3.first); MeshUtil::addFace (m, new3.second, b, new1.second); } else if (s1 == Side::Border && s2 == Side::Negative && s3 == Side::Positive) { assert (borderFlags[oldIndex1] == BorderFlag::ConnectsBoth); unsigned int b = newBorderVertex (oldIndex2, oldIndex3); MeshUtil::addFace (m, new1.first, b, new3.first); MeshUtil::addFace (m, new3.second, b, new1.second); } else if (s1 == Side::Negative && s2 == Side::Positive && s3 == Side::Border) { assert (borderFlags[oldIndex3] == BorderFlag::ConnectsBoth); unsigned int b = newBorderVertex (oldIndex1, oldIndex2); MeshUtil::addFace (m, new2.first, new3.first, b); MeshUtil::addFace (m, b, new3.second, new2.second); } else if (s1 == Side::Negative && s2 == Side::Border && s3 == Side::Positive) { assert (borderFlags[oldIndex2] == BorderFlag::ConnectsBoth); unsigned int b = newBorderVertex (oldIndex1, oldIndex3); MeshUtil::addFace (m, new2.first, new3.first, b); MeshUtil::addFace (m, b, new3.second, new2.second); } else { DILAY_IMPOSSIBLE } } } if (MeshUtil::checkConsistency (m) == false) { m.reset (); } return m; } void MeshUtil::mirror (Mesh& mesh, const PrimPlane& plane) { for (unsigned int i = 0; i < mesh.numVertices (); i++) { mesh.vertex (i, plane.mirror (mesh.vertex (i))); mesh.normal (i, plane.mirrorDirection (mesh.normal (i))); } assert (mesh.numIndices () % 3 == 0); for (unsigned int i = 0; i < mesh.numIndices (); i += 3) { const unsigned int i2 = mesh.index (i + 1); const unsigned int i3 = mesh.index (i + 2); mesh.index (i + 1, i3); mesh.index (i + 2, i2); } } void MeshUtil::moveToCenter (Mesh& mesh) { const PrimAABox bounds = mesh.bounds (); mesh.translate (-bounds.center ()); mesh.normalize (); } void MeshUtil::normalizeScaling (Mesh& mesh) { const PrimAABox bounds = mesh.bounds (); const glm::vec3& center = bounds.center (); const float factor = 2.0f / bounds.maxDimExtent (); for (unsigned int i = 0; i < mesh.numVertices (); i++) { const glm::vec3& v = mesh.vertex (i); mesh.vertex (i, (factor * (v - center)) + center); } } bool MeshUtil::checkConsistency (const Mesh& mesh) { if (mesh.numVertices () == 0) { DILAY_WARN ("empty mesh"); return false; } EdgeMap numEdgeAdjacentFaces (mesh.numVertices ()); std::vector numVertexAdjacentFaces; numVertexAdjacentFaces.resize (mesh.numVertices (), 0); for (unsigned int i = 0; i < mesh.numIndices (); i += 3) { const unsigned int i1 = mesh.index (i + 0); const unsigned int i2 = mesh.index (i + 1); const unsigned int i3 = mesh.index (i + 2); numVertexAdjacentFaces[i1]++; numVertexAdjacentFaces[i2]++; numVertexAdjacentFaces[i3]++; numEdgeAdjacentFaces.increase (i1, i2); numEdgeAdjacentFaces.increase (i1, i3); numEdgeAdjacentFaces.increase (i2, i3); } for (unsigned int v = 0; v < numVertexAdjacentFaces.size (); v++) { if (numVertexAdjacentFaces[v] < 3) { DILAY_WARN ("inconsistent vertex %u with %u adjacent faces", v, numVertexAdjacentFaces[v]); return false; } } for (unsigned int i = 0; i < numEdgeAdjacentFaces.elements.size (); i++) { for (const auto& pair : numEdgeAdjacentFaces.elements[i]) { const unsigned int j = pair.first; const unsigned int value = pair.second; if (value != 2) { DILAY_WARN ("inconsistent edge (%u,%u) with %u adjacent faces", i, j, value); return false; } } } return true; } ================================================ FILE: lib/src/mesh-util.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_MESH_UTIL #define DILAY_MESH_UTIL class Mesh; class PrimPlane; namespace MeshUtil { void addFace (Mesh&, unsigned int, unsigned int, unsigned int); void addFace (Mesh&, unsigned int, unsigned int, unsigned int, unsigned int); Mesh cube (unsigned int); Mesh sphere (unsigned int, unsigned int); Mesh icosphere (unsigned int); Mesh cone (unsigned int); Mesh cylinder (unsigned int); Mesh mirrorPositive (const Mesh&, const PrimPlane&); void mirror (Mesh&, const PrimPlane&); void moveToCenter (Mesh&); void normalizeScaling (Mesh&); bool checkConsistency (const Mesh&); }; #endif ================================================ FILE: lib/src/mesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include "camera.hpp" #include "color.hpp" #include "mesh.hpp" #include "opengl-buffer-id.hpp" #include "opengl.hpp" #include "primitive/aabox.hpp" #include "render-mode.hpp" #include "renderer.hpp" #include "util.hpp" namespace { static_assert (sizeof (glm::vec3) == 3 * sizeof (float), "Unexpected memory layout"); template struct BufferedData { OpenGLBufferId id; std::vector data; unsigned int dataLowerBound; unsigned int dataUpperBound; unsigned int bufferSize; BufferedData () { this->reset (); } void reset () { this->id.reset (); this->data.clear (); this->resetBounds (); this->bufferSize = 0; } void resetBounds () { this->dataLowerBound = Util::maxUnsignedInt (); this->dataUpperBound = 0; } unsigned int numElements () const { return this->data.size (); } void reserve (unsigned int size) { this->data.reserve (size); } void shrink (unsigned int n) { assert (n <= this->numElements ()); this->data.resize (n); this->dataLowerBound = 0; this->dataUpperBound = n > 0 ? n - 1 : 0; } void updateBounds (unsigned int index) { this->dataLowerBound = glm::min (this->dataLowerBound, index); this->dataUpperBound = glm::max (this->dataUpperBound, index); } unsigned int add (const T& value) { this->data.push_back (value); this->updateBounds (this->numElements () - 1); return this->numElements () - 1; } void set (unsigned int index, const T& value) { assert (index < this->numElements ()); this->data[index] = value; this->updateBounds (index); } const T& get (unsigned int index) const { assert (index < this->numElements ()); return this->data[index]; } void bufferData (unsigned int target) { if (this->id.isValid () == false) { this->id.allocate (); this->bufferSize = 0; } OpenGL::glBindBuffer (target, this->id.id ()); const unsigned int dataSize = this->numElements () * sizeof (T); if (this->bufferSize == 0) { OpenGL::glBufferData (target, dataSize, this->data.data (), OpenGL::StaticDraw ()); this->bufferSize = dataSize; } else if (this->bufferSize < dataSize) { const unsigned int newBufferSize = this->bufferSize + (100 * (dataSize - this->bufferSize)); OpenGL::glBufferData (target, newBufferSize, nullptr, OpenGL::StaticDraw ()); OpenGL::glBufferSubData (target, 0, dataSize, this->data.data ()); this->bufferSize = newBufferSize; } else if (this->dataLowerBound <= this->dataUpperBound) { const unsigned int size = (this->dataUpperBound - this->dataLowerBound + 1) * sizeof (T); OpenGL::glBufferSubData (target, this->dataLowerBound * sizeof (T), size, &this->get (this->dataLowerBound)); } this->resetBounds (); } }; } struct Mesh::Impl { // cf. copy-constructor, reset glm::mat4x4 scalingMatrix; glm::mat4x4 rotationMatrix; glm::mat4x4 translationMatrix; BufferedData vertices; BufferedData indices; BufferedData normals; Color color; Color wireframeColor; RenderMode renderMode; Impl () : scalingMatrix (glm::mat4x4 (1.0f)) , rotationMatrix (glm::mat4x4 (1.0f)) , translationMatrix (glm::mat4x4 (1.0f)) , color (Color::White ()) , wireframeColor (Color::Black ()) { this->renderMode.smoothShading (true); } unsigned int numVertices () const { return this->vertices.numElements (); } unsigned int numIndices () const { return this->indices.numElements (); } const glm::vec3& vertex (unsigned int i) const { return this->vertices.get (i); } unsigned int index (unsigned int i) const { return this->indices.get (i); } const glm::vec3& normal (unsigned int i) const { return this->normals.get (i); } void copyNonGeometry (const Mesh& source) { this->scalingMatrix = source.impl->scalingMatrix; this->rotationMatrix = source.impl->rotationMatrix; this->translationMatrix = source.impl->translationMatrix; this->color = source.impl->color; this->wireframeColor = source.impl->wireframeColor; this->renderMode = source.impl->renderMode; } unsigned int addIndex (unsigned int i) { return this->indices.add (i); } void reserveIndices (unsigned int n) { this->indices.reserve (n); } void shrinkIndices (unsigned int n) { this->indices.shrink (n); } unsigned int addVertex (const glm::vec3& v) { return this->addVertex (v, glm::vec3 (0.0f)); } unsigned int addVertex (const glm::vec3& v, const glm::vec3& n) { assert (Util::isNaN (v) == false); assert (Util::isNaN (n) == false); assert (this->vertices.numElements () == this->normals.numElements ()); this->vertices.add (v); return this->normals.add (n); } void reserveVertices (unsigned int n) { this->vertices.reserve (n); this->normals.reserve (n); } void shrinkVertices (unsigned int n) { this->vertices.shrink (n); this->normals.shrink (n); } void index (unsigned int i, unsigned int index) { this->indices.set (i, index); } void vertex (unsigned int i, const glm::vec3& v) { assert (Util::isNaN (v) == false); this->vertices.set (i, v); } void normal (unsigned int i, const glm::vec3& n) { assert (Util::isNaN (n) == false); this->normals.set (i, n); } void bufferData () { this->vertices.bufferData (OpenGL::ArrayBuffer ()); this->indices.bufferData (OpenGL::ElementArrayBuffer ()); this->normals.bufferData (OpenGL::ArrayBuffer ()); OpenGL::glBindBuffer (OpenGL::ElementArrayBuffer (), 0); OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), 0); } glm::mat4x4 modelMatrix () const { return this->translationMatrix * this->rotationMatrix * this->scalingMatrix; } glm::mat3x3 modelNormalMatrix () const { return glm::inverseTranspose (glm::mat3x3 (this->modelMatrix ())); } void setModelMatrix (Camera& camera, bool noZoom) const { camera.setModelViewProjection (this->modelMatrix (), this->modelNormalMatrix (), noZoom); } void renderBegin (Camera& camera) const { if (this->renderMode.renderWireframe () && OpenGL::hasGeometryShader () == false) { RenderMode nonWireframeRenderMode (this->renderMode); nonWireframeRenderMode.renderWireframe (false); camera.renderer ().setProgram (nonWireframeRenderMode); } else { camera.renderer ().setProgram (this->renderMode); } camera.renderer ().setColor (this->color); camera.renderer ().setWireframeColor (this->wireframeColor); this->setModelMatrix (camera, this->renderMode.cameraRotationOnly ()); OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), this->vertices.id.id ()); OpenGL::glEnableVertexAttribArray (OpenGL::PositionIndex); OpenGL::glVertexAttribPointer (OpenGL::PositionIndex, 3, OpenGL::Float (), false, 0, 0); OpenGL::glBindBuffer (OpenGL::ElementArrayBuffer (), this->indices.id.id ()); if (this->renderMode.smoothShading ()) { OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), this->normals.id.id ()); OpenGL::glEnableVertexAttribArray (OpenGL::NormalIndex); OpenGL::glVertexAttribPointer (OpenGL::NormalIndex, 3, OpenGL::Float (), false, 0, 0); } OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), 0); if (this->renderMode.noDepthTest ()) { OpenGL::glDisable (OpenGL::DepthTest ()); } } void renderEnd () const { OpenGL::glDisableVertexAttribArray (OpenGL::PositionIndex); OpenGL::glDisableVertexAttribArray (OpenGL::NormalIndex); OpenGL::glBindBuffer (OpenGL::ArrayBuffer (), 0); OpenGL::glBindBuffer (OpenGL::ElementArrayBuffer (), 0); OpenGL::glEnable (OpenGL::DepthTest ()); } void render (Camera& camera) const { this->renderBegin (camera); OpenGL::glDrawElements (OpenGL::Triangles (), this->numIndices (), OpenGL::UnsignedInt (), nullptr); if (this->renderMode.renderWireframe () && OpenGL::hasGeometryShader () == false) { camera.renderer ().setColor (this->wireframeColor); OpenGL::glPolygonMode (OpenGL::FrontAndBack (), OpenGL::Line ()); OpenGL::glDrawElements (OpenGL::Triangles (), this->numIndices (), OpenGL::UnsignedInt (), nullptr); OpenGL::glPolygonMode (OpenGL::FrontAndBack (), OpenGL::Fill ()); } this->renderEnd (); } void renderLines (Camera& camera) const { this->renderBegin (camera); OpenGL::glDrawElements (OpenGL::Lines (), this->numIndices (), OpenGL::UnsignedInt (), nullptr); this->renderEnd (); } void reset () { this->scalingMatrix = glm::mat4x4 (1.0f); this->rotationMatrix = glm::mat4x4 (1.0f); this->translationMatrix = glm::mat4x4 (1.0f); this->resetGeometry (); } void resetGeometry () { this->vertices.reset (); this->indices.reset (); this->normals.reset (); } void scale (const glm::vec3& v) { this->scalingMatrix = glm::scale (this->scalingMatrix, v); } void scaling (const glm::vec3& v) { this->scalingMatrix = glm::scale (glm::mat4x4 (1.0f), v); } glm::vec3 scaling () const { return glm::vec3 (this->scalingMatrix[0][0], this->scalingMatrix[1][1], this->scalingMatrix[2][2]); } void translate (const glm::vec3& v) { this->translationMatrix = glm::translate (this->translationMatrix, v); } void position (const glm::vec3& v) { this->translationMatrix = glm::translate (glm::mat4x4 (1.0f), v); } glm::vec3 position () const { return glm::vec3 (this->translationMatrix[3][0], this->translationMatrix[3][1], this->translationMatrix[3][2]); } void rotation (const glm::vec3& axis, float angle) { this->rotationMatrix = glm::rotate (glm::mat4x4 (1.0f), angle, axis); } void rotationX (float angle) { this->rotation (glm::vec3 (1.0f, 0.0f, 0.0f), angle); } void rotationY (float angle) { this->rotation (glm::vec3 (0.0f, 1.0f, 0.0f), angle); } void rotationZ (float angle) { this->rotation (glm::vec3 (0.0f, 0.0f, 1.0f), angle); } void rotate (const glm::mat4x4& matrix) { this->rotationMatrix = matrix * this->rotationMatrix; } void rotate (const glm::vec3& axis, float angle) { this->rotationMatrix = glm::rotate (this->rotationMatrix, angle, axis); } void rotateX (float angle) { this->rotate (glm::vec3 (1.0f, 0.0f, 0.0f), angle); } void rotateY (float angle) { this->rotate (glm::vec3 (0.0f, 1.0f, 0.0f), angle); } void rotateZ (float angle) { this->rotate (glm::vec3 (0.0f, 0.0f, 1.0f), angle); } void normalize () { const glm::mat4x4 model = this->modelMatrix (); const glm::mat3x3 modelNormal = this->modelNormalMatrix (); for (unsigned int i = 0; i < this->numVertices (); i++) { this->vertex (i, Util::transformPosition (model, this->vertex (i))); if (Util::isNotNull (this->normal (i))) { this->normal (i, glm::normalize (modelNormal * this->normal (i))); } } this->position (glm::vec3 (0.0f)); this->scaling (glm::vec3 (1.0f)); this->rotationMatrix = glm::mat4x4 (1.0f); } PrimAABox bounds () const { glm::vec3 min = glm::vec3 (Util::maxFloat ()); glm::vec3 max = glm::vec3 (Util::minFloat ()); for (unsigned int i = 0; i < this->numVertices (); i++) { min = glm::min (min, this->vertices.get (i)); max = glm::max (max, this->vertices.get (i)); } return PrimAABox (min, max); } }; DELEGATE_BIG6 (Mesh) DELEGATE_CONST (unsigned int, Mesh, numVertices) DELEGATE_CONST (unsigned int, Mesh, numIndices) DELEGATE1_CONST (const glm::vec3&, Mesh, vertex, unsigned int) DELEGATE1_CONST (unsigned int, Mesh, index, unsigned int) DELEGATE1_CONST (const glm::vec3&, Mesh, normal, unsigned int) DELEGATE1 (void, Mesh, copyNonGeometry, const Mesh&) DELEGATE1 (unsigned int, Mesh, addIndex, unsigned int) DELEGATE1 (void, Mesh, reserveIndices, unsigned int) DELEGATE1 (void, Mesh, shrinkIndices, unsigned int) DELEGATE1 (unsigned int, Mesh, addVertex, const glm::vec3&) DELEGATE2 (unsigned int, Mesh, addVertex, const glm::vec3&, const glm::vec3&) DELEGATE1 (void, Mesh, reserveVertices, unsigned int) DELEGATE1 (void, Mesh, shrinkVertices, unsigned int) DELEGATE2 (void, Mesh, index, unsigned int, unsigned int) DELEGATE2 (void, Mesh, vertex, unsigned int, const glm::vec3&) DELEGATE2 (void, Mesh, normal, unsigned int, const glm::vec3&) DELEGATE (void, Mesh, bufferData) DELEGATE_CONST (glm::mat4x4, Mesh, modelMatrix) DELEGATE_CONST (glm::mat3x3, Mesh, modelNormalMatrix) DELEGATE1_CONST (void, Mesh, renderBegin, Camera&) DELEGATE_CONST (void, Mesh, renderEnd) DELEGATE1_CONST (void, Mesh, render, Camera&) DELEGATE1_CONST (void, Mesh, renderLines, Camera&) DELEGATE (void, Mesh, reset) DELEGATE (void, Mesh, resetGeometry) GETTER_CONST (const RenderMode&, Mesh, renderMode) GETTER (RenderMode&, Mesh, renderMode) DELEGATE1 (void, Mesh, scale, const glm::vec3&) DELEGATE1 (void, Mesh, scaling, const glm::vec3&) DELEGATE_CONST (glm::vec3, Mesh, scaling) DELEGATE1 (void, Mesh, translate, const glm::vec3&) DELEGATE1 (void, Mesh, position, const glm::vec3&) DELEGATE_CONST (glm::vec3, Mesh, position) SETTER (const glm::mat4x4&, Mesh, rotationMatrix) GETTER_CONST (const glm::mat4x4&, Mesh, rotationMatrix) DELEGATE2 (void, Mesh, rotation, const glm::vec3&, float) DELEGATE1 (void, Mesh, rotationX, float) DELEGATE1 (void, Mesh, rotationY, float) DELEGATE1 (void, Mesh, rotationZ, float) DELEGATE1 (void, Mesh, rotate, const glm::mat4x4&) DELEGATE2 (void, Mesh, rotate, const glm::vec3&, float) DELEGATE1 (void, Mesh, rotateX, float) DELEGATE1 (void, Mesh, rotateY, float) DELEGATE1 (void, Mesh, rotateZ, float) DELEGATE (void, Mesh, normalize) DELEGATE_CONST (PrimAABox, Mesh, bounds) GETTER_CONST (const Color&, Mesh, color) SETTER (const Color&, Mesh, color) GETTER_CONST (const Color&, Mesh, wireframeColor) SETTER (const Color&, Mesh, wireframeColor) ================================================ FILE: lib/src/mesh.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_MESH #define DILAY_MESH #include #include "macro.hpp" class Camera; class Color; class PrimAABox; class RenderFlags; class RenderMode; class Mesh { public: DECLARE_BIG6 (Mesh) unsigned int numVertices () const; unsigned int numIndices () const; const glm::vec3& vertex (unsigned int) const; unsigned int index (unsigned int) const; const glm::vec3& normal (unsigned int) const; void copyNonGeometry (const Mesh&); unsigned int addIndex (unsigned int); void reserveIndices (unsigned int); void shrinkIndices (unsigned int); unsigned int addVertex (const glm::vec3&); unsigned int addVertex (const glm::vec3&, const glm::vec3&); void reserveVertices (unsigned int); void shrinkVertices (unsigned int); void index (unsigned int, unsigned int); void vertex (unsigned int, const glm::vec3&); void normal (unsigned int, const glm::vec3&); void bufferData (); glm::mat4x4 modelMatrix () const; glm::mat3x3 modelNormalMatrix () const; void renderBegin (Camera&) const; void renderEnd () const; void render (Camera&) const; void renderLines (Camera&) const; void reset (); void resetGeometry (); const RenderMode& renderMode () const; RenderMode& renderMode (); void scale (const glm::vec3&); void scaling (const glm::vec3&); glm::vec3 scaling () const; void translate (const glm::vec3&); void position (const glm::vec3&); glm::vec3 position () const; void rotationMatrix (const glm::mat4x4&); const glm::mat4x4& rotationMatrix () const; void rotation (const glm::vec3&, float); void rotationX (float); void rotationY (float); void rotationZ (float); void rotate (const glm::mat4x4&); void rotate (const glm::vec3&, float); void rotateX (float); void rotateY (float); void rotateZ (float); void normalize (); PrimAABox bounds () const; const Color& color () const; void color (const Color&); const Color& wireframeColor () const; void wireframeColor (const Color&); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/mirror.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "camera.hpp" #include "color.hpp" #include "config.hpp" #include "dimension.hpp" #include "mesh-util.hpp" #include "mesh.hpp" #include "mirror.hpp" #include "opengl.hpp" #include "primitive/plane.hpp" #include "render-mode.hpp" struct Mirror::Impl { Dimension _dimension; float width; Mesh mirrorMesh; std::unique_ptr _plane; Impl (const Config& config, Dimension d) : _dimension (d) , width (1.0f) { this->mirrorMesh = MeshUtil::cube (0); this->mirrorMesh.renderMode ().constantShading (true); this->mirrorMesh.bufferData (); this->runFromConfig (config); this->dimension (d); } Dimension dimension () const { return this->_dimension; } void dimension (Dimension d) { this->_dimension = d; this->_plane = std::make_unique (glm::vec3 (0.0f), DimensionUtil::vector (d)); } void position (const glm::vec3& p) { this->_plane = std::make_unique (glm::vec3 (p), DimensionUtil::vector (this->_dimension)); this->mirrorMesh.position (p); } const PrimPlane& plane () const { return *this->_plane; } void render (Camera& camera) const { const glm::vec3 pos = camera.position (); const float width2 = this->width * 0.5f; const bool inside = (this->_dimension == Dimension::X && glm::abs (pos.x - this->_plane->point ().x) <= width2) || (this->_dimension == Dimension::Y && glm::abs (pos.y - this->_plane->point ().y) <= width2) || (this->_dimension == Dimension::Z && glm::abs (pos.z - this->_plane->point ().z) <= width2); OpenGL::glClear (OpenGL::StencilBufferBit ()); OpenGL::glDepthMask (false); OpenGL::glEnable (OpenGL::StencilTest ()); OpenGL::glColorMask (false, false, false, false); OpenGL::glCullFace (OpenGL::Front ()); OpenGL::glEnable (OpenGL::StencilTest ()); OpenGL::glStencilFunc (OpenGL::Always (), 1, 255); OpenGL::glStencilOp (OpenGL::Keep (), OpenGL::Replace (), OpenGL::Keep ()); this->mirrorMesh.render (camera); if (inside) { OpenGL::glDisable (OpenGL::DepthTest ()); } else { OpenGL::glCullFace (OpenGL::Back ()); } OpenGL::glColorMask (true, true, true, true); OpenGL::glStencilFunc (OpenGL::Equal (), 1, 255); OpenGL::glStencilOp (OpenGL::Keep (), OpenGL::Keep (), OpenGL::Keep ()); OpenGL::glEnable (OpenGL::Blend ()); OpenGL::glBlendEquation (OpenGL::FuncAdd ()); OpenGL::glBlendFunc (OpenGL::DstColor (), OpenGL::Zero ()); this->mirrorMesh.render (camera); OpenGL::glDisable (OpenGL::Blend ()); if (inside) { OpenGL::glCullFace (OpenGL::Back ()); OpenGL::glEnable (OpenGL::DepthTest ()); } OpenGL::glDisable (OpenGL::StencilTest ()); OpenGL::glDepthMask (true); } void updateMesh () { const float extent = 1000.0f; switch (this->_dimension) { case Dimension::X: this->mirrorMesh.scaling (glm::vec3 (this->width, extent, extent)); break; case Dimension::Y: this->mirrorMesh.scaling (glm::vec3 (extent, this->width, extent)); break; case Dimension::Z: this->mirrorMesh.scaling (glm::vec3 (extent, extent, this->width)); break; } } void runFromConfig (const Config& config) { this->width = config.get ("editor/tool/sculpt/mirror/width"); this->mirrorMesh.color (config.get ("editor/tool/sculpt/mirror/color")); this->updateMesh (); } }; DELEGATE2_BIG2 (Mirror, const Config&, Dimension) DELEGATE_CONST (Dimension, Mirror, dimension) GETTER_CONST (float, Mirror, width) DELEGATE1 (void, Mirror, dimension, Dimension) DELEGATE1 (void, Mirror, position, const glm::vec3&) DELEGATE_CONST (const PrimPlane&, Mirror, plane) DELEGATE1_CONST (void, Mirror, render, Camera&) DELEGATE1 (void, Mirror, runFromConfig, const Config&) ================================================ FILE: lib/src/mirror.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_MIRROR #define DILAY_MIRROR #include #include "configurable.hpp" #include "macro.hpp" class Camera; enum class Dimension; class PrimPlane; class Mirror : public Configurable { public: DECLARE_BIG2 (Mirror, const Config&, Dimension) Dimension dimension () const; float width () const; const PrimPlane& plane () const; void dimension (Dimension); void position (const glm::vec3&); void render (Camera&) const; private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/opengl-buffer-id.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "opengl-buffer-id.hpp" #include "opengl.hpp" OpenGLBufferId::OpenGLBufferId () : _id (0) { } OpenGLBufferId::OpenGLBufferId (const OpenGLBufferId&) : OpenGLBufferId () { } OpenGLBufferId::OpenGLBufferId (OpenGLBufferId&& other) : _id (other._id) { } const OpenGLBufferId& OpenGLBufferId::operator= (const OpenGLBufferId&) { return *this; } const OpenGLBufferId& OpenGLBufferId::operator= (OpenGLBufferId&& other) { this->_id = other._id; return *this; } OpenGLBufferId::~OpenGLBufferId () { this->reset (); } unsigned int OpenGLBufferId::id () const { return this->_id; } bool OpenGLBufferId::isValid () const { return this->_id > 0; } void OpenGLBufferId::allocate () { assert (this->isValid () == false); OpenGL::glGenBuffers (1, &this->_id); assert (this->isValid ()); } void OpenGLBufferId::reset () { if (this->isValid ()) { OpenGL::safeDeleteBuffer (this->_id); } } ================================================ FILE: lib/src/opengl-buffer-id.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_OPENGL_BUFFER_ID #define DILAY_OPENGL_BUFFER_ID #include "macro.hpp" class OpenGLBufferId { public: DECLARE_BIG6 (OpenGLBufferId) unsigned int id () const; bool isValid () const; void allocate (); void reset (); private: unsigned int _id; }; #endif ================================================ FILE: lib/src/opengl.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include #include "log.hpp" #include "opengl.hpp" #include "shader.hpp" #include "util.hpp" #define DELEGATE_GL_CONSTANT(method, constant) \ unsigned int method () { return constant; } #define DELEGATE_GL(r, method) \ r method () { return fun->method (); } #define DELEGATE1_GL(r, method, t1) \ r method (t1 a1) { return fun->method (a1); } #define DELEGATE2_GL(r, method, t1, t2) \ r method (t1 a1, t2 a2) { return fun->method (a1, a2); } #define DELEGATE3_GL(r, method, t1, t2, t3) \ r method (t1 a1, t2 a2, t3 a3) { return fun->method (a1, a2, a3); } #define DELEGATE4_GL(r, method, t1, t2, t3, t4) \ r method (t1 a1, t2 a2, t3 a3, t4 a4) { return fun->method (a1, a2, a3, a4); } #define DELEGATE5_GL(r, method, t1, t2, t3, t4, t5) \ r method (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) { return fun->method (a1, a2, a3, a4, a5); } #define DELEGATE6_GL(r, method, t1, t2, t3, t4, t5, t6) \ r method (t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6) \ { \ return fun->method (a1, a2, a3, a4, a5, a6); \ } namespace OpenGL { static_assert (sizeof (unsigned int) >= 4, "type does not meet size required by OpenGL"); static_assert (sizeof (int) >= 4, "type does not meet size required by OpenGL"); static_assert (sizeof (float) >= 4, "type does not meet size required by OpenGL"); static QOpenGLFunctions_2_1* fun = nullptr; static std::unique_ptr gsFun; void setDefaultFormat () { QSurfaceFormat format; format.setVersion (2, 1); format.setDepthBufferSize (24); format.setStencilBufferSize (1); format.setProfile (QSurfaceFormat::NoProfile); format.setRenderableType (QSurfaceFormat::OpenGL); QSurfaceFormat::setDefaultFormat (format); } void initializeFunctions (bool initGeometryShader) { fun = QOpenGLContext::currentContext ()->versionFunctions (); if (fun == nullptr) { DILAY_PANIC ("could not obtain OpenGL 2.1 context") } fun->initializeOpenGLFunctions (); if (initGeometryShader) { const bool support = QOpenGLContext::currentContext ()->hasExtension (QByteArray ("GL_EXT_geometry_shader4")); if (support) { gsFun = std::make_unique (); if (gsFun == nullptr) { DILAY_PANIC ("could not initialize GL_EXT_geometry_shader4 extension") } gsFun->initializeOpenGLFunctions (); } } DILAY_INFO ("OpenGL version: %s", fun->glGetString (GL_VERSION)); DILAY_INFO ("OpenGL vendor: %s", fun->glGetString (GL_VENDOR)); DILAY_INFO ("OpenGL renderer: %s", fun->glGetString (GL_RENDERER)); DILAY_INFO ("OpenGL GLSL version: %s", fun->glGetString (GL_SHADING_LANGUAGE_VERSION)); DILAY_INFO ("OpenGL supports GL_EXT_geometry_shader4: %i", gsFun != nullptr); } DELEGATE_GL_CONSTANT (Always, GL_ALWAYS); DELEGATE_GL_CONSTANT (ArrayBuffer, GL_ARRAY_BUFFER); DELEGATE_GL_CONSTANT (Back, GL_BACK); DELEGATE_GL_CONSTANT (Blend, GL_BLEND); DELEGATE_GL_CONSTANT (BufferSize, GL_BUFFER_SIZE); DELEGATE_GL_CONSTANT (ColorBufferBit, GL_COLOR_BUFFER_BIT); DELEGATE_GL_CONSTANT (CullFace, GL_CULL_FACE); DELEGATE_GL_CONSTANT (CW, GL_CW); DELEGATE_GL_CONSTANT (CCW, GL_CCW); DELEGATE_GL_CONSTANT (Decr, GL_DECR); DELEGATE_GL_CONSTANT (DecrWrap, GL_DECR_WRAP); DELEGATE_GL_CONSTANT (DepthBufferBit, GL_DEPTH_BUFFER_BIT); DELEGATE_GL_CONSTANT (DepthTest, GL_DEPTH_TEST); DELEGATE_GL_CONSTANT (DstColor, GL_DST_COLOR); DELEGATE_GL_CONSTANT (ElementArrayBuffer, GL_ELEMENT_ARRAY_BUFFER); DELEGATE_GL_CONSTANT (Equal, GL_EQUAL); DELEGATE_GL_CONSTANT (Fill, GL_FILL); DELEGATE_GL_CONSTANT (Float, GL_FLOAT); DELEGATE_GL_CONSTANT (Front, GL_FRONT); DELEGATE_GL_CONSTANT (FrontAndBack, GL_FRONT_AND_BACK); DELEGATE_GL_CONSTANT (FuncAdd, GL_FUNC_ADD); DELEGATE_GL_CONSTANT (Greater, GL_GREATER); DELEGATE_GL_CONSTANT (Incr, GL_INCR); DELEGATE_GL_CONSTANT (IncrWrap, GL_INCR_WRAP); DELEGATE_GL_CONSTANT (Invert, GL_INVERT); DELEGATE_GL_CONSTANT (Keep, GL_KEEP); DELEGATE_GL_CONSTANT (LEqual, GL_LEQUAL); DELEGATE_GL_CONSTANT (Line, GL_LINE); DELEGATE_GL_CONSTANT (Lines, GL_LINES); DELEGATE_GL_CONSTANT (Never, GL_NEVER); DELEGATE_GL_CONSTANT (PolygonOffsetFill, GL_POLYGON_OFFSET_FILL); DELEGATE_GL_CONSTANT (Replace, GL_REPLACE); DELEGATE_GL_CONSTANT (StaticDraw, GL_STATIC_DRAW); DELEGATE_GL_CONSTANT (StencilBufferBit, GL_STENCIL_BUFFER_BIT); DELEGATE_GL_CONSTANT (StencilTest, GL_STENCIL_TEST); DELEGATE_GL_CONSTANT (Triangles, GL_TRIANGLES); DELEGATE_GL_CONSTANT (UnsignedInt, GL_UNSIGNED_INT); DELEGATE_GL_CONSTANT (Zero, GL_ZERO); DELEGATE2_GL (void, glBindBuffer, unsigned int, unsigned int) DELEGATE1_GL (void, glBlendEquation, unsigned int) DELEGATE2_GL (void, glBlendFunc, unsigned int, unsigned int) DELEGATE4_GL (void, glBufferData, unsigned int, unsigned int, const void*, unsigned int) DELEGATE4_GL (void, glBufferSubData, unsigned int, unsigned int, unsigned int, const void*) DELEGATE1_GL (void, glClear, unsigned int) DELEGATE4_GL (void, glClearColor, float, float, float, float) DELEGATE1_GL (void, glClearStencil, int) DELEGATE4_GL (void, glColorMask, bool, bool, bool, bool) DELEGATE1_GL (void, glCullFace, unsigned int) DELEGATE1_GL (void, glDepthFunc, unsigned int) DELEGATE1_GL (void, glDepthMask, bool) DELEGATE1_GL (void, glDisable, unsigned int) DELEGATE1_GL (void, glDisableVertexAttribArray, unsigned int) DELEGATE4_GL (void, glDrawElements, unsigned int, unsigned int, unsigned int, const void*) DELEGATE1_GL (void, glEnable, unsigned int) DELEGATE1_GL (void, glEnableVertexAttribArray, unsigned int) DELEGATE1_GL (void, glFrontFace, unsigned int) DELEGATE2_GL (void, glGenBuffers, unsigned int, unsigned int*) DELEGATE3_GL (void, glGetBufferParameteriv, unsigned int, unsigned int, int*) DELEGATE2_GL (int, glGetUniformLocation, unsigned int, const char*) DELEGATE1_GL (bool, glIsBuffer, unsigned int) DELEGATE1_GL (bool, glIsProgram, unsigned int) DELEGATE2_GL (void, glPolygonMode, unsigned int, unsigned int) DELEGATE2_GL (void, glPolygonOffset, float, float) DELEGATE3_GL (void, glStencilFunc, unsigned int, int, unsigned int) DELEGATE3_GL (void, glStencilOp, unsigned int, unsigned int, unsigned int) DELEGATE2_GL (void, glUniform1f, int, float) DELEGATE4_GL (void, glUniformMatrix3fv, int, unsigned int, bool, const float*) DELEGATE4_GL (void, glUniformMatrix4fv, int, unsigned int, bool, const float*) DELEGATE1_GL (void, glUseProgram, unsigned int) DELEGATE6_GL (void, glVertexAttribPointer, unsigned int, int, unsigned int, bool, unsigned int, const void*) DELEGATE4_GL (void, glViewport, unsigned int, unsigned int, unsigned int, unsigned int) bool hasGeometryShader () { return bool(gsFun); } void glUniformVec3 (unsigned int id, const glm::vec3& v) { fun->glUniform3f (id, v.x, v.y, v.z); } void glUniformVec4 (unsigned int id, const glm::vec4& v) { fun->glUniform4f (id, v.x, v.y, v.z, v.w); } void safeDeleteBuffer (unsigned int& id) { if (id > 0) { fun->glDeleteBuffers (1, &id); } id = 0; } void safeDeleteShader (unsigned int& id) { if (id > 0 && fun->glIsShader (id) == GL_TRUE) { fun->glDeleteShader (id); } id = 0; } void safeDeleteProgram (unsigned int& id) { if (id > 0 && fun->glIsProgram (id) == GL_TRUE) { GLsizei numShaders; GLuint shaderIds[2]; fun->glGetAttachedShaders (id, 2, &numShaders, shaderIds); for (GLsizei i = 0; i < numShaders; i++) { OpenGL::safeDeleteShader (shaderIds[i]); } fun->glDeleteProgram (id); } id = 0; } unsigned int loadProgram (const char* vertexShader, const char* fragmentShader, bool loadGeometryShader) { auto showInfoLog = [](GLuint id) { const int maxLogLength = 1000; char logBuffer[maxLogLength]; GLsizei logLength; fun->glGetShaderInfoLog (id, maxLogLength, &logLength, logBuffer); if (logLength > 0) { DILAY_WARN ("%s", logBuffer) } }; auto compileShader = [&showInfoLog](GLenum shaderType, const char* shaderSource) -> GLuint { GLuint shaderId = fun->glCreateShader (shaderType); fun->glShaderSource (shaderId, 1, &shaderSource, NULL); fun->glCompileShader (shaderId); GLint status; fun->glGetShaderiv (shaderId, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { showInfoLog (shaderId); DILAY_PANIC ("can not compile shader: see info log above") } return shaderId; }; GLuint programId = fun->glCreateProgram (); GLuint vsId = compileShader (GL_VERTEX_SHADER, vertexShader); GLuint fsId = compileShader (GL_FRAGMENT_SHADER, fragmentShader); GLuint gmId = 0; fun->glAttachShader (programId, vsId); fun->glAttachShader (programId, fsId); if (loadGeometryShader) { assert (OpenGL::hasGeometryShader ()); gmId = compileShader (GL_GEOMETRY_SHADER_EXT, Shader::geometryShader ()); fun->glAttachShader (programId, gmId); gsFun->glProgramParameteriEXT (programId, GL_GEOMETRY_VERTICES_OUT_EXT, 3); gsFun->glProgramParameteriEXT (programId, GL_GEOMETRY_INPUT_TYPE_EXT, GL_TRIANGLES); gsFun->glProgramParameteriEXT (programId, GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP); } fun->glBindAttribLocation (programId, OpenGL::PositionIndex, "position"); fun->glBindAttribLocation (programId, OpenGL::NormalIndex, "normal"); fun->glLinkProgram (programId); GLint status; fun->glGetProgramiv (programId, GL_LINK_STATUS, &status); if (status == GL_FALSE) { showInfoLog (programId); OpenGL::safeDeleteProgram (programId); DILAY_PANIC ("can not link shader program: see info log above") } OpenGL::safeDeleteShader (vsId); OpenGL::safeDeleteShader (fsId); OpenGL::safeDeleteShader (gmId); return programId; } void clearError () { fun->glGetError (); } void printError () { const unsigned int glError = fun->glGetError (); switch (glError) { case GL_NO_ERROR: std::cout << "GL_NO_ERROR\n"; break; case GL_INVALID_ENUM: std::cout << "GL_INVALID_ENUM\n"; break; case GL_INVALID_VALUE: std::cout << "GL_INVALID_VALUE\n"; break; case GL_INVALID_OPERATION: std::cout << "GL_INVALID_OPERATION\n"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: std::cout << "GL_INVALID_FRAMEBUFFER_OPERATION\n"; break; case GL_OUT_OF_MEMORY: std::cout << "GL_OUT_OF_MEMORY\n"; break; case GL_STACK_UNDERFLOW: std::cout << "GL_STACK_UNDERFLOW\n"; break; case GL_STACK_OVERFLOW: std::cout << "GL_STACK_OVERFLOW\n"; break; default: std::cout << "Unknown OpenGL error '" << glError << "'\n"; break; } } } ================================================ FILE: lib/src/opengl.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_OPENGL #define DILAY_OPENGL #include #include namespace OpenGL { // QT related void setDefaultFormat (); void initializeFunctions (bool); // wrappers unsigned int Always (); unsigned int ArrayBuffer (); unsigned int Back (); unsigned int Blend (); unsigned int BufferSize (); unsigned int ColorBufferBit (); unsigned int CullFace (); unsigned int CW (); unsigned int CCW (); unsigned int Decr (); unsigned int DecrWrap (); unsigned int DepthBufferBit (); unsigned int DepthTest (); unsigned int DstColor (); unsigned int ElementArrayBuffer (); unsigned int Equal (); unsigned int Fill (); unsigned int Float (); unsigned int Front (); unsigned int FrontAndBack (); unsigned int FuncAdd (); unsigned int Greater (); unsigned int Incr (); unsigned int IncrWrap (); unsigned int Invert (); unsigned int Keep (); unsigned int LEqual (); unsigned int Line (); unsigned int Lines (); unsigned int Never (); unsigned int PolygonOffsetFill (); unsigned int Replace (); unsigned int StaticDraw (); unsigned int StencilBufferBit (); unsigned int StencilTest (); unsigned int Triangles (); unsigned int UnsignedInt (); unsigned int Zero (); void glBindBuffer (unsigned int, unsigned int); void glBlendEquation (unsigned int); void glBlendFunc (unsigned int, unsigned); void glBufferData (unsigned int, unsigned int, const void*, unsigned int); void glBufferSubData (unsigned int, unsigned int, unsigned int, const void*); void glClear (unsigned int); void glClearColor (float, float, float, float); void glClearStencil (int); void glColorMask (bool, bool, bool, bool); void glCullFace (unsigned int); void glDepthFunc (unsigned int); void glDepthMask (bool); void glDisable (unsigned int); void glDisableVertexAttribArray (unsigned int); void glDrawElements (unsigned int, unsigned int, unsigned int, const void*); void glEnable (unsigned int); void glEnableVertexAttribArray (unsigned int); void glFrontFace (unsigned int); void glGenBuffers (unsigned int, unsigned int*); void glGetBufferParameteriv (unsigned int, unsigned int, int*); int glGetUniformLocation (unsigned int, const char*); bool glIsBuffer (unsigned int); bool glIsProgram (unsigned int); void glPolygonMode (unsigned int, unsigned int); void glPolygonOffset (float, float); void glStencilFunc (unsigned int, int, unsigned int); void glStencilOp (unsigned int, unsigned int, unsigned int); void glUniform1f (int, float); void glUniformMatrix3fv (int, unsigned int, bool, const float*); void glUniformMatrix4fv (int, unsigned int, bool, const float*); void glUseProgram (unsigned int); void glVertexAttribPointer (unsigned int, int, unsigned int, bool, unsigned int, const void*); void glViewport (unsigned int, unsigned int, unsigned int, unsigned int); // utilities enum VertexAttributIndex { PositionIndex = 0, NormalIndex = 1 }; bool hasGeometryShader (); void glUniformVec3 (unsigned int, const glm::vec3&); void glUniformVec4 (unsigned int, const glm::vec4&); void safeDeleteBuffer (unsigned int&); void safeDeleteShader (unsigned int&); void safeDeleteProgram (unsigned int&); unsigned int loadProgram (const char*, const char*, bool); void clearError (); void printError (); } #endif ================================================ FILE: lib/src/primitive/aabox.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "primitive/aabox.hpp" PrimAABox::PrimAABox (const glm::vec3& min, const glm::vec3& max) : _minimum (min) , _maximum (max) , _center ((min + max) * 0.5f) { } PrimAABox::PrimAABox (const glm::vec3& pos, float xW, float yW, float zW) : PrimAABox (pos - glm::vec3 (xW * 0.5f, yW * 0.5f, zW * 0.5f), pos + glm::vec3 (xW * 0.5f, yW * 0.5f, zW * 0.5f)) { } PrimAABox::PrimAABox (const glm::vec3& pos, float w) : PrimAABox (pos, w, w, w) { } glm::vec3 PrimAABox::halfWidth () const { return (this->_maximum - this->_minimum) * 0.5f; } float PrimAABox::maxDimExtent () const { const glm::vec3 extent = this->_maximum - this->_minimum; return glm::max (glm::max (extent.x, extent.y), extent.z); } bool PrimAABox::contains (const PrimAABox& box) const { return glm::all (glm::lessThanEqual (this->_minimum, box._minimum)) && glm::all (glm::greaterThanEqual (this->_maximum, box._maximum)); } ================================================ FILE: lib/src/primitive/aabox.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_PRIMITIVE_AABOX #define DILAY_PRIMITIVE_AABOX #include class PrimAABox { public: PrimAABox (const glm::vec3&, const glm::vec3&); PrimAABox (const glm::vec3&, float, float, float); PrimAABox (const glm::vec3&, float); const glm::vec3& maximum () const { return this->_maximum; } const glm::vec3& minimum () const { return this->_minimum; } const glm::vec3& center () const { return this->_center; } glm::vec3 halfWidth () const; float maxDimExtent () const; bool contains (const PrimAABox&) const; private: const glm::vec3 _minimum; const glm::vec3 _maximum; const glm::vec3 _center; }; #endif ================================================ FILE: lib/src/primitive/cone-sphere.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "primitive/cone-sphere.hpp" #include "primitive/cone.hpp" #include "util.hpp" PrimConeSphere::PrimConeSphere (const PrimSphere& s1, const PrimSphere& s2) : _sphere1 (s1.radius () > s2.radius () ? s1 : s2) , _sphere2 (s1.radius () > s2.radius () ? s2 : s1) , _length (glm::distance (s1.center (), s2.center ())) , _direction ((this->_sphere2.center () - this->_sphere1.center ()) / glm::vec3 (this->_length)) , _alpha (glm::half_pi () - glm::acos (this->delta () / this->_length)) , _sinAlpha (glm::sin (this->_alpha)) , _cosAlpha (glm::cos (this->_alpha)) { } float PrimConeSphere::delta () const { return this->_sphere1.radius () - this->_sphere2.radius (); } bool PrimConeSphere::sameRadii () const { return Util::almostEqual (this->delta (), 0.0f); } bool PrimConeSphere::hasCone () const { return this->_length > this->delta (); } float PrimConeSphere::coneSideLength () const { assert (this->hasCone ()); return glm::sqrt ((this->_length * this->_length) - (this->delta () * this->delta ())); } PrimCone PrimConeSphere::toCone () const { assert (this->hasCone ()); const float s = this->coneSideLength (); const float h1 = this->_sphere1.radius () * this->delta () / this->_length; const float h2 = this->_sphere2.radius () * this->delta () / this->_length; const float r1c = this->_sphere1.radius () * s / this->_length; const float r2c = this->_sphere2.radius () * s / this->_length; return PrimCone (this->_sphere2.center () + (this->_direction * h2), r2c, this->_sphere1.center () + (this->_direction * h1), r1c); } ================================================ FILE: lib/src/primitive/cone-sphere.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_PRIMITIVE_CONE_SPHERE #define DILAY_PRIMITIVE_CONE_SPHERE #include #include "primitive/sphere.hpp" class PrimCone; class PrimConeSphere { public: PrimConeSphere (const PrimSphere&, const PrimSphere&); const PrimSphere& sphere1 () const { return this->_sphere1; } const PrimSphere& sphere2 () const { return this->_sphere2; } float length () const { return this->_length; } const glm::vec3& direction () const { return this->_direction; } float alpha () const { return this->_alpha; } float sinAlpha () const { return this->_sinAlpha; } float cosAlpha () const { return this->_cosAlpha; } float delta () const; bool sameRadii () const; bool hasCone () const; float coneSideLength () const; PrimCone toCone () const; private: const PrimSphere _sphere1; const PrimSphere _sphere2; const float _length; const glm::vec3 _direction; const float _alpha; const float _sinAlpha; const float _cosAlpha; }; #endif ================================================ FILE: lib/src/primitive/cone.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "primitive/cone.hpp" #include "util.hpp" PrimCone::PrimCone (const glm::vec3& c1, float r1, const glm::vec3& c2, float r2, float l) : _center1 (r1 > r2 ? c1 : c2) , _radius1 (r1 > r2 ? r1 : r2) , _center2 (r1 > r2 ? c2 : c1) , _radius2 (r1 > r2 ? r2 : r1) , _length (l) , _direction ((this->_center2 - this->_center1) / glm::vec3 (l)) , _isCylinder (Util::almostEqual (r1, r2)) , _apex (this->_isCylinder ? glm::vec3 (0.0f) : this->_center1 + (this->_radius1 * (this->_center2 - this->_center1) / (this->_radius1 - this->_radius2))) , _alpha (glm::atan ((this->_radius1 - this->_radius2) / l)) , _sinAlpha (glm::sin (this->_alpha)) , _cosAlpha (glm::cos (this->_alpha)) { } PrimCone::PrimCone (const glm::vec3& c1, float r1, const glm::vec3& c2, float r2) : PrimCone (c1, r1, c2, r2, glm::distance (c1, c2)) { } glm::vec3 PrimCone::projPointAt (float t) const { return this->_center1 + (t * this->_direction); } glm::vec3 PrimCone::normalAt (const glm::vec3& pointAt, float tCone) const { const glm::vec3 projP = this->projPointAt (tCone); const glm::vec3 diff = glm::normalize (pointAt - projP); const glm::vec3 slope = (this->_center2 + (this->_radius2 * diff)) - (this->_center1 + (this->_radius1 * diff)); const glm::vec3 tang = glm::cross (diff, this->_direction); return glm::normalize (glm::cross (slope, tang)); } ================================================ FILE: lib/src/primitive/cone.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_PRIMITIVE_CONE #define DILAY_PRIMITIVE_CONE #include class PrimCone { public: PrimCone (const glm::vec3&, float, const glm::vec3&, float); PrimCone (const glm::vec3&, float, const glm::vec3&, float, float); const glm::vec3& center1 () const { return this->_center1; } float radius1 () const { return this->_radius1; } const glm::vec3& center2 () const { return this->_center2; } float radius2 () const { return this->_radius2; } float length () const { return this->_length; } const glm::vec3& direction () const { return this->_direction; } bool isCylinder () const { return this->_isCylinder; } const glm::vec3& apex () const { return this->_apex; } float alpha () const { return this->_alpha; } float sinAlpha () const { return this->_sinAlpha; } float cosAlpha () const { return this->_cosAlpha; } glm::vec3 projPointAt (float) const; glm::vec3 normalAt (const glm::vec3&, float) const; private: const glm::vec3 _center1; const float _radius1; const glm::vec3 _center2; const float _radius2; const float _length; const glm::vec3 _direction; const bool _isCylinder; const glm::vec3 _apex; const float _alpha; const float _sinAlpha; const float _cosAlpha; }; #endif ================================================ FILE: lib/src/primitive/cylinder.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "primitive/cone.hpp" #include "primitive/cylinder.hpp" #include "util.hpp" PrimCylinder::PrimCylinder (const glm::vec3& c1, const glm::vec3& c2, float r, float l) : _center1 (c1) , _center2 (c2) , _radius (r) , _length (l) , _direction ((c2 - c1) / glm::vec3 (l)) { } PrimCylinder::PrimCylinder (const glm::vec3& c1, const glm::vec3& c2, float r) : PrimCylinder (c1, c2, r, glm::distance (c1, c2)) { } PrimCylinder::PrimCylinder (const PrimCone& cone) : _center1 (cone.center1 ()) , _center2 (cone.center2 ()) , _radius (cone.radius1 ()) , _length (cone.length ()) , _direction (cone.direction ()) { assert (cone.isCylinder ()); } ================================================ FILE: lib/src/primitive/cylinder.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_PRIMITIVE_CYLINDER #define DILAY_PRIMITIVE_CYLINDER #include class PrimCone; class PrimCylinder { public: PrimCylinder (const glm::vec3&, const glm::vec3&, float); PrimCylinder (const glm::vec3&, const glm::vec3&, float, float); PrimCylinder (const PrimCone&); const glm::vec3& center1 () const { return this->_center1; } const glm::vec3& center2 () const { return this->_center2; } float radius () const { return this->_radius; } float length () const { return this->_length; } const glm::vec3& direction () const { return this->_direction; } private: const glm::vec3 _center1; const glm::vec3 _center2; const float _radius; const float _length; const glm::vec3 _direction; }; #endif ================================================ FILE: lib/src/primitive/plane.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "primitive/plane.hpp" #include "util.hpp" PrimPlane::PrimPlane (const glm::vec3& p, const glm::vec3& n) : _point (p) { this->normal (n); } void PrimPlane::normal (const glm::vec3& n) { this->_normal = glm::normalize (n); this->_u = glm::normalize (Util::orthogonal (this->_normal)); this->_v = glm::normalize (glm::cross (this->_normal, this->_u)); } float PrimPlane::distance (const glm::vec3& p) const { return glm::dot (this->_normal, p - this->_point); } float PrimPlane::absDistance (const glm::vec3& p) const { return glm::abs (this->distance (p)); } bool PrimPlane::onPlane (const glm::vec3& p) const { return this->absDistance (p) < Util::epsilon (); } glm::vec3 PrimPlane::project (const glm::vec3& p) const { return p - (this->_normal * this->distance (p)); } glm::vec3 PrimPlane::project (const glm::vec2& p) const { return this->_point + (this->_u * p.x) + (this->_v * p.y); } glm::vec2 PrimPlane::project2d (const glm::vec3& p) const { const glm::vec3 proj = this->project (p) - this->_point; return glm::vec2 (glm::dot (this->_u, proj), glm::dot (this->_v, proj)); } glm::vec3 PrimPlane::projectDirection (const glm::vec3& d) const { return this->project (d + this->_point) - this->_point; } glm::vec3 PrimPlane::mirror (const glm::vec3& p) const { return p - (2.0f * this->_normal * this->distance (p)); } glm::vec3 PrimPlane::mirrorDirection (const glm::vec3& d) const { return this->mirror (d + this->_point) - this->_point; } ================================================ FILE: lib/src/primitive/plane.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_PRIMITIVE_PLANE #define DILAY_PRIMITIVE_PLANE #include #include "macro.hpp" class PrimPlane { public: PrimPlane (const glm::vec3&, const glm::vec3&); float distance (const glm::vec3&) const; float absDistance (const glm::vec3&) const; bool onPlane (const glm::vec3&) const; glm::vec3 project (const glm::vec3&) const; glm::vec3 project (const glm::vec2&) const; glm::vec2 project2d (const glm::vec3&) const; glm::vec3 projectDirection (const glm::vec3&) const; glm::vec3 mirror (const glm::vec3&) const; glm::vec3 mirrorDirection (const glm::vec3&) const; MEMBER_REF_GETTER_SETTER (glm::vec3, point) MEMBER_REF_GETTER_EXPLICIT_SETTER (glm::vec3, normal) MEMBER_REF_GETTER (glm::vec3, u) MEMBER_REF_GETTER (glm::vec3, v) }; #endif ================================================ FILE: lib/src/primitive/ray.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "primitive/ray.hpp" #include "util.hpp" PrimRay::PrimRay (bool l, const glm::vec3& o, const glm::vec3& d) : _isLine (l) , _origin (o) , _direction (glm::normalize (d)) { } PrimRay::PrimRay (const glm::vec3& o, const glm::vec3& d) : PrimRay (false, o, d) { } glm::vec3 PrimRay::pointAt (float t) const { assert (t >= 0.0f || this->_isLine); return this->_origin + (this->_direction * glm::vec3 (t)); } float PrimRay::distance (const glm::vec3& p) const { const float t = glm::dot (this->_direction, p - this->_origin); return t >= 0.0f || this->_isLine ? glm::distance (p, this->pointAt (t)) : glm::distance (p, this->_origin); } bool PrimRay::onRay (const glm::vec3& p) const { return this->distance (p) < Util::epsilon (); } ================================================ FILE: lib/src/primitive/ray.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_PRIMITIVE_RAY #define DILAY_PRIMITIVE_RAY #include class PrimRay { public: PrimRay (bool, const glm::vec3&, const glm::vec3&); PrimRay (const glm::vec3&, const glm::vec3&); bool isLine () const { return this->_isLine; } const glm::vec3& origin () const { return this->_origin; } const glm::vec3& direction () const { return this->_direction; } void origin (const glm::vec3& o) { this->_origin = o; } glm::vec3 pointAt (float) const; float distance (const glm::vec3&) const; bool onRay (const glm::vec3&) const; private: const bool _isLine; glm::vec3 _origin; const glm::vec3 _direction; }; #endif ================================================ FILE: lib/src/primitive/sphere.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "primitive/aabox.hpp" #include "primitive/sphere.hpp" #include "primitive/triangle.hpp" #include "util.hpp" PrimSphere::PrimSphere (const glm::vec3& o, float r) : _center (o) , _radius (r) { } bool PrimSphere::contains (const glm::vec3& p) const { return glm::distance2 (this->_center, p) <= (this->_radius * this->_radius); } bool PrimSphere::contains (const PrimAABox& aabox) const { return this->contains (aabox.minimum ()) && this->contains (aabox.maximum ()); } bool PrimSphere::contains (const PrimTriangle& tri) const { return this->contains (tri.vertex1 ()) && this->contains (tri.vertex2 ()) && this->contains (tri.vertex3 ()); } ================================================ FILE: lib/src/primitive/sphere.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_PRIMITIVE_SPHERE #define DILAY_PRIMITIVE_SPHERE #include class PrimAABox; class PrimTriangle; class PrimSphere { public: PrimSphere (const glm::vec3&, float); const glm::vec3& center () const { return this->_center; } float radius () const { return this->_radius; } void center (const glm::vec3& c) { this->_center = c; } void radius (float r) { this->_radius = r; } bool contains (const glm::vec3&) const; bool contains (const PrimAABox&) const; bool contains (const PrimTriangle&) const; private: glm::vec3 _center; float _radius; }; #endif ================================================ FILE: lib/src/primitive/triangle.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "primitive/triangle.hpp" #include "util.hpp" PrimTriangle::PrimTriangle (const glm::vec3& v1, const glm::vec3& v2, const glm::vec3& v3) : _vertex1 (v1) , _vertex2 (v2) , _vertex3 (v3) { } glm::vec3 PrimTriangle::cross () const { return glm::cross (this->_vertex2 - this->_vertex1, this->_vertex3 - this->_vertex1); } glm::vec3 PrimTriangle::normal () const { const glm::vec3 c = this->cross (); const float l = glm::length (c); return l > 0.0f ? (c / l) : glm::vec3 (0.0f); } glm::vec3 PrimTriangle::center () const { return (this->_vertex1 + this->_vertex2 + this->_vertex3) / glm::vec3 (3.0f); } glm::vec3 PrimTriangle::minimum () const { return glm::min (glm::min (this->_vertex1, this->_vertex2), this->_vertex3); } glm::vec3 PrimTriangle::maximum () const { return glm::max (glm::max (this->_vertex1, this->_vertex2), this->_vertex3); } float PrimTriangle::maxExtent () const { return glm::length (this->maximum () - this->minimum ()); } float PrimTriangle::maxDimExtent () const { const glm::vec3 extent = this->maximum () - this->minimum (); return glm::max (glm::max (extent.x, extent.y), extent.z); } float PrimTriangle::incircleRadiusSqr () const { const float a = glm::distance (this->_vertex1, this->_vertex2); const float b = glm::distance (this->_vertex2, this->_vertex3); const float c = glm::distance (this->_vertex1, this->_vertex3); const float s = 0.5f * (a + b + c); return (s - a) * (s - b) * (s - c) / s; } float PrimTriangle::longestEdgeSqr () const { return glm::max (glm::max (glm::distance2 (this->_vertex1, this->_vertex2), glm::distance2 (this->_vertex2, this->_vertex3)), glm::distance2 (this->_vertex1, this->_vertex3)); } ================================================ FILE: lib/src/primitive/triangle.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_PRIMITIVE_TRIANGLE #define DILAY_PRIMITIVE_TRIANGLE #include class PrimTriangle { public: PrimTriangle (const glm::vec3&, const glm::vec3&, const glm::vec3&); const glm::vec3& vertex1 () const { return this->_vertex1; } const glm::vec3& vertex2 () const { return this->_vertex2; } const glm::vec3& vertex3 () const { return this->_vertex3; } glm::vec3 cross () const; glm::vec3 normal () const; glm::vec3 center () const; glm::vec3 minimum () const; glm::vec3 maximum () const; float maxExtent () const; float maxDimExtent () const; float incircleRadiusSqr () const; float longestEdgeSqr () const; private: const glm::vec3& _vertex1; const glm::vec3& _vertex2; const glm::vec3& _vertex3; }; #endif ================================================ FILE: lib/src/render-mode.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "render-mode.hpp" #include "shader.hpp" #include "util.hpp" RenderMode::RenderMode () { this->smoothShading (true); this->renderWireframe (false); this->cameraRotationOnly (false); this->noDepthTest (false); } RenderMode::RenderMode (const RenderMode& other) : flags (other.flags) { } bool RenderMode::smoothShading () const { return this->flags.get<0> (); } bool RenderMode::flatShading () const { return this->flags.get<1> (); } bool RenderMode::constantShading () const { return this->flags.get<2> (); } bool RenderMode::renderWireframe () const { return this->flags.get<3> (); } bool RenderMode::cameraRotationOnly () const { return this->flags.get<4> (); } bool RenderMode::noDepthTest () const { return this->flags.get<5> (); } const char* RenderMode::vertexShader () const { if (this->smoothShading ()) { return Shader::smoothVertexShader (); } else if (this->flatShading ()) { return Shader::flatVertexShader (); } else if (this->constantShading ()) { return Shader::constantVertexShader (); } else { DILAY_IMPOSSIBLE } } const char* RenderMode::fragmentShader () const { if (this->smoothShading ()) { return this->renderWireframe () ? Shader::smoothWireframeFragmentShader () : Shader::smoothFragmentShader (); } else if (this->flatShading ()) { return this->renderWireframe () ? Shader::flatWireframeFragmentShader () : Shader::flatFragmentShader (); } else if (this->constantShading ()) { return this->renderWireframe () ? Shader::constantWireframeFragmentShader () : Shader::constantFragmentShader (); } else { DILAY_IMPOSSIBLE } } void RenderMode::smoothShading (bool v) { this->flags.set<0> (v); if (v) { this->flags.set<1> (false); this->flags.set<2> (false); } } void RenderMode::flatShading (bool v) { this->flags.set<1> (v); if (v) { this->flags.set<0> (false); this->flags.set<2> (false); } } void RenderMode::constantShading (bool v) { this->flags.set<2> (v); if (v) { this->flags.set<0> (false); this->flags.set<1> (false); } } void RenderMode::renderWireframe (bool v) { this->flags.set<3> (v); } void RenderMode::cameraRotationOnly (bool v) { this->flags.set<4> (v); } void RenderMode::noDepthTest (bool v) { this->flags.set<5> (v); } ================================================ FILE: lib/src/render-mode.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_RENDER_MODE #define DILAY_RENDER_MODE #include "bitset.hpp" class RenderMode { public: RenderMode (); RenderMode (const RenderMode&); bool smoothShading () const; bool flatShading () const; bool constantShading () const; bool renderWireframe () const; bool cameraRotationOnly () const; bool noDepthTest () const; const char* vertexShader () const; const char* fragmentShader () const; void smoothShading (bool); void flatShading (bool); void constantShading (bool); void renderWireframe (bool); void cameraRotationOnly (bool); void noDepthTest (bool); private: Bitset flags; }; #endif ================================================ FILE: lib/src/renderer.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "color.hpp" #include "config.hpp" #include "opengl.hpp" #include "render-mode.hpp" #include "renderer.hpp" #include "util.hpp" namespace { const unsigned int numLights = 2; struct LightIds { int directionId; int colorId; int irradianceId; LightIds () : directionId (0) , colorId (0) , irradianceId (0) { } }; struct ShaderIds { unsigned int programId; int modelId; int modelNormalId; int viewId; int projectionId; int colorId; int wireframeColorId; int eyePointId; int barycentricId; LightIds lightIds[numLights]; ShaderIds () : programId (0) , modelId (0) , modelNormalId (0) , viewId (0) , projectionId (0) , colorId (0) , wireframeColorId (0) , eyePointId (0) , barycentricId (0) { } }; struct GlobalLightUniforms { glm::vec3 direction; Color color; float irradiance; }; struct GlobalUniforms { GlobalLightUniforms lightUniforms[numLights]; glm::vec3 eyePoint; }; }; struct Renderer::Impl { static const unsigned int numShaders = 6; ShaderIds shaderIds[Impl::numShaders]; ShaderIds* activeShaderIndex; GlobalUniforms globalUniforms; Color clearColor; Impl (const Config& config) : activeShaderIndex (nullptr) { this->runFromConfig (config); } ~Impl () { for (unsigned int i = 0; i < Impl::numShaders; i++) { OpenGL::safeDeleteProgram (this->shaderIds[i].programId); } } void setupRendering () { OpenGL::glClearColor (this->clearColor.r (), this->clearColor.g (), this->clearColor.b (), 0.0f); OpenGL::glClearStencil (0); OpenGL::glFrontFace (OpenGL::CCW ()); OpenGL::glEnable (OpenGL::CullFace ()); OpenGL::glCullFace (OpenGL::Back ()); OpenGL::glEnable (OpenGL::DepthTest ()); OpenGL::glDepthFunc (OpenGL::LEqual ()); OpenGL::glClear (OpenGL::ColorBufferBit () | OpenGL::DepthBufferBit ()); } void shutdownRendering () { OpenGL::glDisable (OpenGL::DepthTest ()); OpenGL::glDisable (OpenGL::CullFace ()); } unsigned int shaderIndex (const RenderMode& renderMode) { if (renderMode.smoothShading ()) { return renderMode.renderWireframe () ? 0 : 1; } else if (renderMode.flatShading ()) { return renderMode.renderWireframe () ? 2 : 3; } else if (renderMode.constantShading ()) { return renderMode.renderWireframe () ? 4 : 5; } else { DILAY_IMPOSSIBLE } } void initalizeProgram (const RenderMode& renderMode) { assert (renderMode.renderWireframe () == false || OpenGL::hasGeometryShader ()); const unsigned int id = OpenGL::loadProgram ( renderMode.vertexShader (), renderMode.fragmentShader (), renderMode.renderWireframe ()); unsigned int index = this->shaderIndex (renderMode); assert (this->shaderIds[index].programId == 0); ShaderIds* s = &this->shaderIds[index]; s->programId = id; s->modelId = OpenGL::glGetUniformLocation (id, "model"); s->modelNormalId = OpenGL::glGetUniformLocation (id, "modelNormal"); s->viewId = OpenGL::glGetUniformLocation (id, "view"); s->projectionId = OpenGL::glGetUniformLocation (id, "projection"); s->colorId = OpenGL::glGetUniformLocation (id, "color"); s->wireframeColorId = OpenGL::glGetUniformLocation (id, "wireframeColor"); s->eyePointId = OpenGL::glGetUniformLocation (id, "eyePoint"); s->barycentricId = OpenGL::glGetUniformLocation (id, "barycentric"); s->lightIds[0].directionId = OpenGL::glGetUniformLocation (id, "light1Direction"); s->lightIds[0].colorId = OpenGL::glGetUniformLocation (id, "light1Color"); s->lightIds[0].irradianceId = OpenGL::glGetUniformLocation (id, "light1Irradiance"); s->lightIds[1].directionId = OpenGL::glGetUniformLocation (id, "light2Direction"); s->lightIds[1].colorId = OpenGL::glGetUniformLocation (id, "light2Color"); s->lightIds[1].irradianceId = OpenGL::glGetUniformLocation (id, "light2Irradiance"); } void setProgram (const RenderMode& renderMode) { const unsigned int index = this->shaderIndex (renderMode); if (this->shaderIds[index].programId == 0) { this->initalizeProgram (renderMode); } assert (this->shaderIds[index].programId); this->activeShaderIndex = &this->shaderIds[index]; OpenGL::glUseProgram (this->activeShaderIndex->programId); OpenGL::glUniformVec3 (this->activeShaderIndex->eyePointId, this->globalUniforms.eyePoint); for (unsigned int i = 0; i < numLights; i++) { OpenGL::glUniformVec3 (this->activeShaderIndex->lightIds[i].directionId, this->globalUniforms.lightUniforms[i].direction); OpenGL::glUniformVec3 (this->activeShaderIndex->lightIds[i].colorId, this->globalUniforms.lightUniforms[i].color.vec3 ()); OpenGL::glUniform1f (this->activeShaderIndex->lightIds[i].irradianceId, this->globalUniforms.lightUniforms[i].irradiance); } } void setModel (const float* model, const float* modelNormal) { assert (this->activeShaderIndex); OpenGL::glUniformMatrix4fv (this->activeShaderIndex->modelId, 1, false, model); OpenGL::glUniformMatrix3fv (this->activeShaderIndex->modelNormalId, 1, false, modelNormal); } void setView (const float* view) { assert (this->activeShaderIndex); OpenGL::glUniformMatrix4fv (this->activeShaderIndex->viewId, 1, false, view); } void setProjection (const float* projection) { assert (this->activeShaderIndex); OpenGL::glUniformMatrix4fv (this->activeShaderIndex->projectionId, 1, false, projection); } void setColor (const Color& c, bool withOpacity) { assert (this->activeShaderIndex); if (withOpacity) { OpenGL::glUniformVec4 (this->activeShaderIndex->colorId, c.vec4 ()); } else { OpenGL::glUniformVec3 (this->activeShaderIndex->colorId, c.vec3 ()); } } void setWireframeColor (const Color& c, bool withOpacity) { assert (this->activeShaderIndex); if (withOpacity) { OpenGL::glUniformVec4 (this->activeShaderIndex->wireframeColorId, c.vec4 ()); } else { OpenGL::glUniformVec3 (this->activeShaderIndex->wireframeColorId, c.vec3 ()); } } void setEyePoint (const glm::vec3& e) { this->globalUniforms.eyePoint = e; } void setLightDirection (unsigned int i, const glm::vec3& d) { assert (i < numLights); this->globalUniforms.lightUniforms[i].direction = d; } void setLightColor (unsigned int i, const Color& c) { assert (i < numLights); this->globalUniforms.lightUniforms[i].color = c; } void setLightIrradiance (unsigned int i, float irr) { assert (i < numLights); this->globalUniforms.lightUniforms[i].irradiance = irr; } void runFromConfig (const Config& config) { this->clearColor = config.get ("editor/background"); for (unsigned int i = 0; i < numLights; i++) { const std::string key = "editor/light/light" + std::to_string (i + 1) + "/"; const glm::vec3 dir = config.get (key + "direction"); this->setLightDirection (i, glm::normalize (dir)); this->setLightColor (i, config.get (key + "color")); this->setLightIrradiance (i, config.get (key + "irradiance")); } } }; DELEGATE1_BIG3 (Renderer, const Config&) DELEGATE (void, Renderer, setupRendering) DELEGATE (void, Renderer, shutdownRendering) DELEGATE1 (void, Renderer, setProgram, const RenderMode&) DELEGATE2 (void, Renderer, setModel, const float*, const float*) DELEGATE1 (void, Renderer, setView, const float*) DELEGATE1 (void, Renderer, setProjection, const float*) DELEGATE2 (void, Renderer, setColor, const Color&, bool) DELEGATE2 (void, Renderer, setWireframeColor, const Color&, bool) DELEGATE1 (void, Renderer, setEyePoint, const glm::vec3&) DELEGATE2 (void, Renderer, setLightDirection, unsigned int, const glm::vec3&) DELEGATE2 (void, Renderer, setLightColor, unsigned int, const Color&) DELEGATE2 (void, Renderer, setLightIrradiance, unsigned int, float) DELEGATE1 (void, Renderer, runFromConfig, const Config&) ================================================ FILE: lib/src/renderer.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_RENDERER #define DILAY_RENDERER #include #include "configurable.hpp" #include "macro.hpp" class Color; class Config; class RenderMode; class Renderer : public Configurable { public: DECLARE_BIG3 (Renderer, const Config&) void setupRendering (); void shutdownRendering (); void setProgram (const RenderMode&); void setModel (const float*, const float*); void setView (const float*); void setProjection (const float*); void setColor (const Color&, bool = false); void setWireframeColor (const Color&, bool = false); void setEyePoint (const glm::vec3&); void setLightDirection (unsigned int, const glm::vec3&); void setLightColor (unsigned int, const Color&); void setLightIrradiance (unsigned int, float); private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/scene.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "config.hpp" #include "dynamic/mesh-intersection.hpp" #include "dynamic/mesh.hpp" #include "import-export.hpp" #include "intersection.hpp" #include "render-mode.hpp" #include "scene.hpp" #include "sketch/bone-intersection.hpp" #include "sketch/mesh-intersection.hpp" #include "sketch/mesh.hpp" #include "sketch/node-intersection.hpp" #include "sketch/path-intersection.hpp" #include "util.hpp" struct Scene::Impl { Scene* self; std::list dynamicMeshes; std::list sketchMeshes; RenderMode commonRenderMode; std::string fileName; Impl (Scene* s, const Config& config) : self (s) { this->runFromConfig (config); this->commonRenderMode.smoothShading (true); } DynamicMesh& newDynamicMesh (const Config& config, const DynamicMesh& other) { this->dynamicMeshes.emplace_back (other); this->setupMesh (config, this->dynamicMeshes.back ()); return this->dynamicMeshes.back (); } DynamicMesh& newDynamicMesh (const Config& config, const Mesh& mesh) { this->dynamicMeshes.emplace_back (mesh); this->setupMesh (config, this->dynamicMeshes.back ()); return this->dynamicMeshes.back (); } SketchMesh& newSketchMesh (const Config& config, const SketchMesh& other) { this->sketchMeshes.emplace_back (other); this->setupMesh (config, this->sketchMeshes.back ()); return this->sketchMeshes.back (); } SketchMesh& newSketchMesh (const Config& config, const SketchTree& tree) { this->sketchMeshes.emplace_back (); this->sketchMeshes.back ().fromTree (tree); this->setupMesh (config, this->sketchMeshes.back ()); return this->sketchMeshes.back (); } void setupMesh (const Config& config, DynamicMesh& mesh) { mesh.bufferData (); mesh.renderMode () = this->commonRenderMode; mesh.fromConfig (config); } void setupMesh (const Config& config, SketchMesh& mesh) { mesh.renderWireframe (this->commonRenderMode.renderWireframe ()); mesh.fromConfig (config); } void deleteMesh (DynamicMesh& mesh) { for (auto it = this->dynamicMeshes.begin (); it != this->dynamicMeshes.end (); ++it) { if (&*it == &mesh) { this->dynamicMeshes.erase (it); this->resetIfEmpty (); return; } } DILAY_IMPOSSIBLE } void deleteMesh (SketchMesh& mesh) { for (auto it = this->sketchMeshes.begin (); it != this->sketchMeshes.end (); ++it) { if (&*it == &mesh) { this->sketchMeshes.erase (it); this->resetIfEmpty (); return; } } DILAY_IMPOSSIBLE } void deleteDynamicMeshes () { this->dynamicMeshes.clear (); } void deleteSketchMeshes () { this->sketchMeshes.clear (); } void deleteEmptyMeshes () { this->dynamicMeshes.remove_if ([](const auto& mesh) { return mesh.isEmpty (); }); this->sketchMeshes.remove_if ([](const auto& mesh) { return mesh.isEmpty (); }); this->resetIfEmpty (); } void render (Camera& camera) { this->forEachMesh ([&](DynamicMesh& m) { m.render (camera); }); this->forEachMesh ([&](SketchMesh& m) { m.render (camera); }); } template bool intersectsT (const PrimRay& ray, TIntersection& intersection, Ts... args) { this->forEachMesh ([&ray, &intersection, &args...](TMesh& m) { m.intersects (ray, intersection, std::forward (args)...); }); return intersection.isIntersection (); } bool intersects (const PrimRay& ray, DynamicMeshIntersection& intersection) { return this->intersectsT (ray, intersection); } bool intersects (const PrimRay& ray, SketchNodeIntersection& intersection, const SketchNode* exclude) { return this->intersectsT (ray, intersection, exclude); } bool intersects (const PrimRay& ray, SketchBoneIntersection& intersection) { return this->intersectsT (ray, intersection); } bool intersects (const PrimRay& ray, SketchMeshIntersection& intersection) { return this->intersectsT (ray, intersection); } bool intersects (const PrimRay& ray, SketchMeshIntersection& intersection, unsigned int numExcludedLastPaths) { return this->intersectsT (ray, intersection, numExcludedLastPaths); } bool intersects (const PrimRay& ray, SketchPathIntersection& intersection) { return this->intersectsT (ray, intersection); } bool intersects (const PrimRay& ray, Intersection& intersection) { DynamicMeshIntersection dIntersection; SketchMeshIntersection sIntersection; if (this->intersects (ray, dIntersection)) { intersection.update (dIntersection.distance (), dIntersection.position (), dIntersection.normal ()); } if (this->intersects (ray, sIntersection)) { intersection.update (sIntersection.distance (), sIntersection.position (), sIntersection.normal ()); } return intersection.isIntersection (); } void printStatistics () const { this->forEachConstMesh ([](const DynamicMesh& mesh) { mesh.printStatistics (); }); } template void forEachMeshT (std::list& list, const std::function& f) { const unsigned int n = list.size (); unsigned int i = 0; for (T& mesh : list) { if (i >= n) { break; } else { f (mesh); i++; } } } template void forEachConstMeshT (const std::list& list, const std::function& f) const { const unsigned int n = list.size (); unsigned int i = 0; for (const T& mesh : list) { if (i >= n) { break; } else { f (mesh); i++; } } } void forEachMesh (const std::function& f) { this->forEachMeshT (this->dynamicMeshes, f); } void forEachMesh (const std::function& f) { this->forEachMeshT (this->sketchMeshes, f); } void forEachConstMesh (const std::function& f) const { this->forEachConstMeshT (this->dynamicMeshes, f); } void forEachConstMesh (const std::function& f) const { this->forEachConstMeshT (this->sketchMeshes, f); } void sanitizeMeshes () { this->forEachMesh ([](DynamicMesh& mesh) { mesh.sanitize (); }); } void reset () { this->deleteDynamicMeshes (); this->deleteSketchMeshes (); this->fileName.clear (); } void resetIfEmpty () { if (this->isEmpty ()) { this->reset (); } } void setCommonRenderMode (const RenderMode& mode) { this->commonRenderMode = mode; this->forEachMesh ([this](DynamicMesh& mesh) { mesh.renderMode () = this->commonRenderMode; }); this->forEachMesh ( [&mode](SketchMesh& mesh) { mesh.renderWireframe (mode.renderWireframe ()); }); } bool renderWireframe () const { return this->commonRenderMode.renderWireframe (); } void renderWireframe (bool value) { this->commonRenderMode.renderWireframe (value); this->setCommonRenderMode (this->commonRenderMode); } void toggleWireframe () { this->renderWireframe (!this->commonRenderMode.renderWireframe ()); } void toggleShading () { if (this->commonRenderMode.smoothShading ()) { this->commonRenderMode.flatShading (true); } else if (this->commonRenderMode.flatShading ()) { this->commonRenderMode.smoothShading (true); } this->setCommonRenderMode (this->commonRenderMode); } bool isEmpty () const { return this->numDynamicMeshes () == 0 && this->numSketchMeshes () == 0; } unsigned int numDynamicMeshes () const { return this->dynamicMeshes.size (); } unsigned int numSketchMeshes () const { return this->sketchMeshes.size (); } unsigned int numFaces () const { unsigned int n = 0; this->forEachConstMesh ([&n](const DynamicMesh& mesh) { n += mesh.numFaces (); }); return n; } bool hasFileName () const { return !this->fileName.empty (); } bool toDlyFile (bool isObjFile) { assert (this->hasFileName ()); return Util::withCLocale ([this, isObjFile]() { if (ImportExport::toDlyFile (this->fileName, *this->self, isObjFile)) { return true; } else { this->fileName.clear (); return false; } }); } bool toDlyFile (const std::string& newFileName, bool isObjFile) { this->fileName = newFileName; return this->toDlyFile (isObjFile); } bool fromDlyFile (const Config& config, const std::string& newFileName) { this->fileName = newFileName; if (ImportExport::fromDlyFile (this->fileName, config, *this->self)) { return true; } else { this->fileName.clear (); return false; } } void runFromConfig (const Config& config) { this->forEachMesh ([&config](DynamicMesh& mesh) { mesh.fromConfig (config); }); this->forEachMesh ([&config](SketchMesh& mesh) { mesh.fromConfig (config); }); } }; DELEGATE1_BIG3_SELF (Scene, const Config&) DELEGATE2 (DynamicMesh&, Scene, newDynamicMesh, const Config&, const DynamicMesh&) DELEGATE2 (DynamicMesh&, Scene, newDynamicMesh, const Config&, const Mesh&) DELEGATE2 (SketchMesh&, Scene, newSketchMesh, const Config&, const SketchMesh&) DELEGATE2 (SketchMesh&, Scene, newSketchMesh, const Config&, const SketchTree&) DELEGATE2 (void, Scene, setupMesh, const Config&, DynamicMesh&) DELEGATE2 (void, Scene, setupMesh, const Config&, SketchMesh&) DELEGATE1 (void, Scene, deleteMesh, DynamicMesh&) DELEGATE1 (void, Scene, deleteMesh, SketchMesh&) DELEGATE (void, Scene, deleteDynamicMeshes) DELEGATE (void, Scene, deleteSketchMeshes) DELEGATE (void, Scene, deleteEmptyMeshes) DELEGATE1 (void, Scene, render, Camera&) DELEGATE2 (bool, Scene, intersects, const PrimRay&, DynamicMeshIntersection&) DELEGATE3 (bool, Scene, intersects, const PrimRay&, SketchNodeIntersection&, const SketchNode*) DELEGATE2 (bool, Scene, intersects, const PrimRay&, SketchBoneIntersection&) DELEGATE2 (bool, Scene, intersects, const PrimRay&, SketchMeshIntersection&) DELEGATE3 (bool, Scene, intersects, const PrimRay&, SketchMeshIntersection&, unsigned int) DELEGATE2 (bool, Scene, intersects, const PrimRay&, SketchPathIntersection&) DELEGATE2 (bool, Scene, intersects, const PrimRay&, Intersection&) DELEGATE_CONST (void, Scene, printStatistics) DELEGATE1 (void, Scene, forEachMesh, const std::function&) DELEGATE1 (void, Scene, forEachMesh, const std::function&) DELEGATE1_CONST (void, Scene, forEachConstMesh, const std::function&) DELEGATE1_CONST (void, Scene, forEachConstMesh, const std::function&) DELEGATE (void, Scene, sanitizeMeshes) DELEGATE (void, Scene, reset) GETTER_CONST (const RenderMode&, Scene, commonRenderMode) DELEGATE_CONST (bool, Scene, renderWireframe) DELEGATE1 (void, Scene, renderWireframe, bool) DELEGATE (void, Scene, toggleWireframe) DELEGATE (void, Scene, toggleShading) DELEGATE_CONST (bool, Scene, isEmpty) DELEGATE_CONST (unsigned int, Scene, numDynamicMeshes) DELEGATE_CONST (unsigned int, Scene, numSketchMeshes) DELEGATE_CONST (unsigned int, Scene, numFaces) DELEGATE_CONST (bool, Scene, hasFileName) GETTER_CONST (const std::string&, Scene, fileName) DELEGATE1 (bool, Scene, toDlyFile, bool) DELEGATE2 (bool, Scene, toDlyFile, const std::string&, bool) DELEGATE2 (bool, Scene, fromDlyFile, const Config&, const std::string&) DELEGATE1 (void, Scene, runFromConfig, const Config&) ================================================ FILE: lib/src/scene.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SCENE #define DILAY_SCENE #include #include "configurable.hpp" #include "macro.hpp" #include "sketch/fwd.hpp" class Camera; class DynamicMesh; class DynamicMeshIntersection; class Intersection; class Mesh; class PrimRay; class RenderMode; class Scene : public Configurable { public: DECLARE_BIG3 (Scene, const Config&) DynamicMesh& newDynamicMesh (const Config&, const DynamicMesh&); DynamicMesh& newDynamicMesh (const Config&, const Mesh&); SketchMesh& newSketchMesh (const Config&, const SketchMesh&); SketchMesh& newSketchMesh (const Config&, const SketchTree&); void setupMesh (const Config&, DynamicMesh&); void setupMesh (const Config&, SketchMesh&); void deleteMesh (DynamicMesh&); void deleteMesh (SketchMesh&); void deleteDynamicMeshes (); void deleteSketchMeshes (); void deleteEmptyMeshes (); void render (Camera&); bool intersects (const PrimRay&, DynamicMeshIntersection&); bool intersects (const PrimRay&, SketchNodeIntersection&, const SketchNode* = nullptr); bool intersects (const PrimRay&, SketchBoneIntersection&); bool intersects (const PrimRay&, SketchMeshIntersection&); bool intersects (const PrimRay&, SketchMeshIntersection&, unsigned int); bool intersects (const PrimRay&, SketchPathIntersection&); bool intersects (const PrimRay&, Intersection&); void printStatistics () const; void forEachMesh (const std::function&); void forEachMesh (const std::function&); void forEachConstMesh (const std::function&) const; void forEachConstMesh (const std::function&) const; void sanitizeMeshes (); void reset (); const RenderMode& commonRenderMode () const; bool renderWireframe () const; void renderWireframe (bool); void toggleWireframe (); void toggleShading (); bool isEmpty () const; unsigned int numDynamicMeshes () const; unsigned int numSketchMeshes () const; unsigned int numFaces () const; bool hasFileName () const; const std::string& fileName () const; bool toDlyFile (bool); bool toDlyFile (const std::string&, bool); bool fromDlyFile (const Config&, const std::string&); private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/shader.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "shader.hpp" #define SMOOTH_VERTEX_SHADER \ "#version 120 \n" \ " \n" \ "uniform mat4 model; \n" \ "uniform mat3 modelNormal; \n" \ "uniform mat4 view; \n" \ "uniform mat4 projection; \n" \ "attribute vec3 position; \n" \ "attribute vec3 normal; \n" \ "uniform vec3 color; \n" \ "uniform vec3 light1Direction; \n" \ "uniform vec3 light1Color; \n" \ "uniform float light1Irradiance; \n" \ "uniform vec3 light2Direction; \n" \ "uniform vec3 light2Color; \n" \ "uniform float light2Irradiance; \n" \ " \n" \ "varying vec3 vsColor; \n" \ " \n" \ "void main () { \n" \ " gl_Position = (projection * view * model) * vec4 (position, 1.0); \n" \ " vec3 viewNormal = vec3 (view * vec4 (normalize (modelNormal * normal), 0.0)); \n" \ " float light1Diff = max (0.0, dot (-light1Direction, viewNormal)); \n" \ " float light2Diff = max (0.0, dot (-light2Direction, viewNormal)); \n" \ " vec3 light1 = light1Irradiance * light1Color * light1Diff; \n" \ " vec3 light2 = light2Irradiance * light2Color * light2Diff; \n" \ " vsColor = color * (light1 + light2); \n" \ "} \n" #define SMOOTH_FRAGMENT_SHADER(COLOR, FINAL) \ "#version 120 \n" \ " \n" \ "uniform vec3 wireframeColor; \n" \ " \n" \ "varying vec3 " COLOR "; \n" \ "varying vec3 barycentric; \n" \ " \n" \ "void main () { \n" \ " gl_FragColor = vec4 (" COLOR \ ", 1.0); \n" FINAL \ "} \n" #define FLAT_VERTEX_SHADER \ "#version 120 \n" \ " \n" \ "uniform mat4 model; \n" \ "uniform mat4 view; \n" \ "uniform mat4 projection; \n" \ "attribute vec3 position; \n" \ " \n" \ "varying vec3 vsColor; \n" \ " \n" \ "void main () { \n" \ " gl_Position = (projection * view * model) * vec4 (position,1.0); \n" \ " vsColor = vec3 (model * vec4 (position, 1.0)); \n" \ "} \n" #define FLAT_FRAGMENT_SHADER(COLOR, FINAL) \ "#version 120 \n" \ " \n" \ "uniform mat4 view; \n" \ "uniform vec3 color; \n" \ "uniform vec3 wireframeColor; \n" \ "uniform vec3 light1Direction; \n" \ "uniform vec3 light1Color; \n" \ "uniform float light1Irradiance; \n" \ "uniform vec3 light2Direction; \n" \ "uniform vec3 light2Color; \n" \ "uniform float light2Irradiance; \n" \ " \n" \ "varying vec3 " COLOR "; \n" \ "varying vec3 barycentric; \n" \ " \n" \ "void main () { \n" \ " vec3 normal = normalize(cross(dFdx(" COLOR "),dFdy(" COLOR "))); \n" \ " vec3 viewNormal = vec3 (view * vec4 (normal,0.0)); \n" \ " \n" \ " float light1Diff = max (0.0, dot (-light1Direction, viewNormal)); \n" \ " float light2Diff = max (0.0, dot (-light2Direction, viewNormal)); \n" \ " vec3 light1 = light1Irradiance * light1Color * vec3 (light1Diff); \n" \ " vec3 light2 = light2Irradiance * light2Color * vec3 (light2Diff); \n" \ " \n" \ " gl_FragColor = vec4 (color * (light1 + light2), 1.0); " \ "\n" FINAL \ "} \n" #define CONSTANT_VERTEX_SHADER \ "#version 120 \n" \ " \n" \ "uniform mat4 model; \n" \ "uniform mat4 view; \n" \ "uniform mat4 projection; \n" \ "attribute vec3 position; \n" \ " \n" \ "void main(){ \n" \ " gl_Position = (projection * view * model) * vec4 (position,1.0); \n" \ "} \n" #define CONSTANT_FRAGMENT_SHADER(FINAL) \ "#version 120 \n" \ " \n" \ "uniform vec3 color; \n" \ "uniform vec3 wireframeColor; \n" \ " \n" \ "varying vec3 barycentric; \n" \ " \n" \ "void main(){ \n" \ " gl_FragColor = vec4 (color, 1.0); " \ "\n" FINAL \ "} \n" #define ADD_WIREFRAME \ "vec3 barycDelta = fwidth (barycentric); \n" \ " \n" \ "vec3 edgeFactor = smoothstep (vec3 (0.0), barycDelta * 1.0, barycentric); \n" \ "float minEdgeFactor = min (min (edgeFactor.x, edgeFactor.y), edgeFactor.z); \n" \ " \n" \ "gl_FragColor.rgb = mix (wireframeColor, gl_FragColor.rgb, minEdgeFactor); \n" #define GEOMETRY_SHADER \ "#extension GL_EXT_geometry_shader4: require \n" \ " \n" \ "varying in vec3 vsColor[3]; \n" \ "varying out vec3 gsColor; \n" \ "varying out vec3 barycentric; \n" \ " \n" \ "void main() { \n" \ " gl_Position = gl_PositionIn[0]; \n" \ " gsColor = vsColor[0]; \n" \ " barycentric = vec3 (1.0,0.0,0.0); \n" \ " EmitVertex(); \n" \ " \n" \ " gl_Position = gl_PositionIn[1]; \n" \ " gsColor = vsColor[1]; \n" \ " barycentric = vec3 (0.0,1.0,0.0); \n" \ " EmitVertex(); \n" \ " \n" \ " gl_Position = gl_PositionIn[2]; \n" \ " gsColor = vsColor[2]; \n" \ " barycentric = vec3 (0.0,0.0,1.0); \n" \ " EmitVertex(); \n" \ " \n" \ " EndPrimitive(); \n" \ "} \n" const char* Shader::smoothVertexShader () { return SMOOTH_VERTEX_SHADER; } const char* Shader::smoothFragmentShader () { return SMOOTH_FRAGMENT_SHADER ("vsColor", ""); } const char* Shader::smoothWireframeFragmentShader () { return SMOOTH_FRAGMENT_SHADER ("gsColor", ADD_WIREFRAME); } const char* Shader::flatVertexShader () { return FLAT_VERTEX_SHADER; } const char* Shader::flatFragmentShader () { return FLAT_FRAGMENT_SHADER ("vsColor", ""); } const char* Shader::flatWireframeFragmentShader () { return FLAT_FRAGMENT_SHADER ("gsColor", ADD_WIREFRAME); } const char* Shader::constantVertexShader () { return CONSTANT_VERTEX_SHADER; } const char* Shader::constantFragmentShader () { return CONSTANT_FRAGMENT_SHADER (""); } const char* Shader::constantWireframeFragmentShader () { return CONSTANT_FRAGMENT_SHADER (ADD_WIREFRAME); } const char* Shader::geometryShader () { return GEOMETRY_SHADER; } ================================================ FILE: lib/src/shader.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SHADER #define DILAY_SHADER namespace Shader { const char* smoothVertexShader (); const char* smoothFragmentShader (); const char* smoothWireframeFragmentShader (); const char* flatVertexShader (); const char* flatFragmentShader (); const char* flatWireframeFragmentShader (); const char* constantVertexShader (); const char* constantFragmentShader (); const char* constantWireframeFragmentShader (); const char* geometryShader (); }; #endif ================================================ FILE: lib/src/sketch/bone-intersection.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "sketch/bone-intersection.hpp" #include "sketch/mesh.hpp" SketchBoneIntersection::SketchBoneIntersection () : _child (nullptr) { } bool SketchBoneIntersection::update (float d, const glm::vec3& p, const glm::vec3& projP, const glm::vec3& n, SketchMesh& mesh, SketchNode& child) { assert (child.parent ()); if (this->SketchMeshIntersection::update (d, p, n, mesh)) { this->_child = &child; this->_projectedPosition = projP; return true; } else { return false; } } SketchNode& SketchBoneIntersection::parent () const { assert (this->isIntersection ()); assert (this->_child); return *this->_child->parent (); } SketchNode& SketchBoneIntersection::child () const { assert (this->isIntersection ()); assert (this->_child); return *this->_child; } const glm::vec3& SketchBoneIntersection::projectedPosition () const { assert (this->isIntersection ()); return this->_projectedPosition; } ================================================ FILE: lib/src/sketch/bone-intersection.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SKETCH_BONE_INTERSECTION #define DILAY_SKETCH_BONE_INTERSECTION #include "sketch/fwd.hpp" #include "sketch/mesh-intersection.hpp" class SketchBoneIntersection : public SketchMeshIntersection { public: SketchBoneIntersection (); SketchNode& parent () const; SketchNode& child () const; const glm::vec3& projectedPosition () const; bool update (float, const glm::vec3&, const glm::vec3&, const glm::vec3&, SketchMesh&, SketchNode&); private: SketchNode* _child; glm::vec3 _projectedPosition; }; #endif ================================================ FILE: lib/src/sketch/fwd.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SKETCH_FWD #define DILAY_SKETCH_FWD #include "primitive/sphere.hpp" #include "tree.hpp" class SketchPath; using SketchPaths = std::vector; class SketchNodeIntersection; class SketchBoneIntersection; class SketchMeshIntersection; class SketchPathIntersection; using SketchNode = TreeNode; using SketchTree = Tree; class SketchMesh; #endif ================================================ FILE: lib/src/sketch/mesh-intersection.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "sketch/mesh-intersection.hpp" #include "sketch/mesh.hpp" SketchMeshIntersection::SketchMeshIntersection () : _mesh (nullptr) { } bool SketchMeshIntersection::update (float d, const glm::vec3& p, const glm::vec3& n, SketchMesh& mesh) { if (this->Intersection::update (d, p, n)) { this->_mesh = &mesh; return true; } else { return false; } } SketchMesh& SketchMeshIntersection::mesh () const { assert (this->isIntersection ()); assert (this->_mesh); return *this->_mesh; } ================================================ FILE: lib/src/sketch/mesh-intersection.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SKETCH_MESH_INTERSECTION #define DILAY_SKETCH_MESH_INTERSECTION #include "intersection.hpp" #include "sketch/fwd.hpp" class SketchMeshIntersection : public Intersection { public: SketchMeshIntersection (); SketchMesh& mesh () const; bool update (float, const glm::vec3&, const glm::vec3&, SketchMesh&); private: SketchMesh* _mesh; }; #endif ================================================ FILE: lib/src/sketch/mesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "../mesh.hpp" #include "color.hpp" #include "config.hpp" #include "dimension.hpp" #include "distance.hpp" #include "mesh-util.hpp" #include "primitive/aabox.hpp" #include "primitive/cone-sphere.hpp" #include "primitive/cone.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "primitive/sphere.hpp" #include "render-mode.hpp" #include "sketch/bone-intersection.hpp" #include "sketch/mesh.hpp" #include "sketch/node-intersection.hpp" #include "sketch/path-intersection.hpp" #include "sketch/path.hpp" #include "util.hpp" namespace { struct RenderConfig { bool renderWireframe; Color nodeColor; Color bubbleColor; Color sphereColor; RenderConfig () : renderWireframe (false) { } }; bool almostEqual (const glm::vec3& a, const glm::vec3& b) { return glm::distance2 (a, b) <= Util::epsilon () * Util::epsilon (); } class PrimSphereIntersection : public Intersection { public: PrimSphereIntersection () : _sphere (PrimSphere (glm::vec3 (0.0f), 0.0f)) { } bool update (float d, const PrimSphere& s) { if (this->Intersection::update (d, s.center (), glm::vec3 (0.0f))) { this->_sphere = s; return true; } else { return false; } } const PrimSphere& sphere () { assert (this->isIntersection ()); return this->_sphere; } private: PrimSphere _sphere; }; } struct SketchMesh::Impl { SketchMesh* self; SketchTree tree; SketchPaths paths; Mesh sphereMesh; Mesh boneMesh; RenderConfig renderConfig; Impl (SketchMesh* s) : self (s) { this->sphereMesh = MeshUtil::icosphere (3); this->sphereMesh.bufferData (); this->boneMesh = MeshUtil::cone (16); this->boneMesh.renderMode ().flatShading (true); this->boneMesh.position (glm::vec3 (0.0f, 0.5f, 0.0f)); this->boneMesh.normalize (); this->boneMesh.bufferData (); } Impl (const Impl& other) : self (nullptr) , tree (other.tree) , paths (other.paths) , sphereMesh (other.sphereMesh) , boneMesh (other.boneMesh) , renderConfig (other.renderConfig) { this->sphereMesh.bufferData (); this->boneMesh.bufferData (); } bool isEmpty () const { return this->tree.hasRoot () == false && this->paths.empty (); } void fromTree (const SketchTree& newTree) { this->tree = newTree; } void reset () { this->tree.reset (); } bool intersects (const PrimRay& ray, SketchNodeIntersection& intersection, const SketchNode* exclude = nullptr) { if (this->tree.hasRoot ()) { this->tree.root ().forEachNode ([this, &ray, &intersection, exclude](SketchNode& node) { float t; if (&node != exclude && IntersectionUtil::intersects (ray, node.data (), &t)) { const glm::vec3 p = ray.pointAt (t); intersection.update (t, p, glm::normalize (p - node.data ().center ()), *this->self, node); } }); } return intersection.isIntersection (); } bool intersects (const PrimRay& ray, SketchBoneIntersection& intersection) { if (this->tree.hasRoot ()) { this->tree.root ().forEachNode ([this, &ray, &intersection](SketchNode& node) { if (node.parent ()) { const PrimConeSphere coneSphere (node.data (), node.parent ()->data ()); if (coneSphere.hasCone ()) { const PrimCone cone = coneSphere.toCone (); float tRay, tCone; if (IntersectionUtil::intersects (ray, cone, &tRay, &tCone)) { const glm::vec3 p = ray.pointAt (tRay); intersection.update (tRay, p, cone.projPointAt (tCone), cone.normalAt (p, tCone), *this->self, node); } } } }); } return intersection.isIntersection (); } bool intersects (const PrimRay& ray, SketchMeshIntersection& intersection, unsigned int numExcludedLastPaths) { SketchNodeIntersection snIntersection; SketchBoneIntersection sbIntersection; SketchPathIntersection spIntersection; if (this->intersects (ray, snIntersection)) { intersection.update (snIntersection.distance (), snIntersection.position (), snIntersection.normal (), snIntersection.mesh ()); } if (this->intersects (ray, sbIntersection)) { intersection.update (sbIntersection.distance (), sbIntersection.position (), sbIntersection.normal (), sbIntersection.mesh ()); } if (numExcludedLastPaths < this->paths.size ()) { for (unsigned int i = 0; i < this->paths.size () - numExcludedLastPaths; i++) { if (this->paths.at (i).intersects (ray, *this->self, spIntersection)) { intersection.update (spIntersection.distance (), spIntersection.position (), spIntersection.normal (), spIntersection.mesh ()); } } } return intersection.isIntersection (); } bool intersects (const PrimRay& ray, SketchPathIntersection& intersection) { for (unsigned int i = 0; i < this->paths.size (); i++) { this->paths.at (i).intersects (ray, *this->self, intersection); } return intersection.isIntersection (); } bool intersects (const glm::vec3& point, PrimSphereIntersection& intersection, const SketchPath& excluded) { auto checkSphere = [&point, &intersection](const SketchNode& node) { const float d2 = glm::distance2 (point, node.data ().center ()); if (d2 <= node.data ().radius () * node.data ().radius ()) { intersection.update (glm::sqrt (d2), node.data ()); } }; auto checkBone = [&point, &intersection, &checkSphere](const SketchNode& node) { if (node.parent ()) { const PrimConeSphere coneSphere (node.data (), node.parent ()->data ()); if (coneSphere.hasCone ()) { const glm::vec3 toP = point - coneSphere.sphere1 ().center (); const float x = glm::dot (toP, coneSphere.direction ()); const float y = glm::sqrt (glm::dot (toP, toP) - (x * x)); const float sigma = glm::half_pi () - coneSphere.alpha (); const float xOff = x - (y / glm::tan (sigma)); float nearestFactor; float nearestRadius; if (xOff <= 0.0f) { nearestFactor = 0.0f; nearestRadius = coneSphere.sphere1 ().radius (); } else if (xOff >= coneSphere.length ()) { nearestFactor = coneSphere.length (); nearestRadius = coneSphere.sphere2 ().radius (); } else { nearestFactor = xOff; nearestRadius = glm::mix (coneSphere.sphere1 ().radius (), coneSphere.sphere2 ().radius (), xOff / coneSphere.length ()); } const glm::vec3 nearestCenter = coneSphere.sphere1 ().center () + (nearestFactor * coneSphere.direction ()); const float d2 = glm::distance2 (point, nearestCenter); if (d2 <= nearestRadius * nearestRadius) { intersection.update (glm::sqrt (d2), PrimSphere (nearestCenter, nearestRadius)); } } else { const float d2 = glm::distance2 (point, coneSphere.sphere1 ().center ()); if (d2 <= coneSphere.sphere1 ().radius () * coneSphere.sphere1 ().radius ()) { intersection.update (glm::sqrt (d2), coneSphere.sphere1 ()); } } } else { checkSphere (node); } }; if (this->tree.hasRoot ()) { this->tree.root ().forEachNode ([&checkBone](SketchNode& node) { checkBone (node); }); } for (const SketchPath& p : this->paths) { if (&p != &excluded) { for (const PrimSphere& s : p.spheres ()) { checkSphere (s); } } } return intersection.isIntersection (); } void renderTree (Camera& camera) { if (this->tree.hasRoot ()) { this->tree.root ().forEachConstNode ([this, &camera](const SketchNode& node) { const glm::vec3& pos = node.data ().center (); const float radius = node.data ().radius (); this->sphereMesh.position (pos); this->sphereMesh.scaling (glm::vec3 (radius)); this->sphereMesh.color (this->renderConfig.nodeColor); this->sphereMesh.render (camera); if (node.parent ()) { const glm::vec3& parPos = node.parent ()->data ().center (); const float parRadius = node.parent ()->data ().radius (); const float distance = glm::distance (pos, parPos); const glm::vec3 direction = (parPos - pos) / distance; if (this->renderConfig.renderWireframe) { const glm::vec3 down = glm::vec3 (0.0f, -1.0f, 0.0f); if (Util::colinearUnit (direction, down)) { this->boneMesh.rotationMatrix (glm::mat4x4 (1.0f)); if (glm::dot (direction, down) < 0.0f) { this->boneMesh.rotateX (glm::pi ()); } } else { this->boneMesh.rotationMatrix (glm::orientation (direction, down)); } this->boneMesh.color (this->renderConfig.nodeColor); this->boneMesh.position (parPos); this->boneMesh.scaling (glm::vec3 (parRadius, distance, parRadius)); this->boneMesh.render (camera); } else { this->sphereMesh.color (this->renderConfig.bubbleColor); for (float d = radius * 0.5f; d < distance;) { const glm::vec3 bubblePos = pos + (d * direction); const float bubbleRadius = glm::mix (radius, parRadius, d / distance); this->sphereMesh.position (bubblePos); this->sphereMesh.scaling (glm::vec3 (bubbleRadius)); this->sphereMesh.render (camera); d += bubbleRadius * 0.5f; } } } }); } } void renderPaths (Camera& camera) { this->sphereMesh.color (this->renderConfig.sphereColor); for (const SketchPath& p : this->paths) { p.render (camera, this->sphereMesh); } } void render (Camera& camera) { this->renderTree (camera); if (this->renderConfig.renderWireframe == false) { this->renderPaths (camera); } } void renderWireframe (bool v) { this->renderConfig.renderWireframe = v; } PrimPlane mirrorPlane (Dimension dim) const { if (this->tree.hasRoot ()) { return PrimPlane (this->tree.root ().data ().center (), DimensionUtil::vector (dim)); } else { return PrimPlane (glm::vec3 (0.0f), DimensionUtil::vector (dim)); } } SketchNode* mirrored (const SketchNode& node, const PrimPlane& mirrorPlane, const SketchNode& exclude) { if (this->tree.hasRoot () && node.parent ()) { SketchNode* result = nullptr; const glm::vec3 pos = mirrorPlane.mirror (node.data ().center ()); this->tree.root ().forEachNode ([&exclude, &result, &pos](SketchNode& n) { if (n.parent () && (&exclude != &n) && almostEqual (n.data ().center (), pos)) { result = &n; } }); return result; } else { return nullptr; } } SketchPath* mirrored (const SketchPath& path) { const unsigned int pathIndex = Util::findIndexByReference (this->paths, path); if (pathIndex > 0 && this->paths.at (pathIndex - 1).spheres ().size () == path.spheres ().size ()) { return &this->paths.at (pathIndex - 1); } else if (pathIndex < this->paths.size () - 1 && this->paths.at (pathIndex + 1).spheres ().size () == path.spheres ().size ()) { return &this->paths.at (pathIndex + 1); } else { return nullptr; } } SketchNode* addMirroredNode (SketchNode& node, const PrimPlane& mirrorPlane) { const glm::vec3 pos = mirrorPlane.mirror (node.data ().center ()); const float radius = node.data ().radius (); SketchNode& parent = *node.parent (); if (parent.parent () == nullptr) { return &parent.emplaceChild (pos, radius); } else { SketchNode* parentM = this->mirrored (parent, mirrorPlane, node); return bool(parentM) ? &parentM->emplaceChild (pos, radius) : nullptr; } } SketchNode& addChild (SketchNode& parent, const glm::vec3& pos, float radius, const Dimension* dim) { SketchNode& newNode = parent.emplaceChild (pos, radius); if (dim) { this->addMirroredNode (newNode, this->mirrorPlane (*dim)); } return newNode; } SketchNode& addParent (SketchNode& child, const glm::vec3& pos, float radius, const Dimension* dim) { assert (child.parent ()); SketchNode& newNode = child.parent ()->emplaceChild (pos, radius); newNode.addChild (child); if (dim) { const PrimPlane mPlane = this->mirrorPlane (*dim); SketchNode* childM = this->mirrored (child, mPlane, child); if (childM && childM->parent ()) { SketchNode* newNodeM = this->addMirroredNode (newNode, mPlane); if (newNodeM) { newNodeM->addChild (*childM); childM->parent ()->deleteChild (*childM); } } } child.parent ()->deleteChild (child); return newNode; } SketchPath& addPath (const SketchPath& path) { this->paths.push_back (path); return this->paths.back (); } void addSphere (bool newPath, const glm::vec3& intersection, const glm::vec3& position, float radius, const Dimension* dim) { if (newPath) { this->paths.emplace_back (); if (dim) { this->paths.emplace_back (); } } this->paths.back ().addSphere (intersection, position, radius); if (dim) { const PrimPlane mirrorPlane = this->mirrorPlane (*dim); this->paths.at (this->paths.size () - 2) .addSphere (mirrorPlane.mirror (intersection), mirrorPlane.mirror (position), radius); } } void move (SketchNode& node, const glm::vec3& delta, bool all, const Dimension* dim) { const auto moveNodes = [all](SketchNode& node, const glm::vec3& delta) { if (all) { node.forEachNode ( [&delta](SketchNode& n) { n.data ().center (n.data ().center () + delta); }); } else { node.data ().center (node.data ().center () + delta); } }; if (dim) { const PrimPlane mirrorPlane = this->mirrorPlane (*dim); SketchNode* nodeM = this->mirrored (node, mirrorPlane, node); moveNodes (node, delta); if (nodeM) { moveNodes (*nodeM, mirrorPlane.mirrorDirection (delta)); } } else { moveNodes (node, delta); } } void scale (SketchNode& node, float factor, bool all, const Dimension* dim) { const auto scaleNodes = [factor, all](SketchNode& node) { if (all) { node.forEachNode ( [factor](SketchNode& n) { n.data ().radius (n.data ().radius () * factor); }); } else { node.data ().radius (node.data ().radius () * factor); } }; if (dim) { SketchNode* nodeM = this->mirrored (node, this->mirrorPlane (*dim), node); scaleNodes (node); if (nodeM) { scaleNodes (*nodeM); } } else { scaleNodes (node); } } void rotate (SketchNode& node, const glm::vec3& axis, float angle, const Dimension* dim) { const auto rotateNodes = [](SketchNode& node, const glm::vec3& axis, float angle) { const glm::mat4x4 matrix = Util::rotation (node.data ().center (), axis, angle); node.forEachNode ([&matrix](SketchNode& n) { n.data ().center (glm::vec3 (matrix * glm::vec4 (n.data ().center (), 1.0f))); }); }; if (dim) { const PrimPlane mirrorPlane = this->mirrorPlane (*dim); SketchNode* nodeM = this->mirrored (node, mirrorPlane, node); rotateNodes (node, axis, angle); if (nodeM) { rotateNodes (*nodeM, mirrorPlane.mirrorDirection (axis), -angle); } } else { rotateNodes (node, axis, angle); } } void deleteNode (SketchNode& node, bool deleteChildren, const Dimension* dim) { assert (this->tree.hasRoot ()); if (node.parent () == nullptr) { this->reset (); } else if (deleteChildren) { if (dim) { SketchNode* nodeM = this->mirrored (node, this->mirrorPlane (*dim), node); if (nodeM && nodeM->parent ()) { nodeM->parent ()->deleteChild (*nodeM); } } node.parent ()->deleteChild (node); } else { node.forEachChild ([&node](SketchNode& child) { node.parent ()->addChild (child); }); if (dim) { SketchNode* nodeM = this->mirrored (node, this->mirrorPlane (*dim), node); if (nodeM && nodeM->parent ()) { nodeM->forEachChild ([nodeM](SketchNode& child) { nodeM->parent ()->addChild (child); }); nodeM->parent ()->deleteChild (*nodeM); } } node.parent ()->deleteChild (node); } } void deletePath (SketchPath& path, const Dimension* dim) { assert (this->paths.empty () == false); if (dim && this->paths.size () >= 2) { const unsigned int index = Util::findIndexByReference (this->paths, path); const SketchPath* mPath = this->mirrored (path); if (mPath) { const unsigned int mIndex = Util::findIndexByReference (this->paths, *mPath); if (mIndex < index) { this->paths.erase (this->paths.begin () + index); this->paths.erase (this->paths.begin () + mIndex); } else if (index < mIndex) { this->paths.erase (this->paths.begin () + mIndex); this->paths.erase (this->paths.begin () + index); } else { DILAY_IMPOSSIBLE } } else { this->paths.erase (this->paths.begin () + index); } } else { this->paths.erase (this->paths.begin ()); } } void mirrorPositiveTree (Dimension dim) { if (this->tree.hasRoot ()) { const PrimPlane mirrorPlane = this->mirrorPlane (dim); auto requiresMirroring = [&mirrorPlane](const SketchNode& node) { assert (node.parent ()); return (mirrorPlane.absDistance (node.data ().center ()) > Util::epsilon ()) || (mirrorPlane.absDistance (node.parent ()->data ().center ()) > Util::epsilon ()); }; std::function mirrorPositiveNode = [this, &mirrorPlane, &requiresMirroring, &mirrorPositiveNode](SketchNode& node) { unsigned int numChildren = node.numChildren (); node.forEachChild ([this, &mirrorPlane, &requiresMirroring, &mirrorPositiveNode, &numChildren](SketchNode& c) { if (numChildren > 0) { if (requiresMirroring (c)) { this->addMirroredNode (c, mirrorPlane); } mirrorPositiveNode (c); numChildren--; } }); }; this->tree.root ().forEachNode ([&mirrorPlane](SketchNode& parent) { parent.deleteChildIf ([&mirrorPlane](const SketchNode& child) { return mirrorPlane.distance (child.data ().center ()) < -Util::epsilon (); }); }); mirrorPositiveNode (this->tree.root ()); } } void mirrorPositivePaths (Dimension dim) { const PrimPlane mPlane = this->mirrorPlane (dim); SketchPaths oldPaths = std::move (this->paths); this->paths.clear (); for (SketchPath& p : oldPaths) { SketchPath mirrored = p.mirrorPositive (mPlane); if (p.isEmpty () == false) { this->paths.push_back (std::move (mirrored)); this->paths.push_back (std::move (p)); } } } void mirrorPositive (Dimension dim) { this->mirrorPositiveTree (dim); this->mirrorPositivePaths (dim); } void rebalance (SketchNode& newRoot) { assert (this->tree.hasRoot ()); this->tree.rebalance (newRoot); } SketchNode& snap (SketchNode& node, Dimension dim) { assert (this->tree.hasRoot ()); const PrimPlane mPlane = this->mirrorPlane (dim); SketchNode* nodeM = this->mirrored (node, mPlane, node); if (nodeM && nodeM != &node) { if (nodeM->parent () == node.parent ()) { SketchNode& snapped = this->addChild ( *node.parent (), 0.5f * (node.data ().center () + nodeM->data ().center ()), node.data ().radius (), nullptr); node.forEachConstChild ([&snapped](const SketchNode& c) { snapped.addChild (c); }); nodeM->forEachConstChild ([&snapped](const SketchNode& c) { snapped.addChild (c); }); this->deleteNode (node, true, &dim); return snapped; } else { node.data ().center (mPlane.project (node.data ().center ())); nodeM->data ().center (mPlane.project (nodeM->data ().center ())); return node; } } else { node.data ().center (mPlane.project (node.data ().center ())); return node; } } void minMax (glm::vec3& min, glm::vec3& max) const { min = glm::vec3 (Util::maxFloat ()); max = glm::vec3 (Util::minFloat ()); if (this->tree.hasRoot ()) { this->tree.root ().forEachConstNode ([&min, &max](const SketchNode& node) { min = glm::min (min, node.data ().center () - glm::vec3 (node.data ().radius ())); max = glm::max (max, node.data ().center () + glm::vec3 (node.data ().radius ())); }); } for (const SketchPath& p : this->paths) { min = glm::min (min, p.minimum ()); max = glm::max (max, p.maximum ()); } } void smoothPath (SketchPath& path, const PrimSphere& range, unsigned int halfWidth, SketchPathSmoothEffect effect, const Dimension* dim) { if (IntersectionUtil::intersects (range, path.aabox ())) { PrimSphereIntersection intersection1, intersection2; this->intersects (path.spheres ().front ().center (), intersection1, path); this->intersects (path.spheres ().back ().center (), intersection2, path); if (dim) { SketchPath* mPath = this->mirrored (path); if (mPath) { PrimSphereIntersection intersection3, intersection4; this->intersects (mPath->spheres ().front ().center (), intersection3, *mPath); this->intersects (mPath->spheres ().back ().center (), intersection4, *mPath); mPath->smooth ( PrimSphere (this->mirrorPlane (*dim).mirror (range.center ()), range.radius ()), halfWidth, effect, intersection3.isIntersection () ? &intersection3.sphere () : nullptr, intersection4.isIntersection () ? &intersection4.sphere () : nullptr); } } path.smooth (range, halfWidth, effect, intersection1.isIntersection () ? &intersection1.sphere () : nullptr, intersection2.isIntersection () ? &intersection2.sphere () : nullptr); } } void optimizePaths () { for (SketchPath& p1 : this->paths) { for (SketchPath& p2 : this->paths) { if (&p1 < &p2) { for (auto it1 = p1.spheres ().begin (); it1 != p1.spheres ().end ();) { bool deletedP1Sphere = false; for (auto it2 = p2.spheres ().begin (); it2 != p2.spheres ().end ();) { const PrimSphere& s1 = *it1; const PrimSphere& s2 = *it2; const float d = glm::distance (s1.center (), s2.center ()); if (s2.radius () > d + s1.radius ()) { it1 = p1.deleteSphere (it1); deletedP1Sphere = true; break; } else if (s1.radius () > d + s2.radius ()) { it2 = p2.deleteSphere (it2); } else { ++it2; } } if (deletedP1Sphere == false) { ++it1; } } } } if (this->tree.hasRoot ()) { this->tree.root ().forEachNode ([&p1](SketchNode& node) { if (node.parent ()) { const PrimConeSphere coneSphere (node.data (), node.parent ()->data ()); for (auto it1 = p1.spheres ().begin (); it1 != p1.spheres ().end ();) { const PrimSphere& s1 = *it1; const float d = Distance::distance (coneSphere, s1.center ()); if (d < -s1.radius ()) { it1 = p1.deleteSphere (it1); } else { ++it1; } } } }); } } } void runFromConfig (const Config& config) { this->renderConfig.nodeColor = config.get ("editor/sketch/node/color"); this->renderConfig.bubbleColor = config.get ("editor/sketch/bubble/color"); this->renderConfig.sphereColor = config.get ("editor/sketch/sphere/color"); } }; DELEGATE_BIG4_COPY_SELF (SketchMesh); GETTER_CONST (const SketchTree&, SketchMesh, tree) GETTER (SketchTree&, SketchMesh, tree) GETTER_CONST (const SketchPaths&, SketchMesh, paths) DELEGATE_CONST (bool, SketchMesh, isEmpty) DELEGATE1 (void, SketchMesh, fromTree, const SketchTree&) DELEGATE (void, SketchMesh, reset) DELEGATE3 (bool, SketchMesh, intersects, const PrimRay&, SketchNodeIntersection&, const SketchNode*) DELEGATE2 (bool, SketchMesh, intersects, const PrimRay&, SketchBoneIntersection&) DELEGATE3 (bool, SketchMesh, intersects, const PrimRay&, SketchMeshIntersection&, unsigned int) DELEGATE2 (bool, SketchMesh, intersects, const PrimRay&, SketchPathIntersection&) DELEGATE1 (void, SketchMesh, render, Camera&) DELEGATE1 (void, SketchMesh, renderWireframe, bool) DELEGATE1 (PrimPlane, SketchMesh, mirrorPlane, Dimension) DELEGATE4 (SketchNode&, SketchMesh, addChild, SketchNode&, const glm::vec3&, float, const Dimension*) DELEGATE4 (SketchNode&, SketchMesh, addParent, SketchNode&, const glm::vec3&, float, const Dimension*) DELEGATE1 (SketchPath&, SketchMesh, addPath, const SketchPath&) DELEGATE5 (void, SketchMesh, addSphere, bool, const glm::vec3&, const glm::vec3&, float, const Dimension*) DELEGATE4 (void, SketchMesh, move, SketchNode&, const glm::vec3&, bool, const Dimension*) DELEGATE4 (void, SketchMesh, scale, SketchNode&, float, bool, const Dimension*) DELEGATE4 (void, SketchMesh, rotate, SketchNode&, const glm::vec3&, float, const Dimension*) DELEGATE3 (void, SketchMesh, deleteNode, SketchNode&, bool, const Dimension*) DELEGATE2 (void, SketchMesh, deletePath, SketchPath&, const Dimension*) DELEGATE1 (void, SketchMesh, mirrorPositive, Dimension) DELEGATE1 (void, SketchMesh, rebalance, SketchNode&) DELEGATE2 (SketchNode&, SketchMesh, snap, SketchNode&, Dimension) DELEGATE2_CONST (void, SketchMesh, minMax, glm::vec3&, glm::vec3&) DELEGATE5 (void, SketchMesh, smoothPath, SketchPath&, const PrimSphere&, unsigned int, SketchPathSmoothEffect, const Dimension*) DELEGATE (void, SketchMesh, optimizePaths) DELEGATE1 (void, SketchMesh, runFromConfig, const Config&) ================================================ FILE: lib/src/sketch/mesh.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SKETCH_MESH #define DILAY_SKETCH_MESH #include #include "configurable.hpp" #include "macro.hpp" #include "sketch/fwd.hpp" class Camera; enum class Dimension; class PrimPlane; class PrimRay; class PrimSphere; enum class SketchPathSmoothEffect; class SketchMesh : public Configurable { public: DECLARE_BIG4_EXPLICIT_COPY (SketchMesh); const SketchTree& tree () const; SketchTree& tree (); const SketchPaths& paths () const; bool isEmpty () const; void fromTree (const SketchTree&); void reset (); bool intersects (const PrimRay&, SketchNodeIntersection&, const SketchNode* = nullptr); bool intersects (const PrimRay&, SketchBoneIntersection&); bool intersects (const PrimRay&, SketchMeshIntersection&, unsigned int = 0); bool intersects (const PrimRay&, SketchPathIntersection&); void render (Camera&); void renderWireframe (bool); PrimPlane mirrorPlane (Dimension); SketchNode& addChild (SketchNode&, const glm::vec3&, float, const Dimension*); SketchNode& addParent (SketchNode&, const glm::vec3&, float, const Dimension*); SketchPath& addPath (const SketchPath&); void addSphere (bool, const glm::vec3&, const glm::vec3&, float, const Dimension*); void move (SketchNode&, const glm::vec3&, bool, const Dimension*); void scale (SketchNode&, float, bool, const Dimension*); void rotate (SketchNode&, const glm::vec3&, float, const Dimension*); void deleteNode (SketchNode&, bool, const Dimension*); void deletePath (SketchPath&, const Dimension*); void mirrorPositive (Dimension); void rebalance (SketchNode&); SketchNode& snap (SketchNode&, Dimension); void minMax (glm::vec3&, glm::vec3&) const; void smoothPath (SketchPath&, const PrimSphere&, unsigned int, SketchPathSmoothEffect, const Dimension*); void optimizePaths (); private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/sketch/node-intersection.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "sketch/mesh.hpp" #include "sketch/node-intersection.hpp" SketchNodeIntersection::SketchNodeIntersection () : _node (nullptr) { } bool SketchNodeIntersection::update (float d, const glm::vec3& p, const glm::vec3& n, SketchMesh& mesh, SketchNode& node) { if (this->SketchMeshIntersection::update (d, p, n, mesh)) { this->_node = &node; return true; } else { return false; } } SketchNode& SketchNodeIntersection::node () const { assert (this->isIntersection ()); assert (this->_node); return *this->_node; } ================================================ FILE: lib/src/sketch/node-intersection.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SKETCH_NODE_INTERSECTION #define DILAY_SKETCH_NODE_INTERSECTION #include "sketch/fwd.hpp" #include "sketch/mesh-intersection.hpp" class SketchNodeIntersection : public SketchMeshIntersection { public: SketchNodeIntersection (); SketchNode& node () const; bool update (float, const glm::vec3&, const glm::vec3&, SketchMesh&, SketchNode&); private: SketchNode* _node; }; #endif ================================================ FILE: lib/src/sketch/path-intersection.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "sketch/path-intersection.hpp" #include "sketch/path.hpp" SketchPathIntersection::SketchPathIntersection () : _path (nullptr) { } bool SketchPathIntersection::update (float d, const glm::vec3& p, const glm::vec3& n, SketchMesh& mesh, SketchPath& path) { if (this->SketchMeshIntersection::update (d, p, n, mesh)) { this->_path = &path; return true; } else { return false; } } SketchPath& SketchPathIntersection::path () const { assert (this->isIntersection ()); assert (this->_path); return *this->_path; } ================================================ FILE: lib/src/sketch/path-intersection.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SKETCH_PATH_INTERSECTION #define DILAY_SKETCH_PATH_INTERSECTION #include "sketch/fwd.hpp" #include "sketch/mesh-intersection.hpp" class SketchPathIntersection : public SketchMeshIntersection { public: SketchPathIntersection (); SketchPath& path () const; bool update (float, const glm::vec3&, const glm::vec3&, SketchMesh&, SketchPath&); private: SketchPath* _path; }; #endif ================================================ FILE: lib/src/sketch/path.cpp ================================================ #include "../mesh.hpp" #include "intersection.hpp" #include "primitive/aabox.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "sketch/path-intersection.hpp" #include "sketch/path.hpp" #include "util.hpp" struct SketchPath::Impl { SketchPath* self; SketchPath::Spheres spheres; glm::vec3 minimum; glm::vec3 maximum; glm::vec3 intersectionFirst; glm::vec3 intersectionLast; Impl (SketchPath* s) : self (s) { this->resetMinMax (); } void resetMinMax () { this->minimum = glm::vec3 (Util::maxFloat ()); this->maximum = glm::vec3 (Util::minFloat ()); } void reset () { this->resetMinMax (); this->spheres.clear (); } void setMinMax () { this->resetMinMax (); for (const PrimSphere& s : this->spheres) { this->maximum = glm::max (this->maximum, s.center () + glm::vec3 (s.radius ())); this->minimum = glm::min (this->minimum, s.center () - glm::vec3 (s.radius ())); } } bool isEmpty () const { return this->spheres.empty (); } PrimAABox aabox () const { assert (this->isEmpty () == false); return PrimAABox (this->minimum, this->maximum); } void addSphere (const glm::vec3& intersection, const glm::vec3& position, float radius) { if (this->spheres.empty ()) { this->intersectionFirst = intersection; this->intersectionLast = intersection; } else { this->intersectionLast = intersection; } this->maximum = glm::max (this->maximum, position + glm::vec3 (radius)); this->minimum = glm::min (this->minimum, position - glm::vec3 (radius)); this->spheres.emplace_back (position, radius); } SketchPath::Spheres::iterator deleteSphere (SketchPath::Spheres::const_iterator it) { return this->spheres.erase (it); } void render (Camera& camera, Mesh& mesh) const { for (const PrimSphere& s : this->spheres) { mesh.position (s.center ()); mesh.scaling (glm::vec3 (s.radius ())); mesh.render (camera); } } bool intersects (const PrimRay& ray, SketchMesh& mesh, SketchPathIntersection& intersection) { const PrimAABox aabox (this->minimum, this->maximum); float t; if (IntersectionUtil::intersects (ray, aabox, &t)) { if (intersection.isIntersection () == false || t < intersection.distance ()) { for (const PrimSphere& s : this->spheres) { if (IntersectionUtil::intersects (ray, s, &t)) { intersection.update (t, ray.pointAt (t), glm::normalize (ray.pointAt (t) - s.center ()), mesh, *this->self); } } } } return intersection.isIntersection (); } SketchPath mirrorPositive (const PrimPlane& mPlane) { SketchPath::Spheres oldSpheres (std::move (this->spheres)); const glm::vec3 oldIntersectionFirst (this->intersectionFirst); const glm::vec3 oldIntersectionLast (this->intersectionLast); SketchPath mirrored; this->reset (); for (unsigned int i = 0; i < oldSpheres.size (); i++) { const PrimSphere& s = oldSpheres[i]; if (mPlane.distance (s.center ()) > -Util::epsilon ()) { const glm::vec3 mCenter = mPlane.mirror (s.center ()); if (i == 0) { this->addSphere (oldIntersectionFirst, s.center (), s.radius ()); mirrored.addSphere (mPlane.mirror (oldIntersectionFirst), mCenter, s.radius ()); } else if (i == oldSpheres.size () - 1) { this->addSphere (oldIntersectionLast, s.center (), s.radius ()); mirrored.addSphere (mPlane.mirror (oldIntersectionLast), mCenter, s.radius ()); } else { this->addSphere (s.center (), s.center (), s.radius ()); mirrored.addSphere (mCenter, mCenter, s.radius ()); } } } return mirrored; } void smooth (const PrimSphere& range, unsigned int halfWidth, SketchPathSmoothEffect effect, const PrimSphere* nearestToFirst, const PrimSphere* nearestToLast) { const unsigned int numS = this->spheres.size (); for (unsigned int i = 0; i < numS; i++) { if (IntersectionUtil::intersects (range, this->spheres.at (i))) { const unsigned int hW = i < halfWidth ? i : (i >= numS - halfWidth ? numS - i - 1 : halfWidth); glm::vec3 center (0.0f); float radius (0.0f); for (unsigned int j = i - hW; j <= i + hW; j++) { center += this->spheres.at (j).center (); radius += this->spheres.at (j).radius (); } const bool effectEmbeds = effect == SketchPathSmoothEffect::Embed || effect == SketchPathSmoothEffect::EmbedAndAdjust; unsigned int numAffectedCenter = 0; unsigned int numAffectedRadius = 0; if (effect != SketchPathSmoothEffect::None) { if (i < halfWidth) { if (nearestToFirst && effectEmbeds) { numAffectedCenter++; center += nearestToFirst->center (); } if (nearestToFirst && effect == SketchPathSmoothEffect::EmbedAndAdjust) { numAffectedRadius++; radius += nearestToFirst->radius (); } else if (effect == SketchPathSmoothEffect::Pinch) { numAffectedRadius++; numAffectedCenter++; center += this->intersectionFirst; } } if (i >= numS - halfWidth) { if (nearestToLast && effectEmbeds) { numAffectedCenter++; center += nearestToLast->center (); } if (nearestToLast && effect == SketchPathSmoothEffect::EmbedAndAdjust) { numAffectedRadius++; radius += nearestToLast->radius (); } else if (effect == SketchPathSmoothEffect::Pinch) { numAffectedRadius++; numAffectedCenter++; center += this->intersectionLast; } } } this->spheres.at (i).center (center / float((2 * hW) + 1 + numAffectedCenter)); this->spheres.at (i).radius (radius / float((2 * hW) + 1 + numAffectedRadius)); } } this->setMinMax (); } }; DELEGATE_BIG6_SELF (SketchPath) GETTER_CONST (const SketchPath::Spheres&, SketchPath, spheres) GETTER_CONST (const glm::vec3&, SketchPath, minimum) GETTER_CONST (const glm::vec3&, SketchPath, maximum) GETTER_CONST (const glm::vec3&, SketchPath, intersectionFirst) GETTER_CONST (const glm::vec3&, SketchPath, intersectionLast) SETTER (const glm::vec3&, SketchPath, intersectionFirst) SETTER (const glm::vec3&, SketchPath, intersectionLast) DELEGATE (void, SketchPath, reset) DELEGATE_CONST (bool, SketchPath, isEmpty) DELEGATE_CONST (PrimAABox, SketchPath, aabox) DELEGATE3 (void, SketchPath, addSphere, const glm::vec3&, const glm::vec3&, float) DELEGATE1 (SketchPath::Spheres::iterator, SketchPath, deleteSphere, SketchPath::Spheres::const_iterator) DELEGATE2_CONST (void, SketchPath, render, Camera&, Mesh&) DELEGATE3 (bool, SketchPath, intersects, const PrimRay&, SketchMesh&, SketchPathIntersection&) DELEGATE1 (SketchPath, SketchPath, mirrorPositive, const PrimPlane&) DELEGATE5 (void, SketchPath, smooth, const PrimSphere&, unsigned int, SketchPathSmoothEffect, const PrimSphere*, const PrimSphere*) ================================================ FILE: lib/src/sketch/path.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_SKETCH_PATH #define DILAY_SKETCH_PATH #include #include "macro.hpp" #include "sketch/fwd.hpp" class Camera; class Intersection; class Mesh; class PrimAABox; class PrimPlane; class PrimRay; enum class SketchPathSmoothEffect { None, Embed, EmbedAndAdjust, Pinch }; class SketchPath { public: using Spheres = std::vector; DECLARE_BIG6 (SketchPath); const Spheres& spheres () const; const glm::vec3& minimum () const; const glm::vec3& maximum () const; const glm::vec3& intersectionFirst () const; const glm::vec3& intersectionLast () const; void intersectionFirst (const glm::vec3&); void intersectionLast (const glm::vec3&); void reset (); bool isEmpty () const; PrimAABox aabox () const; void addSphere (const glm::vec3&, const glm::vec3&, float); Spheres::iterator deleteSphere (Spheres::const_iterator); void render (Camera&, Mesh&) const; bool intersects (const PrimRay&, SketchMesh&, SketchPathIntersection&); SketchPath mirrorPositive (const PrimPlane&); void smooth (const PrimSphere&, unsigned int, SketchPathSmoothEffect, const PrimSphere*, const PrimSphere*); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/state.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "cache.hpp" #include "camera.hpp" #include "config.hpp" #include "history.hpp" #include "maybe.hpp" #include "scene.hpp" #include "state.hpp" #include "tool.hpp" #include "tools.hpp" #include "view/gl-widget.hpp" #include "view/info-pane.hpp" #include "view/info-pane/scene.hpp" #include "view/main-window.hpp" #include "view/shortcut.hpp" #include "view/tool-pane.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" namespace { typedef State::ViewShortcuts ViewShortcuts; } struct State::Impl { State* self; ViewMainWindow& mainWindow; Config& config; Cache& cache; Camera camera; History history; Scene scene; std::unique_ptr toolPtr; Maybe previousToolKey; std::vector shortcuts; Impl (State* s, ViewMainWindow& mW, Config& cfg, Cache& cch) : self (s) , mainWindow (mW) , config (cfg) , cache (cch) , camera (this->config) , history (this->config) , scene (this->config) { this->resetTool (); } bool hasTool () const { return bool(this->toolPtr); } Tool& tool () { assert (this->hasTool ()); return *this->toolPtr; } void addToolShortcut (const ViewShortcut& shortcut, ViewToolTip& tip) { tip.add (shortcut.event (), shortcut.modifier (), shortcut.label ()); this->shortcuts.push_back (&shortcut.toQShortcut (this->mainWindow)); } void addToolShortcut (ToolKey key, ViewToolTip& tip, ViewInputEvent event, const QString& label) { const QKeySequence keys = ViewInput::toQKeySequence (event, ViewInputModifier::None); tip.add (event, label); this->shortcuts.push_back (new QShortcut (keys, &this->mainWindow)); QObject::connect (this->shortcuts.back (), &QShortcut::activated, [this, key]() { this->setTool (key); }); } void addToolShortcut (ToolKey key, ViewToolTip& tip, ViewInputEvent event) { this->addToolShortcut (key, tip, event, this->mainWindow.toolPane ().buttonText (key)); } void addToggleToolShortcut (ViewToolTip& tip, ViewInputEvent event) { const QKeySequence keys = ViewInput::toQKeySequence (event, ViewInputModifier::None); tip.add (event, QObject::tr ("Toggle back")); this->shortcuts.push_back (new QShortcut (keys, &this->mainWindow)); QObject::connect (this->shortcuts.back (), &QShortcut::activated, [this]() { this->setPreviousTool (); }); } void addExitToolShortcut (ViewToolTip& tip, ViewInputEvent event) { const QKeySequence keys = ViewInput::toQKeySequence (event, ViewInputModifier::None); tip.add (event, QObject::tr ("Exit")); this->shortcuts.push_back (new QShortcut (keys, &this->mainWindow)); QObject::connect (this->shortcuts.back (), &QShortcut::activated, [this]() { #ifndef NDEBUG if (this->hasTool ()) { this->resetTool (); } else { this->mainWindow.close (); } #else assert (this->hasTool ()); this->resetTool (); #endif }); } void setToolTip (const ViewToolTip* toolSpecificToolTip, const ViewShortcuts& shortcuts) { for (QShortcut* s : this->shortcuts) { delete s; } this->shortcuts.clear (); this->mainWindow.infoPane ().resetToolTip (); if (toolSpecificToolTip) { this->mainWindow.infoPane ().addToolTip (*toolSpecificToolTip); } ViewToolTip tip; for (const ViewShortcut& s : shortcuts) { this->addToolShortcut (s, tip); } if (this->hasTool () == false || this->toolPtr->getKey () != ToolKey::MoveCamera) { this->addToolShortcut (ToolKey::MoveCamera, tip, ViewInputEvent::Space, QObject::tr ("Camera mode")); } switch (this->mainWindow.toolPane ().selection ()) { case ViewToolPaneSelection::Sculpt: if (this->hasTool () == false) { this->addToolShortcut (ToolKey::SculptDraw, tip, ViewInputEvent::D); this->addToolShortcut (ToolKey::SculptCrease, tip, ViewInputEvent::C); this->addToolShortcut (ToolKey::SculptGrab, tip, ViewInputEvent::G); this->addToolShortcut (ToolKey::SculptPinch, tip, ViewInputEvent::P); this->addToolShortcut (ToolKey::SculptSmooth, tip, ViewInputEvent::S); this->addToolShortcut (ToolKey::SculptFlatten, tip, ViewInputEvent::F); this->addToolShortcut (ToolKey::SculptReduce, tip, ViewInputEvent::R); this->addToolShortcut (ToolKey::TrimMesh, tip, ViewInputEvent::T); this->addToolShortcut (ToolKey::Remesh, tip, ViewInputEvent::M); #ifndef NDEBUG this->addExitToolShortcut (tip, ViewInputEvent::Esc); #endif } else { const bool smoothShortcut = (this->toolPtr->getKey () == ToolKey::SculptDraw) || (this->toolPtr->getKey () == ToolKey::SculptCrease) || (this->toolPtr->getKey () == ToolKey::SculptGrab) || (this->toolPtr->getKey () == ToolKey::SculptFlatten) || (this->toolPtr->getKey () == ToolKey::SculptPinch) || (this->toolPtr->getKey () == ToolKey::SculptReduce) || (this->toolPtr->getKey () == ToolKey::TrimMesh) || (this->toolPtr->getKey () == ToolKey::Remesh); const bool toggleBackFromSmooth = (this->toolPtr->getKey () == ToolKey::SculptSmooth) && this->previousToolKey && (*this->previousToolKey != ToolKey::SculptSmooth); if (smoothShortcut) { this->addToolShortcut (ToolKey::SculptSmooth, tip, ViewInputEvent::S); } else if (toggleBackFromSmooth) { this->addToggleToolShortcut (tip, ViewInputEvent::S); } this->addExitToolShortcut (tip, ViewInputEvent::Esc); } break; case ViewToolPaneSelection::Sketch: if (this->hasTool () == false) { #ifndef NDEBUG this->addExitToolShortcut (tip, ViewInputEvent::Esc); #endif } else { this->addExitToolShortcut (tip, ViewInputEvent::Esc); } break; } this->mainWindow.infoPane ().addToolTip (tip); if (this->hasTool () == false || this->toolPtr->getKey () != ToolKey::MoveCamera) { tip.reset (); tip.add (ViewInputEvent::MouseMiddle, QObject::tr ("Drag to rotate")); tip.add (ViewInputEvent::MouseMiddle, ViewInputModifier::Shift, QObject::tr ("Drag to move")); tip.add (ViewInputEvent::MouseMiddle, ViewInputModifier::Ctrl, QObject::tr ("Drag to zoom")); tip.add (ViewInputEvent::MouseMiddle, ViewInputModifier::Alt, QObject::tr ("Gaze")); tip.add (ViewInputEvent::MouseWheel, QObject::tr ("Zoom")); this->mainWindow.infoPane ().addToolTip (tip); } } void setToolTip (const ViewToolTip* toolSpecificToolTip) { this->setToolTip (toolSpecificToolTip, {}); } void setTool (ToolKey key) { if (this->hasTool ()) { this->resetTool (); } #define SET_TOOL(name) \ case ToolKey::name: \ this->toolPtr.reset (new Tool##name (*this->self)); \ break; switch (key) { SET_TOOL (TransformMesh) SET_TOOL (DeleteMesh) SET_TOOL (NewMesh) SET_TOOL (SculptDraw) SET_TOOL (SculptGrab) SET_TOOL (SculptSmooth) SET_TOOL (SculptFlatten) SET_TOOL (SculptCrease) SET_TOOL (SculptPinch) SET_TOOL (SculptReduce) SET_TOOL (EditSketch) SET_TOOL (DeleteSketch) SET_TOOL (ConvertSketch) SET_TOOL (SketchSpheres) SET_TOOL (TrimMesh) SET_TOOL (Remesh) SET_TOOL (MoveCamera) } #undef SET_TOOL this->mainWindow.toolPane ().setButtonState (this->toolPtr->getKey (), true); ToolResponse initResponse = this->toolPtr->initialize (); switch (initResponse) { case ToolResponse::None: this->handleToolResponse (ToolResponse::Redraw); break; default: this->handleToolResponse (initResponse); break; } } void setPreviousTool () { if (this->previousToolKey) { this->setTool (*this->previousToolKey); } else { this->resetTool (); } } void resetTool () { if (this->hasTool ()) { if (this->toolPtr->getKey () != ToolKey::MoveCamera) { this->previousToolKey = this->toolPtr->getKey (); } this->mainWindow.toolPane ().setButtonState (this->toolPtr->getKey (), false); this->toolPtr->commit (); this->toolPtr.reset (); this->mainWindow.toolPane ().properties ().reset (); this->mainWindow.update (); } this->setToolTip (nullptr); } void fromConfig () { this->camera.fromConfig (this->config); this->history.fromConfig (this->config); this->scene.fromConfig (this->config); if (this->hasTool ()) { this->toolPtr->fromConfig (); } } void undo () { if (this->hasTool ()) { this->handleToolResponse (this->toolPtr->commit ()); } this->history.undo (*this->self); this->mainWindow.update (); } void redo () { if (this->hasTool ()) { this->handleToolResponse (this->toolPtr->commit ()); } this->history.redo (*this->self); this->mainWindow.update (); } void handleToolResponse (ToolResponse response) { switch (response) { case ToolResponse::None: break; case ToolResponse::Redraw: this->mainWindow.update (); break; case ToolResponse::Terminate: this->resetTool (); break; } } }; DELEGATE3_BIG2_SELF (State, ViewMainWindow&, Config&, Cache&) GETTER (ViewMainWindow&, State, mainWindow) GETTER (Config&, State, config) GETTER (Cache&, State, cache) GETTER (Camera&, State, camera) GETTER (History&, State, history) GETTER (Scene&, State, scene) DELEGATE (bool, State, hasTool) DELEGATE (Tool&, State, tool) DELEGATE1 (void, State, setTool, ToolKey) DELEGATE (void, State, setPreviousTool) DELEGATE2 (void, State, setToolTip, const ViewToolTip*, const ViewShortcuts&) DELEGATE1 (void, State, setToolTip, const ViewToolTip*) DELEGATE (void, State, resetTool) DELEGATE (void, State, fromConfig) DELEGATE (void, State, undo) DELEGATE (void, State, redo) DELEGATE1 (void, State, handleToolResponse, ToolResponse) ================================================ FILE: lib/src/state.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_STATE #define DILAY_STATE #include #include "macro.hpp" class Cache; class Camera; class Config; class History; class Id; class Mesh; class Scene; class Tool; enum class ToolKey; enum class ToolResponse; class ViewMainWindow; class ViewShortcut; class ViewToolTip; class State { public: typedef std::initializer_list ViewShortcuts; DECLARE_BIG2 (State, ViewMainWindow&, Config&, Cache&) ViewMainWindow& mainWindow (); Config& config (); Cache& cache (); Camera& camera (); History& history (); Scene& scene (); bool hasTool (); Tool& tool (); void setTool (ToolKey); void setPreviousTool (); void setToolTip (const ViewToolTip*, const ViewShortcuts&); void setToolTip (const ViewToolTip*); void resetTool (); void fromConfig (); void undo (); void redo (); void handleToolResponse (ToolResponse); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/time-delta.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include "time-delta.hpp" namespace TimeDelta { struct TimeData { unsigned int numCalls; std::clock_t localTime; TimeData (std::clock_t c) : numCalls (1) , localTime (c) { } void call (std::clock_t c) { this->localTime += c; this->numCalls++; } }; const unsigned int nameWidth = 80; std::unordered_map data; std::clock_t globalTime; std::clock_t startTime; void printResults () { if (data.empty () == false) { const std::streamsize originalPrec = std::cout.precision (); std::cout << "##### time-delta (" << (float(globalTime) / CLOCKS_PER_SEC) << "s) ######\n"; for (auto pair : data) { std::cout << std::setw (nameWidth + 1) << std::left << pair.first << std::resetiosflags (std::ios_base::left) << (float(pair.second.localTime) / CLOCKS_PER_SEC) << "s (" << std::fixed << std::setprecision (1) << (100.0f * float(pair.second.localTime) / float(globalTime)) << "%) " << std::defaultfloat << std::setprecision (originalPrec) << "(" << pair.second.numCalls << " calls -> " << (1000.0f * (float(pair.second.localTime) / CLOCKS_PER_SEC) / float(pair.second.numCalls)) << "ms / call)\n"; } } } void initialize () { globalTime = 0; std::atexit (TimeDelta::printResults); } void resetTimer () { startTime = std::clock (); } void addBreakpoint (const char* name) { const std::clock_t diff = std::clock () - startTime; const std::string key = std::string (name).substr (0, nameWidth); auto it = data.find (key); if (it == data.end ()) { data.emplace (key, TimeData (diff)); } else { it->second.call (diff); } globalTime += diff; TimeDelta::resetTimer (); } } ================================================ FILE: lib/src/time-delta.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TIME_DELTA #define DILAY_TIME_DELTA #define TIME_DELTA(X) \ TimeDelta::resetTimer (); \ X; \ TimeDelta::addBreakpoint (#X); namespace TimeDelta { void initialize (); void resetTimer (); void addBreakpoint (const char*); } #endif ================================================ FILE: lib/src/tool/convert-sketch.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "distance.hpp" #include "dynamic/mesh.hpp" #include "isosurface-extraction.hpp" #include "mesh.hpp" #include "primitive/aabox.hpp" #include "primitive/cone-sphere.hpp" #include "scene.hpp" #include "sketch/mesh-intersection.hpp" #include "sketch/mesh.hpp" #include "sketch/path.hpp" #include "state.hpp" #include "tool/sculpt/util/action.hpp" #include "tools.hpp" #include "view/pointing-event.hpp" #include "view/resolution-slider.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolConvertSketch::Impl { ToolConvertSketch* self; float resolution; Impl (ToolConvertSketch* s) : self (s) , resolution (s->cache ().get ("resolution", 0.06)) { } ToolResponse runInitialize () { this->setupProperties (); this->setupToolTip (); return ToolResponse::Redraw; } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); ViewResolutionSlider& resolutionEdit = ViewUtil::resolutionSlider (0.01f, this->resolution, 0.1f); ViewUtil::connect (resolutionEdit, [this](float r) { this->resolution = r; this->self->cache ().set ("resolution", r); }); properties.addStacked (QObject::tr ("Resolution"), resolutionEdit); } void setupToolTip () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Convert selection")); this->self->state ().setToolTip (&toolTip); } DynamicMesh& convert (SketchMesh& sketch) { glm::vec3 min, max; sketch.minMax (min, max); const IsosurfaceExtraction::DistanceCallback getDistance = [&sketch](const glm::vec3& pos) { float distance = Util::maxFloat (); if (sketch.tree ().hasRoot ()) { sketch.tree ().root ().forEachConstNode ([&pos, &distance](const SketchNode& node) { const float d = node.parent () ? Distance::distance (PrimConeSphere (node.data (), node.parent ()->data ()), pos) : Distance::distance (node.data (), pos); distance = glm::min (distance, d); }); } for (const SketchPath& p : sketch.paths ()) { for (const PrimSphere& s : p.spheres ()) { distance = glm::min (distance, Distance::distance (s, pos)); } } return distance; }; sketch.optimizePaths (); DynamicMesh mesh; IsosurfaceExtraction::extract (getDistance, PrimAABox (min, max), this->resolution, mesh); State& state = this->self->state (); return state.scene ().newDynamicMesh (state.config (), mesh); } ToolResponse runReleaseEvent (const ViewPointingEvent& e) { if (e.leftButton ()) { SketchMeshIntersection intersection; if (this->self->intersectsScene (e, intersection)) { SketchMesh& sMesh = intersection.mesh (); this->self->snapshotAll (); ToolSculptAction::smoothMesh (this->convert (sMesh)); this->self->state ().scene ().deleteMesh (sMesh); return ToolResponse::Redraw; } } return ToolResponse::None; } }; DELEGATE_TOOL (ToolConvertSketch) DELEGATE_TOOL_RUN_RELEASE_EVENT (ToolConvertSketch) ================================================ FILE: lib/src/tool/delete-mesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "dynamic/mesh-intersection.hpp" #include "scene.hpp" #include "state.hpp" #include "tools.hpp" #include "view/pointing-event.hpp" #include "view/tool-tip.hpp" struct ToolDeleteMesh::Impl { ToolDeleteMesh* self; Impl (ToolDeleteMesh* s) : self (s) { } ToolResponse runInitialize () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Delete selection")); this->self->state ().setToolTip (&toolTip); return ToolResponse::None; } ToolResponse runReleaseEvent (const ViewPointingEvent& e) { if (e.leftButton ()) { DynamicMeshIntersection intersection; if (this->self->intersectsScene (e, intersection)) { Scene& scene = this->self->state ().scene (); this->self->snapshotDynamicMeshes (); scene.deleteMesh (intersection.mesh ()); return ToolResponse::Redraw; } } return ToolResponse::None; } }; DELEGATE_TOOL (ToolDeleteMesh) DELEGATE_TOOL_RUN_RELEASE_EVENT (ToolDeleteMesh) ================================================ FILE: lib/src/tool/delete-sketch.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "cache.hpp" #include "dimension.hpp" #include "scene.hpp" #include "sketch/mesh.hpp" #include "sketch/node-intersection.hpp" #include "sketch/path-intersection.hpp" #include "state.hpp" #include "tools.hpp" #include "util.hpp" #include "view/pointing-event.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" namespace { enum class Mode { DeleteSketch, DeleteNode, DeleteSpheres }; } struct ToolDeleteSketch::Impl { ToolDeleteSketch* self; Mode mode; bool deleteChildren; Impl (ToolDeleteSketch* s) : self (s) , mode (Mode (s->cache ().get ("mode", int(Mode::DeleteNode)))) , deleteChildren (s->cache ().get ("delete-children", false)) { } ToolResponse runInitialize () { this->self->supportsMirror (); this->setupProperties (); this->setupToolTip (); return ToolResponse::None; } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); QCheckBox& deleteChildrenEdit = ViewUtil::checkBox (QObject::tr ("Delete children"), this->deleteChildren); ViewUtil::connect (deleteChildrenEdit, [this](bool m) { this->deleteChildren = m; this->self->cache ().set ("delete-children", m); }); deleteChildrenEdit.setEnabled (this->mode == Mode::DeleteNode); QRadioButton& deleteSketchEdit = ViewUtil::radioButton (QObject::tr ("Delete sketch"), this->mode == Mode::DeleteSketch); ViewUtil::connect (deleteSketchEdit, [this, &deleteChildrenEdit](bool m) { this->mode = Mode::DeleteSketch; this->self->cache ().set ("mode", int(this->mode)); deleteChildrenEdit.setEnabled (!m); this->self->enableMirrorProperties (!m); }); QRadioButton& deleteNodeEdit = ViewUtil::radioButton (QObject::tr ("Delete node"), this->mode == Mode::DeleteNode); ViewUtil::connect (deleteNodeEdit, [this, &deleteChildrenEdit](bool m) { this->mode = Mode::DeleteNode; this->self->cache ().set ("mode", int(this->mode)); deleteChildrenEdit.setEnabled (m); this->self->enableMirrorProperties (m); }); QRadioButton& deleteSpheresEdit = ViewUtil::radioButton (QObject::tr ("Delete spheres"), this->mode == Mode::DeleteSpheres); ViewUtil::connect (deleteSpheresEdit, [this, &deleteChildrenEdit](bool m) { this->mode = Mode::DeleteSpheres; this->self->cache ().set ("mode", int(this->mode)); deleteChildrenEdit.setEnabled (!m); this->self->enableMirrorProperties (m); }); properties.add (deleteSketchEdit); properties.add (deleteNodeEdit); properties.add (deleteSpheresEdit); properties.add (ViewUtil::horizontalLine ()); this->self->addMirrorProperties (); this->self->enableMirrorProperties (this->mode != Mode::DeleteSketch); properties.add (deleteChildrenEdit); } void setupToolTip () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Delete selection")); this->self->state ().setToolTip (&toolTip); } ToolResponse runReleaseEvent (const ViewPointingEvent& e) { if (e.leftButton ()) { switch (this->mode) { case Mode::DeleteSketch: { SketchMeshIntersection intersection; if (this->self->intersectsScene (e, intersection)) { this->self->snapshotSketchMeshes (); this->self->state ().scene ().deleteMesh (intersection.mesh ()); } return ToolResponse::Redraw; } case Mode::DeleteNode: { SketchNodeIntersection intersection; if (this->self->intersectsScene (e, intersection)) { this->self->snapshotSketchMeshes (); intersection.mesh ().deleteNode (intersection.node (), this->deleteChildren, this->self->mirrorDimension ()); if (intersection.mesh ().isEmpty ()) { this->self->state ().scene ().deleteMesh (intersection.mesh ()); } } return ToolResponse::Redraw; } case Mode::DeleteSpheres: { SketchPathIntersection intersection; if (this->self->intersectsScene (e, intersection)) { this->self->snapshotSketchMeshes (); intersection.mesh ().deletePath (intersection.path (), this->self->mirrorDimension ()); if (intersection.mesh ().isEmpty ()) { this->self->state ().scene ().deleteMesh (intersection.mesh ()); } } return ToolResponse::Redraw; } } } return ToolResponse::None; } }; DELEGATE_TOOL (ToolDeleteSketch) DELEGATE_TOOL_RUN_RELEASE_EVENT (ToolDeleteSketch) ================================================ FILE: lib/src/tool/edit-sketch.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "cache.hpp" #include "camera.hpp" #include "mirror.hpp" #include "primitive/plane.hpp" #include "scene.hpp" #include "sketch/bone-intersection.hpp" #include "sketch/mesh.hpp" #include "sketch/node-intersection.hpp" #include "state.hpp" #include "tool/util/movement.hpp" #include "tool/util/rotation.hpp" #include "tool/util/scaling.hpp" #include "tools.hpp" #include "view/pointing-event.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolEditSketch::Impl { ToolEditSketch* self; SketchMesh* mesh; SketchNode* node; SketchNode* parent; ToolUtilMovement movement; ToolUtilScaling scaling; ToolUtilRotation rotation; bool transformChildren; bool splitAndJoin; bool snap; QSlider& snapWidthEdit; Impl (ToolEditSketch* s) : self (s) , mesh (nullptr) , node (nullptr) , parent (nullptr) , movement (s->state ().camera (), false) , scaling (s->state ().camera ()) , rotation (s->state ().camera ()) , transformChildren (s->cache ().get ("transform-children", false)) , splitAndJoin (s->cache ().get ("split-and-join", false)) , snap (s->cache ().get ("snap", true)) , snapWidthEdit (ViewUtil::slider (1, s->cache ().get ("snap-width", 5), 10)) { } ToolResponse runInitialize () { this->self->supportsMirror (); this->setupProperties (); this->setupToolTip (); return ToolResponse::None; } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); this->self->addMirrorProperties (); this->self->enableMirrorProperties (not this->splitAndJoin); this->self->addMoveOnPrimaryPlaneProperties (this->movement); QCheckBox& transformCEdit = ViewUtil::checkBox (QObject::tr ("Transform children"), this->transformChildren); ViewUtil::connect (transformCEdit, [this](bool m) { this->transformChildren = m; this->self->cache ().set ("transform-children", m); }); transformCEdit.setEnabled (not this->splitAndJoin); properties.add (transformCEdit); QCheckBox& splitAndJoinEdit = ViewUtil::checkBox (QObject::tr ("Split and join"), this->splitAndJoin); properties.add (splitAndJoinEdit); QCheckBox& snapEdit = ViewUtil::checkBox (QObject::tr ("Snap"), this->snap); ViewUtil::connect (snapEdit, [this](bool s) { this->snap = s; this->snapWidthEdit.setEnabled (s); this->self->cache ().set ("snap", s); }); snapEdit.setEnabled (not this->splitAndJoin); properties.add (snapEdit); ViewUtil::connect (this->snapWidthEdit, [this](int w) { this->self->cache ().set ("snap-width", w); }); this->snapWidthEdit.setEnabled (this->snap && not this->splitAndJoin); properties.addStacked (QObject::tr ("Snap width"), this->snapWidthEdit); ViewUtil::connect (splitAndJoinEdit, [this, &transformCEdit, &snapEdit](bool s) { this->splitAndJoin = s; this->self->cache ().set ("split-and-join", s); transformCEdit.setEnabled (not this->splitAndJoin); snapEdit.setEnabled (not this->splitAndJoin); this->snapWidthEdit.setEnabled (not this->splitAndJoin); this->self->enableMirrorProperties (not this->splitAndJoin); }); } void setupToolTip () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Add new sketch")); toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Drag node to move")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift, QObject::tr ("Drag node to scale")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Ctrl, QObject::tr ("Drag node to rotate")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Alt, QObject::tr ("Drag node to add child")); toolTip.add (ViewInputEvent::R, QObject::tr ("Click to set new root")); this->self->state ().setToolTip (&toolTip); } ToolResponse runMoveEvent (const ViewPointingEvent& e) { if (e.leftButton () && this->node) { if (e.modifiers () == Qt::ShiftModifier) { if (this->scaling.move (e)) { if (this->parent) { this->mesh->scale (*this->parent, this->scaling.factor (), false, this->self->mirrorDimension ()); } this->mesh->scale (*this->node, this->scaling.factor (), this->transformChildren, this->self->mirrorDimension ()); } } else if (e.modifiers () == Qt::ControlModifier) { if (this->rotation.rotate (e)) { this->mesh->rotate (*this->node, this->rotation.axis (), this->rotation.angle (), this->self->mirrorDimension ()); } } else if (this->movement.move (e)) { if (this->parent) { this->mesh->move (*this->parent, this->movement.delta (), false, this->self->mirrorDimension ()); } const bool transformChildren = this->transformChildren || this->splitAndJoin; this->mesh->move (*this->node, this->movement.delta (), transformChildren, this->self->mirrorDimension ()); } return ToolResponse::Redraw; } else { return ToolResponse::None; } } ToolResponse runPressEvent (const ViewPointingEvent& e) { auto handleNodeIntersection = [this, &e](SketchNodeIntersection& intersection) { this->self->snapshotSketchMeshes (); this->movement.reset (intersection.position ()); this->scaling.reset (intersection.node ().data ().center (), intersection.position ()); this->rotation.reset (intersection.node ().data ().center ()); this->parent = nullptr; if (e.modifiers () == Qt::NoModifier && this->splitAndJoin && intersection.node ().parent ()) { SketchTree tree = intersection.mesh ().tree ().split (intersection.node ()); State& state = this->self->state (); SketchMesh& mesh = state.scene ().newSketchMesh (state.config (), tree); this->mesh = &mesh; this->node = &mesh.tree ().root (); this->self->mirrorPosition (this->mesh->tree ().root ().data ().center ()); } else if (e.modifiers () == Qt::NoModifier && this->self->onKeymap ('r')) { intersection.mesh ().rebalance (intersection.node ()); this->mesh = nullptr; this->node = nullptr; this->self->mirrorPosition (intersection.mesh ().tree ().root ().data ().center ()); } else if (e.modifiers () == Qt::AltModifier) { SketchNode& iNode = intersection.node (); const float radius = iNode.numChildren () > 0 ? iNode.lastChild ().data ().radius () : iNode.data ().radius (); this->mesh = &intersection.mesh (); this->node = &this->mesh->addChild (iNode, iNode.data ().center (), radius, this->self->mirrorDimension ()); this->self->mirrorPosition (this->mesh->tree ().root ().data ().center ()); } else { this->mesh = &intersection.mesh (); this->node = &intersection.node (); this->self->mirrorPosition (this->mesh->tree ().root ().data ().center ()); } }; auto handleBoneIntersection = [this, &e](SketchBoneIntersection& intersection) { this->self->snapshotSketchMeshes (); this->movement.reset (intersection.position ()); this->scaling.reset (intersection.projectedPosition (), intersection.position ()); const glm::vec3 axis = intersection.parent ().data ().center () - intersection.child ().data ().center (); this->rotation.reset (intersection.projectedPosition (), axis); this->mesh = &intersection.mesh (); this->self->mirrorPosition (intersection.mesh ().tree ().root ().data ().center ()); if (e.modifiers () == Qt::AltModifier) { const float radius = glm::distance (intersection.projectedPosition (), intersection.position ()); this->parent = nullptr; this->node = &this->mesh->addParent (intersection.child (), intersection.projectedPosition (), radius, this->self->mirrorDimension ()); } else { this->node = &intersection.child (); this->parent = &intersection.parent (); } }; if (e.leftButton ()) { SketchNodeIntersection nodeIntersection; SketchBoneIntersection boneIntersection; if (this->self->intersectsScene (e, nodeIntersection)) { handleNodeIntersection (nodeIntersection); return ToolResponse::Redraw; } else if (this->self->intersectsScene (e, boneIntersection)) { handleBoneIntersection (boneIntersection); return ToolResponse::Redraw; } else if (e.modifiers () == Qt::NoModifier) { this->self->snapshotSketchMeshes (); State& state = this->self->state (); SketchTree tree; tree.emplaceRoot (state.camera ().viewPlaneIntersection (e.position ()), 0.1f); state.scene ().newSketchMesh (state.config (), tree); return this->runPressEvent (e); } } return ToolResponse::None; } ToolResponse runReleaseEvent (const ViewPointingEvent& e) { if (e.leftButton ()) { if (this->splitAndJoin) { SketchNodeIntersection nodeIntersection; if (this->self->intersectsScene (e, nodeIntersection, (const SketchNode*) this->node)) { this->self->snapshotSketchMeshes (); this->node->forEachChild ( [&nodeIntersection](SketchNode& child) { nodeIntersection.node ().addChild (child); }); this->self->state ().scene ().deleteMesh (*this->mesh); this->node = &nodeIntersection.node (); this->mesh = &nodeIntersection.mesh (); } } return this->runCommit (); } return ToolResponse::None; } ToolResponse runCommit () { if (this->snap && this->mesh && this->self->mirrorEnabled ()) { PrimPlane mirrorPlane = this->mesh->mirrorPlane (*this->self->mirrorDimension ()); const auto isSnappable = [this, &mirrorPlane](const SketchNode& node) -> bool { return mirrorPlane.absDistance (node.data ().center ()) <= (this->snapWidthEdit.value ()) * this->self->mirror ().width (); }; if (this->node && isSnappable (*this->node)) { this->mesh->snap (*this->node, *this->self->mirrorDimension ()); } if (this->parent && isSnappable (*this->parent)) { this->mesh->snap (*this->parent, *this->self->mirrorDimension ()); } } if (this->mesh) { const bool selectedRootNode = this->node->parent () == nullptr; const bool selectedRootBone = this->parent && this->parent->parent () == nullptr; if (selectedRootNode || selectedRootBone) { this->self->mirrorPosition (this->mesh->tree ().root ().data ().center ()); } } this->mesh = nullptr; this->node = nullptr; this->parent = nullptr; return ToolResponse::Redraw; } }; DELEGATE_TOOL (ToolEditSketch) DELEGATE_TOOL_RUN_MOVE_EVENT (ToolEditSketch) DELEGATE_TOOL_RUN_PRESS_EVENT (ToolEditSketch) DELEGATE_TOOL_RUN_RELEASE_EVENT (ToolEditSketch) DELEGATE_TOOL_RUN_COMMIT (ToolEditSketch) ================================================ FILE: lib/src/tool/key.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_KEY #define DILAY_TOOL_KEY #include enum class ToolKey { TransformMesh, DeleteMesh, NewMesh, SculptDraw, SculptGrab, SculptSmooth, SculptFlatten, SculptCrease, SculptPinch, SculptReduce, EditSketch, DeleteSketch, ConvertSketch, SketchSpheres, TrimMesh, Remesh, MoveCamera }; namespace std { template <> struct hash { size_t operator() (const ToolKey& key) const { return std::hash () (int(key)); } }; } #endif ================================================ FILE: lib/src/tool/move-camera.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "camera.hpp" #include "config.hpp" #include "dimension.hpp" #include "intersection.hpp" #include "state.hpp" #include "tools.hpp" #include "view/floor-plane.hpp" #include "view/gl-widget.hpp" #include "view/main-window.hpp" #include "view/pointing-event.hpp" #include "view/shortcut.hpp" #include "view/tool-tip.hpp" struct ToolMoveCamera::Impl { ToolMoveCamera* self; bool isImmediateTool; glm::ivec2 oldPos; float rotationFactor; float movementFactor; float zoomInMouseWheelFactor; Impl (ToolMoveCamera* s, bool i) : self (s) , isImmediateTool (i) , oldPos (s->state ().mainWindow ().glWidget ().cursorPosition ()) { } Impl (ToolMoveCamera* s) : Impl (s, false) { } ToolResponse runInitialize () { if (this->isImmediateTool == false) { this->setupToolTip (); } return ToolResponse::None; } void setupToolTip () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Drag to rotate")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift, QObject::tr ("Drag to move")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Ctrl, QObject::tr ("Drag to zoom")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Alt, QObject::tr ("Gaze")); toolTip.add (ViewInputEvent::C, ViewInputModifier::Shift, QObject::tr ("Snap camera")); toolTip.add (ViewInputEvent::C, ViewInputModifier::Alt, QObject::tr ("Reset gaze point")); const auto exitShortcut = ViewShortcut (ViewInputEvent::Space, QObject::tr ("Exit camera mode"), [this]() { this->self->state ().setPreviousTool (); }); this->self->state ().setToolTip (&toolTip, {exitShortcut}); } bool mouseButton (const ViewPointingEvent& e) { return this->isImmediateTool ? e.middleButton () : e.leftButton (); } ToolResponse runMoveEvent (const ViewPointingEvent& e) { if (this->mouseButton (e)) { Camera& cam = this->self->state ().camera (); const glm::vec2& resolution = glm::vec2 (cam.resolution ()); const glm::vec2 delta = glm::vec2 (e.position ()) - glm::vec2 (this->oldPos); if (e.modifiers () == Qt::NoModifier) { if (delta.x != 0.0f) { cam.verticalRotation (2.0f * glm::pi () * this->rotationFactor * -delta.x / resolution.x); } if (delta.y != 0.0f) { cam.horizontalRotation (2.0f * glm::pi () * this->rotationFactor * -delta.y / resolution.y); } } else if (e.modifiers () == Qt::ShiftModifier) { cam.setGaze (cam.gazePoint () + (this->movementFactor * delta.x * cam.right ()) + (this->movementFactor * -delta.y * cam.realUp ())); } else if (e.modifiers () == Qt::ControlModifier) { const float y = glm::clamp (delta.y, -50.0f, 50.0f); if (y < 0.0f) { cam.stepAlongGaze (1.0f - (-y / 100.0f)); } else if (y > 0.0f) { cam.stepAlongGaze (1.0f / (1.0f - (y / 100.0f))); } this->self->state ().mainWindow ().glWidget ().floorPlane ().update (cam); } this->oldPos = e.position (); return ToolResponse::Redraw; } else { this->oldPos = e.position (); return ToolResponse::None; } } ToolResponse runPressEvent (const ViewPointingEvent& e) { if (this->mouseButton (e) && e.modifiers () == Qt::AltModifier) { Intersection intersection; if (this->self->intersectsScene (e.position (), intersection)) { Camera& camera = this->self->state ().camera (); camera.set (intersection.position (), camera.position () - intersection.position ()); return ToolResponse::Redraw; } } return ToolResponse::None; } void runFromConfig () { const Config& config = this->self->config (); this->rotationFactor = config.get ("editor/camera/rotation-factor"); this->movementFactor = config.get ("editor/camera/movement-factor"); this->zoomInMouseWheelFactor = config.get ("editor/camera/zoom-in-mouse-wheel-factor"); } ToolResponse wheelEvent (const QWheelEvent& e) { if (this->isImmediateTool && e.modifiers () == Qt::NoModifier && e.orientation () == Qt::Vertical) { Camera& camera = this->self->state ().camera (); if (e.delta () > 0) { camera.stepAlongGaze (this->zoomInMouseWheelFactor); } else if (e.delta () < 0) { camera.stepAlongGaze (1.0f / this->zoomInMouseWheelFactor); } this->self->state ().mainWindow ().glWidget ().floorPlane ().update (camera); return ToolResponse::Redraw; } return ToolResponse::None; } void snap () { Camera& cam = this->self->state ().camera (); auto snapTo = [&cam](Dimension d, bool forcePositive) { const float gazeLength = glm::length (cam.toEyePoint ()); const float side = (forcePositive || cam.toEyePoint ()[DimensionUtil::index (d)] > 0.0f) ? 1.0f : -1.0f; const glm::vec3 toEyePoint = side * gazeLength * DimensionUtil::vector (d); cam.set (cam.gazePoint (), toEyePoint); }; auto isSnapped = [&cam](Dimension d) -> bool { const float dot = glm::abs (glm::dot (glm::normalize (cam.toEyePoint ()), DimensionUtil::vector (d))); return dot > 1.0f - Util::epsilon (); }; if (isSnapped (Dimension::X)) { snapTo (Dimension::Y, true); } else if (isSnapped (Dimension::Y)) { snapTo (Dimension::Z, true); } else if (isSnapped (Dimension::Z)) { snapTo (Dimension::X, true); } else { snapTo (cam.primaryDimension (), false); } this->self->state ().mainWindow ().glWidget ().update (); } void resetGazePoint () { Camera& cam = this->self->state ().camera (); cam.set (glm::vec3 (0.0f), cam.position ()); this->self->state ().mainWindow ().glWidget ().update (); } }; DELEGATE_CONSTRUCTOR_BASE (ToolMoveCamera, (State & s, bool i), (this, i), Tool, (s, "ToolMoveCamera")) DELEGATE_TOOL (ToolMoveCamera) DELEGATE_TOOL_RUN_MOVE_EVENT (ToolMoveCamera) DELEGATE_TOOL_RUN_PRESS_EVENT (ToolMoveCamera) DELEGATE_TOOL_RUN_FROM_CONFIG (ToolMoveCamera) DELEGATE1 (ToolResponse, ToolMoveCamera, wheelEvent, const QWheelEvent&) DELEGATE (void, ToolMoveCamera, snap) DELEGATE (void, ToolMoveCamera, resetGazePoint) ================================================ FILE: lib/src/tool/move-camera.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_MOVE_CAMERA #define DILAY_TOOL_MOVE_CAMERA #include "tool.hpp" class QWheelEvent; class ToolMoveCamera : public Tool { public: DECLARE_BIG2 (ToolMoveCamera, State&) ToolMoveCamera (State&, bool); ToolKey getKey () const { return ToolKey::MoveCamera; } ToolResponse wheelEvent (const QWheelEvent&); void snap (); void resetGazePoint (); private: IMPLEMENTATION ToolResponse runInitialize (); ToolResponse runMoveEvent (const ViewPointingEvent&); ToolResponse runPressEvent (const ViewPointingEvent&); void runFromConfig (); }; #endif ================================================ FILE: lib/src/tool/new-mesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "dynamic/mesh.hpp" #include "mesh-util.hpp" #include "mesh.hpp" #include "render-mode.hpp" #include "scene.hpp" #include "state.hpp" #include "tools.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" namespace { enum class MeshType { Icosphere, Cube }; } struct ToolNewMesh::Impl { ToolNewMesh* self; std::unique_ptr mesh; int subdivision; MeshType meshType; Impl (ToolNewMesh* s) : self (s) , subdivision (s->cache ().get ("subdivision", 4)) , meshType (MeshType (s->cache ().get ("mesh-type", int(MeshType::Icosphere)))) { } ToolResponse runInitialize () { this->setupProperties (); this->makeCurrentMesh (); return ToolResponse::Redraw; } void runRender () const { if (this->mesh) { this->mesh->renderMode () = this->self->state ().scene ().commonRenderMode (); this->mesh->render (this->self->state ().camera ()); } } ToolResponse runCommit () { if (this->mesh) { this->self->snapshotDynamicMeshes (); this->self->state ().scene ().newDynamicMesh (this->self->state ().config (), *this->mesh); } return ToolResponse::None; } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); QSlider& subdivisionEdit = ViewUtil::slider (1, this->subdivision, 6); ViewUtil::connect (subdivisionEdit, [this](int r) { this->subdivision = r; this->self->cache ().set ("subdivision", r); this->makeCurrentMesh (); }); properties.addStacked (QObject::tr ("Subdivisions"), subdivisionEdit); QButtonGroup& meshTypeEdit = ViewUtil::buttonGroup ({QObject::tr ("Icosphere"), QObject::tr ("Cube")}); ViewUtil::connect (meshTypeEdit, int(this->meshType), [this](int id) { this->meshType = MeshType (id); this->self->cache ().set ("mesh-type", id); this->makeCurrentMesh (); }); properties.add (meshTypeEdit); } void makeCurrentMesh () { switch (this->meshType) { case MeshType::Icosphere: this->mesh = std::make_unique (MeshUtil::icosphere (this->subdivision)); break; case MeshType::Cube: this->mesh = std::make_unique (MeshUtil::cube (this->subdivision)); break; } this->self->state ().scene ().setupMesh (this->self->state ().config (), *this->mesh); this->self->updateGlWidget (); } }; DELEGATE_TOOL (ToolNewMesh) DELEGATE_TOOL_RUN_RENDER (ToolNewMesh) DELEGATE_TOOL_RUN_COMMIT (ToolNewMesh) ================================================ FILE: lib/src/tool/remesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "color.hpp" #include "config.hpp" #include "dynamic/mesh-intersection.hpp" #include "dynamic/mesh.hpp" #include "isosurface-extraction.hpp" #include "maybe.hpp" #include "mesh.hpp" #include "primitive/aabox.hpp" #include "primitive/ray.hpp" #include "scene.hpp" #include "state.hpp" #include "tool/sculpt/util/action.hpp" #include "tools.hpp" #include "view/pointing-event.hpp" #include "view/resolution-slider.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" namespace { enum class Mode { Normal, Union, Difference, Intersection }; } struct ToolRemesh::Impl { ToolRemesh* self; float resolution; Mode mode; Maybe pressPoint; Impl (ToolRemesh* s) : self (s) , resolution (s->cache ().get ("resolution", 0.06)) , mode (Mode (s->cache ().get ("mode", int(Mode::Normal)))) { } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); QButtonGroup& modeEdit = ViewUtil::buttonGroup ({QObject::tr ("Normal"), QObject::tr ("Union"), QObject::tr ("Difference"), QObject::tr ("Intersection")}); ViewUtil::connect (modeEdit, int(this->mode), [this](int id) { this->mode = Mode (id); this->self->cache ().set ("mode", id); }); properties.add (modeEdit); ViewResolutionSlider& resolutionEdit = ViewUtil::resolutionSlider (0.02f, this->resolution, 0.1f); ViewUtil::connect (resolutionEdit, [this](float r) { this->resolution = r; this->self->cache ().set ("resolution", r); }); properties.addStacked (QObject::tr ("Resolution"), resolutionEdit); } void setupToolTip () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Remesh selection")); this->self->state ().setToolTip (&toolTip); } ToolResponse runInitialize () { this->setupProperties (); this->setupToolTip (); return ToolResponse::None; } ToolResponse runMoveEvent (const ViewPointingEvent&) { return this->mode == Mode::Normal ? ToolResponse::None : ToolResponse::Redraw; } void remesh (DynamicMesh& mesh) { const IsosurfaceExtraction::IntersectionCallback getIntersection = [&mesh](const PrimRay& ray, Intersection& intersection) { if (mesh.intersects (ray, intersection, true)) { return IsosurfaceExtraction::Intersection::Sample; } else { return IsosurfaceExtraction::Intersection::None; } }; const IsosurfaceExtraction::DistanceCallback getDistance = [&mesh](const glm::vec3& pos) { return mesh.unsignedDistance (pos); }; const PrimAABox bounds = mesh.mesh ().bounds (); DynamicMesh extractedMesh; IsosurfaceExtraction::extract (getDistance, getIntersection, bounds, this->resolution, extractedMesh); State& state = this->self->state (); state.scene ().deleteMesh (mesh); DynamicMesh& dMesh = state.scene ().newDynamicMesh (state.config (), extractedMesh); ToolSculptAction::smoothMesh (dMesh); } void remesh (DynamicMesh& meshA, DynamicMesh& meshB) { const IsosurfaceExtraction::IntersectionCallback getCommutativeIntersection = [this, &meshA, &meshB](const PrimRay& ray, Intersection& intersection) { assert (this->mode == Mode::Union || this->mode == Mode::Intersection); Intersection intersectionA, intersectionB; meshA.intersects (ray, intersectionA, true); meshB.intersects (ray, intersectionB, true); Intersection::sort (intersectionA, intersectionB); intersection = intersectionA; const bool intersectsA = intersectionA.isIntersection (); const bool intersectsB = intersectionB.isIntersection (); if (intersectsA && intersectsB) { const bool insideA = glm::dot (ray.direction (), intersectionA.normal ()) > 0.0f; const bool insideB = glm::dot (ray.direction (), intersectionB.normal ()) > 0.0f; if (insideA && insideB) { // (B (A o-> A) B) // (A (B o-> A) B) if (this->mode == Mode::Union) { return IsosurfaceExtraction::Intersection::Continue; } else { assert (this->mode == Mode::Intersection); return IsosurfaceExtraction::Intersection::Sample; } } else if (insideA && insideB == false) { // (A o-> A) (B B) if (this->mode == Mode::Union) { return IsosurfaceExtraction::Intersection::Sample; } else { assert (this->mode == Mode::Intersection); return IsosurfaceExtraction::Intersection::Continue; } } else if (insideA == false && insideB) { // (B o-> (A A) B) // (B o-> (A B) A) if (this->mode == Mode::Union) { return IsosurfaceExtraction::Intersection::Continue; } else { assert (this->mode == Mode::Intersection); return IsosurfaceExtraction::Intersection::Sample; } } else if (insideA == false && insideB == false) { // o-> (A (B B) A) // o-> (A (B A) B) // o-> (A A) (B B) if (this->mode == Mode::Union) { return IsosurfaceExtraction::Intersection::Sample; } else { assert (this->mode == Mode::Intersection); return IsosurfaceExtraction::Intersection::Continue; } } DILAY_IMPOSSIBLE } else if (intersectsA) { if (this->mode == Mode::Union) { return IsosurfaceExtraction::Intersection::Sample; } else { assert (this->mode == Mode::Intersection); return IsosurfaceExtraction::Intersection::Continue; } } else { assert (intersectsB == false); return IsosurfaceExtraction::Intersection::None; } DILAY_IMPOSSIBLE }; const IsosurfaceExtraction::IntersectionCallback getDifferenceIntersection = [this, &meshA, &meshB](const PrimRay& ray, Intersection& intersection) { assert (this->mode == Mode::Difference); Intersection intersectionA, intersectionB; const bool intersectsA = meshA.intersects (ray, intersectionA, true); const bool intersectsB = meshB.intersects (ray, intersectionB, true); if (intersectsA && intersectsB) { const bool insideA = glm::dot (ray.direction (), intersectionA.normal ()) > 0.0f; const bool insideB = glm::dot (ray.direction (), intersectionB.normal ()) > 0.0f; const bool aBeforeB = intersectionA.distance () < intersectionB.distance (); intersection = aBeforeB ? intersectionA : intersectionB; if (insideA && insideB) { if (aBeforeB) { // (B (A o-> A) B) // (A (B o-> A) B) return IsosurfaceExtraction::Intersection::Continue; } else { // (A (B o-> B) A) // (B (A o-> B) A) return IsosurfaceExtraction::Intersection::Sample; } } else if (insideA && insideB == false) { // (A o-> A) (B B) // (A o-> (B B) A) // (A o-> (B A) B) return IsosurfaceExtraction::Intersection::Sample; } else if (insideA == false && insideB) { // (B o-> B) (A A) // (B o-> (A A) B) // (B o-> (A B) A) return IsosurfaceExtraction::Intersection::Continue; } else if (insideA == false && insideB == false) { if (aBeforeB) { // o-> (A (B B) A) // o-> (A (B A) B) // o-> (A A) (B B) return IsosurfaceExtraction::Intersection::Sample; } else { // o-> (B (A A) B) // o-> (B (A B) A) // o-> (B B) (A A) return IsosurfaceExtraction::Intersection::Continue; } } DILAY_IMPOSSIBLE } else if (intersectsA) { intersection = intersectionA; return IsosurfaceExtraction::Intersection::Sample; } else if (intersectsB) { intersection = intersectionB; return IsosurfaceExtraction::Intersection::Continue; } else { return IsosurfaceExtraction::Intersection::None; } DILAY_IMPOSSIBLE }; const IsosurfaceExtraction::DistanceCallback getDistance = [&meshA, &meshB](const glm::vec3& pos) { return glm::min (meshA.unsignedDistance (pos), meshB.unsignedDistance (pos)); }; const PrimAABox boundsA = meshA.mesh ().bounds (); const PrimAABox boundsB = meshB.mesh ().bounds (); const glm::vec3 min = glm::min (boundsA.minimum (), boundsB.minimum ()); const glm::vec3 max = glm::max (boundsA.maximum (), boundsB.maximum ()); const PrimAABox bounds (min, max); DynamicMesh extractedMesh; if (this->mode == Mode::Difference) { IsosurfaceExtraction::extract (getDistance, getDifferenceIntersection, bounds, this->resolution, extractedMesh); } else { IsosurfaceExtraction::extract (getDistance, getCommutativeIntersection, bounds, this->resolution, extractedMesh); } State& state = this->self->state (); state.scene ().deleteMesh (meshA); state.scene ().deleteMesh (meshB); if (extractedMesh.isEmpty () == false) { DynamicMesh& dMesh = state.scene ().newDynamicMesh (state.config (), extractedMesh); ToolSculptAction::smoothMesh (dMesh); } } ToolResponse runPressEvent (const ViewPointingEvent& e) { if (e.leftButton () == false || this->mode == Mode::Normal) { return ToolResponse::None; } else { this->pressPoint = e.position (); return ToolResponse::Redraw; } } ToolResponse runReleaseEvent (const ViewPointingEvent& e) { if (e.leftButton () == false) { return ToolResponse::None; } else { if (this->mode == Mode::Normal) { DynamicMeshIntersection intersection; if (this->self->intersectsScene (e.position (), intersection)) { this->self->snapshotDynamicMeshes (); this->remesh (intersection.mesh ()); return ToolResponse::Redraw; } else { return ToolResponse::None; } } else if (this->pressPoint) { DynamicMeshIntersection intersectionA; DynamicMeshIntersection intersectionB; const bool intersectsA = this->self->intersectsScene (*this->pressPoint, intersectionA); const bool intersectsB = this->self->intersectsScene (e.position (), intersectionB); this->pressPoint.reset (); if (intersectsA && intersectsB) { this->self->snapshotDynamicMeshes (); if (&intersectionA.mesh () == &intersectionB.mesh ()) { this->remesh (intersectionA.mesh ()); } else { this->remesh (intersectionA.mesh (), intersectionB.mesh ()); } return ToolResponse::Redraw; } else { return ToolResponse::None; } } else { return ToolResponse::None; } } } void runPaint (QPainter& painter) const { if (this->mode != Mode::Normal && this->pressPoint) { const QPoint cursorPos (ViewUtil::toQPoint (this->self->cursorPosition ())); QPen pen (this->self->config ().get ("editor/on-screen-color").qColor ()); pen.setCapStyle (Qt::FlatCap); pen.setWidth (2); painter.setPen (pen); painter.drawLine (ViewUtil::toQPoint (*this->pressPoint), cursorPos); } } ToolResponse runCommit () { return ToolResponse::Redraw; } }; DELEGATE_TOOL (ToolRemesh) DELEGATE_TOOL_RUN_MOVE_EVENT (ToolRemesh) DELEGATE_TOOL_RUN_PRESS_EVENT (ToolRemesh) DELEGATE_TOOL_RUN_RELEASE_EVENT (ToolRemesh) DELEGATE_TOOL_RUN_PAINT (ToolRemesh) DELEGATE_TOOL_RUN_COMMIT (ToolRemesh) ================================================ FILE: lib/src/tool/sculpt/crease.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "tool/sculpt/util/brush.hpp" #include "tools.hpp" #include "view/double-slider.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolSculptCrease::Impl { ToolSculptCrease* self; Impl (ToolSculptCrease* s) : self (s) { } void runSetupBrush (SculptBrush& brush) { auto& params = brush.initParameters (); params.intensity (this->self->cache ().get ("intensity", 0.5f)); params.invert (this->self->cache ().get ("invert", false)); } void runSetupCursor (ViewCursor&) {} void runSetupProperties (ViewTwoColumnGrid& properties) { auto& params = this->self->brush ().parameters (); ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.1f, params.intensity (), 0.9f); ViewUtil::connect (intensityEdit, [this, ¶ms](float i) { params.intensity (i); this->self->cache ().set ("intensity", i); }); properties.addStacked (QObject::tr ("Intensity"), intensityEdit); this->self->registerSecondarySlider (intensityEdit); QCheckBox& invertEdit = ViewUtil::checkBox (QObject::tr ("Invert"), params.invert ()); ViewUtil::connect (invertEdit, [this, ¶ms](bool i) { params.invert (i); this->self->cache ().set ("invert", i); }); properties.add (invertEdit); } void runSetupToolTip (ViewToolTip& toolTip) { this->self->addDefaultToolTip (toolTip, true, true); } bool runSculptPointingEvent (const ViewPointingEvent& e) { const std::function toggleInvert = [this]() { this->self->brush ().parameters ().toggleInvert (); }; return this->self->drawlikeStroke (e, true, &toggleInvert); } }; DELEGATE_TOOL_SCULPT (ToolSculptCrease) ================================================ FILE: lib/src/tool/sculpt/draw.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "tool/sculpt/util/brush.hpp" #include "tools.hpp" #include "view/double-slider.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolSculptDraw::Impl { ToolSculptDraw* self; Impl (ToolSculptDraw* s) : self (s) { } void runSetupBrush (SculptBrush& brush) { auto& params = brush.initParameters (); params.intensity (this->self->cache ().get ("intensity", 0.5f)); params.invert (this->self->cache ().get ("invert", false)); params.constantHeight (this->self->cache ().get ("constant-height", false)); } void runSetupCursor (ViewCursor&) {} void runSetupProperties (ViewTwoColumnGrid& properties) { auto& params = this->self->brush ().parameters (); ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.0f, params.intensity (), 1.0f); ViewUtil::connect (intensityEdit, [this, ¶ms](float i) { params.intensity (i); this->self->cache ().set ("intensity", i); }); properties.addStacked (QObject::tr ("Intensity"), intensityEdit); this->self->registerSecondarySlider (intensityEdit); QCheckBox& invertEdit = ViewUtil::checkBox (QObject::tr ("Invert"), params.invert ()); ViewUtil::connect (invertEdit, [this, ¶ms](bool i) { params.invert (i); this->self->cache ().set ("invert", i); }); properties.add (invertEdit); QCheckBox& constantHeightEdit = ViewUtil::checkBox (QObject::tr ("Constant height"), params.constantHeight ()); ViewUtil::connect (constantHeightEdit, [this, ¶ms](bool v) { params.constantHeight (v); this->self->cache ().set ("constant-height", v); }); properties.add (constantHeightEdit); } void runSetupToolTip (ViewToolTip& toolTip) { this->self->addDefaultToolTip (toolTip, true, true); } bool runSculptPointingEvent (const ViewPointingEvent& e) { SBDrawParameters& params = this->self->brush ().parameters (); const std::function toggleInvert = [¶ms]() { params.toggleInvert (); }; return this->self->drawlikeStroke (e, params.constantHeight (), &toggleInvert); } }; DELEGATE_TOOL_SCULPT (ToolSculptDraw) ================================================ FILE: lib/src/tool/sculpt/flatten.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "dynamic/mesh-intersection.hpp" #include "primitive/plane.hpp" #include "state.hpp" #include "tool/sculpt/util/brush.hpp" #include "tool/util/movement.hpp" #include "tools.hpp" #include "view/double-slider.hpp" #include "view/pointing-event.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolSculptFlatten::Impl { ToolSculptFlatten* self; ToolUtilMovement movement; Impl (ToolSculptFlatten* s) : self (s) , movement (this->self->state ().camera (), glm::vec3 (0.0f)) { } void runSetupBrush (SculptBrush& brush) { auto& params = brush.initParameters (); params.intensity (this->self->cache ().get ("intensity", 0.5f)); params.lockPlane (this->self->cache ().get ("lock-plane", false)); brush.subdivide (false); } void runSetupCursor (ViewCursor&) {} void runSetupProperties (ViewTwoColumnGrid& properties) { auto& params = this->self->brush ().parameters (); ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.1f, params.intensity (), 1.0f); ViewUtil::connect (intensityEdit, [this, ¶ms](float i) { params.intensity (i); this->self->cache ().set ("intensity", i); }); properties.addStacked (QObject::tr ("Intensity"), intensityEdit); this->self->registerSecondarySlider (intensityEdit); QCheckBox& lockPlaneEdit = ViewUtil::checkBox (QObject::tr ("Lock plane"), params.lockPlane ()); ViewUtil::connect (lockPlaneEdit, [this, ¶ms](bool v) { params.lockPlane (v); params.resetLockedPlane (); this->self->cache ().set ("lock-plane", v); }); properties.add (lockPlaneEdit); } void runSetupToolTip (ViewToolTip& toolTip) { this->self->addDefaultToolTip (toolTip, false, true); } bool runSculptPointingEvent (const ViewPointingEvent& e) { auto& params = this->self->brush ().parameters (); if (params.lockPlane ()) { if (e.pressEvent ()) { DynamicMeshIntersection intersection; if (this->self->intersectsScene (e, intersection)) { params.lockedPlane (PrimPlane (intersection.position (), intersection.normal ())); this->movement.onFreePlane (intersection.normal ()); } else { params.resetLockedPlane (); } } return this->self->grablikeStroke (e, this->movement); } else { return this->self->drawlikeStroke (e, false); } } }; DELEGATE_TOOL_SCULPT (ToolSculptFlatten) ================================================ FILE: lib/src/tool/sculpt/grab.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "state.hpp" #include "tool/sculpt/util/brush.hpp" #include "tool/util/movement.hpp" #include "tools.hpp" #include "view/pointing-event.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolSculptGrab::Impl { ToolSculptGrab* self; ToolUtilMovement movement; Impl (ToolSculptGrab* s) : self (s) , movement (this->self->state ().camera (), false) { } void runSetupBrush (SculptBrush& brush) { auto& params = brush.initParameters (); params.discardBack (this->self->cache ().get ("discard-back", false)); } void runSetupCursor (ViewCursor&) {} void runSetupProperties (ViewTwoColumnGrid& properties) { auto& params = this->self->brush ().parameters (); this->self->addMoveOnPrimaryPlaneProperties (this->movement); QCheckBox& discardEdit = ViewUtil::checkBox (QObject::tr ("Discard backfaces"), params.discardBack ()); ViewUtil::connect (discardEdit, [this, ¶ms](bool d) { params.discardBack (d); this->self->cache ().set ("discard-back", d); }); properties.add (discardEdit); } void runSetupToolTip (ViewToolTip& toolTip) { this->self->addDefaultToolTip (toolTip, false, false); } bool runSculptPointingEvent (const ViewPointingEvent& e) { return this->self->grablikeStroke (e, this->movement); } }; DELEGATE_TOOL_SCULPT (ToolSculptGrab) ================================================ FILE: lib/src/tool/sculpt/pinch.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "tool/sculpt/util/brush.hpp" #include "tools.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolSculptPinch::Impl { ToolSculptPinch* self; Impl (ToolSculptPinch* s) : self (s) { } void runSetupBrush (SculptBrush& brush) { auto& params = brush.initParameters (); params.invert (this->self->cache ().get ("invert", false)); } void runSetupCursor (ViewCursor&) {} void runSetupProperties (ViewTwoColumnGrid& properties) { auto& params = this->self->brush ().parameters (); QCheckBox& invertEdit = ViewUtil::checkBox (QObject::tr ("Invert"), params.invert ()); ViewUtil::connect (invertEdit, [this, ¶ms](bool i) { params.invert (i); this->self->cache ().set ("invert", i); }); properties.add (invertEdit); } void runSetupToolTip (ViewToolTip& toolTip) { this->self->addDefaultToolTip (toolTip, true, false); } bool runSculptPointingEvent (const ViewPointingEvent& e) { const std::function toggleInvert = [this]() { this->self->brush ().parameters ().toggleInvert (); }; return this->self->drawlikeStroke (e, false, &toggleInvert); } }; DELEGATE_TOOL_SCULPT (ToolSculptPinch) ================================================ FILE: lib/src/tool/sculpt/reduce.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "cache.hpp" #include "tool/sculpt/util/brush.hpp" #include "tools.hpp" #include "view/double-slider.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolSculptReduce::Impl { ToolSculptReduce* self; Impl (ToolSculptReduce* s) : self (s) { } void runSetupBrush (SculptBrush& brush) { auto& params = brush.initParameters (); params.intensity (this->self->cache ().get ("intensity", 0.5f)); brush.subdivide (false); } void runSetupCursor (ViewCursor&) {} void runSetupProperties (ViewTwoColumnGrid& properties) { auto& params = this->self->brush ().parameters (); ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.1f, params.intensity (), 0.9f); ViewUtil::connect (intensityEdit, [this, ¶ms](float i) { params.intensity (i); this->self->cache ().set ("intensity", i); }); properties.addStacked (QObject::tr ("Intensity"), intensityEdit); this->self->registerSecondarySlider (intensityEdit); } void runSetupToolTip (ViewToolTip& toolTip) { this->self->addDefaultToolTip (toolTip, false, true); } bool runSculptPointingEvent (const ViewPointingEvent& e) { return this->self->drawlikeStroke (e, false); } }; DELEGATE_TOOL_SCULPT (ToolSculptReduce) ================================================ FILE: lib/src/tool/sculpt/smooth.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "tool/sculpt/util/brush.hpp" #include "tools.hpp" #include "view/double-slider.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolSculptSmooth::Impl { ToolSculptSmooth* self; Impl (ToolSculptSmooth* s) : self (s) { } void runSetupBrush (SculptBrush& brush) { auto& params = brush.initParameters (); params.intensity (this->self->cache ().get ("intensity", 0.5f)); brush.subdivide (false); } void runSetupCursor (ViewCursor&) {} void runSetupProperties (ViewTwoColumnGrid& properties) { auto& params = this->self->brush ().parameters (); ViewDoubleSlider& intensityEdit = ViewUtil::slider (2, 0.1f, params.intensity (), 1.0f); ViewUtil::connect (intensityEdit, [this, ¶ms](float i) { params.intensity (i); this->self->cache ().set ("intensity", i); }); properties.addStacked (QObject::tr ("Intensity"), intensityEdit); this->self->registerSecondarySlider (intensityEdit); } void runSetupToolTip (ViewToolTip& toolTip) { this->self->addDefaultToolTip (toolTip, false, true); } bool runSculptPointingEvent (const ViewPointingEvent& e) { return this->self->drawlikeStroke (e, false); } }; DELEGATE_TOOL_SCULPT (ToolSculptSmooth) ================================================ FILE: lib/src/tool/sculpt/util/action.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "dynamic/faces.hpp" #include "dynamic/mesh.hpp" #include "intersection.hpp" #include "primitive/sphere.hpp" #include "primitive/triangle.hpp" #include "tool/sculpt/util/action.hpp" #include "tool/sculpt/util/brush.hpp" #include "tool/sculpt/util/edge-collection.hpp" #include "util.hpp" namespace { constexpr float minEdgeLength = 0.001f; struct NewFaces { std::vector vertexIndices; std::unordered_set facesToDelete; void reset () { this->vertexIndices.clear (); this->facesToDelete.clear (); } void addFace (unsigned int i1, unsigned int i2, unsigned int i3) { this->vertexIndices.push_back (i1); this->vertexIndices.push_back (i2); this->vertexIndices.push_back (i3); } void deleteFace (unsigned int i) { this->facesToDelete.insert (i); } bool applyToMesh (DynamicMesh& mesh, DynamicFaces& faces) const { assert (this->vertexIndices.size () % 3 == 0); for (unsigned int i : this->facesToDelete) { mesh.deleteFace (i); } for (unsigned int i = 0; i < this->vertexIndices.size (); i += 3) { const unsigned int f = mesh.addFace (this->vertexIndices[i + 0], this->vertexIndices[i + 1], this->vertexIndices[i + 2]); if (i >= this->facesToDelete.size () * 3) { faces.insert (f); } } return this->facesToDelete.size () <= (this->vertexIndices.size () / 3); } }; void extendAndFilterDomain (const SculptBrush& brush, DynamicFaces& faces, unsigned int numRings) { assert (faces.hasUncomitted () == false); const DynamicMesh& mesh = brush.mesh (); const PrimSphere sphere = brush.sphere (); std::unordered_set frontier; faces.filter ([&mesh, &sphere, &frontier](unsigned int i) { const PrimTriangle face = mesh.face (i); if (IntersectionUtil::intersects (sphere, face) == false) { return false; } else if (sphere.contains (face) == false) { frontier.insert (i); } return true; }); for (unsigned int ring = 0; ring < numRings; ring++) { std::unordered_set extendedFrontier; for (unsigned int i : frontier) { mesh.forEachVertexAdjacentToFace ( i, [&mesh, &faces, &frontier, &extendedFrontier](unsigned int v) { for (unsigned int a : mesh.adjacentFaces (v)) { if (faces.contains (a) == false && frontier.find (a) == frontier.end ()) { faces.insert (a); extendedFrontier.insert (a); } } }); } faces.commit (); frontier = std::move (extendedFrontier); } } void extendDomain (DynamicMesh& mesh, DynamicFaces& faces, unsigned int numRings) { assert (faces.hasUncomitted () == false); for (unsigned int ring = 0; ring < numRings; ring++) { for (unsigned int i : faces) { mesh.forEachVertexAdjacentToFace (i, [&mesh, &faces](unsigned int v) { for (unsigned int a : mesh.adjacentFaces (v)) { if (faces.contains (a) == false) { faces.insert (a); } } }); } faces.commit (); } } void extendDomainByPoles (DynamicMesh& mesh, DynamicFaces& faces) { assert (faces.hasUncomitted () == false); mesh.forEachVertex (faces, [&mesh, &faces](unsigned int i) { if (mesh.valence (i) > 6) { for (unsigned int a : mesh.adjacentFaces (i)) { if (faces.contains (a) == false) { faces.insert (a); } } } }); faces.commit (); } glm::vec3 getSplitPosition (const DynamicMesh& mesh, unsigned int i1, unsigned int i2) { const glm::vec3& p1 = mesh.vertex (i1); const glm::vec3& n1 = mesh.vertexNormal (i1); const glm::vec3& p2 = mesh.vertex (i2); const glm::vec3& n2 = mesh.vertexNormal (i2); if (Util::colinearUnit (n1, n2)) { return 0.5f * (p1 + p2); } else { const glm::vec3 n3 = glm::normalize (glm::cross (n1, n2)); const float d1 = glm::dot (p1, n1); const float d2 = glm::dot (p2, n2); const float d3 = glm::dot (p1, n3); const glm::vec3 p3 = ((d1 * glm::cross (n2, n3)) + (d2 * glm::cross (n3, n1)) + (d3 * glm::cross (n1, n2))) / (glm::dot (n1, glm::cross (n2, n3))); return (p1 * 0.25f) + (p3 * 0.5f) + (p2 * 0.25f); } } void splitEdges (DynamicMesh& mesh, ToolSculptEdgeMap& newE, float maxLength, DynamicFaces& faces) { assert (faces.hasUncomitted () == false); const auto split = [&mesh, &newE, maxLength](unsigned int i1, unsigned int i2) { if (glm::distance2 (mesh.vertex (i1), mesh.vertex (i2)) > maxLength * maxLength) { const glm::vec3 normal = glm::normalize (mesh.vertexNormal (i1) + mesh.vertexNormal (i2)); const unsigned int i3 = mesh.addVertex (getSplitPosition (mesh, i1, i2), normal); newE.insert (i1, i2, i3); return true; } else { return false; } }; faces.filter ([&mesh, &newE, &split](unsigned int f) { bool wasSplit = false; unsigned int i1, i2, i3; mesh.vertexIndices (f, i1, i2, i3); if (newE.contains (i1, i2) == false) { wasSplit = split (i1, i2) || wasSplit; } if (newE.contains (i1, i3) == false) { wasSplit = split (i1, i3) || wasSplit; } if (newE.contains (i2, i3) == false) { wasSplit = split (i2, i3) || wasSplit; } return wasSplit; }); } void triangulate (DynamicMesh& mesh, const ToolSculptEdgeMap& newE, DynamicFaces& faces) { assert (faces.hasUncomitted () == false); NewFaces newF; mesh.forEachFaceExt (faces, [&mesh, &newE, &newF](unsigned int f) { unsigned int i1, i2, i3; mesh.vertexIndices (f, i1, i2, i3); const unsigned int e12 = newE.find (i1, i2); const unsigned int e13 = newE.find (i1, i3); const unsigned int e23 = newE.find (i2, i3); const unsigned int invalid = Util::invalidIndex (); const unsigned int v1 = mesh.valence (i1); const unsigned int v2 = mesh.valence (i2); const unsigned int v3 = mesh.valence (i3); if (e12 == invalid && e13 == invalid && e23 == invalid) { } // One new vertex else if (e12 != invalid && e13 == invalid && e23 == invalid) { newF.deleteFace (f); newF.addFace (i1, e12, i3); newF.addFace (i3, e12, i2); } else if (e12 == invalid && e13 != invalid && e23 == invalid) { newF.deleteFace (f); newF.addFace (i3, e13, i2); newF.addFace (i2, e13, i1); } else if (e12 == invalid && e13 == invalid && e23 != invalid) { newF.deleteFace (f); newF.addFace (i2, e23, i1); newF.addFace (i1, e23, i3); } // Two new vertices else if (e12 != invalid && e13 != invalid && e23 == invalid) { newF.deleteFace (f); newF.addFace (e12, e13, i1); if (v2 < v3) { newF.addFace (i2, i3, e13); newF.addFace (i2, e13, e12); } else { newF.addFace (i3, e12, i2); newF.addFace (i3, e13, e12); } } else if (e12 != invalid && e13 == invalid && e23 != invalid) { newF.deleteFace (f); newF.addFace (e23, e12, i2); if (v1 < v3) { newF.addFace (i1, e23, i3); newF.addFace (i1, e12, e23); } else { newF.addFace (i3, i1, e12); newF.addFace (i3, e12, e23); } } else if (e12 == invalid && e13 != invalid && e23 != invalid) { newF.deleteFace (f); newF.addFace (e13, e23, i3); if (v1 < v2) { newF.addFace (i1, i2, e23); newF.addFace (i1, e23, e13); } else { newF.addFace (i2, e13, i1); newF.addFace (i2, e23, e13); } } // Three new vertices else if (e12 != invalid && e13 != invalid && e23 != invalid) { newF.deleteFace (f); newF.addFace (e12, e23, e13); newF.addFace (i1, e12, e13); newF.addFace (i2, e23, e12); newF.addFace (i3, e13, e23); } else { DILAY_IMPOSSIBLE } }); const bool increasing = newF.applyToMesh (mesh, faces); assert (increasing); unused (increasing); faces.commit (); } void relaxEdges (DynamicMesh& mesh, const DynamicFaces& faces) { assert (faces.hasUncomitted () == false); const auto isRelaxable = [&mesh](const ui_pair& edge, unsigned int leftVertex, unsigned int rightVertex) { const int vE1 = int(mesh.valence (edge.first)); const int vE2 = int(mesh.valence (edge.second)); const int vL = int(mesh.valence (leftVertex)); const int vR = int(mesh.valence (rightVertex)); const int pre = glm::abs (vE1 - 6) + glm::abs (vE2 - 6) + glm::abs (vL - 6) + glm::abs (vR - 6); const int post = glm::abs (vE1 - 6 - 1) + glm::abs (vE2 - 6 - 1) + glm::abs (vL - 6 + 1) + glm::abs (vR - 6 + 1); return (vE1 > 3) && (vE2 > 3) && (post < pre); }; ToolSculptEdgeSet edgeSet; mesh.forEachVertex (faces, [&mesh, &edgeSet](unsigned int i) { if (mesh.valence (i) > 6) { mesh.forEachVertexAdjacentToVertex ( i, [i, &edgeSet](unsigned int j) { edgeSet.insert (i, j); }); } }); for (const ui_pair& edge : edgeSet) { unsigned int leftFace, leftVertex, rightFace, rightVertex; mesh.findAdjacent (edge.first, edge.second, leftFace, leftVertex, rightFace, rightVertex); if (isRelaxable (edge, leftVertex, rightVertex)) { mesh.deleteFace (leftFace); mesh.deleteFace (rightFace); const unsigned int newLeftFace = mesh.addFace (leftVertex, edge.first, rightVertex); const unsigned int newRightFace = mesh.addFace (rightVertex, edge.second, leftVertex); assert (newLeftFace == rightFace); assert (newRightFace == leftFace); unused (newLeftFace); unused (newRightFace); } } } void smooth (DynamicMesh& mesh, DynamicFaces& faces) { std::unordered_map newPosition; mesh.forEachVertex (faces, [&mesh, &newPosition](unsigned int i) { const glm::vec3 avgPos = mesh.averagePosition (i); const glm::vec3& normal = mesh.vertexNormal (i); const glm::vec3 delta = avgPos - mesh.vertex (i); const glm::vec3 tangentialPos = avgPos - (normal * glm::dot (normal, delta)); constexpr float lo = -Util::epsilon (); constexpr float hi = 1.0f + Util::epsilon (); float minDistance = Util::maxFloat (); glm::vec3 projectedPos (0.0f); for (unsigned int a : mesh.adjacentFaces (i)) { unsigned int i1, i2, i3; mesh.vertexIndices (a, i1, i2, i3); const glm::vec3& p1 = mesh.vertex (i1); const glm::vec3& p2 = mesh.vertex (i2); const glm::vec3& p3 = mesh.vertex (i3); const glm::vec3 u = p2 - p1; const glm::vec3 v = p3 - p1; const glm::vec3 w = tangentialPos - p1; const glm::vec3 n = glm::cross (u, v); const float b1 = glm::dot (glm::cross (u, w), n) / (glm::dot (n, n)); const float b2 = glm::dot (glm::cross (w, v), n) / (glm::dot (n, n)); const float b3 = 1.0f - b1 - b2; if (lo < b1 && b1 < hi && lo < b2 && b2 < hi && lo < b3 && b3 < hi) { const glm::vec3 proj = (b3 * p1) + (b2 * p2) + (b1 * p3); const float d = glm::distance2 (tangentialPos, proj); if (d < minDistance) { minDistance = d; projectedPos = proj; } } } if (minDistance != Util::maxFloat ()) { newPosition.emplace (i, projectedPos); } else { newPosition.emplace (i, tangentialPos); } }); for (const auto& it : newPosition) { mesh.vertex (it.first, it.second); } } bool deleteValence3Vertex (DynamicMesh& mesh, unsigned int i, DynamicFaces& faces) { assert (mesh.isFreeVertex (i) == false); assert (mesh.valence (i) == 3); const unsigned int adj1 = mesh.adjacentFaces (i)[0]; const unsigned int adj2 = mesh.adjacentFaces (i)[1]; const unsigned int adj3 = mesh.adjacentFaces (i)[2]; unsigned int adj11, adj12, adj13; mesh.vertexIndices (adj1, adj11, adj12, adj13); unsigned int adj21, adj22, adj23; mesh.vertexIndices (adj2, adj21, adj22, adj23); unsigned int newI1, newI2, newI3; if (i == adj11) { newI1 = adj12; newI2 = adj13; } else if (i == adj12) { newI1 = adj13; newI2 = adj11; } else if (i == adj13) { newI1 = adj11; newI2 = adj12; } else { DILAY_IMPOSSIBLE } if (adj21 != newI1 && adj21 != newI2) { newI3 = adj21; } else if (adj22 != newI1 && adj22 != newI2) { newI3 = adj22; } else if (adj23 != newI1 && adj23 != newI2) { newI3 = adj23; } else { DILAY_IMPOSSIBLE } assert (newI1 != newI2); assert (newI1 != newI3); assert (newI2 != newI3); if (mesh.valence (newI1) > 3 && mesh.valence (newI2) > 3 && mesh.valence (newI3) > 3) { mesh.deleteFace (adj1); mesh.deleteFace (adj2); mesh.deleteFace (adj3); mesh.deleteVertex (i); faces.insert (mesh.addFace (newI1, newI2, newI3)); return true; } else { return false; } }; bool collapseEdge (DynamicMesh& mesh, unsigned int i1, unsigned int i2, DynamicFaces faces) { const unsigned int v1 = mesh.valence (i1); const unsigned int v2 = mesh.valence (i2); assert (v1 >= 3); assert (v2 >= 3); #ifndef NDEBUG const auto isValidEdge = [&mesh](unsigned int i1, unsigned int i2) { assert (i1 != i2); assert (mesh.isFreeVertex (i1) == false); assert (mesh.isFreeVertex (i2) == false); for (unsigned int a : mesh.adjacentFaces (i1)) { unsigned int a1, a2, a3; mesh.vertexIndices (a, a1, a2, a3); if (i2 == a1 || i2 == a2 || i2 == a3) { return true; } } return false; }; assert (isValidEdge (i1, i2)); #endif NewFaces newFaces; const auto addFaces = [&mesh, &newFaces](unsigned int newI, unsigned int i1, unsigned int i2) { for (unsigned int a : mesh.adjacentFaces (i1)) { unsigned int a1, a2, a3; mesh.vertexIndices (a, a1, a2, a3); const bool a1IsAdjacent = (a1 != i1) && (a1 != i2); const bool a2IsAdjacent = (a2 != i1) && (a2 != i2); const bool a3IsAdjacent = (a3 != i1) && (a3 != i2); assert (a1IsAdjacent || a2IsAdjacent || a3IsAdjacent); assert (a1IsAdjacent == false || a2IsAdjacent == false || a3IsAdjacent == false); if (a1IsAdjacent && a2IsAdjacent) { newFaces.addFace (newI, a1, a2); } else if (a2IsAdjacent && a3IsAdjacent) { newFaces.addFace (newI, a2, a3); } else if (a3IsAdjacent && a1IsAdjacent) { newFaces.addFace (newI, a3, a1); } newFaces.deleteFace (a); } }; const auto numCommonAdjacentVertices = [&mesh, &i1, &i2]() -> unsigned int { const auto getSuccessor = [&mesh](unsigned int i, unsigned int a) { unsigned int a1, a2, a3; mesh.vertexIndices (a, a1, a2, a3); if (i == a1) { return a2; } else if (i == a2) { return a3; } else if (i == a3) { return a1; } else { DILAY_IMPOSSIBLE } }; unsigned int n = 0; for (unsigned int a1 : mesh.adjacentFaces (i1)) { const unsigned int succI1 = getSuccessor (i1, a1); if (succI1 != i2) { for (unsigned int a2 : mesh.adjacentFaces (i2)) { if (succI1 == getSuccessor (i2, a2)) { n++; } } } } return n; }; const glm::vec3 newPos = Util::midpoint (mesh.vertex (i1), mesh.vertex (i2)); if (v1 == 3) { if (deleteValence3Vertex (mesh, i1, faces)) { mesh.vertex (i2, newPos); return true; } else { return false; } } if (v2 == 3) { if (deleteValence3Vertex (mesh, i2, faces)) { mesh.vertex (i1, newPos); return true; } else { return false; } } unsigned int leftFace, leftVertex, rightFace, rightVertex; mesh.findAdjacent (i1, i2, leftFace, leftVertex, rightFace, rightVertex); const unsigned int vLeftVertex = mesh.valence (leftVertex); const unsigned int vRightVertex = mesh.valence (rightVertex); assert (vLeftVertex >= 3); assert (vRightVertex >= 3); if (leftVertex == rightVertex) { return false; } else if (vLeftVertex == 3 || vRightVertex == 3) { return false; } else if (numCommonAdjacentVertices () == 2) { const unsigned int newI = mesh.addVertex (newPos, glm::vec3 (0.0f)); addFaces (newI, i1, i2); addFaces (newI, i2, i1); newFaces.applyToMesh (mesh, faces); assert (mesh.adjacentFaces (i1).empty ()); assert (mesh.adjacentFaces (i2).empty ()); mesh.deleteVertex (i1); mesh.deleteVertex (i2); assert (mesh.isFreeVertex (i1)); assert (mesh.isFreeVertex (i2)); assert (mesh.valence (newI) == v1 + v2 - 4); return true; } else { return false; } } typedef std::function CollapsePredicate; bool collapseEdges (DynamicMesh& mesh, const CollapsePredicate& doCollapse, DynamicFaces& faces) { bool collapsed = false; DynamicFaces current; current.insert (faces.indices ()); do { faces.insert (current.uncommitted ()); current.commit (); for (unsigned int i : current) { if (mesh.isFreeFace (i) == false) { unsigned int i1, i2, i3; mesh.vertexIndices (i, i1, i2, i3); if (doCollapse (i1, i2)) { collapsed = collapseEdge (mesh, i1, i2, current) || collapsed; } else if (doCollapse (i1, i3)) { collapsed = collapseEdge (mesh, i1, i3, current) || collapsed; } else if (doCollapse (i2, i3)) { collapsed = collapseEdge (mesh, i2, i3, current) || collapsed; } } } } while (current.uncommitted ().empty () == false); faces.filter ([&mesh](unsigned int f) { return mesh.isFreeFace (f) == false; }); faces.commit (); return collapsed; } bool collapseEdgesByLength (DynamicMesh& mesh, float maxEdgeLengthSqr, DynamicFaces& faces) { const auto isCollapsable = [&mesh, maxEdgeLengthSqr](unsigned int i1, unsigned i2) -> bool { assert (mesh.isFreeVertex (i1) == false); assert (mesh.isFreeVertex (i2) == false); return glm::distance2 (mesh.vertex (i1), mesh.vertex (i2)) < maxEdgeLengthSqr; }; return collapseEdges (mesh, isCollapsable, faces); } bool collapseAllEdges (DynamicMesh& mesh, DynamicFaces& faces) { return collapseEdges (mesh, [](unsigned int, unsigned int) { return true; }, faces); } void finalize (DynamicMesh& mesh, const DynamicFaces& faces) { mesh.forEachVertex (faces, [&mesh](unsigned int i) { mesh.setVertexNormal (i); }); for (unsigned int i : faces) { mesh.realignFace (i); } } } namespace ToolSculptAction { void sculpt (const SculptBrush& brush) { DynamicFaces faces = brush.getAffectedFaces (); if (faces.numElements () > 0) { DynamicMesh& mesh = brush.mesh (); if (brush.parameters ().reduce ()) { const float maxEdgeLengthSqr = mesh.averageEdgeLengthSqr (faces) * brush.parameters ().intensity (); collapseEdgesByLength (mesh, maxEdgeLengthSqr, faces); if (mesh.isEmpty ()) { mesh.reset (); return; } else { extendDomain (mesh, faces, 1); smooth (mesh, faces); finalize (mesh, faces); } assert (mesh.pruneAndCheckConsistency ()); } else { if (brush.subdivide ()) { ToolSculptEdgeMap newEdges; do { newEdges.reset (); extendAndFilterDomain (brush, faces, 1); extendDomainByPoles (mesh, faces); const float maxLength = glm::max (brush.subdivThreshold (), 2.0f * minEdgeLength); splitEdges (mesh, newEdges, maxLength, faces); if (newEdges.isEmpty () == false) { triangulate (mesh, newEdges, faces); } extendDomain (mesh, faces, 1); relaxEdges (mesh, faces); smooth (mesh, faces); finalize (mesh, faces); } while (faces.numElements () > 0 && newEdges.isEmpty () == false); } faces = brush.getAffectedFaces (); brush.sculpt (faces); collapseEdgesByLength (mesh, minEdgeLength * minEdgeLength, faces); finalize (mesh, faces); } } } void smoothMesh (DynamicMesh& mesh) { DynamicFaces faces; mesh.forEachFace ([&faces](unsigned int i) { faces.insert (i); }); faces.commit (); relaxEdges (mesh, faces); smooth (mesh, faces); finalize (mesh, faces); mesh.bufferData (); } bool deleteFaces (DynamicMesh& mesh, DynamicFaces& faces) { bool collapsed = collapseAllEdges (mesh, faces); collapsed = collapseEdgesByLength (mesh, minEdgeLength * minEdgeLength, faces) || collapsed; finalize (mesh, faces); mesh.bufferData (); return collapsed; } } ================================================ FILE: lib/src/tool/sculpt/util/action.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_SCULPT_ACTION #define DILAY_TOOL_SCULPT_ACTION class DynamicMesh; class SculptBrush; namespace ToolSculptAction { void sculpt (const SculptBrush&); void smoothMesh (DynamicMesh&); bool deleteFaces (DynamicMesh&, DynamicFaces&); }; #endif ================================================ FILE: lib/src/tool/sculpt/util/brush.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "dynamic/faces.hpp" #include "dynamic/mesh.hpp" #include "primitive/plane.hpp" #include "primitive/sphere.hpp" #include "primitive/triangle.hpp" #include "tool/sculpt/util/brush.hpp" #include "util.hpp" SBFlattenParameters::SBFlattenParameters () : _lockPlane (false) { } bool SBFlattenParameters::hasLockedPlane () const { return bool(this->_lockedPlane); } const PrimPlane& SBFlattenParameters::lockedPlane () const { return *this->_lockedPlane; } void SBFlattenParameters::lockedPlane (const PrimPlane& p) { this->_lockedPlane = p; } void SBFlattenParameters::resetLockedPlane () { this->_lockedPlane.reset (); } void SBFlattenParameters::mirror (const PrimPlane& m) { if (this->hasLockedPlane ()) { this->_lockedPlane->point (m.mirror (this->_lockedPlane->point ())); this->_lockedPlane->normal (m.mirrorDirection (this->_lockedPlane->normal ())); } } void SBDrawParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const { if (faces.isEmpty () == false) { const float intensity = 0.3f * this->intensity (); const glm::vec3 planeNormal = this->invert (brush.normal ()); const glm::vec3 planePos = brush.position () + (planeNormal * intensity * brush.radius ()); const PrimPlane plane (planePos, planeNormal); brush.mesh ().forEachVertex (faces, [&brush, &plane, intensity](unsigned int i) { const glm::vec3& oldPos = brush.mesh ().vertex (i); const float factor = intensity * Util::linearStep (oldPos, brush.position (), 0.5f * brush.radius (), brush.radius ()); const float distance = glm::min (0.0f, plane.distance (oldPos)); const glm::vec3 newPos = oldPos - (plane.normal () * factor * distance); brush.mesh ().vertex (i, newPos); }); } } void SBGrablikeParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const { brush.mesh ().forEachVertex (faces, [&brush](unsigned int i) { const glm::vec3& oldPos = brush.mesh ().vertex (i); const float factor = Util::linearStep (oldPos, brush.lastPosition (), 0.0f, brush.radius ()); const glm::vec3 newPos = oldPos + (factor * brush.delta ()); brush.mesh ().vertex (i, newPos); }); } void SBSmoothParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const { brush.mesh ().forEachVertex (faces, [this, &brush](unsigned int i) { const glm::vec3 avgPos = brush.mesh ().averagePosition (i); const glm::vec3& oldPos = brush.mesh ().vertex (i); const glm::vec3 newPos = oldPos + (this->intensity () * (avgPos - oldPos)); brush.mesh ().vertex (i, newPos); }); } void SBReduceParameters::sculpt (const SculptBrush&, const DynamicFaces&) const {} void SBFlattenParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const { if (faces.isEmpty () == false) { PrimPlane plane (glm::vec3 (0.0f), glm::vec3 (1.0f)); if (this->hasLockedPlane ()) { plane = this->lockedPlane (); } else { glm::vec3 avgPos, avgNormal; brush.mesh ().average (faces, avgPos, avgNormal); plane = PrimPlane (avgPos, avgNormal); } brush.mesh ().forEachVertex (faces, [this, &brush, &plane](unsigned int i) { const glm::vec3& oldPos = brush.mesh ().vertex (i); const float distance = plane.distance (oldPos); float factor = this->intensity () * Util::linearStep (oldPos, brush.position (), 0.0f, brush.radius ()); factor *= this->hasLockedPlane () ? distance : glm::max (0.0f, distance); const glm::vec3 newPos = oldPos - (plane.normal () * factor); brush.mesh ().vertex (i, newPos); }); } } void SBCreaseParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const { if (faces.isEmpty () == false && brush.position () != brush.lastPosition ()) { const glm::vec3 normal = this->invert (brush.normal ()); brush.mesh ().forEachVertex (faces, [this, &brush, &normal](unsigned int i) { const glm::vec3& oldPos = brush.mesh ().vertex (i); const glm::vec3 delta = brush.position () - oldPos; const float distance = glm::length (delta) / brush.radius (); if (distance <= 1.0f) { const float invDistance2 = (distance - 1.0f) * (distance - 1.0f); const float hFactor = invDistance2 * this->intensity (); float vFactor = invDistance2 * invDistance2 * brush.radius () * this->intensity () * 0.5f; const glm::vec3 newPos = (oldPos + (hFactor * delta)) + (normal * vFactor); brush.mesh ().vertex (i, newPos); } }); } } void SBPinchParameters::sculpt (const SculptBrush& brush, const DynamicFaces& faces) const { brush.mesh ().forEachVertex (faces, [&brush](unsigned int i) { const glm::vec3& oldPos = brush.mesh ().vertex (i); const glm::vec3 delta = brush.position () - oldPos; const float distance = glm::length (delta) / brush.radius (); if (distance <= 1.0f) { const float invDistance2 = (distance - 1.0f) * (distance - 1.0f); const float hFactor = invDistance2 * 0.5f; const glm::vec3 newPos = oldPos + (hFactor * delta); brush.mesh ().vertex (i, newPos); } }); } struct SculptBrush::Impl { SculptBrush* self; float radius; float detailFactor; float stepWidthFactor; bool subdivide; DynamicMesh* _mesh; bool hasPointOfAction; glm::vec3 _prevPosition; glm::vec3 _position; glm::vec3 _normal; std::unique_ptr _parameters; Impl (SculptBrush* s) : self (s) , radius (0.0f) , detailFactor (0.0f) , stepWidthFactor (0.0f) , subdivide (true) , _mesh (nullptr) , hasPointOfAction (false) { } DynamicMesh& mesh () const { assert (this->hasPointOfAction); assert (this->_mesh); return *this->_mesh; } void mesh (DynamicMesh& m) { this->_mesh = &m; } float subdivThreshold () const { assert (this->detailFactor > 0.0f); assert (this->detailFactor < 1.0f); return (1.0f - this->detailFactor) * this->radius; } const glm::vec3& lastPosition () const { assert (this->hasPointOfAction); return this->_prevPosition; } const glm::vec3& position () const { assert (this->hasPointOfAction); return this->_position; } const glm::vec3& normal () const { assert (this->hasPointOfAction); return this->_normal; } glm::vec3 delta () const { assert (this->hasPointOfAction); return this->_position - this->_prevPosition; } PrimSphere sphere () const { assert (this->_parameters); const glm::vec3& pos = this->_parameters->useLastPos () ? this->lastPosition () : this->position (); return PrimSphere (pos, this->radius); } float stepWidth () const { return this->stepWidthFactor * glm::log (this->self->radius () + 1); } void setPointOfAction (DynamicMesh& mesh, const glm::vec3& p, const glm::vec3& n) { this->_mesh = &mesh; this->_prevPosition = this->hasPointOfAction ? this->_position : p; this->_position = p; this->_normal = n; this->hasPointOfAction = true; } void resetPointOfAction () { this->hasPointOfAction = false; this->_mesh = nullptr; } void mirror (const PrimPlane& plane) { if (this->_parameters) { this->_parameters->mirror (plane); } if (this->hasPointOfAction) { this->_prevPosition = plane.mirror (this->_prevPosition); this->_position = plane.mirror (this->_position); this->_normal = plane.mirrorDirection (this->_normal); } } DynamicFaces getAffectedFaces () const { assert (this->hasPointOfAction); assert (this->_parameters); DynamicFaces faces; this->_mesh->intersects (this->sphere (), faces); if (this->_parameters->discardBack ()) { faces.filter ([this](unsigned int i) { return glm::dot (this->normal (), this->_mesh->face (i).cross ()) > 0.0f; }); } return faces; } void sculpt (const DynamicFaces& faces) const { assert (this->_parameters); this->_parameters->sculpt (*this->self, faces); } SBParameters* parametersPointer () const { return this->_parameters.get (); } void parametersPointer (SBParameters* p) { this->_parameters.reset (p); } }; DELEGATE_BIG3_SELF (SculptBrush) GETTER_CONST (float, SculptBrush, radius) GETTER_CONST (float, SculptBrush, detailFactor) GETTER_CONST (float, SculptBrush, stepWidthFactor) GETTER_CONST (bool, SculptBrush, subdivide) DELEGATE_CONST (DynamicMesh&, SculptBrush, mesh) SETTER (float, SculptBrush, radius) SETTER (float, SculptBrush, detailFactor) SETTER (float, SculptBrush, stepWidthFactor) SETTER (bool, SculptBrush, subdivide) DELEGATE_CONST (float, SculptBrush, subdivThreshold) DELEGATE_CONST (const glm::vec3&, SculptBrush, lastPosition) DELEGATE_CONST (const glm::vec3&, SculptBrush, position) DELEGATE_CONST (const glm::vec3&, SculptBrush, normal) DELEGATE_CONST (glm::vec3, SculptBrush, delta) DELEGATE_CONST (PrimSphere, SculptBrush, sphere) DELEGATE_CONST (float, SculptBrush, stepWidth) GETTER_CONST (bool, SculptBrush, hasPointOfAction) DELEGATE3 (void, SculptBrush, setPointOfAction, DynamicMesh&, const glm::vec3&, const glm::vec3&) DELEGATE (void, SculptBrush, resetPointOfAction) DELEGATE1 (void, SculptBrush, mirror, const PrimPlane&) DELEGATE_CONST (DynamicFaces, SculptBrush, getAffectedFaces) DELEGATE1_CONST (void, SculptBrush, sculpt, const DynamicFaces&) DELEGATE_CONST (SBParameters*, SculptBrush, parametersPointer) DELEGATE1 (void, SculptBrush, parametersPointer, SBParameters*) ================================================ FILE: lib/src/tool/sculpt/util/brush.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_SCULPT_BRUSH #define DILAY_TOOL_SCULPT_BRUSH #include #include "macro.hpp" #include "maybe.hpp" class DynamicFaces; class DynamicMesh; class PrimPlane; class PrimSphere; class SculptBrush; class SBParameters { public: virtual ~SBParameters () {} virtual float intensity () const { return 0.0f; } virtual void intensity (float) {} virtual bool useLastPos () const { return false; } virtual bool discardBack () const { return true; } virtual bool reduce () const { return false; } virtual void mirror (const PrimPlane&) {} virtual void sculpt (const SculptBrush&, const DynamicFaces&) const = 0; }; class SBIntensityParameter : virtual public SBParameters { public: SBIntensityParameter () : _intensity (0.0f) { } MEMBER_GETTER_SETTER (float, intensity); }; class SBInvertParameter : virtual public SBParameters { public: SBInvertParameter () : _invert (false) { } void toggleInvert () { this->_invert = !this->_invert; } glm::vec3 invert (const glm::vec3& v) const { return this->_invert ? -v : v; } MEMBER_GETTER_SETTER (bool, invert); }; class SBDiscardBackParameter : virtual public SBParameters { public: SBDiscardBackParameter () : _discardBack (true) { } bool discardBack () const override { return this->_discardBack; } void discardBack (bool d) { this->_discardBack = d; } private: bool _discardBack; }; class SBDrawParameters : public SBIntensityParameter, public SBInvertParameter { public: SBDrawParameters () : _constantHeight (false) { } void sculpt (const SculptBrush&, const DynamicFaces&) const; MEMBER_GETTER_SETTER (bool, constantHeight); }; class SBGrablikeParameters : public SBDiscardBackParameter { public: void sculpt (const SculptBrush&, const DynamicFaces&) const override; bool useLastPos () const override { return true; } }; class SBSmoothParameters : public SBIntensityParameter { public: void sculpt (const SculptBrush&, const DynamicFaces&) const; }; class SBReduceParameters : public SBIntensityParameter { public: bool reduce () const override { return true; } void sculpt (const SculptBrush&, const DynamicFaces&) const override; }; class SBFlattenParameters : public SBIntensityParameter { public: SBFlattenParameters (); void sculpt (const SculptBrush&, const DynamicFaces&) const override; bool hasLockedPlane () const; const PrimPlane& lockedPlane () const; void lockedPlane (const PrimPlane& p); void resetLockedPlane (); void mirror (const PrimPlane&) override; MEMBER_GETTER_SETTER (bool, lockPlane); private: Maybe _lockedPlane; }; class SBCreaseParameters : public SBIntensityParameter, public SBInvertParameter { public: void sculpt (const SculptBrush&, const DynamicFaces&) const; }; class SBPinchParameters : public SBInvertParameter { public: void sculpt (const SculptBrush&, const DynamicFaces&) const; }; class SculptBrush { public: DECLARE_BIG3 (SculptBrush) float radius () const; float detailFactor () const; float stepWidthFactor () const; bool subdivide () const; bool hasMesh () const; DynamicMesh& mesh () const; void radius (float); void detailFactor (float); void stepWidthFactor (float); void subdivide (bool); float subdivThreshold () const; const glm::vec3& lastPosition () const; const glm::vec3& position () const; const glm::vec3& normal () const; glm::vec3 delta () const; PrimSphere sphere () const; float stepWidth () const; bool hasPointOfAction () const; void setPointOfAction (DynamicMesh&, const glm::vec3&, const glm::vec3&); void resetPointOfAction (); void mirror (const PrimPlane&); DynamicFaces getAffectedFaces () const; void sculpt (const DynamicFaces&) const; template T& initParameters () { this->parametersPointer (new T ()); return this->parameters (); } template T& parameters () { return dynamic_cast (*this->parametersPointer ()); } const SBParameters& parameters () const { return *this->parametersPointer (); } private: SBParameters* parametersPointer () const; void parametersPointer (SBParameters*); IMPLEMENTATION }; #endif ================================================ FILE: lib/src/tool/sculpt/util/edge-collection.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "tool/sculpt/util/edge-collection.hpp" #include "util.hpp" namespace { ui_pair makeUiKey (unsigned int i1, unsigned int i2) { assert (i1 != i2); return ui_pair (glm::min (i1, i2), glm::max (i1, i2)); } } void ToolSculptEdgeMap::insert (unsigned int i1, unsigned int i2, unsigned int value) { assert (this->contains (i1, i2) == false); this->map.emplace (makeUiKey (i1, i2), value); } unsigned int ToolSculptEdgeMap::find (unsigned int i1, unsigned int i2) const { const auto it = this->map.find (makeUiKey (i1, i2)); return it == this->map.end () ? Util::invalidIndex () : it->second; } bool ToolSculptEdgeMap::contains (unsigned int i1, unsigned int i2) const { return this->find (i1, i2) != Util::invalidIndex (); } bool ToolSculptEdgeMap::isEmpty () const { return this->map.empty (); } void ToolSculptEdgeMap::reset () { this->map.clear (); } void ToolSculptEdgeSet::insert (unsigned int i1, unsigned int i2) { this->set.emplace (makeUiKey (i1, i2)); } bool ToolSculptEdgeSet::contains (unsigned int i1, unsigned int i2) const { return this->set.find (makeUiKey (i1, i2)) != this->set.end (); } bool ToolSculptEdgeSet::isEmpty () const { return this->set.empty (); } void ToolSculptEdgeSet::reset () { this->set.clear (); } ================================================ FILE: lib/src/tool/sculpt/util/edge-collection.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_SCULPT_EDGE_COLLECTION #define DILAY_TOOL_SCULPT_EDGE_COLLECTION #include #include #include "hash.hpp" class ToolSculptEdgeMap { public: typedef std::unordered_map, unsigned int> Map; void insert (unsigned int, unsigned int, unsigned int); unsigned int find (unsigned int, unsigned int) const; bool contains (unsigned int, unsigned int) const; bool isEmpty () const; void reset (); private: Map map; }; class ToolSculptEdgeSet { public: typedef std::unordered_set> Set; void insert (unsigned int, unsigned int); bool contains (unsigned int, unsigned int) const; bool isEmpty () const; void reset (); Set::const_iterator begin () const { return this->set.begin (); } Set::const_iterator end () const { return this->set.end (); } private: Set set; }; #endif ================================================ FILE: lib/src/tool/sculpt.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "cache.hpp" #include "camera.hpp" #include "config.hpp" #include "dynamic/mesh-intersection.hpp" #include "dynamic/mesh.hpp" #include "history.hpp" #include "maybe.hpp" #include "mirror.hpp" #include "primitive/ray.hpp" #include "scene.hpp" #include "state.hpp" #include "tool/sculpt.hpp" #include "tool/sculpt/util/action.hpp" #include "tool/sculpt/util/brush.hpp" #include "tool/util/movement.hpp" #include "tool/util/step.hpp" #include "view/cursor.hpp" #include "view/double-slider.hpp" #include "view/pointing-event.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" namespace { enum class SculptState { None, Started, Sculpted, Ended }; } struct ToolSculpt::Impl { ToolSculpt* self; SculptBrush brush; ViewCursor cursor; CacheProxy commonCache; ViewDoubleSlider& radiusEdit; ViewDoubleSlider* secondarySlider; bool absoluteRadius; SculptState sculptState; ToolUtilStep step; Impl (ToolSculpt* s) : self (s) , commonCache (this->self->cache ("sculpt")) , radiusEdit ( ViewUtil::slider (2, 0.01f, this->commonCache.get ("radius", 0.1f), 1.0f, 3)) , secondarySlider (nullptr) , absoluteRadius (this->commonCache.get ("absolute-radius", true)) , sculptState (SculptState::None) { } ToolResponse runInitialize () { this->self->supportsMirror (); this->setupBrush (); this->setupCursor (); this->setupProperties (); this->setupToolTip (); return ToolResponse::Redraw; } void setupBrush () { this->brush.subdivide (this->commonCache.get ("subdivide", true)); if (this->absoluteRadius) { this->setAbsoluteRadius (); } else { this->setRelativeRadius (); } this->self->runSetupBrush (this->brush); } void setupCursor () { assert (this->brush.radius () > 0.0f); DynamicMeshIntersection intersection; if (this->self->intersectsScene (this->self->cursorPosition (), intersection)) { this->cursor.enable (); this->cursor.position (intersection.position ()); } else { this->cursor.disable (); } this->cursor.radius (this->brush.radius ()); this->self->runSetupCursor (this->cursor); } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); ViewUtil::connect (this->radiusEdit, [this](float r) { if (this->absoluteRadius) { this->setAbsoluteRadius (); } else { this->setRelativeRadius (); } this->commonCache.set ("radius", r); this->self->updateGlWidget (); }); properties.addStacked (QObject::tr ("Radius"), this->radiusEdit); QCheckBox& absRadiusEdit = ViewUtil::checkBox (QObject::tr ("Absolute radius"), this->absoluteRadius); ViewUtil::connect (absRadiusEdit, [this](bool a) { if (a) { this->setAbsoluteRadius (); } else { this->setRelativeRadius (); } this->commonCache.set ("absolute-radius", a); this->self->updateGlWidget (); }); properties.add (absRadiusEdit); this->self->addMirrorProperties (); properties.add (ViewUtil::horizontalLine ()); this->self->runSetupProperties (properties); } void setupToolTip () { ViewToolTip toolTip; this->self->runSetupToolTip (toolTip); toolTip.add (ViewInputEvent::R, QObject::tr ("Move to change radius")); this->self->state ().setToolTip (&toolTip); } void runRender () const { Camera& camera = this->self->state ().camera (); if (this->cursor.isEnabled ()) { this->cursor.render (camera); } } ToolResponse runPointingEvent (const ViewPointingEvent& e) { if (this->self->onKeymap ('r') && e.moveEvent ()) { this->radiusEdit.setIntValue (this->radiusEdit.intValue () + e.delta ().x); } else if (this->secondarySlider && this->self->onKeymap ('i') && e.moveEvent ()) { this->secondarySlider->setIntValue (this->secondarySlider->intValue () + e.delta ().x); } else if (e.leftButton ()) { if (e.pressEvent ()) { this->self->snapshotDynamicMeshes (); this->sculptState = SculptState::Started; } const bool doSculpt = this->sculptState == SculptState::Started || this->sculptState == SculptState::Sculpted; if (doSculpt && this->self->runSculptPointingEvent (e)) { this->sculptState = SculptState::Sculpted; } if (e.releaseEvent ()) { this->runCommit (); } } else { this->self->runSculptPointingEvent (e); } return ToolResponse::Redraw; } ToolResponse runCursorUpdate (const glm::ivec2& pos) { DynamicMeshIntersection cursorIntersection; this->setCursorByIntersection (pos, cursorIntersection); return ToolResponse::Redraw; } ToolResponse runCommit () { this->brush.resetPointOfAction (); if (this->sculptState == SculptState::Started) { this->self->state ().history ().dropPastSnapshot (); } this->sculptState = SculptState::None; return ToolResponse::None; } void runFromConfig () { const Config& config = this->self->config (); this->brush.detailFactor (config.get ("editor/tool/sculpt/detail-factor")); this->brush.stepWidthFactor (config.get ("editor/tool/sculpt/step-width-factor")); this->cursor.color (this->self->config ().get ("editor/tool/cursor-color")); } void addDefaultToolTip (ViewToolTip& toolTip, bool hasInvertedMode, bool hasIntensity) { toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Drag to sculpt")); if (hasInvertedMode) { toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift, QObject::tr ("Drag to sculpt inverted")); } if (hasIntensity) { toolTip.add (ViewInputEvent::I, QObject::tr ("Move to change intensity")); } } void sculpt () { assert (this->brush.hasPointOfAction ()); ToolSculptAction::sculpt (this->brush); if (this->self->mirrorEnabled () && this->brush.mesh ().isEmpty () == false) { this->brush.mirror (this->self->mirror ().plane ()); ToolSculptAction::sculpt (this->brush); this->brush.mirror (this->self->mirror ().plane ()); } if (this->brush.mesh ().isEmpty ()) { this->self->state ().scene ().deleteEmptyMeshes (); this->brush.resetPointOfAction (); } } bool setCursorByIntersection (const glm::ivec2& pos, DynamicMeshIntersection& intersection) { if (this->self->intersectsScene (pos, intersection)) { if (this->absoluteRadius == false) { this->setRelativeRadius (intersection.distance ()); } this->cursor.enable (); this->cursor.position (intersection.position ()); return true; } else { this->cursor.disable (); return false; } } bool updateBrushByIntersection (bool useRecentMesh, const glm::vec3& cursorStep) { const glm::vec3 from = this->self->state ().camera ().position (); const PrimRay ray = PrimRay (from, cursorStep - from); DynamicMeshIntersection intersection; if (this->self->intersectsScene (ray, intersection)) { if (this->brush.hasPointOfAction () && (&this->brush.mesh () != &intersection.mesh ())) { this->brush.mesh ().bufferData (); } if (useRecentMesh) { Intersection rIntersection; if (this->self->intersectsRecentDynamicMesh (ray, rIntersection)) { this->brush.setPointOfAction (intersection.mesh (), rIntersection.position (), rIntersection.normal ()); } else { this->brush.mesh ().bufferData (); this->brush.resetPointOfAction (); return false; } } else { this->brush.setPointOfAction (intersection.mesh (), intersection.position (), intersection.normal ()); } return true; } else { this->brush.mesh ().bufferData (); this->brush.resetPointOfAction (); return false; } } bool drawlikeStroke (const ViewPointingEvent& e, bool useRecentMesh, const std::function* toggle) { DynamicMeshIntersection cursorIntersection; if (this->setCursorByIntersection (e.position (), cursorIntersection) && e.leftButton ()) { SBParameters& parameters = this->brush.parameters (); const float defaultIntesity = parameters.intensity (); const bool doToggle = toggle && e.modifiers () == Qt::ShiftModifier; parameters.intensity (defaultIntesity * e.intensity ()); if (doToggle) { (*toggle) (); } if (this->brush.hasPointOfAction ()) { this->step.stepWidth (this->brush.stepWidth ()); this->step.position (this->brush.position ()); this->step.step (cursorIntersection.position (), [this, useRecentMesh](const glm::vec3& brushStep) { if (this->brush.hasPointOfAction ()) { if (this->updateBrushByIntersection (useRecentMesh, brushStep)) { this->sculpt (); } return true; } else { return false; } }); } else { if (this->updateBrushByIntersection (useRecentMesh, cursorIntersection.position ())) { this->sculpt (); } } if (this->brush.hasPointOfAction ()) { assert (this->brush.mesh ().isEmpty () == false); this->brush.mesh ().bufferData (); } if (doToggle) { (*toggle) (); } parameters.intensity (defaultIntesity); return true; } else { return false; } } bool grablikeStroke (const ViewPointingEvent& e, ToolUtilMovement& movement) { DynamicMeshIntersection cursorIntersection; if (e.pressEvent ()) { if (e.leftButton ()) { if (this->setCursorByIntersection (e.position (), cursorIntersection)) { this->brush.setPointOfAction (cursorIntersection.mesh (), cursorIntersection.position (), cursorIntersection.normal ()); this->cursor.disable (); movement.reset (cursorIntersection.position ()); return true; } else { this->brush.resetPointOfAction (); return false; } } else { this->cursor.enable (); this->brush.resetPointOfAction (); return false; } } else { if (e.leftButton () == false) { this->setCursorByIntersection (e.position (), cursorIntersection); return false; } else if (this->brush.hasPointOfAction ()) { if (e.moveEvent () && movement.move (e)) { this->brush.setPointOfAction (this->brush.mesh (), movement.position (), this->brush.normal ()); this->sculpt (); if (this->brush.hasPointOfAction ()) { assert (this->brush.mesh ().isEmpty () == false); this->brush.mesh ().bufferData (); } return true; } else { return false; } } else { return false; } } } void registerSecondarySlider (ViewDoubleSlider& slider) { this->secondarySlider = &slider; } void setRelativeRadius (float distance) { const Camera& cam = this->self->state ().camera (); const float factor = this->radiusEdit.doubleValue (); const float radius = cam.toWorld (float(cam.resolution ().x) * factor, distance); this->absoluteRadius = false; this->cursor.radius (radius); this->brush.radius (radius); } void setRelativeRadius () { this->setRelativeRadius ( glm::distance (this->cursor.position (), this->self->state ().camera ().position ())); } void setAbsoluteRadius () { const float max = this->self->config ().get ("editor/tool/sculpt/max-absolute-radius"); const float factor = this->radiusEdit.doubleValue (); this->absoluteRadius = true; this->brush.radius (factor * max); this->cursor.radius (factor * max); } }; DELEGATE_BIG2_BASE (ToolSculpt, (State & s, const char* c), (this), Tool, (s, c)) GETTER (SculptBrush&, ToolSculpt, brush) GETTER (ViewCursor&, ToolSculpt, cursor) DELEGATE3_CONST (void, ToolSculpt, addDefaultToolTip, ViewToolTip&, bool, bool) DELEGATE (void, ToolSculpt, sculpt) DELEGATE3 (bool, ToolSculpt, drawlikeStroke, const ViewPointingEvent&, bool, const std::function*) DELEGATE2 (bool, ToolSculpt, grablikeStroke, const ViewPointingEvent&, ToolUtilMovement&) DELEGATE1 (void, ToolSculpt, registerSecondarySlider, ViewDoubleSlider&) DELEGATE (ToolResponse, ToolSculpt, runInitialize) DELEGATE_CONST (void, ToolSculpt, runRender) DELEGATE1 (ToolResponse, ToolSculpt, runPointingEvent, const ViewPointingEvent&) DELEGATE1 (ToolResponse, ToolSculpt, runCursorUpdate, const glm::ivec2&) DELEGATE (ToolResponse, ToolSculpt, runCommit) DELEGATE (void, ToolSculpt, runFromConfig) ================================================ FILE: lib/src/tool/sculpt.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_SCULPT #define DILAY_TOOL_SCULPT #include "tool.hpp" class QString; class SculptBrush; class ToolUtilMovement; class ViewCursor; class ViewDoubleSlider; class ViewTwoColumnGrid; class ToolSculpt : public Tool { public: DECLARE_BIG2 (ToolSculpt, State&, const char*) protected: SculptBrush& brush (); ViewCursor& cursor (); void addDefaultToolTip (ViewToolTip&, bool, bool) const; void sculpt (); bool drawlikeStroke (const ViewPointingEvent&, bool, const std::function* = nullptr); bool grablikeStroke (const ViewPointingEvent&, ToolUtilMovement&); void registerSecondarySlider (ViewDoubleSlider&); private: IMPLEMENTATION ToolResponse runInitialize (); void runRender () const; ToolResponse runPointingEvent (const ViewPointingEvent&); ToolResponse runCursorUpdate (const glm::ivec2&); ToolResponse runCommit (); void runFromConfig (); virtual void runSetupBrush (SculptBrush&) = 0; virtual void runSetupCursor (ViewCursor&) = 0; virtual void runSetupProperties (ViewTwoColumnGrid&) = 0; virtual void runSetupToolTip (ViewToolTip&) = 0; virtual bool runSculptPointingEvent (const ViewPointingEvent&) = 0; }; #define DECLARE_TOOL_SCULPT(keyName) \ class Tool##keyName : public ToolSculpt \ { \ public: \ DECLARE_BIG2 (Tool##keyName, State&) \ \ ToolKey getKey () const { return ToolKey::keyName; } \ \ private: \ IMPLEMENTATION \ void runSetupBrush (SculptBrush&); \ void runSetupCursor (ViewCursor&); \ void runSetupProperties (ViewTwoColumnGrid&); \ void runSetupToolTip (ViewToolTip&); \ bool runSculptPointingEvent (const ViewPointingEvent&); \ }; #define DELEGATE_TOOL_SCULPT(name) \ DELEGATE_BIG2_BASE (name, (State & s), (this), ToolSculpt, (s, #name)) \ DELEGATE1 (void, name, runSetupBrush, SculptBrush&); \ DELEGATE1 (void, name, runSetupCursor, ViewCursor&); \ DELEGATE1 (void, name, runSetupProperties, ViewTwoColumnGrid&); \ DELEGATE1 (void, name, runSetupToolTip, ViewToolTip&); \ DELEGATE1 (bool, name, runSculptPointingEvent, const ViewPointingEvent&) #endif ================================================ FILE: lib/src/tool/sketch-spheres.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "cache.hpp" #include "camera.hpp" #include "config.hpp" #include "dimension.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "primitive/sphere.hpp" #include "scene.hpp" #include "sketch/mesh-intersection.hpp" #include "sketch/mesh.hpp" #include "sketch/path-intersection.hpp" #include "sketch/path.hpp" #include "state.hpp" #include "tool/util/step.hpp" #include "tools.hpp" #include "view/cursor.hpp" #include "view/double-slider.hpp" #include "view/pointing-event.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ToolSketchSpheres::Impl { ToolSketchSpheres* self; ViewCursor cursor; ViewDoubleSlider& radiusEdit; ViewDoubleSlider& heightEdit; SketchPathSmoothEffect smoothEffect; float stepWidthFactor; SketchMesh* mesh; ToolUtilStep step; Impl (ToolSketchSpheres* s) : self (s) , radiusEdit (ViewUtil::slider (2, 0.01f, s->cache ().get ("radius", 0.1f), 1.0f)) , heightEdit (ViewUtil::slider (2, 0.01f, s->cache ().get ("height", 0.2f), 0.45f)) , smoothEffect (SketchPathSmoothEffect ( s->cache ().get ("smooth-effect", int(SketchPathSmoothEffect::Embed)))) , stepWidthFactor (0.0f) , mesh (nullptr) { } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); this->self->addMirrorProperties (); ViewUtil::connect (this->radiusEdit, [this](float r) { this->cursor.radius (r); this->self->cache ().set ("radius", r); }); properties.addStacked (QObject::tr ("Radius"), this->radiusEdit); ViewUtil::connect (this->heightEdit, [this](float d) { this->self->cache ().set ("height", d); }); properties.addStacked (QObject::tr ("Height"), this->heightEdit); properties.add (ViewUtil::horizontalLine ()); QButtonGroup& smoothEffectEdit = ViewUtil::buttonGroup ({QObject::tr ("None"), QObject::tr ("Embed"), QObject::tr ("Embed and adjust"), QObject::tr ("Pinch")}); ViewUtil::connect (smoothEffectEdit, int(this->smoothEffect), [this](int id) { this->smoothEffect = SketchPathSmoothEffect (id); this->self->cache ().set ("smooth-effect", id); }); properties.addStacked (QObject::tr ("Smoothing effect"), smoothEffectEdit); } void setupToolTip () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Drag to sketch")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift, QObject::tr ("Drag to smooth")); toolTip.add (ViewInputEvent::R, QObject::tr ("Move to change radius")); this->self->state ().setToolTip (&toolTip); } void setupCursor () { this->cursor.disable (); this->cursor.radius (this->radiusEdit.doubleValue ()); } ToolResponse runInitialize () { this->self->supportsMirror (); this->setupProperties (); this->setupToolTip (); this->setupCursor (); return ToolResponse::None; } void runRender () const { Camera& camera = this->self->state ().camera (); if (this->cursor.isEnabled ()) { this->cursor.render (camera); } } glm::vec3 newSpherePosition (bool considerHeight, const glm::vec3& position, const glm::vec3& normal) { if (considerHeight) { const float factor = float(this->radiusEdit.doubleValue () * (1.0f - (2.0f * this->heightEdit.doubleValue ()))); return position - (normal * factor); } else { return position; } } ToolResponse runMoveEvent (const ViewPointingEvent& e) { this->step.stepWidth (this->radiusEdit.doubleValue () * this->stepWidthFactor); if (e.leftButton ()) { if (e.modifiers () == Qt::ShiftModifier) { SketchPathIntersection intersection; if (this->self->intersectsScene (e, intersection)) { this->cursor.enable (); this->cursor.position (intersection.position ()); this->step.step (intersection.position (), [this, &intersection](const glm::vec3& position) { intersection.mesh ().smoothPath (intersection.path (), PrimSphere (position, this->radiusEdit.doubleValue ()), 1, this->smoothEffect, this->self->mirrorDimension ()); return true; }); this->mesh = &intersection.mesh (); } } else if (this->mesh) { SketchMeshIntersection intersection; const unsigned int numExcludedLastPaths = this->self->mirrorEnabled () ? 2 : 1; bool considerHeight = true; if (this->self->intersectsScene (e, intersection, numExcludedLastPaths) == false) { const Camera& camera = this->self->state ().camera (); const PrimRay ray = camera.ray (e.position ()); const PrimPlane plane = PrimPlane (this->step.position (), DimensionUtil::vector (camera.primaryDimension ())); float t; if (IntersectionUtil::intersects (ray, plane, &t)) { intersection.update (t, ray.pointAt (t), plane.normal (), *this->mesh); considerHeight = false; } } if (intersection.isIntersection ()) { this->cursor.enable (); this->cursor.position (intersection.position ()); this->step.step (intersection.position (), [this, considerHeight, &intersection](const glm::vec3& position) { this->mesh->addSphere ( false, intersection.position (), this->newSpherePosition (considerHeight, position, intersection.normal ()), this->radiusEdit.doubleValue (), this->self->mirrorDimension ()); return true; }); } } return ToolResponse::Redraw; } else { if (this->self->onKeymap ('r')) { this->radiusEdit.setIntValue (this->radiusEdit.intValue () + e.delta ().x); } return this->runCursorUpdate (e.position ()); } } ToolResponse runPressEvent (const ViewPointingEvent& e) { auto setupOnIntersection = [this](const SketchMeshIntersection& intersection) { this->cursor.enable (); this->cursor.position (intersection.position ()); this->self->snapshotSketchMeshes (); this->self->mirrorPosition (intersection.mesh ().tree ().root ().data ().center ()); this->mesh = &intersection.mesh (); this->step.position (intersection.position ()); }; if (e.leftButton ()) { if (e.modifiers () == Qt::ShiftModifier) { SketchPathIntersection intersection; if (this->self->intersectsScene (e, intersection)) { setupOnIntersection (intersection); this->mesh->smoothPath ( intersection.path (), PrimSphere (intersection.position (), this->radiusEdit.doubleValue ()), 1, this->smoothEffect, this->self->mirrorDimension ()); } } else { SketchMeshIntersection intersection; if (this->self->intersectsScene (e, intersection)) { setupOnIntersection (intersection); const glm::vec3 spherePosition = this->newSpherePosition (true, intersection.position (), intersection.normal ()); this->mesh->addSphere (true, intersection.position (), spherePosition, this->radiusEdit.doubleValue (), this->self->mirrorDimension ()); } else { this->cursor.disable (); } } return ToolResponse::Redraw; } else { return ToolResponse::None; } } ToolResponse runReleaseEvent (const ViewPointingEvent&) { return this->runCommit (); } ToolResponse runCursorUpdate (const glm::ivec2& pos) { SketchMeshIntersection intersection; if (this->self->intersectsScene (pos, intersection)) { this->cursor.enable (); this->cursor.position (intersection.position ()); } else { this->cursor.disable (); } return ToolResponse::Redraw; } ToolResponse runCommit () { this->mesh = nullptr; return ToolResponse::None; } void runFromConfig () { const Config& config = this->self->config (); this->cursor.color (config.get ("editor/tool/cursor-color")); this->stepWidthFactor = config.get ("editor/tool/sketch-spheres/step-width-factor"); } }; DELEGATE_TOOL (ToolSketchSpheres) DELEGATE_TOOL_RUN_RENDER (ToolSketchSpheres) DELEGATE_TOOL_RUN_MOVE_EVENT (ToolSketchSpheres) DELEGATE_TOOL_RUN_PRESS_EVENT (ToolSketchSpheres) DELEGATE_TOOL_RUN_RELEASE_EVENT (ToolSketchSpheres) DELEGATE_TOOL_RUN_CURSOR_UPDATE (ToolSketchSpheres) DELEGATE_TOOL_RUN_COMMIT (ToolSketchSpheres) DELEGATE_TOOL_RUN_FROM_CONFIG (ToolSketchSpheres) ================================================ FILE: lib/src/tool/transform-mesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "cache.hpp" #include "camera.hpp" #include "dimension.hpp" #include "dynamic/mesh-intersection.hpp" #include "dynamic/mesh.hpp" #include "mesh.hpp" #include "primitive/aabox.hpp" #include "state.hpp" #include "tool/util/movement.hpp" #include "tool/util/rotation.hpp" #include "tool/util/scaling.hpp" #include "tools.hpp" #include "view/pointing-event.hpp" #include "view/shortcut.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" namespace { enum class Mode { Move, Rotate, Scale }; enum class RotationOrigin { Intersection, Center, Origin }; enum class ScalingMode { Uniform, PrimaryPlane }; } struct ToolTransformMesh::Impl { ToolTransformMesh* self; DynamicMesh* mesh; Mode mode; ToolUtilMovement movement; ToolUtilScaling scaling; ScalingMode scalingMode; glm::vec3 scalingSize; ToolUtilRotation rotation; RotationOrigin rotationOrigin; Impl (ToolTransformMesh* s) : self (s) , mesh (nullptr) , movement (s->state ().camera (), false) , scaling (s->state ().camera ()) , scalingMode (ScalingMode (s->cache ().get ("scaling-mode", int(ScalingMode::Uniform)))) , rotation (s->state ().camera ()) , rotationOrigin ( RotationOrigin (s->cache ().get ("rotation-origin", int(RotationOrigin::Center)))) { } ToolResponse runInitialize () { this->setupProperties (); this->setupToolTip (); return ToolResponse::None; } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); this->self->addMoveOnPrimaryPlaneProperties (this->movement); properties.addSeparator (); QButtonGroup& scalingModeEdit = ViewUtil::buttonGroup ( {QObject::tr ("Scale uniformly"), QObject::tr ("Scale on primary plane")}); ViewUtil::connect (scalingModeEdit, int(this->scalingMode), [this](int id) { this->scalingMode = ScalingMode (id); this->self->cache ().set ("scaling-mode", id); }); properties.add (scalingModeEdit); properties.addSeparator (); QButtonGroup& rotationOriginEdit = ViewUtil::buttonGroup ({QObject::tr ("Rotate at intersection"), QObject::tr ("Rotate at center"), QObject::tr ("Rotate at origin")}); ViewUtil::connect (rotationOriginEdit, int(this->rotationOrigin), [this](int id) { this->rotationOrigin = RotationOrigin (id); this->self->cache ().set ("rotation-origin", id); }); properties.add (rotationOriginEdit); } void setupToolTip () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Drag to move")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Shift, QObject::tr ("Drag to scale")); toolTip.add (ViewInputEvent::MouseLeft, ViewInputModifier::Ctrl, QObject::tr ("Drag to rotate")); this->self->state ().setToolTip (&toolTip); } glm::vec3 scalingVector () const { assert (this->mesh); const float minExtent = 0.01f; const glm::vec3 extent = this->scalingSize * this->mesh->scaling (); glm::vec3 scaling = glm::vec3 (1.0f); switch (this->scalingMode) { case ScalingMode::Uniform: scaling = glm::vec3 (this->scaling.factor ()); break; case ScalingMode::PrimaryPlane: switch (this->self->state ().camera ().primaryDimension ()) { case Dimension::X: scaling.z = this->scaling.factorRight (); scaling.y = this->scaling.factorUp (); break; case Dimension::Y: scaling.x = this->scaling.factorRight (); scaling.z = this->scaling.factorUp (); break; case Dimension::Z: scaling.x = this->scaling.factorRight (); scaling.y = this->scaling.factorUp (); break; } } if (scaling.x * extent.x < minExtent) { scaling.x = 1.0f; } if (scaling.y * extent.y < minExtent) { scaling.y = 1.0f; } if (scaling.z * extent.z < minExtent) { scaling.z = 1.0f; } return scaling; } ToolResponse runMoveEvent (const ViewPointingEvent& e) { if (e.leftButton () && this->mesh) { if (this->mode == Mode::Move && this->movement.move (e)) { this->mesh->translate (this->movement.delta ()); return ToolResponse::Redraw; } else if (this->mode == Mode::Scale && this->scaling.move (e)) { this->mesh->scale (this->scalingVector ()); return ToolResponse::Redraw; } else if (this->mode == Mode::Rotate && this->rotation.rotate (e)) { this->mesh->rotate (this->rotation.matrix ()); return ToolResponse::Redraw; } } return ToolResponse::None; } ToolResponse runPressEvent (const ViewPointingEvent& e) { if (e.leftButton ()) { DynamicMeshIntersection intersection; if (this->self->intersectsScene (e, intersection)) { this->mesh = &intersection.mesh (); if (e.modifiers () == Qt::NoModifier) { this->self->snapshotDynamicMeshes (); this->movement.reset (intersection.position ()); this->mode = Mode::Move; } else if (e.modifiers () == Qt::ShiftModifier) { this->self->snapshotDynamicMeshes (); const PrimAABox bounds = this->mesh->mesh ().bounds (); this->scalingSize = bounds.maximum () - bounds.minimum (); this->scaling.reset (bounds.center (), intersection.position ()); this->mesh->position (-bounds.center ()); this->mesh->normalize (); this->mesh->bufferData (); this->mesh->position (bounds.center ()); this->mode = Mode::Scale; } else if (e.modifiers () == Qt::ControlModifier) { this->self->snapshotDynamicMeshes (); switch (this->rotationOrigin) { case RotationOrigin::Intersection: this->rotation.reset (intersection.position ()); break; case RotationOrigin::Center: this->rotation.reset (this->mesh->mesh ().bounds ().center ()); break; case RotationOrigin::Origin: this->rotation.reset (glm::vec3 (0.0f)); break; } this->mode = Mode::Rotate; } } } return ToolResponse::None; } ToolResponse runReleaseEvent (const ViewPointingEvent& e) { if (e.leftButton ()) { return this->runCommit (); } return ToolResponse::None; } ToolResponse runCommit () { if (this->mesh) { this->mesh->normalize (); this->mesh->bufferData (); this->mesh = nullptr; } return ToolResponse::None; } }; DELEGATE_TOOL (ToolTransformMesh) DELEGATE_TOOL_RUN_MOVE_EVENT (ToolTransformMesh) DELEGATE_TOOL_RUN_PRESS_EVENT (ToolTransformMesh) DELEGATE_TOOL_RUN_RELEASE_EVENT (ToolTransformMesh) DELEGATE_TOOL_RUN_COMMIT (ToolTransformMesh) ================================================ FILE: lib/src/tool/trim-mesh/action.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include "dynamic/mesh.hpp" #include "primitive/plane.hpp" #include "tool/trim-mesh/action.hpp" #include "tool/trim-mesh/border.hpp" #include "util.hpp" namespace { constexpr float scalingFactor = 100.0f; constexpr float minSquareSize = 0.02f * scalingFactor; namespace Simple { enum class Location { On, Left, Right }; Location location (const glm::vec2& pos, const glm::vec2& from, const glm::vec2& to) { const float c = Util::cross (from - pos, to - pos); if (c < 0.0f) { return Location::Right; } else if (c < Util::epsilon ()) { return Location::On; } else { return Location::Left; } } bool isLeft (const glm::vec2& pos, const glm::vec2& from, const glm::vec2& to) { return location (pos, from, to) == Location::Left; } bool isRight (const glm::vec2& pos, const glm::vec2& from, const glm::vec2& to) { return location (pos, from, to) == Location::Right; } struct TwoDSquare { enum class State { Outside, Inside, Border, }; unsigned int vertexIndex; glm::uvec2 position; glm::vec2 center; float halfWidth; State state; bool visited; TwoDSquare (const glm::uvec2& p, const glm::vec2& c, float width) : vertexIndex (Util::invalidIndex ()) , position (p) , center (c) , halfWidth (width * 0.5f) , state (State::Outside) , visited (false) { } bool intersects (const glm::vec2& square1, const glm::vec2& square2, const glm::vec2& segment1, const glm::vec2& segment2) const { const glm::vec2 square = square2 - square1; const glm::vec2 segment = segment2 - segment1; const float denom = Util::cross (square, segment); if (Util::almostEqual (0.0f, denom)) { return false; } const float t1 = Util::cross (segment1 - square1, segment) / denom; const float t2 = Util::cross (segment1 - square1, square) / denom; const bool validT1 = 0.0f <= t1 && t1 <= 1.0f; const bool validT2 = 0.0f <= t2 && t2 <= 1.0f; return validT1 && validT2; } bool inside (const glm::vec2& v) const { const bool less = glm::all (glm::lessThanEqual (this->center - halfWidth, v)); const bool greater = glm::all (glm::greaterThanEqual (this->center + halfWidth, v)); return less && greater; } bool intersects (const glm::vec2& segment1, const glm::vec2& segment2) const { const glm::vec2 v1 (this->center.x - this->halfWidth, this->center.y - this->halfWidth); const glm::vec2 v2 (this->center.x - this->halfWidth, this->center.y + this->halfWidth); const glm::vec2 v3 (this->center.x + this->halfWidth, this->center.y - this->halfWidth); const glm::vec2 v4 (this->center.x + this->halfWidth, this->center.y + this->halfWidth); const bool inside = this->inside (segment1) && this->inside (segment2); const bool inter1 = this->intersects (v1, v2, segment1, segment2); const bool inter2 = this->intersects (v1, v3, segment1, segment2); const bool inter3 = this->intersects (v2, v4, segment1, segment2); const bool inter4 = this->intersects (v3, v4, segment1, segment2); return inside || inter1 || inter2 || inter3 || inter4; } }; enum class Curvature { Straight, Convex, Concave }; struct TwoDVertex { unsigned int index; glm::vec2 position; Curvature curvature; bool isEar; float angle; float distanceToPrev; float distanceToNext; TwoDVertex (unsigned int i, const glm::vec2& p) : index (i) , position (p) , curvature (Curvature::Straight) , isEar (false) , angle (0.0f) , distanceToPrev (0.0f) , distanceToNext (0.0f) { } Location location (const glm::vec2& from, const glm::vec2& to) const { return Simple::location (this->position, from, to); } bool isLeft (const glm::vec2& from, const glm::vec2& to) const { return Simple::isLeft (this->position, from, to); } bool isRight (const glm::vec2& from, const glm::vec2& to) const { return Simple::isRight (this->position, from, to); } bool isInsideTriangle (const glm::vec2& v1, const glm::vec2& v2, const glm::vec2& v3) const { return this->isLeft (v1, v2) && this->isLeft (v2, v3) && this->isLeft (v3, v1); } }; typedef std::list TwoDVertices; typedef TwoDVertices::iterator TwoDVertexRef; typedef TwoDVertices::const_iterator TwoDVertexCRef; struct TwoDPolyline; typedef std::vector TwoDPolylines; struct TwoDPolyline { TwoDVertices vertices; TwoDVertexRef maxX; bool isCCW; TwoDPolyline (const TwoDVertices& vs) : vertices (vs) , maxX (this->vertices.end ()) , isCCW (false) { } TwoDVertexRef begin () { return this->vertices.begin (); } TwoDVertexCRef begin () const { return this->vertices.begin (); } TwoDVertexRef end () { return this->vertices.end (); } TwoDVertexCRef end () const { return this->vertices.end (); } unsigned int size () const { return this->vertices.size (); } TwoDVertexRef prev (TwoDVertexRef v) { return std::prev (v == this->begin () ? this->end () : v); } TwoDVertexCRef prev (TwoDVertexCRef v) const { return std::prev (v == this->begin () ? this->end () : v); } TwoDVertexRef next (TwoDVertexRef v) { return v == std::prev (this->end ()) ? this->begin () : std::next (v); } TwoDVertexCRef next (TwoDVertexCRef v) const { return v == std::prev (this->end ()) ? this->begin () : std::next (v); } void setCurvature (TwoDVertexRef v) const { switch (v->location (this->prev (v)->position, this->next (v)->position)) { case Location::On: v->curvature = Curvature::Straight; break; case Location::Right: v->curvature = Curvature::Convex; break; case Location::Left: v->curvature = Curvature::Concave; break; } } void setIsEar (TwoDVertexRef v) const { if (v->curvature == Curvature::Convex) { const TwoDVertexCRef p = this->prev (v); const TwoDVertexCRef n = this->next (v); for (TwoDVertexCRef it = this->begin (); it != this->end (); ++it) { if (it != p && it != v && it != n) { if (it->isInsideTriangle (p->position, v->position, n->position)) { v->isEar = false; return; } } } v->isEar = true; } else { v->isEar = false; } } void setAngle (TwoDVertexRef v) { TwoDVertexRef p = this->prev (v); TwoDVertexRef n = this->next (v); v->distanceToPrev = glm::distance (v->position, p->position); v->distanceToNext = glm::distance (v->position, n->position); p->distanceToNext = v->distanceToPrev; n->distanceToPrev = v->distanceToNext; const glm::vec2 toP = (p->position - v->position) / v->distanceToPrev; const glm::vec2 toN = (n->position - v->position) / v->distanceToNext; v->angle = glm::acos (glm::clamp (glm::dot (toP, toN), -1.0f, 1.0f)); } void setProperties () { int n = 0; this->maxX = this->vertices.end (); for (TwoDVertexRef v = this->begin (); v != this->end (); ++v) { this->setCurvature (v); if (v->curvature == Curvature::Convex) { n++; } else if (v->curvature == Curvature::Concave) { n--; } if (this->maxX == this->vertices.end () || v->position.x > this->maxX->position.x) { this->maxX = v; } } assert (this->maxX != this->vertices.end ()); this->isCCW = n > 0; for (TwoDVertexRef v = this->begin (); v != this->end (); ++v) { this->setIsEar (v); this->setAngle (v); } } void removeEar (TwoDVertexRef v) { assert (v->isEar); assert (this->size () > 3); TwoDVertexRef p = this->prev (v); TwoDVertexRef n = this->next (v); this->vertices.erase (v); this->setCurvature (p); this->setCurvature (n); this->setIsEar (p); this->setIsEar (n); this->setAngle (p); this->setAngle (n); } bool updateEarCandidate (TwoDVertexCRef v, float& weight) const { assert (v->isEar); const bool nearPrev = Util::almostEqual (0.0f, v->distanceToPrev); const bool nearNext = Util::almostEqual (0.0f, v->distanceToNext); if (nearPrev || nearNext) { weight = Util::minFloat (); return true; } else { const float bestAngle = glm::cos (glm::radians (60.0f)); const float w = glm::abs (v->angle - bestAngle); if (w < weight) { weight = w; return true; } else { return false; } } } bool fillHole (DynamicMesh& mesh) { const auto addFace = [&mesh](TwoDVertexCRef a, TwoDVertexCRef b, TwoDVertexCRef c) { mesh.addFace (a->index, b->index, c->index); }; while (this->size () > 3) { TwoDVertexRef earCandidate = this->end (); float weight = Util::maxFloat (); for (TwoDVertexRef v = this->begin (); v != this->end (); ++v) { if (v->isEar && updateEarCandidate (v, weight)) { earCandidate = v; } } if (earCandidate != this->end ()) { addFace (this->prev (earCandidate), earCandidate, this->next (earCandidate)); this->removeEar (earCandidate); } else { DILAY_WARN ("Could not find ear candidate"); return false; } } assert (this->size () == 3); addFace (this->vertices.begin (), std::next (this->vertices.begin (), 1), std::next (this->vertices.begin (), 2)); return true; } bool contains (const glm::vec2& v) const { assert (this->size () >= 3); int windingNumber = 0; for (TwoDVertexCRef v0 = this->begin (); v0 != this->end (); ++v0) { TwoDVertexCRef v1 = this->next (v0); const float v0Y = v0->position.y; const float v1Y = v1->position.y; if (v0Y <= v.y && v.y < v1Y && isLeft (v, v0->position, v1->position)) { windingNumber++; } else if (v1Y <= v.y && v.y < v0Y && isRight (v, v0->position, v1->position)) { windingNumber--; } } return windingNumber != 0; } bool contains (const TwoDPolyline& poly) const { for (TwoDVertexCRef v = poly.begin (); v != poly.end (); ++v) { if (this->contains (v->position) == false) { return false; } } return true; } bool intersects (const TwoDSquare& square) const { for (TwoDVertexCRef v = this->begin (); v != this->end (); ++v) { if (square.intersects (v->position, this->next (v)->position)) { return true; } } return false; } }; struct TwoDGrid { glm::uvec2 dimension; std::vector squares; unsigned int index (unsigned int x, unsigned int y) const { assert (x < this->dimension.x); assert (y < this->dimension.y); assert ((y * this->dimension.x) + x < this->squares.size ()); return (y * this->dimension.x) + x; } unsigned int index (glm::uvec2 pos) const { return this->index (pos.x, pos.y); } TwoDSquare& advanceNeighbor (const TwoDSquare& p, const TwoDSquare& n) { const int x = int(n.position.x) - int(p.position.x); const int y = int(n.position.y) - int(p.position.y); if (x == 0 && y == 1) { return this->squares[this->index (glm::uvec2 (n.position.x + 1, n.position.y))]; } else if (x == 1 && y == 1) { return this->squares[this->index (glm::uvec2 (n.position.x, n.position.y - 1))]; } else if (x == 1 && y == 0) { return this->squares[this->index (glm::uvec2 (n.position.x, n.position.y - 1))]; } else if (x == 1 && y == -1) { return this->squares[this->index (glm::uvec2 (n.position.x - 1, n.position.y))]; } else if (x == 0 && y == -1) { return this->squares[this->index (glm::uvec2 (n.position.x - 1, n.position.y))]; } else if (x == -1 && y == -1) { return this->squares[this->index (glm::uvec2 (n.position.x, n.position.y + 1))]; } else if (x == -1 && y == 0) { return this->squares[this->index (glm::uvec2 (n.position.x, n.position.y + 1))]; } else if (x == -1 && y == 1) { return this->squares[this->index (glm::uvec2 (n.position.x + 1, n.position.y))]; } else { DILAY_IMPOSSIBLE } } TwoDGrid (const ToolTrimMeshBorder& trimBorder, TwoDPolylines& ps) { constexpr TwoDSquare::State border = TwoDSquare::State::Border; constexpr TwoDSquare::State inside = TwoDSquare::State::Inside; constexpr TwoDSquare::State outside = TwoDSquare::State::Outside; glm::vec2 min = glm::vec2 (Util::maxFloat ()); glm::vec2 max = glm::vec2 (Util::minFloat ()); float avgLength = 0.0f; unsigned int numSegments = 0; for (TwoDPolyline& p : ps) { for (TwoDVertexCRef v = p.begin (); v != p.end (); ++v) { min = glm::min (min, v->position); max = glm::max (max, v->position); numSegments++; avgLength += glm::distance (v->position, p.next (v)->position); } } avgLength = glm::max (minSquareSize, avgLength / float(numSegments)); min -= avgLength; max += avgLength; this->dimension.x = (unsigned int) (glm::ceil ((max.x - min.x) / avgLength)); this->dimension.y = (unsigned int) (glm::ceil ((max.y - min.y) / avgLength)); if (this->dimension.x == 0 || this->dimension.y == 0) { return; } this->squares.reserve (this->dimension.x * this->dimension.y); for (unsigned int y = 0; y < this->dimension.y; y++) { for (unsigned int x = 0; x < this->dimension.x; x++) { const glm::vec2 pos = min + (glm::vec2 (float(x), float(y)) * avgLength); this->squares.emplace_back (glm::uvec2 (x, y), pos, avgLength); TwoDSquare& square = this->squares.back (); unsigned int numContains = 0; for (const TwoDPolyline& p : ps) { if (p.contains (pos)) { numContains++; } } if (numContains % 2 == 1) { square.state = inside; } assert (y > 0 || square.state == outside); assert (y < this->dimension.y - 1 || square.state == outside); assert (x > 0 || square.state == outside); assert (x < this->dimension.x - 1 || square.state == outside); } } for (unsigned int y = 1; y < this->dimension.y - 1; y++) { for (unsigned int x = 1; x < this->dimension.x - 1; x++) { TwoDSquare& square = this->squares[this->index (x, y)]; if (square.state == inside) { for (const TwoDPolyline& p : ps) { if (p.intersects (square)) { square.state = outside; break; } } } } } for (unsigned int y = 1; y < this->dimension.y - 1; y++) { for (unsigned int x = 1; x < this->dimension.x - 1; x++) { if (this->squares[this->index (x, y)].state == inside) { const bool o1 = this->squares[this->index (x - 1, y)].state == outside; const bool o2 = this->squares[this->index (x + 1, y)].state == outside; const bool o3 = this->squares[this->index (x, y - 1)].state == outside; const bool o4 = this->squares[this->index (x, y + 1)].state == outside; const bool isBorder = o1 || o2 || o3 || o4; if (isBorder) { this->squares[this->index (x, y)].state = border; } } } } for (unsigned int y = 1; y < this->dimension.y - 1; y++) { for (unsigned int x = 1; x < this->dimension.x - 1; x++) { if (this->squares[this->index (x, y)].state == border) { const bool i1 = this->squares[this->index (x - 1, y)].state == inside; const bool i2 = this->squares[this->index (x + 1, y)].state == inside; const bool i3 = this->squares[this->index (x, y - 1)].state == inside; const bool i4 = this->squares[this->index (x, y + 1)].state == inside; const bool hasInsideNeighbor4 = i1 || i2 || i3 || i4; if (hasInsideNeighbor4 == false) { this->squares[this->index (x, y)].state = outside; } } } } for (unsigned int y = 1; y < this->dimension.y - 1; y++) { for (unsigned int x = 1; x < this->dimension.x - 1; x++) { TwoDSquare& square = this->squares[this->index (x, y)]; if (square.state != outside) { const glm::vec2 position2d = square.center / scalingFactor; const glm::vec3 position = trimBorder.plane ().project (position2d); const glm::vec3 normal = trimBorder.plane ().normal (); square.vertexIndex = trimBorder.mesh ().addVertex (position, normal); } } } for (unsigned int y = 1; y < this->dimension.y - 1; y++) { TwoDSquare* prev = &this->squares[this->index (0, y)]; assert (prev->state == outside); for (unsigned int x = 1; x < this->dimension.x - 1; x++) { TwoDSquare& start = this->squares[this->index (x, y)]; if (prev->state == outside && start.state == border && start.visited == false) { assert (start.vertexIndex != Util::invalidIndex ()); TwoDVertices vertices; TwoDSquare* current = &start; TwoDSquare* candidate = &this->advanceNeighbor (*current, *prev); vertices.emplace_back (current->vertexIndex, current->center); current->visited = true; while (candidate != &start) { if (candidate->state == border) { assert (candidate->vertexIndex != Util::invalidIndex ()); assert (candidate->visited == false); vertices.emplace_back (candidate->vertexIndex, candidate->center); candidate->visited = true; prev = current; current = candidate; candidate = &this->advanceNeighbor (*current, *prev); } else { prev = candidate; candidate = &this->advanceNeighbor (*current, *prev); } } assert (vertices.size () >= 3); ps.emplace_back (std::move (vertices)); } prev = &start; } } } void fill (DynamicMesh& mesh) const { constexpr TwoDSquare::State out = TwoDSquare::State::Outside; for (unsigned int y = 1; y < this->dimension.y - 2; y++) { for (unsigned int x = 1; x < this->dimension.x - 2; x++) { const TwoDSquare& s = this->squares[this->index (x, y)]; const TwoDSquare& sX = this->squares[this->index (x + 1, y)]; const TwoDSquare& sY = this->squares[this->index (x, y + 1)]; const TwoDSquare& sXY = this->squares[this->index (x + 1, y + 1)]; if (s.state != out && sX.state != out && sY.state != out && sXY.state != out) { assert (s.vertexIndex != Util::invalidIndex ()); assert (sX.vertexIndex != Util::invalidIndex ()); assert (sY.vertexIndex != Util::invalidIndex ()); assert (sXY.vertexIndex != Util::invalidIndex ()); mesh.addFace (s.vertexIndex, sX.vertexIndex, sY.vertexIndex); mesh.addFace (sXY.vertexIndex, sY.vertexIndex, sX.vertexIndex); } else if (s.state != out && sX.state == out && sY.state != out && sXY.state != out) { assert (s.vertexIndex != Util::invalidIndex ()); assert (sY.vertexIndex != Util::invalidIndex ()); assert (sXY.vertexIndex != Util::invalidIndex ()); mesh.addFace (s.vertexIndex, sXY.vertexIndex, sY.vertexIndex); } else if (s.state != out && sX.state != out && sY.state == out && sXY.state != out) { assert (s.vertexIndex != Util::invalidIndex ()); assert (sX.vertexIndex != Util::invalidIndex ()); assert (sXY.vertexIndex != Util::invalidIndex ()); mesh.addFace (s.vertexIndex, sX.vertexIndex, sXY.vertexIndex); } else if (s.state != out && sX.state != out && sY.state != out && sXY.state == out) { assert (s.vertexIndex != Util::invalidIndex ()); assert (sX.vertexIndex != Util::invalidIndex ()); assert (sY.vertexIndex != Util::invalidIndex ()); mesh.addFace (s.vertexIndex, sX.vertexIndex, sY.vertexIndex); } else if (s.state == out && sX.state != out && sY.state != out && sXY.state != out) { assert (sX.vertexIndex != Util::invalidIndex ()); assert (sY.vertexIndex != Util::invalidIndex ()); assert (sXY.vertexIndex != Util::invalidIndex ()); mesh.addFace (sXY.vertexIndex, sY.vertexIndex, sX.vertexIndex); } } } } void smooth (DynamicMesh& mesh) const { for (unsigned int i = 0; i < 3; i++) { for (unsigned int y = 1; y < this->dimension.y - 1; y++) { for (unsigned int x = 1; x < this->dimension.x - 1; x++) { const TwoDSquare& square = this->squares[this->index (x, y)]; if (square.state == TwoDSquare::State::Inside) { mesh.vertex (square.vertexIndex, mesh.averagePosition (square.vertexIndex)); } } } } } }; TwoDVertexCRef findMutuallyVisibleVertex (const TwoDPolyline& outer, const TwoDPolyline& inner) { auto getIntersection = [&outer, &inner](TwoDVertexCRef v0, glm::vec2& intersection) -> TwoDVertexCRef { TwoDVertexCRef noCandidate = outer.end (); TwoDVertexCRef v1 = outer.next (v0); TwoDVertexCRef m = inner.maxX; const glm::vec2& p0 = v0->position; const glm::vec2& p1 = v1->position; const glm::vec2& pm = m->position; if (Util::almostEqual (pm.y, p0.y) && Util::almostEqual (pm.y, p1.y)) { if (p0.x <= pm.x && p1.x <= pm.x) { return noCandidate; } else if (p0.x <= pm.x && pm.x < p1.x) { intersection = p1; return v1; } else if (p1.x <= pm.x && pm.x < p0.x) { intersection = p0; return v0; } else if (p0.x <= p1.x) { intersection = p0; return v0; } else if (p1.x <= p0.x) { intersection = p1; return v1; } else { DILAY_IMPOSSIBLE; } } else if (m->isLeft (p0, p1) && p0.y <= pm.y && pm.y <= p1.y) { if (Util::almostEqual (p0.x, p1.x)) { intersection = p0; return v0; } else { const float slope = (p1.y - p0.y) / (p1.x - p0.x); const float x = ((pm.y - p0.y) / slope) + p0.x; intersection = glm::vec2 (x, pm.y); return p0.x >= p1.x ? v0 : v1; } } else { return noCandidate; } }; auto findInitialCandidate = [&getIntersection, &outer, &inner](glm::vec2& minIntersection) -> TwoDVertexCRef { TwoDVertexCRef candidate = outer.end (); float minDistance = Util::maxFloat (); for (TwoDVertexCRef v = outer.begin (); v != outer.end (); ++v) { glm::vec2 intersection; if (getIntersection (v, intersection) != outer.end ()) { const float distance = glm::distance2 (inner.maxX->position, intersection); if (distance < minDistance) { candidate = v; minDistance = distance; minIntersection = intersection; } } } assert (candidate != outer.end ()); return candidate; }; auto findClosestContainedConcaveVertex = [&outer, &inner](const glm::vec2& intersection, TwoDVertexCRef candidate) -> TwoDVertexCRef { const glm::vec2 toCandidate = glm::normalize (candidate->position - inner.maxX->position); TwoDVertexCRef closest = outer.end (); float minDistance = Util::maxFloat (); float minAngle = Util::maxFloat (); for (TwoDVertexCRef v = outer.begin (); v != outer.end (); ++v) { if (v != candidate && v->curvature == Curvature::Concave) { if (v->isInsideTriangle (candidate->position, intersection, inner.maxX->position)) { const float d = glm::distance (v->position, inner.maxX->position); const glm::vec2 toV = (v->position - inner.maxX->position) / d; const float a = glm::acos (glm::clamp (glm::dot (toCandidate, toV), -1.0f, 1.0f)); if (a < minAngle || (Util::almostEqual (a, minAngle) && d < minDistance)) { closest = v; minAngle = a; minDistance = d; } } } } return closest; }; glm::vec2 intersection; TwoDVertexCRef candidate = findInitialCandidate (intersection); if (intersection == candidate->position) { return candidate; } else { TwoDVertexCRef r = findClosestContainedConcaveVertex (intersection, candidate); return r == outer.end () ? candidate : r; } } TwoDPolyline combine (const TwoDPolyline& outer, const TwoDPolyline& inner) { TwoDVertices vertices; TwoDVertexCRef visible = findMutuallyVisibleVertex (outer, inner); TwoDVertexCRef v = inner.maxX; vertices.push_back (*visible); do { vertices.push_back (*v); v = inner.next (v); } while (v != inner.maxX); vertices.push_back (*inner.maxX); v = visible; do { vertices.push_back (*v); v = outer.next (v); } while (v != visible); return TwoDPolyline (vertices); } void combine (TwoDPolyline& outer, TwoDPolylines& inner) { for (TwoDPolyline& i : inner) { i.setProperties (); } std::sort (inner.begin (), inner.end (), [](const TwoDPolyline& a, const TwoDPolyline& b) { return a.maxX->position.x > b.maxX->position.x; }); for (TwoDPolyline& i : inner) { outer.setProperties (); outer = combine (outer, i); } inner.clear (); } } namespace Nested { struct TwoDPolyline; typedef std::vector TwoDPolylines; struct TwoDPolyline { Simple::TwoDPolyline outer; TwoDPolylines inner; TwoDPolyline (const Simple::TwoDPolyline& o) : outer (o) { } TwoDPolyline (const Simple::TwoDPolyline& o, const TwoDPolylines& i) : outer (o) , inner (i) { } }; bool fillHole (TwoDPolylines& polys, DynamicMesh& mesh) { while (polys.empty () == false) { TwoDPolyline poly (std::move (polys.back ())); polys.pop_back (); Simple::TwoDPolylines simpleInner; for (TwoDPolyline& i : poly.inner) { for (TwoDPolyline& oi : i.inner) { polys.push_back (std::move (oi)); } i.inner.clear (); simpleInner.push_back (std::move (i.outer)); } poly.inner.clear (); Simple::combine (poly.outer, simpleInner); poly.outer.setProperties (); if (poly.outer.fillHole (mesh) == false) { return false; } } return true; } TwoDPolylines nest (const Simple::TwoDPolylines& ss) { TwoDPolylines ns; std::function insert = [&insert](TwoDPolyline& n, const Simple::TwoDPolyline& s) { if (n.outer.contains (s)) { for (TwoDPolyline& i : n.inner) { if (insert (i, s)) { return true; } } n.inner.push_back (TwoDPolyline (s)); return true; } else if (s.contains (n.outer)) { TwoDPolylines is (std::move (n.inner)); n.inner.clear (); n.inner.push_back (TwoDPolyline (std::move (n.outer), std::move (is))); n.outer = s; return true; } else { return false; } }; for (const Simple::TwoDPolyline& s : ss) { bool wasInserted = false; for (TwoDPolyline& n : ns) { if (insert (n, s)) { wasInserted = true; break; } } if (wasInserted == false) { ns.push_back (TwoDPolyline (s)); } } return ns; } } bool fillHole (ToolTrimMeshBorder& border) { border.deleteEmptyPolylines (); Simple::TwoDPolylines polylines; for (const ToolTrimMeshBorder::Polyline& p : border.polylines ()) { assert (p.size () >= 3); Simple::TwoDVertices vertices; for (unsigned int i : p) { const glm::vec2 position = border.plane ().project2d (border.mesh ().vertex (i)); vertices.emplace_back (i, scalingFactor * position); } polylines.emplace_back (vertices); } Simple::TwoDGrid grid (border, polylines); Nested::TwoDPolylines nested = Nested::nest (polylines); if (Nested::fillHole (nested, border.mesh ()) == false) { return false; } else { grid.fill (border.mesh ()); grid.smooth (border.mesh ()); } return true; } void trimVertices (const ToolTrimMeshBorder& border) { const auto isAboveBorder = [&border](unsigned int i) { const glm::vec3& p = border.mesh ().vertex (i); return border.onBorder (p) == false && border.plane ().distance (p) > 0.0f; }; std::unordered_set set; const auto addAdjacentAboveBorder = [&border, &isAboveBorder, &set](unsigned int i) { border.mesh ().forEachVertexAdjacentToVertex (i, [&isAboveBorder, &set](unsigned int a) { if (isAboveBorder (a)) { set.insert (a); } }); }; DynamicMesh& mesh = border.mesh (); for (const ToolTrimMeshBorder::Polyline& p : border.polylines ()) { for (unsigned int i : p) { addAdjacentAboveBorder (i); } } while (set.empty () == false) { const unsigned int i = *set.begin (); set.erase (set.begin ()); addAdjacentAboveBorder (i); mesh.deleteVertex (i); } } } namespace ToolTrimMeshAction { bool trimMesh (ToolTrimMeshBorder& border) { trimVertices (border); std::vector newIndices; border.mesh ().prune (&newIndices); if (newIndices.empty () == false) { border.setNewIndices (newIndices); } if (fillHole (border) && border.mesh ().pruneAndCheckConsistency ()) { return true; } else { return false; } } } ================================================ FILE: lib/src/tool/trim-mesh/action.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_TRIM_MESH_ACTION #define DILAY_TOOL_TRIM_MESH_ACTION class ToolTrimMeshBorder; namespace ToolTrimMeshAction { bool trimMesh (ToolTrimMeshBorder&); } #endif ================================================ FILE: lib/src/tool/trim-mesh/border.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "intersection.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "tool/trim-mesh/border.hpp" #include "util.hpp" namespace { typedef ToolTrimMeshBorder::Polyline Polyline; typedef ToolTrimMeshBorder::Polylines Polylines; } struct ToolTrimMeshBorder::Impl { DynamicMesh& mesh; Polylines polylines; const PrimRay edge1; const PrimRay edge2; const PrimPlane plane; Impl (DynamicMesh& m, const PrimRay& r1, const PrimRay& r2) : mesh (m) , edge1 (r1) , edge2 (r2) , plane (r1.origin (), glm::cross (r2.direction (), r1.direction ())) { } void addVertex (unsigned int index, const glm::vec3& p) { assert (this->onBorder (p)); assert (this->polylines.empty () == false); unused (p); this->polylines.back ().emplace_back (index); } void addPolyline () { this->polylines.emplace_back (); } void setNewIndices (const std::vector& newIndices) { for (Polyline& p : this->polylines) { for (unsigned int& i : p) { assert (newIndices.at (i) != Util::invalidIndex ()); i = newIndices.at (i); } } } bool isValidProjection (const glm::vec3& p) const { // assert (this->plane.onPlane (p)); // Occasionally fails due to rounding errors (?) const bool c1 = 0.0f < glm::dot (this->plane.normal (), glm::cross (p - this->edge1.origin (), this->edge1.direction ())); const bool c2 = 0.0f < glm::dot (this->plane.normal (), glm::cross (this->edge2.direction (), p - this->edge2.origin ())); return c1 && c2; } bool onBorder (const glm::vec3& p) const { if (this->edge1.onRay (p)) { return true; } else if (this->edge2.onRay (p)) { return true; } else if (this->plane.onPlane (p)) { return this->isValidProjection (p); } else { return false; } } bool intersects (const PrimRay& ray, float& t) const { if (IntersectionUtil::intersects (ray, this->plane, &t)) { return this->isValidProjection (ray.pointAt (t)); } else { return false; } } void deleteEmptyPolylines () { this->polylines.erase (std::remove_if (this->polylines.begin (), this->polylines.end (), [](Polyline& p) { return p.empty (); }), this->polylines.end ()); } bool hasVertices () const { for (const Polyline& p : this->polylines) { if (p.empty () == false) { return true; } } return false; } }; DELEGATE3_BIG2 (ToolTrimMeshBorder, DynamicMesh&, const PrimRay&, const PrimRay&) GETTER_CONST (DynamicMesh&, ToolTrimMeshBorder, mesh) GETTER_CONST (const Polylines&, ToolTrimMeshBorder, polylines) GETTER_CONST (const PrimPlane&, ToolTrimMeshBorder, plane) DELEGATE2 (void, ToolTrimMeshBorder, addVertex, unsigned int, const glm::vec3&) DELEGATE (void, ToolTrimMeshBorder, addPolyline) DELEGATE1 (void, ToolTrimMeshBorder, setNewIndices, const std::vector&) DELEGATE1_CONST (bool, ToolTrimMeshBorder, onBorder, const glm::vec3&) DELEGATE2_CONST (bool, ToolTrimMeshBorder, intersects, const PrimRay&, float&) DELEGATE (void, ToolTrimMeshBorder, deleteEmptyPolylines) DELEGATE_CONST (bool, ToolTrimMeshBorder, hasVertices) ================================================ FILE: lib/src/tool/trim-mesh/border.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_TRIM_MESH_BORDER #define DILAY_TOOL_TRIM_MESH_BORDER #include #include #include "macro.hpp" class DynamicMesh; class PrimPlane; class PrimRay; class ToolTrimMeshBorder { public: typedef std::vector Polyline; typedef std::vector Polylines; DECLARE_BIG2 (ToolTrimMeshBorder, DynamicMesh&, const PrimRay&, const PrimRay&) DynamicMesh& mesh () const; const Polylines& polylines () const; const PrimPlane& plane () const; void addVertex (unsigned int, const glm::vec3&); void addPolyline (); void setNewIndices (const std::vector&); bool onBorder (const glm::vec3&) const; bool intersects (const PrimRay&, float&) const; void deleteEmptyPolylines (); bool hasVertices () const; private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/tool/trim-mesh/split-mesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "dynamic/faces.hpp" #include "dynamic/mesh.hpp" #include "hash.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "tool/trim-mesh/border.hpp" #include "tool/trim-mesh/split-mesh.hpp" #include "util.hpp" namespace { typedef std::unordered_set BorderVertices; unsigned int splitEdge (DynamicMesh& mesh, unsigned int e1, unsigned e2, const glm::vec3& point) { unsigned int leftFace, leftVertex, rightFace, rightVertex; mesh.findAdjacent (e1, e2, leftFace, leftVertex, rightFace, rightVertex); const glm::vec3 normal = glm::normalize (mesh.vertexNormal (e1) + mesh.vertexNormal (e2)); const unsigned int newI = mesh.addVertex (point, normal); mesh.deleteFace (leftFace); mesh.deleteFace (rightFace); mesh.addFace (e1, newI, leftVertex); mesh.addFace (newI, e2, leftVertex); mesh.addFace (e2, newI, rightVertex); mesh.addFace (newI, e1, rightVertex); return newI; } unsigned int splitEdge (const ToolTrimMeshBorder& border, unsigned int e1, unsigned int e2, BorderVertices& borderVertices) { const glm::vec3 v1 (border.mesh ().vertex (e1)); const glm::vec3 v2 (border.mesh ().vertex (e2)); const PrimRay line (v1, v2 - v1); bool checkIntersection = true; if (border.onBorder (v1)) { borderVertices.insert (e1); checkIntersection = false; } if (border.onBorder (v2)) { borderVertices.insert (e2); checkIntersection = false; } if (checkIntersection) { float t; if (border.intersects (line, t) && t > 0.0f && t < glm::distance (v1, v2)) { const unsigned int i = splitEdge (border.mesh (), e1, e2, line.pointAt (t)); borderVertices.insert (i); return i; } } return Util::invalidIndex (); } void splitMesh (const ToolTrimMeshBorder& border, BorderVertices& borderVertices) { DynamicFaces faces; border.mesh ().intersects (border.plane (), faces); std::unordered_set edges; while (faces.isEmpty () == false) { edges.clear (); for (unsigned int f : faces) { unsigned int i1, i2, i3; border.mesh ().vertexIndices (f, i1, i2, i3); edges.emplace (glm::min (i1, i2), glm::max (i1, i2)); edges.emplace (glm::min (i1, i3), glm::max (i1, i3)); edges.emplace (glm::min (i2, i3), glm::max (i2, i3)); } for (const auto e : edges) { const unsigned int newI = splitEdge (border, e.first, e.second, borderVertices); if (newI != Util::invalidIndex ()) { for (unsigned int a : border.mesh ().adjacentFaces (newI)) { faces.insert (a); } } } faces.resetCommitted (); faces.commit (); } } bool checkBorderVertices (const DynamicMesh& mesh, const BorderVertices& borderVertices) { for (unsigned int v : borderVertices) { unsigned int n = 0; mesh.forEachVertexAdjacentToVertex (v, [&borderVertices, &n](unsigned int a) { BorderVertices::const_iterator bIt = borderVertices.find (a); if (bIt != borderVertices.cend ()) { n++; } }); if (n != 2) { return false; } } return true; } bool traverseAlongEdge (const ToolTrimMeshBorder& border, unsigned int e1, unsigned int e2) { unsigned int leftFace, leftVertex, rightFace, rightVertex; border.mesh ().findAdjacent (e1, e2, leftFace, leftVertex, rightFace, rightVertex); const glm::vec3& vL = border.mesh ().vertex (leftVertex); return border.onBorder (vL) ? false : border.plane ().distance (vL) > 0.0f; } void addPolylinesToBorder (ToolTrimMeshBorder& border, BorderVertices& borderVertices) { BorderVertices::iterator vIt = borderVertices.end (); while (borderVertices.empty () == false) { if (vIt == borderVertices.end ()) { border.addPolyline (); vIt = borderVertices.begin (); } bool foundNext = false; border.mesh ().forEachVertexAdjacentToVertex ( *vIt, [&border, &borderVertices, &vIt, &foundNext](unsigned int a) { if (foundNext == false) { BorderVertices::iterator bIt = borderVertices.find (a); if (bIt != borderVertices.end ()) { if (traverseAlongEdge (border, *vIt, *bIt)) { border.addVertex (*vIt, border.mesh ().vertex (*vIt)); borderVertices.erase (vIt); vIt = bIt; foundNext = true; return; } } } }); if (foundNext == false) { border.addVertex (*vIt, border.mesh ().vertex (*vIt)); borderVertices.erase (vIt); vIt = borderVertices.end (); } } } } bool ToolTrimMeshSplitMesh::splitMesh (ToolTrimMeshBorder& border) { BorderVertices borderVertices; ::splitMesh (border, borderVertices); if (borderVertices.empty ()) { return true; } else if (checkBorderVertices (border.mesh (), borderVertices)) { addPolylinesToBorder (border, borderVertices); return true; } else { DILAY_WARN ("Could not split mesh"); return false; } } ================================================ FILE: lib/src/tool/trim-mesh/split-mesh.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_TRIM_MESH_SPLIT_MESH #define DILAY_TOOL_TRIM_MESH_SPLIT_MESH class ToolTrimMeshBorder; namespace ToolTrimMeshSplitMesh { bool splitMesh (ToolTrimMeshBorder&); } #endif ================================================ FILE: lib/src/tool/trim-mesh.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "cache.hpp" #include "camera.hpp" #include "color.hpp" #include "config.hpp" #include "dynamic/mesh-intersection.hpp" #include "dynamic/mesh.hpp" #include "history.hpp" #include "primitive/ray.hpp" #include "scene.hpp" #include "state.hpp" #include "tool/trim-mesh/action.hpp" #include "tool/trim-mesh/border.hpp" #include "tool/trim-mesh/split-mesh.hpp" #include "tools.hpp" #include "view/main-window.hpp" #include "view/pointing-event.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" namespace { enum class TrimStatus { Trimmed, NotTrimmed, Failed }; enum class TrimMode { Normal, Slice, Cut }; } struct ToolTrimMesh::Impl { ToolTrimMesh* self; std::vector points; TrimMode trimMode; QSlider& widthEdit; Impl (ToolTrimMesh* s) : self (s) , trimMode (TrimMode (s->cache ().get ("trim-mode", int(TrimMode::Normal)))) , widthEdit (ViewUtil::slider (1, s->cache ().get ("trim-width", 10), 200)) { } void setupProperties () { ViewTwoColumnGrid& properties = this->self->properties (); this->widthEdit.setSingleStep (10); ViewUtil::connect (this->widthEdit, [this](int w) { this->self->cache ().set ("trim-width", w); }); QButtonGroup& trimModeEdit = ViewUtil::buttonGroup ({QObject::tr ("Normal"), QObject::tr ("Slice"), QObject::tr ("Cut")}); ViewUtil::connect (trimModeEdit, int(this->trimMode), [this](int id) { this->trimMode = TrimMode (id); this->self->cache ().set ("trim-mode", id); this->widthEdit.setEnabled (this->trimMode != TrimMode::Normal); this->setupToolTip (); }); properties.add (trimModeEdit); properties.addStacked (QObject::tr ("Width"), this->widthEdit); } void setupToolTip () { ViewToolTip toolTip; toolTip.add (ViewInputEvent::MouseLeft, QObject::tr ("Drag to trim")); if (this->widthEdit.isEnabled ()) { toolTip.add (ViewInputEvent::R, QObject::tr ("Drag to change width")); } this->self->state ().setToolTip (&toolTip); } ToolResponse runInitialize () { this->setupProperties (); this->setupToolTip (); return ToolResponse::None; } ToolResponse runMoveEvent (const ViewPointingEvent& e) { if (this->widthEdit.isEnabled () && this->self->onKeymap ('r') && e.moveEvent ()) { this->widthEdit.setValue (this->widthEdit.value () + e.delta ().x); } else if (e.rightButton () && e.modifiers () == Qt::ShiftModifier) { this->widthEdit.setValue (this->widthEdit.value () + e.delta ().x); } return this->points.empty () ? ToolResponse::None : ToolResponse::Redraw; } TrimStatus trimMesh (DynamicMesh& mesh, int offset, bool reverse) { assert (this->points.size () == 2); const glm::ivec2& p1 = reverse ? this->points[1] : this->points[0]; const glm::ivec2& p2 = reverse ? this->points[0] : this->points[1]; const float fOffset = 0.5f * float(offset); const glm::vec2 normOrth = glm::normalize (glm::vec2 (Util::orthogonalRight (p2 - p1))); const glm::ivec2 orth = glm::ivec2 (glm::ceil (normOrth * fOffset)); const PrimRay ray1 = this->self->state ().camera ().ray (p1 + orth); const PrimRay ray2 = this->self->state ().camera ().ray (p2 + orth); ToolTrimMeshBorder border (mesh, ray1, ray2); if (ToolTrimMeshSplitMesh::splitMesh (border)) { if (border.hasVertices ()) { if (ToolTrimMeshAction::trimMesh (border)) { return TrimStatus::Trimmed; } else { return TrimStatus::Failed; } } else { return TrimStatus::NotTrimmed; } } else { return TrimStatus::Failed; } } TrimStatus trimMesh (DynamicMesh& mesh) { if (this->trimMode == TrimMode::Normal) { return this->trimMesh (mesh, 0.0f, false); } else if (this->trimMode == TrimMode::Slice) { const TrimStatus status = this->trimMesh (mesh, this->widthEdit.value (), false); if (status != TrimStatus::Failed) { switch (this->trimMesh (mesh, this->widthEdit.value (), true)) { case TrimStatus::Trimmed: return TrimStatus::Trimmed; case TrimStatus::NotTrimmed: return status; case TrimStatus::Failed: return TrimStatus::Failed; default: DILAY_IMPOSSIBLE } } else { return status; } } else if (this->trimMode == TrimMode::Cut) { DynamicMesh& mesh2 = this->self->state ().scene ().newDynamicMesh (this->self->config (), mesh); switch (this->trimMesh (mesh, -this->widthEdit.value (), false)) { case TrimStatus::Failed: this->self->state ().scene ().deleteMesh (mesh2); return TrimStatus::Failed; case TrimStatus::NotTrimmed: this->self->state ().scene ().deleteMesh (mesh2); return this->trimMesh (mesh, -this->widthEdit.value (), true); case TrimStatus::Trimmed: switch (this->trimMesh (mesh2, -this->widthEdit.value (), true)) { case TrimStatus::Trimmed: return TrimStatus::Trimmed; case TrimStatus::NotTrimmed: this->self->state ().scene ().deleteMesh (mesh2); return TrimStatus::Trimmed; case TrimStatus::Failed: this->self->state ().scene ().deleteMesh (mesh2); return TrimStatus::Failed; default: DILAY_IMPOSSIBLE } default: DILAY_IMPOSSIBLE } } else { DILAY_IMPOSSIBLE } } ToolResponse runReleaseEvent (const ViewPointingEvent& e) { if (e.leftButton () == false) { return ToolResponse::None; } else { DynamicMeshIntersection intersection; if (this->self->intersectsScene (e.position (), intersection) == false) { this->points.push_back (e.position ()); } if (this->points.size () == 2) { this->self->snapshotDynamicMeshes (); TrimStatus status = TrimStatus::NotTrimmed; this->self->state ().scene ().forEachMesh ([&status, this](DynamicMesh& mesh) { if (status != TrimStatus::Failed) { const TrimStatus s = this->trimMesh (mesh); if (s != TrimStatus::NotTrimmed) { status = s; } } }); switch (status) { case TrimStatus::Trimmed: this->self->state ().scene ().deleteEmptyMeshes (); break; case TrimStatus::NotTrimmed: this->self->state ().history ().dropPastSnapshot (); break; case TrimStatus::Failed: this->self->state ().undo (); this->self->state ().history ().dropFutureSnapshot (); ViewUtil::error (this->self->state ().mainWindow (), QObject::tr ("Could not trim mesh.")); break; } this->points.clear (); } return ToolResponse::Redraw; } } void runPaint (QPainter& painter) const { const QPoint cursorPos (ViewUtil::toQPoint (this->self->cursorPosition ())); QPen pen (this->self->config ().get ("editor/on-screen-color").qColor ()); pen.setCapStyle (Qt::FlatCap); pen.setWidth (this->trimMode == TrimMode::Normal ? 2 : this->widthEdit.value ()); painter.setPen (pen); if (this->points.empty () == false) { for (unsigned int i = 0; i < this->points.size () - 1; i++) { painter.drawLine (ViewUtil::toQPoint (this->points[i + 0]), ViewUtil::toQPoint (this->points[i + 1])); } painter.drawLine (ViewUtil::toQPoint (this->points[this->points.size () - 1]), cursorPos); } } ToolResponse runCommit () { this->points.clear (); return ToolResponse::Redraw; } }; DELEGATE_TOOL (ToolTrimMesh) DELEGATE_TOOL_RUN_MOVE_EVENT (ToolTrimMesh) DELEGATE_TOOL_RUN_RELEASE_EVENT (ToolTrimMesh) DELEGATE_TOOL_RUN_PAINT (ToolTrimMesh) DELEGATE_TOOL_RUN_COMMIT (ToolTrimMesh) ================================================ FILE: lib/src/tool/util/movement.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "camera.hpp" #include "dimension.hpp" #include "intersection.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "tool/util/movement.hpp" #include "view/pointing-event.hpp" namespace { enum class MovementPlane { Camera, Primary, Free }; } struct ToolUtilMovement::Impl { const Camera& camera; MovementPlane plane; glm::vec3 planeNormal; glm::vec3 previousPosition; glm::vec3 position; Impl (const Camera& cam, bool p) : camera (cam) , previousPosition (glm::vec3 (0.0f)) , position (glm::vec3 (0.0f)) { this->onPrimaryPlane (p); } Impl (const Camera& cam, const glm::vec3& n) : camera (cam) , previousPosition (glm::vec3 (0.0f)) , position (glm::vec3 (0.0f)) { this->onFreePlane (n); } void setPlaneNormal () { if (this->plane == MovementPlane::Camera) { this->planeNormal = this->camera.toEyePoint (); } else if (this->plane == MovementPlane::Primary) { this->planeNormal = DimensionUtil::vector (this->camera.primaryDimension ()); } } bool onPrimaryPlane () const { return this->plane == MovementPlane::Primary; } void onPrimaryPlane (bool yes) { this->plane = yes ? MovementPlane::Primary : MovementPlane::Camera; this->setPlaneNormal (); } void onFreePlane (const glm::vec3& n) { this->plane = MovementPlane::Free; this->planeNormal = n; } glm::vec3 delta () const { return this->position - this->previousPosition; } bool intersects (const glm::ivec2& p, glm::vec3& i) { this->setPlaneNormal (); const PrimRay ray = this->camera.ray (p); const PrimPlane plane (this->position, this->planeNormal); float t; if (IntersectionUtil::intersects (ray, plane, &t)) { i = ray.pointAt (t); return true; } return false; } bool move (const ViewPointingEvent& e) { glm::vec3 i; if (this->intersects (e.position (), i)) { this->previousPosition = this->position; this->position = i; return true; } else { return false; } } void reset (const glm::vec3& p) { this->previousPosition = p; this->position = p; } }; DELEGATE2_BIG3 (ToolUtilMovement, const Camera&, bool) DELEGATE2_CONSTRUCTOR (ToolUtilMovement, const Camera&, const glm::vec3&) DELEGATE_CONST (bool, ToolUtilMovement, onPrimaryPlane) DELEGATE1 (void, ToolUtilMovement, onPrimaryPlane, bool) DELEGATE1 (void, ToolUtilMovement, onFreePlane, const glm::vec3&) DELEGATE_CONST (glm::vec3, ToolUtilMovement, delta) GETTER_CONST (const glm::vec3&, ToolUtilMovement, position) DELEGATE1 (bool, ToolUtilMovement, move, const ViewPointingEvent&) DELEGATE1 (void, ToolUtilMovement, reset, const glm::vec3&) ================================================ FILE: lib/src/tool/util/movement.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_UTIL_MOVEMENT #define DILAY_TOOL_UTIL_MOVEMENT #include #include "macro.hpp" class Camera; class ViewPointingEvent; class ToolUtilMovement { public: DECLARE_BIG3 (ToolUtilMovement, const Camera&, bool) ToolUtilMovement (const Camera&, const glm::vec3&); bool onPrimaryPlane () const; void onPrimaryPlane (bool); void onFreePlane (const glm::vec3&); glm::vec3 delta () const; const glm::vec3& position () const; bool move (const ViewPointingEvent&); void reset (const glm::vec3&); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/tool/util/rotation.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "camera.hpp" #include "tool/util/rotation.hpp" #include "util.hpp" #include "view/pointing-event.hpp" struct ToolUtilRotation::Impl { const Camera& camera; glm::vec3 origin; glm::vec3 axis; glm::vec2 position; glm::vec2 direction; float angle; Impl (const Camera& cam) : camera (cam) { } glm::mat4x4 matrix () const { return Util::rotation (this->origin, this->axis, this->angle); } bool rotate (const ViewPointingEvent& e) { const glm::vec2 fPoint = glm::vec2 (e.position ()); const float threshold = 10.0f; if (glm::distance (this->position, fPoint) < threshold) { this->direction = glm::vec2 (0.0f); return false; } else if (this->direction == glm::vec2 (0.0f)) { this->direction = glm::normalize (fPoint - this->position); return false; } else { const glm::vec2 newDirection = glm::normalize (fPoint - this->position); const float dot = glm::dot (this->direction, newDirection); if (Util::almostEqual (dot, 1.0f)) { this->angle = 0.0f; } else if (Util::almostEqual (dot, -1.0f)) { this->angle = glm::pi (); } else { this->angle = glm::acos (dot); if (Util::cross (this->direction, newDirection) > 0.0f) { this->angle = (2.0f * glm::pi ()) - this->angle; } } this->direction = newDirection; return true; } } void reset (const glm::vec3& o) { this->origin = o; this->axis = this->camera.toEyePoint (); this->position = this->camera.fromWorld (o, glm::mat4x4 (1.0f), false); this->direction = glm::vec2 (0.0f); } void reset (const glm::vec3& o, const glm::vec3& a) { this->origin = o; this->axis = glm::normalize (a); this->position = this->camera.fromWorld (o, glm::mat4x4 (1.0f), false); this->direction = glm::vec2 (0.0f); } }; DELEGATE1_BIG3 (ToolUtilRotation, const Camera&) GETTER_CONST (const glm::vec3&, ToolUtilRotation, axis) GETTER_CONST (float, ToolUtilRotation, angle) DELEGATE_CONST (glm::mat4x4, ToolUtilRotation, matrix) DELEGATE1 (bool, ToolUtilRotation, rotate, const ViewPointingEvent&) DELEGATE1 (void, ToolUtilRotation, reset, const glm::vec3&) DELEGATE2 (void, ToolUtilRotation, reset, const glm::vec3&, const glm::vec3&) ================================================ FILE: lib/src/tool/util/rotation.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_UTIL_ROTATION #define DILAY_TOOL_UTIL_ROTATION #include #include #include "macro.hpp" class Camera; class ViewPointingEvent; class ToolUtilRotation { public: DECLARE_BIG3 (ToolUtilRotation, const Camera&) const glm::vec3& axis () const; float angle () const; glm::mat4x4 matrix () const; bool rotate (const ViewPointingEvent&); void reset (const glm::vec3&); void reset (const glm::vec3&, const glm::vec3&); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/tool/util/scaling.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "camera.hpp" #include "intersection.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "tool/util/scaling.hpp" #include "util.hpp" #include "view/pointing-event.hpp" struct ToolUtilScaling::Impl { const Camera& camera; std::unique_ptr plane; glm::vec3 previousPosition; glm::vec3 position; Impl (const Camera& cam) : camera (cam) { } float factor (float previousDistance, float distance) const { if (Util::almostEqual (previousDistance, 0.0f)) { return 1.0f; } else { return glm::clamp (distance / previousDistance, 0.75f, 1.25f); } } float factor () const { assert (this->plane); const float pd = glm::distance (this->previousPosition, this->plane->point ()); const float d = glm::distance (this->position, this->plane->point ()); return this->factor (pd, d); } float factorRight () const { const glm::vec3 prevDelta = this->previousPosition - this->plane->point (); const glm::vec3 delta = this->position - this->plane->point (); const glm::vec3& right = this->camera.right (); return this->factor (glm::dot (right, prevDelta), glm::dot (right, delta)); } float factorUp () const { const glm::vec3 prevDelta = this->previousPosition - this->plane->point (); const glm::vec3 delta = this->position - this->plane->point (); const glm::vec3& up = this->camera.realUp (); return this->factor (glm::dot (up, prevDelta), glm::dot (up, delta)); } bool intersects (const glm::ivec2& p, glm::vec3& i) const { assert (this->plane); const PrimRay ray = this->camera.ray (p); float t; if (IntersectionUtil::intersects (ray, *this->plane, &t)) { i = ray.pointAt (t); return true; } return false; } bool move (const ViewPointingEvent& e) { glm::vec3 p; if (this->plane && this->intersects (e.position (), p)) { this->previousPosition = this->position; this->position = p; return true; } else { return false; } } void reset (const glm::vec3& origin, const glm::vec3& reference) { this->plane = std::make_unique (origin, this->camera.toEyePoint ()); const PrimRay ray (this->camera.position (), glm::normalize (reference - this->camera.position ())); float t; if (IntersectionUtil::intersects (ray, *this->plane, &t)) { this->previousPosition = ray.pointAt (t); this->position = ray.pointAt (t); } else { this->plane.reset (); } } }; DELEGATE1_BIG3 (ToolUtilScaling, const Camera&) DELEGATE_CONST (float, ToolUtilScaling, factor) DELEGATE_CONST (float, ToolUtilScaling, factorRight) DELEGATE_CONST (float, ToolUtilScaling, factorUp) DELEGATE1 (bool, ToolUtilScaling, move, const ViewPointingEvent&) DELEGATE2 (void, ToolUtilScaling, reset, const glm::vec3&, const glm::vec3&) ================================================ FILE: lib/src/tool/util/scaling.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_UTIL_SCALING #define DILAY_TOOL_UTIL_SCALING #include #include "macro.hpp" class Camera; class ViewPointingEvent; class ToolUtilScaling { public: DECLARE_BIG3 (ToolUtilScaling, const Camera&) float factor () const; float factorRight () const; float factorUp () const; bool move (const ViewPointingEvent&); void reset (const glm::vec3&, const glm::vec3&); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/tool/util/step.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "tool/util/step.hpp" #include "util.hpp" namespace { const glm::vec3 invalidPosition (Util::maxFloat ()); } struct ToolUtilStep::Impl { glm::vec3 position; float stepWidth; Impl () : position (invalidPosition) , stepWidth (0.0f) { } void step (const glm::vec3& to, const std::function& f) { assert (this->position != invalidPosition); assert (this->stepWidth >= 0.0f); do { const glm::vec3 direction = to - this->position; const float distance = glm::length (direction); if (distance < this->stepWidth) { break; } this->position += direction * (this->stepWidth / distance); } while (f (this->position)); } }; DELEGATE_BIG3 (ToolUtilStep) GETTER_CONST (const glm::vec3&, ToolUtilStep, position) SETTER (const glm::vec3&, ToolUtilStep, position) SETTER (float, ToolUtilStep, stepWidth) DELEGATE2 (void, ToolUtilStep, step, const glm::vec3&, const std::function&) ================================================ FILE: lib/src/tool/util/step.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL_UTIL_STEP #define DILAY_TOOL_UTIL_STEP #include #include #include "macro.hpp" class ToolUtilStep { public: DECLARE_BIG3 (ToolUtilStep) const glm::vec3& position () const; void position (const glm::vec3&); void stepWidth (float); void step (const glm::vec3&, const std::function&); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/tool.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "cache.hpp" #include "camera.hpp" #include "config.hpp" #include "dimension.hpp" #include "dynamic/mesh.hpp" #include "history.hpp" #include "intersection.hpp" #include "mesh.hpp" #include "mirror.hpp" #include "primitive/ray.hpp" #include "primitive/triangle.hpp" #include "scene.hpp" #include "sketch/mesh.hpp" #include "state.hpp" #include "tool.hpp" #include "tool/util/movement.hpp" #include "view/gl-widget.hpp" #include "view/key-event.hpp" #include "view/main-window.hpp" #include "view/pointing-event.hpp" #include "view/tool-pane.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct Tool::Impl { Tool* self; State& state; CacheProxy _cache; Maybe _mirror; QCheckBox* mirrorCheckBox; QPushButton* mirrorSyncButton; glm::ivec2 prevPointingEventPosition; std::array keymap; Impl (Tool* s, State& st, const char* cacheKey) : self (s) , state (st) , _cache (this->cache (cacheKey)) , mirrorCheckBox (nullptr) , mirrorSyncButton (nullptr) { this->keymap.fill (false); } ToolResponse initialize () { this->fromConfig (); #ifndef NDEBUG const ToolResponse response = this->self->runInitialize (); assert (bool(this->_mirror) == false || (this->mirrorCheckBox && this->mirrorSyncButton)); return response; #else return this->self->runInitialize (); #endif } void render () const { this->self->runRender (); if (this->mirrorEnabled () && this->config ().get ("editor/tool/sculpt/mirror/render")) { this->_mirror->render (this->state.camera ()); } } void paint (QPainter& painter) const { this->self->runPaint (painter); } void keyEvent (const ViewKeyEvent& e) { const int index = int(e.key ()) - int(Qt::Key_A); if (index >= 0 && size_t (index) < this->keymap.size ()) { this->keymap[index] = e.pressEvent (); } } ToolResponse pointingEvent (const ViewPointingEvent& e) { if (e.pressEvent ()) { this->prevPointingEventPosition = e.position (); } const ViewPointingEvent eWithDelta (e, this->prevPointingEventPosition); ToolResponse response = this->self->runPointingEvent (eWithDelta); if (e.releaseEvent ()) { this->state.scene ().sanitizeMeshes (); } this->prevPointingEventPosition = e.position (); return response; } ToolResponse cursorUpdate (const glm::ivec2& pos) { return this->self->runCursorUpdate (pos); } ToolResponse commit () { return this->self->runCommit (); } void fromConfig () { if (this->_mirror) { this->_mirror->fromConfig (this->config ()); } this->self->runFromConfig (); } void updateGlWidget () { this->state.mainWindow ().glWidget ().update (); } ViewTwoColumnGrid& properties () const { return this->state.mainWindow ().toolPane ().properties (); } Config& config () const { return this->state.config (); } CacheProxy& cache () { return this->_cache; } CacheProxy cache (const char* key) const { return CacheProxy (this->state.cache (), "editor/tool/" + std::string (key) + "/"); } glm::ivec2 cursorPosition () { return this->state.mainWindow ().glWidget ().cursorPosition (); } void snapshotAll () { this->state.history ().snapshotAll (this->state.scene ()); } void snapshotDynamicMeshes () { this->state.history ().snapshotDynamicMeshes (this->state.scene ()); } void snapshotSketchMeshes () { this->state.history ().snapshotSketchMeshes (this->state.scene ()); } bool intersectsRecentDynamicMesh (const PrimRay& ray, Intersection& intersection) const { assert (this->state.history ().hasRecentDynamicMesh ()); this->state.history ().forEachRecentDynamicMesh ( [&ray, &intersection](const DynamicMesh& mesh) { mesh.intersects (ray, intersection); }); return intersection.isIntersection (); } bool intersectsRecentDynamicMesh (const glm::ivec2& pos, Intersection& intersection) const { return this->intersectsRecentDynamicMesh (this->state.camera ().ray (pos), intersection); } void supportsMirror () { assert (bool(this->_mirror) == false); this->_mirror = Maybe::make (this->config (), Dimension::X); this->mirrorDefaultPosition (); } bool mirrorEnabled () const { return this->_mirror && this->state.cache ().get ("editor/tool/mirror", true); } void mirrorPosition (const glm::vec3& p) { assert (this->_mirror); this->_mirror->position (p); } void mirrorDefaultPosition () { switch (this->state.mainWindow ().toolPane ().selection ()) { case ViewToolPaneSelection::Sculpt: this->mirrorPosition (glm::vec3 (0.0f)); break; case ViewToolPaneSelection::Sketch: if (this->state.scene ().numSketchMeshes () == 1) { this->state.scene ().forEachMesh ([this](const SketchMesh& mesh) { this->mirrorPosition (mesh.tree ().root ().data ().center ()); }); } else { this->mirrorPosition (glm::vec3 (0.0f)); } break; } } const Mirror& mirror () const { assert (this->mirrorEnabled ()); return *this->_mirror; } const Dimension* mirrorDimension () const { const static Dimension d = Dimension::X; return this->mirrorEnabled () ? &d : nullptr; } void mirrorDynamicMeshes () { assert (this->mirrorEnabled ()); this->snapshotDynamicMeshes (); this->state.scene ().forEachMesh ([this](DynamicMesh& mesh) { if (mesh.mirrorPositive (this->mirror ().plane ()) == false) { ViewUtil::error (this->state.mainWindow (), QObject::tr ("Could not mirror mesh.")); } mesh.bufferData (); }); } void mirrorSketchMeshes () { assert (this->mirrorEnabled ()); this->snapshotSketchMeshes (); this->state.scene ().forEachMesh ( [this](SketchMesh& mesh) { mesh.mirrorPositive (*this->mirrorDimension ()); }); } void addMirrorProperties () { assert (this->_mirror); this->mirrorCheckBox = &ViewUtil::checkBox (QObject::tr ("Mirror"), this->mirrorEnabled ()); ViewUtil::connect (*this->mirrorCheckBox, [this](bool m) { this->state.cache ().set ("editor/tool/mirror", m); this->mirrorSyncButton->setEnabled (m); this->updateGlWidget (); }); this->mirrorSyncButton = &ViewUtil::pushButton (QObject::tr ("Sync")); ViewUtil::connect (*this->mirrorSyncButton, [this]() { switch (this->state.mainWindow ().toolPane ().selection ()) { case ViewToolPaneSelection::Sculpt: this->mirrorDynamicMeshes (); break; case ViewToolPaneSelection::Sketch: this->mirrorSketchMeshes (); break; } this->updateGlWidget (); }); this->mirrorSyncButton->setEnabled (this->mirrorEnabled ()); this->properties ().add (*this->mirrorCheckBox, *this->mirrorSyncButton); } void enableMirrorProperties (bool state) { assert (this->mirrorCheckBox); assert (this->mirrorSyncButton); this->mirrorCheckBox->setEnabled (state); this->mirrorSyncButton->setEnabled (state); } void addMoveOnPrimaryPlaneProperties (ToolUtilMovement& movement) { const bool init = this->cache ().get ("move-on-primary-plane", movement.onPrimaryPlane ()); movement.onPrimaryPlane (init); QCheckBox& edit = ViewUtil::checkBox (QObject::tr ("Move on primary plane"), init); ViewUtil::connect (edit, [this, &movement](bool p) { movement.onPrimaryPlane (p); this->cache ().set ("move-on-primary-plane", p); }); this->properties ().add (edit); } bool onKeymap (char c) const { const int index = int(c) - int('a'); if (index >= 0 && size_t (index) < this->keymap.size ()) { return this->keymap[index]; } else { return false; } } template bool intersectsScene (const PrimRay& ray, T& intersection, Ts... args) { return this->state.scene ().intersects (ray, intersection, std::forward (args)...); } template bool intersectsScene (const glm::ivec2& pos, T& intersection, Ts... args) { return this->intersectsScene (this->state.camera ().ray (pos), intersection, std::forward (args)...); } template bool intersectsScene (const ViewPointingEvent& e, T& intersection, Ts... args) { return this->intersectsScene (e.position (), intersection, std::forward (args)...); } ToolResponse runPointingEvent (const ViewPointingEvent& e) { if (e.pressEvent ()) { return this->self->runPressEvent (e); } else if (e.moveEvent ()) { return this->self->runMoveEvent (e); } else if (e.releaseEvent ()) { return this->self->runReleaseEvent (e); } return ToolResponse::None; } }; DELEGATE2_BIG3_SELF (Tool, State&, const char*) DELEGATE (ToolResponse, Tool, initialize) DELEGATE_CONST (void, Tool, render) DELEGATE1_CONST (void, Tool, paint, QPainter&) DELEGATE1 (void, Tool, keyEvent, const ViewKeyEvent&) DELEGATE1 (ToolResponse, Tool, pointingEvent, const ViewPointingEvent&) DELEGATE1 (ToolResponse, Tool, cursorUpdate, const glm::ivec2&) DELEGATE (ToolResponse, Tool, commit) DELEGATE (void, Tool, fromConfig) GETTER_CONST (State&, Tool, state) DELEGATE (void, Tool, updateGlWidget) DELEGATE_CONST (ViewTwoColumnGrid&, Tool, properties) DELEGATE_CONST (Config&, Tool, config) DELEGATE (CacheProxy&, Tool, cache) DELEGATE1_CONST (CacheProxy, Tool, cache, const char*) DELEGATE_CONST (glm::ivec2, Tool, cursorPosition) DELEGATE (void, Tool, snapshotAll) DELEGATE (void, Tool, snapshotDynamicMeshes) DELEGATE (void, Tool, snapshotSketchMeshes) DELEGATE2_CONST (bool, Tool, intersectsRecentDynamicMesh, const PrimRay&, Intersection&) DELEGATE2_CONST (bool, Tool, intersectsRecentDynamicMesh, const glm::ivec2&, Intersection&) DELEGATE (void, Tool, supportsMirror) DELEGATE_CONST (bool, Tool, mirrorEnabled) DELEGATE1 (void, Tool, mirrorPosition, const glm::vec3&) DELEGATE (void, Tool, mirrorDefaultPosition) DELEGATE_CONST (const Mirror&, Tool, mirror) DELEGATE_CONST (const Dimension*, Tool, mirrorDimension) DELEGATE (void, Tool, addMirrorProperties) DELEGATE1 (void, Tool, enableMirrorProperties, bool) DELEGATE1 (void, Tool, addMoveOnPrimaryPlaneProperties, ToolUtilMovement&) DELEGATE1_CONST (bool, Tool, onKeymap, char) DELEGATE1 (ToolResponse, Tool, runPointingEvent, const ViewPointingEvent&) template bool Tool::intersectsScene (const PrimRay& ray, T& intersection, Ts... args) { return this->impl->intersectsScene (ray, intersection, std::forward (args)...); } template bool Tool::intersectsScene (const glm::ivec2& pos, T& intersection, Ts... args) { return this->impl->intersectsScene (pos, intersection, std::forward (args)...); } template bool Tool::intersectsScene (const ViewPointingEvent& e, T& intersection, Ts... args) { return this->impl->intersectsScene (e, intersection, std::forward (args)...); } #define TOOL_INTERSECTS_SCENE(...) \ template bool Tool::intersectsScene (const PrimRay&, __VA_ARGS__); \ template bool Tool::intersectsScene (const glm::ivec2&, __VA_ARGS__); \ template bool Tool::intersectsScene (const ViewPointingEvent&, __VA_ARGS__); TOOL_INTERSECTS_SCENE (DynamicMeshIntersection&) TOOL_INTERSECTS_SCENE (SketchNodeIntersection&) TOOL_INTERSECTS_SCENE (SketchNodeIntersection&, const SketchNode*) TOOL_INTERSECTS_SCENE (SketchBoneIntersection&) TOOL_INTERSECTS_SCENE (SketchMeshIntersection&) TOOL_INTERSECTS_SCENE (SketchMeshIntersection&, unsigned int) TOOL_INTERSECTS_SCENE (SketchPathIntersection&) TOOL_INTERSECTS_SCENE (Intersection&) #undef TOOL_INTERSECTS_SCENE ================================================ FILE: lib/src/tool.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOL #define DILAY_TOOL #include #include "macro.hpp" #include "sketch/fwd.hpp" #include "tool/key.hpp" class CacheProxy; class Config; enum class Dimension; class Intersection; class Mirror; class PrimRay; class QPainter; class QWidget; class State; class ToolUtilMovement; class ViewKeyEvent; class ViewPointingEvent; class ViewToolTip; class ViewTwoColumnGrid; enum class ToolResponse { None, Terminate, Redraw }; class Tool { public: DECLARE_BIG3_VIRTUAL (Tool, State&, const char*) virtual ToolKey getKey () const = 0; ToolResponse initialize (); void render () const; void paint (QPainter&) const; void keyEvent (const ViewKeyEvent&); ToolResponse pointingEvent (const ViewPointingEvent&); ToolResponse cursorUpdate (const glm::ivec2&); ToolResponse commit (); void fromConfig (); protected: State& state () const; void updateGlWidget (); ViewTwoColumnGrid& properties () const; Config& config () const; CacheProxy& cache (); CacheProxy cache (const char*) const; glm::ivec2 cursorPosition () const; void snapshotAll (); void snapshotDynamicMeshes (); void snapshotSketchMeshes (); bool intersectsRecentDynamicMesh (const PrimRay&, Intersection&) const; bool intersectsRecentDynamicMesh (const glm::ivec2&, Intersection&) const; void supportsMirror (); bool mirrorEnabled () const; void mirrorPosition (const glm::vec3&); void mirrorDefaultPosition (); const Mirror& mirror () const; const Dimension* mirrorDimension () const; void addMirrorProperties (); void enableMirrorProperties (bool = true); void addMoveOnPrimaryPlaneProperties (ToolUtilMovement&); bool onKeymap (char) const; template bool intersectsScene (const PrimRay&, T&, Ts...); template bool intersectsScene (const glm::ivec2&, T&, Ts...); template bool intersectsScene (const ViewPointingEvent&, T&, Ts...); private: IMPLEMENTATION virtual ToolResponse runInitialize () = 0; virtual void runRender () const {} virtual void runPaint (QPainter&) const {} virtual ToolResponse runPointingEvent (const ViewPointingEvent&); virtual ToolResponse runPressEvent (const ViewPointingEvent&) { return ToolResponse::None; } virtual ToolResponse runMoveEvent (const ViewPointingEvent&) { return ToolResponse::None; } virtual ToolResponse runReleaseEvent (const ViewPointingEvent&) { return ToolResponse::None; } virtual ToolResponse runCursorUpdate (const glm::ivec2&) { return ToolResponse::None; } virtual ToolResponse runCommit () { return ToolResponse::None; } virtual void runFromConfig () {} }; #define DECLARE_TOOL(keyName, otherMethods) \ class Tool##keyName : public Tool \ { \ public: \ DECLARE_BIG2 (Tool##keyName, State&) \ \ ToolKey getKey () const { return ToolKey::keyName; } \ \ private: \ IMPLEMENTATION \ ToolResponse runInitialize (); \ otherMethods \ }; #define DECLARE_TOOL_RUN_RENDER void runRender () const; #define DECLARE_TOOL_RUN_PAINT void runPaint (QPainter&) const; #define DECLARE_TOOL_RUN_POINTING_EVENT ToolResponse runPointingEvent (const ViewPointingEvent&); #define DECLARE_TOOL_RUN_PRESS_EVENT ToolResponse runPressEvent (const ViewPointingEvent&); #define DECLARE_TOOL_RUN_MOVE_EVENT ToolResponse runMoveEvent (const ViewPointingEvent&); #define DECLARE_TOOL_RUN_RELEASE_EVENT ToolResponse runReleaseEvent (const ViewPointingEvent&); #define DECLARE_TOOL_RUN_CURSOR_UPDATE ToolResponse runCursorUpdate (const glm::ivec2&); #define DECLARE_TOOL_RUN_COMMIT ToolResponse runCommit (); #define DECLARE_TOOL_RUN_FROM_CONFIG void runFromConfig (); #define DELEGATE_TOOL(name) \ DELEGATE_BIG2_BASE (name, (State & s), (this), Tool, (s, #name)) \ DELEGATE (ToolResponse, name, runInitialize) #define DELEGATE_TOOL_RUN_RENDER(n) DELEGATE_CONST (void, n, runRender) #define DELEGATE_TOOL_RUN_PAINT(n) DELEGATE1_CONST (void, n, runPaint, QPainter&) #define DELEGATE_TOOL_RUN_POINTING_EVENT(n) \ DELEGATE1 (ToolResponse, n, runPointingEvent, const ViewPointingEvent&) #define DELEGATE_TOOL_RUN_PRESS_EVENT(n) \ DELEGATE1 (ToolResponse, n, runPressEvent, const ViewPointingEvent&) #define DELEGATE_TOOL_RUN_MOVE_EVENT(n) \ DELEGATE1 (ToolResponse, n, runMoveEvent, const ViewPointingEvent&) #define DELEGATE_TOOL_RUN_RELEASE_EVENT(n) \ DELEGATE1 (ToolResponse, n, runReleaseEvent, const ViewPointingEvent&) #define DELEGATE_TOOL_RUN_CURSOR_UPDATE(n) \ DELEGATE1 (ToolResponse, n, runCursorUpdate, const glm::ivec2&) #define DELEGATE_TOOL_RUN_COMMIT(n) DELEGATE (ToolResponse, n, runCommit) #define DELEGATE_TOOL_RUN_FROM_CONFIG(n) DELEGATE (void, n, runFromConfig) #endif ================================================ FILE: lib/src/tools.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TOOLS #define DILAY_TOOLS #include "tool.hpp" #include "tool/move-camera.hpp" #include "tool/sculpt.hpp" DECLARE_TOOL (TransformMesh, DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_PRESS_EVENT DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_COMMIT) DECLARE_TOOL (DeleteMesh, DECLARE_TOOL_RUN_RELEASE_EVENT) DECLARE_TOOL (NewMesh, DECLARE_TOOL_RUN_RENDER DECLARE_TOOL_RUN_COMMIT) DECLARE_TOOL_SCULPT (SculptDraw) DECLARE_TOOL_SCULPT (SculptGrab) DECLARE_TOOL_SCULPT (SculptSmooth) DECLARE_TOOL_SCULPT (SculptFlatten) DECLARE_TOOL_SCULPT (SculptCrease) DECLARE_TOOL_SCULPT (SculptPinch) DECLARE_TOOL_SCULPT (SculptReduce) DECLARE_TOOL (EditSketch, DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_PRESS_EVENT DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_COMMIT) DECLARE_TOOL (DeleteSketch, DECLARE_TOOL_RUN_RELEASE_EVENT) DECLARE_TOOL (ConvertSketch, DECLARE_TOOL_RUN_RELEASE_EVENT) DECLARE_TOOL (SketchSpheres, DECLARE_TOOL_RUN_RENDER DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_PRESS_EVENT DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_CURSOR_UPDATE DECLARE_TOOL_RUN_COMMIT DECLARE_TOOL_RUN_FROM_CONFIG) DECLARE_TOOL (TrimMesh, DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_PAINT DECLARE_TOOL_RUN_COMMIT) DECLARE_TOOL (Remesh, DECLARE_TOOL_RUN_MOVE_EVENT DECLARE_TOOL_RUN_PRESS_EVENT DECLARE_TOOL_RUN_RELEASE_EVENT DECLARE_TOOL_RUN_PAINT DECLARE_TOOL_RUN_COMMIT) #endif ================================================ FILE: lib/src/tree.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TREE #define DILAY_TREE #include #include "maybe.hpp" #include "util.hpp" template class TreeNode { public: TreeNode (const T& d, TreeNode* p = nullptr) : _data (d) , _parent (p) { } TreeNode (T&& d, TreeNode* p = nullptr) : _data (std::move (d)) , _parent (p) { } TreeNode (const TreeNode& o) : _data (o._data) , _parent (nullptr) , _children (o._children) { this->forEachChild ([this](TreeNode& c) { c._parent = this; }); } template static TreeNode make (Args&&... args) { return TreeNode (T (std::forward (args)...)); } T& data () { return this->_data; } const T& data () const { return this->_data; } void data (const T& d) { this->_data = d; } TreeNode* parent () const { return this->_parent; } template TreeNode& emplaceChild (Args&&... args) { this->_children.emplace_back (make (std::forward (args)...)); this->_children.back ()._parent = this; return this->_children.back (); } TreeNode& addChild (const TreeNode& node) { this->_children.emplace_back (node); this->_children.back ()._parent = this; return this->_children.back (); } void deleteChild (TreeNode& child) { for (auto it = this->_children.begin (); it != this->_children.end (); ++it) { if (&*it == &child) { this->_children.erase (it); return; } } DILAY_IMPOSSIBLE } void forEachChild (const std::function& f) { for (TreeNode& c : this->_children) { f (c); } } void forEachConstChild (const std::function& f) const { for (const TreeNode& c : this->_children) { f (c); } } void forEachNode (const std::function& f) { f (*this); this->forEachChild ([&f](TreeNode& c) { c.forEachNode (f); }); } void forEachConstNode (const std::function& f) const { f (*this); this->forEachConstChild ([&f](const TreeNode& c) { c.forEachConstNode (f); }); } TreeNode& lastChild () { assert (this->numChildren () > 0); return this->_children.back (); } const TreeNode& lastChild () const { assert (this->numChildren () > 0); return this->_children.back (); } unsigned int numChildren () const { return this->_children.size (); } unsigned int numNodes () const { unsigned int n = 0; this->forEachConstNode ([&n](const TreeNode&) { n++; }); return n; } void deleteChildIf (const std::function& f) { for (auto it = this->_children.begin (); it != this->_children.end ();) { if (f (*it)) { it = this->_children.erase (it); } else { ++it; } } } private: T _data; TreeNode* _parent; std::list _children; }; template class Tree { public: bool hasRoot () const { return bool(this->_root); } TreeNode& root () { assert (this->hasRoot ()); return *this->_root; } const TreeNode& root () const { assert (this->hasRoot ()); return *this->_root; } template TreeNode& emplaceRoot (Args&&... args) { this->_root = Maybe>::make (TreeNode::make (std::forward (args)...)); return this->root (); } void reset () { this->_root.reset (); } void rebalance (TreeNode& node) { const std::function&, TreeNode&)> go = [&go](const auto& child, auto& rebalancedChild) { if (child.parent ()) { const auto& parent = *child.parent (); auto& rebalancedParent = rebalancedChild.emplaceChild (parent.data ()); parent.forEachConstChild ([&rebalancedParent, &child](const auto& c) { if (&c != &child) { rebalancedParent.addChild (c); } }); go (parent, rebalancedParent); } }; TreeNode& newRoot (node); go (node, newRoot); this->_root = std::move (newRoot); } Tree split (TreeNode& node) { Tree tree; tree._root = node; if (node.parent ()) { node.parent ()->deleteChild (node); } else if (&node == this->_root.get ()) { this->reset (); } return tree; } private: Maybe> _root; }; #endif ================================================ FILE: lib/src/util.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include "util.hpp" namespace { template bool colinearUnitT (const T& v1, const T& v2) { return Util::almostEqual (glm::abs (glm::dot (v1, v2)), 1.0f); } template bool colinearT (const T& v1, const T& v2) { return colinearUnitT (glm::normalize (v1), glm::normalize (v2)); } } glm::vec3 Util::midpoint (const glm::vec3& a, const glm::vec3& b) { return (a + b) * (glm::vec3 (0.5f)); } glm::vec3 Util::transformPosition (const glm::mat4x4& m, const glm::vec3& v) { return glm::vec3 (m * glm::vec4 (v, 1.0f)); } glm::vec3 Util::transformDirection (const glm::mat4x4& m, const glm::vec3& v) { return glm::vec3 (m * glm::vec4 (v, 0.0f)); } glm::vec3 Util::orthogonal (const glm::vec3& v) { return glm::abs (v.x) > glm::abs (v.z) ? glm::vec3 (-v.y, v.x, 0.0f) : glm::vec3 (0.0f, -v.z, v.y); } glm::ivec2 Util::orthogonalRight (const glm::ivec2& v) { return glm::ivec2 (v.y, -v.x); } glm::mat4x4 Util::rotation (const glm::vec3& origin, const glm::vec3& axis, float angle) { const glm::mat4x4 translate = glm::translate (glm::mat4x4 (1.0f), origin); const glm::mat4x4 rotate = glm::rotate (translate, angle, axis); return glm::translate (rotate, -origin); } bool Util::colinear (const glm::vec2& v1, const glm::vec2& v2) { return colinearT (v1, v2); } bool Util::colinear (const glm::vec3& v1, const glm::vec3& v2) { return colinearT (v1, v2); } bool Util::colinearUnit (const glm::vec2& v1, const glm::vec2& v2) { return colinearUnitT (v1, v2); } bool Util::colinearUnit (const glm::vec3& v1, const glm::vec3& v2) { return colinearUnitT (v1, v2); } float Util::smoothStep (const glm::vec3& v, const glm::vec3& center, float innerRadius, float radius) { assert (innerRadius <= radius); const float d = glm::distance (v, center); if (radius - innerRadius < Util::epsilon ()) { return d > radius ? 0.0f : 1.0f; } else { const float x = glm::clamp ((radius - d) / (radius - innerRadius), 0.0f, 1.0f); return x * x * x * (x * (x * 6.0f - 15.0f) + 10.0f); } } float Util::linearStep (const glm::vec3& v, const glm::vec3& center, float innerRadius, float radius) { assert (innerRadius <= radius); const float d = glm::distance (v, center); if (radius - innerRadius < Util::epsilon ()) { return d > radius ? 0.0f : 1.0f; } else { return glm::clamp ((radius - d) / (radius - innerRadius), 0.0f, 1.0f); } } float Util::cross (const glm::vec2& v1, const glm::vec2& v2) { return (v1.x * v2.y) - (v1.y * v2.x); } std::string Util::readFile (const std::string& filePath) { std::string content; std::ifstream stream (filePath, std::ios::in); if (stream.is_open ()) { std::string line (""); while (getline (stream, line)) content += "\n" + line; stream.close (); } return content; } unsigned int Util::solveQuadraticEq (float a, float b, float c, float& s1, float& s2) { const float radicand = (b * b) - (4.0f * a * c); if (radicand < Util::epsilon ()) return 0; const float root = glm::sqrt (radicand); if (b < -Util::epsilon ()) { s1 = (-b + root) / (2.0f * a); s2 = (2.0f * c) / (-b + root); return 2; } else if (b > Util::epsilon ()) { s1 = (-b - root) / (2.0f * a); s2 = (2.0f * c) / (-b - root); return 2; } else { s1 = root / (2.0f * a); return 1; } } unsigned int Util::solveCubicEq (float a, float b, float c, float d, float& s1, float& s2, float& s3) { return Util::solveCubicEq (b / a, c / a, d / a, s1, s2, s3); } unsigned int Util::solveCubicEq (float a, float b, float c, float& s1, float& s2, float& s3) { const float q = ((a * a) - (3.0f * b)) / 9.0f; const float r = ((2.0f * a * a * a) - (9.0f * a * b) + (27.0f * c)) / 54.0f; const float w = (r * r) - (q * q * q); const float s = a / 3.0f; if (w < 0.0f) { const float theta = glm::acos (r / glm::sqrt (q * q * q)); const float f = -2.0f * glm::sqrt (q); s1 = (f * glm::cos (theta / 3.0f)) - s; s2 = (f * glm::cos ((theta + (2.0f * glm::pi ())) / 3.0f)) - s; s3 = (f * glm::cos ((theta - (2.0f * glm::pi ())) / 3.0f)) - s; return 3; } else { const float x = -glm::sign (r) * glm::pow (glm::abs (r) + glm::sqrt (w), 1.0f / 3.0f); const float y = Util::almostEqual (x, 0.0f) ? 0.0f : q / x; s1 = x + y - s; return 1; } } bool Util::isNaN (float v) { return glm::isnan (v); } bool Util::isNaN (const glm::vec3& v) { return glm::any (glm::isnan (v)); } bool Util::isNotNull (const glm::vec3& v) { const bool bx = Util::almostEqual (v.x, 0.0f) == false; const bool by = Util::almostEqual (v.y, 0.0f) == false; const bool bz = Util::almostEqual (v.z, 0.0f) == false; return bx || by || bz; } bool Util::almostEqual (float a, float b) { return glm::epsilonEqual (a, b, Util::epsilon ()); } bool Util::fromString (const std::string& string, int& value) { try { value = std::stoi (string); return true; } catch (const std::invalid_argument&) { return false; } catch (const std::out_of_range&) { return false; } } bool Util::fromString (const std::string& string, unsigned int& value) { try { value = (unsigned int) (std::stoul (string)); return true; } catch (const std::invalid_argument&) { return false; } catch (const std::out_of_range&) { return false; } } bool Util::fromString (const std::string& string, float& value) { try { value = std::stof (string); return true; } catch (const std::invalid_argument&) { return false; } catch (const std::out_of_range&) { return false; } } unsigned int Util::countOnes (unsigned int x) { unsigned int n = 0; for (; x > 0; n++) { x &= x - 1; } return n; } bool Util::hasSuffix (const std::string& string, const std::string& suffix) { if (string.size () >= suffix.size ()) { return string.compare (string.size () - suffix.size (), suffix.size (), suffix) == 0; } else { return false; } } namespace Util { template <> void withCLocale (const std::function& f) { const std::locale prev = std::locale::global (std::locale::classic ()); f (); std::locale::global (prev); } } ================================================ FILE: lib/src/util.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_UTIL #define DILAY_UTIL #include #include #include #include #include #include #include "log.hpp" #define DILAY_INFO(fmt, ...) Log::log (Log::Level::Info, __FILE__, __LINE__, fmt, ##__VA_ARGS__); #define DILAY_WARN(fmt, ...) Log::log (Log::Level::Warning, __FILE__, __LINE__, fmt, ##__VA_ARGS__); #define DILAY_PANIC(fmt, ...) \ { \ Log::log (Log::Level::Panic, __FILE__, __LINE__, fmt, ##__VA_ARGS__); \ Log::log (Log::Level::Panic, __FILE__, __LINE__, "aborting due to previous error..."); \ std::abort (); \ } #define DILAY_IMPOSSIBLE DILAY_PANIC ("the impossible happend") #define unused(x) ((void) (x)) typedef std::pair ui_pair; namespace Util { glm::vec3 midpoint (const glm::vec3&, const glm::vec3&); glm::vec3 transformPosition (const glm::mat4x4&, const glm::vec3&); glm::vec3 transformDirection (const glm::mat4x4&, const glm::vec3&); glm::vec3 orthogonal (const glm::vec3&); glm::ivec2 orthogonalRight (const glm::ivec2&); glm::mat4x4 rotation (const glm::vec3&, const glm::vec3&, float); bool colinear (const glm::vec2&, const glm::vec2&); bool colinear (const glm::vec3&, const glm::vec3&); bool colinearUnit (const glm::vec2&, const glm::vec2&); bool colinearUnit (const glm::vec3&, const glm::vec3&); float smoothStep (const glm::vec3&, const glm::vec3&, float, float); float linearStep (const glm::vec3&, const glm::vec3&, float, float); float cross (const glm::vec2&, const glm::vec2&); std::string readFile (const std::string&); unsigned int solveQuadraticEq (float, float, float, float&, float&); unsigned int solveCubicEq (float, float, float, float&, float&, float&); unsigned int solveCubicEq (float, float, float, float, float&, float&, float&); bool isNaN (float); bool isNaN (const glm::vec3&); bool isNotNull (const glm::vec3&); bool almostEqual (float, float); void warn (const char*, unsigned int, const char*, ...); bool fromString (const std::string&, int&); bool fromString (const std::string&, unsigned int&); bool fromString (const std::string&, float&); unsigned int countOnes (unsigned int); bool hasSuffix (const std::string&, const std::string&); constexpr float epsilon () { return 0.0001f; } constexpr float minFloat () { return std::numeric_limits::lowest (); } constexpr float maxFloat () { return std::numeric_limits::max (); } constexpr int minInt () { return std::numeric_limits::lowest (); } constexpr int maxInt () { return std::numeric_limits::max (); } constexpr int maxUnsignedInt () { return std::numeric_limits::max (); } constexpr unsigned int invalidIndex () { return std::numeric_limits::max (); } template void setIfNotNull (T* ptr, const T& value) { if (ptr) { *ptr = value; } } template unsigned int findIndexByReference (const std::vector& vec, const T& obj) { return &obj - &vec.at (0); } template T withCLocale (const std::function& f) { const std::locale prev = std::locale::global (std::locale::classic ()); T result = f (); std::locale::global (prev); return result; } template <> void withCLocale (const std::function& f); template void prune (std::vector& v, const std::function& p, std::vector* indexMap = nullptr) { if (indexMap) { indexMap->resize (v.size (), Util::invalidIndex ()); } auto lastIt = std::find_if_not (v.rbegin (), v.rend (), p); if (lastIt == v.rend ()) { v.clear (); } else { unsigned int last = v.size () - (lastIt - v.rbegin ()) - 1; for (unsigned int i = 0; i <= last; i++) { if (p (v[i])) { v[i] = v[last]; if (indexMap) { (*indexMap)[i] = Util::invalidIndex (); (*indexMap)[last] = i; } do { last--; } while (p (v[last])); } else { if (indexMap) { (*indexMap)[i] = i; } } } v.resize (last + 1); } } } #endif ================================================ FILE: lib/src/variant.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef VARIANT_35425680_d10a_41c7_b91e_2e48cfe545da #define VARIANT_35425680_d10a_41c7_b91e_2e48cfe545da #include #include #include // `VariantDetails` encapsulates internal details of the variant implementation namespace VariantDetails { template union VariantUnion; // Utility structure to initialize value in a union using its default constructor template struct InitValue; template struct InitValue<0, U, T, Ts...> { static void run (VariantUnion& variant) { static_assert (std::is_same::value, "variant type mismatch"); variant.t = new U (); } }; template struct InitValue { static void run (VariantUnion& variant) { InitValue::run (variant.ts); } }; // Utility structure to set value in a union template struct SetValue; template struct SetValue<0, U, T, Ts...> { static void run (VariantUnion& variant, const U& u) { static_assert (std::is_same::value, "variant type mismatch"); variant.t = new U (u); } }; template struct SetValue { static void run (VariantUnion& variant, const U& u) { SetValue::run (variant.ts, u); } }; // Utility structure to get the type of the i-th variant template struct GetType; template struct GetType<0, T, Ts...> { typedef T type; }; template struct GetType { typedef typename GetType::type type; }; // Utility structure to get the index of the variant of a certain type template struct GetIndex; template struct GetIndex { static constexpr bool found = std::is_same::value; static constexpr unsigned int index = i; }; template struct GetIndex { static constexpr bool found = std::is_same::value ? true : GetIndex::found; static constexpr unsigned int index = std::is_same::value ? i : GetIndex::index; }; // `VariantUnion ` implements union over pointers of type `T1,T2,...,Tn` // // Case n == 1; template union VariantUnion { static_assert (std::is_object::value, "non-object types are not supported"); static_assert (!std::is_const::value, "const-qualified types are not supported"); static_assert (!std::is_volatile::value, "volatile-qualified types are not supported"); T* t; VariantUnion () : t (nullptr) { } VariantUnion (const VariantUnion&) = delete; VariantUnion (VariantUnion&&) = delete; const VariantUnion& operator= (const VariantUnion&) = delete; const VariantUnion& operator= (VariantUnion&&) = delete; void copy (unsigned int i, const VariantUnion& other) { assert (i == 0); (void) i; this->t = new T (*other.t); } void move (unsigned int i, VariantUnion&& other) { assert (i == 0); (void) i; this->t = other.t; other.t = nullptr; } void release (unsigned int i) { assert (i == 0); (void) i; delete this->t; } template void init () { InitValue::run (*this); } template void set (const U& u) { SetValue::run (*this, u); } template U& get (unsigned int i) { assert (i == 0); assert ((std::is_same::value)); (void) i; return *reinterpret_cast (this->t); } template const U& get (unsigned int i) const { assert (i == 0); assert ((std::is_same::value)); (void) i; return *reinterpret_cast (this->t); } template U caseOf (unsigned int i, const std::function& branch) const { assert (i == 0); (void) i; return branch (*this->t); } }; // Case n > 1; template union VariantUnion { static_assert (std::is_object::value, "non-object types are not supported"); static_assert (!std::is_const::value, "const-qualified types are not supported"); static_assert (!std::is_volatile::value, "volatile-qualified types are not supported"); T* t; VariantUnion ts; VariantUnion () : t (nullptr) { } VariantUnion (const VariantUnion&) = delete; VariantUnion (VariantUnion&&) = delete; const VariantUnion& operator= (const VariantUnion&) = delete; const VariantUnion& operator= (VariantUnion&&) = delete; void copy (unsigned int i, const VariantUnion& other) { if (i == 0) { this->t = new T (*other.t); } else { this->ts.copy (i - 1, other.ts); } } void move (unsigned int i, VariantUnion&& other) { if (i == 0) { this->t = other.t; other.t = nullptr; } else { this->ts.move (i - 1, std::move (other.ts)); } } void release (unsigned int i) { if (i == 0) { delete this->t; } else { this->ts.release (i - 1); } } template void init () { InitValue::run (*this); } template void set (const U& u) { SetValue::run (*this, u); } template U& get (unsigned int i) { if (i == 0) { assert ((std::is_same::value)); return *reinterpret_cast (this->t); } else { return this->ts.template get (i - 1); } } template const U& get (unsigned int i) const { if (i == 0) { assert ((std::is_same::value)); return *reinterpret_cast (this->t); } else { return this->ts.template get (i - 1); } } template U caseOf (unsigned int i, const std::function& branch, const std::function&... branches) const { if (i == 0) { return branch (*this->t); } else { return this->ts.template caseOf (i - 1, branches...); } } }; }; // `Variant` wraps `VariantUnion` and handles construction, access and destruction template class Variant { public: Variant () : _varUnion () , _isSet (false) , _setTo (0) { } Variant (const Variant& other) : _varUnion () , _isSet (other._isSet) , _setTo (other._setTo) { if (this->isSet ()) { this->_varUnion.copy (this->_setTo, other._varUnion); } } Variant (Variant&& other) : _varUnion () , _isSet (other._isSet) , _setTo (other._setTo) { other._isSet = false; if (this->isSet ()) { this->_varUnion.move (this->_setTo, std::move (other._varUnion)); } } const Variant& operator= (const Variant& other) { if (this == &other) { return *this; } this->release (); this->_isSet = other._isSet; this->_setTo = other._setTo; if (this->isSet ()) { this->_varUnion.copy (this->_setTo, other._varUnion); } return *this; } const Variant& operator= (Variant&& other) { if (this == &other) { return *this; } this->release (); this->_isSet = other._isSet; this->_setTo = other._setTo; other._isSet = false; if (this->isSet ()) { this->_varUnion.move (this->_setTo, std::move (other._varUnion)); } return *this; } ~Variant () { this->release (); } void release () { if (this->isSet ()) { this->_varUnion.release (this->_setTo); this->_isSet = false; } } template U& get () { assert (this->isSet ()); return this->_varUnion.template get (this->_setTo); } template const U& get () const { assert (this->isSet ()); return this->_varUnion.template get (this->_setTo); } template > void initAt () { this->template resetTo (); this->_varUnion.template init (); } template void init () { constexpr bool found = VariantDetails::GetIndex<0, U, Ts...>::found; constexpr unsigned int index = VariantDetails::GetIndex<0, U, Ts...>::index; static_assert (found, "variant type not found"); this->template initAt (); } template > void setAt (const U& u) { this->template resetTo (); this->_varUnion.template set (u); } template void set (const U& u) { constexpr bool found = VariantDetails::GetIndex<0, U, Ts...>::found; constexpr unsigned int index = VariantDetails::GetIndex<0, U, Ts...>::index; static_assert (found, "variant type not found"); this->template setAt (u); } template bool is () const { if (this->isSet ()) { constexpr bool found = VariantDetails::GetIndex<0, U, Ts...>::found; constexpr unsigned int index = VariantDetails::GetIndex<0, U, Ts...>::index; static_assert (found, "variant type not found"); return this->_setTo == index; } else { return false; } } template U caseOf (const std::function&... branches) const { assert (this->isSet ()); return this->_varUnion.template caseOf (this->_setTo, branches...); } bool isSet () const { return this->_isSet; } private: VariantDetails::VariantUnion _varUnion; bool _isSet; unsigned int _setTo; template void resetTo () { if (this->isSet ()) { this->release (); } this->_isSet = true; this->_setTo = i; } }; #endif ================================================ FILE: lib/src/view/axis.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "camera.hpp" #include "color.hpp" #include "config.hpp" #include "dimension.hpp" #include "mesh-util.hpp" #include "mesh.hpp" #include "opengl.hpp" #include "render-mode.hpp" #include "view/axis.hpp" struct ViewAxis::Impl { Mesh coneMesh; Mesh cylinderMesh; Mesh gridMesh; glm::uvec2 axisResolution; Color axisColor; Color axisLabelColor; glm::vec3 axisScaling; glm::vec3 axisArrowScaling; unsigned int gridResolution; Impl (const Config& config) { this->runFromConfig (config); this->axisResolution = glm::uvec2 (200, 200); this->gridResolution = 6; this->coneMesh = MeshUtil::cone (10); this->cylinderMesh = MeshUtil::cylinder (10); this->cylinderMesh.renderMode ().constantShading (true); this->cylinderMesh.renderMode ().cameraRotationOnly (true); this->cylinderMesh.bufferData (); this->coneMesh.renderMode ().constantShading (true); this->coneMesh.renderMode ().cameraRotationOnly (true); this->coneMesh.bufferData (); this->initializeGrid (); } void initializeGrid () { float gridSpace = 1.0f / float(gridResolution - 1); for (unsigned int j = 0; j < gridResolution; j++) { for (unsigned int i = 0; i < gridResolution; i++) { this->gridMesh.addVertex (glm::vec3 (float(i) * gridSpace, float(j) * gridSpace, 0.0f)); } } for (unsigned int j = 1; j < gridResolution; j++) { for (unsigned int i = 1; i < gridResolution; i++) { this->gridMesh.addIndex ((j * gridResolution) + i - 1); this->gridMesh.addIndex ((j * gridResolution) + i); this->gridMesh.addIndex (((j - 1) * gridResolution) + i); this->gridMesh.addIndex ((j * gridResolution) + i); } } this->gridMesh.renderMode ().constantShading (true); this->gridMesh.renderMode ().cameraRotationOnly (true); this->gridMesh.bufferData (); } void render (Camera& camera) { OpenGL::glClear (OpenGL::DepthBufferBit ()); const glm::uvec2 resolution = camera.resolution (); camera.updateResolution (glm::uvec2 (200, 200)); this->cylinderMesh.scaling (this->axisScaling); this->cylinderMesh.position (glm::vec3 (0.0f, this->axisScaling.y * 0.5f, 0.0f)); this->cylinderMesh.rotationMatrix (glm::mat4x4 (1.0f)); this->cylinderMesh.color (this->axisColor); this->cylinderMesh.render (camera); this->cylinderMesh.position (glm::vec3 (this->axisScaling.y * 0.5f, 0.0f, 0.0f)); this->cylinderMesh.rotationZ (0.5f * glm::pi ()); this->cylinderMesh.render (camera); this->cylinderMesh.position (glm::vec3 (0.0f, 0.0f, this->axisScaling.y * 0.5f)); this->cylinderMesh.rotationX (0.5f * glm::pi ()); this->cylinderMesh.render (camera); this->coneMesh.scaling (this->axisArrowScaling); this->coneMesh.position (glm::vec3 (0.0f, this->axisScaling.y, 0.0f)); this->coneMesh.rotationMatrix (glm::mat4x4 (1.0f)); this->coneMesh.color (this->axisColor); this->coneMesh.render (camera); this->coneMesh.position (glm::vec3 (this->axisScaling.y, 0.0f, 0.0f)); this->coneMesh.rotationZ (-0.5f * glm::pi ()); this->coneMesh.render (camera); this->coneMesh.position (glm::vec3 (0.0f, 0.0f, this->axisScaling.y)); this->coneMesh.rotationX (0.5f * glm::pi ()); this->coneMesh.render (camera); this->renderGrid (camera); camera.updateResolution (resolution); } void renderGrid (Camera& camera) { switch (camera.primaryDimension ()) { case Dimension::X: this->gridMesh.rotationY (-0.5f * glm::pi ()); break; case Dimension::Y: this->gridMesh.rotationX (0.5f * glm::pi ()); break; case Dimension::Z: this->gridMesh.rotationMatrix (glm::mat4x4 (1.0f)); break; } this->gridMesh.scaling (glm::vec3 (this->axisScaling.y)); this->gridMesh.color (this->axisColor); this->gridMesh.renderLines (camera); } void render (Camera& camera, QPainter& painter) { this->coneMesh.rotationMatrix (glm::mat4x4 (1.0f)); QFont font; font.setWeight (QFont::Bold); QFontMetrics metrics (font); int w = glm::max (metrics.maxWidth (), metrics.height ()); glm::uvec2 resolution = camera.resolution (); camera.updateResolution (this->axisResolution); auto renderLabel = [this, &resolution, &painter, w, &camera](const glm::vec3& p, const QString& l) { this->coneMesh.position (p); glm::vec2 pos = camera.fromWorld (glm::vec3 (0.0f), this->coneMesh.modelMatrix (), true); QRect rect (int(pos.x) - (w / 2), resolution.y - this->axisResolution.y + int(pos.y) - (w / 2), w, w); painter.drawText (rect, Qt::AlignCenter, l); }; painter.setPen (this->axisLabelColor.qColor ()); painter.setFont (font); const float labelPosition = this->axisScaling.y + (this->axisArrowScaling.y * 0.5f); renderLabel (glm::vec3 (labelPosition, 0.0f, 0.0f), "X"); renderLabel (glm::vec3 (0.0f, labelPosition, 0.0f), "Y"); renderLabel (glm::vec3 (0.0f, 0.0f, labelPosition), "Z"); camera.updateResolution (resolution); } void runFromConfig (const Config& config) { this->axisLabelColor = config.get ("editor/axis/color/label"); this->axisColor = config.get ("editor/axis/color/normal"); this->axisScaling = config.get ("editor/axis/scaling"); this->axisArrowScaling = config.get ("editor/axis/arrow-scaling"); } }; DELEGATE1_BIG3 (ViewAxis, const Config&) DELEGATE1 (void, ViewAxis, render, Camera&) DELEGATE2 (void, ViewAxis, render, Camera&, QPainter&) DELEGATE1 (void, ViewAxis, runFromConfig, const Config&) ================================================ FILE: lib/src/view/axis.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_AXIS #define DILAY_VIEW_AXIS #include "configurable.hpp" #include "macro.hpp" class Camera; class Config; class QPainter; class ViewAxis : public Configurable { public: DECLARE_BIG3 (ViewAxis, const Config&) void render (Camera&); void render (Camera&, QPainter&); private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/view/color-button.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "color.hpp" #include "view/color-button.hpp" #include "view/util.hpp" struct ViewColorButton::Impl { ViewColorButton* self; Color color; Impl (ViewColorButton* s, const Color& c, bool alpha) : self (s) , color (c) { ViewUtil::connect (*this->self, [this, alpha]() { QColorDialog::ColorDialogOptions options; options.setFlag (QColorDialog::DontUseNativeDialog); if (alpha) { options.setFlag (QColorDialog::ShowAlphaChannel); } QColor selected = QColorDialog::getColor (this->color.qColor (), this->self->parentWidget (), QObject::tr ("Select color"), options); if (selected.isValid ()) { this->color = Color (selected); this->self->update (); emit this->self->colorChanged (this->color); } }); } void paintEvent (QPaintEvent* event) { this->self->QPushButton::paintEvent (event); QPainter painter (this->self); QRect rect (this->self->rect ()); const int dw = this->self->width () / 10; const int dh = this->self->height () / 5; rect.setLeft (rect.left () + dw); rect.setRight (rect.right () - dw); rect.setTop (rect.top () + dh); rect.setBottom (rect.bottom () - dh); painter.fillRect (rect, this->color.qColor ()); } }; DELEGATE_BIG2_BASE (ViewColorButton, (const Color& c, bool a, QWidget* p), (this, c, a), QPushButton, (p)) DELEGATE1 (void, ViewColorButton, paintEvent, QPaintEvent*) ================================================ FILE: lib/src/view/color-button.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_COLOR_BUTTON #define DILAY_COLOR_BUTTON #include #include "macro.hpp" class Color; class ViewColorButton : public QPushButton { Q_OBJECT public: DECLARE_BIG2 (ViewColorButton, const Color&, bool = false, QWidget* = nullptr) signals: void colorChanged (const Color&); protected: void paintEvent (QPaintEvent*); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/configuration.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include #include #include #include "../util.hpp" #include "color.hpp" #include "config.hpp" #include "state.hpp" #include "view/color-button.hpp" #include "view/configuration.hpp" #include "view/gl-widget.hpp" #include "view/main-window.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" #include "view/vector-edit.hpp" namespace { const std::array requireRestart = {"editor/use-geometry-shader"}; struct DialogData { ViewGlWidget& glWidget; bool requireRestart; DialogData (ViewGlWidget& w) : glWidget (w) , requireRestart (false) { } void checkIfRestartIsRequired (const std::string& path) { const auto it = std::find (::requireRestart.begin (), ::requireRestart.end (), path); if (it != ::requireRestart.end ()) { this->requireRestart = true; } } }; template void setAndUpdate (DialogData& data, const std::string& path, const T& value) { data.glWidget.state ().config ().set (path, value); data.glWidget.fromConfig (); data.glWidget.update (); data.checkIfRestartIsRequired (path); } void addColorButton (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path, const QString& label, bool alpha = false) { const Color& color = data.glWidget.state ().config ().get (path); ViewColorButton& button = *new ViewColorButton (color, alpha, &data.glWidget); QObject::connect (&button, &ViewColorButton::colorChanged, [&data, path](const Color& c) { setAndUpdate (data, path, c); }); grid.add (label, button); } void addVectorEdit (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path, const QString& label) { const glm::vec3& vector = data.glWidget.state ().config ().get (path); ViewVectorEdit& edit = *new ViewVectorEdit (vector); QObject::connect (&edit, &ViewVectorEdit::vectorEdited, [&data, path](const glm::vec3& v) { setAndUpdate (data, path, v); }); grid.add (label, edit); } void addFloatEdit (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path, const QString& label, float min, float max) { const float value = data.glWidget.state ().config ().get (path); QLineEdit& edit = ViewUtil::lineEdit (min, value, max); ViewUtil::connectFloat (edit, [&data, path](float f) { setAndUpdate (data, path, f); }); grid.add (label, edit); } void addIntEdit (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path, const QString& label, int min, int max) { const int value = data.glWidget.state ().config ().get (path); QLineEdit& edit = ViewUtil::lineEdit (min, value, max); ViewUtil::connectInt (edit, [&data, path](int i) { setAndUpdate (data, path, i); }); grid.add (label, edit); } void addBoolEdit (DialogData& data, ViewTwoColumnGrid& grid, const std::string& path, const QString& label) { const bool value = data.glWidget.state ().config ().get (path); QCheckBox& edit = ViewUtil::checkBox (label, value); ViewUtil::connect (edit, [&data, path](bool b) { setAndUpdate (data, path, b); }); grid.add (edit); } QWidget* makeColorsPage (DialogData& data) { ViewTwoColumnGrid* grid = new ViewTwoColumnGrid; addColorButton (data, *grid, "editor/background", QObject::tr ("Background")); addColorButton (data, *grid, "editor/on-screen-color", QObject::tr ("On-Screen"), true); addColorButton (data, *grid, "editor/axis/color/normal", QObject::tr ("Axis")); addColorButton (data, *grid, "editor/axis/color/label", QObject::tr ("Axis label")); addColorButton (data, *grid, "editor/floor-plane/color", QObject::tr ("Floor-plane")); addColorButton (data, *grid, "editor/mesh/color/normal", QObject::tr ("Mesh")); addColorButton (data, *grid, "editor/mesh/color/wireframe", QObject::tr ("Wireframe")); addColorButton (data, *grid, "editor/sketch/bubble/color", QObject::tr ("Sketch")); addColorButton (data, *grid, "editor/sketch/node/color", QObject::tr ("Sketch-node")); addColorButton (data, *grid, "editor/sketch/sphere/color", QObject::tr ("Sketch-sphere")); grid->addStretcher (); return grid; } QWidget* makeLightsPage (DialogData& data) { QWidget* widget = new QWidget; QHBoxLayout* layout = new QHBoxLayout; widget->setLayout (layout); ViewTwoColumnGrid* grid1 = new ViewTwoColumnGrid; grid1->addCenter (QObject::tr ("Light 1")); addVectorEdit (data, *grid1, "editor/light/light1/direction", QObject::tr ("Direction")); addColorButton (data, *grid1, "editor/light/light1/color", QObject::tr ("Color")); grid1->addStretcher (); ViewTwoColumnGrid* grid2 = new ViewTwoColumnGrid; grid2->addCenter (QObject::tr ("Light 2")); addVectorEdit (data, *grid2, "editor/light/light2/direction", QObject::tr ("Direction")); addColorButton (data, *grid2, "editor/light/light2/color", QObject::tr ("Color")); grid2->addStretcher (); layout->addWidget (grid1); layout->addWidget (grid2); return widget; } QWidget* makeCameraPage (DialogData& data) { ViewTwoColumnGrid* grid = new ViewTwoColumnGrid; addFloatEdit (data, *grid, "editor/camera/near-clipping", QObject::tr ("Near clipping plane"), Util::epsilon (), 1.0f); addFloatEdit (data, *grid, "editor/camera/far-clipping", QObject::tr ("Far clipping plane"), 100.0f, Util::maxFloat ()); addFloatEdit (data, *grid, "editor/camera/rotation-factor", QObject::tr ("Rotation factor"), Util::epsilon (), 100.0f); addFloatEdit (data, *grid, "editor/camera/movement-factor", QObject::tr ("Movement factor"), Util::epsilon (), 100.0f); addFloatEdit (data, *grid, "editor/camera/zoom-in-mouse-wheel-factor", QObject::tr ("Zoom factor (mouse wheel)"), Util::epsilon (), 1.0f); addFloatEdit (data, *grid, "editor/camera/field-of-view", QObject::tr ("Field of view"), Util::epsilon (), 120.0f); grid->addStretcher (); return grid; } QWidget* makeToolsPage (DialogData& data) { QWidget* widget = new QWidget; QHBoxLayout* layout = new QHBoxLayout; widget->setLayout (layout); ViewTwoColumnGrid* gridSculpt = new ViewTwoColumnGrid; gridSculpt->addCenter (QObject::tr ("General")); addColorButton (data, *gridSculpt, "editor/tool/cursor-color", QObject::tr ("Cursor color")); gridSculpt->addCenter (QObject::tr ("Sculpt")); addFloatEdit (data, *gridSculpt, "editor/tool/sculpt/detail-factor", QObject::tr ("Detail factor"), Util::epsilon (), 1.0f); addFloatEdit (data, *gridSculpt, "editor/tool/sculpt/step-width-factor", QObject::tr ("Step width factor"), Util::epsilon (), 1.0f); addFloatEdit (data, *gridSculpt, "editor/tool/sculpt/max-absolute-radius", QObject::tr ("Maximum absolute radius"), Util::epsilon (), 100.0f); addBoolEdit (data, *gridSculpt, "editor/tool/sculpt/mirror/render", QObject::tr ("Render mirror")); addFloatEdit (data, *gridSculpt, "editor/tool/sculpt/mirror/width", QObject::tr ("Mirror width"), Util::epsilon (), 1.0f); addColorButton (data, *gridSculpt, "editor/tool/sculpt/mirror/color", QObject::tr ("Mirror color")); gridSculpt->addStretcher (); ViewTwoColumnGrid* gridSketch = new ViewTwoColumnGrid; gridSketch->addCenter (QObject::tr ("Sketch")); addFloatEdit (data, *gridSketch, "editor/tool/sketch-spheres/step-width-factor", QObject::tr ("Step width factor"), Util::epsilon (), 1.0f); gridSketch->addStretcher (); layout->addWidget (gridSculpt); layout->addWidget (gridSketch); return widget; } QWidget* makeMiscPage (DialogData& data) { ViewTwoColumnGrid* grid = new ViewTwoColumnGrid; addIntEdit (data, *grid, "editor/undo-depth", QObject::tr ("Undo depth"), 1, Util::maxInt ()); addIntEdit (data, *grid, "window/initial-width", QObject::tr ("Initial window width"), 1, Util::maxInt ()); addIntEdit (data, *grid, "window/initial-height", QObject::tr ("Initial window height"), 1, Util::maxInt ()); addVectorEdit (data, *grid, "editor/axis/scaling", QObject::tr ("Axis scaling")); addVectorEdit (data, *grid, "editor/axis/arrow-scaling", QObject::tr ("Axis-arrow scaling")); addFloatEdit (data, *grid, "editor/floor-plane/tile-width", QObject::tr ("Floor-plane tile-width"), Util::epsilon (), 10.0f); addFloatEdit (data, *grid, "editor/tablet-pressure-intensity", QObject::tr ("Table pressure intensity"), Util::epsilon (), 10.0f); addBoolEdit (data, *grid, "editor/use-geometry-shader", QObject::tr ("Use geometry shader")); grid->addStretcher (); return grid; } } void ViewConfiguration::show (ViewMainWindow& window, ViewGlWidget& glWidget) { QDialog dialog (&window); DialogData data (glWidget); std::function setup = [&dialog, &data, &setup]() { delete dialog.layout (); QTabWidget* widget = new QTabWidget; widget->addTab (makeColorsPage (data), QObject::tr ("&Colors")); widget->addTab (makeLightsPage (data), QObject::tr ("&Lights")); widget->addTab (makeCameraPage (data), QObject::tr ("C&amera")); widget->addTab (makeToolsPage (data), QObject::tr ("&Tools")); widget->addTab (makeMiscPage (data), QObject::tr ("&Misc")); QDialogButtonBox* buttons = new QDialogButtonBox (QDialogButtonBox::Ok | QDialogButtonBox::RestoreDefaults); QObject::connect (buttons, &QDialogButtonBox::accepted, [&dialog]() { dialog.accept (); }); QObject::connect (&dialog, &QDialog::accepted, [&data]() { data.glWidget.fromConfig (); data.glWidget.update (); }); QObject::connect (buttons->button (QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, [&data, &setup]() { data.glWidget.state ().config ().restoreDefaults (); data.glWidget.fromConfig (); data.glWidget.update (); setup (); }); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget (widget); layout->addWidget (buttons); dialog.setLayout (layout); }; setup (); dialog.setWindowTitle (QObject::tr ("Configuration")); dialog.exec (); if (data.requireRestart) { ViewUtil::info (glWidget, QObject::tr ("A restart is required for some changes to come into effect.")); } } ================================================ FILE: lib/src/view/configuration.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_CONFIGURATION #define DILAY_VIEW_CONFIGURATION class ViewGlWidget; class ViewMainWindow; namespace ViewConfiguration { void show (ViewMainWindow&, ViewGlWidget&); } #endif ================================================ FILE: lib/src/view/context-menu.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "camera.hpp" #include "dimension.hpp" #include "dynamic/mesh-intersection.hpp" #include "dynamic/mesh.hpp" #include "mesh.hpp" #include "primitive/aabox.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "scene.hpp" #include "sketch/mesh-intersection.hpp" #include "state.hpp" #include "view/context-menu.hpp" #include "view/gl-widget.hpp" #include "view/main-window.hpp" #include "view/util.hpp" namespace { void addActions (QMenu& menu, ViewMainWindow& mainWindow, DynamicMesh& mesh) { Scene& scene = mainWindow.glWidget ().state ().scene (); Config& config = mainWindow.glWidget ().state ().config (); ViewUtil::addAction (menu, QObject::tr ("Copy mesh"), QKeySequence (), [&mainWindow, &scene, &config, &mesh]() { scene.newDynamicMesh (config, mesh); mainWindow.update (); }); ViewUtil::addAction ( menu, QObject::tr ("Mirror mesh"), QKeySequence (), [&mainWindow, &mesh]() { const PrimAABox bounds = mesh.mesh ().bounds (); const PrimPlane plane (bounds.center (), DimensionUtil::vector (Dimension::X)); mesh.mirror (plane); mainWindow.update (); }); ViewUtil::addAction (menu, QObject::tr ("Move mesh to center"), QKeySequence (), [&mainWindow, &mesh]() { mesh.moveToCenter (); mainWindow.update (); }); ViewUtil::addAction (menu, QObject::tr ("Normalize mesh scaling"), QKeySequence (), [&mainWindow, &mesh]() { mesh.normalizeScaling (); mainWindow.update (); }); ViewUtil::addAction (menu, QObject::tr ("Delete mesh"), QKeySequence (), [&mainWindow, &scene, &mesh]() { scene.deleteMesh (mesh); mainWindow.update (); }); } void addActions (QMenu& menu, ViewMainWindow& mainWindow, SketchMesh& sketch) { Scene& scene = mainWindow.glWidget ().state ().scene (); Config& config = mainWindow.glWidget ().state ().config (); ViewUtil::addAction (menu, QObject::tr ("Copy sketch"), QKeySequence (), [&mainWindow, &scene, &config, &sketch]() { scene.newSketchMesh (config, sketch); mainWindow.update (); }); ViewUtil::addAction (menu, QObject::tr ("Delete sketch"), QKeySequence (), [&mainWindow, &scene, &sketch]() { scene.deleteMesh (sketch); mainWindow.update (); }); } } ViewContextMenu::ViewContextMenu (ViewMainWindow& mainWindow, DynamicMesh& mesh) { ::addActions (*this, mainWindow, mesh); } ViewContextMenu::ViewContextMenu (ViewMainWindow& mainWindow, SketchMesh& sketch) { ::addActions (*this, mainWindow, sketch); } ViewContextMenu::ViewContextMenu (ViewMainWindow& mainWindow, const glm::ivec2& pos) { Scene& scene = mainWindow.glWidget ().state ().scene (); const PrimRay ray = mainWindow.glWidget ().state ().camera ().ray (pos); DynamicMeshIntersection mIntersection; SketchMeshIntersection sIntersection; if (scene.intersects (ray, mIntersection)) { ::addActions (*this, mainWindow, mIntersection.mesh ()); } else if (scene.intersects (ray, sIntersection)) { ::addActions (*this, mainWindow, sIntersection.mesh ()); } } ================================================ FILE: lib/src/view/context-menu.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_CONTEXT_MENU #define DILAY_VIEW_CONTEXT_MENU #include #include class DynamicMesh; class SketchMesh; class ViewMainWindow; class ViewContextMenu : public QMenu { public: ViewContextMenu (ViewMainWindow&, DynamicMesh&); ViewContextMenu (ViewMainWindow&, SketchMesh&); ViewContextMenu (ViewMainWindow&, const glm::ivec2&); }; #endif ================================================ FILE: lib/src/view/cursor.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "mesh-util.hpp" #include "mesh.hpp" #include "opengl.hpp" #include "render-mode.hpp" #include "view/cursor.hpp" struct ViewCursor::Impl { Mesh radiusMesh; float _radius; bool isEnabled; static const unsigned int numSectors = 40; Impl () : _radius (0.0f) , isEnabled (false) { this->radiusMesh = MeshUtil::icosphere (2); this->radiusMesh.renderMode ().constantShading (true); this->radiusMesh.bufferData (); } float radius () const { return this->_radius; } glm::vec3 position () const { return this->radiusMesh.position (); } const Color& color () const { return this->radiusMesh.color (); } void radius (float r) { this->_radius = r; this->update (); } void position (const glm::vec3& p) { this->radiusMesh.position (p); } void color (const Color& color) { this->radiusMesh.color (color); } void enable () { this->isEnabled = true; } void disable () { this->isEnabled = false; } void render (Camera& camera) const { if (this->isEnabled) { OpenGL::glClear (OpenGL::StencilBufferBit ()); OpenGL::glDepthMask (false); OpenGL::glColorMask (false, false, false, false); OpenGL::glEnable (OpenGL::StencilTest ()); OpenGL::glCullFace (OpenGL::Front ()); OpenGL::glEnable (OpenGL::StencilTest ()); OpenGL::glStencilFunc (OpenGL::Always (), 1, 255); OpenGL::glStencilOp (OpenGL::Keep (), OpenGL::Replace (), OpenGL::Keep ()); this->radiusMesh.render (camera); OpenGL::glCullFace (OpenGL::Back ()); OpenGL::glColorMask (true, true, true, true); OpenGL::glStencilFunc (OpenGL::Equal (), 1, 255); OpenGL::glStencilOp (OpenGL::Keep (), OpenGL::Keep (), OpenGL::Keep ()); OpenGL::glEnable (OpenGL::Blend ()); OpenGL::glBlendEquation (OpenGL::FuncAdd ()); OpenGL::glBlendFunc (OpenGL::DstColor (), OpenGL::Zero ()); this->radiusMesh.render (camera); OpenGL::glDisable (OpenGL::Blend ()); OpenGL::glDisable (OpenGL::StencilTest ()); OpenGL::glDepthMask (true); } } void update () { this->radiusMesh.scaling (glm::vec3 (this->radius ())); } }; DELEGATE_BIG6 (ViewCursor) DELEGATE_CONST (float, ViewCursor, radius) DELEGATE_CONST (glm::vec3, ViewCursor, position) DELEGATE_CONST (const Color&, ViewCursor, color) GETTER_CONST (bool, ViewCursor, isEnabled) DELEGATE1 (void, ViewCursor, radius, float) DELEGATE1 (void, ViewCursor, position, const glm::vec3&) DELEGATE1 (void, ViewCursor, color, const Color&) DELEGATE (void, ViewCursor, enable) DELEGATE (void, ViewCursor, disable) DELEGATE1_CONST (void, ViewCursor, render, Camera&) ================================================ FILE: lib/src/view/cursor.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_CURSOR #define DILAY_VIEW_CURSOR #include #include "macro.hpp" class Camera; class Color; class Mesh; class ViewCursor { public: DECLARE_BIG6 (ViewCursor) float radius () const; glm::vec3 position () const; const Color& color () const; bool isEnabled () const; void radius (float); void position (const glm::vec3&); void color (const Color&); void enable (); void disable (); void render (Camera&) const; private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/double-slider.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "../util.hpp" #include "view/double-slider.hpp" struct ViewDoubleSlider::Impl { ViewDoubleSlider* self; const unsigned int factor; const unsigned short order; Impl (ViewDoubleSlider* s, unsigned short numDecimals, unsigned short o) : self (s) , factor (glm::pow (10.0f, float(numDecimals))) , order (o) { assert (this->order > 0); QObject::connect (this->self, &QSlider::valueChanged, [this](int i) { emit this->self->doubleValueChanged (this->toDouble (i, false)); }); } double toDouble (int value, bool forceLinear) const { const unsigned short o = forceLinear ? 1 : this->order; if (o == 1) { return double(value) / this->factor; } else { const double min = double(this->self->minimum ()) / this->factor; const double max = double(this->self->maximum ()) / this->factor; const double d = double(value) / this->factor; const double norm = (d - min) / (max - min); const double result = min + (glm::pow (float(norm), float(o)) * (max - min)); return result; } } int toInt (double value, bool forceLinear) const { const unsigned short o = forceLinear ? 1 : this->order; if (o == 1) { return int(std::round (value * this->factor)); } else { const double min = double(this->self->minimum ()) / this->factor; const double max = double(this->self->maximum ()) / this->factor; const double norm = (value - min) / (max - min); const double slope = norm <= Util::epsilon () ? 0.0f : glm::pow (float(norm), 1.0f / float(o)); return int(std::round (this->factor * (min + (slope * (max - min))))); } } double doubleValue () const { return this->toDouble (this->self->value (), false); } double doubleSingleStep () const { return this->toDouble (this->self->singleStep (), true); } void setDoubleValue (double v) { this->self->setValue (this->toInt (v, false)); } void setDoubleRange (double min, double max) { this->self->setRange (this->toInt (min, true), this->toInt (max, true)); } void setDoubleSingleStep (double v) { this->self->setSingleStep (this->toInt (v, true)); } void setDoublePageStep (double v) { this->self->setPageStep (this->toInt (v, true)); } int intValue () const { return this->self->QSlider::value (); } int intSingleStep () const { return this->self->QSlider::singleStep (); } void setIntValue (int v) { this->self->QSlider::setValue (v); } void setIntRange (int min, int max) { this->self->QSlider::setRange (min, max); } void setIntSingleStep (int v) { this->self->QSlider::setSingleStep (v); } void setIntPageStep (int v) { this->self->QSlider::setPageStep (v); } int value () const { return this->intValue (); } int singleStep () const { return this->intSingleStep (); } void setValue (int v) { this->setIntValue (v); } void setRange (int min, int max) { this->setIntRange (min, max); } void setSingleStep (int v) { this->setIntSingleStep (v); } void setPageStep (int v) { this->setIntPageStep (v); } }; DELEGATE2_BIG2_SELF (ViewDoubleSlider, unsigned short, unsigned short) DELEGATE_CONST (double, ViewDoubleSlider, doubleValue) DELEGATE_CONST (double, ViewDoubleSlider, doubleSingleStep) DELEGATE1 (void, ViewDoubleSlider, setDoubleValue, double) DELEGATE2 (void, ViewDoubleSlider, setDoubleRange, double, double) DELEGATE1 (void, ViewDoubleSlider, setDoubleSingleStep, double) DELEGATE1 (void, ViewDoubleSlider, setDoublePageStep, double) DELEGATE_CONST (int, ViewDoubleSlider, intValue) DELEGATE_CONST (int, ViewDoubleSlider, intSingleStep) DELEGATE1 (void, ViewDoubleSlider, setIntValue, int) DELEGATE2 (void, ViewDoubleSlider, setIntRange, int, int) DELEGATE1 (void, ViewDoubleSlider, setIntSingleStep, int) DELEGATE1 (void, ViewDoubleSlider, setIntPageStep, int) DELEGATE_CONST (int, ViewDoubleSlider, value) DELEGATE_CONST (int, ViewDoubleSlider, singleStep) DELEGATE1 (void, ViewDoubleSlider, setValue, int) DELEGATE2 (void, ViewDoubleSlider, setRange, int, int) DELEGATE1 (void, ViewDoubleSlider, setSingleStep, int) DELEGATE1 (void, ViewDoubleSlider, setPageStep, int) ================================================ FILE: lib/src/view/double-slider.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_DOUBLE_SLIDER #define DILAY_DOUBLE_SLIDER #include #include "macro.hpp" class ViewDoubleSlider : public QSlider { Q_OBJECT public: DECLARE_BIG2 (ViewDoubleSlider, unsigned short, unsigned short) double doubleValue () const; double doubleSingleStep () const; void setDoubleValue (double); void setDoubleRange (double, double); void setDoubleSingleStep (double); void setDoublePageStep (double); int intValue () const; int intSingleStep () const; void setIntValue (int); void setIntRange (int, int); void setIntSingleStep (int); void setIntPageStep (int); signals: void doubleValueChanged (double); private: int value () const; int singleStep () const; void setValue (int); void setRange (int, int); void setSingleStep (int); void setPageStep (int); IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/floor-plane.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "camera.hpp" #include "color.hpp" #include "config.hpp" #include "mesh.hpp" #include "render-mode.hpp" #include "view/floor-plane.hpp" struct ViewFloorPlane::Impl { Mesh mesh; float tileWidth; unsigned int resolution; bool isActive; Impl (const Config& config, const Camera& camera) : resolution (0) , isActive (false) { this->runFromConfig (config); this->update (camera); } void render (Camera& camera) const { if (this->isActive) { this->mesh.renderLines (camera); } } void update (const Camera& cam) { const float w = cam.toWorld (float(cam.resolution ().x), glm::length (cam.position ())); const unsigned int r = (unsigned int) (w / this->tileWidth) + 2; if (r != this->resolution) { this->resolution = r; this->mesh.reset (); for (unsigned int j = 0; j < r; j++) { for (unsigned int i = 0; i < r; i++) { this->mesh.addVertex ( glm::vec3 (float(i) * this->tileWidth, 0.0f, float(j) * this->tileWidth)); } } for (unsigned int j = 1; j < r; j++) { this->mesh.addIndex (j - 1); this->mesh.addIndex (j); this->mesh.addIndex ((j - 1) * r); this->mesh.addIndex (j * r); for (unsigned int i = 1; i < r; i++) { this->mesh.addIndex ((j * r) + i - 1); this->mesh.addIndex ((j * r) + i); this->mesh.addIndex (((j - 1) * r) + i); this->mesh.addIndex ((j * r) + i); } } const float center = -0.5f * float(r - 1) * this->tileWidth; this->mesh.position (glm::vec3 (center, 0.0f, center)); this->mesh.renderMode ().constantShading (true); this->mesh.bufferData (); } } void runFromConfig (const Config& config) { this->mesh.color (config.get ("editor/floor-plane/color")); this->tileWidth = config.get ("editor/floor-plane/tile-width"); } }; DELEGATE2_BIG3 (ViewFloorPlane, const Config&, const Camera&) DELEGATE1_CONST (void, ViewFloorPlane, render, Camera&) DELEGATE1 (void, ViewFloorPlane, update, const Camera&) GETTER_CONST (bool, ViewFloorPlane, isActive) SETTER (bool, ViewFloorPlane, isActive) DELEGATE1 (void, ViewFloorPlane, runFromConfig, const Config&) ================================================ FILE: lib/src/view/floor-plane.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_FLOORPLANE #define DILAY_VIEW_FLOORPLANE #include "configurable.hpp" #include "macro.hpp" class Camera; class Config; class ViewFloorPlane : public Configurable { public: DECLARE_BIG3 (ViewFloorPlane, const Config&, const Camera&) void render (Camera&) const; void update (const Camera&); bool isActive () const; void isActive (bool); private: IMPLEMENTATION void runFromConfig (const Config&); }; #endif ================================================ FILE: lib/src/view/gl-widget.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include "camera.hpp" #include "config.hpp" #include "mesh-util.hpp" #include "mesh.hpp" #include "opengl.hpp" #include "renderer.hpp" #include "scene.hpp" #include "state.hpp" #include "tool/move-camera.hpp" #include "view/axis.hpp" #include "view/context-menu.hpp" #include "view/floor-plane.hpp" #include "view/gl-widget.hpp" #include "view/info-pane.hpp" #include "view/info-pane/scene.hpp" #include "view/key-event.hpp" #include "view/main-window.hpp" #include "view/pointing-event.hpp" #include "view/tool-pane.hpp" #include "view/util.hpp" struct ViewGlWidget::Impl { typedef std::unique_ptr ToolMoveCameraPtr; typedef std::unique_ptr StatePtr; typedef std::unique_ptr AxisPtr; typedef std::unique_ptr FloorPlanePtr; ViewGlWidget* self; ViewMainWindow& mainWindow; Config& config; Cache& cache; ToolMoveCameraPtr _immediateMoveCamera; StatePtr _state; AxisPtr axis; FloorPlanePtr _floorPlane; bool tabletPressed; Impl (ViewGlWidget* s, ViewMainWindow& mW, Config& cfg, Cache& cch) : self (s) , mainWindow (mW) , config (cfg) , cache (cch) , tabletPressed (false) { this->self->setAutoFillBackground (false); } ~Impl () { this->self->makeCurrent (); this->_state.reset (nullptr); this->axis.reset (nullptr); this->_floorPlane.reset (nullptr); this->self->doneCurrent (); } ToolMoveCamera& immediateMoveCamera () { assert (this->_immediateMoveCamera); return *this->_immediateMoveCamera; } State& state () { assert (this->_state); return *this->_state; } ViewFloorPlane& floorPlane () { assert (this->_floorPlane); return *this->_floorPlane; } glm::ivec2 cursorPosition () { return ViewUtil::toIVec2 (this->self->mapFromGlobal (QCursor::pos ())); } void fromConfig () { assert (this->axis); assert (this->_immediateMoveCamera); this->state ().fromConfig (); this->axis->fromConfig (this->config); this->floorPlane ().fromConfig (this->config); this->floorPlane ().update (this->state ().camera ()); this->_immediateMoveCamera->fromConfig (); } void initializeGL () { OpenGL::initializeFunctions (this->config.get ("editor/use-geometry-shader")); this->_state.reset (new State (this->mainWindow, this->config, this->cache)); this->axis.reset (new ViewAxis (this->config)); this->_floorPlane.reset (new ViewFloorPlane (this->config, this->state ().camera ())); this->_immediateMoveCamera.reset (new ToolMoveCamera (this->state (), true)); this->_immediateMoveCamera->initialize (); this->self->setMouseTracking (true); this->self->setTabletTracking (true); this->initializeScene (); this->mainWindow.toolPane ().forceWidth (); } void initializeScene () { const QStringList arguments = QCoreApplication::arguments (); if (arguments.size () > 1) { const std::string fileName = arguments.at (1).toStdString (); if (this->state ().scene ().fromDlyFile (this->state ().config (), fileName) == false) { ViewUtil::error (this->mainWindow, QObject::tr ("Could not open file.")); } } else { this->state ().scene ().newDynamicMesh (this->config, MeshUtil::icosphere (4)); } this->mainWindow.update (); } void paintGL () { QPainter painter (this->self); painter.beginNativePainting (); this->state ().camera ().renderer ().setupRendering (); this->state ().scene ().render (this->state ().camera ()); this->floorPlane ().render (this->state ().camera ()); if (this->state ().hasTool ()) { this->state ().tool ().render (); } this->axis->render (this->state ().camera ()); this->state ().camera ().renderer ().shutdownRendering (); painter.endNativePainting (); this->axis->render (this->state ().camera (), painter); if (this->state ().hasTool ()) { this->state ().tool ().paint (painter); } } void resizeGL (int w, int h) { this->state ().camera ().updateResolution (glm::uvec2 (w, h)); } void pointingEvent (const ViewPointingEvent& e) { if (e.valid ()) { if (this->_immediateMoveCamera->pointingEvent (e) == ToolResponse::Redraw) { this->state ().handleToolResponse (ToolResponse::Redraw); this->updateCursorInTool (); } if (this->state ().hasTool ()) { this->state ().handleToolResponse (this->state ().tool ().pointingEvent (e)); } } } void mouseMoveEvent (QMouseEvent* e) { if (this->tabletPressed == false) { this->pointingEvent (ViewPointingEvent (*e)); } } void mousePressEvent (QMouseEvent* e) { if (this->tabletPressed == false) { this->pointingEvent (ViewPointingEvent (*e)); } } void mouseReleaseEvent (QMouseEvent* e) { if (this->tabletPressed == false) { this->pointingEvent (ViewPointingEvent (*e)); } } void wheelEvent (QWheelEvent* e) { if (this->_immediateMoveCamera->wheelEvent (*e) == ToolResponse::Redraw) { this->state ().handleToolResponse (ToolResponse::Redraw); this->updateCursorInTool (); } } void tabletEvent (QTabletEvent* e) { const ViewPointingEvent pointingEvent (this->state ().config (), *e); if (pointingEvent.pressEvent ()) { this->tabletPressed = true; } else if (pointingEvent.releaseEvent ()) { this->tabletPressed = false; } this->pointingEvent (pointingEvent); } void keyPressEvent (QKeyEvent* e) { const ViewKeyEvent keyEvent (*e, true); if (this->state ().hasTool ()) { this->state ().tool ().keyEvent (keyEvent); } this->self->QOpenGLWidget::keyPressEvent (e); } void keyReleaseEvent (QKeyEvent* e) { const ViewKeyEvent keyEvent (*e, false); if (this->state ().hasTool ()) { this->state ().tool ().keyEvent (keyEvent); } this->self->QOpenGLWidget::keyReleaseEvent (e); } void enterEvent (QEvent*) { this->self->setFocus (); } void contextMenuEvent (QContextMenuEvent* event) { this->state ().resetTool (); ViewContextMenu menu (this->mainWindow, ViewUtil::toIVec2 (event->pos ())); menu.exec (this->self->mapToGlobal (event->pos ())); } void updateCursorInTool () { if (this->state ().hasTool ()) { this->state ().handleToolResponse ( this->state ().tool ().cursorUpdate (this->cursorPosition ())); } } }; DELEGATE3_BIG2_SELF (ViewGlWidget, ViewMainWindow&, Config&, Cache&) DELEGATE (ToolMoveCamera&, ViewGlWidget, immediateMoveCamera) DELEGATE (State&, ViewGlWidget, state) DELEGATE (ViewFloorPlane&, ViewGlWidget, floorPlane) DELEGATE (glm::ivec2, ViewGlWidget, cursorPosition) DELEGATE (void, ViewGlWidget, fromConfig) DELEGATE (void, ViewGlWidget, initializeGL) DELEGATE2 (void, ViewGlWidget, resizeGL, int, int) DELEGATE (void, ViewGlWidget, paintGL) DELEGATE1 (void, ViewGlWidget, mouseMoveEvent, QMouseEvent*) DELEGATE1 (void, ViewGlWidget, mousePressEvent, QMouseEvent*) DELEGATE1 (void, ViewGlWidget, mouseReleaseEvent, QMouseEvent*) DELEGATE1 (void, ViewGlWidget, wheelEvent, QWheelEvent*) DELEGATE1 (void, ViewGlWidget, tabletEvent, QTabletEvent*) DELEGATE1 (void, ViewGlWidget, keyPressEvent, QKeyEvent*) DELEGATE1 (void, ViewGlWidget, keyReleaseEvent, QKeyEvent*) DELEGATE1 (void, ViewGlWidget, enterEvent, QEvent*) DELEGATE1 (void, ViewGlWidget, contextMenuEvent, QContextMenuEvent*) ================================================ FILE: lib/src/view/gl-widget.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_GL_WIDGET #define DILAY_VIEW_GL_WIDGET #include #include #include "macro.hpp" class Cache; class Config; class State; class ToolMoveCamera; class ViewFloorPlane; class ViewMainWindow; class ViewGlWidget : public QOpenGLWidget { Q_OBJECT public: DECLARE_BIG2 (ViewGlWidget, ViewMainWindow&, Config&, Cache&) ToolMoveCamera& immediateMoveCamera (); State& state (); ViewFloorPlane& floorPlane (); glm::ivec2 cursorPosition (); void fromConfig (); protected: void initializeGL (); void resizeGL (int, int); void paintGL (); void mouseMoveEvent (QMouseEvent*); void mousePressEvent (QMouseEvent*); void mouseReleaseEvent (QMouseEvent*); void wheelEvent (QWheelEvent*); void tabletEvent (QTabletEvent*); void keyPressEvent (QKeyEvent*); void keyReleaseEvent (QKeyEvent*); void enterEvent (QEvent*); void contextMenuEvent (QContextMenuEvent*); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/info-pane/scene.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "../../scene.hpp" #include "dynamic/mesh.hpp" #include "sketch/mesh.hpp" #include "sketch/path.hpp" #include "state.hpp" #include "view/context-menu.hpp" #include "view/gl-widget.hpp" #include "view/info-pane/scene.hpp" #include "view/main-window.hpp" namespace { static const int MeshType = QTreeWidgetItem::UserType + 0; static const int SketchType = QTreeWidgetItem::UserType + 1; struct MeshItem : public QTreeWidgetItem { DynamicMesh* mesh; MeshItem (QTreeWidgetItem& parent, const QStringList& labels, DynamicMesh& m) : QTreeWidgetItem (&parent, labels, MeshType) { this->mesh = &m; } MeshItem (QTreeWidget& parent, const QStringList& labels, DynamicMesh& m) : QTreeWidgetItem (&parent, labels, MeshType) { this->mesh = &m; } }; struct SketchItem : public QTreeWidgetItem { SketchMesh* sketch; SketchItem (QTreeWidgetItem& parent, const QStringList& labels, SketchMesh& s) : QTreeWidgetItem (&parent, labels, SketchType) { this->sketch = &s; } SketchItem (QTreeWidget& parent, const QStringList& labels, SketchMesh& s) : QTreeWidgetItem (&parent, labels, SketchType) { this->sketch = &s; } }; } struct ViewInfoPaneScene::Impl { ViewInfoPaneScene* self; ViewMainWindow& mainWindow; QTreeWidget* tree; Impl (ViewInfoPaneScene* s, ViewMainWindow& m) : self (s) , mainWindow (m) , tree (new QTreeWidget (this->self)) { this->self->setLayout (new QVBoxLayout); this->tree->setHeaderLabels ({QObject::tr ("Object"), QObject::tr ("Value")}); this->tree->setRootIsDecorated (false); this->tree->setContextMenuPolicy (Qt::CustomContextMenu); QObject::connect (this->tree, &QTreeWidget::customContextMenuRequested, [this](const QPoint& p) { this->showMenu (p); }); } void updateInfo () { const auto showMesh = [this](DynamicMesh& mesh) { MeshItem& item = *new MeshItem (*this->tree, {QObject::tr ("Mesh")}, mesh); new MeshItem (item, {QObject::tr ("Faces"), QString::number (mesh.numFaces ())}, mesh); new MeshItem (item, {QObject::tr ("Vertices"), QString::number (mesh.numVertices ())}, mesh); }; const auto showSketch = [this](SketchMesh& sketch) { SketchItem& item = *new SketchItem (*this->tree, {QObject::tr ("Sketch")}, sketch); if (sketch.tree ().hasRoot ()) { const unsigned int numNodes = sketch.tree ().root ().numNodes (); const unsigned int numPaths = sketch.paths ().size (); new SketchItem (item, {QObject::tr ("Nodes"), QString::number (numNodes)}, sketch); new SketchItem (item, {QObject::tr ("Paths"), QString::number (numPaths)}, sketch); } }; this->tree->clear (); this->mainWindow.glWidget ().state ().scene ().forEachMesh (showMesh); this->mainWindow.glWidget ().state ().scene ().forEachMesh (showSketch); this->tree->expandAll (); this->tree->setItemsExpandable (false); this->self->layout ()->addWidget (this->tree); } void showMenu (const QPoint& point) { QTreeWidgetItem* item = this->tree->itemAt (point); if (item && item->type () == MeshType) { this->mainWindow.glWidget ().state ().resetTool (); ViewContextMenu menu (this->mainWindow, *static_cast (item)->mesh); menu.exec (this->tree->viewport ()->mapToGlobal (point)); } else if (item && item->type () == SketchType) { this->mainWindow.glWidget ().state ().resetTool (); ViewContextMenu menu (this->mainWindow, *static_cast (item)->sketch); menu.exec (this->tree->viewport ()->mapToGlobal (point)); } } }; DELEGATE_BIG2_BASE (ViewInfoPaneScene, (ViewMainWindow & m, QWidget* p), (this, m), QWidget, (p)) DELEGATE (void, ViewInfoPaneScene, updateInfo) ================================================ FILE: lib/src/view/info-pane/scene.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_INFO_PANE_SCENE #define DILAY_VIEW_INFO_PANE_SCENE #include #include "macro.hpp" class ViewMainWindow; class ViewInfoPaneScene : public QWidget { public: DECLARE_BIG2 (ViewInfoPaneScene, ViewMainWindow&, QWidget* = nullptr) void updateInfo (); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/info-pane.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "view/info-pane.hpp" #include "view/info-pane/scene.hpp" #include "view/tool-tip.hpp" #include "view/two-column-grid.hpp" struct ViewInfoPane::Impl { ViewInfoPane* self; ViewMainWindow& mainWindow; ViewTwoColumnGrid& toolTip; ViewInfoPaneScene& scene; Impl (ViewInfoPane* s, ViewMainWindow& m) : self (s) , mainWindow (m) , toolTip (*new ViewTwoColumnGrid) , scene (*new ViewInfoPaneScene (m)) { QScrollArea* scrollArea = new QScrollArea; QTabWidget* tabWidget = new QTabWidget; tabWidget->addTab (this->initializeToolTipTab (), QObject::tr ("Keys")); tabWidget->addTab (&this->scene, QObject::tr ("Scene")); scrollArea->setWidgetResizable (true); scrollArea->setWidget (tabWidget); this->self->setWindowTitle (QObject::tr ("Info")); this->self->setWidget (scrollArea); this->self->setFeatures (DockWidgetMovable | DockWidgetClosable); this->self->setAllowedAreas (Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); this->resetToolTip (); } QWidget* initializeToolTipTab () { ViewToolTip dummyTip; dummyTip.add (ViewInputEvent::MouseMiddle, ViewInputModifier::Shift, "01234567890123456789"); this->addToolTip (dummyTip); this->toolTip.setEqualColumnStretch (); QWidget* pane = new QWidget; QVBoxLayout* layout = new QVBoxLayout (pane); layout->setContentsMargins (0, 0, 0, 0); layout->setSpacing (0); layout->addWidget (&this->toolTip); layout->addStretch (1); return pane; } void addToolTip (const ViewToolTip& tip) { if (tip.isEmpty ()) { return; } else if (this->toolTip.numRows () > 0) { this->toolTip.addSeparator (); } tip.render ( [this](const QString& action, const QString& tip) { this->toolTip.add (action, tip); }); } void resetToolTip () { this->toolTip.reset (); } }; DELEGATE_BIG2_BASE (ViewInfoPane, (ViewMainWindow & m, QWidget* p), (this, m), QDockWidget, (p)) GETTER (ViewInfoPaneScene&, ViewInfoPane, scene) DELEGATE1 (void, ViewInfoPane, addToolTip, const ViewToolTip&) DELEGATE (void, ViewInfoPane, resetToolTip) ================================================ FILE: lib/src/view/info-pane.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_INFO_PANE #define DILAY_VIEW_INFO_PANE #include #include "macro.hpp" class ViewInfoPaneScene; class ViewMainWindow; class ViewToolTip; class ViewInfoPane : public QDockWidget { public: DECLARE_BIG2 (ViewInfoPane, ViewMainWindow&, QWidget* = nullptr) ViewInfoPaneScene& scene (); void addToolTip (const ViewToolTip&); void resetToolTip (); void reset (); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/input.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "../util.hpp" #include "view/input.hpp" namespace ViewInput { QKeySequence toQKeySequence (ViewInputEvent event, ViewInputModifier modifier) { unsigned int value = 0; switch (modifier) { case ViewInputModifier::None: break; case ViewInputModifier::Ctrl: value += Qt::CTRL; break; case ViewInputModifier::Shift: value += Qt::SHIFT; break; case ViewInputModifier::Alt: value += Qt::ALT; break; } switch (event) { case ViewInputEvent::A: value += Qt::Key_A; break; case ViewInputEvent::B: value += Qt::Key_B; break; case ViewInputEvent::C: value += Qt::Key_C; break; case ViewInputEvent::D: value += Qt::Key_D; break; case ViewInputEvent::E: value += Qt::Key_E; break; case ViewInputEvent::F: value += Qt::Key_F; break; case ViewInputEvent::G: value += Qt::Key_G; break; case ViewInputEvent::H: value += Qt::Key_H; break; case ViewInputEvent::I: value += Qt::Key_I; break; case ViewInputEvent::J: value += Qt::Key_J; break; case ViewInputEvent::K: value += Qt::Key_K; break; case ViewInputEvent::L: value += Qt::Key_L; break; case ViewInputEvent::M: value += Qt::Key_M; break; case ViewInputEvent::N: value += Qt::Key_N; break; case ViewInputEvent::O: value += Qt::Key_O; break; case ViewInputEvent::P: value += Qt::Key_P; break; case ViewInputEvent::Q: value += Qt::Key_Q; break; case ViewInputEvent::R: value += Qt::Key_R; break; case ViewInputEvent::S: value += Qt::Key_S; break; case ViewInputEvent::T: value += Qt::Key_T; break; case ViewInputEvent::U: value += Qt::Key_U; break; case ViewInputEvent::V: value += Qt::Key_V; break; case ViewInputEvent::W: value += Qt::Key_W; break; case ViewInputEvent::X: value += Qt::Key_X; break; case ViewInputEvent::Y: value += Qt::Key_Y; break; case ViewInputEvent::Z: value += Qt::Key_Z; break; case ViewInputEvent::Esc: value += Qt::Key_Escape; break; case ViewInputEvent::Space: value += Qt::Key_Space; break; default: DILAY_IMPOSSIBLE; } return QKeySequence (value); } QString toQString (ViewInputEvent event) { switch (event) { case ViewInputEvent::A: return QObject::tr ("A"); case ViewInputEvent::B: return QObject::tr ("B"); case ViewInputEvent::C: return QObject::tr ("C"); case ViewInputEvent::D: return QObject::tr ("D"); case ViewInputEvent::E: return QObject::tr ("E"); case ViewInputEvent::F: return QObject::tr ("F"); case ViewInputEvent::G: return QObject::tr ("G"); case ViewInputEvent::H: return QObject::tr ("H"); case ViewInputEvent::I: return QObject::tr ("I"); case ViewInputEvent::J: return QObject::tr ("J"); case ViewInputEvent::K: return QObject::tr ("K"); case ViewInputEvent::L: return QObject::tr ("L"); case ViewInputEvent::M: return QObject::tr ("M"); case ViewInputEvent::N: return QObject::tr ("N"); case ViewInputEvent::O: return QObject::tr ("O"); case ViewInputEvent::P: return QObject::tr ("P"); case ViewInputEvent::Q: return QObject::tr ("Q"); case ViewInputEvent::R: return QObject::tr ("R"); case ViewInputEvent::S: return QObject::tr ("S"); case ViewInputEvent::T: return QObject::tr ("T"); case ViewInputEvent::U: return QObject::tr ("U"); case ViewInputEvent::V: return QObject::tr ("V"); case ViewInputEvent::W: return QObject::tr ("W"); case ViewInputEvent::X: return QObject::tr ("X"); case ViewInputEvent::Y: return QObject::tr ("Y"); case ViewInputEvent::Z: return QObject::tr ("Z"); case ViewInputEvent::Esc: return QObject::tr ("Esc"); case ViewInputEvent::Space: return QObject::tr ("Space"); case ViewInputEvent::MouseLeft: return QObject::tr ("Left"); case ViewInputEvent::MouseMiddle: return QObject::tr ("Middle"); case ViewInputEvent::MouseWheel: return QObject::tr ("Wheel"); case ViewInputEvent::MouseRight: return QObject::tr ("Right"); default: DILAY_IMPOSSIBLE; } } QString toQString (ViewInputModifier modifier) { switch (modifier) { case ViewInputModifier::None: return ""; case ViewInputModifier::Ctrl: return QObject::tr ("Ctrl"); case ViewInputModifier::Shift: return QObject::tr ("Shift"); case ViewInputModifier::Alt: return QObject::tr ("Alt"); default: DILAY_IMPOSSIBLE; } } QString toQString (ViewInputEvent event, ViewInputModifier modifier) { const QString sEvent = toQString (event); const QString sModifier = toQString (modifier); if (sModifier.isEmpty ()) { return sEvent; } else { return sModifier + QString ("+") + sEvent; } } } ================================================ FILE: lib/src/view/input.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_INPUT #define DILAY_VIEW_INPUT class QKeySequence; class QString; enum class ViewInputEvent { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Esc, Space, MouseLeft, MouseMiddle, MouseWheel, MouseRight }; enum class ViewInputModifier { None, Ctrl, Shift, Alt }; namespace ViewInput { QKeySequence toQKeySequence (ViewInputEvent, ViewInputModifier); QString toQString (ViewInputEvent); QString toQString (ViewInputModifier); QString toQString (ViewInputEvent, ViewInputModifier); } #endif ================================================ FILE: lib/src/view/key-event.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "view/key-event.hpp" ViewKeyEvent::ViewKeyEvent (const QKeyEvent& event, bool press) : _key (Qt::Key (event.key ())) , _pressEvent (press) , _releaseEvent (not press) { } ================================================ FILE: lib/src/view/key-event.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_KEY_EVENT #define DILAY_VIEW_KEY_EVENT #include class QKeyEvent; class ViewKeyEvent { public: explicit ViewKeyEvent (const QKeyEvent&, bool); Qt::Key key () const { return this->_key; } bool pressEvent () const { return this->_pressEvent; } bool releaseEvent () const { return this->_releaseEvent; } private: Qt::Key _key; bool _pressEvent; bool _releaseEvent; }; #endif ================================================ FILE: lib/src/view/light.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "color.hpp" #include "view/light.hpp" struct ViewLight::Impl { glm::vec3 position; Color color; float irradiance; Impl (const glm::vec3& p, const Color& c, float i) : position (p) , color (c) , irradiance (i) { } }; DELEGATE3_BIG6 (ViewLight, const glm::vec3&, const Color&, float) GETTER_CONST (const glm::vec3&, ViewLight, position) GETTER_CONST (const Color&, ViewLight, color) GETTER_CONST (float, ViewLight, irradiance) SETTER (const glm::vec3&, ViewLight, position) SETTER (const Color&, ViewLight, color) SETTER (float, ViewLight, irradiance) ================================================ FILE: lib/src/view/light.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_LIGHT #define DILAY_VIEW_LIGHT #include #include "macro.hpp" class Color; class ViewLight { public: DECLARE_BIG6 (ViewLight, const glm::vec3&, const Color&, float); const glm::vec3& position () const; const Color& color () const; float irradiance () const; void position (const glm::vec3&); void color (const Color&); void irradiance (float); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/log.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include #include #include "../util.hpp" #include "view/log.hpp" #include "view/main-window.hpp" #include "view/util.hpp" QString ViewLog::logPath () { return QDir::temp ().filePath ("dilay.log"); } QString ViewLog::crashLogPath () { return QDir::temp ().filePath ("dilay-crash.log"); } void ViewLog::show (ViewMainWindow& window) { QDialog dialog (&window); QVBoxLayout* layout = new QVBoxLayout; QTextEdit* textEdit = new QTextEdit (&dialog); textEdit->setReadOnly (true); textEdit->setLineWrapMode (QTextEdit::NoWrap); if (QFile (ViewLog::logPath ()).exists ()) { const std::string content = Util::readFile (ViewLog::logPath ().toStdString ()); textEdit->setPlainText ("-- LOG ----------------------------------"); textEdit->append (QString::fromStdString (content)); textEdit->append (""); } if (QFile (ViewLog::crashLogPath ()).exists ()) { const std::string content = Util::readFile (ViewLog::crashLogPath ().toStdString ()); textEdit->append ("-- CRASH LOG ----------------------------"); textEdit->append (QString::fromStdString (content)); textEdit->append (""); } QDialogButtonBox* buttons = new QDialogButtonBox (QDialogButtonBox::Close); QPushButton* ctc = buttons->addButton (QObject::tr ("Copy to clipboard"), QDialogButtonBox::ActionRole); QObject::connect (buttons, &QDialogButtonBox::rejected, [&dialog]() { dialog.reject (); }); ViewUtil::connect (*ctc, [textEdit]() { if (QGuiApplication::clipboard ()) { QGuiApplication::clipboard ()->setText (textEdit->toPlainText ()); } else { DILAY_WARN ("Could not access clipboard"); } }); layout->addWidget (textEdit); layout->addWidget (buttons); dialog.setFixedWidth (100 * QFontMetrics (textEdit->currentFont ()).width ("x")); dialog.setFixedHeight (25 * QFontMetrics (textEdit->currentFont ()).height ()); dialog.setLayout (layout); dialog.setWindowTitle (QObject::tr ("Log")); dialog.exec (); } ================================================ FILE: lib/src/view/log.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_LOG #define DILAY_VIEW_LOG #include class ViewMainWindow; namespace ViewLog { QString logPath (); QString crashLogPath (); void show (ViewMainWindow&); } #endif ================================================ FILE: lib/src/view/main-window.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "view/gl-widget.hpp" #include "view/info-pane.hpp" #include "view/info-pane/scene.hpp" #include "view/main-window.hpp" #include "view/menu-bar.hpp" #include "view/tool-pane.hpp" #include "view/util.hpp" struct ViewMainWindow::Impl { ViewMainWindow* self; ViewGlWidget& glWidget; ViewToolPane& toolPane; ViewInfoPane& infoPane; Impl (ViewMainWindow* s, Config& config, Cache& cache) : self (s) , glWidget (*new ViewGlWidget (*this->self, config, cache)) , toolPane (*new ViewToolPane (this->glWidget)) , infoPane (*new ViewInfoPane (*this->self)) { this->self->setCentralWidget (&this->glWidget); this->self->addDockWidget (Qt::LeftDockWidgetArea, &this->toolPane); this->self->addDockWidget (Qt::RightDockWidgetArea, &this->infoPane); ViewMenuBar::setup (*this->self, this->glWidget); } void update () { this->self->QMainWindow::update (); this->glWidget.update (); this->infoPane.scene ().updateInfo (); } void closeEvent (QCloseEvent* e) { #ifndef NDEBUG e->accept (); #else if (ViewUtil::question (*this->self, QObject::tr ("Do you want to quit?"))) { e->accept (); } else { e->ignore (); } #endif } }; DELEGATE2_BIG2_SELF (ViewMainWindow, Config&, Cache&) GETTER (ViewGlWidget&, ViewMainWindow, glWidget) GETTER (ViewToolPane&, ViewMainWindow, toolPane) GETTER (ViewInfoPane&, ViewMainWindow, infoPane) DELEGATE (void, ViewMainWindow, update) DELEGATE1 (void, ViewMainWindow, closeEvent, QCloseEvent*) ================================================ FILE: lib/src/view/main-window.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_MAIN_WINDOW #define DILAY_VIEW_MAIN_WINDOW #include #include "macro.hpp" class Cache; class Config; class QCloseEvent; class ViewGlWidget; class ViewInfoPane; class ViewToolPane; class ViewMainWindow : public QMainWindow { Q_OBJECT public: DECLARE_BIG2 (ViewMainWindow, Config&, Cache&) ViewGlWidget& glWidget (); ViewToolPane& toolPane (); ViewInfoPane& infoPane (); void update (); protected: void closeEvent (QCloseEvent*); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/menu-bar.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "../util.hpp" #include "history.hpp" #include "scene.hpp" #include "state.hpp" #include "tool/move-camera.hpp" #include "view/configuration.hpp" #include "view/floor-plane.hpp" #include "view/gl-widget.hpp" #include "view/info-pane.hpp" #include "view/info-pane/scene.hpp" #include "view/log.hpp" #include "view/main-window.hpp" #include "view/menu-bar.hpp" #include "view/util.hpp" namespace { QString getFileDialogPath (const Scene& scene) { return scene.hasFileName () ? QString (scene.fileName ().c_str ()) : QStandardPaths::standardLocations (QStandardPaths::HomeLocation).front (); } QString filterAllFiles () { return QObject::tr ("All files (*.*)"); } QString filterDlyFiles () { return QObject::tr ("Dilay files (*.dly)"); } QString filterObjFiles () { return QObject::tr ("Wavefront files (*.obj)"); } QString fileDialogFilters () { return filterAllFiles () + ";;" + filterDlyFiles () + ";;" + filterObjFiles (); } QString selectedFilter (const Scene& scene) { if (scene.hasFileName ()) { if (Util::hasSuffix (scene.fileName (), ".dly")) { return filterDlyFiles (); } else if (Util::hasSuffix (scene.fileName (), ".obj")) { return filterObjFiles (); } } return filterAllFiles (); } } void ViewMenuBar::setup (ViewMainWindow& mainWindow, ViewGlWidget& glWidget) { QMenuBar& menuBar = *mainWindow.menuBar (); QMenu& fileMenu = *menuBar.addMenu (QObject::tr ("&File")); QMenu& editMenu = *menuBar.addMenu (QObject::tr ("&Edit")); QMenu& viewMenu = *menuBar.addMenu (QObject::tr ("&View")); QMenu& helpMenu = *menuBar.addMenu (QObject::tr ("&Help")); ViewUtil::addAction ( fileMenu, QObject::tr ("&Open..."), QKeySequence::Open, [&mainWindow, &glWidget]() { Scene& scene = glWidget.state ().scene (); QString filter = filterAllFiles (); const std::string fileName = QFileDialog::getOpenFileName (&mainWindow, QObject::tr ("Open"), getFileDialogPath (scene), fileDialogFilters (), &filter, QFileDialog::DontUseNativeDialog) .toStdString (); if (fileName.empty () == false) { #ifndef NDEBUG scene.reset (); glWidget.state ().history ().reset (); #else if (scene.isEmpty () == false) { if (ViewUtil::question (mainWindow, QObject::tr ("Replace existent scene?"))) { scene.reset (); glWidget.state ().history ().reset (); } else { glWidget.state ().history ().snapshotAll (scene); } } #endif if (scene.fromDlyFile (glWidget.state ().config (), fileName) == false) { ViewUtil::error (mainWindow, QObject::tr ("Could not open file.")); } mainWindow.update (); } }); QAction& saveAsAction = ViewUtil::addAction ( fileMenu, QObject::tr ("Save &as..."), QKeySequence::SaveAs, [&mainWindow, &glWidget]() { Scene& scene = glWidget.state ().scene (); QString filter = selectedFilter (scene); const std::string fileName = QFileDialog::getSaveFileName (&mainWindow, QObject::tr ("Save as"), getFileDialogPath (scene), fileDialogFilters (), &filter, QFileDialog::DontUseNativeDialog) .toStdString (); if (fileName.empty () == false) { const bool saveAsObj = Util::hasSuffix (fileName, ".obj") || filter == filterObjFiles (); if (scene.toDlyFile (fileName, saveAsObj) == false) { ViewUtil::error (mainWindow, QObject::tr ("Could not save to file.")); } else if (saveAsObj && scene.numSketchMeshes () > 0) { ViewUtil::info (mainWindow, QObject::tr ("Sketches are omitted when saving Wavefront files.")); } } }); ViewUtil::addAction (fileMenu, QObject::tr ("&Save"), QKeySequence::Save, [&mainWindow, &glWidget, &saveAsAction]() { Scene& scene = glWidget.state ().scene (); if (scene.hasFileName ()) { const bool saveAsObj = Util::hasSuffix (scene.fileName (), ".obj"); if (scene.toDlyFile (saveAsObj) == false) { ViewUtil::error (mainWindow, QObject::tr ("Could not save to file.")); } } else { saveAsAction.trigger (); } }); fileMenu.addSeparator (); ViewUtil::addAction (fileMenu, QObject::tr ("&Quit"), QKeySequence::Quit, [&mainWindow]() { mainWindow.close (); }); ViewUtil::addAction (editMenu, QObject::tr ("&Undo"), QKeySequence::Undo, [&glWidget]() { glWidget.state ().undo (); }); ViewUtil::addAction (editMenu, QObject::tr ("&Redo"), QKeySequence::Redo, [&glWidget]() { glWidget.state ().redo (); }); ViewUtil::addAction ( editMenu, QObject::tr ("&Configuration..."), QKeySequence (), [&mainWindow, &glWidget]() { ViewConfiguration::show (mainWindow, glWidget); }); ViewUtil::addAction (viewMenu, QObject::tr ("Toggle &info pane"), Qt::CTRL + Qt::Key_I, [&mainWindow]() { if (mainWindow.infoPane ().isVisible ()) { mainWindow.infoPane ().close (); } else { mainWindow.infoPane ().show (); } }); viewMenu.addSeparator (); ViewUtil::addAction (viewMenu, QObject::tr ("&Snap camera"), Qt::SHIFT + Qt::Key_C, [&glWidget]() { glWidget.immediateMoveCamera ().snap (); }); ViewUtil::addAction (viewMenu, QObject::tr ("Reset &gaze point"), Qt::ALT + Qt::Key_C, [&glWidget]() { glWidget.immediateMoveCamera ().resetGazePoint (); }); viewMenu.addSeparator (); ViewUtil::addAction (viewMenu, QObject::tr ("Toggle &wireframe"), Qt::Key_W, [&mainWindow, &glWidget]() { glWidget.state ().scene ().toggleWireframe (); mainWindow.update (); }); ViewUtil::addAction (viewMenu, QObject::tr ("Toggle &shading"), Qt::SHIFT + Qt::Key_W, [&mainWindow, &glWidget]() { glWidget.state ().scene ().toggleShading (); mainWindow.update (); }); ViewUtil::addCheckableAction (viewMenu, QObject::tr ("Show &floor plane"), QKeySequence (), false, [&mainWindow, &glWidget](bool a) { glWidget.floorPlane ().isActive (a); mainWindow.update (); }); ViewUtil::addAction (helpMenu, QObject::tr ("&Manual..."), QKeySequence (), [&mainWindow]() { if (QDesktopServices::openUrl (QUrl ("http://abau.org/dilay/manual.html")) == false) { ViewUtil::error (mainWindow, QObject::tr ("Could not open manual.")); } }); ViewUtil::addAction (helpMenu, QObject::tr ("&View log..."), QKeySequence (), [&mainWindow]() { ViewLog::show (mainWindow); }); ViewUtil::addAction (helpMenu, QObject::tr ("&About Dilay..."), QKeySequence (), [&mainWindow]() { ViewUtil::about ( mainWindow, QString ("Dilay " DILAY_VERSION " - ") + QObject::tr ("a 3D sculpting application") + QString ("\n\n") + QString ("Copyright © 2015-2018 Alexander Bau") + QString ("\n\n") + QObject::tr ("Use and redistribute under the terms of the GNU General Public License")); }); } ================================================ FILE: lib/src/view/menu-bar.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_MENU_BAR #define DILAY_VIEW_MENU_BAR class ViewGlWidget; class ViewMainWindow; namespace ViewMenuBar { void setup (ViewMainWindow&, ViewGlWidget&); } #endif ================================================ FILE: lib/src/view/pointing-event.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include "config.hpp" #include "view/pointing-event.hpp" namespace { Qt::MouseButton fromButtons (const Qt::MouseButtons& buttons) { if (buttons.testFlag (Qt::LeftButton)) { return Qt::LeftButton; } else if (buttons.testFlag (Qt::MiddleButton)) { return Qt::MiddleButton; } else if (buttons.testFlag (Qt::RightButton)) { return Qt::RightButton; } else { return Qt::NoButton; } } } ViewPointingEvent::ViewPointingEvent (const QMouseEvent& event) : _modifiers (event.modifiers ()) , _pressEvent (event.type () == QEvent::MouseButtonPress) , _moveEvent (event.type () == QEvent::MouseMove) , _releaseEvent (event.type () == QEvent::MouseButtonRelease) , _button (fromButtons (this->_moveEvent ? event.buttons () : event.button ())) , _position (glm::ivec2 (event.x (), event.y ())) , _prevPosition (_position) , _intensity (1.0f) { } ViewPointingEvent::ViewPointingEvent (const Config& config, const QTabletEvent& event) : _modifiers (QGuiApplication::queryKeyboardModifiers ()) , _pressEvent (event.type () == QEvent::TabletPress) , _moveEvent (event.type () == QEvent::TabletMove) , _releaseEvent (event.type () == QEvent::TabletRelease) , _button (fromButtons (this->_moveEvent ? event.buttons () : event.button ())) , _position (glm::ivec2 (event.x (), event.y ())) , _prevPosition (_position) , _intensity (config.get ("editor/tablet-pressure-intensity") * event.pressure ()) { } ViewPointingEvent::ViewPointingEvent (const ViewPointingEvent& e, const glm::ivec2& prevPos) : _modifiers (e._modifiers) , _pressEvent (e._pressEvent) , _moveEvent (e._moveEvent) , _releaseEvent (e._releaseEvent) , _button (e._button) , _position (e._position) , _prevPosition (prevPos) , _intensity (e._intensity) { } bool ViewPointingEvent::valid () const { return this->pressEvent () || this->moveEvent () || this->releaseEvent (); } bool ViewPointingEvent::leftButton () const { return this->_button == Qt::LeftButton; } bool ViewPointingEvent::middleButton () const { return this->_button == Qt::MiddleButton; } bool ViewPointingEvent::rightButton () const { return this->_button == Qt::RightButton; } ================================================ FILE: lib/src/view/pointing-event.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_POINTING_EVENT #define DILAY_VIEW_POINTING_EVENT #include #include class Config; class QMouseEvent; class QTabletEvent; class ViewPointingEvent { public: explicit ViewPointingEvent (const QMouseEvent&); explicit ViewPointingEvent (const Config&, const QTabletEvent&); explicit ViewPointingEvent (const ViewPointingEvent&, const glm::ivec2&); bool valid () const; bool leftButton () const; bool middleButton () const; bool rightButton () const; Qt::KeyboardModifiers modifiers () const { return this->_modifiers; } bool pressEvent () const { return this->_pressEvent; } bool moveEvent () const { return this->_moveEvent; } bool releaseEvent () const { return this->_releaseEvent; } const glm::ivec2& position () const { return this->_position; } glm::ivec2 delta () const { return this->_position - this->_prevPosition; } float intensity () const { return this->_intensity; } private: Qt::KeyboardModifiers _modifiers; bool _pressEvent; bool _moveEvent; bool _releaseEvent; Qt::MouseButton _button; glm::ivec2 _position; glm::ivec2 _prevPosition; float _intensity; }; #endif ================================================ FILE: lib/src/view/resolution-slider.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "view/resolution-slider.hpp" #include "view/util.hpp" struct ViewResolutionSlider::Impl { Impl (ViewResolutionSlider* s, float min, float max) { ViewDoubleSlider* doubleSlider = s; ViewUtil::connect (*doubleSlider, [s, min, max](float r) { emit s->resolutionChanged (max + min - r); }); } }; DELEGATE_BIG2_BASE (ViewResolutionSlider, (float min, float max), (this, min, max), ViewDoubleSlider, (2, 1)) ================================================ FILE: lib/src/view/resolution-slider.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_RESOLUTION_SLIDER #define DILAY_VIEW_RESOLUTION_SLIDER #include "view/double-slider.hpp" class ViewResolutionSlider : public ViewDoubleSlider { Q_OBJECT public: DECLARE_BIG2 (ViewResolutionSlider, float, float) signals: void resolutionChanged (float); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/shortcut.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "view/input.hpp" #include "view/shortcut.hpp" namespace { typedef ViewShortcut::Call Call; } struct ViewShortcut::Impl { ViewInputEvent event; ViewInputModifier modifier; QString label; Call call; Impl (const ViewInputEvent& e, const ViewInputModifier& m, const QString& l, Call&& c) : event (e) , modifier (m) , label (l) , call (std::move (c)) { } Impl (const ViewInputEvent& e, const QString& l, Call&& c) : Impl (e, ViewInputModifier::None, l, std::move (c)) { } QShortcut& toQShortcut (QWidget& parent) const { const QKeySequence keys = ViewInput::toQKeySequence (this->event, this->modifier); QShortcut& shortcut = *new QShortcut (keys, &parent); QObject::connect (&shortcut, &QShortcut::activated, this->call); return shortcut; } }; DELEGATE3_BIG6 (ViewShortcut, const ViewInputEvent&, const QString&, Call&&) DELEGATE4_CONSTRUCTOR (ViewShortcut, const ViewInputEvent&, const ViewInputModifier&, const QString&, Call&&) GETTER_CONST (ViewInputEvent, ViewShortcut, event) GETTER_CONST (ViewInputModifier, ViewShortcut, modifier) GETTER_CONST (const QString&, ViewShortcut, label) GETTER_CONST (const Call&, ViewShortcut, call) DELEGATE1_CONST (QShortcut&, ViewShortcut, toQShortcut, QWidget&) ================================================ FILE: lib/src/view/shortcut.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_SHORTCUT #define DILAY_VIEW_SHORTCUT #include #include "macro.hpp" enum class ViewInputEvent; enum class ViewInputModifier; class QShortcut; class QString; class QWidget; class ViewShortcut { public: typedef std::function Call; DECLARE_BIG6 (ViewShortcut, const ViewInputEvent&, const QString&, Call&&) ViewShortcut (const ViewInputEvent&, const ViewInputModifier&, const QString&, Call&&); ViewInputEvent event () const; ViewInputModifier modifier () const; const QString& label () const; const Call& call () const; QShortcut& toQShortcut (QWidget&) const; private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/tool-pane.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include "state.hpp" #include "tools.hpp" #include "view/gl-widget.hpp" #include "view/tool-pane.hpp" #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ViewToolPane::Impl { typedef std::unordered_map Buttons; ViewToolPane* self; ViewGlWidget& glWidget; QVBoxLayout& layout; QTabWidget& toolSelection; ViewTwoColumnGrid& properties; Buttons buttons; Impl (ViewToolPane* s, ViewGlWidget& g) : self (s) , glWidget (g) , layout (*new QVBoxLayout) , toolSelection (*new QTabWidget) , properties (*new ViewTwoColumnGrid) { QScrollArea* scrollArea = new QScrollArea; QWidget* pane = new QWidget; this->initializeToolSelection (); this->layout.setContentsMargins (0, 0, 0, 0); this->layout.setSpacing (0); this->layout.addWidget (&this->toolSelection); this->layout.addWidget (&this->properties); this->layout.addStretch (1); scrollArea->setWidgetResizable (true); scrollArea->setWidget (pane); pane->setLayout (&this->layout); this->self->setWindowTitle (QObject::tr ("Tools")); this->self->setWidget (scrollArea); this->self->setFeatures (DockWidgetMovable); this->self->setAllowedAreas (Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); } void initializeToolSelection () { this->toolSelection.addTab (this->initalizeSculptSelection (), QObject::tr ("Sculpt")); this->toolSelection.addTab (this->initalizeSketchSelection (), QObject::tr ("Sketch")); QObject::connect (&this->toolSelection, &QTabWidget::currentChanged, [this](int) { this->glWidget.state ().resetTool (); ViewUtil::adjustSize (this->toolSelection); }); } void addToolButton (ToolKey key, QLayout* layout, const QString& name) { QPushButton& button = ViewUtil::pushButton (name); this->buttons.emplace (key, &button); button.setCheckable (true); ViewUtil::connect (button, [this, key]() { this->glWidget.state ().setTool (key); }); layout->addWidget (&button); } QWidget* initalizeSculptSelection () { QWidget* toolPane = new QWidget; QVBoxLayout* toolPaneLayout = new QVBoxLayout; toolPane->setLayout (toolPaneLayout); this->addToolButton (ToolKey::NewMesh, toolPaneLayout, QObject::tr ("01234567890123456789")); this->addToolButton (ToolKey::DeleteMesh, toolPaneLayout, QObject::tr ("Delete mesh")); this->addToolButton (ToolKey::TransformMesh, toolPaneLayout, QObject::tr ("Transform mesh")); toolPaneLayout->addWidget (&ViewUtil::horizontalLine ()); this->addToolButton (ToolKey::SculptDraw, toolPaneLayout, QObject::tr ("Draw")); this->addToolButton (ToolKey::SculptCrease, toolPaneLayout, QObject::tr ("Crease")); this->addToolButton (ToolKey::SculptGrab, toolPaneLayout, QObject::tr ("Grab")); this->addToolButton (ToolKey::SculptPinch, toolPaneLayout, QObject::tr ("Pinch")); toolPaneLayout->addWidget (&ViewUtil::horizontalLine ()); this->addToolButton (ToolKey::SculptSmooth, toolPaneLayout, QObject::tr ("Smooth")); this->addToolButton (ToolKey::SculptFlatten, toolPaneLayout, QObject::tr ("Flatten")); this->addToolButton (ToolKey::SculptReduce, toolPaneLayout, QObject::tr ("Reduce")); toolPaneLayout->addWidget (&ViewUtil::horizontalLine ()); this->addToolButton (ToolKey::Remesh, toolPaneLayout, QObject::tr ("Remesh")); this->addToolButton (ToolKey::TrimMesh, toolPaneLayout, QObject::tr ("Trim")); toolPaneLayout->addStretch (1); return toolPane; } QWidget* initalizeSketchSelection () { QWidget* toolPane = new QWidget; QVBoxLayout* toolPaneLayout = new QVBoxLayout; toolPane->setLayout (toolPaneLayout); this->addToolButton (ToolKey::EditSketch, toolPaneLayout, QObject::tr ("Edit sketch")); this->addToolButton (ToolKey::DeleteSketch, toolPaneLayout, QObject::tr ("Delete sketch")); toolPaneLayout->addWidget (&ViewUtil::horizontalLine ()); this->addToolButton (ToolKey::SketchSpheres, toolPaneLayout, QObject::tr ("Sketch spheres")); toolPaneLayout->addWidget (&ViewUtil::horizontalLine ()); this->addToolButton (ToolKey::ConvertSketch, toolPaneLayout, QObject::tr ("Convert sketch")); toolPaneLayout->addStretch (1); return toolPane; } void forceWidth () { const auto it = this->buttons.find (ToolKey::NewMesh); assert (it != this->buttons.end ()); it->second->setText (QObject::tr ("New mesh")); } ViewToolPaneSelection selection () const { switch (this->toolSelection.currentIndex ()) { case 0: return ViewToolPaneSelection::Sculpt; case 1: return ViewToolPaneSelection::Sketch; default: DILAY_IMPOSSIBLE } } void setButtonState (ToolKey key, bool state) { auto it = this->buttons.find (key); if (it != this->buttons.end ()) { it->second->setChecked (state); } } QString buttonText (ToolKey key) const { auto it = this->buttons.find (key); assert (it != this->buttons.end ()); return it->second->text (); } }; DELEGATE_BIG2_BASE (ViewToolPane, (ViewGlWidget & g, QWidget* p), (this, g), QDockWidget, (p)) GETTER (ViewTwoColumnGrid&, ViewToolPane, properties) DELEGATE (void, ViewToolPane, forceWidth) DELEGATE_CONST (ViewToolPaneSelection, ViewToolPane, selection) DELEGATE2 (void, ViewToolPane, setButtonState, ToolKey, bool) DELEGATE1_CONST (QString, ViewToolPane, buttonText, ToolKey) ================================================ FILE: lib/src/view/tool-pane.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_TOOL_PANE #define DILAY_VIEW_TOOL_PANE #include #include "macro.hpp" enum class ToolKey; class QPushButton; class ViewGlWidget; class ViewTwoColumnGrid; enum class ViewToolPaneSelection { Sculpt, Sketch }; class ViewToolPane : public QDockWidget { public: DECLARE_BIG2 (ViewToolPane, ViewGlWidget&, QWidget* = nullptr) ViewTwoColumnGrid& properties (); void forceWidth (); ViewToolPaneSelection selection () const; void setButtonState (ToolKey, bool); QString buttonText (ToolKey) const; private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/tool-tip.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "../util.hpp" #include "view/tool-tip.hpp" struct ViewToolTip::Impl { typedef std::tuple Tip; std::vector tips; void render (const std::function& f) const { for (auto& t : this->tips) { f (ViewInput::toQString (std::get<0> (t), std::get<1> (t)), std::get<2> (t)); } } void add (ViewInputEvent event, ViewInputModifier modifier, const QString& tip) { this->tips.push_back (std::make_tuple (event, modifier, tip)); } void add (ViewInputEvent event, const QString& tip) { this->add (event, ViewInputModifier::None, tip); } void reset () { this->tips.clear (); } bool isEmpty () const { return this->tips.empty (); } }; DELEGATE_BIG6 (ViewToolTip) DELEGATE1_CONST (void, ViewToolTip, render, const std::function&) DELEGATE3 (void, ViewToolTip, add, ViewInputEvent, ViewInputModifier, const QString&) DELEGATE2 (void, ViewToolTip, add, ViewInputEvent, const QString&) DELEGATE (void, ViewToolTip, reset) DELEGATE_CONST (bool, ViewToolTip, isEmpty) ================================================ FILE: lib/src/view/tool-tip.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_TOOL_TIP #define DILAY_VIEW_TOOL_TIP #include #include "macro.hpp" #include "view/input.hpp" class ViewToolTip { public: DECLARE_BIG6 (ViewToolTip) void render (const std::function&) const; void add (ViewInputEvent, ViewInputModifier, const QString&); void add (ViewInputEvent, const QString&); void reset (); bool isEmpty () const; private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/two-column-grid.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include "view/two-column-grid.hpp" #include "view/util.hpp" struct ViewTwoColumnGrid::Impl { ViewTwoColumnGrid* self; QGridLayout& layout; unsigned int numRows; Impl (ViewTwoColumnGrid* s) : self (s) , layout (*new QGridLayout (this->self)) , numRows (0) { this->layout.setColumnStretch (0, 0); this->layout.setColumnStretch (1, 1); } void setEqualColumnStretch () { this->layout.setColumnStretch (0, 1); this->layout.setColumnStretch (1, 1); } void add (QWidget& widget) { this->layout.addWidget (&widget, this->numRows, 0, 1, 2); this->layout.setRowStretch (this->numRows, 0); this->numRows++; } void add (const QString& labelLeft, const QString& labelRight) { this->add (*new QLabel (labelLeft), *new QLabel (labelRight)); } void add (const QString& label, QWidget& widget) { this->add (*new QLabel (label), widget); } void add (QWidget& w1, QWidget& w2) { this->layout.addWidget (&w1, this->numRows, 0); this->layout.addWidget (&w2, this->numRows, 1); this->layout.setRowStretch (this->numRows, 0); this->numRows++; } void add (QButtonGroup& group) { for (QAbstractButton* button : group.buttons ()) { this->add (*button); } } void addStacked (const QString& labelText, QWidget& widget) { QVBoxLayout& stack = *new QVBoxLayout; QLabel& label = *new QLabel (labelText); label.setAlignment (Qt::AlignHCenter); stack.addWidget (&label); stack.addWidget (&widget); this->layout.addLayout (&stack, this->numRows, 0, 1, 2); this->layout.setRowStretch (this->numRows, 0); this->numRows++; } void addStacked (const QString& labelText, QButtonGroup& group) { QVBoxLayout& stack = *new QVBoxLayout; QLabel& label = *new QLabel (labelText); label.setAlignment (Qt::AlignHCenter); stack.addWidget (&label); for (QAbstractButton* button : group.buttons ()) { stack.addWidget (button); } this->layout.addLayout (&stack, this->numRows, 0, 1, 2); this->layout.setRowStretch (this->numRows, 0); this->numRows++; } void addLeft (const QString& label) { this->add (label, *new QWidget); } void addCenter (const QString& labelText) { QLabel& label = *new QLabel (labelText); label.setAlignment (Qt::AlignHCenter); this->add (label); } void addStretcher () { this->add (*new QWidget, *new QWidget); this->layout.setRowStretch (this->numRows, 1); } void addSeparator () { this->add (ViewUtil::horizontalLine ()); } void reset () { QWidget* widget = nullptr; while ((widget = this->self->findChild ())) { delete widget; } this->numRows = 0; } }; DELEGATE_BIG2_BASE (ViewTwoColumnGrid, (QWidget * p), (this), QWidget, (p)) GETTER_CONST (unsigned int, ViewTwoColumnGrid, numRows) DELEGATE (void, ViewTwoColumnGrid, setEqualColumnStretch) DELEGATE1 (void, ViewTwoColumnGrid, add, QWidget&) DELEGATE2 (void, ViewTwoColumnGrid, add, const QString&, const QString&) DELEGATE2 (void, ViewTwoColumnGrid, add, const QString&, QWidget&) DELEGATE2 (void, ViewTwoColumnGrid, add, QWidget&, QWidget&) DELEGATE1 (void, ViewTwoColumnGrid, add, QButtonGroup&) DELEGATE2 (void, ViewTwoColumnGrid, addStacked, const QString&, QWidget&) DELEGATE2 (void, ViewTwoColumnGrid, addStacked, const QString&, QButtonGroup&) DELEGATE1 (void, ViewTwoColumnGrid, addLeft, const QString&) DELEGATE1 (void, ViewTwoColumnGrid, addCenter, const QString&) DELEGATE (void, ViewTwoColumnGrid, addStretcher) DELEGATE (void, ViewTwoColumnGrid, addSeparator) DELEGATE (void, ViewTwoColumnGrid, reset) ================================================ FILE: lib/src/view/two-column-grid.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_TWO_COLUMN_GRID #define DILAY_VIEW_TWO_COLUMN_GRID #include #include #include "macro.hpp" class QButtonGroup; class QString; class ViewTwoColumnGrid : public QWidget { public: DECLARE_BIG2 (ViewTwoColumnGrid, QWidget* = nullptr) unsigned int numRows () const; void setEqualColumnStretch (); void add (QWidget&); void add (const QString&, const QString&); void add (const QString&, QWidget&); void add (QWidget&, QWidget&); void add (QButtonGroup&); void addStacked (const QString&, QWidget&); void addStacked (const QString&, QButtonGroup&); void addLeft (const QString&); void addCenter (const QString&); void addStretcher (); void addSeparator (); void reset (); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/view/util.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "../util.hpp" #include "view/double-slider.hpp" #include "view/resolution-slider.hpp" #include "view/util.hpp" namespace { void setupDoubleSlider (ViewDoubleSlider& slider, float min, float value, float max) { slider.setDoubleRange (min, max); slider.setDoubleValue (value); slider.setDoubleSingleStep ((max - min) / 10.0f); slider.setDoublePageStep ((max - min) / 10.0f); slider.setTracking (true); slider.setOrientation (Qt::Horizontal); } } QSpinBox& ViewUtil::spinBox (int min, int value, int max, int stepSize) { QSpinBox& spinBox = *new QSpinBox; spinBox.setRange (min, max); spinBox.setValue (value); spinBox.setSingleStep (stepSize); return spinBox; } QDoubleSpinBox& ViewUtil::spinBox (float min, float value, float max, float stepSize) { QDoubleSpinBox& spinBox = *new QDoubleSpinBox; spinBox.setValue (double(value)); spinBox.setRange (min, max); spinBox.setSingleStep (stepSize); spinBox.setDecimals (2); return spinBox; } QPushButton& ViewUtil::pushButton (const QString& label, bool isDefaultButton) { QPushButton& button = *new QPushButton (label); button.setDefault (isDefaultButton); return button; } QToolButton& ViewUtil::toolButton (const QString& label) { QToolButton& button = *new QToolButton (); button.setText (label); return button; } QRadioButton& ViewUtil::radioButton (const QString& label, bool isChecked) { QRadioButton& button = *new QRadioButton (label); button.setChecked (isChecked); return button; } QCheckBox& ViewUtil::checkBox (const QString& label, bool isChecked) { QCheckBox& box = *new QCheckBox (label); box.setChecked (isChecked); return box; } QSlider& ViewUtil::slider (int min, int value, int max) { QSlider& slider = *new QSlider; slider.setRange (min, max); slider.setValue (value); slider.setSingleStep (1); slider.setPageStep (1); slider.setTracking (true); slider.setOrientation (Qt::Horizontal); return slider; } ViewDoubleSlider& ViewUtil::slider (unsigned short numDecimals, float min, float value, float max, unsigned short order) { ViewDoubleSlider& slider = *new ViewDoubleSlider (numDecimals, order); setupDoubleSlider (slider, min, value, max); return slider; } ViewResolutionSlider& ViewUtil::resolutionSlider (float min, float value, float max) { ViewResolutionSlider& slider = *new ViewResolutionSlider (min, max); setupDoubleSlider (slider, min, max + min - value, max); return slider; } QButtonGroup& ViewUtil::buttonGroup (const std::vector& labels) { QButtonGroup& group = *new QButtonGroup; int id = 0; for (const QString& label : labels) { QRadioButton& button = ViewUtil::radioButton (label); group.addButton (&button, id); id++; } return group; } QFrame& ViewUtil::horizontalLine () { QFrame& frame = *new QFrame; frame.setFrameShape (QFrame::HLine); frame.setFrameShadow (QFrame::Sunken); return frame; } QWidget& ViewUtil::emptyWidget () { return *new QWidget; } QLineEdit& ViewUtil::lineEdit (float value, unsigned short numDecimals) { return ViewUtil::lineEdit (Util::minFloat (), value, Util::maxFloat (), numDecimals); } QLineEdit& ViewUtil::lineEdit (float min, float value, float max, unsigned short numDecimals) { QLineEdit& edit = *new QLineEdit; QDoubleValidator& validator = *new QDoubleValidator (&edit); validator.setRange (min, max, numDecimals); edit.setValidator (&validator); edit.setText (QString::number (value, 'f', numDecimals)); return edit; } QLineEdit& ViewUtil::lineEdit (int value) { QLineEdit& edit = *new QLineEdit; edit.setText (QString::number (value)); return edit; } QLineEdit& ViewUtil::lineEdit (int min, int value, int max) { QLineEdit& edit = ViewUtil::lineEdit (value); QIntValidator& validator = *new QIntValidator (&edit); validator.setRange (min, max); edit.setValidator (&validator); return edit; } glm::uvec2 ViewUtil::toUVec2 (const QPoint& p) { assert (p.x () >= 0); assert (p.y () >= 0); return glm::uvec2 (p.x (), p.y ()); } glm::ivec2 ViewUtil::toIVec2 (const QPoint& p) { return glm::ivec2 (p.x (), p.y ()); } QPoint ViewUtil::toQPoint (const glm::uvec2& p) { return QPoint (int(p.x), int(p.y)); } QPoint ViewUtil::toQPoint (const glm::ivec2& p) { return QPoint (p.x, p.y); } void ViewUtil::connect (const QSpinBox& s, const std::function& f) { void (QSpinBox::*ptr) (int) = &QSpinBox::valueChanged; QObject::connect (&s, ptr, f); } void ViewUtil::connect (const QDoubleSpinBox& s, const std::function& f) { void (QDoubleSpinBox::*ptr) (double) = &QDoubleSpinBox::valueChanged; QObject::connect (&s, ptr, f); } void ViewUtil::connect (const QPushButton& b, const std::function& f) { QObject::connect (&b, &QPushButton::released, f); } void ViewUtil::connect (const QButtonGroup& g, int initial, const std::function& f) { void (QButtonGroup::*ptr) (int) = &QButtonGroup::buttonReleased; QObject::connect (&g, ptr, f); g.button (initial)->click (); } void ViewUtil::connect (const QCheckBox& c, const std::function& f) { QObject::connect (&c, &QCheckBox::stateChanged, [f](int state) { if (state == Qt::Unchecked) { f (false); } else if (state == Qt::Checked) { f (true); } }); } void ViewUtil::connect (const QRadioButton& r, const std::function& f) { QObject::connect (&r, &QRadioButton::clicked, f); } void ViewUtil::connect (const QSlider& s, const std::function& f) { QObject::connect (&s, &QSlider::valueChanged, f); } void ViewUtil::connect (const ViewResolutionSlider& s, const std::function& f) { QObject::connect (&s, &ViewResolutionSlider::resolutionChanged, f); } void ViewUtil::connect (const ViewDoubleSlider& s, const std::function& f) { QObject::connect (&s, &ViewDoubleSlider::doubleValueChanged, f); } void ViewUtil::connect (const QAction& a, const std::function& f) { QObject::connect (&a, &QAction::triggered, f); } void ViewUtil::connectFloat (const QLineEdit& e, const std::function& f) { QObject::connect (&e, &QLineEdit::textEdited, [&e, f](const QString& text) { if (e.hasAcceptableInput ()) { bool ok; float value = text.toFloat (&ok); assert (ok); f (value); } }); } void ViewUtil::connectInt (const QLineEdit& e, const std::function& f) { QObject::connect (&e, &QLineEdit::textEdited, [&e, f](const QString& text) { if (e.hasAcceptableInput ()) { bool ok; float value = text.toInt (&ok); assert (ok); f (value); } }); } QWidget& ViewUtil::stretcher (bool horizontal, bool vertical) { assert (horizontal || vertical); QWidget& widget = *new QWidget (); widget.setSizePolicy (horizontal ? QSizePolicy::Expanding : QSizePolicy::Preferred, vertical ? QSizePolicy::Expanding : QSizePolicy::Preferred); return widget; } void ViewUtil::deselect (QAbstractSpinBox& spinBox) { spinBox.findChild ()->deselect (); } void ViewUtil::adjustSize (QTabWidget& tab) { const int current = tab.currentIndex (); for (int i = 0; i < tab.count (); i++) { if (i == current) { tab.widget (i)->setSizePolicy (QSizePolicy::Preferred, QSizePolicy::Preferred); } else { tab.widget (i)->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored); } } } bool ViewUtil::question (QWidget& parent, const QString& label) { return QMessageBox::question (&parent, label, label) == QMessageBox::Yes; } void ViewUtil::error (QWidget& parent, const QString& label) { QMessageBox::critical (&parent, QObject::tr ("Error"), label); } void ViewUtil::about (QWidget& parent, const QString& label) { QMessageBox::about (&parent, QObject::tr ("About Dilay"), label); } void ViewUtil::info (QWidget& parent, const QString& label) { QMessageBox::information (&parent, QObject::tr ("Information"), label); } QAction& ViewUtil::addAction (QMenu& menu, const QString& label, const QKeySequence& keySequence, const std::function& f) { QAction* a = new QAction (label, &menu); a->setShortcut (keySequence); menu.addAction (a); QObject::connect (a, &QAction::triggered, f); return *a; } QAction& ViewUtil::addCheckableAction (QMenu& menu, const QString& label, const QKeySequence& keySequence, bool state, const std::function& f) { QAction* a = new QAction (label, &menu); a->setShortcut (keySequence); a->setCheckable (true); a->setChecked (state); menu.addAction (a); QObject::connect (a, &QAction::toggled, f); return *a; } ================================================ FILE: lib/src/view/util.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef VIEW_UTIL #define VIEW_UTIL #include #include #include class ViewDoubleSlider; class ViewResolutionSlider; class QAbstractSpinBox; class QAction; class QButtonGroup; class QCheckBox; class QDoubleSpinBox; class QFrame; class QKeySequence; class QLineEdit; class QMenu; class QPoint; class QPushButton; class QRadioButton; class QSlider; class QSpinBox; class QString; class QTabWidget; class QToolButton; class QWidget; namespace ViewUtil { QSpinBox& spinBox (int, int, int, int = 1); QDoubleSpinBox& spinBox (float, float, float, float); QPushButton& pushButton (const QString&, bool = false); QToolButton& toolButton (const QString&); QRadioButton& radioButton (const QString&, bool = false); QCheckBox& checkBox (const QString&, bool = false); QSlider& slider (int, int, int); ViewDoubleSlider& slider (unsigned short, float, float, float, unsigned short = 1); ViewResolutionSlider& resolutionSlider (float, float, float); QButtonGroup& buttonGroup (const std::vector&); QFrame& horizontalLine (); QWidget& emptyWidget (); QLineEdit& lineEdit (float, unsigned short = 2); QLineEdit& lineEdit (float, float, float, unsigned short = 2); QLineEdit& lineEdit (int); QLineEdit& lineEdit (int, int, int); glm::uvec2 toUVec2 (const QPoint&); glm::ivec2 toIVec2 (const QPoint&); QPoint toQPoint (const glm::uvec2&); QPoint toQPoint (const glm::ivec2&); void connect (const QSpinBox&, const std::function&); void connect (const QDoubleSpinBox&, const std::function&); void connect (const QPushButton&, const std::function&); void connect (const QButtonGroup&, int, const std::function&); void connect (const QCheckBox&, const std::function&); void connect (const QRadioButton&, const std::function&); void connect (const QSlider&, const std::function&); void connect (const ViewResolutionSlider&, const std::function&); void connect (const ViewDoubleSlider&, const std::function&); void connect (const QAction&, const std::function&); void connectFloat (const QLineEdit&, const std::function&); void connectInt (const QLineEdit&, const std::function&); QWidget& stretcher (bool, bool); void select (QButtonGroup&, int); void deselect (QAbstractSpinBox&); void adjustSize (QTabWidget&); bool question (QWidget&, const QString&); void error (QWidget&, const QString&); void about (QWidget&, const QString&); void info (QWidget&, const QString&); QAction& addAction (QMenu&, const QString&, const QKeySequence&, const std::function&); QAction& addCheckableAction (QMenu&, const QString&, const QKeySequence&, bool, const std::function&); }; #endif ================================================ FILE: lib/src/view/vector-edit.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "view/util.hpp" #include "view/vector-edit.hpp" struct ViewVectorEdit::Impl { ViewVectorEdit* self; glm::vec3 vectorData; QLineEdit* edit[3]; static const int numDecimals = 2; Impl (ViewVectorEdit* s, const glm::vec3& v) : self (s) , vectorData (v) { QVBoxLayout* layout = new QVBoxLayout; layout->setSpacing (0); layout->setContentsMargins (0, 11, 0, 11); this->self->setLayout (layout); for (int i = 0; i <= 2; i++) { this->edit[i] = &ViewUtil::lineEdit (v[i], Impl::numDecimals); ViewUtil::connectFloat (*this->edit[i], [this, i](float v) { this->vectorData[i] = v; emit this->self->vectorEdited (this->vectorData); }); layout->addWidget (this->edit[i]); } }; void vector (const glm::vec3& v) { this->x (v.x); this->y (v.y); this->z (v.z); } void x (float v) { this->changeComponent (0, v); } void y (float v) { this->changeComponent (1, v); } void z (float v) { this->changeComponent (2, v); } void changeComponent (int i, float v) { this->vectorData[i] = v; this->edit[i]->setText (QString::number (v, 'f', Impl::numDecimals)); } }; DELEGATE_BIG2_BASE (ViewVectorEdit, (const glm::vec3& v, QWidget* p), (this, v), QWidget, (p)) DELEGATE1 (void, ViewVectorEdit, vector, const glm::vec3&) DELEGATE1 (void, ViewVectorEdit, x, float) DELEGATE1 (void, ViewVectorEdit, y, float) DELEGATE1 (void, ViewVectorEdit, z, float) ================================================ FILE: lib/src/view/vector-edit.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_VIEW_VECTOR_EDIT #define DILAY_VIEW_VECTOR_EDIT #include #include #include "macro.hpp" class ViewVectorEdit : public QWidget { Q_OBJECT public: DECLARE_BIG2 (ViewVectorEdit, const glm::vec3&, QWidget* = nullptr) void vector (const glm::vec3&); void x (float); void y (float); void z (float); signals: void vectorEdited (const glm::vec3&); private: IMPLEMENTATION }; #endif ================================================ FILE: lib/src/xml-conversion.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "color.hpp" #include "xml-conversion.hpp" bool XmlConversion::fromDomElement (QDomElement e, float& v) { assert (e.attributeNode ("type").value () == "float"); bool ok = true; v = e.text ().toFloat (&ok); return ok; } bool XmlConversion::fromDomElement (QDomElement e, int& v) { assert (e.attributeNode ("type").value () == "integer"); bool ok = true; v = e.text ().toInt (&ok); return ok; } bool XmlConversion::fromDomElement (QDomElement e, bool& v) { assert (e.attributeNode ("type").value () == "boolean"); bool ok = true; v = e.text ().toInt (&ok) != 0; return ok; } bool XmlConversion::fromDomElement (QDomElement e, glm::vec3& v) { assert (e.attributeNode ("type").value () == "vector3f"); const bool okX = XmlConversion::fromDomElement (e.firstChildElement ("x"), v.x); const bool okY = XmlConversion::fromDomElement (e.firstChildElement ("y"), v.y); const bool okZ = XmlConversion::fromDomElement (e.firstChildElement ("z"), v.z); return okX && okY && okZ; } bool XmlConversion::fromDomElement (QDomElement e, glm::ivec2& v) { assert (e.attributeNode ("type").value () == "vector2i"); const bool okX = XmlConversion::fromDomElement (e.firstChildElement ("x"), v.x); const bool okY = XmlConversion::fromDomElement (e.firstChildElement ("y"), v.y); return okX && okY; } bool XmlConversion::fromDomElement (QDomElement e, Color& v) { assert (e.attributeNode ("type").value () == "color"); float tmp; bool okR = XmlConversion::fromDomElement (e.firstChildElement ("r"), tmp); v.r (tmp); bool okG = XmlConversion::fromDomElement (e.firstChildElement ("g"), tmp); v.g (tmp); bool okB = XmlConversion::fromDomElement (e.firstChildElement ("b"), tmp); v.b (tmp); bool okOpacity = true; if (e.firstChildElement ("opacity").isNull () == false) { okOpacity = XmlConversion::fromDomElement (e.firstChildElement ("opacity"), tmp); v.opacity (tmp); } return okR && okG && okB && okOpacity; } QDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const float& v) { elem.setAttribute ("type", "float"); elem.appendChild (doc.createTextNode (std::to_string (v).c_str ())); return elem; } QDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const int& v) { elem.setAttribute ("type", "integer"); elem.appendChild (doc.createTextNode (std::to_string (v).c_str ())); return elem; } QDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const bool& v) { elem.setAttribute ("type", "boolean"); elem.appendChild (doc.createTextNode (std::to_string (v ? 1 : 0).c_str ())); return elem; } QDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const glm::vec3& v) { elem.setAttribute ("type", "vector3f"); QDomElement x = doc.createElement ("x"); QDomElement y = doc.createElement ("y"); QDomElement z = doc.createElement ("z"); elem.appendChild (XmlConversion::toDomElement (doc, x, v.x)); elem.appendChild (XmlConversion::toDomElement (doc, y, v.y)); elem.appendChild (XmlConversion::toDomElement (doc, z, v.z)); return elem; } QDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const glm::ivec2& v) { elem.setAttribute ("type", "vector2i"); QDomElement x = doc.createElement ("x"); QDomElement y = doc.createElement ("y"); elem.appendChild (XmlConversion::toDomElement (doc, x, v.x)); elem.appendChild (XmlConversion::toDomElement (doc, y, v.y)); return elem; } QDomElement& XmlConversion::toDomElement (QDomDocument& doc, QDomElement& elem, const Color& v) { elem.setAttribute ("type", "color"); QDomElement r = doc.createElement ("r"); QDomElement g = doc.createElement ("g"); QDomElement b = doc.createElement ("b"); elem.appendChild (XmlConversion::toDomElement (doc, r, v.r ())); elem.appendChild (XmlConversion::toDomElement (doc, g, v.g ())); elem.appendChild (XmlConversion::toDomElement (doc, b, v.b ())); if (v.isOpaque () == false) { QDomElement opacity = doc.createElement ("opacity"); elem.appendChild (XmlConversion::toDomElement (doc, opacity, v.opacity ())); } return elem; } ================================================ FILE: lib/src/xml-conversion.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_CONFIG_CONVERSION #define DILAY_CONFIG_CONVERSION #include class QDomDocument; class QDomElement; class Color; namespace XmlConversion { bool fromDomElement (QDomElement, float&); bool fromDomElement (QDomElement, int&); bool fromDomElement (QDomElement, bool&); bool fromDomElement (QDomElement, glm::vec3&); bool fromDomElement (QDomElement, glm::ivec2&); bool fromDomElement (QDomElement, Color&); QDomElement& toDomElement (QDomDocument&, QDomElement&, const float&); QDomElement& toDomElement (QDomDocument&, QDomElement&, const int&); QDomElement& toDomElement (QDomDocument&, QDomElement&, const bool&); QDomElement& toDomElement (QDomDocument&, QDomElement&, const glm::vec3&); QDomElement& toDomElement (QDomDocument&, QDomElement&, const glm::ivec2&); QDomElement& toDomElement (QDomDocument&, QDomElement&, const Color&); } #endif ================================================ FILE: test/src/main.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "test-bitset.hpp" #include "test-distance.hpp" #include "test-intersection.hpp" #include "test-maybe.hpp" #include "test-misc.hpp" #include "test-octree.hpp" #include "test-prune.hpp" #include "test-tree.hpp" int main () { QCoreApplication::setApplicationName ("dilay"); TestIntersection::test1 (); TestIntersection::test2 (); TestMaybe::test1 (); TestMaybe::test2 (); TestMaybe::test3 (); TestOctree::test (); TestBitset::test (); TestTree::test1 (); TestTree::test2 (); TestTree::test3 (); TestMisc::test (); TestDistance::test (); TestPrune::test (); std::cout << "all tests ran successfully\n"; return 0; } ================================================ FILE: test/src/test-bitset.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "bitset.hpp" #include "test-bitset.hpp" void TestBitset::test () { Bitset bs; assert (bs.get<0> () == false); assert (bs.get<8 * sizeof (unsigned int) - 1> () == false); bs.toggle<0> (); bs.toggle<8 * sizeof (unsigned int) - 1> (); // bs.toggle <8 * sizeof (unsigned int)> (); // must not compile assert (bs.get<0> ()); assert (bs.get<1> () == false); assert (bs.get<8 * sizeof (unsigned int) - 1> ()); assert (bs.value () == std::pow (2, 8 * sizeof (unsigned int) - 1) + 1); bs.reset (); assert (bs.none ()); bs.set<0> (); bs.set<1> (); bs.set<2> (); assert (bs.none () == false); assert (bs.all<2> ()); assert (bs.all<3> ()); assert (bs.all<4> () == false); assert (bs.value () == 7); } ================================================ FILE: test/src/test-bitset.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TEST_BITSET #define DILAY_TEST_BITSET namespace TestBitset { void test (); } #endif ================================================ FILE: test/src/test-distance.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "distance.hpp" #include "primitive/cylinder.hpp" #include "test-distance.hpp" #include "util.hpp" void TestDistance::test () { using Distance::distance; const float eps = Util::epsilon (); PrimCylinder cyl (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (1.0f, 0.0f, 0.0f), 0.5f); assert (glm::epsilonEqual (distance (cyl, glm::vec3 (0.5f, 1.3f, 0.0f)), 0.8f, eps)); assert (glm::epsilonEqual (distance (cyl, glm::vec3 (0.1f, 0.0f, 0.0f)), -0.1f, eps)); assert (glm::epsilonEqual (distance (cyl, glm::vec3 (0.9f, 0.0f, 0.0f)), -0.1f, eps)); assert (glm::epsilonEqual (distance (cyl, glm::vec3 (0.5f, 0.4f, 0.0f)), -0.1f, eps)); assert (glm::epsilonEqual (distance (cyl, glm::vec3 (-0.3f, 0.3f, 0.0f)), 0.3f, eps)); assert (glm::epsilonEqual (distance (cyl, glm::vec3 (1.7f, 0.3f, 0.0f)), 0.7f, eps)); assert (glm::epsilonEqual (distance (cyl, glm::vec3 (-2.0f, 2.0f, 0.0f)), glm::sqrt ((1.5f * 1.5f) + (2.0f * 2.0f)), eps)); assert (glm::epsilonEqual (distance (cyl, glm::vec3 (2.0f, 2.0f, 0.0f)), glm::sqrt ((1.5f * 1.5f) + (1.0f * 1.0f)), eps)); unused (eps); } ================================================ FILE: test/src/test-distance.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TEST_DISTANCE #define DILAY_TEST_DISTANCE namespace TestDistance { void test (); } #endif ================================================ FILE: test/src/test-intersection.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "intersection.hpp" #include "primitive/aabox.hpp" #include "primitive/cone.hpp" #include "primitive/cylinder.hpp" #include "primitive/plane.hpp" #include "primitive/ray.hpp" #include "primitive/sphere.hpp" #include "primitive/triangle.hpp" #include "test-intersection.hpp" #include "util.hpp" void TestIntersection::test1 () { using IntersectionUtil::intersects; const glm::vec3 v1 (0.0f, 0.0f, 0.0f); const glm::vec3 v2 (2.0f, 0.0f, 0.0f); const glm::vec3 v3 (0.0f, 2.0f, 0.0f); PrimTriangle tri (v1, v2, v3); PrimSphere sph (glm::vec3 (0.0f, 0.0f, 0.0f), 1.0f); PrimPlane pln (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)); PrimAABox abx (glm::vec3 (0.0f, 0.0f, 0.0f), 1.0f); PrimCylinder cyl (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f), 1.0f); PrimCone cne (glm::vec3 (0.0f, 0.0f, 0.0f), 1.0f, glm::vec3 (0.0f, 1.0f, 0.0f), 0.5f); float t = 0.0f; assert (intersects (PrimRay (glm::vec3 (0.1f, 0.1f, 1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), tri, false, nullptr)); assert (intersects (PrimRay (glm::vec3 (0.1f, 0.1f, -1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), tri, false, nullptr) == false); assert (intersects (PrimRay (true, glm::vec3 (0.1f, 0.1f, -1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), tri, false, nullptr)); assert ( intersects (PrimRay (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), sph, &t)); assert (t > 0.0f); assert ( intersects (PrimRay (glm::vec3 (0.0f, 0.0f, 2.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), sph, &t)); assert (t > 0.0f && t < 2.0f); assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, -2.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), sph, &t) == false); assert (intersects (PrimRay (true, glm::vec3 (0.0f, 0.0f, -2.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), sph, &t)); assert (t < 0.0f && t > -2.0f); assert ( intersects (PrimRay (glm::vec3 (0.0f, 1.0f, 0.0f), glm::vec3 (0.0f, -1.0f, 0.0f)), pln, &t)); assert (t > 0.0f); assert ( intersects (PrimRay (glm::vec3 (0.0f, -1.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), pln, &t)); assert (t > 0.0f); assert (intersects (PrimRay (glm::vec3 (0.0f, 1.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), pln, &t) == false); assert (intersects (PrimRay (true, glm::vec3 (0.0f, 1.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), pln, &t)); assert (t < 0.0f); assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, 1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), abx, nullptr)); assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, -1.0f), glm::vec3 (0.0f, 0.0f, 1.0f)), abx, nullptr)); assert (intersects (PrimRay (glm::vec3 (1.5f, 0.0f, 1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), abx, nullptr) == false); assert (intersects (PrimRay (glm::vec3 (1.5f, 0.0f, -1.0f), glm::vec3 (0.0f, 0.0f, 1.0f)), abx, nullptr) == false); assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, -1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), abx, nullptr) == false); assert (intersects (PrimRay (glm::vec3 (0.0f, 0.0f, 1.0f), glm::vec3 (0.0f, 0.0f, 1.0f)), abx, nullptr) == false); assert (intersects (PrimRay (true, glm::vec3 (0.0f, 0.0f, -1.0f), glm::vec3 (0.0f, 0.0f, -1.0f)), abx, nullptr)); assert (intersects (PrimPlane (glm::vec3 (0.0f, 0.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), abx)); assert (intersects (PrimPlane (glm::vec3 (0.0f, 0.4f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), abx)); assert (intersects (PrimPlane (glm::vec3 (0.0f, 0.6f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), abx) == false); assert (intersects (PrimPlane (glm::vec3 (0.0f, 2.0f, 0.0f), glm::vec3 (0.0f, 1.0f, 0.0f)), tri)); assert (intersects (cyl, glm::vec3 (0.0f, -0.1f, 0.0f)) == false); assert (intersects (cyl, glm::vec3 (0.0f, 1.1f, 0.0f)) == false); assert (intersects (cyl, glm::vec3 (1.1f, 0.1f, 0.0f)) == false); assert (intersects (cyl, glm::vec3 (1.0f, 0.0f, 0.0f))); assert (intersects (cyl, glm::vec3 (1.0f, 1.0f, 0.0f))); assert (intersects (cyl, glm::vec3 (0.9f, 0.1f, 0.0f))); assert (intersects (cyl, glm::vec3 (0.1f, 0.9f, 0.0f))); assert (intersects (cne, glm::vec3 (0.0f, -0.1f, 0.0f)) == false); assert (intersects (cne, glm::vec3 (1.0f, 0.1f, 0.0f)) == false); assert (intersects (cne, glm::vec3 (1.0f, 0.0f, 0.0f))); assert (intersects (cne, glm::vec3 (0.5f, 1.0f, 0.0f))); assert (intersects (cne, glm::vec3 (0.8f, 0.1f, 0.0f))); unused (t); } void TestIntersection::test2 () { Intersection i1, i2; i1.update (2.0f, glm::vec3 (2.0f), glm::vec3 (2.0f)); i2.update (1.0f, glm::vec3 (1.0f), glm::vec3 (1.0f)); Intersection::sort (i1, i2); assert (i1.distance () == 1.0f); assert (i1.position () == glm::vec3 (1.0f)); assert (i1.normal () == glm::vec3 (1.0f)); assert (i2.distance () == 2.0f); assert (i2.position () == glm::vec3 (2.0f)); assert (i2.normal () == glm::vec3 (2.0f)); } ================================================ FILE: test/src/test-intersection.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TEST_INTERSECTION #define DILAY_TEST_INTERSECTION namespace TestIntersection { void test1 (); void test2 (); } #endif ================================================ FILE: test/src/test-maybe.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "maybe.hpp" #include "test-maybe.hpp" void TestMaybe::test1 () { Maybe m1 (5); assert (m1.hasValue ()); assert (*m1 == 5); Maybe m2 (m1); assert (*m1 == 5); assert (*m2 == 5); Maybe m3 (std::move (m1)); assert (m1.hasValue () == false); assert (*m3 == 5); m2 = 12; m3 = std::move (m2); assert (m2.hasValue () == false); assert (*m3 == 12); m3 = std::move (m2); assert (m3.hasValue () == false); m3 = 12; m3 = m2; assert (m3.hasValue () == false); m3 = 44; assert (*m3 == 44); int* i = new int(55); m3 = i; assert (*m3 == 55); m3 = nullptr; assert (m3.hasValue () == false); } namespace { class Foo { public: Foo (int d) : _data (d) { } int data () const { return this->_data; } private: int _data; }; } void TestMaybe::test2 () { Maybe m = Maybe::make (5); assert (m.hasValue ()); assert (m->data () == 5); } void TestMaybe::test3 () { Maybe m1 = 5; Maybe m2; assert (m1.hasValue ()); assert (m2.hasValue () == false); m2 = m1.release (); assert (m1.hasValue () == false); assert (m2.hasValue ()); assert (*m2 == 5); } ================================================ FILE: test/src/test-maybe.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TEST_MAYBE #define DILAY_TEST_MAYBE namespace TestMaybe { void test1 (); void test2 (); void test3 (); } #endif ================================================ FILE: test/src/test-misc.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include "test-misc.hpp" #include "util.hpp" void TestMisc::test () { assert (Util::countOnes (0) == 0); assert (Util::countOnes (1) == 1); assert (Util::countOnes (2) == 1); assert (Util::countOnes (3) == 2); assert (Util::countOnes (127) == 7); assert (Util::countOnes (128) == 1); assert (Util::countOnes (255) == 8); assert (Util::countOnes (256) == 1); assert (Util::countOnes (std::numeric_limits::max ()) == sizeof (unsigned int) * 8); } ================================================ FILE: test/src/test-misc.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TEST_MISC #define DILAY_TEST_MISC namespace TestMisc { void test (); } #endif ================================================ FILE: test/src/test-octree.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include #include #include #include "dynamic/octree.hpp" #include "primitive/triangle.hpp" #include "test-octree.hpp" void TestOctree::test () { const unsigned int numSamples = 10000; DynamicOctree octree; octree.setupRoot (glm::vec3 (0.0f), 10.0f); std::default_random_engine gen; std::uniform_real_distribution unitD (0.0f, 1.0f); std::uniform_real_distribution posD (-10.0f, 10.0f); std::uniform_real_distribution scaleD (0.00001f, 10.0f); std::uniform_real_distribution twoPiD (0.0f, 2.0f * glm::pi ()); for (unsigned int i = 0; i < numSamples; i++) { const glm::vec3 m1 (-1.0f, 0.0f, 0.0f); const glm::vec3 m2 (1.0f, 0.0f, 0.0f); const glm::vec3 m3 (0.0f, -1.0f, 0.0f); const glm::mat4x4 translationMatrix = glm::translate (glm::mat4x4 (1.0f), glm::vec3 (posD (gen), posD (gen), posD (gen))); const glm::mat4x4 rotationMatrix = glm::rotate (glm::mat4x4 (1.0f), twoPiD (gen), glm::normalize (glm::vec3 (unitD (gen), unitD (gen), unitD (gen)))); const glm::mat4x4 scalingMatrix = glm::scale (glm::mat4x4 (1.0f), glm::vec3 (scaleD (gen), scaleD (gen), scaleD (gen))); const glm::mat4x4 modelMatrix = translationMatrix * rotationMatrix * scalingMatrix; const glm::vec3 w1 = glm::vec3 (modelMatrix * glm::vec4 (m1, 1.0f)); const glm::vec3 w2 = glm::vec3 (modelMatrix * glm::vec4 (m2, 1.0f)); const glm::vec3 w3 = glm::vec3 (modelMatrix * glm::vec4 (m3, 1.0f)); const PrimTriangle tri = PrimTriangle (w1, w2, w3); octree.addElement (i, tri.center (), tri.maxDimExtent ()); } for (unsigned int i = 0; i < numSamples; i++) { octree.deleteElement (i); } } ================================================ FILE: test/src/test-octree.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TEST_OCTREE #define DILAY_TEST_OCTREE namespace TestOctree { void test (); } #endif ================================================ FILE: test/src/test-prune.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include "test-prune.hpp" #include "util.hpp" namespace { bool equals (std::vector prune, const std::vector& vec, const std::vector& indices) { std::vector pruneIndices; Util::prune (prune, [](int i) { return i < 0; }, &pruneIndices); return std::equal (prune.begin (), prune.end (), vec.begin (), vec.end ()) && std::equal (pruneIndices.begin (), pruneIndices.end (), indices.begin (), indices.end ()); } } void TestPrune::test () { const unsigned int x = Util::invalidIndex (); assert ( 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})); assert (equals ({-1, 2, -3, 4, -5, 6, -7, 8, -9}, {8, 2, 6, 4}, {x, 1, x, 3, x, 2, x, 0, x})); assert (equals ({-1, -2, -3, -4, -5, -6, -7, -8, -9}, {}, {x, x, x, x, x, x, x, x, x})); assert (equals ({-1, -2, -3, -4, -5, -6, -7, -8, 9}, {9}, {x, x, x, x, x, x, x, x, 0})); assert (equals ({1, -2, -3, -4, -5, -6, -7, -8, 9}, {1, 9}, {0, x, x, x, x, x, x, x, 1})); assert (equals ({-1, 2, -3, -4, -5, -6, -7, -8, 9}, {9, 2}, {x, 1, x, x, x, x, x, x, 0})); assert (equals ({-1, -2, -3, -4, -5, -6, 7, 8, 9}, {9, 8, 7}, {x, x, x, x, x, x, 2, 1, 0})); unused (x); unused (equals); } ================================================ FILE: test/src/test-prune.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TEST_PRUNE #define DILAY_TEST_PRUNE namespace TestPrune { void test (); } #endif ================================================ FILE: test/src/test-tree.cpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #include #include "test-tree.hpp" #include "tree.hpp" namespace { struct Foo { int i; Foo (int v) : i (v) { } }; } void TestTree::test1 () { Tree tree; auto& n0 = tree.emplaceRoot (0); auto& n1 = n0.emplaceChild (100); auto& n2 = n1.emplaceChild (200); assert (n1.data ().i == 100); assert (n2.parent () == &n1); assert (tree.root ().numNodes () == 3); assert (n1.lastChild ().data ().i == n2.data ().i); n0.deleteChild (n1); assert (tree.root ().numNodes () == 1); n0.emplaceChild (5); n0.emplaceChild (6).emplaceChild (7); assert (tree.root ().numNodes () == 4); n0.deleteChildIf ([](const auto& c) { return c.data ().i == 6; }); assert (tree.root ().numNodes () == 2); assert (n0.lastChild ().data ().i == 5); Tree copy (tree); tree.reset (); assert (copy.root ().numNodes () == 2); assert (copy.root ().data ().i == 0); assert (copy.root ().lastChild ().data ().i == 5); assert (copy.root ().lastChild ().parent () == ©.root ()); unused (n2); } void TestTree::test2 () { Tree t; t.emplaceRoot (1).emplaceChild (2).emplaceChild (3).emplaceChild (4); assert (t.root ().numNodes () == 4); assert (t.root ().data () == 1); assert (t.root ().lastChild ().data () == 2); assert (t.root ().lastChild ().lastChild ().data () == 3); assert (t.root ().lastChild ().lastChild ().lastChild ().data () == 4); t.rebalance (t.root ().lastChild ().lastChild ().lastChild ()); assert (t.root ().numNodes () == 4); assert (t.root ().data () == 4); assert (t.root ().lastChild ().data () == 3); assert (t.root ().lastChild ().lastChild ().data () == 2); assert (t.root ().lastChild ().lastChild ().lastChild ().data () == 1); } void TestTree::test3 () { Tree t1; TreeNode& node1 = t1.emplaceRoot (1).emplaceChild (2).emplaceChild (3); node1.emplaceChild (4); Tree t2 = t1.split (node1); assert (t1.root ().numNodes () == 2); assert (t1.root ().data () == 1); assert (t1.root ().lastChild ().data () == 2); assert (t2.root ().numNodes () == 2); assert (t2.root ().data () == 3); assert (t2.root ().lastChild ().data () == 4); Tree t3 = t1.split (t1.root ()); assert (t1.hasRoot () == false); assert (t3.root ().numNodes () == 2); assert (t3.root ().data () == 1); assert (t3.root ().lastChild ().data () == 2); } ================================================ FILE: test/src/test-tree.hpp ================================================ /* This file is part of Dilay * Copyright © 2015-2018 Alexander Bau * Use and redistribute under the terms of the GNU General Public License */ #ifndef DILAY_TEST_TREE #define DILAY_TEST_TREE namespace TestTree { void test1 (); void test2 (); void test3 (); } #endif ================================================ FILE: test/test.pro ================================================ include (../common.pri) TEMPLATE = app TARGET = run-tests DESTDIR = $$OUT_PWD/.. DEPENDPATH += src INCLUDEPATH += src $$PWD/../lib/src SOURCES += \ src/main.cpp \ src/test-bitset.cpp \ src/test-distance.cpp \ src/test-intersection.cpp \ src/test-maybe.cpp \ src/test-misc.cpp \ src/test-octree.cpp \ src/test-prune.cpp \ src/test-tree.cpp HEADERS += \ src/test-bitset.hpp \ src/test-distance.hpp \ src/test-intersection.hpp \ src/test-maybe.hpp \ src/test-misc.hpp \ src/test-octree.hpp \ src/test-prune.hpp \ src/test-tree.hpp win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../lib/release/ -ldilay else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../lib/debug/ -ldilay else:unix: LIBS += -L$$OUT_PWD/../lib/ -ldilay win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../lib/release/libdilay.a else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../lib/debug/libdilay.a else:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../lib/release/dilay.lib else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$OUT_PWD/../lib/debug/dilay.lib else:unix: PRE_TARGETDEPS += $$OUT_PWD/../lib/libdilay.a unix { format.commands = clang-format -style=file -i $$SOURCES $$HEADERS QMAKE_EXTRA_TARGETS += format } ================================================ FILE: unix/dilay.desktop ================================================ [Desktop Entry] Type=Application Version=1.0 Name=Dilay Comment=A 3D sculpting application Exec=dilay Icon=dilay Terminal=false Categories=Graphics;3DGraphics; ================================================ FILE: unix/docker/appimage/Dockerfile ================================================ FROM ubuntu:trusty RUN apt-get update RUN apt-get install -y software-properties-common RUN add-apt-repository -y ppa:ubuntu-toolchain-r/test RUN add-apt-repository -y ppa:beineri/opt-qt592-trusty RUN apt-get update RUN apt-get install -y build-essential git qt59base libglm-dev g++-5 libgl1-mesa-dev wget RUN update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 20 COPY entrypoint.sh /usr/bin/ ENTRYPOINT entrypoint.sh ================================================ FILE: unix/docker/appimage/entrypoint.sh ================================================ #!/bin/bash cd /tmp git clone --depth=1 file:///dilay cd /tmp/dilay source /opt/qt*/bin/qt*-env.sh qmake -r PREFIX=/usr make release -j$(nproc) make INSTALL_ROOT=appdir install wget -c -q "https://github.com/probonopd/linuxdeployqt/releases/download/continuous/linuxdeployqt-continuous-x86_64.AppImage" unset QTDIR unset QT_PLUGIN_PATH unset LD_LIBRARY_PATH export VERSION=$(git describe --dirty --tags) # linuxdeployqt uses this for naming the file chmod a+x linuxdeployqt*.AppImage ./linuxdeployqt*.AppImage --appimage-extract ./squashfs-root/AppRun ./app/appdir/usr/share/applications/*.desktop -bundle-non-qt-libs ./squashfs-root/AppRun ./app/appdir/usr/share/applications/*.desktop -appimage mv Dilay*.AppImage /dilay ================================================ FILE: unix/docker/debian-sid/Dockerfile ================================================ FROM debian:sid RUN apt-get update RUN apt-get install -y build-essential git qt5-default qt5-qmake libglm-dev COPY entrypoint.sh /usr/bin/ ENTRYPOINT entrypoint.sh ================================================ FILE: unix/docker/debian-sid/entrypoint.sh ================================================ #!/bin/bash cd /tmp git clone --depth=1 file:///dilay cd /tmp/dilay qmake -r make release -j$(nproc) ================================================ FILE: unix/docker/ubuntu-bionic/Dockerfile ================================================ FROM ubuntu:bionic RUN apt-get update RUN apt-get install -y build-essential git qt5-default qt5-qmake libglm-dev COPY entrypoint.sh /usr/bin/ ENTRYPOINT entrypoint.sh ================================================ FILE: unix/docker/ubuntu-bionic/entrypoint.sh ================================================ #!/bin/bash cd /tmp git clone --depth=1 file:///dilay cd /tmp/dilay qmake -r make release -j$(nproc) ================================================ FILE: unix/docker/ubuntu-trusty/Dockerfile ================================================ FROM ubuntu:trusty RUN apt-get update RUN apt-get install -y software-properties-common RUN add-apt-repository -y ppa:ubuntu-toolchain-r/test RUN add-apt-repository -y ppa:beineri/opt-qt592-trusty RUN apt-get update RUN apt-get install -y build-essential git qt59base libglm-dev g++-5 libgl1-mesa-dev RUN update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 20 COPY entrypoint.sh /usr/bin/ ENTRYPOINT entrypoint.sh ================================================ FILE: unix/docker/ubuntu-trusty/entrypoint.sh ================================================ #!/bin/bash cd /tmp git clone --depth=1 file:///dilay cd /tmp/dilay source /opt/qt*/bin/qt*-env.sh qmake -r make release -j$(nproc) ================================================ FILE: unix/docker/ubuntu-xenial/Dockerfile ================================================ FROM ubuntu:xenial RUN apt-get update RUN apt-get install -y software-properties-common RUN add-apt-repository -y ppa:beineri/opt-qt592-xenial RUN apt-get update RUN apt-get update RUN apt-get install -y build-essential git qt59base libglm-dev libgl1-mesa-dev COPY entrypoint.sh /usr/bin/ ENTRYPOINT entrypoint.sh ================================================ FILE: unix/docker/ubuntu-xenial/entrypoint.sh ================================================ #!/bin/bash cd /tmp git clone --depth=1 file:///dilay cd /tmp/dilay source /opt/qt*/bin/qt*-env.sh qmake -r make release -j$(nproc) ================================================ FILE: win32/LICENSE.rtf ================================================ {\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\lang1031\f0\fs18 GNU GENERAL PUBLIC LICENSE\par Version 3, 29 June 2007\par \par Copyright (C) 2007 Free Software Foundation, Inc. \par Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\par \par Preamble\par \par The GNU General Public License is a free, copyleft license for software and other kinds of works.\par \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par The precise terms and conditions for copying, distribution and modification follow.\par \par TERMS AND CONDITIONS\par \par 0. Definitions.\par \par "This License" refers to version 3 of the GNU General Public License.\par \par "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\par \par "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 \par 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 \par A "covered work" means either the unmodified Program or a work based on the Program.\par \par 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 \par 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 \par 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 \par 1. Source Code.\par \par 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 \par 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 \par 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 \par 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 \par The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\par \par The Corresponding Source for a work in source code form is that same work.\par \par 2. Basic Permissions.\par \par 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 \par 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 \par Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.\par \par 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\par \par 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 \par 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 \par 4. Conveying Verbatim Copies.\par \par 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 \par 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 \par 5. Conveying Modified Source Versions.\par \par 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 \par a) The work must carry prominent notices stating that you modified it, and giving a relevant date.\par \par 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 \par 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 \par 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 \par 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 \par 6. Conveying Non-Source Forms.\par \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par "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 \par 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 \par 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 \par 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 \par 7. Additional Terms.\par \par "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 \par 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 \par 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 \par a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or\par \par 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 \par 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 \par d) Limiting the use for publicity purposes of names of licensors or authors of the material; or\par \par e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or\par \par 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 \par 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 \par 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 \par 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 \par 8. Termination.\par \par 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 \par 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 \par 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 \par 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 \par 9. Acceptance Not Required for Having Copies.\par \par 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 \par 10. Automatic Licensing of Downstream Recipients.\par \par 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 \par 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 \par 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 \par 11. Patents.\par \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par 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 \par 12. No Surrender of Others' Freedom.\par \par 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 \par 13. Use with the GNU Affero General Public License.\par \par 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 \par 14. Revised Versions of this License.\par \par 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 \par 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 \par 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 \par 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 \par 15. Disclaimer of Warranty.\par \par 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 \par 16. Limitation of Liability.\par \par 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 \par 17. Interpretation of Sections 15 and 16.\par \par 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 \par END OF TERMS AND CONDITIONS\par } ================================================ FILE: win32/deploy.bat ================================================ REM Qt's install directory: %1 REM compilation's target directory: %2 REM Dilay's source directory: %3 REM Dilay's version: %4 @echo off if exist win32deploy ( rmdir /s /q win32deploy ) mkdir win32deploy mkdir win32deploy\Dilay xcopy %2\dilay.exe win32deploy\Dilay xcopy %1\bin\libgcc_s_dw2-1.dll win32deploy\Dilay xcopy %1\bin\libstdc++-6.dll win32deploy\Dilay xcopy %1\bin\libwinpthread-1.dll win32deploy\Dilay xcopy %1\bin\Qt5Core.dll win32deploy\Dilay xcopy %1\bin\Qt5Gui.dll win32deploy\Dilay xcopy %1\bin\Qt5Widgets.dll win32deploy\Dilay xcopy %1\bin\Qt5Xml.dll win32deploy\Dilay xcopy %3\win32\icon.ico win32deploy\Dilay xcopy %3\win32\LICENSE.rtf win32deploy\Dilay mkdir win32deploy\Dilay\platforms xcopy %1\plugins\platforms\qwindows.dll win32deploy\Dilay\platforms "%ProgramFiles(x86)%\WiX Toolset v3.11\bin\candle.exe" -dDilayVersion=%4 -out win32deploy/dilay.wixobj %3\win32\installer.wix "%ProgramFiles(x86)%\WiX Toolset v3.11\bin\light.exe" -ext WixUIExtension -b win32deploy -cultures:en-US -out win32deploy/dilay-%4.msi win32deploy/dilay.wixobj ================================================ FILE: win32/installer.wix ================================================