@ -0,0 +1,7 @@ | |||||
CMakeFiles | |||||
CMakeCache.txt | |||||
cmake_install.cmake | |||||
Makefile | |||||
build | |||||
src/configuration.hpp | |||||
.DS_Store |
@ -0,0 +1,6 @@ | |||||
[submodule "emergent"] | |||||
path = lib/emergent | |||||
url = https://github.com/cjhoward/emergent.git | |||||
[submodule "data"] | |||||
path = data | |||||
url = https://gitlab.com/cjhoward/antkeeper-data.git |
@ -0,0 +1,181 @@ | |||||
cmake_minimum_required(VERSION 3.7) | |||||
project(antkeeper | |||||
VERSION "0.0.0" | |||||
) | |||||
set(PLATFORM "" CACHE STRING "") | |||||
set(LANGUAGE "en-us" CACHE STRING "") | |||||
# Setup configuration strings | |||||
set(ANTKEEPER_VERSION ${PROJECT_VERSION}) | |||||
set(ANTKEEPER_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) | |||||
set(ANTKEEPER_VERSION_MINOR ${PROJECT_VERSION_MINOR}) | |||||
set(ANTKEEPER_VERSION_PATCH ${PROJECT_VERSION_PATCH}) | |||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug") | |||||
set(ANTKEEPER_BUILD_TYPE debug) | |||||
set(ANTKEEPER_DEBUG ON) | |||||
else() | |||||
set(ANTKEEPER_BUILD_TYPE release) | |||||
set(ANTKEEPER_DEBUG OFF) | |||||
endif() | |||||
# Setup build type paths | |||||
set(BUILD_DIR ${PROJECT_SOURCE_DIR}/build) | |||||
set(BUILD_DEBUG_DIR ${BUILD_DIR}/debug) | |||||
set(BUILD_RELEASE_DIR ${BUILD_DIR}/release) | |||||
# Set package name | |||||
set(PACKAGE_NAME ${PROJECT_NAME}-${PROJECT_VERSION}-${PLATFORM}) | |||||
set(PACKAGE_BUILD_NAME ${PACKAGE_NAME}-${ANTKEEPER_BUILD_TYPE}) | |||||
# Set package directory | |||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug") | |||||
set(PLATFORM_PACKAGE_DIR ${BUILD_DEBUG_DIR}/${PACKAGE_NAME}) | |||||
else() | |||||
set(PLATFORM_PACKAGE_DIR ${BUILD_RELEASE_DIR}/${PACKAGE_NAME}) | |||||
endif() | |||||
# Add Emergent library | |||||
add_subdirectory(${PROJECT_SOURCE_DIR}/lib/emergent) | |||||
set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} ${PROJECT_SOURCE_DIR}/lib/emergent) | |||||
# Find dependencies | |||||
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules) | |||||
find_package(SDL2 REQUIRED) | |||||
find_package(OpenGL REQUIRED) | |||||
# Set C++ compiler flags for debug and release build types | |||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") | |||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} -O0 -g") | |||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS} -O3 -s -DNDEBUG -mwindows") | |||||
# Set C and C++ compiler flags for the target architecture | |||||
if(${PLATFORM} STREQUAL "win32" OR ${PLATFORM} STREQUAL "linux32") | |||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32") | |||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32") | |||||
elseif(${PLATFORM} STREQUAL "win64" OR ${PLATFORM} STREQUAL "linux64") | |||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m64") | |||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m64") | |||||
elseif(${PLATFORM} STREQUAL "osx" AND CMAKE_OSX_ARCHITECTURES STREQUAL "") | |||||
# 32-bit | |||||
#set(CMAKE_OSX_ARCHITECTURES "i386" CACHE STRING "" FORCE) | |||||
# 64-bit | |||||
#set(CMAKE_OSX_ARCHITECTURES "x86_64" CACHE STRING "" FORCE) | |||||
# 96-bit universal | |||||
set(CMAKE_OSX_ARCHITECTURES "x86_64;i386" CACHE STRING "" FORCE) | |||||
endif() | |||||
# Set C++ version | |||||
set(CMAKE_CXX_STANDARD 11) | |||||
set(CMAKE_CXX_STANDARD_REQUIRED ON) | |||||
set(CMAKE_CXX_EXTENSIONS OFF) | |||||
# Find executable source directory | |||||
set(EXECUTABLE_SOURCE_DIR ${PROJECT_SOURCE_DIR}/src) | |||||
# Generate C++ configuration file | |||||
configure_file(${EXECUTABLE_SOURCE_DIR}/configuration.hpp.in ${EXECUTABLE_SOURCE_DIR}/configuration.hpp) | |||||
# Collect executable source files | |||||
set(EXECUTABLE_SOURCES | |||||
${EXECUTABLE_SOURCE_DIR}/configuration.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/windows-dirent.h | |||||
${EXECUTABLE_SOURCE_DIR}/controls.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/render-passes.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/settings.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/settings.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/terrain.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/terrain.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/controls.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/input.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/input.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/main.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/mesh.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/mesh.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/application-state.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/application-state.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/application.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/application.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/states/splash-state.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/states/splash-state.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/states/title-state.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/states/title-state.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/states/experiment-state.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/states/experiment-state.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/ui/ui.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/ui/ui.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/ui/tween.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/ui/tween.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/render-passes.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/ant.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/ant.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/nest.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/nest.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/debug.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/debug.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/camera-controller.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/camera-controller.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/model-loader.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/model-loader.cpp | |||||
${EXECUTABLE_SOURCE_DIR}/material-loader.hpp | |||||
${EXECUTABLE_SOURCE_DIR}/material-loader.cpp | |||||
) | |||||
# Setup exe icon for windows | |||||
if(${PLATFORM} STREQUAL "win32" OR ${PLATFORM} STREQUAL "win64") | |||||
if(EXISTS ${PROJECT_SOURCE_DIR}/data) | |||||
set(RC_FILES "${PROJECT_SOURCE_DIR}/data/icons/icon.rc") | |||||
set(CMAKE_RC_COMPILER_INIT windres) | |||||
enable_language(RC) | |||||
set(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> <FLAGS> -O coff <DEFINES> -i <SOURCE> -o <OBJECT>") | |||||
set(EXECUTABLE_SOURCES "${EXECUTABLE_SOURCES};${RC_FILES}") | |||||
endif() | |||||
endif() | |||||
# Set executable and library output directories | |||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PLATFORM_PACKAGE_DIR}) | |||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PLATFORM_PACKAGE_DIR}) | |||||
# Add executable | |||||
set(EXECUTABLE_NAME antkeeper) | |||||
set(EXECUTABLE_TARGET ${PACKAGE_BUILD_NAME}-executable) | |||||
add_executable(${EXECUTABLE_TARGET} ${EXECUTABLE_SOURCES}) | |||||
set_target_properties(${EXECUTABLE_TARGET} PROPERTIES OUTPUT_NAME ${EXECUTABLE_NAME}) | |||||
# Set include directories | |||||
target_include_directories(${EXECUTABLE_TARGET} PUBLIC | |||||
${PROJECT_SOURCE_DIR}/lib/emergent/include | |||||
${SDL2_INCLUDE_DIRS} | |||||
${OPENGL_INCLUDE_DIRS} | |||||
) | |||||
message("SDL: ${SDL2_LIBRARIES}") | |||||
# Build library list | |||||
list(APPEND EXECUTABLE_LIBRARIES | |||||
m | |||||
#dl | |||||
mingw32 | |||||
#PROBLEM IS LINKING TO STDC++!!!!!!!!!!!!!!!! | |||||
#stdc++ | |||||
emergent | |||||
${SDL2_LIBRARIES} | |||||
${OPENGL_gl_LIBRARY} | |||||
) | |||||
# Link libraries | |||||
target_link_libraries(${EXECUTABLE_TARGET} ${EXECUTABLE_LIBRARIES}) | |||||
# Add run target | |||||
add_custom_target(run | |||||
COMMAND ${EXECUTABLE_TARGET} | |||||
DEPENDS ${EXECUTABLE_TARGET} | |||||
WORKING_DIRECTORY ${PLATFORM_PACKAGE_DIR} | |||||
) | |||||
# Add data subdirectory (if it exists) | |||||
if(EXISTS ${PROJECT_SOURCE_DIR}/data) | |||||
add_subdirectory(${PROJECT_SOURCE_DIR}/data) | |||||
endif() |
@ -0,0 +1,674 @@ | |||||
GNU GENERAL PUBLIC LICENSE | |||||
Version 3, 29 June 2007 | |||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> | |||||
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. | |||||
<one line to give the program's name and a brief idea of what it does.> | |||||
Copyright (C) <year> <name of author> | |||||
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 <http://www.gnu.org/licenses/>. | |||||
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: | |||||
<program> Copyright (C) <year> <name of author> | |||||
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 | |||||
<http://www.gnu.org/licenses/>. | |||||
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 | |||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>. |
@ -0,0 +1,47 @@ | |||||
# Antkeeper | |||||
Antkeeper is an ant colony simulation game. This repository contains all of the source code to Antkeeper. The game data, however, is proprietary and resides in a closed-source Git submodule. | |||||
## Getting Started | |||||
### Prerequisites | |||||
* Git | |||||
* CMake | |||||
* SDL 2 | |||||
* FreeType 2 | |||||
### Download | |||||
Use Git to download the `antkeeper` repository and its submodules: | |||||
git clone --recursive https://github.com/cjhoward/antkeeper.git antkeeper | |||||
### Configuration | |||||
Antkeeper uses the CMake build system for configuration. | |||||
cd antkeeper | |||||
cmake . -G "MinGW Makefiles" -DCMAKE_BUILD_TYPE=Debug -DPLATFORM=win32 -DLANGUAGE=en-us | |||||
### Building | |||||
cmake --build . | |||||
4. Testing | |||||
cmake --build . --target run | |||||
5. Cleaning | |||||
First perform a dry run to check what will be deleted: | |||||
git clean -d -f -x -n | |||||
If there are no issues, clean: | |||||
git clean -d -f -x | |||||
## License | |||||
The source code for Antkeeper is licensed under the GNU General Public License, version 3. See [COPYING](./COPYING) for details. |
@ -0,0 +1,35 @@ | |||||
# - Try to find FREETYPE2 | |||||
# This module defines | |||||
# FREETYPE2_FOUND - System has FREETYPE2 | |||||
# FREETYPE2_INCLUDE_DIRS - The FREETYPE2 include directories | |||||
# FREETYPE2_LIBRARIES - Link to these to use FREETYPE2 | |||||
# Copyright (C) 2011-2014 Christopher J. Howard | |||||
# | |||||
# This file is part of Open Graphics Framework (OGF). | |||||
# | |||||
# OGF 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. | |||||
# | |||||
# OGF 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 OGF. If not, see <http://www.gnu.org/licenses/>. | |||||
find_path(FREETYPE2_INCLUDE_DIR ft2build.h PATH_SUFFIXES include/freetype2 include) | |||||
find_library(FREETYPE2_LIBRARY NAMES freetype) | |||||
set(FREETYPE2_LIBRARIES ${FREETYPE2_LIBRARY}) | |||||
set(FREETYPE2_INCLUDE_DIRS ${FREETYPE2_INCLUDE_DIR}) | |||||
include(FindPackageHandleStandardArgs) | |||||
find_package_handle_standard_args( | |||||
FREETYPE2 DEFAULT_MSG | |||||
FREETYPE2_LIBRARY FREETYPE2_INCLUDE_DIR) | |||||
mark_as_advanced(FREETYPE2_INCLUDE_DIR FREETYPE2_LIBRARY) |
@ -0,0 +1,50 @@ | |||||
# - Try to find SDL2 | |||||
# This module defines | |||||
# SDL2_FOUND - System has SDL2 | |||||
# SDL2_INCLUDE_DIRS - The SDL2 include directories | |||||
# SDL2_LIBRARIES - Link to these to use SDL2 | |||||
# Copyright (C) 2011-2014 Christopher J. Howard | |||||
# | |||||
# This file is part of Open Graphics Framework (OGF). | |||||
# | |||||
# OGF 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. | |||||
# | |||||
# OGF 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 OGF. If not, see <http://www.gnu.org/licenses/>. | |||||
set(SDL2_SEARCH_PATHS | |||||
/) | |||||
find_path(SDL2_INCLUDE_DIR SDL.h | |||||
NAMES SDL2 | |||||
PATH_SUFFIXES include/SDL2 include | |||||
PATHS ${SDL2_SEARCH_PATHS}) | |||||
find_library(SDL2MAIN_LIBRARY | |||||
NAMES SDL2main | |||||
PATH_SUFFIXES lib64 lib | |||||
PATHS ${SDL2_SEARCH_PATHS}) | |||||
find_library(SDL2_LIBRARY | |||||
NAMES SDL2 | |||||
PATH_SUFFIXES lib64 lib | |||||
PATHS ${SDL2_SEARCH_PATHS}) | |||||
set(SDL2_LIBRARIES ${SDL2MAIN_LIBRARY} ${SDL2_LIBRARY}) | |||||
set(SDL2_INCLUDE_DIRS ${SDL2_INCLUDE_DIR}) | |||||
include(FindPackageHandleStandardArgs) | |||||
find_package_handle_standard_args( | |||||
SDL2 DEFAULT_MSG | |||||
SDL2_LIBRARY SDL2MAIN_LIBRARY SDL2_INCLUDE_DIR) | |||||
mark_as_advanced(SDL2_INCLUDE_DIR SDL2_LIBRARY SDL2MAIN_LIBRARY) |
@ -0,0 +1,21 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "ant.hpp" | |||||
@ -0,0 +1,84 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef ANT_HPP | |||||
#define ANT_HPP | |||||
#include <vector> | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
class Gait; | |||||
class Ant | |||||
{ | |||||
public: | |||||
/** | |||||
* Named constants corresponding to leg indices. | |||||
* | |||||
* \_/ | |||||
* L1 --| |-- R1 | |||||
* L2 --| |-- R2 | |||||
* L3 --|_|-- R3 | |||||
*/ | |||||
enum class LegIndex | |||||
{ | |||||
L1, | |||||
L2, | |||||
L3, | |||||
R1, | |||||
R2, | |||||
R3 | |||||
}; | |||||
private: | |||||
Transform transform; | |||||
ModelInstance modelInstance; | |||||
Pose* skeletonPose; | |||||
}; | |||||
class Colony | |||||
{ | |||||
public: | |||||
Ant* spawn(); | |||||
const Model* getAntModel() const; | |||||
Model* getAntModel(); | |||||
const Skeleton* getAntSkeleton() const; | |||||
Skeleton* getSkeleton(); | |||||
private: | |||||
// Rendering | |||||
Model* antModel; | |||||
Skeleton* antSkeleton; | |||||
// Locomotion | |||||
float walkSpeed; | |||||
float turnSpeed; | |||||
Gait* tripodGait; | |||||
Gait* rippleGait; | |||||
Gait* slowWaveGait; | |||||
std::vector<Ant*> ants; | |||||
}; | |||||
#endif // ANT_HPP |
@ -0,0 +1,27 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "application-state.hpp" | |||||
ApplicationState::ApplicationState(Application* application): | |||||
application(application) | |||||
{} | |||||
ApplicationState::~ApplicationState() | |||||
{} |
@ -0,0 +1,48 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef APPLICATION_STATE_HPP | |||||
#define APPLICATION_STATE_HPP | |||||
class Application; | |||||
/** | |||||
* Abstract base class for application states. | |||||
*/ | |||||
class ApplicationState | |||||
{ | |||||
public: | |||||
ApplicationState(Application* application); | |||||
virtual ~ApplicationState(); | |||||
// Run once when the state is initially entered | |||||
virtual void enter() = 0; | |||||
// Run continually while the state is valid | |||||
virtual void execute() = 0; | |||||
// Run once when the state is exited | |||||
virtual void exit() = 0; | |||||
protected: | |||||
Application* application; | |||||
}; | |||||
#endif // APPLICATION_STATE_HPP |
@ -0,0 +1,593 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "application.hpp" | |||||
#include "application-state.hpp" | |||||
#include "states/splash-state.hpp" | |||||
#include "states/title-state.hpp" | |||||
#include "states/experiment-state.hpp" | |||||
#include <cstdlib> | |||||
#include <iostream> | |||||
#include <SDL.h> | |||||
#define OPENGL_VERSION_MAJOR 3 | |||||
#define OPENGL_VERSION_MINOR 3 | |||||
#include "model-loader.hpp" | |||||
#include "material-loader.hpp" | |||||
Application::Application(int argc, char* argv[]): | |||||
state(nullptr), | |||||
nextState(nullptr), | |||||
terminationCode(EXIT_SUCCESS) | |||||
{ | |||||
window = nullptr; | |||||
context = nullptr; | |||||
// Initialize SDL | |||||
std::cout << "Initializing SDL... "; | |||||
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_GAMECONTROLLER) < 0) | |||||
{ | |||||
std::cout << "failed: \"" << SDL_GetError() << "\"" << std::endl; | |||||
close(EXIT_FAILURE); | |||||
return; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Print SDL version strings | |||||
SDL_version compiled; | |||||
SDL_version linked; | |||||
SDL_VERSION(&compiled); | |||||
SDL_GetVersion(&linked); | |||||
std::cout << "Compiled with SDL " << (int)compiled.major << "." << (int)compiled.minor << "." << (int)compiled.patch << std::endl; | |||||
std::cout << "Linking to SDL " << (int)linked.major << "." << (int)linked.minor << "." << (int)linked.patch << std::endl; | |||||
// Find app and user data paths | |||||
appDataPath = std::string(SDL_GetBasePath()) + "data/"; | |||||
userDataPath = SDL_GetPrefPath("cjhoward", "antkeeper"); | |||||
std::cout << "Application data path: \"" << appDataPath << "\"" << std::endl; | |||||
std::cout << "User data path: \"" << userDataPath << "\"" << std::endl; | |||||
// Form pathes to settings files | |||||
defaultSettingsFilename = appDataPath + "default-settings.txt"; | |||||
userSettingsFilename = userDataPath + "settings.txt"; | |||||
// Load default settings | |||||
std::cout << "Loading default settings from \"" << defaultSettingsFilename << "\"... "; | |||||
if (!settings.load(defaultSettingsFilename)) | |||||
{ | |||||
std::cout << "failed" << std::endl; | |||||
close(EXIT_FAILURE); | |||||
return; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Load user settings | |||||
std::cout << "Loading user settings from \"" << userSettingsFilename << "\"... "; | |||||
if (!settings.load(userSettingsFilename)) | |||||
{ | |||||
// Failed, save default settings as user settings | |||||
std::cout << "failed" << std::endl; | |||||
saveUserSettings(); | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Get values of required settings | |||||
settings.get("fullscreen", &fullscreen); | |||||
settings.get("fullscreen_width", &fullscreenWidth); | |||||
settings.get("fullscreen_height", &fullscreenHeight); | |||||
settings.get("windowed_width", &windowedWidth); | |||||
settings.get("windowed_height", &windowedHeight); | |||||
settings.get("swap_interval", &swapInterval); | |||||
// Load strings | |||||
std::string language; | |||||
settings.get("language", &language); | |||||
std::string stringsFile = appDataPath + "strings/" + language + ".txt"; | |||||
std::cout << "Loading strings from \"" << stringsFile << "\"... "; | |||||
if (!strings.load(stringsFile)) | |||||
{ | |||||
std::cout << "failed" << std::endl; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Select OpenGL version | |||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); | |||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, OPENGL_VERSION_MAJOR); | |||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, OPENGL_VERSION_MINOR); | |||||
// Set OpenGL buffer attributes | |||||
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); | |||||
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); | |||||
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); | |||||
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); | |||||
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); | |||||
// Check desktop display mode | |||||
SDL_DisplayMode displayMode; | |||||
if (SDL_GetDesktopDisplayMode(0, &displayMode) != 0) | |||||
{ | |||||
std::cerr << "Failed to get desktop display mode: \"" << SDL_GetError() << "\"" << std::endl; | |||||
close(EXIT_FAILURE); | |||||
return; | |||||
} | |||||
// Check (usable?) display bounds | |||||
SDL_Rect displayBounds; | |||||
if (SDL_GetDisplayBounds(0, &displayBounds) != 0) | |||||
{ | |||||
std::cerr << "Failed to get display bounds: \"" << SDL_GetError() << "\"" << std::endl; | |||||
close(EXIT_FAILURE); | |||||
return; | |||||
} | |||||
// Use display resolution if settings request | |||||
if (windowedWidth == -1 || windowedHeight == -1) | |||||
{ | |||||
windowedWidth = displayBounds.w; | |||||
windowedHeight = displayBounds.h; | |||||
} | |||||
if (fullscreenWidth == -1 || fullscreenHeight == -1) | |||||
{ | |||||
fullscreenWidth = displayMode.w; | |||||
fullscreenHeight = displayMode.h; | |||||
} | |||||
// Determine window parameters | |||||
Uint32 windowFlags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; | |||||
if (fullscreen) | |||||
{ | |||||
width = fullscreenWidth; | |||||
height = fullscreenHeight; | |||||
windowFlags |= SDL_WINDOW_FULLSCREEN; | |||||
} | |||||
else | |||||
{ | |||||
width = windowedWidth; | |||||
height = windowedHeight; | |||||
} | |||||
// Get window title string | |||||
std::string title; | |||||
strings.get("title", &title); | |||||
// Create window | |||||
std::cout << "Creating a window... "; | |||||
window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, windowFlags); | |||||
if (window == nullptr) | |||||
{ | |||||
std::cout << "failed: \"" << SDL_GetError() << "\"" << std::endl; | |||||
close(EXIT_FAILURE); | |||||
return; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Get actual window size | |||||
SDL_GetWindowSize(window, &width, &height); | |||||
if (fullscreen) | |||||
{ | |||||
fullscreenWidth = width; | |||||
fullscreenHeight = height; | |||||
} | |||||
else | |||||
{ | |||||
windowedWidth = width; | |||||
windowedHeight = height; | |||||
} | |||||
// Print video driver | |||||
const char* videoDriver = SDL_GetCurrentVideoDriver(); | |||||
if (!videoDriver) | |||||
{ | |||||
std::cout << "Unable to determine video driver" << std::endl; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "Using video driver \"" << videoDriver << "\"" << std::endl; | |||||
} | |||||
// Create an OpenGL context | |||||
std::cout << "Creating an OpenGL context... "; | |||||
context = SDL_GL_CreateContext(window); | |||||
if (context == nullptr) | |||||
{ | |||||
std::cout << "failed: \"" << SDL_GetError() << "\"" << std::endl; | |||||
close(EXIT_FAILURE); | |||||
return; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Initialize GL3W | |||||
std::cout << "Initializing GL3W... "; | |||||
if (gl3wInit()) | |||||
{ | |||||
std::cout << "failed" << std::endl; | |||||
close(EXIT_FAILURE); | |||||
return; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Check if OpenGL version is supported | |||||
if (!gl3wIsSupported(OPENGL_VERSION_MAJOR, OPENGL_VERSION_MINOR)) | |||||
{ | |||||
std::cout << "OpenGL " << OPENGL_VERSION_MAJOR << "." << OPENGL_VERSION_MINOR << " not supported" << std::endl; | |||||
close(EXIT_FAILURE); | |||||
return; | |||||
} | |||||
// Print OpenGL and GLSL version strings | |||||
std::cout << "Using OpenGL " << glGetString(GL_VERSION) << ", GLSL " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; | |||||
// Set swap interval (vsync) | |||||
if (swapInterval) | |||||
{ | |||||
std::cout << "Enabling vertical sync... "; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "Disabling vertical sync... "; | |||||
} | |||||
if (SDL_GL_SetSwapInterval(swapInterval) != 0) | |||||
{ | |||||
std::cout << "failed: \"" << SDL_GetError() << "\"" << std::endl; | |||||
swapInterval = SDL_GL_GetSwapInterval(); | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Get display DPI | |||||
std::cout << "Getting DPI of display 0... "; | |||||
if (SDL_GetDisplayDPI(0, &dpi, nullptr, nullptr) != 0) | |||||
{ | |||||
std::cerr << "failed: \"" << SDL_GetError() << "\"" << std::endl; | |||||
std::cout << "Reverting to default DPI" << std::endl; | |||||
settings.get("default_dpi", &dpi); | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Print DPI | |||||
std::cout << "Rendering at " << dpi << " DPI" << std::endl; | |||||
// Determine base font size | |||||
settings.get("font_size", &fontSizePT); | |||||
fontSizePX = fontSizePT * (1.0f / 72.0f) * dpi; | |||||
// Print font size | |||||
std::cout << "Base font size is " << fontSizePT << "pt (" << fontSizePX << "px)" << std::endl; | |||||
// Setup input | |||||
inputManager = new SDLInputManager(); | |||||
keyboard = (*inputManager->getKeyboards()).front(); | |||||
mouse = (*inputManager->getMice()).front(); | |||||
// Setup menu navigation controls | |||||
menuControlProfile = new ControlProfile(inputManager); | |||||
menuControlProfile->registerControl("menu_left", &menuLeft); | |||||
menuControlProfile->registerControl("menu_right", &menuRight); | |||||
menuControlProfile->registerControl("menu_up", &menuUp); | |||||
menuControlProfile->registerControl("menu_down", &menuDown); | |||||
menuControlProfile->registerControl("menu_select", &menuSelect); | |||||
menuControlProfile->registerControl("menu_cancel", &menuCancel); | |||||
menuControlProfile->registerControl("toggle_fullscreen", &toggleFullscreen); | |||||
menuControlProfile->registerControl("escape", &escape); | |||||
menuLeft.bindKey(keyboard, SDL_SCANCODE_LEFT); | |||||
menuLeft.bindKey(keyboard, SDL_SCANCODE_A); | |||||
menuRight.bindKey(keyboard, SDL_SCANCODE_RIGHT); | |||||
menuRight.bindKey(keyboard, SDL_SCANCODE_D); | |||||
menuUp.bindKey(keyboard, SDL_SCANCODE_UP); | |||||
menuUp.bindKey(keyboard, SDL_SCANCODE_W); | |||||
menuDown.bindKey(keyboard, SDL_SCANCODE_DOWN); | |||||
menuDown.bindKey(keyboard, SDL_SCANCODE_S); | |||||
menuSelect.bindKey(keyboard, SDL_SCANCODE_RETURN); | |||||
menuSelect.bindKey(keyboard, SDL_SCANCODE_SPACE); | |||||
menuSelect.bindKey(keyboard, SDL_SCANCODE_Z); | |||||
menuCancel.bindKey(keyboard, SDL_SCANCODE_BACKSPACE); | |||||
menuCancel.bindKey(keyboard, SDL_SCANCODE_X); | |||||
toggleFullscreen.bindKey(keyboard, SDL_SCANCODE_F11); | |||||
escape.bindKey(keyboard, SDL_SCANCODE_ESCAPE); | |||||
// Setup in-game controls | |||||
gameControlProfile = new ControlProfile(inputManager); | |||||
gameControlProfile->registerControl("camera-move-forward", &cameraMoveForward); | |||||
gameControlProfile->registerControl("camera-move-back", &cameraMoveBack); | |||||
gameControlProfile->registerControl("camera-move-left", &cameraMoveLeft); | |||||
gameControlProfile->registerControl("camera-move-right", &cameraMoveRight); | |||||
gameControlProfile->registerControl("camera-rotate-cw", &cameraRotateCW); | |||||
gameControlProfile->registerControl("camera-rotate-ccw", &cameraRotateCCW); | |||||
gameControlProfile->registerControl("camera-zoom-in", &cameraZoomIn); | |||||
gameControlProfile->registerControl("camera-zoom-out", &cameraZoomOut); | |||||
gameControlProfile->registerControl("camera-toggle-nest-view", &cameraToggleNestView); | |||||
gameControlProfile->registerControl("camera-toggle-overhead-view", &cameraToggleOverheadView); | |||||
cameraMoveForward.bindKey(keyboard, SDL_SCANCODE_W); | |||||
cameraMoveBack.bindKey(keyboard, SDL_SCANCODE_S); | |||||
cameraMoveLeft.bindKey(keyboard, SDL_SCANCODE_A); | |||||
cameraMoveRight.bindKey(keyboard, SDL_SCANCODE_D); | |||||
cameraRotateCW.bindKey(keyboard, SDL_SCANCODE_Q); | |||||
cameraRotateCCW.bindKey(keyboard, SDL_SCANCODE_E); | |||||
cameraZoomIn.bindKey(keyboard, SDL_SCANCODE_EQUALS); | |||||
cameraZoomOut.bindKey(keyboard, SDL_SCANCODE_MINUS); | |||||
cameraToggleOverheadView.bindKey(keyboard, SDL_SCANCODE_R); | |||||
cameraToggleNestView.bindKey(keyboard, SDL_SCANCODE_F); | |||||
cameraOverheadView = true; | |||||
cameraNestView = false; | |||||
// Allocate states | |||||
splashState = new SplashState(this); | |||||
titleState = new TitleState(this); | |||||
experimentState = new ExperimentState(this); | |||||
// Clear screen to black | |||||
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); | |||||
glClear(GL_COLOR_BUFFER_BIT); | |||||
SDL_GL_SwapWindow(window); | |||||
// Setup loaders | |||||
materialLoader = new MaterialLoader(); | |||||
modelLoader = new ModelLoader(); | |||||
modelLoader->setMaterialLoader(materialLoader); | |||||
// Enter splash state | |||||
state = nextState = splashState; | |||||
state->enter(); | |||||
} | |||||
Application::~Application() | |||||
{ | |||||
SDL_GL_DeleteContext(context); | |||||
SDL_DestroyWindow(window); | |||||
SDL_Quit(); | |||||
} | |||||
int Application::execute() | |||||
{ | |||||
while (state != nullptr) | |||||
{ | |||||
state->execute(); | |||||
if (nextState != state) | |||||
{ | |||||
state->exit(); | |||||
state = nextState; | |||||
if (nextState != nullptr) | |||||
{ | |||||
state->enter(); | |||||
} | |||||
} | |||||
} | |||||
return terminationCode; | |||||
} | |||||
void Application::changeState(ApplicationState* state) | |||||
{ | |||||
nextState = state; | |||||
} | |||||
void Application::setTerminationCode(int code) | |||||
{ | |||||
terminationCode = code; | |||||
} | |||||
void Application::close(int terminationCode) | |||||
{ | |||||
setTerminationCode(terminationCode); | |||||
changeState(nullptr); | |||||
} | |||||
void Application::changeFullscreen() | |||||
{ | |||||
fullscreen = !fullscreen; | |||||
if (fullscreen) | |||||
{ | |||||
width = fullscreenWidth; | |||||
height = fullscreenHeight; | |||||
SDL_SetWindowSize(window, width, height); | |||||
if (SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN) != 0) | |||||
{ | |||||
std::cerr << "Failed to set fullscreen mode: \"" << SDL_GetError() << "\"" << std::endl; | |||||
fullscreen = false; | |||||
} | |||||
} | |||||
else | |||||
{ | |||||
width = windowedWidth; | |||||
height = windowedHeight; | |||||
if (SDL_SetWindowFullscreen(window, 0) != 0) | |||||
{ | |||||
std::cerr << "Failed to set windowed mode: \"" << SDL_GetError() << "\"" << std::endl; | |||||
fullscreen = true; | |||||
} | |||||
else | |||||
{ | |||||
SDL_SetWindowSize(window, width, height); | |||||
SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); | |||||
} | |||||
} | |||||
// Get actual window size | |||||
SDL_GetWindowSize(window, &width, &height); | |||||
// Print mode and resolution | |||||
if (fullscreen) | |||||
{ | |||||
std::cout << "Changed to fullscreen mode at resolution " << width << "x" << height << std::endl; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "Changed to windowed mode at resolution " << width << "x" << height << std::endl; | |||||
} | |||||
// Save settings | |||||
settings.set("fullscreen", fullscreen); | |||||
saveUserSettings(); | |||||
// Notify window observers | |||||
inputManager->update(); | |||||
} | |||||
void Application::changeVerticalSync() | |||||
{ | |||||
swapInterval = (swapInterval == 1) ? 0 : 1; | |||||
if (swapInterval == 1) | |||||
{ | |||||
std::cout << "Enabling vertical sync... "; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "Disabling vertical sync... "; | |||||
} | |||||
if (SDL_GL_SetSwapInterval(swapInterval) != 0) | |||||
{ | |||||
std::cout << "failed: \"" << SDL_GetError() << "\"" << std::endl; | |||||
swapInterval = SDL_GL_GetSwapInterval(); | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
// Save settings | |||||
settings.set("swap_interval", swapInterval); | |||||
saveUserSettings(); | |||||
} | |||||
void Application::saveUserSettings() | |||||
{ | |||||
std::cout << "Saving user setttings to \"" << userSettingsFilename << "\"... "; | |||||
if (!settings.save(userSettingsFilename)) | |||||
{ | |||||
std::cout << "failed" << std::endl; | |||||
} | |||||
else | |||||
{ | |||||
std::cout << "success" << std::endl; | |||||
} | |||||
} | |||||
void Application::resizeUI() | |||||
{ | |||||
// Adjust UI dimensions | |||||
uiRootElement->setDimensions(Vector2(width, height)); | |||||
uiRootElement->update(); | |||||
// Adjust UI camera projection | |||||
uiCamera.setOrthographic(0, width, height, 0, -1.0f, 1.0f); | |||||
} | |||||
void Application::enterMenu(std::size_t index) | |||||
{ | |||||
if (index != currentMenuIndex) | |||||
{ | |||||
exitMenu(currentMenuIndex); | |||||
} | |||||
// Select next menu | |||||
currentMenuIndex = index; | |||||
selectedMenuItemIndex = 0; | |||||
currentMenu = menus[currentMenuIndex]; | |||||
menus[currentMenuIndex]->getItem(selectedMenuItemIndex)->select(); | |||||
// Start menu fade-in tween | |||||
menuFadeInTween->setUpdateCallback(std::bind(UIElement::setTintColor, menuContainers[currentMenuIndex], std::placeholders::_1)); | |||||
menuFadeInTween->setEndCallback(std::bind(UIElement::setActive, menuContainers[currentMenuIndex], true)); | |||||
menuFadeInTween->reset(); | |||||
menuFadeInTween->start(); | |||||
// Start menu slide-in tween | |||||
menuSlideInTween->setUpdateCallback(std::bind(UIElement::setTranslation, menuContainers[currentMenuIndex], std::placeholders::_1)); | |||||
menuSlideInTween->reset(); | |||||
menuSlideInTween->start(); | |||||
// Make menu visible | |||||
menuContainers[currentMenuIndex]->setVisible(true); | |||||
} | |||||
void Application::exitMenu(std::size_t index) | |||||
{ | |||||
// Deactivate previous menu | |||||
menuContainers[currentMenuIndex]->setActive(false); | |||||
// Fade out previous menu | |||||
menuFadeOutTween->setUpdateCallback(std::bind(UIElement::setTintColor, menuContainers[currentMenuIndex], std::placeholders::_1)); | |||||
menuFadeOutTween->setEndCallback(std::bind(UIElement::setVisible, menuContainers[currentMenuIndex], false)); | |||||
menuFadeOutTween->reset(); | |||||
menuFadeOutTween->start(); | |||||
} | |||||
void Application::selectMenuItem(std::size_t index) | |||||
{ | |||||
if (currentMenu == nullptr || index > currentMenu->getItemCount()) | |||||
{ | |||||
std::cout << "Selected invalid menu item" << std::endl; | |||||
return; | |||||
} | |||||
MenuItem* previousItem = currentMenu->getItem(selectedMenuItemIndex); | |||||
previousItem->deselect(); | |||||
selectedMenuItemIndex = index; | |||||
MenuItem* nextItem = currentMenu->getItem(selectedMenuItemIndex); | |||||
nextItem->select(); | |||||
} | |||||
void Application::activateMenuItem(std::size_t index) | |||||
{ | |||||
if (index > menus[currentMenuIndex]->getItemCount()) | |||||
{ | |||||
std::cout << "Activated invalid menu item" << std::endl; | |||||
return; | |||||
} | |||||
menus[currentMenuIndex]->getItem(index)->deselect(); | |||||
menus[currentMenuIndex]->getItem(index)->activate(); | |||||
} |
@ -0,0 +1,268 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef APPLICATION_HPP | |||||
#define APPLICATION_HPP | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
#include "mesh.hpp" | |||||
#include "terrain.hpp" | |||||
#include "input.hpp" | |||||
#include "controls.hpp" | |||||
#include "settings.hpp" | |||||
#include "render-passes.hpp" | |||||
#include "ui/ui.hpp" | |||||
#include "ui/tween.hpp" | |||||
class Menu; | |||||
class ApplicationState; | |||||
class Colony; | |||||
class SplashState; | |||||
class TitleState; | |||||
class ExperimentState; | |||||
class CameraController; | |||||
class SurfaceCameraController; | |||||
class TunnelCameraController; | |||||
class LineBatcher; | |||||
class ModelLoader; | |||||
class MaterialLoader; | |||||
class Application | |||||
{ | |||||
public: | |||||
Application(int argc, char* argv[]); | |||||
~Application(); | |||||
// Executes the application and returns a status code | |||||
int execute(); | |||||
// Changes the application state | |||||
void changeState(ApplicationState* state); | |||||
// Sets the termination code to be returned when the application finishes | |||||
void setTerminationCode(int code); | |||||
// Closes the application | |||||
void close(int terminationCode); | |||||
void changeFullscreen(); | |||||
void changeVerticalSync(); | |||||
void saveUserSettings(); | |||||
void resizeUI(); | |||||
void enterMenu(std::size_t index); | |||||
void exitMenu(std::size_t index); | |||||
void selectMenuItem(std::size_t index); | |||||
void activateMenuItem(std::size_t index); | |||||
private: | |||||
ApplicationState* state; | |||||
ApplicationState* nextState; | |||||
int terminationCode; | |||||
public: | |||||
SDL_Window* window; | |||||
SDL_GLContext context; | |||||
ModelInstance lensToolObject; | |||||
ModelInstance forcepsToolObject; | |||||
ModelInstance navigatorObject; | |||||
DirectionalLight sunlight; | |||||
DirectionalLight fillLight; | |||||
DirectionalLight backLight; | |||||
Spotlight lensHotspot; | |||||
Spotlight lensFalloff; | |||||
RenderTarget shadowMapRenderTarget; | |||||
GLuint shadowFramebuffer; | |||||
GLuint shadowDepthTexture; | |||||
ShadowMapRenderPass shadowMapPass; | |||||
Compositor shadowCompositor; | |||||
Camera sunlightCamera; | |||||
RenderTarget defaultRenderTarget; | |||||
LightingRenderPass lightingPass; | |||||
DebugRenderPass debugPass; | |||||
Compositor defaultCompositor; | |||||
Camera camera; | |||||
Scene scene; | |||||
BillboardBatch particleBatch; | |||||
MaterialLoader* materialLoader; | |||||
ModelLoader* modelLoader; | |||||
Renderer renderer; | |||||
int toolIndex; | |||||
std::string appDataPath; | |||||
std::string userDataPath; | |||||
ParameterDict settings; | |||||
std::string defaultSettingsFilename; | |||||
std::string userSettingsFilename; | |||||
bool fullscreen; | |||||
int fullscreenWidth; | |||||
int fullscreenHeight; | |||||
int windowedWidth; | |||||
int windowedHeight; | |||||
int swapInterval; | |||||
int width; | |||||
int height; | |||||
InputManager* inputManager; | |||||
Keyboard* keyboard; | |||||
Mouse* mouse; | |||||
SplashState* splashState; | |||||
TitleState* titleState; | |||||
ExperimentState* experimentState; | |||||
ControlProfile* menuControlProfile; | |||||
Control menuLeft; | |||||
Control menuRight; | |||||
Control menuUp; | |||||
Control menuDown; | |||||
Control menuSelect; | |||||
Control menuCancel; | |||||
Control toggleFullscreen; | |||||
Control escape; | |||||
ControlProfile* gameControlProfile; | |||||
Control cameraMoveForward; | |||||
Control cameraMoveBack; | |||||
Control cameraMoveLeft; | |||||
Control cameraMoveRight; | |||||
Control cameraRotateCW; | |||||
Control cameraRotateCCW; | |||||
Control cameraZoomIn; | |||||
Control cameraZoomOut; | |||||
Control cameraToggleOverheadView; | |||||
Control cameraToggleNestView; | |||||
bool cameraOverheadView; | |||||
bool cameraNestView; | |||||
// Misc | |||||
Timer frameTimer; | |||||
// UI | |||||
ParameterDict strings; | |||||
float dpi; | |||||
float fontSizePT; | |||||
float fontSizePX; | |||||
Font* menuFont; | |||||
Texture splashTexture; | |||||
Texture titleTexture; | |||||
Vector4 selectedColor; | |||||
Vector4 deselectedColor; | |||||
UIContainer* uiRootElement; | |||||
UIImage* blackoutImage; | |||||
UIImage* splashImage; | |||||
UIImage* titleImage; | |||||
UIImage* copyrightImage; | |||||
UILabel* anyKeyLabel; | |||||
UILabel* menuSelectorLabel; | |||||
UIContainer* mainMenuContainer; | |||||
UIContainer* challengeMenuContainer; | |||||
UIContainer* experimentMenuContainer; | |||||
UIContainer* settingsMenuContainer; | |||||
UILabel* challengeLabel; | |||||
UILabel* experimentLabel; | |||||
UILabel* settingsLabel; | |||||
UILabel* quitLabel; | |||||
UILabel* loadLabel; | |||||
UILabel* newLabel; | |||||
UILabel* experimentBackLabel; | |||||
UILabel* videoLabel; | |||||
UILabel* audioLabel; | |||||
UILabel* controlsLabel; | |||||
UILabel* gameLabel; | |||||
UILabel* settingsBackLabel; | |||||
UIContainer* pauseMenuContainer; | |||||
UILabel* pausedResumeLabel; | |||||
UILabel* pausedSaveLabel; | |||||
UILabel* pausedNewLabel; | |||||
UILabel* pausedSettingsLabel; | |||||
UILabel* returnToMainMenuLabel; | |||||
UILabel* quitToDesktopLabel; | |||||
BillboardBatch* uiBatch; | |||||
UIBatcher* uiBatcher; | |||||
UIRenderPass uiPass; | |||||
Compositor uiCompositor; | |||||
Camera uiCamera; | |||||
Scene uiScene; | |||||
Camera bgCamera; | |||||
BillboardBatch bgBatch; | |||||
Compositor bgCompositor; | |||||
VignetteRenderPass vignettePass; | |||||
Scene bgScene; | |||||
// Animation | |||||
Tweener* tweener; | |||||
Tween<Vector4>* fadeInTween; | |||||
Tween<Vector4>* fadeOutTween; | |||||
Tween<Vector4>* splashFadeInTween; | |||||
Tween<Vector4>* splashFadeOutTween; | |||||
Tween<Vector4>* titleFadeInTween; | |||||
Tween<Vector4>* titleFadeOutTween; | |||||
Tween<Vector4>* copyrightFadeInTween; | |||||
Tween<Vector4>* copyrightFadeOutTween; | |||||
Tween<Vector4>* anyKeyFadeInTween; | |||||
Tween<Vector4>* anyKeyFadeOutTween; | |||||
Tween<Vector4>* menuFadeInTween; | |||||
Tween<Vector4>* menuFadeOutTween; | |||||
Tween<Vector2>* menuSlideInTween; | |||||
// Menus | |||||
std::size_t menuCount; | |||||
Menu** menus; | |||||
int currentMenuIndex; | |||||
int selectedMenuItemIndex; | |||||
UIContainer** menuContainers; | |||||
Menu* currentMenu; | |||||
Menu* mainMenu; | |||||
Menu* challengeMenu; | |||||
Menu* experimentMenu; | |||||
Menu* settingsMenu; | |||||
// Models | |||||
Model* displayModel; | |||||
Model* antModel; | |||||
ModelInstance* displayModelInstance; | |||||
ModelInstance* antModelInstance; | |||||
// Game variables | |||||
Colony* colony; | |||||
SurfaceCameraController* surfaceCam; | |||||
TunnelCameraController* tunnelCam; | |||||
Plane clippingPlanes[5]; | |||||
Vector3 clippingPlaneNormals[5]; | |||||
Vector3 clippingPlaneOffsets[5]; | |||||
AABB clippingPlaneAABBS[5]; | |||||
// Debug | |||||
LineBatcher* lineBatcher; | |||||
}; | |||||
#endif // APPLICATION_HPP |
@ -0,0 +1,157 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "camera-controller.hpp" | |||||
CameraController::CameraController(): | |||||
camera(nullptr) | |||||
{} | |||||
SurfaceCameraController::SurfaceCameraController(): | |||||
elevationRotation(1, 0, 0, 0), | |||||
azimuthRotation(1, 0, 0, 0), | |||||
rotation(1, 0, 0, 0), | |||||
targetElevationRotation(1, 0, 0, 0), | |||||
targetAzimuthRotation(1, 0, 0, 0), | |||||
targetRotation(1, 0, 0, 0) | |||||
{} | |||||
SurfaceCameraController::~SurfaceCameraController() | |||||
{} | |||||
void SurfaceCameraController::update(float dt) | |||||
{ | |||||
float interpolationFactor = 0.25f / (1.0 / 60.0f) * dt; | |||||
// Calculate rotation and target rotation quaternions | |||||
//rotation = azimuthRotation * elevationRotation; | |||||
targetRotation = targetAzimuthRotation * targetElevationRotation; | |||||
// Calculate target translation | |||||
targetTranslation = targetFocalPoint + targetRotation * Vector3(0.0f, 0.0f, targetFocalDistance); | |||||
// Interpolate rotation | |||||
//rotation = glm::mix(rotation, targetRotation, interpolationFactor); | |||||
// Interpolate angles | |||||
setElevation(glm::mix(elevation, targetElevation, interpolationFactor)); | |||||
setAzimuth(glm::mix(azimuth, targetAzimuth, interpolationFactor)); | |||||
// Calculate rotation | |||||
rotation = azimuthRotation * elevationRotation; | |||||
// Interpolate focal point and focal distance | |||||
focalPoint = glm::mix(focalPoint, targetFocalPoint, interpolationFactor); | |||||
focalDistance = glm::mix(focalDistance, targetFocalDistance, interpolationFactor); | |||||
// Caluclate translation | |||||
translation = focalPoint + rotation * Vector3(0.0f, 0.0f, focalDistance); | |||||
/* | |||||
// Recalculate azimuth | |||||
azimuthRotation = rotation; | |||||
azimuthRotation.x = 0.0f; | |||||
azimuthRotation.z = 0.0f; | |||||
azimuthRotation = glm::normalize(azimuthRotation); | |||||
azimuth = 2.0f * std::acos(azimuthRotation.w); | |||||
// Recalculate elevation | |||||
elevationRotation = rotation; | |||||
elevationRotation.y = 0.0f; | |||||
elevationRotation.z = 0.0f; | |||||
elevationRotation = glm::normalize(elevationRotation); | |||||
elevation = 2.0f * std::acos(elevationRotation.w); | |||||
*/ | |||||
// Update camera | |||||
if (camera != nullptr) | |||||
{ | |||||
camera->lookAt(translation, focalPoint, Vector3(0.0f, 1.0f, 0.0f)); | |||||
} | |||||
} | |||||
void SurfaceCameraController::move(Vector2 direction) | |||||
{ | |||||
targetFocalPoint += azimuthRotation * Vector3(direction.x, 0.0f, direction.y); | |||||
} | |||||
void SurfaceCameraController::rotate(float angle) | |||||
{ | |||||
setTargetAzimuth(targetAzimuth + angle); | |||||
} | |||||
void SurfaceCameraController::zoom(float distance) | |||||
{ | |||||
setTargetFocalDistance(targetFocalDistance - distance); | |||||
} | |||||
void SurfaceCameraController::setFocalPoint(const Vector3& point) | |||||
{ | |||||
focalPoint = point; | |||||
} | |||||
void SurfaceCameraController::setFocalDistance(float distance) | |||||
{ | |||||
focalDistance = distance; | |||||
} | |||||
void SurfaceCameraController::setElevation(float angle) | |||||
{ | |||||
elevation = angle; | |||||
elevationRotation = glm::angleAxis(elevation, Vector3(-1.0f, 0.0f, 0.0f)); | |||||
} | |||||
void SurfaceCameraController::setAzimuth(float angle) | |||||
{ | |||||
azimuth = angle; | |||||
azimuthRotation = glm::angleAxis(azimuth, Vector3(0.0f, 1.0f, 0.0f)); | |||||
} | |||||
void SurfaceCameraController::setTargetFocalPoint(const Vector3& point) | |||||
{ | |||||
targetFocalPoint = point; | |||||
} | |||||
void SurfaceCameraController::setTargetFocalDistance(float distance) | |||||
{ | |||||
targetFocalDistance = distance; | |||||
} | |||||
void SurfaceCameraController::setTargetElevation(float angle) | |||||
{ | |||||
targetElevation = angle; | |||||
targetElevationRotation = glm::angleAxis(targetElevation, Vector3(-1.0f, 0.0f, 0.0f)); | |||||
} | |||||
void SurfaceCameraController::setTargetAzimuth(float angle) | |||||
{ | |||||
targetAzimuth = angle; | |||||
targetAzimuthRotation = glm::angleAxis(targetAzimuth, Vector3(0.0f, 1.0f, 0.0f)); | |||||
} | |||||
TunnelCameraController::TunnelCameraController() | |||||
{} | |||||
TunnelCameraController::~TunnelCameraController() | |||||
{} | |||||
void TunnelCameraController::update(float dt) | |||||
{ | |||||
} |
@ -0,0 +1,193 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef CAMERA_CONTROLLER_HPP | |||||
#define CAMERA_CONTROLLER_HPP | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
class CameraController | |||||
{ | |||||
public: | |||||
CameraController(); | |||||
virtual void update(float dt) = 0; | |||||
void setCamera(Camera* camera); | |||||
const Camera* getCamera() const; | |||||
Camera* getCamera(); | |||||
protected: | |||||
Camera* camera; | |||||
}; | |||||
inline void CameraController::setCamera(Camera* camera) | |||||
{ | |||||
this->camera = camera; | |||||
} | |||||
inline const Camera* CameraController::getCamera() const | |||||
{ | |||||
return camera; | |||||
} | |||||
inline Camera* CameraController::getCamera() | |||||
{ | |||||
return camera; | |||||
} | |||||
class SurfaceCameraController: public CameraController | |||||
{ | |||||
public: | |||||
SurfaceCameraController(); | |||||
virtual ~SurfaceCameraController(); | |||||
virtual void update(float dt); | |||||
/// @param direction Specifies the movement direction and speed scale on the XZ plane | |||||
void move(Vector2 direction); | |||||
void rotate(float angle); | |||||
void zoom(float distance); | |||||
void setFocalPoint(const Vector3& point); | |||||
void setFocalDistance(float distance); | |||||
void setElevation(float angle); | |||||
void setAzimuth(float angle); | |||||
void setTargetFocalPoint(const Vector3& point); | |||||
void setTargetFocalDistance(float distance); | |||||
void setTargetElevation(float angle); | |||||
void setTargetAzimuth(float angle); | |||||
const Vector3& getFocalPoint() const; | |||||
float getFocalDistance() const; | |||||
float getElevation() const; | |||||
float getAzimuth() const; | |||||
const Vector3& getTargetFocalPoint() const; | |||||
float getTargetFocalDistance() const; | |||||
float getTargetElevation() const; | |||||
float getTargetAzimuth() const; | |||||
const Vector3& getTranslation() const; | |||||
const glm::quat& getRotation() const; | |||||
const Vector3& getTargetTranslation() const; | |||||
const glm::quat& getTargetRotation() const; | |||||
private: | |||||
Vector3 focalPoint; | |||||
float focalDistance; | |||||
float elevation; | |||||
float azimuth; | |||||
Vector3 targetFocalPoint; | |||||
float targetFocalDistance; | |||||
float targetElevation; | |||||
float targetAzimuth; | |||||
glm::quat elevationRotation; | |||||
glm::quat azimuthRotation; | |||||
glm::quat rotation; | |||||
glm::quat targetElevationRotation; | |||||
glm::quat targetAzimuthRotation; | |||||
glm::quat targetRotation; | |||||
Vector3 translation; | |||||
Vector3 targetTranslation; | |||||
}; | |||||
inline const Vector3& SurfaceCameraController::getFocalPoint() const | |||||
{ | |||||
return focalPoint; | |||||
} | |||||
inline float SurfaceCameraController::getFocalDistance() const | |||||
{ | |||||
return focalDistance; | |||||
} | |||||
inline float SurfaceCameraController::getElevation() const | |||||
{ | |||||
return elevation; | |||||
} | |||||
inline float SurfaceCameraController::getAzimuth() const | |||||
{ | |||||
return azimuth; | |||||
} | |||||
inline const Vector3& SurfaceCameraController::getTargetFocalPoint() const | |||||
{ | |||||
return targetFocalPoint; | |||||
} | |||||
inline float SurfaceCameraController::getTargetFocalDistance() const | |||||
{ | |||||
return targetFocalDistance; | |||||
} | |||||
inline float SurfaceCameraController::getTargetElevation() const | |||||
{ | |||||
return targetElevation; | |||||
} | |||||
inline float SurfaceCameraController::getTargetAzimuth() const | |||||
{ | |||||
return targetAzimuth; | |||||
} | |||||
inline const Vector3& SurfaceCameraController::getTranslation() const | |||||
{ | |||||
return translation; | |||||
} | |||||
inline const glm::quat& SurfaceCameraController::getRotation() const | |||||
{ | |||||
return rotation; | |||||
} | |||||
inline const Vector3& SurfaceCameraController::getTargetTranslation() const | |||||
{ | |||||
return targetTranslation; | |||||
} | |||||
inline const glm::quat& SurfaceCameraController::getTargetRotation() const | |||||
{ | |||||
return targetRotation; | |||||
} | |||||
/** | |||||
* Note, when mouseover tunnel, highlight (in red?) the entire path from the end of the tunnel to the entrance of the nest. | |||||
*/ | |||||
class TunnelCameraController: public CameraController | |||||
{ | |||||
public: | |||||
TunnelCameraController(); | |||||
virtual ~TunnelCameraController(); | |||||
virtual void update(float dt); | |||||
void rotateCW(float scale); | |||||
void rotateCCW(float scale); | |||||
// Ascends the tunnel system in the direction of the entrance | |||||
void ascend(float scale); | |||||
// Descends along the current tunnel | |||||
void descend(float scale); | |||||
}; | |||||
#endif |
@ -0,0 +1,29 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef CONFIGURATION_HPP | |||||
#define CONFIGURATION_HPP | |||||
#define ANTKEEPER_VERSION_MAJOR @ANTKEEPER_VERSION_MAJOR@ | |||||
#define ANTKEEPER_VERSION_MINOR @ANTKEEPER_VERSION_MINOR@ | |||||
#define ANTKEEPER_VERSION_PATCH @ANTKEEPER_VERSION_PATCH@ | |||||
#define ANTKEEPER_VERSION_STRING "@ANTKEEPER_VERSION@" | |||||
#cmakedefine ANTKEEPER_DEBUG | |||||
#endif // CONFIGURATION_HPP |
@ -0,0 +1,532 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "controls.hpp" | |||||
#include <sstream> | |||||
#include <fstream> | |||||
#include <vector> | |||||
Control::Control(): | |||||
deadzone(0.1f), | |||||
currentValue(0.0f), | |||||
previousValue(0.0f) | |||||
{} | |||||
Control::~Control() | |||||
{} | |||||
void Control::setDeadzone(float value) | |||||
{ | |||||
deadzone = value; | |||||
} | |||||
void Control::update() | |||||
{ | |||||
previousValue = currentValue; | |||||
} | |||||
bool Control::isTriggered() const | |||||
{ | |||||
return currentValue > deadzone; | |||||
} | |||||
bool Control::wasTriggered() const | |||||
{ | |||||
return previousValue > deadzone; | |||||
} | |||||
bool Control::isUnbound() const | |||||
{ | |||||
return (boundKeys.empty() && boundMouseButtons.empty() && boundGamepadButtons.empty() && boundGamepadAxes.empty()); | |||||
} | |||||
void Control::bindKey(Keyboard* keyboard, int scancode) | |||||
{ | |||||
// Check if already observing this keyboard | |||||
bool observing = false; | |||||
for (auto it: boundKeys) | |||||
{ | |||||
if (it.first == keyboard) | |||||
{ | |||||
observing = true; | |||||
break; | |||||
} | |||||
} | |||||
if (!observing) | |||||
keyboard->addKeyObserver(static_cast<KeyObserver*>(this)); | |||||
boundKeys.push_back(std::pair<Keyboard*, int>(keyboard, scancode)); | |||||
} | |||||
void Control::bindMouseButton(Mouse* mouse, int button) | |||||
{ | |||||
// Checking if already observing this mouse | |||||
bool observing = false; | |||||
for (auto it: boundMouseButtons) | |||||
{ | |||||
if (it.first == mouse) | |||||
{ | |||||
observing = true; | |||||
break; | |||||
} | |||||
} | |||||
if (!observing) | |||||
mouse->addMouseButtonObserver(static_cast<MouseButtonObserver*>(this)); | |||||
boundMouseButtons.push_back(std::pair<Mouse*, int>(mouse, button)); | |||||
} | |||||
void Control::bindGamepadButton(Gamepad* gamepad, int button) | |||||
{ | |||||
bool observing = false; | |||||
for (auto it: boundGamepadButtons) | |||||
{ | |||||
if (it.first == gamepad) | |||||
{ | |||||
observing = true; | |||||
break; | |||||
} | |||||
} | |||||
if (!observing) | |||||
gamepad->addGamepadButtonObserver(static_cast<GamepadButtonObserver*>(this)); | |||||
boundGamepadButtons.push_back(std::pair<Gamepad*, int>(gamepad, button)); | |||||
} | |||||
void Control::bindGamepadAxis(Gamepad* gamepad, int axis, bool negative) | |||||
{ | |||||
bool observing = false; | |||||
for (auto it: boundGamepadAxes) | |||||
{ | |||||
if (std::get<0>(it) == gamepad) | |||||
{ | |||||
observing = true; | |||||
break; | |||||
} | |||||
} | |||||
if (!observing) | |||||
gamepad->addGamepadAxisObserver(static_cast<GamepadAxisObserver*>(this)); | |||||
boundGamepadAxes.push_back(std::make_tuple(gamepad, axis, negative)); | |||||
} | |||||
void Control::bind(const InputEvent& event) | |||||
{ | |||||
switch (event.type) | |||||
{ | |||||
case InputEvent::Type::KEY: | |||||
bindKey(event.key.first, event.key.second); | |||||
break; | |||||
case InputEvent::Type::MOUSE_BUTTON: | |||||
bindMouseButton(event.mouseButton.first, event.mouseButton.second); | |||||
break; | |||||
case InputEvent::Type::GAMEPAD_BUTTON: | |||||
bindGamepadButton(event.gamepadButton.first, event.gamepadButton.second); | |||||
break; | |||||
case InputEvent::Type::GAMEPAD_AXIS: | |||||
bindGamepadAxis(std::get<0>(event.gamepadAxis), std::get<1>(event.gamepadAxis), std::get<2>(event.gamepadAxis)); | |||||
break; | |||||
default: | |||||
break; | |||||
} | |||||
} | |||||
void Control::unbind() | |||||
{ | |||||
while (!boundKeys.empty()) | |||||
{ | |||||
// Remove the first bound key and stop observing its keyboard | |||||
Keyboard* keyboard = boundKeys.front().first; | |||||
keyboard->removeKeyObserver(static_cast<KeyObserver*>(this)); | |||||
boundKeys.pop_front(); | |||||
// Remove other bound keys which are associated with the keyboard | |||||
auto it = boundKeys.begin(); | |||||
while (it != boundKeys.end()) | |||||
{ | |||||
if (it->first == keyboard) | |||||
boundKeys.erase(it++); | |||||
else | |||||
++it; | |||||
} | |||||
} | |||||
while (!boundMouseButtons.empty()) | |||||
{ | |||||
// Remove the first bound mouse button and stop observing its mouse | |||||
Mouse* mouse = boundMouseButtons.front().first; | |||||
mouse->removeMouseButtonObserver(static_cast<MouseButtonObserver*>(this)); | |||||
boundMouseButtons.pop_front(); | |||||
// Remove other bound mouse buttons which are associated with the mouse | |||||
auto it = boundMouseButtons.begin(); | |||||
while (it != boundMouseButtons.end()) | |||||
{ | |||||
if (it->first == mouse) | |||||
boundMouseButtons.erase(it++); | |||||
else | |||||
++it; | |||||
} | |||||
} | |||||
while (!boundGamepadButtons.empty()) | |||||
{ | |||||
// Remove the first bound gamepad button and stop observing its gamepad | |||||
Gamepad* gamepad = boundGamepadButtons.front().first; | |||||
gamepad->removeGamepadButtonObserver(static_cast<GamepadButtonObserver*>(this)); | |||||
boundGamepadButtons.pop_front(); | |||||
// Remove other bound gamepad buttons which are associated with the gamepad | |||||
auto it = boundGamepadButtons.begin(); | |||||
while (it != boundGamepadButtons.end()) | |||||
{ | |||||
if (it->first == gamepad) | |||||
boundGamepadButtons.erase(it++); | |||||
else | |||||
++it; | |||||
} | |||||
} | |||||
while (!boundGamepadAxes.empty()) | |||||
{ | |||||
// Remove the first bound gamepad axis and stop observing its gamepad | |||||
Gamepad* gamepad = std::get<0>(boundGamepadAxes.front()); | |||||
gamepad->removeGamepadAxisObserver(static_cast<GamepadAxisObserver*>(this)); | |||||
boundGamepadAxes.pop_front(); | |||||
// Remove other bound gamepad axes which are associated with the gamepad | |||||
auto it = boundGamepadAxes.begin(); | |||||
while (it != boundGamepadAxes.end()) | |||||
{ | |||||
if (std::get<0>(*it) == gamepad) | |||||
boundGamepadAxes.erase(it++); | |||||
else | |||||
++it; | |||||
} | |||||
} | |||||
} | |||||
void Control::keyPressed(int scancode) | |||||
{ | |||||
for (auto it: boundKeys) | |||||
{ | |||||
if (it.second == scancode) | |||||
{ | |||||
currentValue = 1.0f; | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
void Control::keyReleased(int scancode) | |||||
{ | |||||
for (auto it: boundKeys) | |||||
{ | |||||
if (it.second == scancode) | |||||
{ | |||||
currentValue = 0.0f; | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
void Control::mouseButtonPressed(int button, int x, int y) | |||||
{ | |||||
for (auto it: boundMouseButtons) | |||||
{ | |||||
if (it.second == button) | |||||
{ | |||||
currentValue = 1.0f; | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
void Control::mouseButtonReleased(int button, int x, int y) | |||||
{ | |||||
for (auto it: boundMouseButtons) | |||||
{ | |||||
if (it.second == button) | |||||
{ | |||||
currentValue = 0.0f; | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
void Control::gamepadButtonPressed(int button) | |||||
{ | |||||
for (auto it: boundGamepadButtons) | |||||
{ | |||||
if (it.second == button) | |||||
{ | |||||
currentValue = 1.0f; | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
void Control::gamepadButtonReleased(int button) | |||||
{ | |||||
for (auto it: boundGamepadButtons) | |||||
{ | |||||
if (it.second == button) | |||||
{ | |||||
currentValue = 0.0f; | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
void Control::gamepadAxisMoved(int axis, bool negative, float value) | |||||
{ | |||||
for (auto it: boundGamepadAxes) | |||||
{ | |||||
if (std::get<1>(it) == axis && std::get<2>(it) == negative) | |||||
{ | |||||
currentValue = value; | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
const std::list<std::pair<Keyboard*, int>>* Control::getBoundKeys() const | |||||
{ | |||||
return &boundKeys; | |||||
} | |||||
const std::list<std::pair<Mouse*, int>>* Control::getBoundMouseButtons() const | |||||
{ | |||||
return &boundMouseButtons; | |||||
} | |||||
const std::list<std::pair<Gamepad*, int>>* Control::getBoundGamepadButtons() const | |||||
{ | |||||
return &boundGamepadButtons; | |||||
} | |||||
const std::list<std::tuple<Gamepad*, int, bool>>* Control::getBoundGamepadAxes() const | |||||
{ | |||||
return &boundGamepadAxes; | |||||
} | |||||
ControlProfile::ControlProfile(InputManager* inputManager): | |||||
inputManager(inputManager) | |||||
{} | |||||
void ControlProfile::registerControl(const std::string& name, Control* control) | |||||
{ | |||||
controls[name] = control; | |||||
} | |||||
bool ControlProfile::save(const std::string& filename) | |||||
{ | |||||
// Open control profile | |||||
std::ofstream file(filename.c_str()); | |||||
if (!file.is_open()) | |||||
{ | |||||
std::cerr << "Failed to open control profile \"" << filename << "\"" << std::endl; | |||||
return false; | |||||
} | |||||
for (auto it = controls.begin(); it != controls.end(); ++it) | |||||
{ | |||||
Control* control = it->second; | |||||
const std::list<std::pair<Keyboard*, int>>* boundKeys = control->getBoundKeys(); | |||||
const std::list<std::pair<Mouse*, int>>* boundMouseButtons = control->getBoundMouseButtons(); | |||||
const std::list<std::pair<Gamepad*, int>>* boundGamepadButtons = control->getBoundGamepadButtons(); | |||||
const std::list<std::tuple<Gamepad*, int, bool>>* boundGamepadAxes = control->getBoundGamepadAxes(); | |||||
for (auto boundKey: *boundKeys) | |||||
{ | |||||
int key = boundKey.second; | |||||
file << "control\t" << it->first << "\tkeyboard\tkey\t" << key << '\n'; | |||||
} | |||||
for (auto boundMouseButton: *boundMouseButtons) | |||||
{ | |||||
int button = boundMouseButton.second; | |||||
file << "control\t" << it->first << "\tmouse\tbutton\t" << button << '\n'; | |||||
} | |||||
for (auto boundGamepadButton: *boundGamepadButtons) | |||||
{ | |||||
const std::string& gamepadName = boundGamepadButton.first->getName(); | |||||
int button = boundGamepadButton.second; | |||||
file << "control\t" << it->first << "\tgamepad\t" << gamepadName << "\tbutton\t" << button << '\n'; | |||||
} | |||||
for (auto boundGamepadAxis: *boundGamepadAxes) | |||||
{ | |||||
const std::string& gamepadName = std::get<0>(boundGamepadAxis)->getName(); | |||||
int axis = std::get<1>(boundGamepadAxis); | |||||
bool negative = std::get<2>(boundGamepadAxis); | |||||
std::stringstream axisstream; | |||||
if (negative) | |||||
axisstream << "-"; | |||||
else | |||||
axisstream << "+"; | |||||
axisstream << axis; | |||||
file << "control\t" << it->first << "\tgamepad\t" << gamepadName << "\taxis\t" << axisstream.str() << '\n'; | |||||
} | |||||
} | |||||
file.close(); | |||||
return true; | |||||
} | |||||
bool ControlProfile::load(const std::string& filename) | |||||
{ | |||||
// Open control profile | |||||
std::ifstream file(filename.c_str()); | |||||
if (!file.is_open()) | |||||
{ | |||||
std::cerr << "Failed to open control profile \"" << filename << "\"" << std::endl; | |||||
return false; | |||||
} | |||||
// Read profile | |||||
std::string line; | |||||
while (file.good() && std::getline(file, line)) | |||||
{ | |||||
// Tokenize line (tab-delimeted) | |||||
std::vector<std::string> tokens; | |||||
std::string token; | |||||
std::istringstream linestream(line); | |||||
while (std::getline(linestream, token, '\t')) | |||||
tokens.push_back(token); | |||||
if (tokens.empty() || tokens[0][0] == '#') | |||||
continue; | |||||
if (tokens[0] == "control" && tokens.size() >= 5) | |||||
{ | |||||
// Use control name to get control pointer | |||||
auto it = controls.find(tokens[1]); | |||||
if (it == controls.end()) | |||||
{ | |||||
std::cerr << "Attempted to load unregistered control \"" << tokens[1] << "\" from control profile \"" << filename << "\"" << std::endl; | |||||
continue; | |||||
} | |||||
Control* control = it->second; | |||||
// Find input device | |||||
if (tokens[2] == "keyboard") | |||||
{ | |||||
Keyboard* keyboard = inputManager->getKeyboards()->front(); | |||||
if (tokens[3] == "key") | |||||
{ | |||||
std::stringstream keystream(tokens[4]); | |||||
int scancode = -1; | |||||
keystream >> scancode; | |||||
control->bindKey(keyboard, scancode); | |||||
} | |||||
else | |||||
{ | |||||
std::cerr << "Invalid line \"" << line << "\" in control profile \"" << filename << "\"" << std::endl; | |||||
} | |||||
} | |||||
else if (tokens[2] == "mouse") | |||||
{ | |||||
Mouse* mouse = inputManager->getMice()->front(); | |||||
if (tokens[3] == "button") | |||||
{ | |||||
std::stringstream buttonstream(tokens[4]); | |||||
int button = -1; | |||||
buttonstream >> button; | |||||
control->bindMouseButton(mouse, button); | |||||
} | |||||
else | |||||
{ | |||||
std::cerr << "Invalid line \"" << line << "\" in control profile \"" << filename << "\"" << std::endl; | |||||
continue; | |||||
} | |||||
} | |||||
else if (tokens[2] == "gamepad") | |||||
{ | |||||
if (tokens.size() != 6) | |||||
{ | |||||
std::cerr << "Invalid line \"" << line << "\" in control profile \"" << filename << "\"" << std::endl; | |||||
continue; | |||||
} | |||||
Gamepad* gamepad = inputManager->getGamepad(tokens[3]); | |||||
if (!gamepad) | |||||
{ | |||||
gamepad = new Gamepad(tokens[3]); | |||||
gamepad->setDisconnected(true); | |||||
inputManager->registerGamepad(gamepad); | |||||
} | |||||
if (tokens[4] == "button") | |||||
{ | |||||
std::stringstream buttonstream(tokens[5]); | |||||
int button = -1; | |||||
buttonstream >> button; | |||||
control->bindGamepadButton(gamepad, button); | |||||
} | |||||
else if (tokens[4] == "axis") | |||||
{ | |||||
bool negative = (tokens[5][0] == '-'); | |||||
std::stringstream axisstream(tokens[5].substr(1, tokens[5].length() - 1)); | |||||
int axis = -1; | |||||
axisstream >> axis; | |||||
control->bindGamepadAxis(gamepad, axis, negative); | |||||
} | |||||
else | |||||
{ | |||||
std::cerr << "Invalid line \"" << line << "\" in control profile \"" << filename << "\"" << std::endl; | |||||
continue; | |||||
} | |||||
} | |||||
else | |||||
{ | |||||
std::cerr << "Unsupported input device \"" << tokens[3] << "\" in control profile \"" << filename << "\"" << std::endl; | |||||
continue; | |||||
} | |||||
} | |||||
} | |||||
file.close(); | |||||
return true; | |||||
} | |||||
void ControlProfile::update() | |||||
{ | |||||
for (auto it = controls.begin(); it != controls.end(); ++it) | |||||
{ | |||||
it->second->update(); | |||||
} | |||||
} | |||||
@ -0,0 +1,121 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef CONTROLS_HPP | |||||
#define CONTROLS_HPP | |||||
#include "input.hpp" | |||||
#include <list> | |||||
#include <utility> | |||||
#include <tuple> | |||||
#include <map> | |||||
class Control: | |||||
public KeyObserver, | |||||
public MouseButtonObserver, | |||||
public GamepadButtonObserver, | |||||
public GamepadAxisObserver | |||||
{ | |||||
public: | |||||
Control(); | |||||
virtual ~Control(); | |||||
void setDeadzone(float value); | |||||
void update(); | |||||
float getDeadzone() const; | |||||
float getCurrentValue() const; | |||||
float getPreviousValue() const; | |||||
bool isTriggered() const; | |||||
bool wasTriggered() const; | |||||
bool isUnbound() const; | |||||
void bindKey(Keyboard* keyboard, int scancode); | |||||
void bindMouseButton(Mouse* mouse, int button); | |||||
void bindGamepadButton(Gamepad* gamepad, int button); | |||||
void bindGamepadAxis(Gamepad* gamepad, int axis, bool negative); | |||||
void bind(const InputEvent& event); | |||||
void unbind(); | |||||
virtual void keyPressed(int scancode); | |||||
virtual void keyReleased(int scancode); | |||||
virtual void mouseButtonPressed(int button, int x, int y); | |||||
virtual void mouseButtonReleased(int button, int x, int y); | |||||
virtual void gamepadButtonPressed(int button); | |||||
virtual void gamepadButtonReleased(int button); | |||||
virtual void gamepadAxisMoved(int axis, bool negative, float value); | |||||
const std::list<std::pair<Keyboard*, int>>* getBoundKeys() const; | |||||
const std::list<std::pair<Mouse*, int>>* getBoundMouseButtons() const; | |||||
const std::list<std::pair<Gamepad*, int>>* getBoundGamepadButtons() const; | |||||
const std::list<std::tuple<Gamepad*, int, bool>>* getBoundGamepadAxes() const; | |||||
private: | |||||
float deadzone; | |||||
float currentValue; | |||||
float previousValue; | |||||
std::list<std::pair<Keyboard*, int>> boundKeys; | |||||
std::list<std::pair<Mouse*, int>> boundMouseButtons; | |||||
std::list<std::pair<Gamepad*, int>> boundGamepadButtons; | |||||
std::list<std::tuple<Gamepad*, int, bool>> boundGamepadAxes; | |||||
}; | |||||
inline float Control::getDeadzone() const | |||||
{ | |||||
return deadzone; | |||||
} | |||||
inline float Control::getCurrentValue() const | |||||
{ | |||||
return currentValue; | |||||
} | |||||
inline float Control::getPreviousValue() const | |||||
{ | |||||
return previousValue; | |||||
} | |||||
class ControlProfile | |||||
{ | |||||
public: | |||||
ControlProfile(InputManager* inputManager); | |||||
void registerControl(const std::string& name, Control* control); | |||||
bool save(const std::string& filename); | |||||
bool load(const std::string& filename); | |||||
// Calls Control::update() on each control registered with this profile | |||||
void update(); | |||||
const std::map<std::string, Control*>* getControlMap() const; | |||||
private: | |||||
InputManager* inputManager; | |||||
std::map<std::string, Control*> controls; | |||||
}; | |||||
inline const std::map<std::string, Control*>* ControlProfile::getControlMap() const | |||||
{ | |||||
return &controls; | |||||
} | |||||
#endif | |||||
@ -0,0 +1,80 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "debug.hpp" | |||||
#include <iostream> | |||||
LineBatcher::LineBatcher(std::size_t lineCount): | |||||
lineCount(lineCount), | |||||
currentLine(0), | |||||
width(1.0f), | |||||
color(1.0f) | |||||
{ | |||||
batch.resize(lineCount); | |||||
range = batch.addRange(); | |||||
range->material = &material; | |||||
material.color = Vector3(1.0f); | |||||
} | |||||
void LineBatcher::begin() | |||||
{ | |||||
currentLine = 0; | |||||
range->start = 0; | |||||
range->length = 0; | |||||
} | |||||
void LineBatcher::end() | |||||
{ | |||||
range->length = currentLine; | |||||
batch.update(); | |||||
} | |||||
void LineBatcher::draw(const Vector3& start, const Vector3& end) | |||||
{ | |||||
if (currentLine >= batch.getBillboardCount()) | |||||
{ | |||||
std::cout << "LineBatcher::draw(): maximum line count exceeded" << std::endl; | |||||
return; | |||||
} | |||||
Vector3 center = (start + end) * 0.5f; | |||||
float length = glm::length(end - start); | |||||
Vector3 forward = glm::normalize(end - start); | |||||
glm::quat rotation = glm::normalize(glm::rotation(Vector3(1, 0, 0), forward)); | |||||
Billboard* billboard = batch.getBillboard(currentLine); | |||||
billboard->setTranslation(center); | |||||
billboard->setDimensions(Vector2(length, width)); | |||||
billboard->setRotation(rotation); | |||||
billboard->setTintColor(color); | |||||
++currentLine; | |||||
} | |||||
void LineBatcher::setWidth(float width) | |||||
{ | |||||
this->width = width; | |||||
} | |||||
void LineBatcher::setColor(const Vector4& color) | |||||
{ | |||||
this->color = color; | |||||
} |
@ -0,0 +1,65 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef DEBUG_HPP | |||||
#define DEBUG_HPP | |||||
#include <emergent/emergent.hpp> | |||||
#include "materials.hpp" | |||||
using namespace Emergent; | |||||
class LineBatcher | |||||
{ | |||||
public: | |||||
LineBatcher(std::size_t lineCount); | |||||
~LineBatcher(); | |||||
void setWidth(float width); | |||||
void setColor(const Vector4& color); | |||||
void begin(); | |||||
void end(); | |||||
void draw(const Vector3& start, const Vector3& end); | |||||
const BillboardBatch* getBatch() const; | |||||
BillboardBatch* getBatch(); | |||||
private: | |||||
std::size_t lineCount; | |||||
std::size_t currentLine; | |||||
BillboardBatch batch; | |||||
BillboardBatch::Range* range; | |||||
float width; | |||||
Vector4 color; | |||||
PhysicalMaterial material; | |||||
}; | |||||
inline const BillboardBatch* LineBatcher::getBatch() const | |||||
{ | |||||
return &batch; | |||||
} | |||||
inline BillboardBatch* LineBatcher::getBatch() | |||||
{ | |||||
return &batch; | |||||
} | |||||
#endif // DEBUG_HPP |
@ -0,0 +1,704 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "input.hpp" | |||||
#include <iostream> | |||||
InputDevice::InputDevice(const std::string& name): | |||||
name(name), | |||||
disconnected(true) | |||||
{} | |||||
void InputDevice::setDisconnected(bool disconnected) | |||||
{ | |||||
this->disconnected = disconnected; | |||||
} | |||||
Keyboard::Keyboard(const std::string& name): | |||||
InputDevice(name) | |||||
{} | |||||
Keyboard::~Keyboard() | |||||
{} | |||||
void Keyboard::addKeyObserver(KeyObserver* observer) | |||||
{ | |||||
keyObservers.push_back(observer); | |||||
} | |||||
void Keyboard::removeKeyObserver(KeyObserver* observer) | |||||
{ | |||||
keyObservers.remove(observer); | |||||
} | |||||
void Keyboard::removeKeyObservers() | |||||
{ | |||||
keyObservers.clear(); | |||||
} | |||||
void Keyboard::press(int scancode) | |||||
{ | |||||
for (auto observer: keyObservers) | |||||
{ | |||||
observer->keyPressed(scancode); | |||||
} | |||||
} | |||||
void Keyboard::release(int scancode) | |||||
{ | |||||
for (auto observer: keyObservers) | |||||
{ | |||||
observer->keyReleased(scancode); | |||||
} | |||||
} | |||||
Mouse::Mouse(const std::string& name): | |||||
InputDevice(name), | |||||
notifyingMotionObservers(false), | |||||
notifyingButtonObservers(false) | |||||
{} | |||||
Mouse::~Mouse() | |||||
{} | |||||
void Mouse::addMouseMotionObserver(MouseMotionObserver* observer) | |||||
{ | |||||
if (notifyingMotionObservers) | |||||
{ | |||||
additionFlaggedMotionObservers.push_back(observer); | |||||
} | |||||
else | |||||
{ | |||||
motionObservers.push_back(observer); | |||||
} | |||||
} | |||||
void Mouse::addMouseButtonObserver(MouseButtonObserver* observer) | |||||
{ | |||||
if (notifyingButtonObservers) | |||||
{ | |||||
additionFlaggedButtonObservers.push_back(observer); | |||||
} | |||||
else | |||||
{ | |||||
buttonObservers.push_back(observer); | |||||
} | |||||
} | |||||
void Mouse::removeMouseMotionObserver(MouseMotionObserver* observer) | |||||
{ | |||||
if (notifyingMotionObservers) | |||||
{ | |||||
removalFlaggedMotionObservers.push_back(observer); | |||||
} | |||||
else | |||||
{ | |||||
motionObservers.remove(observer); | |||||
} | |||||
} | |||||
void Mouse::removeMouseButtonObserver(MouseButtonObserver* observer) | |||||
{ | |||||
if (notifyingButtonObservers) | |||||
{ | |||||
removalFlaggedButtonObservers.push_back(observer); | |||||
} | |||||
else | |||||
{ | |||||
buttonObservers.remove(observer); | |||||
} | |||||
} | |||||
void Mouse::removeMouseMotionObservers() | |||||
{ | |||||
motionObservers.clear(); | |||||
} | |||||
void Mouse::removeMouseButtonObservers() | |||||
{ | |||||
buttonObservers.clear(); | |||||
} | |||||
void Mouse::press(int button, int x, int y) | |||||
{ | |||||
// Notify observers | |||||
notifyingButtonObservers = true; | |||||
for (auto observer: buttonObservers) | |||||
{ | |||||
observer->mouseButtonPressed(button, x, y); | |||||
} | |||||
notifyingButtonObservers = false; | |||||
// Process flags | |||||
processFlaggedButtonObservers(); | |||||
} | |||||
void Mouse::release(int button, int x, int y) | |||||
{ | |||||
// Notify observers | |||||
notifyingButtonObservers = true; | |||||
for (auto observer: buttonObservers) | |||||
{ | |||||
observer->mouseButtonReleased(button, x, y); | |||||
} | |||||
notifyingButtonObservers = false; | |||||
// Process flags | |||||
processFlaggedButtonObservers(); | |||||
} | |||||
void Mouse::move(int x, int y) | |||||
{ | |||||
previousPosition = currentPosition; | |||||
currentPosition = glm::ivec2(x, y); | |||||
// Notify observers | |||||
notifyingMotionObservers = true; | |||||
for (auto observer: motionObservers) | |||||
{ | |||||
observer->mouseMoved(x, y); | |||||
} | |||||
notifyingMotionObservers = false; | |||||
// Process flags | |||||
processFlaggedMotionObservers(); | |||||
} | |||||
void Mouse::processFlaggedMotionObservers() | |||||
{ | |||||
// Remove observers which are flagged for removal | |||||
for (auto observer: removalFlaggedMotionObservers) | |||||
{ | |||||
motionObservers.remove(observer); | |||||
} | |||||
removalFlaggedMotionObservers.clear(); | |||||
// Add observers which are flagged for addition | |||||
for (auto observer: additionFlaggedMotionObservers) | |||||
{ | |||||
motionObservers.push_back(observer); | |||||
} | |||||
additionFlaggedMotionObservers.clear(); | |||||
} | |||||
void Mouse::processFlaggedButtonObservers() | |||||
{ | |||||
// Remove observers which are flagged for removal | |||||
for (auto observer: removalFlaggedButtonObservers) | |||||
{ | |||||
buttonObservers.remove(observer); | |||||
} | |||||
removalFlaggedButtonObservers.clear(); | |||||
// Add observers which are flagged for addition | |||||
for (auto observer: additionFlaggedButtonObservers) | |||||
{ | |||||
buttonObservers.push_back(observer); | |||||
} | |||||
additionFlaggedButtonObservers.clear(); | |||||
} | |||||
Gamepad::Gamepad(const std::string& name): | |||||
InputDevice(name) | |||||
{} | |||||
Gamepad::~Gamepad() | |||||
{} | |||||
void Gamepad::addGamepadButtonObserver(GamepadButtonObserver* observer) | |||||
{ | |||||
buttonObservers.push_back(observer); | |||||
} | |||||
void Gamepad::removeGamepadButtonObserver(GamepadButtonObserver* observer) | |||||
{ | |||||
buttonObservers.remove(observer); | |||||
} | |||||
void Gamepad::removeGamepadButtonObservers() | |||||
{ | |||||
buttonObservers.clear(); | |||||
} | |||||
void Gamepad::addGamepadAxisObserver(GamepadAxisObserver* observer) | |||||
{ | |||||
axisObservers.push_back(observer); | |||||
} | |||||
void Gamepad::removeGamepadAxisObserver(GamepadAxisObserver* observer) | |||||
{ | |||||
axisObservers.remove(observer); | |||||
} | |||||
void Gamepad::removeGamepadAxisObservers() | |||||
{ | |||||
axisObservers.clear(); | |||||
} | |||||
void Gamepad::press(int button) | |||||
{ | |||||
for (auto observer: buttonObservers) | |||||
{ | |||||
observer->gamepadButtonPressed(button); | |||||
} | |||||
} | |||||
void Gamepad::release(int button) | |||||
{ | |||||
for (auto observer: buttonObservers) | |||||
{ | |||||
observer->gamepadButtonReleased(button); | |||||
} | |||||
} | |||||
void Gamepad::move(int axis, bool negative, float value) | |||||
{ | |||||
for (auto observer: axisObservers) | |||||
{ | |||||
observer->gamepadAxisMoved(axis, negative, value); | |||||
} | |||||
} | |||||
InputEvent::InputEvent(): | |||||
type(InputEvent::Type::NONE) | |||||
{} | |||||
InputManager::InputManager(): | |||||
closed(false) | |||||
{} | |||||
void InputManager::addWindowObserver(WindowObserver* observer) | |||||
{ | |||||
windowObservers.push_back(observer); | |||||
} | |||||
void InputManager::removeWindowObserver(WindowObserver* observer) | |||||
{ | |||||
windowObservers.remove(observer); | |||||
} | |||||
void InputManager::removeWindowObservers() | |||||
{ | |||||
windowObservers.clear(); | |||||
} | |||||
void InputManager::registerKeyboard(Keyboard* keyboard) | |||||
{ | |||||
keyboards.push_back(keyboard); | |||||
} | |||||
void InputManager::registerMouse(Mouse* mouse) | |||||
{ | |||||
mice.push_back(mouse); | |||||
} | |||||
void InputManager::registerGamepad(Gamepad* gamepad) | |||||
{ | |||||
gamepads.push_back(gamepad); | |||||
} | |||||
void InputManager::unregisterKeyboard(Keyboard* keyboard) | |||||
{ | |||||
keyboards.remove(keyboard); | |||||
} | |||||
void InputManager::unregisterMouse(Mouse* mouse) | |||||
{ | |||||
mice.remove(mouse); | |||||
} | |||||
void InputManager::unregisterGamepad(Gamepad* gamepad) | |||||
{ | |||||
gamepads.remove(gamepad); | |||||
} | |||||
bool InputManager::isRegistered(const Keyboard* keyboard) const | |||||
{ | |||||
for (auto it = keyboards.begin(); it != keyboards.end(); ++it) | |||||
{ | |||||
if (*it == keyboard) | |||||
return true; | |||||
} | |||||
return false; | |||||
} | |||||
bool InputManager::isRegistered(const Mouse* mouse) const | |||||
{ | |||||
for (auto it = mice.begin(); it != mice.end(); ++it) | |||||
{ | |||||
if (*it == mouse) | |||||
return true; | |||||
} | |||||
return false; | |||||
} | |||||
bool InputManager::isRegistered(const Gamepad* gamepad) const | |||||
{ | |||||
for (auto it = gamepads.begin(); it != gamepads.end(); ++it) | |||||
{ | |||||
if (*it == gamepad) | |||||
return true; | |||||
} | |||||
return false; | |||||
} | |||||
const Gamepad* InputManager::getGamepad(const std::string& name) const | |||||
{ | |||||
for (auto gamepad: gamepads) | |||||
{ | |||||
if (gamepad->getName() == name) | |||||
return gamepad; | |||||
} | |||||
return nullptr; | |||||
} | |||||
Gamepad* InputManager::getGamepad(const std::string& name) | |||||
{ | |||||
for (auto gamepad: gamepads) | |||||
{ | |||||
if (gamepad->getName() == name) | |||||
return gamepad; | |||||
} | |||||
return nullptr; | |||||
} | |||||
SDLInputManager::SDLInputManager() | |||||
{ | |||||
keyboard = new Keyboard("Default Keyboard"); | |||||
mouse = new Mouse("Default Mouse"); | |||||
registerKeyboard(keyboard); | |||||
registerMouse(mouse); | |||||
keyboard->setDisconnected(false); | |||||
mouse->setDisconnected(false); | |||||
} | |||||
SDLInputManager::~SDLInputManager() | |||||
{ | |||||
unregisterKeyboard(keyboard); | |||||
unregisterMouse(mouse); | |||||
for (auto gamepad: allocatedGamepads) | |||||
{ | |||||
unregisterGamepad(gamepad); | |||||
delete gamepad; | |||||
} | |||||
delete keyboard; | |||||
delete mouse; | |||||
} | |||||
void SDLInputManager::update() | |||||
{ | |||||
while (SDL_PollEvent(&event)) | |||||
{ | |||||
switch (event.type) | |||||
{ | |||||
case SDL_KEYDOWN: | |||||
{ | |||||
int scancode = event.key.keysym.scancode; | |||||
keyboard->press(scancode); | |||||
break; | |||||
} | |||||
case SDL_KEYUP: | |||||
{ | |||||
int scancode = event.key.keysym.scancode; | |||||
keyboard->release(scancode); | |||||
break; | |||||
} | |||||
case SDL_MOUSEMOTION: | |||||
{ | |||||
int x = event.motion.x; | |||||
int y = event.motion.y; | |||||
mouse->move(x, y); | |||||
break; | |||||
} | |||||
case SDL_MOUSEBUTTONDOWN: | |||||
{ | |||||
int button = event.button.button; | |||||
mouse->press(button, event.button.x, event.button.y); | |||||
break; | |||||
} | |||||
case SDL_MOUSEBUTTONUP: | |||||
{ | |||||
int button = event.button.button; | |||||
mouse->release(button, event.button.x, event.button.y); | |||||
break; | |||||
} | |||||
case SDL_CONTROLLERBUTTONDOWN: | |||||
{ | |||||
int instanceID = event.cbutton.which; | |||||
auto it = gamepadMap.find(instanceID); | |||||
if (it == gamepadMap.end()) | |||||
{ | |||||
std::cerr << "Received event from invalid gamepad" << std::endl; | |||||
break; | |||||
} | |||||
Gamepad* gamepad = it->second; | |||||
int button = event.cbutton.button; | |||||
gamepad->press(button); | |||||
break; | |||||
} | |||||
case SDL_CONTROLLERBUTTONUP: | |||||
{ | |||||
int instanceID = event.cbutton.which; | |||||
auto it = gamepadMap.find(instanceID); | |||||
if (it == gamepadMap.end()) | |||||
{ | |||||
std::cerr << "Received event from invalid gamepad" << std::endl; | |||||
break; | |||||
} | |||||
Gamepad* gamepad = it->second; | |||||
int button = event.cbutton.button; | |||||
gamepad->release(button); | |||||
break; | |||||
} | |||||
case SDL_CONTROLLERAXISMOTION: | |||||
{ | |||||
int instanceID = event.caxis.which; | |||||
auto it = gamepadMap.find(instanceID); | |||||
if (it == gamepadMap.end()) | |||||
{ | |||||
std::cerr << "Received event from invalid gamepad" << std::endl; | |||||
break; | |||||
} | |||||
Gamepad* gamepad = it->second; | |||||
int axis = event.caxis.axis; | |||||
bool negative; | |||||
float value; | |||||
if (event.caxis.value < 0) | |||||
{ | |||||
negative = true; | |||||
value = (float)event.caxis.value / -32768.0f; | |||||
} | |||||
else | |||||
{ | |||||
negative = false; | |||||
value = (float)event.caxis.value / 32767.0f; | |||||
} | |||||
gamepad->move(axis, negative, value); | |||||
break; | |||||
} | |||||
case SDL_CONTROLLERDEVICEADDED: | |||||
{ | |||||
SDL_GameController* controller = SDL_GameControllerOpen(event.cdevice.which); | |||||
if (controller != nullptr) | |||||
{ | |||||
// Find controller's joystick instance ID | |||||
SDL_Joystick* joystick = SDL_GameControllerGetJoystick(controller); | |||||
int instanceID = SDL_JoystickInstanceID(joystick); | |||||
// Determine gamepad name | |||||
std::string name = SDL_GameControllerName(controller); | |||||
if (name.empty()) | |||||
{ | |||||
name = "Unknown Gamepad"; | |||||
} | |||||
bool reconnected = false; | |||||
const std::list<Gamepad*>* gamepads = getGamepads(); | |||||
for (auto it = gamepads->begin(); it != gamepads->end(); ++it) | |||||
{ | |||||
// Check if this gamepad was previously connected | |||||
if ((*it)->isDisconnected() && (*it)->getName() == name) | |||||
{ | |||||
// Map to new instance ID | |||||
Gamepad* gamepad = *it; | |||||
gamepadMap[instanceID] = gamepad; | |||||
gamepad->setDisconnected(false); | |||||
reconnected = true; | |||||
std::cout << "Reconnected gamepad \"" << name << "\" with ID " << instanceID << std::endl; | |||||
break; | |||||
} | |||||
} | |||||
if (!reconnected) | |||||
{ | |||||
// Create new gamepad | |||||
Gamepad* gamepad = new Gamepad(name); | |||||
// Add to list of allocated gamepads | |||||
allocatedGamepads.push_back(gamepad); | |||||
// Register with the input manager | |||||
registerGamepad(gamepad); | |||||
// Map instance ID to gamepad pointer | |||||
gamepadMap[instanceID] = gamepad; | |||||
// Connect gamepad | |||||
gamepad->setDisconnected(false); | |||||
std::cout << "Connected gamepad \"" << name << "\" with ID " << instanceID << std::endl; | |||||
} | |||||
} | |||||
break; | |||||
} | |||||
case SDL_CONTROLLERDEVICEREMOVED: | |||||
{ | |||||
int instanceID = event.cdevice.which; | |||||
// Find gamepad | |||||
auto mapIt = gamepadMap.find(instanceID); | |||||
if (mapIt == gamepadMap.end()) | |||||
{ | |||||
std::cerr << "Attempted to remove nonexistent gamepad with ID " << instanceID << std::endl; | |||||
break; | |||||
} | |||||
Gamepad* gamepad = mapIt->second; | |||||
// Remove from gamepad map | |||||
gamepadMap.erase(mapIt); | |||||
// Set disconnected flag | |||||
gamepad->setDisconnected(true); | |||||
std::cout << "Disconnected gamepad \"" << gamepad->getName() << "\" with ID " << instanceID << std::endl; | |||||
break; | |||||
} | |||||
case SDL_WINDOWEVENT: | |||||
{ | |||||
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) | |||||
{ | |||||
for (auto observer: windowObservers) | |||||
{ | |||||
observer->windowResized(event.window.data1, event.window.data2); | |||||
} | |||||
} | |||||
else if (event.window.event == SDL_WINDOWEVENT_CLOSE) | |||||
{ | |||||
closed = true; | |||||
for (auto observer: windowObservers) | |||||
{ | |||||
observer->windowClosed(); | |||||
} | |||||
} | |||||
break; | |||||
} | |||||
case SDL_QUIT: | |||||
{ | |||||
closed = true; | |||||
for (auto observer: windowObservers) | |||||
{ | |||||
observer->windowClosed(); | |||||
} | |||||
break; | |||||
} | |||||
default: | |||||
break; | |||||
} | |||||
} | |||||
} | |||||
void SDLInputManager::listen(InputEvent* inputEvent) | |||||
{ | |||||
int eventCount; | |||||
// Gather events | |||||
SDL_PumpEvents(); | |||||
// Check for key events | |||||
eventCount = SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, SDL_KEYDOWN, SDL_KEYDOWN); | |||||
if (eventCount) | |||||
{ | |||||
int scancode = event.key.keysym.scancode; | |||||
inputEvent->type = InputEvent::Type::KEY; | |||||
inputEvent->key.first = keyboard; | |||||
inputEvent->key.second = scancode; | |||||
return; | |||||
} | |||||
// Check for mouse button events | |||||
eventCount = SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONDOWN); | |||||
if (eventCount) | |||||
{ | |||||
int button = event.button.button; | |||||
inputEvent->type = InputEvent::Type::MOUSE_BUTTON; | |||||
inputEvent->mouseButton.first = mouse; | |||||
inputEvent->mouseButton.second = button; | |||||
return; | |||||
} | |||||
// Check for gamepad button events | |||||
eventCount = SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, SDL_CONTROLLERBUTTONDOWN, SDL_CONTROLLERBUTTONDOWN); | |||||
if (eventCount) | |||||
{ | |||||
int instanceID = event.cbutton.which; | |||||
auto it = gamepadMap.find(instanceID); | |||||
if (it == gamepadMap.end()) | |||||
{ | |||||
std::cerr << "Received event from invalid gamepad" << std::endl; | |||||
return; | |||||
} | |||||
Gamepad* gamepad = it->second; | |||||
int button = event.cbutton.button; | |||||
inputEvent->type = InputEvent::Type::GAMEPAD_BUTTON; | |||||
inputEvent->gamepadButton.first = gamepad; | |||||
inputEvent->gamepadButton.second = button; | |||||
return; | |||||
} | |||||
// Check for gamepad axis events | |||||
eventCount = SDL_PeepEvents(&event, 1, SDL_PEEKEVENT, SDL_CONTROLLERAXISMOTION, SDL_CONTROLLERAXISMOTION); | |||||
if (eventCount) | |||||
{ | |||||
int instanceID = event.caxis.which; | |||||
auto it = gamepadMap.find(instanceID); | |||||
if (it == gamepadMap.end()) | |||||
{ | |||||
std::cerr << "Received event from invalid gamepad" << std::endl; | |||||
return; | |||||
} | |||||
Gamepad* gamepad = it->second; | |||||
int axis = event.caxis.axis; | |||||
bool negative = event.caxis.value < 0; | |||||
inputEvent->type = InputEvent::Type::GAMEPAD_AXIS; | |||||
std::get<0>(inputEvent->gamepadAxis) = gamepad; | |||||
std::get<1>(inputEvent->gamepadAxis) = axis; | |||||
std::get<2>(inputEvent->gamepadAxis) = negative; | |||||
return; | |||||
} | |||||
} |
@ -0,0 +1,316 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef INPUT_HPP | |||||
#define INPUT_HPP | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
#include <string> | |||||
#include <iostream> | |||||
#include <map> | |||||
#include <list> | |||||
#include <SDL.h> | |||||
class KeyObserver | |||||
{ | |||||
public: | |||||
virtual void keyPressed(int scancode) = 0; | |||||
virtual void keyReleased(int scancode) = 0; | |||||
}; | |||||
class MouseMotionObserver | |||||
{ | |||||
public: | |||||
virtual void mouseMoved(int x, int y) = 0; | |||||
}; | |||||
class MouseButtonObserver | |||||
{ | |||||
public: | |||||
virtual void mouseButtonPressed(int button, int x, int y) = 0; | |||||
virtual void mouseButtonReleased(int button, int x, int y) = 0; | |||||
}; | |||||
class GamepadButtonObserver | |||||
{ | |||||
public: | |||||
virtual void gamepadButtonPressed(int button) = 0; | |||||
virtual void gamepadButtonReleased(int button) = 0; | |||||
}; | |||||
class GamepadAxisObserver | |||||
{ | |||||
public: | |||||
virtual void gamepadAxisMoved(int axis, bool negative, float value) = 0; | |||||
}; | |||||
class WindowObserver | |||||
{ | |||||
public: | |||||
virtual void windowClosed() = 0; | |||||
virtual void windowResized(int width, int height) = 0; | |||||
}; | |||||
class InputDevice | |||||
{ | |||||
public: | |||||
enum class Type | |||||
{ | |||||
KEYBOARD, | |||||
MOUSE, | |||||
GAMEPAD | |||||
}; | |||||
InputDevice(const std::string& name); | |||||
const std::string& getName() const; | |||||
virtual InputDevice::Type getType() const = 0; | |||||
void setDisconnected(bool disconnected); | |||||
bool isDisconnected() const; | |||||
private: | |||||
std::string name; | |||||
bool disconnected; | |||||
}; | |||||
inline const std::string& InputDevice::getName() const | |||||
{ | |||||
return name; | |||||
} | |||||
inline bool InputDevice::isDisconnected() const | |||||
{ | |||||
return disconnected; | |||||
} | |||||
class Keyboard: public InputDevice | |||||
{ | |||||
public: | |||||
Keyboard(const std::string& name); | |||||
virtual ~Keyboard(); | |||||
InputDevice::Type getType() const; | |||||
void addKeyObserver(KeyObserver* observer); | |||||
void removeKeyObserver(KeyObserver* observer); | |||||
void removeKeyObservers(); | |||||
void press(int scancode); | |||||
void release(int scancode); | |||||
private: | |||||
std::list<KeyObserver*> keyObservers; | |||||
}; | |||||
inline InputDevice::Type Keyboard::getType() const | |||||
{ | |||||
return InputDevice::Type::KEYBOARD; | |||||
} | |||||
class Mouse: public InputDevice | |||||
{ | |||||
public: | |||||
Mouse(const std::string& name); | |||||
virtual ~Mouse(); | |||||
InputDevice::Type getType() const; | |||||
void addMouseMotionObserver(MouseMotionObserver* observer); | |||||
void addMouseButtonObserver(MouseButtonObserver* observer); | |||||
void removeMouseMotionObserver(MouseMotionObserver* observer); | |||||
void removeMouseButtonObserver(MouseButtonObserver* observer); | |||||
void removeMouseMotionObservers(); | |||||
void removeMouseButtonObservers(); | |||||
void press(int button, int x, int y); | |||||
void release(int button, int x, int y); | |||||
void move(int x, int y); | |||||
const glm::ivec2& getCurrentPosition() const; | |||||
const glm::ivec2& getPreviousPosition() const; | |||||
private: | |||||
void processFlaggedMotionObservers(); | |||||
void processFlaggedButtonObservers(); | |||||
glm::ivec2 currentPosition; | |||||
glm::ivec2 previousPosition; | |||||
std::list<MouseMotionObserver*> motionObservers; | |||||
std::list<MouseButtonObserver*> buttonObservers; | |||||
bool notifyingMotionObservers; | |||||
bool notifyingButtonObservers; | |||||
std::list<MouseMotionObserver*> additionFlaggedMotionObservers; | |||||
std::list<MouseButtonObserver*> additionFlaggedButtonObservers; | |||||
std::list<MouseMotionObserver*> removalFlaggedMotionObservers; | |||||
std::list<MouseButtonObserver*> removalFlaggedButtonObservers; | |||||
}; | |||||
inline InputDevice::Type Mouse::getType() const | |||||
{ | |||||
return InputDevice::Type::MOUSE; | |||||
} | |||||
inline const glm::ivec2& Mouse::getCurrentPosition() const | |||||
{ | |||||
return currentPosition; | |||||
} | |||||
inline const glm::ivec2& Mouse::getPreviousPosition() const | |||||
{ | |||||
return previousPosition; | |||||
} | |||||
class Gamepad: public InputDevice | |||||
{ | |||||
public: | |||||
Gamepad(const std::string& name); | |||||
virtual ~Gamepad(); | |||||
InputDevice::Type getType() const; | |||||
void addGamepadButtonObserver(GamepadButtonObserver* observer); | |||||
void removeGamepadButtonObserver(GamepadButtonObserver* observer); | |||||
void removeGamepadButtonObservers(); | |||||
void addGamepadAxisObserver(GamepadAxisObserver* observer); | |||||
void removeGamepadAxisObserver(GamepadAxisObserver* observer); | |||||
void removeGamepadAxisObservers(); | |||||
void press(int button); | |||||
void release(int button); | |||||
void move(int axis, bool negative, float value); | |||||
private: | |||||
std::list<GamepadButtonObserver*> buttonObservers; | |||||
std::list<GamepadAxisObserver*> axisObservers; | |||||
}; | |||||
inline InputDevice::Type Gamepad::getType() const | |||||
{ | |||||
return InputDevice::Type::GAMEPAD; | |||||
} | |||||
struct InputEvent | |||||
{ | |||||
public: | |||||
enum class Type | |||||
{ | |||||
NONE, | |||||
KEY, | |||||
MOUSE_BUTTON, | |||||
GAMEPAD_BUTTON, | |||||
GAMEPAD_AXIS | |||||
}; | |||||
InputEvent(); | |||||
InputEvent::Type type; | |||||
std::pair<Keyboard*, int> key; | |||||
std::pair<Mouse*, int> mouseButton; | |||||
std::pair<Gamepad*, int> gamepadButton; | |||||
std::tuple<Gamepad*, int, int> gamepadAxis; | |||||
}; | |||||
class InputManager | |||||
{ | |||||
public: | |||||
InputManager(); | |||||
// Processes input events | |||||
virtual void update() = 0; | |||||
// Listens for the next input event, should be called BEFORE update() | |||||
virtual void listen(InputEvent* inputEvent) = 0; | |||||
bool wasClosed() const; | |||||
void addWindowObserver(WindowObserver* observer); | |||||
void removeWindowObserver(WindowObserver* observer); | |||||
void removeWindowObservers(); | |||||
void registerKeyboard(Keyboard* keyboard); | |||||
void registerMouse(Mouse* mouse); | |||||
void registerGamepad(Gamepad* gamepad); | |||||
void unregisterKeyboard(Keyboard* keyboard); | |||||
void unregisterMouse(Mouse* mouse); | |||||
void unregisterGamepad(Gamepad* gamepad); | |||||
bool isRegistered(const Keyboard* keyboard) const; | |||||
bool isRegistered(const Mouse* mouse) const; | |||||
bool isRegistered(const Gamepad* gamepad) const; | |||||
const Gamepad* getGamepad(const std::string& name) const; | |||||
Gamepad* getGamepad(const std::string& name); | |||||
const std::list<Keyboard*>* getKeyboards() const; | |||||
const std::list<Mouse*>* getMice() const; | |||||
const std::list<Gamepad*>* getGamepads() const; | |||||
protected: | |||||
bool closed; | |||||
std::list<WindowObserver*> windowObservers; | |||||
private: | |||||
std::list<Keyboard*> keyboards; | |||||
std::list<Mouse*> mice; | |||||
std::list<Gamepad*> gamepads; | |||||
}; | |||||
inline bool InputManager::wasClosed() const | |||||
{ | |||||
return closed; | |||||
} | |||||
inline const std::list<Keyboard*>* InputManager::getKeyboards() const | |||||
{ | |||||
return &keyboards; | |||||
} | |||||
inline const std::list<Mouse*>* InputManager::getMice() const | |||||
{ | |||||
return &mice; | |||||
} | |||||
inline const std::list<Gamepad*>* InputManager::getGamepads() const | |||||
{ | |||||
return &gamepads; | |||||
} | |||||
class SDLInputManager: public InputManager | |||||
{ | |||||
public: | |||||
SDLInputManager(); | |||||
~SDLInputManager(); | |||||
virtual void update(); | |||||
virtual void listen(InputEvent* event); | |||||
private: | |||||
Keyboard* keyboard; | |||||
Mouse* mouse; | |||||
std::map<int, Gamepad*> gamepadMap; | |||||
SDL_Event event; | |||||
std::list<Gamepad*> allocatedGamepads; | |||||
}; | |||||
#endif | |||||
@ -0,0 +1,25 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "application.hpp" | |||||
int main(int argc, char* argv[]) | |||||
{ | |||||
return Application(argc, argv).execute(); | |||||
} |
@ -0,0 +1,199 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "material-loader.hpp" | |||||
#include <fstream> | |||||
#include <sstream> | |||||
#include <vector> | |||||
MaterialLoader::MaterialLoader() | |||||
{} | |||||
MaterialLoader::~MaterialLoader() | |||||
{ | |||||
unload(); | |||||
} | |||||
void MaterialLoader::unload() | |||||
{ | |||||
for (auto it = materialCache.begin(); it != materialCache.end(); ++it) | |||||
{ | |||||
delete it->second; | |||||
} | |||||
materialCache.clear(); | |||||
for (auto it = textureCache.begin(); it != textureCache.end(); ++it) | |||||
{ | |||||
delete it->second; | |||||
} | |||||
textureCache.clear(); | |||||
} | |||||
PhysicalMaterial* MaterialLoader::load(const std::string& filename) | |||||
{ | |||||
// Check if material exists in cache | |||||
auto it = materialCache.find(filename); | |||||
if (it != materialCache.end()) | |||||
{ | |||||
return it->second; | |||||
} | |||||
// Allocate new material | |||||
PhysicalMaterial* material = new PhysicalMaterial(); | |||||
// Open file | |||||
std::ifstream file(filename.c_str(), std::ifstream::in); | |||||
if (!file.is_open()) | |||||
{ | |||||
std::cerr << "MaterialLoader::load(): Failed to open material file \"" << filename << "\"" << std::endl; | |||||
delete material; | |||||
return nullptr; | |||||
} | |||||
// Parse lines | |||||
std::string line; | |||||
while (file.good() && std::getline(file, line)) | |||||
{ | |||||
const std::string whitespace = " \t"; | |||||
// Skip empty lines | |||||
if (line.empty()) | |||||
{ | |||||
continue; | |||||
} | |||||
// Find position of first character in command string | |||||
std::size_t firstCommand = line.find_first_not_of(whitespace, 0); | |||||
if (firstCommand == std::string::npos) | |||||
{ | |||||
continue; | |||||
} | |||||
// Find position of first character in delimeter string | |||||
std::size_t firstDelimeter = line.find_first_of(whitespace, firstCommand); | |||||
if (firstDelimeter == std::string::npos) | |||||
{ | |||||
continue; | |||||
} | |||||
// Find position of first character in arguments string | |||||
std::size_t firstArgument = line.find_first_not_of(whitespace, firstDelimeter); | |||||
if (firstArgument == std::string::npos) | |||||
{ | |||||
firstArgument = firstDelimeter + 1; | |||||
} | |||||
// Form command string and argument list string | |||||
std::string command = line.substr(firstCommand, firstDelimeter - firstCommand); | |||||
std::string argumentList = line.substr(firstArgument); | |||||
// Form vector of argument strings | |||||
std::vector<std::string> arguments; | |||||
std::istringstream argumentStream(argumentList); | |||||
std::string argument; | |||||
while (argumentStream >> argument) | |||||
{ | |||||
arguments.push_back(argument); | |||||
} | |||||
if (command == "color" && arguments.size() == 3) | |||||
{ | |||||
std::stringstream(arguments[0]) >> material->color.x; | |||||
std::stringstream(arguments[1]) >> material->color.y; | |||||
std::stringstream(arguments[2]) >> material->color.z; | |||||
} | |||||
else if (command == "roughness" && arguments.size() == 1) | |||||
{ | |||||
std::stringstream(arguments[0]) >> material->roughness; | |||||
} | |||||
else if (command == "metallic" && arguments.size() == 1) | |||||
{ | |||||
std::stringstream(arguments[0]) >> material->metallic; | |||||
} | |||||
else if (command == "specular" && arguments.size() == 1) | |||||
{ | |||||
std::stringstream(arguments[0]) >> material->specular; | |||||
} | |||||
else if (command == "opacity" && arguments.size() == 1) | |||||
{ | |||||
std::stringstream(arguments[0]) >> material->opacity; | |||||
} | |||||
else if (command == "color-map") | |||||
{ | |||||
material->colorMap = loadTexture(argumentList); | |||||
} | |||||
else if (command == "roughness-map") | |||||
{ | |||||
material->roughnessMap = loadTexture(argumentList); | |||||
} | |||||
else if (command == "metallic-map") | |||||
{ | |||||
material->metallicMap = loadTexture(argumentList); | |||||
} | |||||
else if (command == "specular-map") | |||||
{ | |||||
material->specularMap = loadTexture(argumentList); | |||||
} | |||||
else if (command == "opacity-map") | |||||
{ | |||||
material->opacityMap = loadTexture(argumentList); | |||||
} | |||||
else if (command == "normal-map") | |||||
{ | |||||
material->normalMap = loadTexture(argumentList); | |||||
} | |||||
else if (command[0] != '#') | |||||
{ | |||||
std::cerr << "MaterialLoader::load(): Invalid line \"" << line << "\" in file \"" << filename << "\"" << std::endl; | |||||
} | |||||
} | |||||
// Close file | |||||
file.close(); | |||||
// Add material to cache | |||||
materialCache[filename] = material; | |||||
return material; | |||||
} | |||||
Texture* MaterialLoader::loadTexture(const std::string& filename) | |||||
{ | |||||
// Check if texture exists in cache | |||||
auto it = textureCache.find(filename); | |||||
if (it != textureCache.end()) | |||||
{ | |||||
return it->second; | |||||
} | |||||
// Load texture | |||||
std::string fullFilename = std::string("data/textures/") + filename; | |||||
Texture* texture = new Texture(); | |||||
if (!texture->load(fullFilename)) | |||||
{ | |||||
std::cerr << "MaterialLoader::loadTexture(): Failed to load texture file \"" << fullFilename << "\"" << std::endl; | |||||
delete texture; | |||||
return nullptr; | |||||
} | |||||
// Add texture to cache | |||||
textureCache[filename] = texture; | |||||
return texture; | |||||
} |
@ -0,0 +1,41 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef MATERIAL_LOADER_HPP | |||||
#define MATERIAL_LOADER_HPP | |||||
#include <string> | |||||
#include "materials.hpp" | |||||
class MaterialLoader | |||||
{ | |||||
public: | |||||
MaterialLoader(); | |||||
~MaterialLoader(); | |||||
void unload(); | |||||
PhysicalMaterial* load(const std::string& filename); | |||||
private: | |||||
Texture* loadTexture(const std::string& filename); | |||||
std::map<std::string, Texture*> textureCache; | |||||
std::map<std::string, PhysicalMaterial*> materialCache; | |||||
}; | |||||
#endif // MATERIAL_LOADER_HPP |
@ -0,0 +1,85 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef MATERIALS | |||||
#define MATERIALS | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
enum class MaterialFormat | |||||
{ | |||||
UI, | |||||
PHYSICAL | |||||
}; | |||||
class UIMaterial: public Material | |||||
{ | |||||
public: | |||||
UIMaterial(): texture(nullptr) {} | |||||
virtual ~UIMaterial() {} | |||||
virtual unsigned int getMaterialFormatID() const; | |||||
Texture* texture; | |||||
}; | |||||
inline unsigned int UIMaterial::getMaterialFormatID() const | |||||
{ | |||||
return static_cast<unsigned int>(MaterialFormat::UI); | |||||
} | |||||
class PhysicalMaterial: public Material | |||||
{ | |||||
public: | |||||
PhysicalMaterial(): | |||||
colorMap(nullptr), | |||||
roughnessMap(nullptr), | |||||
metallicMap(nullptr), | |||||
specularMap(nullptr), | |||||
opacityMap(nullptr), | |||||
normalMap(nullptr) | |||||
{}; | |||||
virtual ~PhysicalMaterial() {}; | |||||
virtual unsigned int getMaterialFormatID() const; | |||||
Vector3 color; | |||||
float roughness; | |||||
float metallic; | |||||
float specular; | |||||
float opacity; | |||||
Texture* colorMap; | |||||
Texture* roughnessMap; | |||||
Texture* metallicMap; | |||||
Texture* specularMap; | |||||
Texture* opacityMap; | |||||
Texture* normalMap; | |||||
bool shadowCaster; | |||||
bool shadowReceiver; | |||||
}; | |||||
inline unsigned int PhysicalMaterial::getMaterialFormatID() const | |||||
{ | |||||
return static_cast<unsigned int>(MaterialFormat::PHYSICAL); | |||||
} | |||||
#endif // MATERIALS |
@ -0,0 +1,401 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "mesh.hpp" | |||||
#include <iostream> | |||||
#include <fstream> | |||||
#include <map> | |||||
#include <string> | |||||
#include <sstream> | |||||
#include <vector> | |||||
#include <limits> | |||||
bool loadHeightmap(const std::string& filename, glm::vec3 scale, WingedEdge* mesh) | |||||
{ | |||||
int width; | |||||
int height; | |||||
int components; | |||||
// Load image data | |||||
unsigned char* pixels = stbi_load(filename.c_str(), &width, &height, &components, 1); | |||||
if (!pixels) | |||||
{ | |||||
std::cerr << "Failed to load heightmap image \"" << filename << "\"\n"; | |||||
return false; | |||||
} | |||||
std::size_t vertexCount = width * height; | |||||
std::size_t triangleCount = (width - 1) * (height - 1) * 2; | |||||
std::size_t indexCount = triangleCount * 3; | |||||
std::vector<glm::vec3> vertices(vertexCount); | |||||
std::vector<std::size_t> indices(indexCount); | |||||
// Adjust scale | |||||
scale.x *= 1.0f / ((float)width - 1); | |||||
scale.y *= 1.0f / 255.0f; | |||||
scale.z *= 1.0f / ((float)height - 1); | |||||
if (width > height) scale.z *= (float)height / (float) width; | |||||
else if (height > width) scale.x *= (float)width / (float)height; | |||||
// Calculate centered offset | |||||
glm::vec3 offset; | |||||
offset.x = (float)width * -0.5f * scale.x; | |||||
offset.y = 0.0f; | |||||
offset.z = (float)height * -0.5f * scale.z; | |||||
// Calculate vertex positions | |||||
for (int i = 0; i < height; ++i) | |||||
{ | |||||
for (int j = 0; j < width; ++j) | |||||
{ | |||||
std::size_t index = i * width + j; | |||||
glm::vec3* vertex = &vertices[index]; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = (float)pixels[index] * scale.y; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
} | |||||
} | |||||
// Free loaded image | |||||
stbi_image_free(pixels); | |||||
// Generate indices | |||||
for (int i = 0; i < height - 1; ++i) | |||||
{ | |||||
for (int j = 0; j < width - 1; ++j) | |||||
{ | |||||
std::size_t a = i * width + j; | |||||
std::size_t b = (i + 1) * width + j; | |||||
std::size_t c = i * width + j + 1; | |||||
std::size_t d = (i + 1) * width + j + 1; | |||||
std::size_t index = (i * (width - 1) + j) * 2 * 3; | |||||
indices[index] = a; | |||||
indices[index + 1] = b; | |||||
indices[index + 2] = c; | |||||
indices[index + 3] = c; | |||||
indices[index + 4] = b; | |||||
indices[index + 5] = d; | |||||
} | |||||
} | |||||
return mesh->create(vertices, indices); | |||||
} | |||||
bool loadHeightmapBase(const std::string& filename, glm::vec3 scale, float floor, WingedEdge* mesh) | |||||
{ | |||||
int width; | |||||
int height; | |||||
int components; | |||||
// Load image data | |||||
unsigned char* pixels = stbi_load(filename.c_str(), &width, &height, &components, 1); | |||||
if (!pixels) | |||||
{ | |||||
std::cerr << "Failed to load heightmap image \"" << filename << "\"\n"; | |||||
return false; | |||||
} | |||||
std::size_t vertexCount = width * 4 + height * 4; | |||||
std::size_t triangleCount = (width - 1) * 4 + (height - 1) * 4; | |||||
std::size_t indexCount = triangleCount * 3; | |||||
std::vector<glm::vec3> vertices(vertexCount); | |||||
std::vector<std::size_t> indices(indexCount); | |||||
// Adjust scale | |||||
scale.x *= 1.0f / ((float)width - 1); | |||||
scale.y *= 1.0f / 255.0f; | |||||
scale.z *= 1.0f / ((float)height - 1); | |||||
if (width > height) scale.z *= (float)height / (float) width; | |||||
else if (height > width) scale.x *= (float)width / (float)height; | |||||
// Calculate centered offset | |||||
glm::vec3 offset; | |||||
offset.x = (float)width * -0.5f * scale.x; | |||||
offset.y = 0.0f; | |||||
offset.z = (float)height * -0.5f * scale.z; | |||||
glm::vec3* vertex = &vertices[0]; | |||||
// Top row | |||||
for (int j = 0; j < width; ++j) | |||||
{ | |||||
int i = 0; | |||||
std::size_t index = i * width + j; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = (float)pixels[index] * scale.y; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
++vertex; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = floor; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
++vertex; | |||||
} | |||||
// Bottom row | |||||
for (int j = 0; j < width; ++j) | |||||
{ | |||||
int i = (height - 1); | |||||
std::size_t index = i * width + j; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = (float)pixels[index] * scale.y; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
++vertex; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = floor; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
++vertex; | |||||
} | |||||
// Left column | |||||
for (int i = 0; i < height; ++i) | |||||
{ | |||||
int j = 0; | |||||
std::size_t index = i * width + j; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = (float)pixels[index] * scale.y; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
++vertex;; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = floor; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
++vertex; | |||||
} | |||||
// Right column | |||||
for (int i = 0; i < height; ++i) | |||||
{ | |||||
int j = (width - 1); | |||||
std::size_t index = i * width + j; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = (float)pixels[index] * scale.y; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
++vertex; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = floor; | |||||
vertex->z = (float)i * scale.z + offset.z; | |||||
++vertex; | |||||
} | |||||
// Free loaded image | |||||
stbi_image_free(pixels); | |||||
// Generate indices | |||||
std::size_t* index = &indices[0]; | |||||
for (int i = 0; i < width - 1; ++i) | |||||
{ | |||||
std::size_t a = i * 2; | |||||
std::size_t b = i * 2 + 1; | |||||
std::size_t c = (i + 1) * 2; | |||||
std::size_t d = (i + 1) * 2 + 1; | |||||
(*(index++)) = b; | |||||
(*(index++)) = a; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = d; | |||||
a += width * 2; | |||||
b += width * 2; | |||||
c += width * 2; | |||||
d += width * 2; | |||||
(*(index++)) = a; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = d; | |||||
} | |||||
for (int i = 0; i < height - 1; ++i) | |||||
{ | |||||
std::size_t a = width * 4 + i * 2; | |||||
std::size_t b = width * 4 + i * 2 + 1; | |||||
std::size_t c = width * 4 + (i + 1) * 2; | |||||
std::size_t d = width * 4 + (i + 1) * 2 + 1; | |||||
(*(index++)) = a; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = d; | |||||
a += height * 2; | |||||
b += height * 2; | |||||
c += height * 2; | |||||
d += height * 2; | |||||
(*(index++)) = b; | |||||
(*(index++)) = a; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = d; | |||||
} | |||||
return mesh->create(vertices, indices); | |||||
} | |||||
void move(const WingedEdge* mesh, WingedEdge::Triangle* triangle, const glm::vec3& start, const glm::vec3& target, std::vector<WingedEdge::Triangle*>* visited, glm::vec3* end) | |||||
{ | |||||
// Add triangle to visited list | |||||
visited->push_back(triangle); | |||||
// Grab triangle coordinates | |||||
const glm::vec3& a = triangle->edge->vertex->position; | |||||
const glm::vec3& b = triangle->edge->next->vertex->position; | |||||
const glm::vec3& c = triangle->edge->previous->vertex->position; | |||||
// Project target onto triangle | |||||
glm::vec3 closestPoint; | |||||
int edgeIndex = -1; | |||||
WingedEdge::Edge* closestEdge = nullptr; | |||||
project_on_triangle(target, a, b, c, &closestPoint, &edgeIndex); | |||||
*end = closestPoint; | |||||
// Determine if projected target is on an edge | |||||
switch (edgeIndex) | |||||
{ | |||||
case -1: | |||||
// Projected target inside triangle | |||||
return; | |||||
case 0: | |||||
closestEdge = triangle->edge; | |||||
break; | |||||
case 1: | |||||
closestEdge = triangle->edge->next; | |||||
break; | |||||
case 2: | |||||
closestEdge = triangle->edge->previous; | |||||
break; | |||||
} | |||||
// If edge is not loose, repeat with connected triangle | |||||
if (closestEdge->symmetric != nullptr) | |||||
{ | |||||
for (std::size_t i = 0; i < visited->size() - 1; ++i) | |||||
{ | |||||
if ((*visited)[i] == closestEdge->symmetric->triangle) | |||||
return; | |||||
} | |||||
move(mesh, closestEdge->symmetric->triangle, closestPoint, target, visited, end); | |||||
} | |||||
} | |||||
std::tuple<bool, float, float, float> intersects(const glm::vec3& origin, const glm::vec3& direction, const glm::vec3& a, const glm::vec3& b, const glm::vec3& c) | |||||
{ | |||||
// Find edges | |||||
glm::vec3 edge10 = b - a; | |||||
glm::vec3 edge20 = c - a; | |||||
// Calculate determinant | |||||
glm::vec3 pv = glm::cross(direction, edge20); | |||||
float det = glm::dot(edge10, pv); | |||||
if (!det) | |||||
{ | |||||
return std::make_tuple(false, std::numeric_limits<float>::infinity(), 0.0f, 0.0f); | |||||
} | |||||
float inverseDet = 1.0f / det; | |||||
// Calculate u | |||||
glm::vec3 tv = origin - a; | |||||
float u = glm::dot(tv, pv) * inverseDet; | |||||
if (u < 0.0f || u > 1.0f) | |||||
{ | |||||
return std::make_tuple(false, std::numeric_limits<float>::infinity(), 0.0f, 0.0f); | |||||
} | |||||
// Calculate v | |||||
glm::vec3 qv = glm::cross(tv, edge10); | |||||
float v = glm::dot(direction, qv) * inverseDet; | |||||
if (v < 0.0f || u + v > 1.0f) | |||||
{ | |||||
return std::make_tuple(false, std::numeric_limits<float>::infinity(), 0.0f, 0.0f); | |||||
} | |||||
// Calculate t | |||||
float t = glm::dot(edge20, qv) * inverseDet; | |||||
if (t > 0.0f) | |||||
{ | |||||
return std::make_tuple(true, t, u, v); | |||||
} | |||||
return std::make_tuple(false, std::numeric_limits<float>::infinity(), 0.0f, 0.0f); | |||||
} | |||||
std::tuple<bool, float, float, std::size_t, std::size_t> intersects(const glm::vec3& origin, const glm::vec3& direction, const WingedEdge& mesh) | |||||
{ | |||||
const std::vector<WingedEdge::Triangle*>* triangles = mesh.getTriangles(); | |||||
bool intersection = false; | |||||
float t0 = std::numeric_limits<float>::infinity(); | |||||
float t1 = -std::numeric_limits<float>::infinity(); | |||||
std::size_t index0 = triangles->size(); | |||||
std::size_t index1 = index0; | |||||
for (std::size_t i = 0; i < triangles->size(); ++i) | |||||
{ | |||||
const WingedEdge::Triangle* triangle = (*triangles)[i]; | |||||
const glm::vec3& a = triangle->edge->vertex->position; | |||||
const glm::vec3& b = triangle->edge->next->vertex->position; | |||||
const glm::vec3& c = triangle->edge->previous->vertex->position; | |||||
auto result = intersects(origin, direction, a, b, c); | |||||
if (std::get<0>(result)) | |||||
{ | |||||
intersection = true; | |||||
float t = std::get<1>(result); | |||||
float cosTheta = glm::dot(direction, triangle->normal); | |||||
if (cosTheta <= 0.0f) | |||||
{ | |||||
// Front-facing | |||||
t0 = std::min(t0, t); | |||||
index0 = i; | |||||
} | |||||
else | |||||
{ | |||||
// Back-facing | |||||
t1 = std::max(t1, t); | |||||
index1 = i; | |||||
} | |||||
} | |||||
} | |||||
return std::make_tuple(intersection, t0, t1, index0, index1); | |||||
} |
@ -0,0 +1,59 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef MESH_HPP | |||||
#define MESH_HPP | |||||
#include <emergent/emergent.hpp> | |||||
#include <string> | |||||
#include <vector> | |||||
#include <tuple> | |||||
using namespace Emergent; | |||||
struct navigator | |||||
{ | |||||
glm::vec3 position; // World-space cartesian coordinates | |||||
float heading; | |||||
WingedEdge::Triangle* triangle; | |||||
glm::vec3 barycentric; // Current barycentric coordinates | |||||
}; | |||||
bool loadHeightmap(const std::string& filename, glm::vec3 scale, WingedEdge* mesh); | |||||
bool loadHeightmapBase(const std::string& filename, glm::vec3 scale, float floor, WingedEdge* mesh); | |||||
// Recursive function which moves a navigator along the surface of a navmesh. | |||||
void move(const WingedEdge* mesh, WingedEdge::Triangle* triangle, const glm::vec3& start, const glm::vec3& target, std::vector<WingedEdge::Triangle*>* visited, glm::vec3* end); | |||||
// Checks for intersection between a ray and a triangle | |||||
// The first element in the tuple indicates whether or not an intersection occurred. The second element indicates the distance from the origin to point of intersection. The third element is the barycentric U coordinate. The fourth element is the barycentric V coordinate. | |||||
// @see http://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm | |||||
// @see http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-9-ray-triangle-intersection/m-ller-trumbore-algorithm/ | |||||
std::tuple<bool, float, float, float> intersects(const glm::vec3& origin, const glm::vec3& direction, const WingedEdge::Triangle& triangle); | |||||
// Checks for intersection between a ray and a mesh. | |||||
// The first element in the tuple indicates whether or not an intersection occurred. The second and third elements indicate the distance from the origin to the nearest and farthest points of intersection, respectively. The fourth and fifth elements contain the indices of the nearest and farthest intersected triangles, respectively. | |||||
std::tuple<bool, float, float, std::size_t, std::size_t> intersects(const glm::vec3& origin, const glm::vec3& direction, const WingedEdge& mesh); | |||||
#endif // MESH_HPP | |||||
@ -0,0 +1,305 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "model-loader.hpp" | |||||
#include "material-loader.hpp" | |||||
#include <fstream> | |||||
template <typename T> | |||||
inline static void read8(T* result, unsigned char** data) | |||||
{ | |||||
std::uint8_t temp = (*data)[0]; | |||||
*result = *reinterpret_cast<T*>(&temp); | |||||
*data += 1; | |||||
} | |||||
template <typename T> | |||||
inline static void read16(T* result, unsigned char** data) | |||||
{ | |||||
std::uint16_t temp = ((*data)[0] << 0) | ((*data)[1] << 8); | |||||
*result = *reinterpret_cast<T*>(&temp); | |||||
*data += 2; | |||||
} | |||||
template <typename T> | |||||
inline static void read32(T* result, unsigned char** data) | |||||
{ | |||||
std::uint32_t temp = ((*data)[0] << 0) | ((*data)[1] << 8) | ((*data)[2] << 16) | ((*data)[3] << 24); | |||||
*result = *reinterpret_cast<T*>(&temp); | |||||
*data += 4; | |||||
} | |||||
inline static void readString(std::string* result, unsigned char** data) | |||||
{ | |||||
result->resize((*data)[0]); | |||||
for (std::size_t i = 0; i < result->size(); ++i) | |||||
{ | |||||
(*result)[i] = (*data)[i + 1]; | |||||
} | |||||
*data += result->size() + 1; | |||||
} | |||||
ModelLoader::ModelLoader(): | |||||
materialLoader(nullptr) | |||||
{} | |||||
ModelLoader::~ModelLoader() | |||||
{} | |||||
Model* ModelLoader::load(const std::string& filename) | |||||
{ | |||||
// Open file | |||||
std::ifstream file(filename.c_str(), std::ifstream::in | std::ifstream::binary | std::ifstream::ate); | |||||
if (!file.is_open()) | |||||
{ | |||||
std::cerr << "ModelLoader::load(): Failed to open model file \"" << filename << "\"" << std::endl; | |||||
return nullptr; | |||||
} | |||||
// Allocate file data buffer | |||||
int filesize = file.tellg(); | |||||
unsigned char* buffer = new unsigned char[filesize]; | |||||
// Read file data into buffer | |||||
file.seekg(0, file.beg); | |||||
file.read(reinterpret_cast<char*>(&buffer[0]), filesize); | |||||
unsigned char* bufferOffset = &buffer[0]; | |||||
// Close file | |||||
file.close(); | |||||
// Allocate model data | |||||
ModelData* modelData = new ModelData(); | |||||
// Allocate material groups | |||||
read32(&modelData->groupCount, &bufferOffset); | |||||
modelData->groups = new MaterialGroup[modelData->groupCount]; | |||||
// Read material groups (and calculate triangle count) | |||||
std::uint32_t triangleCount = 0; | |||||
for (std::size_t i = 0; i < modelData->groupCount; ++i) | |||||
{ | |||||
MaterialGroup* group = &modelData->groups[i]; | |||||
readString(&group->materialName, &bufferOffset); | |||||
read32(&group->indexOffset, &bufferOffset); | |||||
read32(&group->triangleCount, &bufferOffset); | |||||
// Read bounds | |||||
Vector3 min; | |||||
Vector3 max; | |||||
read32(&min.x, &bufferOffset); | |||||
read32(&min.y, &bufferOffset); | |||||
read32(&min.z, &bufferOffset); | |||||
read32(&max.x, &bufferOffset); | |||||
read32(&max.y, &bufferOffset); | |||||
read32(&max.z, &bufferOffset); | |||||
group->bounds.setMin(min); | |||||
group->bounds.setMax(max); | |||||
triangleCount += group->triangleCount; | |||||
} | |||||
// Read vertex format and count | |||||
read32(&modelData->vertexFormat, &bufferOffset); | |||||
read32(&modelData->vertexCount, &bufferOffset); | |||||
// Read bounds | |||||
Vector3 min; | |||||
Vector3 max; | |||||
read32(&min.x, &bufferOffset); | |||||
read32(&min.y, &bufferOffset); | |||||
read32(&min.z, &bufferOffset); | |||||
read32(&max.x, &bufferOffset); | |||||
read32(&max.y, &bufferOffset); | |||||
read32(&max.z, &bufferOffset); | |||||
modelData->bounds.setMin(min); | |||||
modelData->bounds.setMax(max); | |||||
// Calculate vertex size | |||||
std::uint32_t vertexSize = | |||||
3 // Position | |||||
+ 3 // Normal | |||||
+ 2 * ((modelData->vertexFormat & UV) != 0) // UV | |||||
+ 4 * ((modelData->vertexFormat & TANGENT) != 0) // Tangent | |||||
+ 4 * ((modelData->vertexFormat & TANGENT) != 0) // Bitangent | |||||
+ 4 * ((modelData->vertexFormat & WEIGHTS) != 0) // Indices | |||||
+ 4 * ((modelData->vertexFormat & WEIGHTS) != 0); // Weights | |||||
// Allocate vertex data | |||||
modelData->vertexData = new float[modelData->vertexCount * vertexSize]; | |||||
// Read vertex data | |||||
float* vertexDataOffset = &modelData->vertexData[0]; | |||||
for (std::size_t i = 0; i < modelData->vertexCount; ++i) | |||||
{ | |||||
for (std::size_t j = 0; j < vertexSize; ++j) | |||||
{ | |||||
read32(vertexDataOffset, &bufferOffset); | |||||
++vertexDataOffset; | |||||
} | |||||
} | |||||
// Allocate index data | |||||
std::uint32_t indexCount = triangleCount * 3; | |||||
modelData->indexData = new std::uint32_t[indexCount]; | |||||
// Read index data | |||||
for (std::size_t i = 0; i < indexCount; ++i) | |||||
{ | |||||
read32(&modelData->indexData[i], &bufferOffset); | |||||
} | |||||
// Free file data buffer | |||||
delete[] buffer; | |||||
GLuint vao; | |||||
GLuint vbo; | |||||
GLuint ibo; | |||||
// Generate and bind VAO | |||||
glGenVertexArrays(1, &vao); | |||||
glBindVertexArray(vao); | |||||
// Generate and bind VBO, then upload vertex data | |||||
glGenBuffers(1, &vbo); | |||||
glBindBuffer(GL_ARRAY_BUFFER, vbo); | |||||
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertexSize * modelData->vertexCount, modelData->vertexData, GL_STATIC_DRAW); | |||||
// Setup vertex attribute arrays | |||||
std::size_t attribOffset = 0; | |||||
std::size_t attribSize = 0; | |||||
// Vertex position attribute | |||||
attribSize = 3; | |||||
glEnableVertexAttribArray(EMERGENT_VERTEX_POSITION); | |||||
glVertexAttribPointer(EMERGENT_VERTEX_POSITION, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float)); | |||||
attribOffset += attribSize; | |||||
// Vertex normal attribute | |||||
attribSize = 3; | |||||
glEnableVertexAttribArray(EMERGENT_VERTEX_NORMAL); | |||||
glVertexAttribPointer(EMERGENT_VERTEX_NORMAL, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float)); | |||||
attribOffset += attribSize; | |||||
// Vertex UV attribute | |||||
if ((modelData->vertexFormat & UV) != 0) | |||||
{ | |||||
attribSize = 2; | |||||
glEnableVertexAttribArray(EMERGENT_VERTEX_TEXCOORD); | |||||
glVertexAttribPointer(EMERGENT_VERTEX_TEXCOORD, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float)); | |||||
attribOffset += attribSize; | |||||
} | |||||
// Vertex tangent and bitangent attributes | |||||
if ((modelData->vertexFormat & TANGENT) != 0) | |||||
{ | |||||
// Tangent | |||||
attribSize = 4; | |||||
glEnableVertexAttribArray(EMERGENT_VERTEX_TANGENT); | |||||
glVertexAttribPointer(EMERGENT_VERTEX_TANGENT, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float)); | |||||
attribOffset += attribSize; | |||||
// Bitangent | |||||
attribSize = 4; | |||||
glEnableVertexAttribArray(EMERGENT_VERTEX_BITANGENT); | |||||
glVertexAttribPointer(EMERGENT_VERTEX_BITANGENT, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float)); | |||||
attribOffset += attribSize; | |||||
} | |||||
// Vertex indices and weights attributes | |||||
if ((modelData->vertexFormat & TANGENT) != 0) | |||||
{ | |||||
// Indices | |||||
attribSize = 4; | |||||
glEnableVertexAttribArray(EMERGENT_VERTEX_BONE_INDICES); | |||||
glVertexAttribPointer(EMERGENT_VERTEX_BONE_INDICES, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float)); | |||||
attribOffset += attribSize; | |||||
// Weights | |||||
attribSize = 4; | |||||
glEnableVertexAttribArray(EMERGENT_VERTEX_BONE_WEIGHTS); | |||||
glVertexAttribPointer(EMERGENT_VERTEX_BONE_WEIGHTS, attribSize, GL_FLOAT, GL_FALSE, sizeof(float) * vertexSize, (char*)0 + attribOffset * sizeof(float)); | |||||
attribOffset += attribSize; | |||||
} | |||||
// Generate and bind IBO, then upload index data | |||||
glGenBuffers(1, &ibo); | |||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); | |||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(std::uint32_t) * indexCount, modelData->indexData, GL_STATIC_DRAW); | |||||
// Delete vertex and index data | |||||
delete[] modelData->vertexData; | |||||
delete[] modelData->indexData; | |||||
// Allocate model | |||||
Model* model = new Model(); | |||||
model->setBounds(modelData->bounds); | |||||
// Create model groups | |||||
for (std::size_t i = 0; i < modelData->groupCount; ++i) | |||||
{ | |||||
ModelLoader::MaterialGroup* modelDataGroup = &modelData->groups[i]; | |||||
// Allocate model group | |||||
Model::Group* modelGroup = new Model::Group(); | |||||
// Set model group name | |||||
modelGroup->name = modelDataGroup->materialName; | |||||
// Load material | |||||
std::string materialFilename = std::string("data/materials/") + modelDataGroup->materialName + std::string(".mtl"); | |||||
if (materialLoader != nullptr) | |||||
{ | |||||
modelGroup->material = materialLoader->load(materialFilename); | |||||
if (!modelGroup->material) | |||||
{ | |||||
std::cerr << "ModelLoader::load(): Failed to load material file \"" << materialFilename << "\" for model file \"" << filename << "\"" << std::endl; | |||||
} | |||||
} | |||||
else | |||||
{ | |||||
modelGroup->material = nullptr; | |||||
std::cerr << "ModelLoader::load(): No valid material loader, material file \"" << materialFilename << "\" not loaded" << std::endl; | |||||
} | |||||
// Setup model group geometry | |||||
modelGroup->indexOffset = modelDataGroup->indexOffset; | |||||
modelGroup->triangleCount = modelDataGroup->triangleCount; | |||||
modelGroup->bounds = modelDataGroup->bounds; | |||||
// Add model group to model | |||||
model->addGroup(modelGroup); | |||||
} | |||||
// Delete model data groups | |||||
delete[] modelData->groups; | |||||
// Delete model data | |||||
delete modelData; | |||||
return model; | |||||
} | |||||
void ModelLoader::setMaterialLoader(MaterialLoader* materialLoader) | |||||
{ | |||||
this->materialLoader = materialLoader; | |||||
} |
@ -0,0 +1,69 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef MODEL_LOADER_HPP | |||||
#define MODEL_LOADER_HPP | |||||
#include <string> | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
class MaterialLoader; | |||||
class ModelLoader | |||||
{ | |||||
public: | |||||
ModelLoader(); | |||||
~ModelLoader(); | |||||
Model* load(const std::string& filename); | |||||
void setMaterialLoader(MaterialLoader* materialLoader); | |||||
private: | |||||
struct MaterialGroup | |||||
{ | |||||
std::string materialName; | |||||
std::uint32_t indexOffset; | |||||
std::uint32_t triangleCount; | |||||
AABB bounds; | |||||
}; | |||||
enum VertexFlags | |||||
{ | |||||
UV = 1, | |||||
TANGENT = 2, | |||||
WEIGHTS = 4 | |||||
}; | |||||
struct ModelData | |||||
{ | |||||
std::uint32_t groupCount; | |||||
MaterialGroup* groups; | |||||
std::uint32_t vertexFormat; | |||||
std::uint32_t vertexCount; | |||||
AABB bounds; | |||||
float* vertexData; | |||||
std::uint32_t* indexData; | |||||
}; | |||||
MaterialLoader* materialLoader; | |||||
}; | |||||
#endif // MODEL_LOADER_HPP |
@ -0,0 +1,213 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "nest.hpp" | |||||
#include <cmath> | |||||
Vector3 Shaft::getHelixPosition(float depth) const | |||||
{ | |||||
Vector3 position; | |||||
position.x = entrance.x + std::cos(initialHelixAngle + depth / helixPitch) * helixRadius; | |||||
position.y = entrance.y + depth; | |||||
position.z = entrance.z + std::sin(initialHelixAngle + depth / helixPitch) * helixRadius; | |||||
return position; | |||||
} | |||||
float Shaft::getHelixAngle(float depth) const | |||||
{ | |||||
return initialHelixAngle + depth / helixPitch; | |||||
} | |||||
Nest::Nest(): | |||||
root(nullptr) | |||||
{} | |||||
Nest::~Nest() | |||||
{ | |||||
if (root != nullptr) | |||||
{ | |||||
free(root); | |||||
} | |||||
} | |||||
void Nest::generate() | |||||
{ | |||||
if (root != nullptr) | |||||
{ | |||||
// Delete existing shafts and chambers | |||||
free(root); | |||||
} | |||||
// Seed random number generator | |||||
rng.seed(parameters.randomSeed); | |||||
// Generate shafts and chambers | |||||
root = dig(nullptr); | |||||
// Merge intersecting chambers | |||||
// Create nest map | |||||
map(); | |||||
} | |||||
Shaft* Nest::dig(Chamber* parent) const | |||||
{ | |||||
Shaft* shaft = new Shaft(); | |||||
// Set child's parent | |||||
shaft->parent = parent; | |||||
if (parent != nullptr) | |||||
{ | |||||
// Set parent's child to this shaft | |||||
parent->child = shaft; | |||||
// Increment generation | |||||
shaft->generation = parent->parent->generation + 1; | |||||
// Determine initial helix angle | |||||
shaft->initialHelixAngle = parent->parent->getHelixAngle(parent->relativeDepth); | |||||
} | |||||
else | |||||
{ | |||||
// Shaft is root shaft | |||||
shaft->generation = 0; | |||||
shaft->entrance = Vector3(0.0f); | |||||
// Choose initial helix angle | |||||
} | |||||
shaft->initialHelixAngle = random(glm::radians(-180.0f), glm::radians(180.0f)); | |||||
if (parent == nullptr) | |||||
{ | |||||
// Choose initial random parameters | |||||
shaft->shaftRadius = random(parameters.minShaftRadius, parameters.maxShaftRadius); | |||||
shaft->helixRadius = random(parameters.minShaftHelixRadius, parameters.maxShaftHelixRadius); | |||||
shaft->helixPitch = random(parameters.minShaftHelixPitch, parameters.maxShaftHelixPitch); | |||||
} | |||||
else | |||||
{ | |||||
// Copy initial random parameters from grandparent | |||||
shaft->shaftRadius = parent->parent->shaftRadius; | |||||
shaft->helixRadius = parent->parent->helixRadius; | |||||
shaft->helixPitch = parent->parent->helixPitch; | |||||
} | |||||
// Choose random depth | |||||
shaft->shaftDepth = random(parameters.minShaftDepth, parameters.maxShaftDepth); | |||||
// Calculate entrance position | |||||
if (parent != nullptr) | |||||
{ | |||||
Vector3 helixPosition = parent->parent->getHelixPosition(parent->relativeDepth); | |||||
float helixAngle = parent->parent->getHelixAngle(parent->relativeDepth); | |||||
shaft->entrance.x = helixPosition.x + std::cos(helixAngle) * (parent->outerRadius - parent->innerRadius) - std::cos(shaft->initialHelixAngle) * shaft->helixRadius; | |||||
shaft->entrance.y = helixPosition.y; | |||||
shaft->entrance.z = helixPosition.z + std::sin(helixAngle) * (parent->outerRadius - parent->innerRadius) - std::sin(shaft->initialHelixAngle) * shaft->helixRadius; | |||||
} | |||||
// Determine potential child count (may be less, according to spacing between chambers) | |||||
int maxChildCount = std::max(1, random(parameters.minShaftChamberCount, parameters.maxShaftChamberCount)); | |||||
// Generate chambers, starting with final chamber (shaft must end with a chamber) | |||||
for (float depth = shaft->shaftDepth; depth >= 0.0f;) | |||||
{ | |||||
Chamber* chamber = new Chamber(); | |||||
shaft->children.push_back(chamber); | |||||
chamber->parent = shaft; | |||||
chamber->child = nullptr; | |||||
chamber->relativeDepth = depth; | |||||
chamber->absoluteDepth = shaft->entrance.y + chamber->relativeDepth; | |||||
chamber->innerRadius = random(parameters.minChamberInnerRadius, parameters.maxChamberInnerRadius); | |||||
chamber->outerRadius = random(parameters.minChamberOuterRadius, parameters.maxChamberOuterRadius); | |||||
chamber->centralAngle = random(parameters.minChamberCentralAngle, parameters.maxChamberCentralAngle); | |||||
// Check if maximum child count has been reached | |||||
if (shaft->children.size() >= maxChildCount) | |||||
{ | |||||
break; | |||||
} | |||||
// Decrease depth by random amount | |||||
depth -= random(parameters.minShaftChamberPitch, parameters.maxShaftChamberPitch); | |||||
} | |||||
// Generate subshafts from chambers | |||||
if (shaft->generation < parameters.maxShaftGeneration) | |||||
{ | |||||
for (Chamber* chamber: shaft->children) | |||||
{ | |||||
dig(chamber); | |||||
} | |||||
} | |||||
return shaft; | |||||
} | |||||
void Nest::merge() | |||||
{ | |||||
} | |||||
void Nest::map() | |||||
{ | |||||
} | |||||
void Nest::free(Shaft* shaft) | |||||
{ | |||||
for (Chamber* chamber: shaft->children) | |||||
{ | |||||
if (chamber->child != nullptr) | |||||
{ | |||||
free(chamber->child); | |||||
} | |||||
delete chamber; | |||||
} | |||||
delete shaft; | |||||
} | |||||
inline float Nest::random(float min, float max) const | |||||
{ | |||||
std::uniform_real_distribution<float> distribution(min, std::nextafter(max, std::numeric_limits<float>::max())); | |||||
return distribution(rng); | |||||
} | |||||
inline int Nest::random(int min, int max) const | |||||
{ | |||||
std::uniform_int_distribution<int> distribution(min, std::nextafter(max, std::numeric_limits<int>::max())); | |||||
return distribution(rng); | |||||
} | |||||
void Nest::setParameters(const NestParameters& parameters) | |||||
{ | |||||
this->parameters = parameters; | |||||
} | |||||
const NestParameters& Nest::getParameters() const | |||||
{ | |||||
return parameters; | |||||
} |
@ -0,0 +1,182 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef NEST_HPP | |||||
#define NEST_HPP | |||||
#include <random> | |||||
#include <vector> | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
/** | |||||
* General algorithm: Draw a series of lines straight down. Select multiple elevation levels on each line at which to create a chamber. Create helixes around lines. At the selected elevation levels on each line, create a corresponding chambers on the helixes at the same elevations, in the direction of the outside of the helix. Check for intersections between chambers and tunnels, and merge as necessary. | |||||
*/ | |||||
struct Chamber; | |||||
/** | |||||
* A vertically-directed helical shaft with one or more connected chambers. | |||||
*/ | |||||
struct Shaft | |||||
{ | |||||
Chamber* parent; // The parent chamber from which this shaft begins | |||||
std::vector<Chamber*> children; // A list of chambers which are formed from this shaft | |||||
int generation; // The generation index of this shaft. The root shaft is gen 0, the shafts from its chambers are gen 1, and so on. | |||||
Vector3 entrance; // Position of the entrance point of this shaft | |||||
float shaftRadius; // Radius of the shaft | |||||
float shaftDepth; // Total depth of this shaft | |||||
float initialHelixAngle; // Angle at which the shaft helix begins | |||||
float helixRadius; // Radius of the shaft helix | |||||
float helixPitch; // Pitch of the shaft helix | |||||
/** | |||||
* Returns the position on the shaft's helix at the specified depth. | |||||
* | |||||
* @param depth Depth relative to the entrance of this shaft. | |||||
* @return Point on the helix at the specified depth. | |||||
*/ | |||||
Vector3 getHelixPosition(float depth) const; | |||||
/** | |||||
* Returns the angle to the helix at the specified depth. | |||||
* | |||||
* @param depth Depth relative to the entrance of this shaft. | |||||
* @return Angle to the helix at the specified depth. | |||||
*/ | |||||
float getHelixAngle(float depth) const; | |||||
}; | |||||
/** | |||||
* A horizontal annular chamber with one parent shaft and a max of one child shaft. Chambers always face toward the outside of the parent shaft's helix. | |||||
*/ | |||||
struct Chamber | |||||
{ | |||||
Shaft* parent; // Parent shaft from which this chamber was formed | |||||
Shaft* child; // Child shaft which begins in this chamber | |||||
int generation; // The number of chambers from this chamber to the root shaft. | |||||
float relativeDepth; // Depth from the entrance of the parent shaft to this chamber | |||||
float absoluteDepth; // Depth from the entrance of the root shaft to this chamber | |||||
float innerRadius; // Inner radius of the annulus | |||||
float outerRadius; // Outer radius of the annulus | |||||
float centralAngle; // Angle of the annular sector | |||||
float height; // Height of the annular sector | |||||
float childAngle; // The angle on the annulus at which the child shaft begins | |||||
}; | |||||
/** | |||||
* Describes the parameters required to generate a nest. | |||||
*/ | |||||
struct NestParameters | |||||
{ | |||||
// Random params | |||||
unsigned int randomSeed; | |||||
// Shaft params | |||||
int maxShaftGeneration; | |||||
float minShaftRadius; | |||||
float maxShaftRadius; | |||||
float minShaftDepth; | |||||
float maxShaftDepth; | |||||
float minShaftHelixRadius; | |||||
float maxShaftHelixRadius; | |||||
float minShaftHelixPitch; | |||||
float maxShaftHelixPitch; | |||||
int minShaftChamberCount; | |||||
int maxShaftChamberCount; | |||||
float minShaftChamberPitch; | |||||
float maxShaftChamberPitch; | |||||
// Chamber params | |||||
float minChamberInnerRadius; | |||||
float maxChamberInnerRadius; | |||||
float minChamberOuterRadius; | |||||
float maxChamberOuterRadius; | |||||
float minChamberCentralAngle; | |||||
float maxChamberCentralAngle; | |||||
}; | |||||
class Nest | |||||
{ | |||||
public: | |||||
Nest(); | |||||
~Nest(); | |||||
/** | |||||
* Generates the nest and all of its shafts and chambers. | |||||
*/ | |||||
void generate(); | |||||
/** | |||||
* Sets the nest generation parameters. | |||||
*/ | |||||
void setParameters(const NestParameters& parameters); | |||||
/** | |||||
* Returns the nest generation parameters. | |||||
*/ | |||||
const NestParameters& getParameters() const; | |||||
/** | |||||
* Returns a pointer to the root shaft of the nest. | |||||
*/ | |||||
const Shaft* getRootShaft() const; | |||||
private: | |||||
/** | |||||
* Recursive function which generates a connected system of shafts and chambers. | |||||
* | |||||
* @param parent Specifies the parent chamber of the shaft. A value of `nullptr` indicates the root shaft. | |||||
* @param generation The index of the shaft's generation. The root shaft is generation 0, the shafts formed from the root shaft's chambers are generation 1, and so on. | |||||
* @return The newly created shaft. | |||||
*/ | |||||
Shaft* dig(Chamber* parent) const; | |||||
/** | |||||
* Determines intersections between chambers and connects them. | |||||
*/ | |||||
void merge(); | |||||
/** | |||||
* Creates a map (interconnected system of nodes) with which can be used to navigate the nest. | |||||
*/ | |||||
void map(); | |||||
/** | |||||
* Recursive function which deletes a shaft and all of its connect chambers and subshafts. | |||||
* | |||||
* @param Specifies a shaft to delete. | |||||
*/ | |||||
void free(Shaft* shaft); | |||||
float random(float min, float max) const; | |||||
int random(int min, int max) const; | |||||
NestParameters parameters; | |||||
Shaft* root; | |||||
mutable std::default_random_engine rng; | |||||
}; | |||||
inline const Shaft* Nest::getRootShaft() const | |||||
{ | |||||
return root; | |||||
} | |||||
#endif // NEST_HPP |
@ -0,0 +1,189 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef RENDER_PASSES_HPP | |||||
#define RENDER_PASSES_HPP | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
#include "material-loader.hpp" | |||||
#include "model-loader.hpp" | |||||
/** | |||||
* Renders the distance from the view frustum's near clipping plane to scene geometry. The render target should have a depth only framebuffer. | |||||
*/ | |||||
class ShadowMapRenderPass: public RenderPass | |||||
{ | |||||
public: | |||||
ShadowMapRenderPass(); | |||||
virtual bool load(const RenderContext* renderContext); | |||||
virtual void unload(); | |||||
virtual void render(const RenderContext* renderContext); | |||||
private: | |||||
ShaderLoader shaderLoader; | |||||
Shader* depthShader; | |||||
}; | |||||
/** | |||||
* Writes clipped edges to stencil buffer. | |||||
*/ | |||||
class ClippingRenderPass: public RenderPass | |||||
{ | |||||
public: | |||||
ClippingRenderPass(); | |||||
virtual bool load(const RenderContext* renderContext); | |||||
virtual void unload(); | |||||
virtual void render(const RenderContext* renderContext); | |||||
void setClippingPlane(const Plane& plane); | |||||
private: | |||||
ShaderLoader shaderLoader; | |||||
Shader* shader; | |||||
Vector4 clippingPlane; | |||||
}; | |||||
/** | |||||
* Caps clipped geometry. | |||||
*/ | |||||
class CappingRenderPass: public RenderPass | |||||
{ | |||||
public: | |||||
CappingRenderPass(); | |||||
virtual bool load(const RenderContext* renderContext); | |||||
virtual void unload(); | |||||
virtual void render(const RenderContext* renderContext); | |||||
private: | |||||
ShaderLoader shaderLoader; | |||||
Shader* shader; | |||||
Texture horizonOTexture; | |||||
Texture horizonATexture; | |||||
Texture horizonBTexture; | |||||
Texture horizonCTexture; | |||||
}; | |||||
/** | |||||
* Renders scene geometry. | |||||
*/ | |||||
class LightingRenderPass: public RenderPass | |||||
{ | |||||
public: | |||||
LightingRenderPass(); | |||||
virtual bool load(const RenderContext* renderContext); | |||||
virtual void unload(); | |||||
virtual void render(const RenderContext* renderContext); | |||||
inline void setShadowMap(GLuint shadowMap) { this->shadowMap = shadowMap; } | |||||
inline void setShadowCamera(const Camera* camera) { this->shadowCamera = camera; } | |||||
inline void setClippingPlanes(const Plane* planes) | |||||
{ | |||||
for (int i = 0; i < 5; ++i) | |||||
{ | |||||
this->clippingPlanes[i] = planes[i]; | |||||
} | |||||
} | |||||
private: | |||||
bool loadShader(const RenderOperation& operation); | |||||
ShaderLoader shaderLoader; | |||||
std::map<std::size_t, Shader*> shaderCache; | |||||
Matrix4 biasMatrix; | |||||
GLuint shadowMap; | |||||
Texture treeShadow; | |||||
const Camera* shadowCamera; | |||||
float time; | |||||
// Cutaway clipping and capping | |||||
Plane clippingPlanes[5]; | |||||
Model* unitPlaneModel; | |||||
ModelInstance cappingPlaneInstances[5]; | |||||
RenderQueue cappingRenderQueue; | |||||
RenderContext cappingRenderContext; | |||||
ClippingRenderPass clippingRenderPass; | |||||
CappingRenderPass cappingRenderPass; | |||||
MaterialLoader materialLoader; | |||||
ModelLoader modelLoader; | |||||
}; | |||||
/** | |||||
* Renders bounding boxes, skeletons | |||||
*/ | |||||
class DebugRenderPass: public RenderPass | |||||
{ | |||||
public: | |||||
virtual bool load(const RenderContext* renderContext); | |||||
virtual void unload(); | |||||
virtual void render(const RenderContext* renderContext); | |||||
private: | |||||
ShaderLoader shaderLoader; | |||||
Shader* unlitSolidShader; | |||||
int aabbVertexCount; | |||||
int aabbIndexCount; | |||||
GLuint aabbVAO; | |||||
GLuint aabbVBO; | |||||
GLuint aabbIBO; | |||||
}; | |||||
/** | |||||
* Renders the user interface | |||||
*/ | |||||
class UIRenderPass: public RenderPass | |||||
{ | |||||
public: | |||||
virtual bool load(const RenderContext* renderContext); | |||||
virtual void unload(); | |||||
virtual void render(const RenderContext* renderContext); | |||||
private: | |||||
ShaderLoader shaderLoader; | |||||
Shader* texturedUIShader; | |||||
Shader* untexturedUIShader; | |||||
}; | |||||
/** | |||||
* Renders a vignette | |||||
*/ | |||||
class VignetteRenderPass: public RenderPass | |||||
{ | |||||
public: | |||||
VignetteRenderPass(); | |||||
virtual bool load(const RenderContext* renderContext); | |||||
virtual void unload(); | |||||
virtual void render(const RenderContext* renderContext); | |||||
private: | |||||
ShaderLoader shaderLoader; | |||||
Shader* shader; | |||||
GLuint bayerTextureID; | |||||
}; | |||||
#endif // RENDER_PASSES_HPP |
@ -0,0 +1,79 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "settings.hpp" | |||||
#include <fstream> | |||||
#include <sstream> | |||||
#include <vector> | |||||
#include <iostream> | |||||
bool ParameterDict::load(const std::string& filename) | |||||
{ | |||||
// Open parameter dict file | |||||
std::ifstream file(filename.c_str()); | |||||
if (!file.is_open()) | |||||
{ | |||||
std::cerr << "Failed to open file \"" << filename << "\"" << std::endl; | |||||
return false; | |||||
} | |||||
// Read file | |||||
std::string line; | |||||
while (file.good() && std::getline(file, line)) | |||||
{ | |||||
// Tokenize line (tab-delimeted) | |||||
std::vector<std::string> tokens; | |||||
std::string token; | |||||
std::istringstream linestream(line); | |||||
while (std::getline(linestream, token, '\t')) | |||||
tokens.push_back(token); | |||||
if (tokens.empty() || tokens[0][0] == '#') | |||||
continue; | |||||
if (tokens.size() != 2) | |||||
{ | |||||
std::cerr << "Invalid line \"" << line << "\" in file \"" << filename << "\"" << std::endl; | |||||
continue; | |||||
} | |||||
parameters[tokens[0]] = tokens[1]; | |||||
} | |||||
file.close(); | |||||
return true; | |||||
} | |||||
bool ParameterDict::save(const std::string& filename) | |||||
{ | |||||
std::ofstream file(filename.c_str()); | |||||
if (!file.is_open()) | |||||
{ | |||||
std::cerr << "Failed to open file \"" << filename << "\"" << std::endl; | |||||
return false; | |||||
} | |||||
for (auto it = parameters.begin(); it != parameters.end(); ++it) | |||||
file << it->first << "\t" << it->second << std::endl; | |||||
file.close(); | |||||
return true; | |||||
} |
@ -0,0 +1,80 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef SETTINGS_HPP | |||||
#define SETTINGS_HPP | |||||
#include <map> | |||||
#include <string> | |||||
#include <sstream> | |||||
class ParameterDict | |||||
{ | |||||
public: | |||||
template <typename T> | |||||
bool get(const std::string& name, T* value) const; | |||||
template <typename T> | |||||
void set(const std::string& name, const T& value); | |||||
bool load(const std::string& filename); | |||||
bool save(const std::string& filename); | |||||
private: | |||||
std::map<std::string, std::string> parameters; | |||||
}; | |||||
template <typename T> | |||||
bool ParameterDict::get(const std::string& name, T* value) const | |||||
{ | |||||
auto it = parameters.find(name); | |||||
if (it == parameters.end()) | |||||
return false; | |||||
std::stringstream stream(it->second); | |||||
stream >> (*value); | |||||
if (stream.fail()) | |||||
return false; | |||||
return true; | |||||
} | |||||
template <> | |||||
inline bool ParameterDict::get<std::string>(const std::string& name, std::string* value) const | |||||
{ | |||||
auto it = parameters.find(name); | |||||
if (it == parameters.end()) | |||||
return false; | |||||
*value = it->second; | |||||
return true; | |||||
} | |||||
template <typename T> | |||||
void ParameterDict::set(const std::string& name, const T& value) | |||||
{ | |||||
std::stringstream stream; | |||||
stream << value; | |||||
parameters[name] = stream.str(); | |||||
} | |||||
#endif | |||||
@ -0,0 +1,562 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "experiment-state.hpp" | |||||
#include "../application.hpp" | |||||
#include "../camera-controller.hpp" | |||||
#include "../ui/ui.hpp" | |||||
#include <iostream> | |||||
#include <SDL.h> | |||||
ExperimentState::ExperimentState(Application* application): | |||||
ApplicationState(application) | |||||
{} | |||||
ExperimentState::~ExperimentState() | |||||
{} | |||||
void drawShaft(LineBatcher* lineBatcher, const Shaft* shaft); | |||||
void drawChamber(LineBatcher* lineBatcher, const Chamber* chamber) | |||||
{ | |||||
float helixAngle = chamber->parent->getHelixAngle(chamber->relativeDepth); | |||||
float minAngle = helixAngle - chamber->centralAngle * 0.5f; | |||||
float maxAngle = helixAngle + chamber->centralAngle * 0.5f; | |||||
// Find position on helix | |||||
Vector3 helixPosition = chamber->parent->getHelixPosition(chamber->relativeDepth); | |||||
helixPosition.y = -helixPosition.y; | |||||
// Move annulus toward helix by the inner radius | |||||
Vector3 helixDirection = glm::normalize(Vector3(std::cos(helixAngle), 0.0f, std::sin(helixAngle))); | |||||
Vector3 offset = helixPosition - helixDirection * (chamber->innerRadius - chamber->parent->shaftRadius); | |||||
int stepCount = 10; | |||||
float angleStep = chamber->centralAngle / (float)stepCount; | |||||
for (int i = 0; i < stepCount; ++i) | |||||
{ | |||||
float angle0 = minAngle + angleStep * (float)i; | |||||
float angle1 = minAngle + angleStep * (float)(i + 1); | |||||
float x0 = std::cos(angle0); | |||||
float z0 = std::sin(angle0); | |||||
float x1 = std::cos(angle1); | |||||
float z1 = std::sin(angle1); | |||||
Vector3 innerStart; | |||||
innerStart.x = x0 * chamber->innerRadius; | |||||
innerStart.y = 0.0f; | |||||
innerStart.z = z0 * chamber->innerRadius; | |||||
Vector3 outerStart; | |||||
outerStart.x = x0 * chamber->outerRadius; | |||||
outerStart.y = 0.0f; | |||||
outerStart.z = z0 * chamber->outerRadius; | |||||
Vector3 innerEnd; | |||||
innerEnd.x = x1 * chamber->innerRadius; | |||||
innerEnd.y = 0.0f; | |||||
innerEnd.z = z1 * chamber->innerRadius; | |||||
Vector3 outerEnd; | |||||
outerEnd.x = x1 * chamber->outerRadius; | |||||
outerEnd.y = 0.0f; | |||||
outerEnd.z = z1 * chamber->outerRadius; | |||||
lineBatcher->draw(offset + innerStart, offset + innerEnd); | |||||
lineBatcher->draw(offset + outerStart, offset + outerEnd); | |||||
} | |||||
Vector3 leftWallStart; | |||||
leftWallStart.x = std::cos(minAngle) * chamber->innerRadius; | |||||
leftWallStart.y = 0.0f; | |||||
leftWallStart.z = std::sin(minAngle) * chamber->innerRadius; | |||||
Vector3 leftWallEnd; | |||||
leftWallEnd.x = std::cos(minAngle) * chamber->outerRadius; | |||||
leftWallEnd.y = 0.0f; | |||||
leftWallEnd.z = std::sin(minAngle) * chamber->outerRadius; | |||||
Vector3 rightWallStart; | |||||
rightWallStart.x = std::cos(maxAngle) * chamber->innerRadius; | |||||
rightWallStart.y = 0.0f; | |||||
rightWallStart.z = std::sin(maxAngle) * chamber->innerRadius; | |||||
Vector3 rightWallEnd; | |||||
rightWallEnd.x = std::cos(maxAngle) * chamber->outerRadius; | |||||
rightWallEnd.y = 0.0f; | |||||
rightWallEnd.z = std::sin(maxAngle) * chamber->outerRadius; | |||||
lineBatcher->draw(offset + leftWallStart, offset + leftWallEnd); | |||||
lineBatcher->draw(offset + rightWallStart, offset + rightWallEnd); | |||||
if (chamber->child != nullptr) | |||||
{ | |||||
drawShaft(lineBatcher, chamber->child); | |||||
} | |||||
} | |||||
void drawShaft(LineBatcher* lineBatcher, const Shaft* shaft) | |||||
{ | |||||
// Draw helix | |||||
int stepCount = 50; | |||||
float depthStep = shaft->shaftDepth / (float)stepCount; | |||||
for (int i = 0; i < stepCount; ++i) | |||||
{ | |||||
Vector3 start = shaft->getHelixPosition((float)i * depthStep); | |||||
Vector3 end = shaft->getHelixPosition((float)(i + 1) * depthStep); | |||||
start.y = -start.y; | |||||
end.y = -end.y; | |||||
lineBatcher->draw(start, end); | |||||
} | |||||
// Draw children | |||||
for (const Chamber* chamber: shaft->children) | |||||
{ | |||||
drawChamber(lineBatcher, chamber); | |||||
} | |||||
} | |||||
void ExperimentState::generateNest() | |||||
{ | |||||
NestParameters params; | |||||
params.randomSeed = std::rand(); | |||||
params.maxShaftGeneration = 2; | |||||
params.minShaftRadius = 0.0f; | |||||
params.maxShaftRadius = 0.0f; | |||||
params.minShaftDepth = 4.0f; | |||||
params.maxShaftDepth = 6.0f; | |||||
params.minShaftHelixRadius = 0.1f; | |||||
params.maxShaftHelixRadius = 1.0f; | |||||
params.minShaftHelixPitch = 0.25f; | |||||
params.maxShaftHelixPitch = 0.75f; | |||||
params.minShaftChamberCount = 1; | |||||
params.maxShaftChamberCount = 5; | |||||
params.minShaftChamberPitch = 0.5f; | |||||
params.maxShaftChamberPitch = 2.0f; | |||||
params.minChamberInnerRadius = 0.2f; | |||||
params.maxChamberInnerRadius = 0.2f; | |||||
params.minChamberOuterRadius = 0.5f; | |||||
params.maxChamberOuterRadius = 0.5f; | |||||
params.minChamberCentralAngle = glm::radians(240.0f); | |||||
params.maxChamberCentralAngle = glm::radians(240.0f); | |||||
nest.setParameters(params); | |||||
nest.generate(); | |||||
// Draw nest | |||||
application->lineBatcher->setColor(Vector4(1.0f)); | |||||
application->lineBatcher->setWidth(0.015f); | |||||
application->lineBatcher->begin(); | |||||
drawShaft(application->lineBatcher, nest.getRootShaft()); | |||||
application->lineBatcher->end(); | |||||
} | |||||
void ExperimentState::enter() | |||||
{ | |||||
std::cout << "Entering ExperimentState..." << std::endl; | |||||
std::srand(std::time(0)); | |||||
// BG | |||||
application->bgBatch.resize(1); | |||||
BillboardBatch::Range* bgRange = application->bgBatch.addRange(); | |||||
bgRange->start = 0; | |||||
bgRange->length = 1; | |||||
Billboard* bgBillboard = application->bgBatch.getBillboard(0); | |||||
bgBillboard->setDimensions(Vector2(1.0f, 1.0f)); | |||||
bgBillboard->setTranslation(Vector3(0.5f, 0.5f, 0.0f)); | |||||
bgBillboard->setTintColor(Vector4(1, 0, 0, 1)); | |||||
application->bgBatch.update(); | |||||
application->vignettePass.setRenderTarget(&application->defaultRenderTarget); | |||||
application->bgCompositor.addPass(&application->vignettePass); | |||||
application->bgCompositor.load(nullptr); | |||||
application->bgCamera.setOrthographic(0, 1.0f, 1.0f, 0, -1.0f, 1.0f); | |||||
application->bgCamera.lookAt(glm::vec3(0), glm::vec3(0, 0, -1), glm::vec3(0, 1, 0)); | |||||
application->bgCamera.setCompositor(&application->bgCompositor); | |||||
application->bgCamera.setCompositeIndex(0); | |||||
application->bgScene.addLayer(); | |||||
application->bgScene.getLayer(0)->addObject(&application->bgCamera); | |||||
application->bgScene.getLayer(0)->addObject(&application->bgBatch); | |||||
SceneLayer* terrainLayer = application->scene.addLayer(); | |||||
SceneLayer* objectsLayer = application->scene.addLayer(); | |||||
terrainLayer->addObject(&application->camera); | |||||
objectsLayer->addObject(&application->camera); | |||||
objectsLayer->addObject(application->displayModelInstance); | |||||
objectsLayer->addObject(application->antModelInstance); | |||||
objectsLayer->addObject(application->lineBatcher->getBatch()); | |||||
// Create terrain | |||||
terrain.create(16, 16, Vector3(150.0f)); | |||||
terrainLayer->addObject(terrain.getSurfaceModel()->createInstance()); | |||||
terrainLayer->addObject(terrain.getSubsurfaceModel()->createInstance()); | |||||
DirectionalLight* lightA = new DirectionalLight(); | |||||
DirectionalLight* lightB = new DirectionalLight(); | |||||
DirectionalLight* lightC = new DirectionalLight(); | |||||
lightA->setColor(glm::vec3(1.0f)); | |||||
lightB->setColor(glm::vec3(0.25f)); | |||||
lightC->setColor(glm::vec3(1.0f, 1.0f, 1.0f)); | |||||
lightA->setDirection(glm::normalize(glm::vec3(0.0, -0.8, -0.2))); | |||||
lightB->setDirection(glm::normalize(glm::vec3(1.0, -.2, 0.0f))); | |||||
lightC->setDirection(glm::normalize(glm::vec3(0.0, 1.0, 0.0))); | |||||
terrainLayer->addObject(lightA); | |||||
terrainLayer->addObject(lightB); | |||||
terrainLayer->addObject(lightC); | |||||
objectsLayer->addObject(lightA); | |||||
objectsLayer->addObject(lightB); | |||||
objectsLayer->addObject(lightC); | |||||
// Load compositor | |||||
application->defaultCompositor.unload(); | |||||
RenderQueue renderQueue; | |||||
const std::list<SceneObject*>* objects = terrainLayer->getObjects(); | |||||
for (const SceneObject* object: *objects) | |||||
renderQueue.queue(object); | |||||
objects = objectsLayer->getObjects(); | |||||
for (const SceneObject* object: *objects) | |||||
renderQueue.queue(object); | |||||
RenderContext renderContext; | |||||
renderContext.camera = nullptr; | |||||
renderContext.layer = objectsLayer; | |||||
renderContext.queue = &renderQueue; | |||||
application->defaultCompositor.load(&renderContext); | |||||
application->camera.setPerspective( | |||||
glm::radians(25.0f), | |||||
(float)application->width / (float)application->height, | |||||
0.5f, | |||||
2000.0f); | |||||
// Setup camera controller | |||||
application->surfaceCam->setCamera(&application->camera); | |||||
application->surfaceCam->setFocalPoint(Vector3(0.0f)); | |||||
application->surfaceCam->setFocalDistance(10.0f); | |||||
application->surfaceCam->setElevation(glm::radians(90.0f * (3.0f / 4.0f))); | |||||
application->surfaceCam->setAzimuth(glm::radians(45.0f)); | |||||
application->surfaceCam->setTargetFocalPoint(application->surfaceCam->getFocalPoint()); | |||||
application->surfaceCam->setTargetFocalDistance(application->surfaceCam->getFocalDistance()); | |||||
application->surfaceCam->setTargetElevation(application->surfaceCam->getElevation()); | |||||
application->surfaceCam->setTargetAzimuth(application->surfaceCam->getAzimuth()); | |||||
application->surfaceCam->update(0.0f); | |||||
application->pauseMenuContainer->setVisible(false); | |||||
application->pauseMenuContainer->setActive(false); | |||||
// Generate nest | |||||
generateNest(); | |||||
dragging = oldDragging = false; | |||||
application->inputManager->addWindowObserver(this); | |||||
application->mouse->addMouseButtonObserver(this); | |||||
windowResized(application->width, application->height); | |||||
// Start timer | |||||
timer.start(); | |||||
} | |||||
void ExperimentState::execute() | |||||
{ | |||||
// Calculate delta time (in seconds) | |||||
float dt = static_cast<float>(timer.microseconds().count()) / 1000000.0f; | |||||
timer.reset(); | |||||
// Update controls | |||||
application->menuControlProfile->update(); | |||||
application->gameControlProfile->update(); | |||||
// Update input | |||||
oldDragging = dragging; | |||||
application->inputManager->update(); | |||||
// Check if application was closed | |||||
if (application->inputManager->wasClosed() || application->escape.isTriggered()) | |||||
{ | |||||
application->close(EXIT_SUCCESS); | |||||
return; | |||||
} | |||||
// Check if fullscreen was toggled | |||||
if (application->toggleFullscreen.isTriggered() && !application->toggleFullscreen.wasTriggered()) | |||||
{ | |||||
application->changeFullscreen(); | |||||
} | |||||
// Move camera | |||||
Vector2 movementVector(0.0f); | |||||
if (application->cameraMoveLeft.isTriggered()) | |||||
movementVector.x -= application->cameraMoveLeft.getCurrentValue(); | |||||
if (application->cameraMoveRight.isTriggered()) | |||||
movementVector.x += application->cameraMoveRight.getCurrentValue(); | |||||
if (application->cameraMoveForward.isTriggered()) | |||||
movementVector.y -= application->cameraMoveForward.getCurrentValue(); | |||||
if (application->cameraMoveBack.isTriggered()) | |||||
movementVector.y += application->cameraMoveBack.getCurrentValue(); | |||||
if (movementVector.x != 0.0f || movementVector.y != 0.0f) | |||||
{ | |||||
movementVector *= 0.005f * application->surfaceCam->getFocalDistance() * dt / (1.0f / 60.0f); | |||||
application->surfaceCam->move(movementVector); | |||||
} | |||||
// Rotate camera | |||||
/* | |||||
if (application->cameraRotateCW.isTriggered() && !application->cameraRotateCW.wasTriggered()) | |||||
application->surfaceCam->rotate(glm::radians(-90.0f)); | |||||
if (application->cameraRotateCCW.isTriggered() && !application->cameraRotateCCW.wasTriggered()) | |||||
application->surfaceCam->rotate(glm::radians(90.0f)); | |||||
*/ | |||||
float rotationSpeed = glm::radians(3.0f) * dt / (1.0f / 60.0f); | |||||
if (application->cameraRotateCW.isTriggered()) | |||||
application->surfaceCam->rotate(-rotationSpeed); | |||||
if (application->cameraRotateCCW.isTriggered()) | |||||
application->surfaceCam->rotate(rotationSpeed); | |||||
// Zoom camera | |||||
float zoomFactor = application->surfaceCam->getFocalDistance() / 20.0f * dt / (1.0f / 60.0f); | |||||
if (application->cameraZoomIn.isTriggered()) | |||||
application->surfaceCam->zoom(zoomFactor * application->cameraZoomIn.getCurrentValue()); | |||||
if (application->cameraZoomOut.isTriggered()) | |||||
application->surfaceCam->zoom(-zoomFactor * application->cameraZoomOut.getCurrentValue()); | |||||
// Enforce camera focal distance constraints | |||||
float minFocalDistance = 2.5f; | |||||
float maxFocalDistance = 1000.0f; | |||||
if (application->surfaceCam->getTargetFocalDistance() > maxFocalDistance) | |||||
{ | |||||
application->surfaceCam->setTargetFocalDistance(maxFocalDistance); | |||||
} | |||||
else if (application->surfaceCam->getTargetFocalDistance() < minFocalDistance) | |||||
{ | |||||
application->surfaceCam->setTargetFocalDistance(minFocalDistance); | |||||
} | |||||
// Enforce camera focal point constraints | |||||
float worldSize = 150.0f; | |||||
Vector3 boundsMin = Vector3(-worldSize * 0.5f, 0.0f, -worldSize * 0.5f); | |||||
Vector3 boundsMax = Vector3(worldSize * 0.5f, 0.0f, worldSize * 0.5f); | |||||
Vector3 targetFocalPoint = application->surfaceCam->getTargetFocalPoint(); | |||||
targetFocalPoint.x = std::max(boundsMin.x, std::min(boundsMax.x, targetFocalPoint.x)); | |||||
targetFocalPoint.z = std::max(boundsMin.z, std::min(boundsMax.z, targetFocalPoint.z)); | |||||
application->surfaceCam->setTargetFocalPoint(targetFocalPoint); | |||||
// Fixed camera angles | |||||
float overheadViewElevation = glm::radians(90.0f * (3.0f / 4.0f)); | |||||
float tiltedViewElevation = glm::radians(30.0f); | |||||
float nestViewElevation = glm::radians(0.0f); | |||||
// Toggle overhead view | |||||
if (!application->cameraNestView) | |||||
{ | |||||
if (application->cameraToggleOverheadView.isTriggered() && !application->cameraToggleOverheadView.wasTriggered()) | |||||
{ | |||||
application->cameraOverheadView = !application->cameraOverheadView; | |||||
float elevation = (application->cameraOverheadView) ? overheadViewElevation : tiltedViewElevation; | |||||
application->surfaceCam->setTargetElevation(elevation); | |||||
} | |||||
} | |||||
// Toggle nest view | |||||
if (application->cameraToggleNestView.isTriggered() && !application->cameraToggleNestView.wasTriggered()) | |||||
{ | |||||
application->cameraNestView = !application->cameraNestView; | |||||
float elevation = (application->cameraNestView) ? nestViewElevation : (application->cameraOverheadView) ? overheadViewElevation : tiltedViewElevation; | |||||
application->surfaceCam->setTargetElevation(elevation); | |||||
} | |||||
if (application->menuSelect.isTriggered() && !application->menuSelect.wasTriggered()) | |||||
{ | |||||
generateNest(); | |||||
} | |||||
application->surfaceCam->update(dt); | |||||
// Picking | |||||
// Pick!!! | |||||
glm::ivec2 mousePosition = application->mouse->getCurrentPosition(); | |||||
mousePosition.y = application->height - mousePosition.y; | |||||
Vector4 viewport(0.0f, 0.0f, application->width, application->height); | |||||
Vector3 mouseNear = application->camera.unproject(Vector3(mousePosition.x, mousePosition.y, 0.0f), viewport); | |||||
Vector3 mouseFar = application->camera.unproject(Vector3(mousePosition.x, mousePosition.y, 1.0f), viewport); | |||||
Ray pickingRay; | |||||
pickingRay.origin = mouseNear; | |||||
pickingRay.direction = glm::normalize(mouseFar - mouseNear); | |||||
Vector3 pick; | |||||
if (dragging) | |||||
{ | |||||
auto result = pickingRay.intersects(*terrain.getSurfaceMesh()); | |||||
if (std::get<0>(result)) | |||||
{ | |||||
pick = pickingRay.extrapolate(std::get<1>(result)); | |||||
} | |||||
else | |||||
{ | |||||
Plane plane; | |||||
plane.set(Vector3(0, 1, 0), Vector3(0.0f)); | |||||
auto result = pickingRay.intersects(plane); | |||||
pick = pickingRay.extrapolate(std::get<1>(result)); | |||||
} | |||||
Transform xf = Transform::getIdentity(); | |||||
xf.translation = pick; | |||||
application->antModelInstance->setTransform(xf); | |||||
if (!oldDragging) | |||||
{ | |||||
dragStart = pick; | |||||
} | |||||
dragEnd = pick; | |||||
Vector3 dragMin; | |||||
dragMin.x = std::min(dragStart.x, dragEnd.x); | |||||
dragMin.y = std::min(dragStart.y, dragEnd.y); | |||||
dragMin.z = std::min(dragStart.z, dragEnd.z); | |||||
Vector3 dragMax; | |||||
dragMax.x = std::max(dragStart.x, dragEnd.x); | |||||
dragMax.y = std::max(dragStart.y, dragEnd.y); | |||||
dragMax.z = std::max(dragStart.z, dragEnd.z); | |||||
float halfWorldSize = worldSize * 0.5f; | |||||
application->clippingPlaneOffsets[0] = Vector3(dragMax.x, -halfWorldSize, 0.0f); | |||||
application->clippingPlaneOffsets[1] = Vector3(0.0f, -halfWorldSize, dragMin.z); | |||||
application->clippingPlaneOffsets[2] = Vector3(dragMin.x, -halfWorldSize, 0.0f); | |||||
application->clippingPlaneOffsets[3] = Vector3(0.0f, -halfWorldSize, dragMax.z); | |||||
} | |||||
// Calculate clipping planes | |||||
float halfWorldSize = worldSize * 0.5f; | |||||
// E, N, W, S, B | |||||
//application->clippingPlaneOffsets[0] = Vector3(halfWorldSize * 0.5f, -halfWorldSize, 0.0f); | |||||
//application->clippingPlaneOffsets[1] = Vector3(0.0f, -halfWorldSize, -halfWorldSize * 0.5f); | |||||
//application->clippingPlaneOffsets[2] = Vector3(-halfWorldSize * 0.5f, -halfWorldSize, 0.0f); | |||||
//application->clippingPlaneOffsets[3] = Vector3(0.0f, -halfWorldSize, halfWorldSize * 0.5f); | |||||
application->clippingPlaneOffsets[4] = Vector3(0.0f, -worldSize * 2.0f, 0.0f); | |||||
application->clippingPlaneNormals[0] = Vector3(1.0f, 0.0f, 0.0f); | |||||
application->clippingPlaneNormals[1] = Vector3(0.0f, 0.0f, -1.0f); | |||||
application->clippingPlaneNormals[2] = Vector3(-1.0f, 0.0f, 0.0f); | |||||
application->clippingPlaneNormals[3] = Vector3(0.0f, 0.0f, 1.0f); | |||||
application->clippingPlaneNormals[4] = Vector3(0.0f, -1.0f, 0.0f); | |||||
for (int i = 0; i < 5; ++i) | |||||
{ | |||||
application->clippingPlanes[i].set(application->clippingPlaneNormals[i], application->clippingPlaneOffsets[i]); | |||||
} | |||||
application->lightingPass.setClippingPlanes(&application->clippingPlanes[0]); | |||||
application->lineBatcher->getBatch()->update(); | |||||
// Perform tweening | |||||
application->tweener->update(dt); | |||||
// Update UI | |||||
application->uiRootElement->update(); | |||||
// Clear to black | |||||
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); | |||||
// Render background | |||||
application->renderer.render(application->bgScene); | |||||
// Render scene | |||||
application->renderer.render(application->scene); | |||||
// Form billboard batch for UI then render UI scene | |||||
application->uiBatcher->batch(application->uiBatch, application->uiRootElement); | |||||
application->renderer.render(application->uiScene); | |||||
// Swap buffers | |||||
SDL_GL_SwapWindow(application->window); | |||||
} | |||||
void ExperimentState::exit() | |||||
{ | |||||
std::cout << "Exiting ExperimentState..." << std::endl; | |||||
application->inputManager->removeWindowObserver(this); | |||||
} | |||||
void ExperimentState::windowClosed() | |||||
{ | |||||
application->close(EXIT_SUCCESS); | |||||
} | |||||
void ExperimentState::windowResized(int width, int height) | |||||
{ | |||||
// Update application dimensions | |||||
application->width = width; | |||||
application->height = height; | |||||
if (application->fullscreen) | |||||
{ | |||||
application->fullscreenWidth = width; | |||||
application->fullscreenHeight = height; | |||||
} | |||||
else | |||||
{ | |||||
application->windowedWidth = width; | |||||
application->windowedHeight = height; | |||||
} | |||||
// Setup default render target | |||||
application->defaultRenderTarget.width = application->width; | |||||
application->defaultRenderTarget.height = application->height; | |||||
// UI camera | |||||
application->uiCamera.setOrthographic(0, application->width, application->height, 0, -1.0f, 1.0f); | |||||
// 3D camera | |||||
application->camera.setPerspective( | |||||
glm::radians(25.0f), | |||||
(float)application->width / (float)application->height, | |||||
0.5f, | |||||
2000.0f); | |||||
} | |||||
void ExperimentState::mouseButtonPressed(int button, int x, int y) | |||||
{ | |||||
dragging = true; | |||||
} | |||||
void ExperimentState::mouseButtonReleased(int button, int x, int y) | |||||
{ | |||||
dragging = false; | |||||
} |
@ -0,0 +1,59 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef EXPERIMENT_STATE_HPP | |||||
#define EXPERIMENT_STATE_HPP | |||||
#include "../application-state.hpp" | |||||
#include "../input.hpp" | |||||
#include "../debug.hpp" | |||||
#include "../nest.hpp" | |||||
#include "../terrain.hpp" | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
class ExperimentState: public ApplicationState, public WindowObserver, public MouseButtonObserver | |||||
{ | |||||
public: | |||||
ExperimentState(Application* application); | |||||
virtual ~ExperimentState(); | |||||
virtual void enter(); | |||||
virtual void execute(); | |||||
virtual void exit(); | |||||
virtual void windowClosed(); | |||||
virtual void windowResized(int width, int height); | |||||
virtual void mouseButtonPressed(int button, int x, int y); | |||||
virtual void mouseButtonReleased(int button, int x, int y); | |||||
void generateNest(); | |||||
private: | |||||
Timer timer; | |||||
Nest nest; | |||||
Terrain terrain; | |||||
bool dragging; | |||||
bool oldDragging; | |||||
Vector3 dragStart; | |||||
Vector3 dragEnd; | |||||
}; | |||||
#endif // EXPERIMENT_STATE_HPP |
@ -0,0 +1,654 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "splash-state.hpp" | |||||
#include "title-state.hpp" | |||||
#include "experiment-state.hpp" | |||||
#include "../application.hpp" | |||||
#include "../camera-controller.hpp" | |||||
#include "../debug.hpp" | |||||
#include "../model-loader.hpp" | |||||
#include <iostream> | |||||
#include <cstdio> | |||||
#include <SDL.h> | |||||
const float blankDuration = 0.0f; | |||||
const float fadeInDuration = 0.5f; | |||||
const float hangDuration = 1.0f; | |||||
const float fadeOutDuration = 0.5f; | |||||
SplashState::SplashState(Application* application): | |||||
ApplicationState(application) | |||||
{} | |||||
SplashState::~SplashState() | |||||
{} | |||||
void SplashState::enter() | |||||
{ | |||||
std::cout << "Entering SplashState..." << std::endl; | |||||
application->scene.addLayer(); | |||||
application->uiScene.addLayer(); | |||||
// Debug | |||||
application->lineBatcher = new LineBatcher(4096); | |||||
BillboardBatch* lineBatch = application->lineBatcher->getBatch(); | |||||
lineBatch->setAlignment(&application->camera, BillboardAlignmentMode::CYLINDRICAL); | |||||
lineBatch->setAlignmentVector(Vector3(1, 0, 0)); | |||||
application->scene.getLayer(0)->addObject(lineBatch); | |||||
// Load menu font | |||||
application->menuFont = new Font(512, 512); | |||||
FontLoader* fontLoader = new FontLoader(); | |||||
if (!fontLoader->load("data/fonts/Varela-Regular.ttf", application->fontSizePX, application->menuFont)) | |||||
{ | |||||
std::cerr << "Failed to load font" << std::endl; | |||||
} | |||||
delete fontLoader; | |||||
// Load splash texture | |||||
application->splashTexture.load("data/textures/splash.png"); | |||||
// Load title texture | |||||
application->titleTexture.load("data/textures/title.png"); | |||||
// Get UI strings | |||||
std::string pressAnyKeyString; | |||||
std::string backString; | |||||
std::string challengeString; | |||||
std::string experimentString; | |||||
std::string settingsString; | |||||
std::string quitString; | |||||
std::string loadString; | |||||
std::string newString; | |||||
std::string videoString; | |||||
std::string audioString; | |||||
std::string controlsString; | |||||
std::string gameString; | |||||
std::string resumeString; | |||||
std::string returnToMainMenuString; | |||||
std::string quitToDesktopString; | |||||
application->strings.get("press-any-key", &pressAnyKeyString); | |||||
application->strings.get("back", &backString); | |||||
application->strings.get("challenge", &challengeString); | |||||
application->strings.get("experiment", &experimentString); | |||||
application->strings.get("settings", &settingsString); | |||||
application->strings.get("quit", &quitString); | |||||
application->strings.get("load", &loadString); | |||||
application->strings.get("new", &newString); | |||||
application->strings.get("video", &videoString); | |||||
application->strings.get("audio", &audioString); | |||||
application->strings.get("controls", &controlsString); | |||||
application->strings.get("game", &gameString); | |||||
application->strings.get("resume", &resumeString); | |||||
application->strings.get("return-to-main-menu", &returnToMainMenuString); | |||||
application->strings.get("quit-to-desktop", &quitToDesktopString); | |||||
// Colors | |||||
application->selectedColor = Vector4(1.0f, 1.0f, 1.0f, 1.0f); | |||||
application->deselectedColor = Vector4(0.35f, 0.35f, 0.35f, 1.0f); | |||||
// Build UI | |||||
application->uiRootElement = new UIContainer(); | |||||
application->uiRootElement->setDimensions(Vector2(application->width, application->height)); | |||||
application->mouse->addMouseMotionObserver(application->uiRootElement); | |||||
application->mouse->addMouseButtonObserver(application->uiRootElement); | |||||
application->blackoutImage = new UIImage(); | |||||
application->blackoutImage->setDimensions(Vector2(application->width, application->height)); | |||||
application->blackoutImage->setLayerOffset(99); | |||||
application->blackoutImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f)); | |||||
application->blackoutImage->setVisible(false); | |||||
application->uiRootElement->addChild(application->blackoutImage); | |||||
application->splashImage = new UIImage(); | |||||
application->splashImage->setAnchor(Anchor::CENTER); | |||||
application->splashImage->setDimensions(Vector2(application->splashTexture.getWidth(), application->splashTexture.getHeight())); | |||||
application->splashImage->setTexture(&application->splashTexture); | |||||
application->splashImage->setVisible(false); | |||||
application->uiRootElement->addChild(application->splashImage); | |||||
application->titleImage = new UIImage(); | |||||
application->titleImage->setAnchor(Vector2(0.5f, 0.0f)); | |||||
application->titleImage->setDimensions(Vector2(application->titleTexture.getWidth(), application->titleTexture.getHeight())); | |||||
application->titleImage->setTranslation(Vector2(0.0f, (int)(application->height * (1.0f / 3.0f) - application->titleTexture.getHeight()))); | |||||
application->titleImage->setTexture(&application->titleTexture); | |||||
application->titleImage->setVisible(false); | |||||
application->uiRootElement->addChild(application->titleImage); | |||||
/* | |||||
application->copyrightImage = new UIImage(); | |||||
application->copyrightImage->setAnchor(Vector2(0.5f, 1.0f)); | |||||
application->copyrightImage->setDimensions(Vector2(copyrightTextureWidth, copyrightTextureHeight)); | |||||
application->copyrightImage->setTranslation(Vector2(-.5f, (int)(-application->height * (1.0f / 10.0f) - copyrightTextureHeight * 0.5f))); | |||||
application->copyrightImage->setTexture(nullptr); | |||||
application->copyrightImage->setVisible(false); | |||||
application->uiRootElement->addChild(application->copyrightImage); | |||||
*/ | |||||
application->anyKeyLabel = new UILabel(); | |||||
application->anyKeyLabel->setAnchor(Vector2(0.5f, 1.0f)); | |||||
application->anyKeyLabel->setFont(application->menuFont); | |||||
application->anyKeyLabel->setTranslation(Vector2(0.0f, (int)(-application->height * (1.0f / 3.0f)/* - application->menuFont->getMetrics().getHeight() * 0.5f*/))); | |||||
application->anyKeyLabel->setText(pressAnyKeyString); | |||||
application->anyKeyLabel->setVisible(false); | |||||
application->uiRootElement->addChild(application->anyKeyLabel); | |||||
application->menuSelectorLabel = new UILabel(); | |||||
application->menuSelectorLabel->setAnchor(Anchor::TOP_LEFT); | |||||
application->menuSelectorLabel->setFont(application->menuFont); | |||||
application->menuSelectorLabel->setText(">"); | |||||
/* | |||||
application->menuSelectorLabel = new UIImage(); | |||||
application->menuSelectorLabel->setAnchor(Anchor::TOP_LEFT); | |||||
application->menuSelectorLabel->setDimensions(Vector2(selectorTextureWidth, selectorTextureHeight)); | |||||
application->menuSelectorLabel->setTextureID(selectorTextureID); | |||||
*/ | |||||
application->menuSelectorLabel->setVisible(false); | |||||
application->uiRootElement->addChild(application->menuSelectorLabel); | |||||
application->mainMenuContainer = new UIContainer(); | |||||
application->mainMenuContainer->setDimensions(Vector2(application->width, application->menuFont->getMetrics().getHeight() * 4)); | |||||
application->mainMenuContainer->setAnchor(Vector2(0.0f, 0.5f)); | |||||
application->mainMenuContainer->setVisible(false); | |||||
application->mainMenuContainer->setActive(false); | |||||
application->uiRootElement->addChild(application->mainMenuContainer); | |||||
application->challengeLabel = new UILabel(); | |||||
application->challengeLabel->setFont(application->menuFont); | |||||
application->challengeLabel->setText(challengeString); | |||||
application->challengeLabel->setTintColor(application->deselectedColor); | |||||
application->experimentLabel = new UILabel(); | |||||
application->experimentLabel->setFont(application->menuFont); | |||||
application->experimentLabel->setText(experimentString); | |||||
application->experimentLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight())); | |||||
application->experimentLabel->setTintColor(application->deselectedColor); | |||||
application->settingsLabel = new UILabel(); | |||||
application->settingsLabel->setFont(application->menuFont); | |||||
application->settingsLabel->setText(settingsString); | |||||
application->settingsLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 2)); | |||||
application->settingsLabel->setTintColor(application->deselectedColor); | |||||
application->quitLabel = new UILabel(); | |||||
application->quitLabel->setFont(application->menuFont); | |||||
application->quitLabel->setText(quitString); | |||||
application->quitLabel->setTintColor(application->deselectedColor); | |||||
application->quitLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 3)); | |||||
application->mainMenuContainer->addChild(application->challengeLabel); | |||||
application->mainMenuContainer->addChild(application->experimentLabel); | |||||
application->mainMenuContainer->addChild(application->settingsLabel); | |||||
application->mainMenuContainer->addChild(application->quitLabel); | |||||
application->challengeMenuContainer = new UIContainer(); | |||||
application->challengeMenuContainer->setDimensions(Vector2(application->width, application->menuFont->getMetrics().getHeight() * 4)); | |||||
application->challengeMenuContainer->setAnchor(Vector2(0.0f, 0.5f)); | |||||
application->challengeMenuContainer->setVisible(false); | |||||
application->challengeMenuContainer->setActive(false); | |||||
application->uiRootElement->addChild(application->challengeMenuContainer); | |||||
application->experimentMenuContainer = new UIContainer(); | |||||
application->experimentMenuContainer->setDimensions(Vector2(application->width, application->menuFont->getMetrics().getHeight() * 3)); | |||||
application->experimentMenuContainer->setAnchor(Vector2(0.0f, 0.5f)); | |||||
application->experimentMenuContainer->setVisible(false); | |||||
application->experimentMenuContainer->setActive(false); | |||||
application->uiRootElement->addChild(application->experimentMenuContainer); | |||||
application->loadLabel = new UILabel(); | |||||
application->loadLabel->setFont(application->menuFont); | |||||
application->loadLabel->setText(loadString); | |||||
application->loadLabel->setTintColor(application->deselectedColor); | |||||
application->loadLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 0)); | |||||
application->experimentMenuContainer->addChild(application->loadLabel); | |||||
application->newLabel = new UILabel(); | |||||
application->newLabel->setFont(application->menuFont); | |||||
application->newLabel->setText(newString); | |||||
application->newLabel->setTintColor(application->deselectedColor); | |||||
application->newLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 1)); | |||||
application->experimentMenuContainer->addChild(application->newLabel); | |||||
application->experimentBackLabel = new UILabel(); | |||||
application->experimentBackLabel->setFont(application->menuFont); | |||||
application->experimentBackLabel->setText(backString); | |||||
application->experimentBackLabel->setTintColor(application->deselectedColor); | |||||
application->experimentBackLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 2)); | |||||
application->experimentMenuContainer->addChild(application->experimentBackLabel); | |||||
application->settingsMenuContainer = new UIContainer(); | |||||
application->settingsMenuContainer->setDimensions(Vector2(application->width, application->menuFont->getMetrics().getHeight() * 5)); | |||||
application->settingsMenuContainer->setAnchor(Vector2(0.0f, 0.5f)); | |||||
application->settingsMenuContainer->setVisible(false); | |||||
application->settingsMenuContainer->setActive(false); | |||||
application->uiRootElement->addChild(application->settingsMenuContainer); | |||||
application->videoLabel = new UILabel(); | |||||
application->videoLabel->setFont(application->menuFont); | |||||
application->videoLabel->setText(videoString); | |||||
application->videoLabel->setTintColor(application->deselectedColor); | |||||
application->videoLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 0)); | |||||
application->settingsMenuContainer->addChild(application->videoLabel); | |||||
application->audioLabel = new UILabel(); | |||||
application->audioLabel->setFont(application->menuFont); | |||||
application->audioLabel->setText(audioString); | |||||
application->audioLabel->setTintColor(application->deselectedColor); | |||||
application->audioLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 1)); | |||||
application->settingsMenuContainer->addChild(application->audioLabel); | |||||
application->controlsLabel = new UILabel(); | |||||
application->controlsLabel->setFont(application->menuFont); | |||||
application->controlsLabel->setText(controlsString); | |||||
application->controlsLabel->setTintColor(application->deselectedColor); | |||||
application->controlsLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 2)); | |||||
application->settingsMenuContainer->addChild(application->controlsLabel); | |||||
application->gameLabel = new UILabel(); | |||||
application->gameLabel->setFont(application->menuFont); | |||||
application->gameLabel->setText(gameString); | |||||
application->gameLabel->setTintColor(application->deselectedColor); | |||||
application->gameLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 3)); | |||||
application->settingsMenuContainer->addChild(application->gameLabel); | |||||
application->settingsBackLabel = new UILabel(); | |||||
application->settingsBackLabel->setFont(application->menuFont); | |||||
application->settingsBackLabel->setText(backString); | |||||
application->settingsBackLabel->setTintColor(application->deselectedColor); | |||||
application->settingsBackLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 4)); | |||||
application->settingsMenuContainer->addChild(application->settingsBackLabel); | |||||
application->pauseMenuContainer = new UIContainer(); | |||||
application->pauseMenuContainer->setDimensions(Vector2(application->width, application->menuFont->getMetrics().getHeight() * 6)); | |||||
application->pauseMenuContainer->setAnchor(Anchor::CENTER); | |||||
application->pauseMenuContainer->setVisible(false); | |||||
application->pauseMenuContainer->setActive(false); | |||||
application->uiRootElement->addChild(application->pauseMenuContainer); | |||||
application->pausedResumeLabel = new UILabel(); | |||||
application->pausedResumeLabel->setFont(application->menuFont); | |||||
application->pausedResumeLabel->setText(resumeString); | |||||
application->pausedResumeLabel->setTintColor(application->deselectedColor); | |||||
application->pausedResumeLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 0)); | |||||
application->pauseMenuContainer->addChild(application->pausedResumeLabel); | |||||
application->returnToMainMenuLabel = new UILabel(); | |||||
application->returnToMainMenuLabel->setFont(application->menuFont); | |||||
application->returnToMainMenuLabel->setText(returnToMainMenuString); | |||||
application->returnToMainMenuLabel->setTintColor(application->deselectedColor); | |||||
application->returnToMainMenuLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 1)); | |||||
application->pauseMenuContainer->addChild(application->returnToMainMenuLabel); | |||||
application->quitToDesktopLabel = new UILabel(); | |||||
application->quitToDesktopLabel->setFont(application->menuFont); | |||||
application->quitToDesktopLabel->setText(quitToDesktopString); | |||||
application->quitToDesktopLabel->setTintColor(application->deselectedColor); | |||||
application->quitToDesktopLabel->setTranslation(Vector2(0.0f, application->menuFont->getMetrics().getHeight() * 2)); | |||||
application->pauseMenuContainer->addChild(application->quitToDesktopLabel); | |||||
/* | |||||
UIContainer* pauseMenuContainer; | |||||
UILabel* pausedResumeLabel; | |||||
UILabel* pausedSaveLabel; | |||||
UILabel* pausedNewLabel; | |||||
UILabel* pausedSettingsLabel; | |||||
UILabel* returnToMainMenuLabel; | |||||
UILabel* quitToDesktopLabel;*/ | |||||
// Setup UI batch | |||||
application->uiBatch = new BillboardBatch(); | |||||
application->uiBatch->resize(256); | |||||
application->uiBatcher = new UIBatcher(); | |||||
// Setup UI render pass and compositor | |||||
application->uiPass.setRenderTarget(&application->defaultRenderTarget); | |||||
application->uiCompositor.addPass(&application->uiPass); | |||||
application->uiCompositor.load(nullptr); | |||||
// Setup UI camera | |||||
application->uiCamera.lookAt(glm::vec3(0), glm::vec3(0, 0, -1), glm::vec3(0, 1, 0)); | |||||
application->uiCamera.setCompositor(&application->uiCompositor); | |||||
application->uiCamera.setCompositeIndex(0); | |||||
// Setup UI scene | |||||
application->uiScene.getLayer(0)->addObject(application->uiBatch); | |||||
application->uiScene.getLayer(0)->addObject(&application->uiCamera); | |||||
// Setup tweening | |||||
application->tweener = new Tweener(); | |||||
application->fadeInTween = new Tween<Vector4>(EaseFunction::IN_CUBIC, 0.0f, 1.5f, Vector4(0.0f, 0.0f, 0.0f, 1.0f), Vector4(0.0f, 0.0f, 0.0f, -1.0f)); | |||||
application->fadeInTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->blackoutImage, std::placeholders::_1)); | |||||
application->tweener->addTween(application->fadeInTween); | |||||
application->fadeOutTween = new Tween<Vector4>(EaseFunction::OUT_CUBIC, 0.0f, 1.5f, Vector4(0.0f, 0.0f, 0.0f, 0.0f), Vector4(0.0f, 0.0f, 0.0f, 1.0f)); | |||||
application->fadeOutTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->blackoutImage, std::placeholders::_1)); | |||||
application->tweener->addTween(application->fadeOutTween); | |||||
application->splashFadeInTween = new Tween<Vector4>(EaseFunction::IN_CUBIC, 0.0f, 0.5f, Vector4(1.0f, 1.0f, 1.0f, 0.0f), Vector4(0.0f, 0.0f, 0.0f, 1.0f)); | |||||
application->splashFadeInTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->splashImage, std::placeholders::_1)); | |||||
application->tweener->addTween(application->splashFadeInTween); | |||||
application->splashFadeOutTween = new Tween<Vector4>(EaseFunction::OUT_CUBIC, 0.0f, 0.5f, Vector4(1.0f, 1.0f, 1.0f, 1.0f), Vector4(0.0f, 0.0f, 0.0f, -1.0f)); | |||||
application->splashFadeOutTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->splashImage, std::placeholders::_1)); | |||||
application->tweener->addTween(application->splashFadeOutTween); | |||||
application->titleFadeInTween = new Tween<Vector4>(EaseFunction::IN_CUBIC, 0.0f, 2.0f, Vector4(1.0f, 1.0f, 1.0f, 0.0f), Vector4(0.0f, 0.0f, 0.0f, 1.0f)); | |||||
application->titleFadeInTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->titleImage, std::placeholders::_1)); | |||||
application->tweener->addTween(application->titleFadeInTween); | |||||
application->titleFadeOutTween = new Tween<Vector4>(EaseFunction::OUT_CUBIC, 0.0f, 0.25f, Vector4(1.0f, 1.0f, 1.0f, 1.0f), Vector4(0.0f, 0.0f, 0.0f, -1.0f)); | |||||
application->titleFadeOutTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->titleImage, std::placeholders::_1)); | |||||
application->tweener->addTween(application->titleFadeOutTween); | |||||
application->copyrightFadeInTween = new Tween<Vector4>(EaseFunction::IN_CUBIC, 0.0f, 1.0f, Vector4(1.0f, 1.0f, 1.0f, 0.0f), Vector4(0.0f, 0.0f, 0.0f, 1.0f)); | |||||
application->copyrightFadeInTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->copyrightImage, std::placeholders::_1)); | |||||
application->tweener->addTween(application->copyrightFadeInTween); | |||||
application->copyrightFadeOutTween = new Tween<Vector4>(EaseFunction::OUT_CUBIC, 0.0f, 0.25f, Vector4(1.0f, 1.0f, 1.0f, 1.0f), Vector4(0.0f, 0.0f, 0.0f, -1.0f)); | |||||
application->copyrightFadeOutTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->copyrightImage, std::placeholders::_1)); | |||||
application->tweener->addTween(application->copyrightFadeOutTween); | |||||
application->anyKeyFadeInTween = new Tween<Vector4>(EaseFunction::LINEAR, 0.0f, 1.5f, Vector4(1.0f, 1.0f, 1.0f, 0.0f), Vector4(0.0f, 0.0f, 0.0f, 1.0f)); | |||||
application->anyKeyFadeInTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->anyKeyLabel, std::placeholders::_1)); | |||||
application->tweener->addTween(application->anyKeyFadeInTween); | |||||
application->anyKeyFadeOutTween = new Tween<Vector4>(EaseFunction::LINEAR, 0.0f, 1.5f, Vector4(1.0f, 1.0f, 1.0f, 1.0f), Vector4(0.0f, 0.0f, 0.0f, -1.0f)); | |||||
application->anyKeyFadeOutTween->setUpdateCallback(std::bind(UIElement::setTintColor, application->anyKeyLabel, std::placeholders::_1)); | |||||
application->tweener->addTween(application->anyKeyFadeOutTween); | |||||
float menuFadeInDuration = 0.15f; | |||||
Vector4 menuFadeInStartColor = Vector4(1.0f, 1.0f, 1.0f, 0.0f); | |||||
Vector4 menuFadeInDeltaColor = Vector4(0.0f, 0.0f, 0.0f, 1.0f); | |||||
float menuFadeOutDuration = 0.15f; | |||||
Vector4 menuFadeOutStartColor = Vector4(1.0f, 1.0f, 1.0f, 1.0f); | |||||
Vector4 menuFadeOutDeltaColor = Vector4(0.0f, 0.0f, 0.0f, -1.0f); | |||||
float menuSlideInDuration = 0.35f; | |||||
Vector2 menuSlideInStartTranslation = Vector2(-64.0f, 0.0f); | |||||
Vector2 menuSlideInDeltaTranslation = Vector2(128.0f, 0.0f); | |||||
application->menuFadeInTween = new Tween<Vector4>(EaseFunction::OUT_QUINT, 0.0f, menuFadeInDuration, menuFadeInStartColor, menuFadeInDeltaColor); | |||||
application->tweener->addTween(application->menuFadeInTween); | |||||
application->menuFadeOutTween = new Tween<Vector4>(EaseFunction::OUT_QUINT, 0.0f, menuFadeOutDuration, menuFadeOutStartColor, menuFadeOutDeltaColor); | |||||
application->tweener->addTween(application->menuFadeOutTween); | |||||
application->menuSlideInTween = new Tween<Vector2>(EaseFunction::OUT_QUINT, 0.0f, menuSlideInDuration, menuSlideInStartTranslation, menuSlideInDeltaTranslation); | |||||
application->tweener->addTween(application->menuSlideInTween); | |||||
// Link tweens | |||||
application->anyKeyFadeInTween->setEndCallback(std::bind(TweenBase::start, application->anyKeyFadeOutTween)); | |||||
application->anyKeyFadeOutTween->setEndCallback(std::bind(TweenBase::start, application->anyKeyFadeInTween)); | |||||
// Menus | |||||
application->selectedMenuItemIndex = 0; | |||||
application->mainMenu = new Menu(); | |||||
MenuItem* challengeItem = application->mainMenu->addItem(); | |||||
challengeItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->challengeLabel, application->selectedColor)); | |||||
challengeItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->challengeLabel, application->deselectedColor)); | |||||
challengeItem->setActivatedCallback(std::bind(std::printf, "0\n")); | |||||
application->challengeLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, challengeItem->getIndex())); | |||||
application->challengeLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, challengeItem->getIndex())); | |||||
application->challengeLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, challengeItem->getIndex())); | |||||
MenuItem* experimentItem = application->mainMenu->addItem(); | |||||
experimentItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->experimentLabel, application->selectedColor)); | |||||
experimentItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->experimentLabel, application->deselectedColor)); | |||||
experimentItem->setActivatedCallback(std::bind(Application::enterMenu, application, 2)); | |||||
application->experimentLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, experimentItem->getIndex())); | |||||
application->experimentLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, experimentItem->getIndex())); | |||||
application->experimentLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, experimentItem->getIndex())); | |||||
MenuItem* settingsItem = application->mainMenu->addItem(); | |||||
settingsItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->settingsLabel, application->selectedColor)); | |||||
settingsItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->settingsLabel, application->deselectedColor)); | |||||
settingsItem->setActivatedCallback(std::bind(Application::enterMenu, application, 3)); | |||||
application->settingsLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, settingsItem->getIndex())); | |||||
application->settingsLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, settingsItem->getIndex())); | |||||
application->settingsLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, settingsItem->getIndex())); | |||||
MenuItem* quitItem = application->mainMenu->addItem(); | |||||
quitItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->quitLabel, application->selectedColor)); | |||||
quitItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->quitLabel, application->deselectedColor)); | |||||
quitItem->setActivatedCallback(std::bind(Application::close, application, EXIT_SUCCESS)); | |||||
application->quitLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, quitItem->getIndex())); | |||||
application->quitLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, quitItem->getIndex())); | |||||
application->quitLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, quitItem->getIndex())); | |||||
application->experimentMenu = new Menu(); | |||||
MenuItem* loadItem = application->experimentMenu->addItem(); | |||||
loadItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->loadLabel, application->selectedColor)); | |||||
loadItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->loadLabel, application->deselectedColor)); | |||||
loadItem->setActivatedCallback(std::bind(std::printf, "0\n")); | |||||
application->loadLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, loadItem->getIndex())); | |||||
application->loadLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, loadItem->getIndex())); | |||||
application->loadLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, loadItem->getIndex())); | |||||
MenuItem* newItem = application->experimentMenu->addItem(); | |||||
newItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->newLabel, application->selectedColor)); | |||||
newItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->newLabel, application->deselectedColor)); | |||||
newItem->setActivatedCallback(std::bind(Application::changeState, application, application->experimentState)); | |||||
application->newLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, newItem->getIndex())); | |||||
application->newLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, newItem->getIndex())); | |||||
application->newLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, newItem->getIndex())); | |||||
MenuItem* experimentBackItem = application->experimentMenu->addItem(); | |||||
experimentBackItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->experimentBackLabel, application->selectedColor)); | |||||
experimentBackItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->experimentBackLabel, application->deselectedColor)); | |||||
experimentBackItem->setActivatedCallback(std::bind(Application::enterMenu, application, 0)); | |||||
application->experimentBackLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, experimentBackItem->getIndex())); | |||||
application->experimentBackLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, experimentBackItem->getIndex())); | |||||
application->experimentBackLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, experimentBackItem->getIndex())); | |||||
application->settingsMenu = new Menu(); | |||||
MenuItem* videoItem = application->settingsMenu->addItem(); | |||||
videoItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->videoLabel, application->selectedColor)); | |||||
videoItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->videoLabel, application->deselectedColor)); | |||||
videoItem->setActivatedCallback(std::bind(std::printf, "0\n")); | |||||
application->videoLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, videoItem->getIndex())); | |||||
application->videoLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, videoItem->getIndex())); | |||||
application->videoLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, videoItem->getIndex())); | |||||
MenuItem* audioItem = application->settingsMenu->addItem(); | |||||
audioItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->audioLabel, application->selectedColor)); | |||||
audioItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->audioLabel, application->deselectedColor)); | |||||
audioItem->setActivatedCallback(std::bind(std::printf, "1\n")); | |||||
application->audioLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, audioItem->getIndex())); | |||||
application->audioLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, audioItem->getIndex())); | |||||
application->audioLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, audioItem->getIndex())); | |||||
MenuItem* controlsItem = application->settingsMenu->addItem(); | |||||
controlsItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->controlsLabel, application->selectedColor)); | |||||
controlsItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->controlsLabel, application->deselectedColor)); | |||||
controlsItem->setActivatedCallback(std::bind(std::printf, "2\n")); | |||||
application->controlsLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, controlsItem->getIndex())); | |||||
application->controlsLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, controlsItem->getIndex())); | |||||
application->controlsLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, controlsItem->getIndex())); | |||||
MenuItem* gameItem = application->settingsMenu->addItem(); | |||||
gameItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->gameLabel, application->selectedColor)); | |||||
gameItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->gameLabel, application->deselectedColor)); | |||||
gameItem->setActivatedCallback(std::bind(std::printf, "3\n")); | |||||
application->gameLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, gameItem->getIndex())); | |||||
application->gameLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, gameItem->getIndex())); | |||||
application->gameLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, gameItem->getIndex())); | |||||
MenuItem* settingsBackItem = application->settingsMenu->addItem(); | |||||
settingsBackItem->setSelectedCallback(std::bind(UIElement::setTintColor, application->settingsBackLabel, application->selectedColor)); | |||||
settingsBackItem->setDeselectedCallback(std::bind(UIElement::setTintColor, application->settingsBackLabel, application->deselectedColor)); | |||||
settingsBackItem->setActivatedCallback(std::bind(Application::enterMenu, application, 0)); | |||||
application->settingsBackLabel->setMouseOverCallback(std::bind(Application::selectMenuItem, application, settingsBackItem->getIndex())); | |||||
application->settingsBackLabel->setMouseMovedCallback(std::bind(Application::selectMenuItem, application, settingsBackItem->getIndex())); | |||||
application->settingsBackLabel->setMousePressedCallback(std::bind(Application::activateMenuItem, application, settingsBackItem->getIndex())); | |||||
application->menuCount = 4; | |||||
application->menus = new Menu*[application->menuCount]; | |||||
application->menus[0] = application->mainMenu; | |||||
application->menus[1] = application->challengeMenu; | |||||
application->menus[2] = application->experimentMenu; | |||||
application->menus[3] = application->settingsMenu; | |||||
application->menuContainers = new UIContainer*[application->menuCount]; | |||||
application->menuContainers[0] = application->mainMenuContainer; | |||||
application->menuContainers[1] = application->challengeMenuContainer; | |||||
application->menuContainers[2] = application->experimentMenuContainer; | |||||
application->menuContainers[3] = application->settingsMenuContainer; | |||||
application->currentMenu = application->mainMenu; | |||||
application->currentMenuIndex = 0; | |||||
application->selectedMenuItemIndex = 0; | |||||
application->selectMenuItem(application->selectedMenuItemIndex); | |||||
// Models | |||||
application->displayModel = application->modelLoader->load("data/models/display.mdl"); | |||||
application->antModel = application->modelLoader->load("data/models/worker-ant.mdl"); | |||||
// Model instances | |||||
application->displayModelInstance = new ModelInstance(); | |||||
application->antModelInstance = new ModelInstance(); | |||||
// Allocate game variables | |||||
application->surfaceCam = new SurfaceCameraController(); | |||||
application->tunnelCam = new TunnelCameraController(); | |||||
// Setup screen fade-in transition | |||||
fadeIn = false; | |||||
fadeOut = false; | |||||
// Check for splash screen skip setting | |||||
skip = false; | |||||
application->settings.get("skip_splash", &skip); | |||||
// Add window observer and set layout | |||||
application->inputManager->addWindowObserver(this); | |||||
windowResized(application->width, application->height); | |||||
// Start timer | |||||
stateTime = 0.0f; | |||||
application->frameTimer.reset(); | |||||
application->frameTimer.start(); | |||||
} | |||||
void SplashState::execute() | |||||
{ | |||||
// Calculate delta time (in seconds) | |||||
float dt = static_cast<float>(application->frameTimer.microseconds().count()) / 1000000.0f; | |||||
application->frameTimer.reset(); | |||||
// Add dt to state time | |||||
stateTime += dt; | |||||
// Listen for splash screen skip | |||||
InputEvent event; | |||||
application->inputManager->listen(&event); | |||||
if (skip || event.type != InputEvent::Type::NONE) | |||||
{ | |||||
application->menuControlProfile->update(); | |||||
application->inputManager->update(); | |||||
// Check if application was closed | |||||
if (application->escape.isTriggered()) | |||||
{ | |||||
application->close(EXIT_SUCCESS); | |||||
return; | |||||
} | |||||
// Check if fullscreen was toggled | |||||
else if (application->toggleFullscreen.isTriggered() && !application->toggleFullscreen.wasTriggered()) | |||||
{ | |||||
application->changeFullscreen(); | |||||
} | |||||
else | |||||
{ | |||||
// Clear screen | |||||
glClear(GL_COLOR_BUFFER_BIT); | |||||
SDL_GL_SwapWindow(application->window); | |||||
// Change to title state | |||||
application->changeState(application->titleState); | |||||
return; | |||||
} | |||||
} | |||||
// Start fade-in | |||||
if (!fadeIn && stateTime >= blankDuration) | |||||
{ | |||||
// Begin fade-in | |||||
fadeIn = true; | |||||
application->splashImage->setVisible(true); | |||||
application->splashFadeInTween->start(); | |||||
} | |||||
// Begin fade-out | |||||
if (!fadeOut && stateTime >= blankDuration + application->splashFadeInTween->getDuration() + hangDuration) | |||||
{ | |||||
fadeOut = true; | |||||
application->splashFadeOutTween->start(); | |||||
} | |||||
// Next state | |||||
if (fadeOut && application->splashFadeOutTween->isStopped()) | |||||
{ | |||||
application->splashImage->setVisible(false); | |||||
application->changeState(application->titleState); | |||||
return; | |||||
} | |||||
// Update input | |||||
application->inputManager->update(); | |||||
// Update menu controls | |||||
application->menuControlProfile->update(); | |||||
// Check if application was closed | |||||
if (application->inputManager->wasClosed() || application->escape.isTriggered()) | |||||
{ | |||||
application->close(EXIT_SUCCESS); | |||||
return; | |||||
} | |||||
// Perform tweening | |||||
application->tweener->update(dt); | |||||
// Update UI | |||||
application->uiRootElement->update(); | |||||
// Clear to black | |||||
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); | |||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); | |||||
// Form billboard batch for UI then render UI scene | |||||
application->uiBatcher->batch(application->uiBatch, application->uiRootElement); | |||||
application->renderer.render(application->uiScene); | |||||
// Swap buffers | |||||
SDL_GL_SwapWindow(application->window); | |||||
} | |||||
void SplashState::exit() | |||||
{ | |||||
std::cout << "Exiting SplashState..." << std::endl; | |||||
// Hide splash screen | |||||
application->splashImage->setVisible(false); | |||||
application->inputManager->removeWindowObserver(this); | |||||
} | |||||
void SplashState::windowClosed() | |||||
{ | |||||
application->close(EXIT_SUCCESS); | |||||
} | |||||
void SplashState::windowResized(int width, int height) | |||||
{ | |||||
// Update application dimensions | |||||
application->width = width; | |||||
application->height = height; | |||||
if (application->fullscreen) | |||||
{ | |||||
application->fullscreenWidth = width; | |||||
application->fullscreenHeight = height; | |||||
} | |||||
else | |||||
{ | |||||
application->windowedWidth = width; | |||||
application->windowedHeight = height; | |||||
} | |||||
// Setup default render target | |||||
application->defaultRenderTarget.width = application->width; | |||||
application->defaultRenderTarget.height = application->height; | |||||
// Resize UI | |||||
application->resizeUI(); | |||||
} |
@ -0,0 +1,52 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef SPLASH_STATE_HPP | |||||
#define SPLASH_STATE_HPP | |||||
#include "../application-state.hpp" | |||||
#include "../input.hpp" | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
/** | |||||
* Displays a splash screen. | |||||
*/ | |||||
class SplashState: public ApplicationState, public WindowObserver | |||||
{ | |||||
public: | |||||
SplashState(Application* application); | |||||
virtual ~SplashState(); | |||||
virtual void enter(); | |||||
virtual void execute(); | |||||
virtual void exit(); | |||||
void windowClosed(); | |||||
void windowResized(int width, int height); | |||||
private: | |||||
float stateTime; | |||||
bool fadeIn; | |||||
bool fadeOut; | |||||
bool skip; | |||||
}; | |||||
#endif // SPLASH_STATE_HPP |
@ -0,0 +1,381 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "title-state.hpp" | |||||
#include "experiment-state.hpp" | |||||
#include "../application.hpp" | |||||
#include <iostream> | |||||
#include <SDL.h> | |||||
const float blankDuration = 0.0f; | |||||
const float fadeInDuration = 0.5f; | |||||
const float hangDuration = 1.0f; | |||||
const float fadeOutDuration = 0.5f; | |||||
const float titleDelay = 2.0f; | |||||
const float copyrightDelay = 3.0f; | |||||
const float pressAnyKeyDelay = 5.0f; | |||||
TitleState::TitleState(Application* application): | |||||
ApplicationState(application) | |||||
{} | |||||
TitleState::~TitleState() | |||||
{} | |||||
void TitleState::enter() | |||||
{ | |||||
std::cout << "Entering TitleState..." << std::endl; | |||||
// Setup screen fade-in transition | |||||
fadeIn = false; | |||||
fadeOut = false; | |||||
/* | |||||
// Load tunnel texture | |||||
GLuint tunnelTexture; | |||||
loadTexture("data/textures/soil-01.png", &tunnelTexture); | |||||
// Setup triplanar texturing | |||||
Material* material = (Material*)application->displayModel->getMaterial(0); | |||||
material->setRoughness(0.75f); | |||||
material->setDiffuseColor(glm::vec3(1.0f)); | |||||
material->setSpecularColor(glm::vec3(0.001f)); | |||||
material->setOpacity(0.999f); | |||||
Texture* texture = material->createTexture(); | |||||
texture->setTextureID(tunnelTexture); | |||||
texture->setCoordinateSource(TextureCoordinateSource::TRIPLANAR_PROJECTION); | |||||
texture->setCoordinateScale(glm::vec3(1.0f / 2.0f)); | |||||
texture->setDiffuseInfluence(1.0f); | |||||
*/ | |||||
application->displayModelInstance->setModel(application->displayModel); | |||||
application->displayModelInstance->setTransform(Transform::getIdentity()); | |||||
application->antModelInstance->setModel(application->antModel); | |||||
application->antModelInstance->setTransform(Transform::getIdentity()); | |||||
// Setup lighting | |||||
application->sunlight.setColor(glm::vec3(1.0f)); | |||||
application->sunlight.setDirection(glm::normalize(glm::vec3(0.5, -1, -0.5))); | |||||
// Setup lighting pass | |||||
application->lightingPass.setRenderTarget(&application->defaultRenderTarget); | |||||
application->lightingPass.setShadowMap(0); | |||||
application->lightingPass.setShadowCamera(&application->camera); | |||||
application->defaultCompositor.addPass(&application->lightingPass); | |||||
application->camera.lookAt( | |||||
glm::vec3(0.0f, 0.0f, 10.0f), | |||||
glm::vec3(0.0f, 0.0f, 0.0f), | |||||
glm::vec3(0.0f, 1.0f, 0.0f)); | |||||
application->camera.setCompositor(&application->defaultCompositor); | |||||
application->camera.setCompositeIndex(0); | |||||
// Setup scene | |||||
DirectionalLight* lightA = new DirectionalLight(); | |||||
DirectionalLight* lightB = new DirectionalLight(); | |||||
DirectionalLight* lightC = new DirectionalLight(); | |||||
lightA->setColor(glm::vec3(1.0f)); | |||||
lightB->setColor(glm::vec3(0.25f)); | |||||
lightC->setColor(glm::vec3(1.0f, 1.0f, 1.0f)); | |||||
lightA->setDirection(glm::normalize(glm::vec3(0.0, -0.8, -0.2))); | |||||
lightB->setDirection(glm::normalize(glm::vec3(1.0, -.2, 0.0f))); | |||||
lightC->setDirection(glm::normalize(glm::vec3(0.0, 1.0, 0.0))); | |||||
//application->scene.addObject(&application->sunlight); | |||||
application->scene.getLayer(0)->addObject(lightA); | |||||
application->scene.getLayer(0)->addObject(lightB); | |||||
application->scene.getLayer(0)->addObject(lightC); | |||||
application->scene.getLayer(0)->addObject(application->displayModelInstance); | |||||
application->scene.getLayer(0)->addObject(application->antModelInstance); | |||||
application->scene.getLayer(0)->addObject(&application->camera); | |||||
// Load compositor | |||||
RenderQueue renderQueue; | |||||
const std::list<SceneObject*>* objects = application->scene.getLayer(0)->getObjects(); | |||||
for (const SceneObject* object: *objects) | |||||
renderQueue.queue(object); | |||||
RenderContext renderContext; | |||||
renderContext.camera = nullptr; | |||||
renderContext.layer = application->scene.getLayer(0); | |||||
renderContext.queue = &renderQueue; | |||||
application->defaultCompositor.load(&renderContext); | |||||
// Setup fade-in | |||||
application->blackoutImage->setVisible(true); | |||||
application->fadeInTween->start(); | |||||
application->inputManager->addWindowObserver(this); | |||||
windowResized(application->width, application->height); | |||||
// Start timer | |||||
stateTime = 0.0f; | |||||
application->frameTimer.reset(); | |||||
application->frameTimer.start(); | |||||
substate = 0; | |||||
} | |||||
void TitleState::execute() | |||||
{ | |||||
// Calculate delta time (in seconds) | |||||
float dt = static_cast<float>(application->frameTimer.microseconds().count()) / 1000000.0f; | |||||
application->frameTimer.reset(); | |||||
// Add dt to state time | |||||
stateTime += dt; | |||||
if (substate == 0 || substate == 1) | |||||
{ | |||||
if (stateTime >= titleDelay && !application->titleImage->isVisible()) | |||||
{ | |||||
application->titleImage->setVisible(true); | |||||
application->titleFadeInTween->start(); | |||||
} | |||||
if (stateTime >= copyrightDelay && !application->copyrightImage->isVisible()) | |||||
{ | |||||
//application->copyrightImage->setVisible(true); | |||||
//application->copyrightFadeInTween->start(); | |||||
} | |||||
if (stateTime >= pressAnyKeyDelay && !application->anyKeyLabel->isVisible()) | |||||
{ | |||||
application->anyKeyLabel->setVisible(true); | |||||
application->anyKeyFadeInTween->start(); | |||||
} | |||||
} | |||||
if (substate == 0 && stateTime >= titleDelay && application->titleFadeInTween->isStopped()) | |||||
{ | |||||
substate = 1; | |||||
} | |||||
// Listen for fade-in skip and "press any key" | |||||
if (substate < 2) | |||||
{ | |||||
InputEvent event; | |||||
application->inputManager->listen(&event); | |||||
if (event.type != InputEvent::Type::NONE) | |||||
{ | |||||
application->menuControlProfile->update(); | |||||
application->inputManager->update(); | |||||
// Check if application was closed | |||||
if (application->escape.isTriggered()) | |||||
{ | |||||
application->close(EXIT_SUCCESS); | |||||
return; | |||||
} | |||||
// Check if fullscreen was toggled | |||||
else if (application->toggleFullscreen.isTriggered() && !application->toggleFullscreen.wasTriggered()) | |||||
{ | |||||
application->changeFullscreen(); | |||||
} | |||||
else if (!application->menuCancel.isTriggered()) | |||||
{ | |||||
if (substate == 0) | |||||
{ | |||||
// Remove fade-in | |||||
substate = 1; | |||||
application->fadeInTween->stop(); | |||||
application->blackoutImage->setTintColor(Vector4(0.0f)); | |||||
application->blackoutImage->setVisible(false); | |||||
application->titleFadeInTween->stop(); | |||||
application->titleImage->setVisible(true); | |||||
application->titleImage->setTintColor(Vector4(1.0f)); | |||||
application->anyKeyFadeInTween->start(); | |||||
application->anyKeyLabel->setVisible(true); | |||||
} | |||||
else if (substate == 1) | |||||
{ | |||||
substate = 2; | |||||
application->titleFadeInTween->stop(); | |||||
application->titleFadeOutTween->start(); | |||||
//application->copyrightFadeInTween->stop(); | |||||
//application->copyrightFadeOutTween->start(); | |||||
application->anyKeyFadeInTween->stop(); | |||||
application->anyKeyFadeOutTween->stop(); | |||||
application->anyKeyLabel->setVisible(false); | |||||
application->enterMenu(0); | |||||
application->menuSelectorLabel->setVisible(true); | |||||
//enterMenu(application, &mainMenu); | |||||
} | |||||
} | |||||
} | |||||
} | |||||
// Check state time | |||||
if (!fadeIn && stateTime >= blankDuration) | |||||
{ | |||||
// Begin fade-in | |||||
fadeIn = true; | |||||
} | |||||
// Update display model | |||||
Transform transform = application->displayModelInstance->getTransform(); | |||||
transform.translation = Vector3(0, 0.0f, 0); | |||||
transform.scale = Vector3(0.75f); | |||||
transform.rotation = glm::angleAxis(stateTime * glm::radians(360.0f) / 60.0f, glm::vec3(0, 1, 0)); | |||||
application->displayModelInstance->setTransform(transform); | |||||
transform.scale = Vector3(0.25f); | |||||
transform.translation.y = 0.0f; | |||||
//application->antModelInstance->setTransform(transform); | |||||
// Update menu controls | |||||
application->menuControlProfile->update(); | |||||
// Update input | |||||
application->inputManager->update(); | |||||
// Check if application was closed | |||||
if (application->inputManager->wasClosed() || application->escape.isTriggered()) | |||||
{ | |||||
application->close(EXIT_SUCCESS); | |||||
return; | |||||
} | |||||
// Check if fullscreen was toggled | |||||
if (application->toggleFullscreen.isTriggered() && !application->toggleFullscreen.wasTriggered()) | |||||
{ | |||||
application->changeFullscreen(); | |||||
} | |||||
// Navigate menu | |||||
if (application->menuDown.isTriggered() && !application->menuDown.wasTriggered()) | |||||
{ | |||||
if (application->selectedMenuItemIndex < application->currentMenu->getItemCount() - 1) | |||||
{ | |||||
application->selectMenuItem(application->selectedMenuItemIndex + 1); | |||||
} | |||||
else | |||||
{ | |||||
application->selectMenuItem(0); | |||||
} | |||||
} | |||||
else if (application->menuUp.isTriggered() && !application->menuUp.wasTriggered()) | |||||
{ | |||||
if (application->selectedMenuItemIndex > 0) | |||||
{ | |||||
application->selectMenuItem(application->selectedMenuItemIndex - 1); | |||||
} | |||||
else | |||||
{ | |||||
application->selectMenuItem(application->currentMenu->getItemCount() - 1); | |||||
} | |||||
} | |||||
if (application->menuSelect.isTriggered() && !application->menuSelect.wasTriggered()) | |||||
{ | |||||
application->activateMenuItem(application->selectedMenuItemIndex); | |||||
} | |||||
else if (application->menuCancel.isTriggered() && !application->menuCancel.wasTriggered()) | |||||
{ | |||||
} | |||||
float lineHeight = application->menuFont->getMetrics().getHeight(); | |||||
const UIContainer* container = application->menuContainers[application->currentMenuIndex]; | |||||
application->menuSelectorLabel->setTranslation( | |||||
Vector2(container->getPosition().x - application->menuSelectorLabel->getDimensions().x * 1.5f, | |||||
container->getPosition().y + lineHeight * 0.5f - application->menuSelectorLabel->getDimensions().y * 0.5f + lineHeight * application->selectedMenuItemIndex)); | |||||
// Perform tweening | |||||
application->tweener->update(dt); | |||||
// Update UI | |||||
application->uiRootElement->update(); | |||||
// Clear to black | |||||
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); | |||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); | |||||
// Render scene | |||||
application->renderer.render(application->scene); | |||||
// Form billboard batch for UI then render UI scene | |||||
application->uiBatcher->batch(application->uiBatch, application->uiRootElement); | |||||
application->renderer.render(application->uiScene); | |||||
// Swap buffers | |||||
SDL_GL_SwapWindow(application->window); | |||||
} | |||||
void TitleState::exit() | |||||
{ | |||||
std::cout << "Exiting TitleState..." << std::endl; | |||||
application->inputManager->removeWindowObserver(this); | |||||
application->exitMenu(application->currentMenuIndex); | |||||
application->menuSelectorLabel->setVisible(false); | |||||
application->scene.removeLayers(); | |||||
} | |||||
void TitleState::windowClosed() | |||||
{ | |||||
application->close(EXIT_SUCCESS); | |||||
} | |||||
void TitleState::windowResized(int width, int height) | |||||
{ | |||||
// Update application dimensions | |||||
application->width = width; | |||||
application->height = height; | |||||
if (application->fullscreen) | |||||
{ | |||||
application->fullscreenWidth = width; | |||||
application->fullscreenHeight = height; | |||||
} | |||||
else | |||||
{ | |||||
application->windowedWidth = width; | |||||
application->windowedHeight = height; | |||||
} | |||||
// Setup default render target | |||||
application->defaultRenderTarget.width = application->width; | |||||
application->defaultRenderTarget.height = application->height; | |||||
// Resize UI | |||||
application->resizeUI(); | |||||
// 3D camera | |||||
application->camera.setPerspective( | |||||
glm::radians(25.0f), | |||||
(float)application->width / (float)application->height, | |||||
0.1f, | |||||
1000.0f); | |||||
} |
@ -0,0 +1,52 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef TITLE_STATE_HPP | |||||
#define TITLE_STATE_HPP | |||||
#include "../application-state.hpp" | |||||
#include "../ui/ui.hpp" | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
/** | |||||
* Displays the title screen. | |||||
*/ | |||||
class TitleState: public ApplicationState, public WindowObserver | |||||
{ | |||||
public: | |||||
TitleState(Application* application); | |||||
virtual ~TitleState(); | |||||
virtual void enter(); | |||||
virtual void execute(); | |||||
virtual void exit(); | |||||
void windowClosed(); | |||||
void windowResized(int width, int height); | |||||
private: | |||||
float stateTime; | |||||
bool fadeIn; | |||||
bool fadeOut; | |||||
int substate; | |||||
}; | |||||
#endif // TITLE_STATE_HPP |
@ -0,0 +1,621 @@ | |||||
#include "terrain.hpp" | |||||
void Terrain::create(int columns, int rows, const Vector3& dimensions) | |||||
{ | |||||
this->columns = columns; | |||||
this->rows = rows; | |||||
this->dimensions = dimensions; | |||||
createSurface(); | |||||
createSubsurface(); | |||||
} | |||||
void Terrain::createSurface() | |||||
{ | |||||
std::size_t vertexCount = (columns + 1) * (rows + 1); | |||||
std::size_t triangleCount = columns * rows * 2; | |||||
std::size_t indexCount = triangleCount * 3; | |||||
surfaceVertices.resize(vertexCount); | |||||
surfaceIndices.resize(indexCount); | |||||
// Calculate scale and offset | |||||
Vector2 scale(dimensions.x / (float)columns, dimensions.z / (float)rows); | |||||
Vector2 offset(dimensions.x * -0.5f, dimensions.z * -0.5f); | |||||
// Calculate vertex positions | |||||
for (int i = 0; i <= rows; ++i) | |||||
{ | |||||
for (int j = 0; j <= columns; ++j) | |||||
{ | |||||
std::size_t index = i * (columns + 1) + j; | |||||
Vector3* vertex = &surfaceVertices[index]; | |||||
vertex->x = (float)j * scale.x + offset.x; | |||||
vertex->y = rand()%10; | |||||
vertex->z = (float)i * scale.y + offset.y; | |||||
} | |||||
} | |||||
// Generate indices | |||||
for (int i = 0; i < rows; ++i) | |||||
{ | |||||
for (int j = 0; j < columns; ++j) | |||||
{ | |||||
std::size_t a = i * (columns + 1) + j; | |||||
std::size_t b = (i + 1) * (columns + 1) + j; | |||||
std::size_t c = i * (columns + 1) + j + 1; | |||||
std::size_t d = (i + 1) * (columns + 1) + j + 1; | |||||
std::size_t index = (i * columns + j) * 2 * 3; | |||||
surfaceIndices[index] = a; | |||||
surfaceIndices[index + 1] = b; | |||||
surfaceIndices[index + 2] = c; | |||||
surfaceIndices[index + 3] = c; | |||||
surfaceIndices[index + 4] = b; | |||||
surfaceIndices[index + 5] = d; | |||||
} | |||||
} | |||||
// Create winged-edge mesh | |||||
surfaceMesh.create(surfaceVertices, surfaceIndices); | |||||
// Create model | |||||
surfaceModel.create(&surfaceMesh); | |||||
} | |||||
void Terrain::createSubsurface() | |||||
{ | |||||
std::size_t vertexCount = (columns + 1) * 4 + (rows + 1) * 4; | |||||
std::size_t triangleCount = columns * 4 + rows * 4 + 2; | |||||
std::size_t indexCount = triangleCount * 3; | |||||
subsurfaceVertices.resize(vertexCount); | |||||
subsurfaceIndices.resize(indexCount); | |||||
// Calculate floor position | |||||
float subsurfaceFloor = -dimensions.y; | |||||
// Calculate vertex positions | |||||
Vector3* vertex = &subsurfaceVertices[0]; | |||||
// Top row | |||||
for (int j = 0; j <= columns; ++j) | |||||
{ | |||||
int i = 0; | |||||
std::size_t surfaceIndex = i * (columns + 1) + j; | |||||
const Vector3& surfaceVertex = surfaceVertices[surfaceIndex]; | |||||
*(vertex++) = surfaceVertex; | |||||
*(vertex++) = Vector3(surfaceVertex.x, subsurfaceFloor, surfaceVertex.z); | |||||
} | |||||
// Bottom row | |||||
for (int j = 0; j <= columns; ++j) | |||||
{ | |||||
int i = rows; | |||||
std::size_t surfaceIndex = i * (columns + 1) + j; | |||||
const Vector3& surfaceVertex = surfaceVertices[surfaceIndex]; | |||||
*(vertex++) = surfaceVertex; | |||||
*(vertex++) = Vector3(surfaceVertex.x, subsurfaceFloor, surfaceVertex.z); | |||||
} | |||||
// Left column | |||||
for (int i = 0; i <= rows; ++i) | |||||
{ | |||||
int j = 0; | |||||
std::size_t surfaceIndex = i * (columns + 1) + j; | |||||
const Vector3& surfaceVertex = surfaceVertices[surfaceIndex]; | |||||
*(vertex++) = surfaceVertex; | |||||
*(vertex++) = Vector3(surfaceVertex.x, subsurfaceFloor, surfaceVertex.z); | |||||
} | |||||
// Right column | |||||
for (int i = 0; i <= rows; ++i) | |||||
{ | |||||
int j = columns; | |||||
std::size_t surfaceIndex = i * (columns + 1) + j; | |||||
const Vector3& surfaceVertex = surfaceVertices[surfaceIndex]; | |||||
*(vertex++) = surfaceVertex; | |||||
*(vertex++) = Vector3(surfaceVertex.x, subsurfaceFloor, surfaceVertex.z); | |||||
} | |||||
// Generate indices | |||||
std::size_t* index = &subsurfaceIndices[0]; | |||||
for (int i = 0; i < columns; ++i) | |||||
{ | |||||
std::size_t a = i * 2; | |||||
std::size_t b = i * 2 + 1; | |||||
std::size_t c = (i + 1) * 2; | |||||
std::size_t d = (i + 1) * 2 + 1; | |||||
(*(index++)) = b; | |||||
(*(index++)) = a; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = d; | |||||
a += (columns + 1) * 2; | |||||
b += (columns + 1) * 2; | |||||
c += (columns + 1) * 2; | |||||
d += (columns + 1) * 2; | |||||
(*(index++)) = a; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = d; | |||||
} | |||||
for (int i = 0; i < rows; ++i) | |||||
{ | |||||
std::size_t a = (columns + 1) * 4 + i * 2; | |||||
std::size_t b = (columns + 1) * 4 + i * 2 + 1; | |||||
std::size_t c = (columns + 1) * 4 + (i + 1) * 2; | |||||
std::size_t d = (columns + 1) * 4 + (i + 1) * 2 + 1; | |||||
(*(index++)) = a; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = d; | |||||
a += (rows + 1) * 2; | |||||
b += (rows + 1) * 2; | |||||
c += (rows + 1) * 2; | |||||
d += (rows + 1) * 2; | |||||
(*(index++)) = b; | |||||
(*(index++)) = a; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = d; | |||||
} | |||||
// Floor | |||||
std::size_t a = 1; | |||||
std::size_t b = 1 + (rows + 1) * 2; | |||||
std::size_t c = columns * 2 + 1; | |||||
std::size_t d = columns * 2 + 1 + (columns + 1) * 2; | |||||
(*(index++)) = a; | |||||
(*(index++)) = c; | |||||
(*(index++)) = b; | |||||
(*(index++)) = b; | |||||
(*(index++)) = c; | |||||
(*(index++)) = d; | |||||
// Create winged-edge mesh | |||||
subsurfaceMesh.create(subsurfaceVertices, subsurfaceIndices); | |||||
// Create model | |||||
subsurfaceModel.create(&subsurfaceMesh); | |||||
} | |||||
struct voxel | |||||
{ | |||||
glm::vec3 vertices[8]; | |||||
float values[8]; | |||||
}; | |||||
// LUT to map isosurface vertices to intersecting edges | |||||
static const int EDGE_TABLE[256] = | |||||
{ | |||||
0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, | |||||
0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, | |||||
0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, | |||||
0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, | |||||
0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, | |||||
0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, | |||||
0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, | |||||
0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, | |||||
0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, | |||||
0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, | |||||
0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, | |||||
0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, | |||||
0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, | |||||
0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, | |||||
0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, | |||||
0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, | |||||
0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, | |||||
0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, | |||||
0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, | |||||
0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, | |||||
0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, | |||||
0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, | |||||
0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, | |||||
0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460, | |||||
0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, | |||||
0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0, | |||||
0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, | |||||
0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230, | |||||
0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, | |||||
0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190, | |||||
0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, | |||||
0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 | |||||
}; | |||||
static const int TRIANGLE_TABLE[256][16] = | |||||
{ | |||||
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, | |||||
{8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, | |||||
{3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, | |||||
{4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, | |||||
{4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, | |||||
{9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, | |||||
{10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, | |||||
{5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, | |||||
{5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, | |||||
{8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, | |||||
{2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, | |||||
{7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, | |||||
{2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, | |||||
{11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, | |||||
{5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, | |||||
{11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, | |||||
{11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, | |||||
{2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, | |||||
{6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, | |||||
{3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, | |||||
{6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, | |||||
{6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, | |||||
{8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, | |||||
{7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, | |||||
{3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, | |||||
{0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, | |||||
{9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, | |||||
{8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, | |||||
{5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, | |||||
{0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, | |||||
{6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, | |||||
{10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, | |||||
{8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, | |||||
{1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, | |||||
{0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, | |||||
{3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, | |||||
{6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, | |||||
{9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, | |||||
{8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, | |||||
{3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, | |||||
{6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, | |||||
{10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, | |||||
{10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, | |||||
{2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, | |||||
{7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, | |||||
{7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, | |||||
{2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, | |||||
{1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, | |||||
{11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, | |||||
{8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, | |||||
{0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, | |||||
{7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, | |||||
{6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, | |||||
{7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, | |||||
{10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, | |||||
{0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, | |||||
{7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, | |||||
{6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, | |||||
{8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, | |||||
{6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, | |||||
{4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, | |||||
{10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, | |||||
{8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, | |||||
{1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, | |||||
{8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, | |||||
{10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, | |||||
{10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, | |||||
{11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, | |||||
{9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, | |||||
{6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, | |||||
{7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, | |||||
{3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, | |||||
{7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, | |||||
{3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, | |||||
{6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, | |||||
{9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, | |||||
{1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, | |||||
{4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, | |||||
{7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, | |||||
{6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, | |||||
{0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, | |||||
{6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, | |||||
{0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, | |||||
{11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, | |||||
{6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, | |||||
{5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, | |||||
{9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, | |||||
{1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, | |||||
{10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, | |||||
{0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, | |||||
{10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, | |||||
{11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, | |||||
{9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, | |||||
{7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, | |||||
{2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, | |||||
{8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, | |||||
{9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, | |||||
{9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, | |||||
{1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, | |||||
{5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, | |||||
{0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, | |||||
{10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, | |||||
{2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, | |||||
{0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, | |||||
{0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, | |||||
{9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, | |||||
{5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, | |||||
{5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, | |||||
{8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, | |||||
{9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, | |||||
{1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, | |||||
{3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, | |||||
{4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, | |||||
{9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, | |||||
{11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, | |||||
{11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, | |||||
{2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, | |||||
{9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, | |||||
{3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, | |||||
{1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, | |||||
{4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, | |||||
{0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, | |||||
{9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, | |||||
{1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, | |||||
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} | |||||
}; | |||||
// Lookup table which contains the indices of the vertices which define an edge. | |||||
static const int VERTEX_TABLE[12][2] = | |||||
{ | |||||
{0, 1}, | |||||
{1, 2}, | |||||
{2, 3}, | |||||
{3, 0}, | |||||
{4, 5}, | |||||
{5, 6}, | |||||
{6, 7}, | |||||
{7, 4}, | |||||
{0, 4}, | |||||
{1, 5}, | |||||
{2, 6}, | |||||
{3, 7} | |||||
}; | |||||
/* | |||||
* The marching cubes algorithm can produce a maximum of 5 triangles per cell. Therefore the maximum triangle count of a grid is `w * h * d * 5`. | |||||
*/ | |||||
struct triangle | |||||
{ | |||||
glm::vec3 vertices[3]; | |||||
}; | |||||
bool less_than(const glm::vec3& a, const glm::vec3& b) | |||||
{ | |||||
if (a.x < b.x) | |||||
return true; | |||||
else if (a.x > b.x) | |||||
return false; | |||||
if (a.y < b.y) | |||||
return true; | |||||
else if (a.y > b.y) | |||||
return false; | |||||
if (a.z < b.z) | |||||
return true; | |||||
return false; | |||||
} | |||||
glm::vec3 interpolate(float isolevel, glm::vec3 p0, glm::vec3 p1, float v0, float v1) | |||||
{ | |||||
static const float epsilon = 0.00001f; | |||||
if (less_than(p1, p0)) | |||||
{ | |||||
glm::vec3 ptemp = p0; | |||||
p0 = p1; | |||||
p1 = ptemp; | |||||
float vtemp = v0; | |||||
v0 = v1; | |||||
v1 = vtemp; | |||||
} | |||||
if (std::fabs(v0 - v1) > epsilon) | |||||
{ | |||||
return p0 + ((p1 - p0) / (v1 - v0) * (isolevel - v0)); | |||||
} | |||||
return p0; | |||||
} | |||||
int polygonize(const voxel& vox, float isolevel, triangle* triangles) | |||||
{ | |||||
// Set bitflags for each of the cube's 8 vertices, indicating whether or not they are inside the isosurface. | |||||
int edge_index = 0; | |||||
for (int i = 0; i < 8; ++i) | |||||
{ | |||||
if (vox.values[i] < isolevel) | |||||
edge_index |= (1 << i); | |||||
} | |||||
// Get edge flags from lookup table | |||||
int edge_flags = EDGE_TABLE[edge_index]; | |||||
if (edge_flags == 0) | |||||
{ | |||||
// No intersections, cube is completely in or out of the isosurface. | |||||
return 0; | |||||
} | |||||
// Calculate vertex positions | |||||
glm::vec3 vertices[12]; | |||||
// For each edge | |||||
for (int i = 0; i < 12; ++i) | |||||
{ | |||||
// If this edge is intersected | |||||
if (edge_flags & (1 << i)) | |||||
{ | |||||
int a = VERTEX_TABLE[i][0]; | |||||
int b = VERTEX_TABLE[i][1]; | |||||
vertices[i] = interpolate(isolevel, vox.vertices[a], vox.vertices[b], vox.values[a], vox.values[b]); | |||||
} | |||||
} | |||||
// Form triangles | |||||
int triangle_count = 0; | |||||
for (int i = 0; TRIANGLE_TABLE[edge_index][i] != -1; i += 3) | |||||
{ | |||||
int a = TRIANGLE_TABLE[edge_index][i]; | |||||
int b = TRIANGLE_TABLE[edge_index][i + 1]; | |||||
int c = TRIANGLE_TABLE[edge_index][i + 2]; | |||||
triangles[triangle_count].vertices[0] = vertices[a]; | |||||
triangles[triangle_count].vertices[1] = vertices[b]; | |||||
triangles[triangle_count].vertices[2] = vertices[c]; | |||||
++triangle_count; | |||||
} | |||||
return triangle_count; | |||||
} | |||||
@ -0,0 +1,88 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef TERRAIN_HPP | |||||
#define TERRAIN_HPP | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
class Terrain | |||||
{ | |||||
public: | |||||
/** | |||||
* Creates a flat terrain surface. | |||||
* | |||||
* @param columns Specifies the width of the terrain, in cells. | |||||
* @param rows Specifies the depth of the terrain, in cells. | |||||
* @param dimensions Specifies the dimensions of the terrain. | |||||
*/ | |||||
void create(int columns, int rows, const Vector3& dimensions); | |||||
/// Returns the winged-edge mesh representing the terrain surface. | |||||
const WingedEdge* getSurfaceMesh() const; | |||||
/// Returns the winged-edge mesh representing the terrain subsurface. | |||||
const WingedEdge* getSubsurfaceMesh() const; | |||||
/// Returns the model representing the terrain surface. | |||||
const Model* getSurfaceModel() const; | |||||
/// Returns the model representing the terrain subsurface. | |||||
const Model* getSubsurfaceModel() const; | |||||
private: | |||||
void createSurface(); | |||||
void createSubsurface(); | |||||
int columns; | |||||
int rows; | |||||
Vector3 dimensions; | |||||
std::vector<Vector3> surfaceVertices; | |||||
std::vector<Vector3> subsurfaceVertices; | |||||
std::vector<std::size_t> surfaceIndices; | |||||
std::vector<std::size_t> subsurfaceIndices; | |||||
WingedEdge surfaceMesh; | |||||
WingedEdge subsurfaceMesh; | |||||
Model surfaceModel; | |||||
Model subsurfaceModel; | |||||
}; | |||||
inline const WingedEdge* Terrain::getSurfaceMesh() const | |||||
{ | |||||
return &surfaceMesh; | |||||
}; | |||||
inline const WingedEdge* Terrain::getSubsurfaceMesh() const | |||||
{ | |||||
return &subsurfaceMesh; | |||||
}; | |||||
inline const Model* Terrain::getSurfaceModel() const | |||||
{ | |||||
return &surfaceModel; | |||||
} | |||||
inline const Model* Terrain::getSubsurfaceModel() const | |||||
{ | |||||
return &subsurfaceModel; | |||||
} | |||||
#endif // TERRAIN_HPP |
@ -0,0 +1,390 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "tween.hpp" | |||||
#include <cmath> | |||||
const TweenBase::EaseFunctionPointer TweenBase::easeFunctionPointers[] = | |||||
{ | |||||
&TweenBase::easeLinear, | |||||
&TweenBase::easeInSine, | |||||
&TweenBase::easeOutSine, | |||||
&TweenBase::easeInOutSine, | |||||
&TweenBase::easeInQuad, | |||||
&TweenBase::easeOutQuad, | |||||
&TweenBase::easeInOutQuad, | |||||
&TweenBase::easeInCubic, | |||||
&TweenBase::easeOutCubic, | |||||
&TweenBase::easeInOutCubic, | |||||
&TweenBase::easeInQuart, | |||||
&TweenBase::easeOutQuart, | |||||
&TweenBase::easeInOutQuart, | |||||
&TweenBase::easeInQuint, | |||||
&TweenBase::easeOutQuint, | |||||
&TweenBase::easeInOutQuint, | |||||
&TweenBase::easeInExpo, | |||||
&TweenBase::easeOutExpo, | |||||
&TweenBase::easeInOutExpo, | |||||
&TweenBase::easeInCirc, | |||||
&TweenBase::easeOutCirc, | |||||
&TweenBase::easeInOutCirc, | |||||
&TweenBase::easeInBack, | |||||
&TweenBase::easeOutBack, | |||||
&TweenBase::easeInOutBack, | |||||
&TweenBase::easeInBounce, | |||||
&TweenBase::easeOutBounce, | |||||
&TweenBase::easeInOutBounce, | |||||
}; | |||||
TweenBase::TweenBase(EaseFunction function, float time, float duration): | |||||
time(time), | |||||
duration(duration), | |||||
stopped(true), | |||||
oldStopped(true), | |||||
paused(false) | |||||
{ | |||||
setEaseFunction(function); | |||||
} | |||||
TweenBase::TweenBase(): | |||||
time(0.0f), | |||||
duration(0.0f), | |||||
stopped(true), | |||||
oldStopped(true), | |||||
paused(false) | |||||
{ | |||||
setEaseFunction(EaseFunction::LINEAR); | |||||
} | |||||
TweenBase::~TweenBase() | |||||
{} | |||||
void TweenBase::start() | |||||
{ | |||||
if (stopped) | |||||
{ | |||||
stopped = false; | |||||
oldStopped = true; | |||||
time = 0.0f; | |||||
} | |||||
else if (paused) | |||||
{ | |||||
paused = false; | |||||
} | |||||
} | |||||
void TweenBase::stop() | |||||
{ | |||||
if (!stopped) | |||||
{ | |||||
stopped = true; | |||||
oldStopped = false; | |||||
paused = false; | |||||
} | |||||
} | |||||
void TweenBase::pause() | |||||
{ | |||||
if (!stopped && !paused) | |||||
{ | |||||
paused = true; | |||||
oldStopped = false; | |||||
} | |||||
} | |||||
void TweenBase::reset() | |||||
{ | |||||
time = 0.0f; | |||||
} | |||||
inline void TweenBase::setEaseFunction(EaseFunction function) | |||||
{ | |||||
easeFunction = function; | |||||
easeFunctionPointer = easeFunctionPointers[static_cast<std::size_t>(easeFunction)]; | |||||
} | |||||
void TweenBase::setTime(float time) | |||||
{ | |||||
this->time = time; | |||||
} | |||||
void TweenBase::setDuration(float duration) | |||||
{ | |||||
this->duration = duration; | |||||
} | |||||
float TweenBase::easeLinear(float t, float b, float c, float d) | |||||
{ | |||||
return c * t / d + b; | |||||
} | |||||
float TweenBase::easeInSine(float t, float b, float c, float d) | |||||
{ | |||||
return -c * std::cos(t / d * glm::half_pi<float>()) + c + b; | |||||
} | |||||
float TweenBase::easeOutSine(float t, float b, float c, float d) | |||||
{ | |||||
return c * std::sin(t / d * glm::half_pi<float>()) + b; | |||||
} | |||||
float TweenBase::easeInOutSine(float t, float b, float c, float d) | |||||
{ | |||||
return -c * 0.5f * (std::cos(glm::pi<float>() * t / d) - 1.0f) + b; | |||||
} | |||||
float TweenBase::easeInQuad(float t, float b, float c, float d) | |||||
{ | |||||
t /= d; | |||||
return c * t * t + b; | |||||
} | |||||
float TweenBase::easeOutQuad(float t, float b, float c, float d) | |||||
{ | |||||
t /= d; | |||||
return -c * t * (t - 2.0f) + b; | |||||
} | |||||
float TweenBase::easeInOutQuad(float t, float b, float c, float d) | |||||
{ | |||||
t /= d; | |||||
if ((t * 0.5f) < 1.0f) | |||||
{ | |||||
return c * 0.5f * t * t + b; | |||||
} | |||||
t -= 1.0f; | |||||
return -c * 0.5f * (t * (t - 2.0f) - 1.0f) + b; | |||||
} | |||||
float TweenBase::easeInCubic(float t, float b, float c, float d) | |||||
{ | |||||
t /= d; | |||||
return c * t * t * t + b; | |||||
} | |||||
float TweenBase::easeOutCubic(float t, float b, float c, float d) | |||||
{ | |||||
t = t / d - 1.0f; | |||||
return c * (t * t * t + 1.0f) + b; | |||||
} | |||||
float TweenBase::easeInOutCubic(float t, float b, float c, float d) | |||||
{ | |||||
t /= d * 0.5f; | |||||
if (t < 1.0f) | |||||
{ | |||||
return c * 0.5f * t * t * t + b; | |||||
} | |||||
t -= 2.0f; | |||||
return c * 0.5f * (t * t * t + 2.0f) + b; | |||||
} | |||||
float TweenBase::easeInQuart(float t, float b, float c, float d) | |||||
{ | |||||
t /= d; | |||||
return c * t * t * t * t + b; | |||||
} | |||||
float TweenBase::easeOutQuart(float t, float b, float c, float d) | |||||
{ | |||||
t = t / d - 1.0f; | |||||
return -c * (t * t * t * t - 1.0f) + b; | |||||
} | |||||
float TweenBase::easeInOutQuart(float t, float b, float c, float d) | |||||
{ | |||||
t /= d * 0.5f; | |||||
if (t < 1.0f) | |||||
{ | |||||
return c * 0.5f * t * t * t * t + b; | |||||
} | |||||
t -= 2.0f; | |||||
return -c * 0.5f * (t * t * t * t - 2.0f) + b; | |||||
} | |||||
float TweenBase::easeInQuint(float t, float b, float c, float d) | |||||
{ | |||||
t /= d; | |||||
return c * t * t * t * t * t + b; | |||||
} | |||||
float TweenBase::easeOutQuint(float t, float b, float c, float d) | |||||
{ | |||||
t = t / d - 1.0f; | |||||
return c * (t * t * t * t * t + 1.0f) + b; | |||||
} | |||||
float TweenBase::easeInOutQuint(float t, float b, float c, float d) | |||||
{ | |||||
t /= d * 0.5f; | |||||
if (t < 1.0f) | |||||
{ | |||||
return c * 0.5f * t * t * t * t * t + b; | |||||
} | |||||
t -= 2.0f; | |||||
return c * 0.5f * (t * t * t * t * t + 2.0f) + b; | |||||
} | |||||
float TweenBase::easeInExpo(float t, float b, float c, float d) | |||||
{ | |||||
return (t == 0.0f) ? b : c * std::pow(2.0f, 10.0f * (t / d - 1.0f)) + b - c * 0.001f; | |||||
} | |||||
float TweenBase::easeOutExpo(float t, float b, float c, float d) | |||||
{ | |||||
return (t == d) ? b + c : c * 1.001f * (-std::pow(2.0f, -10.0f * t / d) + 1.0f) + b; | |||||
} | |||||
float TweenBase::easeInOutExpo(float t, float b, float c, float d) | |||||
{ | |||||
if (t == 0.0f) | |||||
{ | |||||
return b; | |||||
} | |||||
if (t == d) | |||||
{ | |||||
return b + c; | |||||
} | |||||
t /= d * 0.5f; | |||||
if (t < 1.0f) | |||||
{ | |||||
return c * 0.5f * std::pow(2.0f, 10.0f * (t - 1.0f)) + b - c * 0.0005f; | |||||
} | |||||
t -= 1.0f; | |||||
return c * 0.5f * 1.0005f * (-std::pow(2.0f, -10.0f * t) + 2.0f) + b; | |||||
} | |||||
float TweenBase::easeInCirc(float t, float b, float c, float d) | |||||
{ | |||||
t /= d; | |||||
return -c * (std::sqrt(1.0f - t * t) - 1.0f) + b; | |||||
} | |||||
float TweenBase::easeOutCirc(float t, float b, float c, float d) | |||||
{ | |||||
t = t / d - 1.0f; | |||||
return c * std::sqrt(1.0f - t * t) + b; | |||||
} | |||||
float TweenBase::easeInOutCirc(float t, float b, float c, float d) | |||||
{ | |||||
t /= d * 0.5f; | |||||
if (t < 1.0f) | |||||
{ | |||||
return -c * 0.5f * (std::sqrt(1.0f - t * t) - 1.0f) + b; | |||||
} | |||||
t -= 2.0f; | |||||
return c * 0.5f * (std::sqrt(1.0f - t * t) + 1.0f) + b; | |||||
} | |||||
float TweenBase::easeInBack(float t, float b, float c, float d) | |||||
{ | |||||
float s = 1.70158f; | |||||
t /= d; | |||||
return c * t * t * ((s + 1.0f) * t - s) + b; | |||||
} | |||||
float TweenBase::easeOutBack(float t, float b, float c, float d) | |||||
{ | |||||
float s = 1.70158f; | |||||
t = t / d - 1.0f; | |||||
return c * (t * t * ((s + 1.0f) * t + s) + 1.0f) + b; | |||||
} | |||||
float TweenBase::easeInOutBack(float t, float b, float c, float d) | |||||
{ | |||||
float s = 1.70158f; | |||||
t /= d * 0.5f; | |||||
if (t < 1.0f) | |||||
{ | |||||
s *= 1.525f; | |||||
return c * 0.5f * (t * t * ((s + 1.0f) * t - s)) + b; | |||||
} | |||||
t -= 2.0f; | |||||
s *= 1.525f; | |||||
return c * 0.5f * (t * t * ((s + 1.0f) * t + s) + 2.0f) + b; | |||||
} | |||||
float TweenBase::easeInBounce(float t, float b, float c, float d) | |||||
{ | |||||
return c - easeOutBounce(d - t, 0.0f, c, d) + b; | |||||
} | |||||
float TweenBase::easeOutBounce(float t, float b, float c, float d) | |||||
{ | |||||
t /= d; | |||||
if (t < (1.0f / 2.75f)) | |||||
{ | |||||
return c * (7.5625f * t * t) + b; | |||||
} | |||||
else if (t < (2.0f / 2.75f)) | |||||
{ | |||||
t -= (1.5f / 2.75f); | |||||
return c * (7.5625f * t * t + 0.75f) + b; | |||||
} | |||||
else if (t < (2.5f / 2.75f)) | |||||
{ | |||||
t -= (2.25f / 2.75f); | |||||
return c * (7.5625f * t * t + 0.9375f) + b; | |||||
} | |||||
t -= (2.625f / 2.75f); | |||||
return c * (7.5625f * t * t + 0.984375f) + b; | |||||
} | |||||
float TweenBase::easeInOutBounce(float t, float b, float c, float d) | |||||
{ | |||||
if (t < d * 0.5f) | |||||
{ | |||||
return easeInBounce(t * 2.0f, 0.0f, c, d) * 0.5f + b; | |||||
} | |||||
return easeOutBounce(t * 2.0f - d, 0.0f, c, d) * 0.5f + c * 0.5f + b; | |||||
} | |||||
void Tweener::update(float dt) | |||||
{ | |||||
for (TweenBase* tween: tweens) | |||||
{ | |||||
tween->update(dt); | |||||
} | |||||
} | |||||
void Tweener::addTween(TweenBase* tween) | |||||
{ | |||||
tweens.push_back(tween); | |||||
} | |||||
void Tweener::removeTween(TweenBase* tween) | |||||
{ | |||||
tweens.remove(tween); | |||||
} | |||||
void Tweener::removeTweens() | |||||
{ | |||||
tweens.clear(); | |||||
} |
@ -0,0 +1,378 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef TWEEN_HPP | |||||
#define TWEEN_HPP | |||||
#include <functional> | |||||
#include <list> | |||||
#include <iostream> | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
/// @see http://easings.net/ | |||||
/// @see http://wiki.unity3d.com/index.php?title=Tween | |||||
enum class EaseFunction | |||||
{ | |||||
LINEAR, | |||||
IN_SINE, | |||||
OUT_SINE, | |||||
IN_OUT_SINE, | |||||
IN_QUAD, | |||||
OUT_QUAD, | |||||
IN_OUT_QUAD, | |||||
IN_CUBIC, | |||||
OUT_CUBIC, | |||||
IN_OUT_CUBIC, | |||||
IN_QUART, | |||||
OUT_QUART, | |||||
IN_OUT_QUART, | |||||
IN_QUINT, | |||||
OUT_QUINT, | |||||
IN_OUT_QUINT, | |||||
IN_EXPO, | |||||
OUT_EXPO, | |||||
IN_OUT_EXPO, | |||||
IN_CIRC, | |||||
OUT_CIRC, | |||||
IN_OUT_CIRC, | |||||
IN_BACK, | |||||
OUT_BACK, | |||||
IN_OUT_BACK, | |||||
IN_BOUNCE, | |||||
OUT_BOUNCE, | |||||
IN_OUT_BOUNCE | |||||
}; | |||||
class TweenBase | |||||
{ | |||||
public: | |||||
TweenBase(EaseFunction function, float time, float duration); | |||||
TweenBase(); | |||||
virtual ~TweenBase(); | |||||
void start(); | |||||
void stop(); | |||||
void pause(); | |||||
void reset(); | |||||
void setEaseFunction(EaseFunction function); | |||||
void setTime(float time); | |||||
void setDuration(float duration); | |||||
EaseFunction getEaseFunction() const; | |||||
float getTime() const; | |||||
float getDuration() const; | |||||
bool isStopped() const; | |||||
bool wasStopped() const; | |||||
bool isPaused() const; | |||||
protected: | |||||
typedef float (*EaseFunctionPointer)(float, float, float, float); | |||||
EaseFunction easeFunction; | |||||
EaseFunctionPointer easeFunctionPointer; | |||||
float time; | |||||
float duration; | |||||
bool stopped; | |||||
bool oldStopped; | |||||
bool paused; | |||||
private: | |||||
friend class Tweener; | |||||
static const EaseFunctionPointer easeFunctionPointers[28]; | |||||
virtual void update(float dt) = 0; | |||||
static float easeLinear(float t, float b, float c, float d); | |||||
static float easeInSine(float t, float b, float c, float d); | |||||
static float easeOutSine(float t, float b, float c, float d); | |||||
static float easeInOutSine(float t, float b, float c, float d); | |||||
static float easeInQuad(float t, float b, float c, float d); | |||||
static float easeOutQuad(float t, float b, float c, float d); | |||||
static float easeInOutQuad(float t, float b, float c, float d); | |||||
static float easeInCubic(float t, float b, float c, float d); | |||||
static float easeOutCubic(float t, float b, float c, float d); | |||||
static float easeInOutCubic(float t, float b, float c, float d); | |||||
static float easeInQuart(float t, float b, float c, float d); | |||||
static float easeOutQuart(float t, float b, float c, float d); | |||||
static float easeInOutQuart(float t, float b, float c, float d); | |||||
static float easeInQuint(float t, float b, float c, float d); | |||||
static float easeOutQuint(float t, float b, float c, float d); | |||||
static float easeInOutQuint(float t, float b, float c, float d); | |||||
static float easeInExpo(float t, float b, float c, float d); | |||||
static float easeOutExpo(float t, float b, float c, float d); | |||||
static float easeInOutExpo(float t, float b, float c, float d); | |||||
static float easeInCirc(float t, float b, float c, float d); | |||||
static float easeOutCirc(float t, float b, float c, float d); | |||||
static float easeInOutCirc(float t, float b, float c, float d); | |||||
static float easeInBack(float t, float b, float c, float d); | |||||
static float easeOutBack(float t, float b, float c, float d); | |||||
static float easeInOutBack(float t, float b, float c, float d); | |||||
static float easeInBounce(float t, float b, float c, float d); | |||||
static float easeOutBounce(float t, float b, float c, float d); | |||||
static float easeInOutBounce(float t, float b, float c, float d); | |||||
}; | |||||
inline EaseFunction TweenBase::getEaseFunction() const | |||||
{ | |||||
return easeFunction; | |||||
} | |||||
inline float TweenBase::getTime() const | |||||
{ | |||||
return time; | |||||
} | |||||
inline float TweenBase::getDuration() const | |||||
{ | |||||
return duration; | |||||
} | |||||
inline bool TweenBase::isStopped() const | |||||
{ | |||||
return stopped; | |||||
} | |||||
inline bool TweenBase::wasStopped() const | |||||
{ | |||||
return oldStopped; | |||||
} | |||||
inline bool TweenBase::isPaused() const | |||||
{ | |||||
return paused; | |||||
} | |||||
template <typename T> | |||||
class Tween: public TweenBase | |||||
{ | |||||
public: | |||||
Tween(EaseFunction function, float time, float duration, const T& startValue, const T& deltaValue); | |||||
Tween(); | |||||
virtual ~Tween(); | |||||
void setStartValue(const T& startValue); | |||||
void setDeltaValue(const T& deltaValue); | |||||
void setStartCallback(std::function<void(const T&)> callback); | |||||
void setUpdateCallback(std::function<void(const T&)> callback); | |||||
void setEndCallback(std::function<void(const T&)> callback); | |||||
const T& getStartValue() const; | |||||
const T& getDeltaValue() const; | |||||
const T& getTweenValue() const; | |||||
std::function<void(const T&)> getStartCallback() const; | |||||
std::function<void(const T&)> getUpdateCallback() const; | |||||
std::function<void(const T&)> getEndCallback() const; | |||||
private: | |||||
virtual void update(float dt); | |||||
void calculateTweenValue(); | |||||
T startValue; | |||||
T deltaValue; | |||||
T tweenValue; | |||||
std::function<void(const T&)> startCallback; | |||||
std::function<void(const T&)> updateCallback; | |||||
std::function<void(const T&)> endCallback; | |||||
}; | |||||
template <typename T> | |||||
Tween<T>::Tween(EaseFunction function, float time, float duration, const T& startValue, const T& deltaValue): | |||||
TweenBase(function, time, duration), | |||||
startValue(startValue), | |||||
deltaValue(deltaValue), | |||||
tweenValue(startValue), | |||||
startCallback(nullptr), | |||||
updateCallback(nullptr), | |||||
endCallback(nullptr) | |||||
{} | |||||
template <typename T> | |||||
Tween<T>::Tween(): | |||||
startCallback(nullptr), | |||||
updateCallback(nullptr), | |||||
endCallback(nullptr) | |||||
{} | |||||
template <typename T> | |||||
Tween<T>::~Tween() | |||||
{} | |||||
template <typename T> | |||||
void Tween<T>::update(float dt) | |||||
{ | |||||
if (isStopped() || isPaused()) | |||||
{ | |||||
return; | |||||
} | |||||
// Check if tween was just started | |||||
if (!isStopped() && wasStopped()) | |||||
{ | |||||
// Execute start callback | |||||
if (startCallback != nullptr) | |||||
{ | |||||
startCallback(startValue); | |||||
} | |||||
} | |||||
oldStopped = stopped; | |||||
// Add delta time to time and calculate tween value | |||||
time = std::min(duration, time + dt); | |||||
calculateTweenValue(); | |||||
// Execute update callback | |||||
if (updateCallback != nullptr) | |||||
{ | |||||
updateCallback(tweenValue); | |||||
} | |||||
// Check if tween has ended | |||||
if (time >= duration) | |||||
{ | |||||
if (!isStopped()) | |||||
{ | |||||
// Stop tween | |||||
stop(); | |||||
// Execute end callback | |||||
if (endCallback != nullptr) | |||||
{ | |||||
endCallback(tweenValue); | |||||
} | |||||
} | |||||
} | |||||
} | |||||
template <typename T> | |||||
inline void Tween<T>::setStartValue(const T& startValue) | |||||
{ | |||||
this->startValue = startValue; | |||||
} | |||||
template <typename T> | |||||
inline void Tween<T>::setDeltaValue(const T& deltaValue) | |||||
{ | |||||
this->deltaValue = deltaValue; | |||||
} | |||||
template <typename T> | |||||
inline void Tween<T>::setStartCallback(std::function<void(const T&)> callback) | |||||
{ | |||||
this->startCallback = callback; | |||||
} | |||||
template <typename T> | |||||
inline void Tween<T>::setUpdateCallback(std::function<void(const T&)> callback) | |||||
{ | |||||
this->updateCallback = callback; | |||||
} | |||||
template <typename T> | |||||
inline void Tween<T>::setEndCallback(std::function<void(const T&)> callback) | |||||
{ | |||||
this->endCallback = callback; | |||||
} | |||||
template <typename T> | |||||
inline const T& Tween<T>::getStartValue() const | |||||
{ | |||||
return startValue; | |||||
} | |||||
template <typename T> | |||||
inline const T& Tween<T>::getDeltaValue() const | |||||
{ | |||||
return deltaValue; | |||||
} | |||||
template <typename T> | |||||
inline const T& Tween<T>::getTweenValue() const | |||||
{ | |||||
return tweenValue; | |||||
} | |||||
template <typename T> | |||||
inline std::function<void(const T&)> Tween<T>::getStartCallback() const | |||||
{ | |||||
return startCallback; | |||||
} | |||||
template <typename T> | |||||
inline std::function<void(const T&)> Tween<T>::getUpdateCallback() const | |||||
{ | |||||
return updateCallback; | |||||
} | |||||
template <typename T> | |||||
inline std::function<void(const T&)> Tween<T>::getEndCallback() const | |||||
{ | |||||
return endCallback; | |||||
} | |||||
template <typename T> | |||||
inline void Tween<T>::calculateTweenValue() | |||||
{ | |||||
tweenValue = easeFunctionPointer(time, startValue, deltaValue, duration); | |||||
} | |||||
template <> | |||||
inline void Tween<Vector2>::calculateTweenValue() | |||||
{ | |||||
tweenValue.x = easeFunctionPointer(time, startValue.x, deltaValue.x, duration); | |||||
tweenValue.y = easeFunctionPointer(time, startValue.y, deltaValue.y, duration); | |||||
} | |||||
template <> | |||||
inline void Tween<Vector3>::calculateTweenValue() | |||||
{ | |||||
tweenValue.x = easeFunctionPointer(time, startValue.x, deltaValue.x, duration); | |||||
tweenValue.y = easeFunctionPointer(time, startValue.y, deltaValue.y, duration); | |||||
tweenValue.z = easeFunctionPointer(time, startValue.z, deltaValue.z, duration); | |||||
} | |||||
template <> | |||||
inline void Tween<Vector4>::calculateTweenValue() | |||||
{ | |||||
tweenValue.x = easeFunctionPointer(time, startValue.x, deltaValue.x, duration); | |||||
tweenValue.y = easeFunctionPointer(time, startValue.y, deltaValue.y, duration); | |||||
tweenValue.z = easeFunctionPointer(time, startValue.z, deltaValue.z, duration); | |||||
tweenValue.w = easeFunctionPointer(time, startValue.w, deltaValue.w, duration); | |||||
} | |||||
class Tweener | |||||
{ | |||||
public: | |||||
void update(float dt); | |||||
void addTween(TweenBase* tween); | |||||
void removeTween(TweenBase* tween); | |||||
void removeTweens(); | |||||
private: | |||||
std::list<TweenBase*> tweens; | |||||
}; | |||||
#endif // TWEEN_HPP |
@ -0,0 +1,500 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#include "ui.hpp" | |||||
#include "../application.hpp" | |||||
// UI callbacks | |||||
void menuPrint(Application* application, const std::string& string) | |||||
{ | |||||
std::cout << string << std::endl; | |||||
} | |||||
UIElement::UIElement(): | |||||
parent(nullptr), | |||||
anchor(Anchor::TOP_LEFT), | |||||
layerOffset(0), | |||||
layer(0), | |||||
origin(0.0f), | |||||
translation(0.0f), | |||||
dimensions(0.0f), | |||||
position(0.0f), | |||||
bounds(position, position), | |||||
tintColor(1.0f), | |||||
color(tintColor), | |||||
visible(true), | |||||
active(true), | |||||
mouseOver(false), | |||||
mouseOverCallback(nullptr), | |||||
mouseOutCallback(nullptr), | |||||
mouseMovedCallback(nullptr), | |||||
mousePressedCallback(nullptr), | |||||
mouseReleasedCallback(nullptr) | |||||
{} | |||||
UIElement::~UIElement() | |||||
{} | |||||
void UIElement::update() | |||||
{ | |||||
// Calculate position | |||||
if (parent != nullptr) | |||||
{ | |||||
// Calculate world-space position | |||||
Vector2 anchorPoint = parent->position + parent->dimensions * anchor - dimensions * anchor; | |||||
position = anchorPoint + origin + translation; | |||||
// Calculate layer | |||||
layer = parent->layer + 1 + layerOffset; | |||||
// Calculate color | |||||
color = parent->color * tintColor; | |||||
} | |||||
else | |||||
{ | |||||
position = origin + translation; | |||||
layer = layerOffset; | |||||
color = tintColor; | |||||
} | |||||
// Calculate bounds | |||||
bounds.setMin(position); | |||||
bounds.setMax(position + dimensions); | |||||
// Update children | |||||
for (UIElement* child: children) | |||||
{ | |||||
child->update(); | |||||
} | |||||
} | |||||
void UIElement::addChild(UIElement* element) | |||||
{ | |||||
children.push_back(element); | |||||
element->parent = this; | |||||
} | |||||
void UIElement::removeChild(UIElement* element) | |||||
{ | |||||
for (auto it = children.begin(); it != children.end(); ++it) | |||||
{ | |||||
if (*it == element) | |||||
{ | |||||
children.erase(it); | |||||
return; | |||||
} | |||||
} | |||||
} | |||||
void UIElement::setMouseOverCallback(std::function<void()> callback) | |||||
{ | |||||
mouseOverCallback = callback; | |||||
} | |||||
void UIElement::setMouseOutCallback(std::function<void()> callback) | |||||
{ | |||||
mouseOutCallback = callback; | |||||
} | |||||
void UIElement::setMouseMovedCallback(std::function<void()> callback) | |||||
{ | |||||
mouseMovedCallback = callback; | |||||
} | |||||
void UIElement::setMousePressedCallback(std::function<void(int)> callback) | |||||
{ | |||||
mousePressedCallback = callback; | |||||
} | |||||
void UIElement::setMouseReleasedCallback(std::function<void(int)> callback) | |||||
{ | |||||
mouseReleasedCallback = callback; | |||||
} | |||||
void UIElement::mouseMoved(int x, int y) | |||||
{ | |||||
if (!active) | |||||
{ | |||||
return; | |||||
} | |||||
if (bounds.contains(Vector2(x, y))) | |||||
{ | |||||
if (!mouseOver) | |||||
{ | |||||
mouseOver = true; | |||||
if (mouseOverCallback) | |||||
{ | |||||
mouseOverCallback(); | |||||
} | |||||
} | |||||
if (mouseMovedCallback) | |||||
{ | |||||
mouseMovedCallback(); | |||||
} | |||||
} | |||||
else if (mouseOver) | |||||
{ | |||||
mouseOver = false; | |||||
if (mouseOutCallback) | |||||
{ | |||||
mouseOutCallback(); | |||||
} | |||||
} | |||||
for (UIElement* child: children) | |||||
{ | |||||
child->mouseMoved(x, y); | |||||
} | |||||
} | |||||
void UIElement::mouseButtonPressed(int button, int x, int y) | |||||
{ | |||||
if (!active) | |||||
{ | |||||
return; | |||||
} | |||||
if (bounds.contains(Vector2(x, y))) | |||||
{ | |||||
if (mousePressedCallback) | |||||
{ | |||||
mousePressedCallback(button); | |||||
} | |||||
for (UIElement* child: children) | |||||
{ | |||||
child->mouseButtonPressed(button, x, y); | |||||
} | |||||
} | |||||
} | |||||
void UIElement::mouseButtonReleased(int button, int x, int y) | |||||
{ | |||||
if (!active) | |||||
{ | |||||
return; | |||||
} | |||||
if (bounds.contains(Vector2(x, y))) | |||||
{ | |||||
if (mouseReleasedCallback) | |||||
{ | |||||
mouseReleasedCallback(button); | |||||
} | |||||
for (UIElement* child: children) | |||||
{ | |||||
child->mouseButtonReleased(button, x, y); | |||||
} | |||||
} | |||||
} | |||||
UILabel::UILabel(): | |||||
font(nullptr) | |||||
{} | |||||
UILabel::~UILabel() | |||||
{} | |||||
void UILabel::setFont(Font* font) | |||||
{ | |||||
this->font = font; | |||||
material.texture = font->getTexture(); | |||||
calculateDimensions(); | |||||
} | |||||
void UILabel::setText(const std::string& text) | |||||
{ | |||||
this->text = text; | |||||
calculateDimensions(); | |||||
} | |||||
void UILabel::calculateDimensions() | |||||
{ | |||||
if (font != nullptr && !text.empty()) | |||||
{ | |||||
float width = font->getWidth(text.c_str()); | |||||
float height = font->getMetrics().getHeight(); | |||||
setDimensions(Vector2(width, height)); | |||||
} | |||||
else | |||||
{ | |||||
setDimensions(Vector2(0.0f)); | |||||
} | |||||
} | |||||
UIImage::UIImage(): | |||||
textureBounds(Vector2(0.0f), Vector2(1.0f)) | |||||
{} | |||||
UIImage::~UIImage() | |||||
{} | |||||
void UIBatcher::batch(BillboardBatch* result, const UIElement* ui) | |||||
{ | |||||
// Create list of visible UI elements | |||||
std::list<const UIElement*> elements; | |||||
queueElements(&elements, ui); | |||||
// Sort UI elements according to layer and texture | |||||
elements.sort([](const UIElement* a, const UIElement* b) | |||||
{ | |||||
if (a->getLayer() < b->getLayer()) | |||||
{ | |||||
return true; | |||||
} | |||||
else if (b->getLayer() < a->getLayer()) | |||||
{ | |||||
return false; | |||||
} | |||||
return (a->getMaterial()->texture < b->getMaterial()->texture); | |||||
}); | |||||
// Clear previous ranges | |||||
result->removeRanges(); | |||||
// Batch UI elements | |||||
for (const UIElement* element: elements) | |||||
{ | |||||
batchElement(result, element); | |||||
} | |||||
// Update batch | |||||
result->update(); | |||||
} | |||||
void UIBatcher::queueElements(std::list<const UIElement*>* elements, const UIElement* element) const | |||||
{ | |||||
if (element->isVisible()) | |||||
{ | |||||
elements->push_back(element); | |||||
for (std::size_t i = 0; i < element->getChildCount(); ++i) | |||||
{ | |||||
queueElements(elements, element->getChild(i)); | |||||
} | |||||
} | |||||
} | |||||
BillboardBatch::Range* UIBatcher::getRange(BillboardBatch* result, const UIElement* element) const | |||||
{ | |||||
BillboardBatch::Range* range = nullptr; | |||||
if (!result->getRangeCount()) | |||||
{ | |||||
// Create initial range | |||||
range = result->addRange(); | |||||
range->material = (Material*)element->getMaterial(); | |||||
range->start = 0; | |||||
range->length = 0; | |||||
} | |||||
else | |||||
{ | |||||
range = result->getRange(result->getRangeCount() - 1); | |||||
const UIMaterial* material = static_cast<UIMaterial*>(range->material); | |||||
if (material->texture != element->getMaterial()->texture) | |||||
{ | |||||
// Create new range for the element | |||||
BillboardBatch::Range* precedingRange = range; | |||||
range = result->addRange(); | |||||
range->material = (Material*)element->getMaterial(); | |||||
range->start = precedingRange->start + precedingRange->length; | |||||
range->length = 0; | |||||
} | |||||
} | |||||
return range; | |||||
} | |||||
void UIBatcher::batchElement(BillboardBatch* result, const UIElement* element) | |||||
{ | |||||
switch (element->getElementType()) | |||||
{ | |||||
case UIElement::Type::LABEL: | |||||
batchLabel(result, static_cast<const UILabel*>(element)); | |||||
break; | |||||
case UIElement::Type::IMAGE: | |||||
batchImage(result, static_cast<const UIImage*>(element)); | |||||
break; | |||||
case UIElement::Type::CONTAINER: | |||||
break; | |||||
default: | |||||
break; | |||||
} | |||||
} | |||||
void UIBatcher::batchLabel(BillboardBatch* result, const UILabel* label) | |||||
{ | |||||
if (label->getFont() != nullptr && !label->getText().empty()) | |||||
{ | |||||
// Get range | |||||
BillboardBatch::Range* range = getRange(result, label); | |||||
// Pixel-perfect | |||||
Vector3 origin = Vector3((int)label->getPosition().x, (int)label->getPosition().y, label->getLayer() * 0.01f); | |||||
// Print billboards | |||||
const Font* font = label->getFont(); | |||||
std::size_t index = range->start + range->length; | |||||
std::size_t count = 0; | |||||
font->puts(result, origin, label->getText().c_str(), label->getColor(), index, &count); | |||||
// Increment range length | |||||
range->length += count; | |||||
} | |||||
} | |||||
void UIBatcher::batchImage(BillboardBatch* result, const UIImage* image) | |||||
{ | |||||
// Get range | |||||
BillboardBatch::Range* range = getRange(result, image); | |||||
// Create billboard | |||||
std::size_t index = range->start + range->length; | |||||
Billboard* billboard = result->getBillboard(index); | |||||
billboard->setDimensions(image->getDimensions()); | |||||
billboard->setTranslation(Vector3(image->getPosition() + image->getDimensions() * 0.5f, image->getLayer() * 0.01f)); | |||||
billboard->setTextureCoordinates(image->getTextureBounds().getMin(), image->getTextureBounds().getMax()); | |||||
billboard->setTintColor(image->getColor()); | |||||
// Increment range length | |||||
++(range->length); | |||||
} | |||||
MenuItem::MenuItem(Menu* parent, std::size_t index): | |||||
parent(parent), | |||||
index(index), | |||||
selected(false), | |||||
selectedCallback(nullptr), | |||||
deselectedCallback(nullptr), | |||||
activatedCallback(nullptr) | |||||
{} | |||||
void MenuItem::select() | |||||
{ | |||||
if (!selected) | |||||
{ | |||||
selected = true; | |||||
if (selectedCallback != nullptr) | |||||
{ | |||||
selectedCallback(); | |||||
} | |||||
} | |||||
} | |||||
void MenuItem::deselect() | |||||
{ | |||||
if (selected) | |||||
{ | |||||
selected = false; | |||||
if (deselectedCallback != nullptr) | |||||
{ | |||||
deselectedCallback(); | |||||
} | |||||
} | |||||
} | |||||
void MenuItem::activate() | |||||
{ | |||||
if (activatedCallback != nullptr) | |||||
{ | |||||
activatedCallback(); | |||||
} | |||||
} | |||||
void MenuItem::setSelectedCallback(std::function<void()> callback) | |||||
{ | |||||
this->selectedCallback = callback = callback; | |||||
} | |||||
void MenuItem::setDeselectedCallback(std::function<void()> callback) | |||||
{ | |||||
this->deselectedCallback = callback; | |||||
} | |||||
void MenuItem::setActivatedCallback(std::function<void()> callback) | |||||
{ | |||||
this->activatedCallback = callback; | |||||
} | |||||
Menu::Menu(): | |||||
enteredCallback(nullptr), | |||||
exitedCallback(nullptr) | |||||
{} | |||||
Menu::~Menu() | |||||
{ | |||||
for (MenuItem* item: items) | |||||
{ | |||||
delete item; | |||||
} | |||||
} | |||||
void Menu::enter() | |||||
{ | |||||
if (enteredCallback != nullptr) | |||||
{ | |||||
enteredCallback(); | |||||
} | |||||
} | |||||
void Menu::exit() | |||||
{ | |||||
if (exitedCallback != nullptr) | |||||
{ | |||||
exitedCallback(); | |||||
} | |||||
} | |||||
MenuItem* Menu::addItem() | |||||
{ | |||||
MenuItem* item = new MenuItem(this, items.size()); | |||||
items.push_back(item); | |||||
return item; | |||||
} | |||||
void Menu::removeItems() | |||||
{ | |||||
for (MenuItem* item: items) | |||||
{ | |||||
delete item; | |||||
} | |||||
items.clear(); | |||||
} | |||||
void Menu::setEnteredCallback(std::function<void()> callback) | |||||
{ | |||||
this->enteredCallback = callback; | |||||
} | |||||
void Menu::setExitedCallback(std::function<void()> callback) | |||||
{ | |||||
this->exitedCallback = callback; | |||||
} |
@ -0,0 +1,506 @@ | |||||
/* | |||||
* Copyright (C) 2017 Christopher J. Howard | |||||
* | |||||
* This file is part of Antkeeper Source Code. | |||||
* | |||||
* Antkeeper Source Code 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. | |||||
* | |||||
* Antkeeper Source Code 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 Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>. | |||||
*/ | |||||
#ifndef UI_HPP | |||||
#define UI_HPP | |||||
#include "../input.hpp" | |||||
#include "../materials.hpp" | |||||
#include <vector> | |||||
#include <functional> | |||||
#include <emergent/emergent.hpp> | |||||
using namespace Emergent; | |||||
namespace Anchor | |||||
{ | |||||
static const Vector2& TOP_LEFT = Vector2(0.0f, 0.0f); | |||||
static const Vector2& TOP_RIGHT = Vector2(1.0f, 0.0f); | |||||
static const Vector2& BOTTOM_LEFT = Vector2(0.0f, 1.0f); | |||||
static const Vector2& BOTTOM_RIGHT = Vector2(1.0f, 1.0f); | |||||
static const Vector2& CENTER = Vector2(0.5f, 0.5f); | |||||
} | |||||
class UIElement: public MouseMotionObserver, public MouseButtonObserver | |||||
{ | |||||
public: | |||||
enum class Type | |||||
{ | |||||
CONTAINER, | |||||
LABEL, | |||||
IMAGE | |||||
}; | |||||
UIElement(); | |||||
virtual ~UIElement(); | |||||
/// Sets the anchor vector. Possible values are 0, 0.5, and 1, corresponding to the left, center, and right, respectively, and the top, center, and bottom. | |||||
void setAnchor(const Vector2& anchor); | |||||
/// Sets the layer offset, relative to its parent layer + 1 | |||||
void setLayerOffset(int offset); | |||||
/// Sets the local origin of the element | |||||
void setOrigin(const Vector2& origin); | |||||
/// Sets the translation of the element, relative to its position in its parent element | |||||
void setTranslation(const Vector2& translation); | |||||
/// Sets the dimensions of the element | |||||
void setDimensions(const Vector2& dimensions); | |||||
/// Sets the tint color of the element | |||||
void setTintColor(const Vector4& color); | |||||
/// Sets the visibility of the element | |||||
void setVisible(bool visible); | |||||
/// Enables or disables callbacks | |||||
void setActive(bool active); | |||||
/// Returns the type of this element | |||||
virtual UIElement::Type getElementType() const = 0; | |||||
/// Returns the material of this element | |||||
const UIMaterial* getMaterial() const; | |||||
/// @copydoc UIElement::getMaterial() const | |||||
UIMaterial* getMaterial(); | |||||
/// Returns the parent of this element | |||||
const UIElement* getParent() const; | |||||
/// @copydoc UIElement::getParent() const | |||||
UIElement* getParent(); | |||||
/// Returns the number of child elements | |||||
std::size_t getChildCount() const; | |||||
/// Returns the child element at the specified index | |||||
const UIElement* getChild(std::size_t index) const; | |||||
/// @copydoc UIElement::getChild() const | |||||
UIElement* getChild(std::size_t index); | |||||
/// Returns the anchor vector | |||||
const Vector2& getAnchor() const; | |||||
/// Returns the layer offset | |||||
int getLayerOffset() const; | |||||
/// Returns the layer of this element | |||||
int getLayer() const; | |||||
/// Returns the origin of this element | |||||
const Vector2& getOrigin() const; | |||||
/// Returns the translation of this element, relative to its parent | |||||
const Vector2& getTranslation() const; | |||||
/// Returns the dimensions of this element | |||||
const Vector2& getDimensions() const; | |||||
/// Returns the world-space position of this element. Only accurate after update() is called | |||||
const Vector2& getPosition() const; | |||||
/// Returns the world-space bounds of this element. | |||||
const Rect& getBounds() const; | |||||
/// Returns the tint color of this element | |||||
const Vector4& getTintColor() const; | |||||
/// Returns the final color of this element, relative to its ancestor's tint colors | |||||
const Vector4& getColor() const; | |||||
/// Returns the visibility of this element | |||||
bool isVisible() const; | |||||
/// Returns `true` if the element is active (callbacks enabled) | |||||
bool isActive() const; | |||||
/// Calculates the world-space position and bounds of this element and its children | |||||
virtual void update(); | |||||
/// Adds a child to this element | |||||
void addChild(UIElement* element); | |||||
/// Removes a child from this element | |||||
void removeChild(UIElement* element); | |||||
void setMouseOverCallback(std::function<void()> callback); | |||||
void setMouseOutCallback(std::function<void()> callback); | |||||
void setMouseMovedCallback(std::function<void()> callback); | |||||
void setMousePressedCallback(std::function<void(int)> callback); | |||||
void setMouseReleasedCallback(std::function<void(int)> callback); | |||||
void mouseMoved(int x, int y); | |||||
void mouseButtonPressed(int button, int x, int y); | |||||
void mouseButtonReleased(int button, int x, int y); | |||||
protected: | |||||
UIMaterial material; | |||||
private: | |||||
UIElement* parent; | |||||
std::vector<UIElement*> children; | |||||
Vector2 anchor; | |||||
int layerOffset; | |||||
int layer; | |||||
Vector2 origin; | |||||
Vector2 translation; | |||||
Vector2 dimensions; | |||||
Vector2 position; | |||||
Rect bounds; | |||||
Vector4 tintColor; | |||||
Vector4 color; | |||||
bool visible; | |||||
bool active; | |||||
bool mouseOver; | |||||
std::function<void()> mouseOverCallback; | |||||
std::function<void()> mouseOutCallback; | |||||
std::function<void()> mouseMovedCallback; | |||||
std::function<void(int)> mousePressedCallback; | |||||
std::function<void(int)> mouseReleasedCallback; | |||||
}; | |||||
inline void UIElement::setAnchor(const Vector2& anchor) | |||||
{ | |||||
this->anchor = anchor; | |||||
} | |||||
inline void UIElement::setLayerOffset(int offset) | |||||
{ | |||||
this->layerOffset = offset; | |||||
} | |||||
inline void UIElement::setOrigin(const Vector2& origin) | |||||
{ | |||||
this->origin = origin; | |||||
} | |||||
inline void UIElement::setTranslation(const Vector2& translation) | |||||
{ | |||||
this->translation = translation; | |||||
} | |||||
inline void UIElement::setDimensions(const Vector2& dimensions) | |||||
{ | |||||
this->dimensions = dimensions; | |||||
} | |||||
inline void UIElement::setTintColor(const Vector4& color) | |||||
{ | |||||
this->tintColor = color; | |||||
} | |||||
inline void UIElement::setVisible(bool visible) | |||||
{ | |||||
this->visible = visible; | |||||
} | |||||
inline void UIElement::setActive(bool active) | |||||
{ | |||||
this->active = active; | |||||
} | |||||
inline const UIElement* UIElement::getParent() const | |||||
{ | |||||
return parent; | |||||
} | |||||
inline const UIMaterial* UIElement::getMaterial() const | |||||
{ | |||||
return &material; | |||||
} | |||||
inline UIMaterial* UIElement::getMaterial() | |||||
{ | |||||
return &material; | |||||
} | |||||
inline UIElement* UIElement::getParent() | |||||
{ | |||||
return parent; | |||||
} | |||||
inline std::size_t UIElement::getChildCount() const | |||||
{ | |||||
return children.size(); | |||||
} | |||||
inline const UIElement* UIElement::getChild(std::size_t index) const | |||||
{ | |||||
return children[index]; | |||||
} | |||||
inline UIElement* UIElement::getChild(std::size_t index) | |||||
{ | |||||
return children[index]; | |||||
} | |||||
inline const Vector2& UIElement::getAnchor() const | |||||
{ | |||||
return anchor; | |||||
} | |||||
inline int UIElement::getLayerOffset() const | |||||
{ | |||||
return layerOffset; | |||||
} | |||||
inline int UIElement::getLayer() const | |||||
{ | |||||
return layer; | |||||
} | |||||
inline const Vector2& UIElement::getOrigin() const | |||||
{ | |||||
return origin; | |||||
} | |||||
inline const Vector2& UIElement::getTranslation() const | |||||
{ | |||||
return translation; | |||||
} | |||||
inline const Vector2& UIElement::getDimensions() const | |||||
{ | |||||
return dimensions; | |||||
} | |||||
inline const Vector2& UIElement::getPosition() const | |||||
{ | |||||
return position; | |||||
} | |||||
inline const Rect& UIElement::getBounds() const | |||||
{ | |||||
return bounds; | |||||
} | |||||
inline const Vector4& UIElement::getTintColor() const | |||||
{ | |||||
return tintColor; | |||||
} | |||||
inline const Vector4& UIElement::getColor() const | |||||
{ | |||||
return color; | |||||
} | |||||
inline bool UIElement::isVisible() const | |||||
{ | |||||
return visible; | |||||
} | |||||
inline bool UIElement::isActive() const | |||||
{ | |||||
return active; | |||||
} | |||||
class UIContainer: public UIElement | |||||
{ | |||||
public: | |||||
virtual UIElement::Type getElementType() const; | |||||
}; | |||||
inline UIElement::Type UIContainer::getElementType() const | |||||
{ | |||||
return UIElement::Type::CONTAINER; | |||||
} | |||||
class UILabel: public UIElement | |||||
{ | |||||
public: | |||||
UILabel(); | |||||
virtual ~UILabel(); | |||||
virtual UIElement::Type getElementType() const; | |||||
void setFont(Font* font); | |||||
void setText(const std::string& text); | |||||
const Font* getFont() const; | |||||
Font* getFont(); | |||||
const std::string& getText() const; | |||||
private: | |||||
void calculateDimensions(); | |||||
Font* font; | |||||
std::string text; | |||||
}; | |||||
inline UIElement::Type UILabel::getElementType() const | |||||
{ | |||||
return UIElement::Type::LABEL; | |||||
} | |||||
inline const Font* UILabel::getFont() const | |||||
{ | |||||
return font; | |||||
} | |||||
inline Font* UILabel::getFont() | |||||
{ | |||||
return font; | |||||
} | |||||
inline const std::string& UILabel::getText() const | |||||
{ | |||||
return text; | |||||
} | |||||
class UIImage: public UIElement | |||||
{ | |||||
public: | |||||
UIImage(); | |||||
virtual ~UIImage(); | |||||
virtual UIElement::Type getElementType() const; | |||||
virtual const Texture* getTexture() const; | |||||
void setTexture(Texture* texture); | |||||
void setTextureBounds(const Rect& bounds); | |||||
const Rect& getTextureBounds() const; | |||||
private: | |||||
Rect textureBounds; | |||||
}; | |||||
inline UIElement::Type UIImage::getElementType() const | |||||
{ | |||||
return UIElement::Type::IMAGE; | |||||
} | |||||
inline const Texture* UIImage::getTexture() const | |||||
{ | |||||
return material.texture; | |||||
} | |||||
inline void UIImage::setTexture(Texture* texture) | |||||
{ | |||||
material.texture = texture; | |||||
} | |||||
inline void UIImage::setTextureBounds(const Rect& bounds) | |||||
{ | |||||
this->textureBounds = bounds; | |||||
} | |||||
inline const Rect& UIImage::getTextureBounds() const | |||||
{ | |||||
return textureBounds; | |||||
} | |||||
// Creates a scene from a root UI element (follows visitor pattern?) | |||||
class UIBatcher | |||||
{ | |||||
public: | |||||
void batch(BillboardBatch* result, const UIElement* ui); | |||||
private: | |||||
void queueElements(std::list<const UIElement*>* elements, const UIElement* element) const; | |||||
BillboardBatch::Range* getRange(BillboardBatch* result, const UIElement* element) const; | |||||
void batchElement(BillboardBatch* result, const UIElement* element); | |||||
void batchLabel(BillboardBatch* result, const UILabel* label); | |||||
void batchImage(BillboardBatch* result, const UIImage* image); | |||||
}; | |||||
class Menu; | |||||
class MenuItem | |||||
{ | |||||
public: | |||||
void select(); | |||||
void deselect(); | |||||
void activate(); | |||||
void setSelectedCallback(std::function<void()> callback); | |||||
void setDeselectedCallback(std::function<void()> callback); | |||||
void setActivatedCallback(std::function<void()> callback); | |||||
std::size_t getIndex() const; | |||||
bool isSelected() const; | |||||
private: | |||||
friend class Menu; | |||||
MenuItem(Menu* parent, std::size_t index); | |||||
Menu* parent; | |||||
std::size_t index; | |||||
bool selected; | |||||
std::function<void()> selectedCallback; | |||||
std::function<void()> deselectedCallback; | |||||
std::function<void()> activatedCallback; | |||||
}; | |||||
inline std::size_t MenuItem::getIndex() const | |||||
{ | |||||
return index; | |||||
} | |||||
inline bool MenuItem::isSelected() const | |||||
{ | |||||
return selected; | |||||
} | |||||
class Menu | |||||
{ | |||||
public: | |||||
Menu(); | |||||
~Menu(); | |||||
void enter(); | |||||
void exit(); | |||||
MenuItem* addItem(); | |||||
void removeItems(); | |||||
void setEnteredCallback(std::function<void()> callback); | |||||
void setExitedCallback(std::function<void()> callback); | |||||
std::size_t getItemCount(); | |||||
const MenuItem* getItem(std::size_t index) const; | |||||
MenuItem* getItem(std::size_t index); | |||||
private: | |||||
std::vector<MenuItem*> items; | |||||
std::function<void()> enteredCallback; | |||||
std::function<void()> exitedCallback; | |||||
}; | |||||
inline std::size_t Menu::getItemCount() | |||||
{ | |||||
return items.size(); | |||||
} | |||||
inline const MenuItem* Menu::getItem(std::size_t index) const | |||||
{ | |||||
return items[index]; | |||||
} | |||||
inline MenuItem* Menu::getItem(std::size_t index) | |||||
{ | |||||
return items[index]; | |||||
} | |||||
#endif // UI_HPP |
@ -0,0 +1,929 @@ | |||||
/* | |||||
* Dirent interface for Microsoft Visual Studio | |||||
* Version 1.21 | |||||
* | |||||
* Copyright (C) 2006-2012 Toni Ronkko | |||||
* This file is part of dirent. Dirent may be freely distributed | |||||
* under the MIT license. For all details and documentation, see | |||||
* https://github.com/tronkko/dirent | |||||
*/ | |||||
#ifndef DIRENT_H | |||||
#define DIRENT_H | |||||
/* | |||||
* Include windows.h without Windows Sockets 1.1 to prevent conflicts with | |||||
* Windows Sockets 2.0. | |||||
*/ | |||||
#ifndef WIN32_LEAN_AND_MEAN | |||||
# define WIN32_LEAN_AND_MEAN | |||||
#endif | |||||
#include <windows.h> | |||||
#include <stdio.h> | |||||
#include <stdarg.h> | |||||
#include <wchar.h> | |||||
#include <string.h> | |||||
#include <stdlib.h> | |||||
#include <malloc.h> | |||||
#include <sys/types.h> | |||||
#include <sys/stat.h> | |||||
#include <errno.h> | |||||
/* Indicates that d_type field is available in dirent structure */ | |||||
#define _DIRENT_HAVE_D_TYPE | |||||
/* Indicates that d_namlen field is available in dirent structure */ | |||||
#define _DIRENT_HAVE_D_NAMLEN | |||||
/* Entries missing from MSVC 6.0 */ | |||||
#if !defined(FILE_ATTRIBUTE_DEVICE) | |||||
# define FILE_ATTRIBUTE_DEVICE 0x40 | |||||
#endif | |||||
/* File type and permission flags for stat(), general mask */ | |||||
#if !defined(S_IFMT) | |||||
# define S_IFMT _S_IFMT | |||||
#endif | |||||
/* Directory bit */ | |||||
#if !defined(S_IFDIR) | |||||
# define S_IFDIR _S_IFDIR | |||||
#endif | |||||
/* Character device bit */ | |||||
#if !defined(S_IFCHR) | |||||
# define S_IFCHR _S_IFCHR | |||||
#endif | |||||
/* Pipe bit */ | |||||
#if !defined(S_IFFIFO) | |||||
# define S_IFFIFO _S_IFFIFO | |||||
#endif | |||||
/* Regular file bit */ | |||||
#if !defined(S_IFREG) | |||||
# define S_IFREG _S_IFREG | |||||
#endif | |||||
/* Read permission */ | |||||
#if !defined(S_IREAD) | |||||
# define S_IREAD _S_IREAD | |||||
#endif | |||||
/* Write permission */ | |||||
#if !defined(S_IWRITE) | |||||
# define S_IWRITE _S_IWRITE | |||||
#endif | |||||
/* Execute permission */ | |||||
#if !defined(S_IEXEC) | |||||
# define S_IEXEC _S_IEXEC | |||||
#endif | |||||
/* Pipe */ | |||||
#if !defined(S_IFIFO) | |||||
# define S_IFIFO _S_IFIFO | |||||
#endif | |||||
/* Block device */ | |||||
#if !defined(S_IFBLK) | |||||
# define S_IFBLK 0 | |||||
#endif | |||||
/* Link */ | |||||
#if !defined(S_IFLNK) | |||||
# define S_IFLNK 0 | |||||
#endif | |||||
/* Socket */ | |||||
#if !defined(S_IFSOCK) | |||||
# define S_IFSOCK 0 | |||||
#endif | |||||
/* Read user permission */ | |||||
#if !defined(S_IRUSR) | |||||
# define S_IRUSR S_IREAD | |||||
#endif | |||||
/* Write user permission */ | |||||
#if !defined(S_IWUSR) | |||||
# define S_IWUSR S_IWRITE | |||||
#endif | |||||
/* Execute user permission */ | |||||
#if !defined(S_IXUSR) | |||||
# define S_IXUSR 0 | |||||
#endif | |||||
/* Read group permission */ | |||||
#if !defined(S_IRGRP) | |||||
# define S_IRGRP 0 | |||||
#endif | |||||
/* Write group permission */ | |||||
#if !defined(S_IWGRP) | |||||
# define S_IWGRP 0 | |||||
#endif | |||||
/* Execute group permission */ | |||||
#if !defined(S_IXGRP) | |||||
# define S_IXGRP 0 | |||||
#endif | |||||
/* Read others permission */ | |||||
#if !defined(S_IROTH) | |||||
# define S_IROTH 0 | |||||
#endif | |||||
/* Write others permission */ | |||||
#if !defined(S_IWOTH) | |||||
# define S_IWOTH 0 | |||||
#endif | |||||
/* Execute others permission */ | |||||
#if !defined(S_IXOTH) | |||||
# define S_IXOTH 0 | |||||
#endif | |||||
/* Maximum length of file name */ | |||||
#if !defined(PATH_MAX) | |||||
# define PATH_MAX MAX_PATH | |||||
#endif | |||||
#if !defined(FILENAME_MAX) | |||||
# define FILENAME_MAX MAX_PATH | |||||
#endif | |||||
#if !defined(NAME_MAX) | |||||
# define NAME_MAX FILENAME_MAX | |||||
#endif | |||||
/* File type flags for d_type */ | |||||
#define DT_UNKNOWN 0 | |||||
#define DT_REG S_IFREG | |||||
#define DT_DIR S_IFDIR | |||||
#define DT_FIFO S_IFIFO | |||||
#define DT_SOCK S_IFSOCK | |||||
#define DT_CHR S_IFCHR | |||||
#define DT_BLK S_IFBLK | |||||
#define DT_LNK S_IFLNK | |||||
/* Macros for converting between st_mode and d_type */ | |||||
#define IFTODT(mode) ((mode) & S_IFMT) | |||||
#define DTTOIF(type) (type) | |||||
/* | |||||
* File type macros. Note that block devices, sockets and links cannot be | |||||
* distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are | |||||
* only defined for compatibility. These macros should always return false | |||||
* on Windows. | |||||
*/ | |||||
#if !defined(S_ISFIFO) | |||||
# define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) | |||||
#endif | |||||
#if !defined(S_ISDIR) | |||||
# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) | |||||
#endif | |||||
#if !defined(S_ISREG) | |||||
# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) | |||||
#endif | |||||
#if !defined(S_ISLNK) | |||||
# define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) | |||||
#endif | |||||
#if !defined(S_ISSOCK) | |||||
# define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) | |||||
#endif | |||||
#if !defined(S_ISCHR) | |||||
# define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) | |||||
#endif | |||||
#if !defined(S_ISBLK) | |||||
# define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) | |||||
#endif | |||||
/* Return the exact length of d_namlen without zero terminator */ | |||||
#define _D_EXACT_NAMLEN(p) ((p)->d_namlen) | |||||
/* Return number of bytes needed to store d_namlen */ | |||||
#define _D_ALLOC_NAMLEN(p) (PATH_MAX) | |||||
#ifdef __cplusplus | |||||
extern "C" { | |||||
#endif | |||||
/* Wide-character version */ | |||||
struct _wdirent { | |||||
/* Always zero */ | |||||
long d_ino; | |||||
/* Structure size */ | |||||
unsigned short d_reclen; | |||||
/* Length of name without \0 */ | |||||
size_t d_namlen; | |||||
/* File type */ | |||||
int d_type; | |||||
/* File name */ | |||||
wchar_t d_name[PATH_MAX]; | |||||
}; | |||||
typedef struct _wdirent _wdirent; | |||||
struct _WDIR { | |||||
/* Current directory entry */ | |||||
struct _wdirent ent; | |||||
/* Private file data */ | |||||
WIN32_FIND_DATAW data; | |||||
/* True if data is valid */ | |||||
int cached; | |||||
/* Win32 search handle */ | |||||
HANDLE handle; | |||||
/* Initial directory name */ | |||||
wchar_t *patt; | |||||
}; | |||||
typedef struct _WDIR _WDIR; | |||||
static _WDIR *_wopendir (const wchar_t *dirname); | |||||
static struct _wdirent *_wreaddir (_WDIR *dirp); | |||||
static int _wclosedir (_WDIR *dirp); | |||||
static void _wrewinddir (_WDIR* dirp); | |||||
/* For compatibility with Symbian */ | |||||
#define wdirent _wdirent | |||||
#define WDIR _WDIR | |||||
#define wopendir _wopendir | |||||
#define wreaddir _wreaddir | |||||
#define wclosedir _wclosedir | |||||
#define wrewinddir _wrewinddir | |||||
/* Multi-byte character versions */ | |||||
struct dirent { | |||||
/* Always zero */ | |||||
long d_ino; | |||||
/* Structure size */ | |||||
unsigned short d_reclen; | |||||
/* Length of name without \0 */ | |||||
size_t d_namlen; | |||||
/* File type */ | |||||
int d_type; | |||||
/* File name */ | |||||
char d_name[PATH_MAX]; | |||||
}; | |||||
typedef struct dirent dirent; | |||||
struct DIR { | |||||
struct dirent ent; | |||||
struct _WDIR *wdirp; | |||||
}; | |||||
typedef struct DIR DIR; | |||||
static DIR *opendir (const char *dirname); | |||||
static struct dirent *readdir (DIR *dirp); | |||||
static int closedir (DIR *dirp); | |||||
static void rewinddir (DIR* dirp); | |||||
/* Internal utility functions */ | |||||
static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp); | |||||
static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp); | |||||
static int dirent_mbstowcs_s( | |||||
size_t *pReturnValue, | |||||
wchar_t *wcstr, | |||||
size_t sizeInWords, | |||||
const char *mbstr, | |||||
size_t count); | |||||
static int dirent_wcstombs_s( | |||||
size_t *pReturnValue, | |||||
char *mbstr, | |||||
size_t sizeInBytes, | |||||
const wchar_t *wcstr, | |||||
size_t count); | |||||
static void dirent_set_errno (int error); | |||||
/* | |||||
* Open directory stream DIRNAME for read and return a pointer to the | |||||
* internal working area that is used to retrieve individual directory | |||||
* entries. | |||||
*/ | |||||
static _WDIR* | |||||
_wopendir( | |||||
const wchar_t *dirname) | |||||
{ | |||||
_WDIR *dirp = NULL; | |||||
int error; | |||||
/* Must have directory name */ | |||||
if (dirname == NULL || dirname[0] == '\0') { | |||||
dirent_set_errno (ENOENT); | |||||
return NULL; | |||||
} | |||||
/* Allocate new _WDIR structure */ | |||||
dirp = (_WDIR*) malloc (sizeof (struct _WDIR)); | |||||
if (dirp != NULL) { | |||||
DWORD n; | |||||
/* Reset _WDIR structure */ | |||||
dirp->handle = INVALID_HANDLE_VALUE; | |||||
dirp->patt = NULL; | |||||
dirp->cached = 0; | |||||
/* Compute the length of full path plus zero terminator | |||||
* | |||||
* Note that on WinRT there's no way to convert relative paths | |||||
* into absolute paths, so just assume its an absolute path. | |||||
*/ | |||||
# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) | |||||
n = wcslen(dirname); | |||||
# else | |||||
n = GetFullPathNameW (dirname, 0, NULL, NULL); | |||||
# endif | |||||
/* Allocate room for absolute directory name and search pattern */ | |||||
dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16); | |||||
if (dirp->patt) { | |||||
/* | |||||
* Convert relative directory name to an absolute one. This | |||||
* allows rewinddir() to function correctly even when current | |||||
* working directory is changed between opendir() and rewinddir(). | |||||
* | |||||
* Note that on WinRT there's no way to convert relative paths | |||||
* into absolute paths, so just assume its an absolute path. | |||||
*/ | |||||
# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) | |||||
wcsncpy_s(dirp->patt, n+1, dirname, n); | |||||
# else | |||||
n = GetFullPathNameW (dirname, n, dirp->patt, NULL); | |||||
# endif | |||||
if (n > 0) { | |||||
wchar_t *p; | |||||
/* Append search pattern \* to the directory name */ | |||||
p = dirp->patt + n; | |||||
if (dirp->patt < p) { | |||||
switch (p[-1]) { | |||||
case '\\': | |||||
case '/': | |||||
case ':': | |||||
/* Directory ends in path separator, e.g. c:\temp\ */ | |||||
/*NOP*/; | |||||
break; | |||||
default: | |||||
/* Directory name doesn't end in path separator */ | |||||
*p++ = '\\'; | |||||
} | |||||
} | |||||
*p++ = '*'; | |||||
*p = '\0'; | |||||
/* Open directory stream and retrieve the first entry */ | |||||
if (dirent_first (dirp)) { | |||||
/* Directory stream opened successfully */ | |||||
error = 0; | |||||
} else { | |||||
/* Cannot retrieve first entry */ | |||||
error = 1; | |||||
dirent_set_errno (ENOENT); | |||||
} | |||||
} else { | |||||
/* Cannot retrieve full path name */ | |||||
dirent_set_errno (ENOENT); | |||||
error = 1; | |||||
} | |||||
} else { | |||||
/* Cannot allocate memory for search pattern */ | |||||
error = 1; | |||||
} | |||||
} else { | |||||
/* Cannot allocate _WDIR structure */ | |||||
error = 1; | |||||
} | |||||
/* Clean up in case of error */ | |||||
if (error && dirp) { | |||||
_wclosedir (dirp); | |||||
dirp = NULL; | |||||
} | |||||
return dirp; | |||||
} | |||||
/* | |||||
* Read next directory entry. The directory entry is returned in dirent | |||||
* structure in the d_name field. Individual directory entries returned by | |||||
* this function include regular files, sub-directories, pseudo-directories | |||||
* "." and ".." as well as volume labels, hidden files and system files. | |||||
*/ | |||||
static struct _wdirent* | |||||
_wreaddir( | |||||
_WDIR *dirp) | |||||
{ | |||||
WIN32_FIND_DATAW *datap; | |||||
struct _wdirent *entp; | |||||
/* Read next directory entry */ | |||||
datap = dirent_next (dirp); | |||||
if (datap) { | |||||
size_t n; | |||||
DWORD attr; | |||||
/* Pointer to directory entry to return */ | |||||
entp = &dirp->ent; | |||||
/* | |||||
* Copy file name as wide-character string. If the file name is too | |||||
* long to fit in to the destination buffer, then truncate file name | |||||
* to PATH_MAX characters and zero-terminate the buffer. | |||||
*/ | |||||
n = 0; | |||||
while (n + 1 < PATH_MAX && datap->cFileName[n] != 0) { | |||||
entp->d_name[n] = datap->cFileName[n]; | |||||
n++; | |||||
} | |||||
dirp->ent.d_name[n] = 0; | |||||
/* Length of file name excluding zero terminator */ | |||||
entp->d_namlen = n; | |||||
/* File type */ | |||||
attr = datap->dwFileAttributes; | |||||
if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { | |||||
entp->d_type = DT_CHR; | |||||
} else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { | |||||
entp->d_type = DT_DIR; | |||||
} else { | |||||
entp->d_type = DT_REG; | |||||
} | |||||
/* Reset dummy fields */ | |||||
entp->d_ino = 0; | |||||
entp->d_reclen = sizeof (struct _wdirent); | |||||
} else { | |||||
/* Last directory entry read */ | |||||
entp = NULL; | |||||
} | |||||
return entp; | |||||
} | |||||
/* | |||||
* Close directory stream opened by opendir() function. This invalidates the | |||||
* DIR structure as well as any directory entry read previously by | |||||
* _wreaddir(). | |||||
*/ | |||||
static int | |||||
_wclosedir( | |||||
_WDIR *dirp) | |||||
{ | |||||
int ok; | |||||
if (dirp) { | |||||
/* Release search handle */ | |||||
if (dirp->handle != INVALID_HANDLE_VALUE) { | |||||
FindClose (dirp->handle); | |||||
dirp->handle = INVALID_HANDLE_VALUE; | |||||
} | |||||
/* Release search pattern */ | |||||
if (dirp->patt) { | |||||
free (dirp->patt); | |||||
dirp->patt = NULL; | |||||
} | |||||
/* Release directory structure */ | |||||
free (dirp); | |||||
ok = /*success*/0; | |||||
} else { | |||||
/* Invalid directory stream */ | |||||
dirent_set_errno (EBADF); | |||||
ok = /*failure*/-1; | |||||
} | |||||
return ok; | |||||
} | |||||
/* | |||||
* Rewind directory stream such that _wreaddir() returns the very first | |||||
* file name again. | |||||
*/ | |||||
static void | |||||
_wrewinddir( | |||||
_WDIR* dirp) | |||||
{ | |||||
if (dirp) { | |||||
/* Release existing search handle */ | |||||
if (dirp->handle != INVALID_HANDLE_VALUE) { | |||||
FindClose (dirp->handle); | |||||
} | |||||
/* Open new search handle */ | |||||
dirent_first (dirp); | |||||
} | |||||
} | |||||
/* Get first directory entry (internal) */ | |||||
static WIN32_FIND_DATAW* | |||||
dirent_first( | |||||
_WDIR *dirp) | |||||
{ | |||||
WIN32_FIND_DATAW *datap; | |||||
/* Open directory and retrieve the first entry */ | |||||
dirp->handle = FindFirstFileExW( | |||||
dirp->patt, FindExInfoStandard, &dirp->data, | |||||
FindExSearchNameMatch, NULL, 0); | |||||
if (dirp->handle != INVALID_HANDLE_VALUE) { | |||||
/* a directory entry is now waiting in memory */ | |||||
datap = &dirp->data; | |||||
dirp->cached = 1; | |||||
} else { | |||||
/* Failed to re-open directory: no directory entry in memory */ | |||||
dirp->cached = 0; | |||||
datap = NULL; | |||||
} | |||||
return datap; | |||||
} | |||||
/* Get next directory entry (internal) */ | |||||
static WIN32_FIND_DATAW* | |||||
dirent_next( | |||||
_WDIR *dirp) | |||||
{ | |||||
WIN32_FIND_DATAW *p; | |||||
/* Get next directory entry */ | |||||
if (dirp->cached != 0) { | |||||
/* A valid directory entry already in memory */ | |||||
p = &dirp->data; | |||||
dirp->cached = 0; | |||||
} else if (dirp->handle != INVALID_HANDLE_VALUE) { | |||||
/* Get the next directory entry from stream */ | |||||
if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) { | |||||
/* Got a file */ | |||||
p = &dirp->data; | |||||
} else { | |||||
/* The very last entry has been processed or an error occured */ | |||||
FindClose (dirp->handle); | |||||
dirp->handle = INVALID_HANDLE_VALUE; | |||||
p = NULL; | |||||
} | |||||
} else { | |||||
/* End of directory stream reached */ | |||||
p = NULL; | |||||
} | |||||
return p; | |||||
} | |||||
/* | |||||
* Open directory stream using plain old C-string. | |||||
*/ | |||||
static DIR* | |||||
opendir( | |||||
const char *dirname) | |||||
{ | |||||
struct DIR *dirp; | |||||
int error; | |||||
/* Must have directory name */ | |||||
if (dirname == NULL || dirname[0] == '\0') { | |||||
dirent_set_errno (ENOENT); | |||||
return NULL; | |||||
} | |||||
/* Allocate memory for DIR structure */ | |||||
dirp = (DIR*) malloc (sizeof (struct DIR)); | |||||
if (dirp) { | |||||
wchar_t wname[PATH_MAX]; | |||||
size_t n; | |||||
/* Convert directory name to wide-character string */ | |||||
error = dirent_mbstowcs_s (&n, wname, PATH_MAX, dirname, PATH_MAX); | |||||
if (!error) { | |||||
/* Open directory stream using wide-character name */ | |||||
dirp->wdirp = _wopendir (wname); | |||||
if (dirp->wdirp) { | |||||
/* Directory stream opened */ | |||||
error = 0; | |||||
} else { | |||||
/* Failed to open directory stream */ | |||||
error = 1; | |||||
} | |||||
} else { | |||||
/* | |||||
* Cannot convert file name to wide-character string. This | |||||
* occurs if the string contains invalid multi-byte sequences or | |||||
* the output buffer is too small to contain the resulting | |||||
* string. | |||||
*/ | |||||
error = 1; | |||||
} | |||||
} else { | |||||
/* Cannot allocate DIR structure */ | |||||
error = 1; | |||||
} | |||||
/* Clean up in case of error */ | |||||
if (error && dirp) { | |||||
free (dirp); | |||||
dirp = NULL; | |||||
} | |||||
return dirp; | |||||
} | |||||
/* | |||||
* Read next directory entry. | |||||
* | |||||
* When working with text consoles, please note that file names returned by | |||||
* readdir() are represented in the default ANSI code page while any output to | |||||
* console is typically formatted on another code page. Thus, non-ASCII | |||||
* characters in file names will not usually display correctly on console. The | |||||
* problem can be fixed in two ways: (1) change the character set of console | |||||
* to 1252 using chcp utility and use Lucida Console font, or (2) use | |||||
* _cprintf function when writing to console. The _cprinf() will re-encode | |||||
* ANSI strings to the console code page so many non-ASCII characters will | |||||
* display correcly. | |||||
*/ | |||||
static struct dirent* | |||||
readdir( | |||||
DIR *dirp) | |||||
{ | |||||
WIN32_FIND_DATAW *datap; | |||||
struct dirent *entp; | |||||
/* Read next directory entry */ | |||||
datap = dirent_next (dirp->wdirp); | |||||
if (datap) { | |||||
size_t n; | |||||
int error; | |||||
/* Attempt to convert file name to multi-byte string */ | |||||
error = dirent_wcstombs_s( | |||||
&n, dirp->ent.d_name, PATH_MAX, datap->cFileName, PATH_MAX); | |||||
/* | |||||
* If the file name cannot be represented by a multi-byte string, | |||||
* then attempt to use old 8+3 file name. This allows traditional | |||||
* Unix-code to access some file names despite of unicode | |||||
* characters, although file names may seem unfamiliar to the user. | |||||
* | |||||
* Be ware that the code below cannot come up with a short file | |||||
* name unless the file system provides one. At least | |||||
* VirtualBox shared folders fail to do this. | |||||
*/ | |||||
if (error && datap->cAlternateFileName[0] != '\0') { | |||||
error = dirent_wcstombs_s( | |||||
&n, dirp->ent.d_name, PATH_MAX, | |||||
datap->cAlternateFileName, PATH_MAX); | |||||
} | |||||
if (!error) { | |||||
DWORD attr; | |||||
/* Initialize directory entry for return */ | |||||
entp = &dirp->ent; | |||||
/* Length of file name excluding zero terminator */ | |||||
entp->d_namlen = n - 1; | |||||
/* File attributes */ | |||||
attr = datap->dwFileAttributes; | |||||
if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { | |||||
entp->d_type = DT_CHR; | |||||
} else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { | |||||
entp->d_type = DT_DIR; | |||||
} else { | |||||
entp->d_type = DT_REG; | |||||
} | |||||
/* Reset dummy fields */ | |||||
entp->d_ino = 0; | |||||
entp->d_reclen = sizeof (struct dirent); | |||||
} else { | |||||
/* | |||||
* Cannot convert file name to multi-byte string so construct | |||||
* an errornous directory entry and return that. Note that | |||||
* we cannot return NULL as that would stop the processing | |||||
* of directory entries completely. | |||||
*/ | |||||
entp = &dirp->ent; | |||||
entp->d_name[0] = '?'; | |||||
entp->d_name[1] = '\0'; | |||||
entp->d_namlen = 1; | |||||
entp->d_type = DT_UNKNOWN; | |||||
entp->d_ino = 0; | |||||
entp->d_reclen = 0; | |||||
} | |||||
} else { | |||||
/* No more directory entries */ | |||||
entp = NULL; | |||||
} | |||||
return entp; | |||||
} | |||||
/* | |||||
* Close directory stream. | |||||
*/ | |||||
static int | |||||
closedir( | |||||
DIR *dirp) | |||||
{ | |||||
int ok; | |||||
if (dirp) { | |||||
/* Close wide-character directory stream */ | |||||
ok = _wclosedir (dirp->wdirp); | |||||
dirp->wdirp = NULL; | |||||
/* Release multi-byte character version */ | |||||
free (dirp); | |||||
} else { | |||||
/* Invalid directory stream */ | |||||
dirent_set_errno (EBADF); | |||||
ok = /*failure*/-1; | |||||
} | |||||
return ok; | |||||
} | |||||
/* | |||||
* Rewind directory stream to beginning. | |||||
*/ | |||||
static void | |||||
rewinddir( | |||||
DIR* dirp) | |||||
{ | |||||
/* Rewind wide-character string directory stream */ | |||||
_wrewinddir (dirp->wdirp); | |||||
} | |||||
/* Convert multi-byte string to wide character string */ | |||||
static int | |||||
dirent_mbstowcs_s( | |||||
size_t *pReturnValue, | |||||
wchar_t *wcstr, | |||||
size_t sizeInWords, | |||||
const char *mbstr, | |||||
size_t count) | |||||
{ | |||||
int error; | |||||
#if defined(_MSC_VER) && _MSC_VER >= 1400 | |||||
/* Microsoft Visual Studio 2005 or later */ | |||||
error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count); | |||||
#else | |||||
/* Older Visual Studio or non-Microsoft compiler */ | |||||
size_t n; | |||||
/* Convert to wide-character string (or count characters) */ | |||||
n = mbstowcs (wcstr, mbstr, sizeInWords); | |||||
if (!wcstr || n < count) { | |||||
/* Zero-terminate output buffer */ | |||||
if (wcstr && sizeInWords) { | |||||
if (n >= sizeInWords) { | |||||
n = sizeInWords - 1; | |||||
} | |||||
wcstr[n] = 0; | |||||
} | |||||
/* Length of resuting multi-byte string WITH zero terminator */ | |||||
if (pReturnValue) { | |||||
*pReturnValue = n + 1; | |||||
} | |||||
/* Success */ | |||||
error = 0; | |||||
} else { | |||||
/* Could not convert string */ | |||||
error = 1; | |||||
} | |||||
#endif | |||||
return error; | |||||
} | |||||
/* Convert wide-character string to multi-byte string */ | |||||
static int | |||||
dirent_wcstombs_s( | |||||
size_t *pReturnValue, | |||||
char *mbstr, | |||||
size_t sizeInBytes, /* max size of mbstr */ | |||||
const wchar_t *wcstr, | |||||
size_t count) | |||||
{ | |||||
int error; | |||||
#if defined(_MSC_VER) && _MSC_VER >= 1400 | |||||
/* Microsoft Visual Studio 2005 or later */ | |||||
error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count); | |||||
#else | |||||
/* Older Visual Studio or non-Microsoft compiler */ | |||||
size_t n; | |||||
/* Convert to multi-byte string (or count the number of bytes needed) */ | |||||
n = wcstombs (mbstr, wcstr, sizeInBytes); | |||||
if (!mbstr || n < count) { | |||||
/* Zero-terminate output buffer */ | |||||
if (mbstr && sizeInBytes) { | |||||
if (n >= sizeInBytes) { | |||||
n = sizeInBytes - 1; | |||||
} | |||||
mbstr[n] = '\0'; | |||||
} | |||||
/* Length of resulting multi-bytes string WITH zero-terminator */ | |||||
if (pReturnValue) { | |||||
*pReturnValue = n + 1; | |||||
} | |||||
/* Success */ | |||||
error = 0; | |||||
} else { | |||||
/* Cannot convert string */ | |||||
error = 1; | |||||
} | |||||
#endif | |||||
return error; | |||||
} | |||||
/* Set errno variable */ | |||||
static void | |||||
dirent_set_errno( | |||||
int error) | |||||
{ | |||||
#if defined(_MSC_VER) && _MSC_VER >= 1400 | |||||
/* Microsoft Visual Studio 2005 and later */ | |||||
_set_errno (error); | |||||
#else | |||||
/* Non-Microsoft compiler or older Microsoft compiler */ | |||||
errno = error; | |||||
#endif | |||||
} | |||||
#ifdef __cplusplus | |||||
} | |||||
#endif | |||||
#endif /*DIRENT_H*/ | |||||