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