Initial Commit

This commit is contained in:
Travis Hunter 2025-04-20 12:29:36 -06:00
parent 8f454725a6
commit bbe1199dbb
49 changed files with 32117 additions and 232 deletions

3
.gitignore vendored
View File

@ -2,6 +2,9 @@
# Prerequisites
*.d
# build directory
build/
# Compiled Object files
*.slo
*.lo

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"files.associations": {
"numeric": "cpp",
"algorithm": "cpp"
}
}

62
CMakeLists.txt Normal file
View File

@ -0,0 +1,62 @@
cmake_minimum_required(VERSION 3.16)
project(qtrocket LANGUAGES CXX)
# Enable testing
include(CTest)
enable_testing()
# Set C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Python3 COMPONENTS Interpreter Development REQUIRED)
# Include directories
include_directories(include)
# Find all source files
file(GLOB_RECURSE SIM_SRC src/*.cpp)
file(GLOB_RECURSE TEST_SRC tests/*.cpp)
# Create the rocket simulator library
add_library(rocketsimlib ${SIM_SRC})
# Main example executable
add_executable(basic_flight_simulation examples/basic_flight_simulation.cpp)
target_include_directories(basic_flight_simulation
PRIVATE /usr/lib/python3.13/site-packages/numpy/_core/include/)
target_link_libraries(basic_flight_simulation PRIVATE rocketsimlib PRIVATE Python3::Python)
# Test executable
add_executable(unit_tests ${TEST_SRC})
target_link_libraries(unit_tests PRIVATE rocketsimlib)
# Register tests with CTest
add_test(NAME UnitTests COMMAND unit_tests)
# ----------------------------------------------------------------------------
# PlantUML documentation generation
# ----------------------------------------------------------------------------
find_program(PLANTUML_EXECUTABLE plantuml DOC "Path to PlantUML executable")
if(PLANTUML_EXECUTABLE)
file(GLOB UML_FILES "${CMAKE_SOURCE_DIR}/docs/*.puml")
foreach(UML_FILE ${UML_FILES})
get_filename_component(UML_NAME ${UML_FILE} NAME_WE)
set(UML_OUTPUT "${CMAKE_SOURCE_DIR}/docs/${UML_NAME}.svg")
add_custom_command(
OUTPUT ${UML_OUTPUT}
COMMAND ${PLANTUML_EXECUTABLE} -tsvg ${UML_FILE}
DEPENDS ${UML_FILE}
COMMENT "Generating UML diagram ${UML_NAME}.svg"
VERBATIM
)
list(APPEND UML_OUTPUTS ${UML_OUTPUT})
endforeach()
add_custom_target(docs_uml ALL DEPENDS ${UML_OUTPUTS})
endif()

232
LICENSE
View File

@ -1,232 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://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.
qtrocket2
Copyright (C) 2025 travis
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 <https://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:
qtrocket2 Copyright (C) 2025 travis
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 <https://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 <https://www.gnu.org/philosophy/why-not-lgpl.html>.

90
docs/BIGIDEA.md Executable file
View File

@ -0,0 +1,90 @@
# ? Problem Statement: Rocket Design and Flight Simulation Application
## Overview
There is a critical need for an intuitive, extensible, and technically rigorous software application
that empowers hobbyists, students, certification candidates, and early-career engineers to design,
simulate, and optimize low-power, mid-power, high-power, and amateur-class rockets. The tool must
emphasize accessibility, modularity, and educational transparency, and be written in clean,
modern C++ using an object-oriented architecture. It must support both immediate practical needs
(rocket design, flight prediction) and deeper study of aerospace physics and software engineering
principles.
The platform must remain open-source, support .ork file compatibility, and operate reliably across
Linux, Mac, and Windows environments.
## Goals
- **Modern Design Tools**: Allow users to easily create and modify rocket models, specifying
parameters like airframes, mass properties, center of gravity (CG), center of pressure (CP),
propulsion systems, and aerodynamic surfaces.
- **Physics-Based Flight Simulation**: Simulate rocket flight through launch, coast, apogee, descent,
and recovery, using accurate force models (thrust, drag, gravity, weather effects).
- **Extensible Simulation Architecture**: Architect the system to initially support
3 Degree-of-Freedom (3-DoF) simulations, but natively prepare for future extension to 6-DoF
(full 3D translation and rotation dynamics) without major rework.
- **Educational Transparency**: Build the codebase to be highly readable, logically organized, and
deeply documented, promoting learning about flight dynamics and systems modeling.
- **Component Modularity**: Each rocket component (e.g., motors, fins, payloads, recovery systems)
must exist as independent, interchangeable modules.
- **Visualization**: Provide meaningful visual outputs, including:
- 2D/3D trajectory plots
- Stability margin graphs (e.g., CG-CP margin over time)
- Thrust, velocity, and altitude vs. time graphs
- **Certification-Ready Fidelity**: Achieve simulation fidelity that can support Tripoli Rocketry
Association and NAR Level 3 certification requirements.
- **Competitive Capability**: Aim to function as a drop-in replacement or superior alternative to
tools like OpenRocket and RockSim Pro.
- **Cross-Platform Support**: Deliver fully supported builds on Linux, Mac, and Windows.
## User Personas
- **Hobbyist Rocketeer**: Designs and refines personal rockets, needing accuracy and usability
without extensive technical setup.
- **High School/University Student**: Builds rockets for courses, competitions, or research projects,
using simulation to test and verify designs.
- **STEM Educator**: Leverages the tool in classrooms to teach core concepts of dynamics, propulsion,
aerodynamics, and systems engineering.
- **Certification Candidate (NAR/Tripoli)**: Designs rockets intended for Level 1, 2, or 3
certification and needs trustworthy simulation results.
- **Aerospace Engineering Student/Professional**: Uses the tool to prototype amateur designs, and
values modular, clear, and modern C++ code.
## Operating Constraints
- **Language**: Must be written in modern C++ (C++17 or newer) with strong attention to modularity,
memory safety, and performance.
- **Portability**: Must fully support Linux, Mac, and Windows platforms with minimal
platform-specific code.
- **Open Source**: Must be licensed under a permissive open-source license (e.g., MIT or BSD
3-clause) to encourage adoption, study, and contribution.
- **File Format Compatibility**: Must support import/export of OpenRocket (.ork) files, ensuring
interoperability with existing hobbyist ecosystems.
- **Performance**: Must run smoothly on consumer-grade hardware and support both interactive design
work and batch simulation runs for optimization.
- **Incremental Upgrades**: Initial release will support 3-DoF dynamics (translational motion only)
but architecture must cleanly allow extension to full 6-DoF dynamics (translational + rotational
motion).
## User Interface Requirements
- **Modular Design**: The UI should be modular, allowing for easy addition of new features and
components without breaking existing functionality.
- **Intuitive Interaction**: The interface should be intuitive and user-friendly, with clear
labels, tooltips, and responsive design.

0
docs/Doxyfile Normal file
View File

35
docs/flight_sequence.puml Normal file
View File

@ -0,0 +1,35 @@
@startuml
participant "FlightSimulator" as FS
participant "Rocket" as Rocket
participant "Stage" as Stage
participant "Motor" as Motor
participant "ForcesModel" as FM
participant "Environment" as Env
participant "Integrator" as Integrator
participant "FlightState" as State
participant "RecoverySystem" as Recovery
== Launch Preparation ==
FS -> Rocket: prepareForFlight(environment)
== Launch Simulation ==
loop simulation time steps
FS -> Stage: updateMotors(deltaTime)
FS -> FM: computeNetForce(State)
FM -> Rocket: query mass/CG
FM -> Env: get air density, gravity
FM -> Motor: get thrust
FS -> Integrator: step(State, netForce, deltaTime)
Integrator -> Rocket: query mass
FS -> Rocket: applyFlightState(State)
alt FS -> Rocket: check for burnout, apogee, recovery deployment
Rocket -> RecoverySystem: checkDeploymentCondition
end
== Landing ==
FS -> FlightState: detect low altitude and low vertical velocity
note over FS
End simulation after landing detected
end note
@enduml

1
docs/flight_sequence.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 19 KiB

15
docs/plotting_system.puml Normal file
View File

@ -0,0 +1,15 @@
@startuml
abstract class Plotter {
{abstract} +plot2D()
{abstract} +addMarker()
{abstract} +plotPosVelAcc()
}
class MatplotlibPlotter {
+plot2D()
+addMarker()
+plotPosVelAcc()
}
Plotter <|-- MatplotlibPlotter
@enduml

51
docs/rocket_system.puml Normal file
View File

@ -0,0 +1,51 @@
@startuml
class Rocket {
+addStage()
+updateMassProperties()
+prepareForFlight()
+applyFlightState()
+getTotalMass()
+getCenterOfGravity()
+getCenterOfPressure()
}
class Stage {
+addMotor()
+setAirframe()
+setFinSet()
+setRecoverySystem()
+updateMassProperties()
+getTotalThrust()
}
class Motor {
+addThrustDataPoint()
+ignite()
+update()
+getCurrentThrust()
}
class Airframe {
+getLength()
+getReferenceArea()
}
class FinSet {
+calculateNormalForceCoefficient()
+calculateCenterOfPressure()
+calculateDragArea()
+calculateMass()
}
class RecoverySystem {
+checkDeploymentCondition()
+deploy()
+isDeployed()
}
Rocket "1" *-- "*" Stage
Stage "1" *-- "*" Motor
Stage "1" *-- "0..1" Airframe
Stage "1" *-- "0..1" FinSet
Stage "1" *-- "0..1" RecoverySystem
@enduml

52
docs/simulation_core.puml Normal file
View File

@ -0,0 +1,52 @@
@startuml
class FlightSimulator {
+run()
+step()
+initialize()
+handleEvents()
+checkTermination()
+updateMotors()
}
class ForcesModel {
+computeNetForce()
+computeNetMoment()
+computeThrust()
+computeAerodynamicDrag()
+computeGravity()
}
class FlightState {
+getPosition()
+setPosition()
+getVelocity()
+setVelocity()
+getAcceleration()
+setAcceleration()
+getOrientation()
+setOrientation()
+getAngularVelocity()
+setAngularVelocity()
+getTime()
+setTime()
}
class Environment {
+getAirDensity()
+getGravity()
}
class Integrator {
+step()
+eulerIntegration()
}
FlightSimulator --> ForcesModel
FlightSimulator --> Integrator
FlightSimulator --> FlightState
FlightSimulator --> Environment
ForcesModel --> Rocket
ForcesModel --> Environment
Integrator --> Rocket
Integrator --> ForcesModel
@enduml

View File

@ -0,0 +1,147 @@
// examples/basic_flight_simulation.cpp
#include <iostream>
#include <memory>
// Include headers
#include "Rocket.h"
#include "Stage.h"
#include "Motor.h"
#include "Airframe.h"
#include "FinSet.h"
#include "RecoverySystem.h"
#include "FlightSimulator.h"
#include "Environment.h"
#include "FlightState.h"
#include "ForcesModel.h"
#include "Integrator.h"
#include "plotting/MatplotlibPlotter.h"
int main() {
// Create environment: sea level, 15?C
auto environment = std::make_shared<Environment>(
101325.0, // surface pressure (Pa)
288.15, // surface temperature (K)
0.0 // launch altitude (m)
);
// Build Rocket
auto rocket = std::make_shared<Rocket>("Test Rocket");
// Build Stage
auto stage = std::make_unique<Stage>("First Stage");
// Add Motor
auto motor = std::make_unique<Motor>("F50",
0.050, // 50 grams of propellant
50.0 // total impulse (Ns)
);
// Simple thrust curve (linear ramp-up and down)
motor->addThrustDataPoint(0.0, 0.0);
motor->addThrustDataPoint(0.1, 50.0);
motor->addThrustDataPoint(1.5, 50.0);
motor->addThrustDataPoint(1.6, 0.0);
stage->addMotor(std::move(motor));
// Add Airframe
auto airframe = std::make_unique<Airframe>("Standard Tube",
1.0, // length (m)
0.1, // diameter (m)
1.2, // dry mass (kg)
0.75 // drag coefficient (unitless)
);
stage->setAirframe(std::move(airframe));
// Add FinSet
auto finset = std::make_unique<FinSet>("Tri-Fins",
3, // number of fins
0.15, // root chord (m)
0.10, // tip chord (m)
0.10, // span (m)
0.05, // sweep length (m)
0.003, // thickness (m)
500.0 // material density (kg/m3)
);
stage->setFinSet(std::move(finset));
// Add Recovery System
auto recovery = std::make_unique<RecoverySystem>("Main Parachute",
RecoverySystem::DeploymentType::Apogee,
0.0, // trigger value not needed for apogee deploy
1.5, // drag coefficient (very large for parachutes)
1.0 // reference area (m2)
);
stage->setRecoverySystem(std::move(recovery));
// Finalize Rocket
rocket->addStage(std::move(stage));
rocket->updateMassProperties();
// Setup Simulation
FlightSimulator simulator(rocket, environment);
// Run simulation
simulator.run(30.0, 0.01); // 30 seconds max, 10ms timestep
// Output simple telemetry
const auto& flightLog = simulator.getFlightLog();
MatplotlibPlotter plotter;
// Build flight data vectors
std::vector<double> time, altitude, velocity, acceleration;
for (const auto& state : flightLog) {
time.push_back(state.getTime());
altitude.push_back(state.getPosition()[2]);
velocity.push_back(state.getVelocity()[2]);
acceleration.push_back(state.getAcceleration()[2]);
}
// --- Detect Apogee ---
double maxAltitude = 0.0;
double apogeeTime = 0.0;
for (const auto& state : flightLog) {
double alt = state.getPosition()[2];
if (alt > maxAltitude) {
maxAltitude = alt;
apogeeTime = state.getTime();
}
}
plotter.addMarker(apogeeTime, "Apogee");
// --- Detect Motor Burnout ---
// (Simple version: find when thrust becomes near zero)
bool burnoutDetected = false;
for (size_t i = 0; i < flightLog.size(); ++i) {
if (i == 0) continue; // skip first entry
double velPrev = flightLog[i-1].getVelocity()[2];
double velCurr = flightLog[i].getVelocity()[2];
// If velocity was increasing and then starts decreasing significantly
if (velPrev > velCurr + 1.0) { // "significant" drop
plotter.addMarker(flightLog[i].getTime(), "Motor Burnout (inferred)");
burnoutDetected = true;
break;
}
}
if (!burnoutDetected) {
std::cout << "Warning: Motor burnout not detected automatically.\n";
}
// --- Plot Altitude vs Time ---
plotter.plot2D(time, altitude, "Altitude vs Time", "Time (s)", "Altitude (m)");
// --- Plot Velocity vs Time ---
plotter.plot2D(time, velocity, "Velocity vs Time", "Time (s)", "Velocity (m/s)");
// --- Plot Acceleration vs Time ---
plotter.plot2D(time, acceleration, "Acceleration vs Time", "Time (s)", "Acceleration (m/s2)");
plotter.plotPosVelAcc(time, altitude, velocity, acceleration);
return 0;
}

81
include/Airframe.h Normal file
View File

@ -0,0 +1,81 @@
#ifndef AIRFRAME_H
#define AIRFRAME_H
#include <string>
/**
* @brief Represents the structural body and aerodynamic shell of a rocket stage.
*
* The Airframe class manages geometric dimensions, mass properties,
* and aerodynamic characteristics needed for simulation.
*/
class Airframe {
public:
/**
* @brief Constructs a new Airframe.
* @param name Name of the airframe component.
* @param length Total length of the airframe (meters).
* @param diameter Maximum body diameter (meters).
* @param dryMass Dry mass of the airframe structure (kilograms).
* @param dragCoefficient Estimated drag coefficient (unitless).
*/
Airframe(const std::string& name,
double length,
double diameter,
double dryMass,
double dragCoefficient);
/**
* @brief Default destructor.
*/
~Airframe() = default;
/**
* @brief Gets the total length of the airframe.
* @return Length in meters.
*/
double getLength() const;
/**
* @brief Gets the maximum diameter of the airframe.
* @return Diameter in meters.
*/
double getDiameter() const;
/**
* @brief Gets the dry mass of the airframe.
* @return Mass in kilograms.
*/
double getDryMass() const;
/**
* @brief Gets the aerodynamic drag coefficient.
* @return Drag coefficient (dimensionless).
*/
double getDragCoefficient() const;
/**
* @brief Calculates the reference area for drag computation.
*
* Reference area = Pi * (diameter / 2)^2
*
* @return Cross-sectional area in square meters.
*/
double getReferenceArea() const;
/**
* @brief Gets the name of the airframe.
* @return Name as a constant reference.
*/
const std::string& getName() const;
private:
std::string name_; ///< Name of the airframe.
double length_; ///< Total length [m].
double diameter_; ///< Maximum diameter [m].
double dryMass_; ///< Structural dry mass [kg].
double dragCoefficient_; ///< Drag coefficient (Cd).
};
#endif // AIRFRAME_H

79
include/Environment.h Normal file
View File

@ -0,0 +1,79 @@
#ifndef ENVIRONMENT_H
#define ENVIRONMENT_H
/**
* @brief Models atmospheric and gravitational conditions for the flight simulation.
*
* The Environment class provides atmospheric properties (air density, pressure, temperature)
* and gravity based on altitude. Future versions may support wind models.
*/
class Environment {
public:
/**
* @brief Constructs a new Environment.
* @param surfacePressure Surface pressure at launch site (Pascals).
* @param surfaceTemperature Surface temperature at launch site (Kelvin).
* @param launchAltitude Launch site altitude (meters above sea level).
*/
Environment(double surfacePressure,
double surfaceTemperature,
double launchAltitude);
/**
* @brief Default destructor.
*/
~Environment() = default;
/**
* @brief Returns the atmospheric density at a given altitude.
* @param altitude Altitude above sea level (meters).
* @return Air density in kg/m3.
*/
double getAirDensity(double altitude) const;
/**
* @brief Returns the gravitational acceleration at a given altitude.
* @param altitude Altitude above sea level (meters).
* @return Gravitational acceleration in m/s2.
*/
double getGravity(double altitude) const;
/**
* @brief Returns the surface pressure at launch site.
* @return Pressure in Pascals.
*/
double getSurfacePressure() const;
/**
* @brief Returns the surface temperature at launch site.
* @return Temperature in Kelvin.
*/
double getSurfaceTemperature() const;
/**
* @brief Returns the launch altitude above sea level.
* @return Altitude in meters.
*/
double getLaunchAltitude() const;
private:
double surfacePressure_; ///< Surface pressure at launch site [Pa].
double surfaceTemperature_; ///< Surface temperature at launch site [K].
double launchAltitude_; ///< Launch altitude above sea level [m].
/**
* @brief Internal method to compute standard atmosphere temperature at altitude.
* @param altitude Altitude above sea level (meters).
* @return Temperature at altitude (Kelvin).
*/
double getStandardTemperature(double altitude) const;
/**
* @brief Internal method to compute standard atmosphere pressure at altitude.
* @param altitude Altitude above sea level (meters).
* @return Pressure at altitude (Pascals).
*/
double getStandardPressure(double altitude) const;
};
#endif // ENVIRONMENT_H

87
include/FinSet.h Normal file
View File

@ -0,0 +1,87 @@
#ifndef FINSET_H
#define FINSET_H
#include <string>
/**
* @brief Represents a set of aerodynamic fins attached to a rocket stage.
*
* The FinSet class models stability contributions, drag effects,
* and center of pressure location based on fin geometry and number.
*/
class FinSet {
public:
/**
* @brief Constructs a new FinSet.
* @param name Name of the fin set.
* @param numberOfFins Number of fins in the set.
* @param rootChord Root chord length (meters).
* @param tipChord Tip chord length (meters).
* @param span Fin span (meters).
* @param sweepLength Sweep length of the fin (meters).
* @param thickness Fin thickness (meters).
* @param materialDensity Density of fin material (kg/m3).
*/
FinSet(const std::string& name,
int numberOfFins,
double rootChord,
double tipChord,
double span,
double sweepLength,
double thickness,
double materialDensity);
/**
* @brief Default destructor.
*/
~FinSet() = default;
/**
* @brief Calculates the normal force coefficient contribution of the fin set.
* @return Normal force coefficient (Cn).
*/
double calculateNormalForceCoefficient() const;
/**
* @brief Calculates the location of the center of pressure contribution of the fin set.
* @return Distance from leading edge of root chord (meters).
*/
double calculateCenterOfPressure() const;
/**
* @brief Calculates the drag area contribution of the fins.
* @return Drag area (Cd x A) in square meters.
*/
double calculateDragArea() const;
/**
* @brief Calculates the total mass of the fin set.
* @return Mass in kilograms.
*/
double calculateMass() const;
/**
* @brief Gets the name of the fin set.
* @return Fin set name as a constant reference.
*/
const std::string& getName() const;
private:
std::string name_; ///< Name of the fin set.
int numberOfFins_; ///< Number of fins in the set.
double rootChord_; ///< Root chord length [m].
double tipChord_; ///< Tip chord length [m].
double span_; ///< Span (distance from airframe to tip) [m].
double sweepLength_; ///< Sweep length (leading edge sweep) [m].
double thickness_; ///< Thickness of fin [m].
double materialDensity_; ///< Material density [kg/m3].
/**
* @brief Helper method to calculate the planform area of a single fin.
* @return Planform area in square meters.
*/
double calculateSingleFinArea() const;
};
#endif // FINSET_H

86
include/FlightSimulator.h Normal file
View File

@ -0,0 +1,86 @@
#ifndef FLIGHTSIMULATOR_H
#define FLIGHTSIMULATOR_H
#include <memory>
#include <vector>
class Rocket;
class Environment;
class ForcesModel;
class FlightState;
class Integrator;
/**
* @brief Manages the simulation of a rocket flight from launch to landing.
*
* The FlightSimulator coordinates the rocket, environment, force models,
* and numerical integration to simulate rocket flight dynamics over time.
*/
class FlightSimulator {
public:
/**
* @brief Constructs a new FlightSimulator.
* @param rocket Pointer to the rocket to simulate.
* @param environment Pointer to the launch environment.
*/
FlightSimulator(std::shared_ptr<Rocket> rocket,
std::shared_ptr<Environment> environment);
/**
* @brief Default destructor.
*/
~FlightSimulator() = default;
/**
* @brief Runs the full flight simulation.
* @param maxSimulationTime Maximum allowable simulation time (seconds).
* @param timeStep Initial time step for integration (seconds).
*/
void run(double maxSimulationTime, double timeStep);
/**
* @brief Returns the recorded flight states over time.
* @return Vector of FlightState snapshots.
*/
const std::vector<FlightState>& getFlightLog() const;
private:
std::shared_ptr<Rocket> rocket_; ///< Rocket being simulated.
std::shared_ptr<Environment> environment_; ///< Atmospheric and gravity conditions.
std::shared_ptr<ForcesModel> forcesModel_; ///< Computes forces and moments on the rocket.
std::unique_ptr<Integrator> integrator_; ///< Integrates equations of motion.
std::vector<FlightState> flightLog_; ///< Time history of flight state snapshots.
bool hasLaunched_ = false; ///< Have we left the lauch pad/rail?
/**
* @brief Initializes simulation (prepare rocket, set initial conditions).
*/
void initialize();
/**
* @brief Advances the simulation by one time step.
* @param deltaTime The time step size (seconds).
*/
void step(double deltaTime);
/**
* @brief Detects and processes key events (burnout, separation, recovery).
* @param state Current flight state.
*/
void handleEvents(FlightState& state);
/**
* @brief Checks if simulation termination conditions are met (e.g., landed).
* @param state Current flight state.
* @return True if simulation should stop.
*/
bool checkTermination(const FlightState& state);
void updateMotors(double deltaTime);
};
#endif // FLIGHTSIMULATOR_H

102
include/FlightState.h Normal file
View File

@ -0,0 +1,102 @@
#ifndef FLIGHTSTATE_H
#define FLIGHTSTATE_H
#include <array>
/**
* @brief Represents the physical state of the rocket at a given simulation time.
*
* The FlightState contains position, velocity, acceleration, orientation,
* and angular velocity information, future-proofed for 6-DoF dynamics.
*/
class FlightState {
public:
/**
* @brief Default constructor. Initializes to zero state.
*/
FlightState();
/**
* @brief Gets the current position vector.
* @return Position (x, y, z) in meters.
*/
const std::array<double, 3>& getPosition() const;
/**
* @brief Sets the current position vector.
* @param pos Position (x, y, z) in meters.
*/
void setPosition(const std::array<double, 3>& pos);
/**
* @brief Gets the current velocity vector.
* @return Velocity (vx, vy, vz) in meters per second.
*/
const std::array<double, 3>& getVelocity() const;
/**
* @brief Sets the current velocity vector.
* @param vel Velocity (vx, vy, vz) in meters per second.
*/
void setVelocity(const std::array<double, 3>& vel);
/**
* @brief Gets the current acceleration vector.
* @return Acceleration (ax, ay, az) in meters per second squared.
*/
const std::array<double, 3>& getAcceleration() const;
/**
* @brief Sets the current acceleration vector.
* @param acc Acceleration (ax, ay, az) in meters per second squared.
*/
void setAcceleration(const std::array<double, 3>& acc);
/**
* @brief Gets the current orientation quaternion.
* @return Orientation quaternion (w, x, y, z).
*/
const std::array<double, 4>& getOrientation() const;
/**
* @brief Sets the current orientation quaternion.
* @param quat Orientation quaternion (w, x, y, z).
*/
void setOrientation(const std::array<double, 4>& quat);
/**
* @brief Gets the current angular velocity vector.
* @return Angular velocity (roll rate, pitch rate, yaw rate) in radians per second.
*/
const std::array<double, 3>& getAngularVelocity() const;
/**
* @brief Sets the current angular velocity vector.
* @param angVel Angular velocity (roll rate, pitch rate, yaw rate) in radians per second.
*/
void setAngularVelocity(const std::array<double, 3>& angVel);
/**
* @brief Gets the elapsed simulation time.
* @return Elapsed time in seconds.
*/
double getTime() const;
/**
* @brief Sets the elapsed simulation time.
* @param time Time in seconds.
*/
void setTime(double time);
private:
std::array<double, 3> position_; ///< (x, y, z) position in meters.
std::array<double, 3> velocity_; ///< (vx, vy, vz) velocity in m/s.
std::array<double, 3> acceleration_; ///< (ax, ay, az) acceleration in m/s2.
std::array<double, 4> orientation_; ///< Orientation quaternion (w, x, y, z).
std::array<double, 3> angularVelocity_; ///< Angular rates (roll, pitch, yaw) in rad/s.
double time_; ///< Elapsed simulation time [s].
};
#endif // FLIGHTSTATE_H

74
include/ForcesModel.h Normal file
View File

@ -0,0 +1,74 @@
#ifndef FORCESMODEL_H
#define FORCESMODEL_H
#include <array>
#include <memory>
class Rocket;
class Environment;
class FlightState;
/**
* @brief Computes aerodynamic, thrust, and gravitational forces acting on the rocket.
*
* The ForcesModel provides force and moment outputs based on the current rocket state,
* environmental conditions, and rocket configuration.
*/
class ForcesModel {
public:
/**
* @brief Constructs a new ForcesModel.
* @param rocket Pointer to the rocket configuration.
* @param environment Pointer to the simulation environment.
*/
ForcesModel(std::shared_ptr<Rocket> rocket,
std::shared_ptr<Environment> environment);
/**
* @brief Default destructor.
*/
~ForcesModel() = default;
/**
* @brief Computes the net external force vector acting on the rocket.
* @param state Current flight state.
* @return Force vector (Fx, Fy, Fz) in Newtons.
*/
std::array<double, 3> computeNetForce(const FlightState& state) const;
/**
* @brief Computes the net external moment vector acting on the rocket.
*
* Initially returns zero (for 3-DoF), but structured for 6-DoF extension.
*
* @param state Current flight state.
* @return Moment vector (Mx, My, Mz) in Newton-meters.
*/
std::array<double, 3> computeNetMoment(const FlightState& state) const;
private:
std::shared_ptr<Rocket> rocket_; ///< Rocket model reference.
std::shared_ptr<Environment> environment_; ///< Atmospheric and gravity conditions.
/**
* @brief Computes aerodynamic drag force based on velocity and rocket configuration.
* @param state Current flight state.
* @return Drag force vector (Newton).
*/
std::array<double, 3> computeAerodynamicDrag(const FlightState& state) const;
/**
* @brief Computes thrust force based on motor outputs.
* @param state Current flight state.
* @return Thrust force vector (Newton).
*/
std::array<double, 3> computeThrust(const FlightState& state) const;
/**
* @brief Computes gravitational force based on altitude and mass.
* @param state Current flight state.
* @return Gravity force vector (Newton).
*/
std::array<double, 3> computeGravity(const FlightState& state) const;
};
#endif // FORCESMODEL_H

55
include/Integrator.h Normal file
View File

@ -0,0 +1,55 @@
#ifndef INTEGRATOR_H
#define INTEGRATOR_H
#include <memory>
#include <array>
class Rocket;
class Environment;
class ForcesModel;
class FlightState;
/**
* @brief Advances the rocket's flight state using numerical integration.
*
* The Integrator uses simple time-stepping methods (e.g., Euler, RK4) to
* update position, velocity, and optionally orientation and angular velocity.
*/
class Integrator {
public:
/**
* @brief Constructs a new Integrator.
* @param rocket Pointer to the rocket being simulated.
* @param forcesModel Pointer to the forces model.
*/
Integrator(std::shared_ptr<Rocket> rocket,
std::shared_ptr<ForcesModel> forcesModel);
/**
* @brief Default destructor.
*/
~Integrator() = default;
/**
* @brief Advances the flight state forward by one time step.
* @param state The flight state to update.
* @param deltaTime Time step size (seconds).
*/
void step(FlightState& state, const std::array<double, 3>& netForce, double deltaTime);
private:
std::shared_ptr<Rocket> rocket_; ///< Rocket model reference.
std::shared_ptr<ForcesModel> forcesModel_; ///< Forces model reference.
/**
* @brief Performs simple Euler integration for translational motion.
* @param state Current flight state.
* @param netForce Force vector acting on rocket [N].
* @param deltaTime Time step size (seconds).
*/
void eulerIntegration(FlightState& state,
const std::array<double, 3>& netForce,
double deltaTime);
};
#endif // INTEGRATOR_H

98
include/Motor.h Normal file
View File

@ -0,0 +1,98 @@
#ifndef MOTOR_H
#define MOTOR_H
#include <string>
#include <vector>
#include <utility> // for std::pair
/**
* @brief Represents a rocket motor with thrust characteristics over time.
*
* The Motor class manages the thrust curve, ignition timing, burn duration,
* and remaining propellant mass of a single propulsion unit.
*/
class Motor {
public:
/**
* @brief Constructs a new Motor with a given name and mass properties.
* @param name Name of the motor.
* @param initialPropellantMass Initial mass of propellant (kg).
* @param totalImpulse Total impulse (Ns) for basic verification.
*/
Motor(const std::string& name, double initialPropellantMass, double totalImpulse);
/**
* @brief Default destructor.
*/
~Motor() = default;
/**
* @brief Adds a thrust curve data point.
*
* Should be called during setup. Time must be monotonically increasing.
*
* @param time Time since ignition (seconds).
* @param thrust Thrust at this time (Newtons).
*/
void addThrustDataPoint(double time, double thrust);
/**
* @brief Starts motor ignition (sets internal ignition time to zero).
*/
void ignite();
/**
* @brief Updates the motor status based on elapsed time.
* @param deltaTime Time step in seconds.
*/
void update(double deltaTime);
/**
* @brief Gets the current thrust output.
* @return Current thrust in Newtons.
*/
double getCurrentThrust() const;
/**
* @brief Checks whether the motor has burned out.
* @return True if burnout has occurred.
*/
bool isBurnedOut() const;
/**
* @brief Returns the remaining propellant mass.
* @return Remaining propellant mass in kilograms.
*/
double getRemainingPropellantMass() const;
/**
* @brief Gets the name of the motor.
* @return Motor name as a constant reference.
*/
const std::string& getName() const;
private:
std::string name_; ///< Name of the motor.
double initialPropellantMass_; ///< Initial propellant mass [kg].
double remainingPropellantMass_; ///< Current propellant mass [kg].
double totalImpulse_; ///< Total impulse [Ns], used for sanity checks.
std::vector<std::pair<double, double>> thrustCurve_; ///< Thrust curve (time, thrust) points.
double ignitionTime_; ///< Elapsed time since ignition [s].
bool ignited_; ///< Whether the motor has been ignited.
bool burnedOut_; ///< Whether the motor has finished burning.
double currentThrust_; ///< Cached current thrust [N].
/**
* @brief Linearly interpolates thrust from the thrust curve.
* @param time Time since ignition (seconds).
* @return Interpolated thrust (Newtons).
*/
double interpolateThrust(double time) const;
};
#endif // MOTOR_H

93
include/RecoverySystem.h Normal file
View File

@ -0,0 +1,93 @@
#ifndef RECOVERYSYSTEM_H
#define RECOVERYSYSTEM_H
#include <string>
/**
* @brief Represents a recovery system for a rocket stage.
*
* The RecoverySystem class models parachutes, drogues, or streamers
* and handles deployment logic based on flight conditions.
*/
class RecoverySystem {
public:
/**
* @brief Deployment trigger types.
*/
enum class DeploymentType {
Apogee,
Altitude,
Timer
};
/**
* @brief Constructs a new RecoverySystem.
* @param name Name of the recovery device.
* @param deploymentType Type of deployment trigger (apogee, altitude, timer).
* @param triggerValue Value associated with deployment trigger (e.g., altitude in meters or time in seconds).
* @param dragCoefficient Drag coefficient of the recovery device.
* @param referenceArea Reference area (canopy projected area) in square meters.
*/
RecoverySystem(const std::string& name,
DeploymentType deploymentType,
double triggerValue,
double dragCoefficient,
double referenceArea);
/**
* @brief Default destructor.
*/
~RecoverySystem() = default;
/**
* @brief Checks if deployment conditions are met based on flight state.
* @param altitude Current altitude above ground (meters).
* @param velocity Current vertical velocity (m/s).
* @param time Elapsed flight time (seconds).
* @param atApogee Flag indicating if rocket has reached apogee.
* @return True if deployment should occur.
*/
bool checkDeploymentCondition(double altitude, double velocity, double time, bool atApogee) const;
/**
* @brief Marks the recovery system as deployed.
*/
void deploy();
/**
* @brief Returns whether the recovery system has been deployed.
* @return True if deployed.
*/
bool isDeployed() const;
/**
* @brief Gets the drag coefficient.
* @return Drag coefficient (dimensionless).
*/
double getDragCoefficient() const;
/**
* @brief Gets the reference area.
* @return Reference area (square meters).
*/
double getReferenceArea() const;
/**
* @brief Gets the name of the recovery system.
* @return Recovery system name as a constant reference.
*/
const std::string& getName() const;
private:
std::string name_; ///< Name of the recovery system.
DeploymentType deploymentType_; ///< Deployment trigger type.
double triggerValue_; ///< Trigger value (meters for altitude, seconds for timer).
double dragCoefficient_; ///< Drag coefficient after deployment.
double referenceArea_; ///< Reference area [m2].
bool deployed_; ///< Whether the recovery system has been deployed.
};
#endif // RECOVERYSYSTEM_H

127
include/Rocket.h Normal file
View File

@ -0,0 +1,127 @@
#ifndef ROCKET_H
#define ROCKET_H
#include <string>
#include <vector>
#include <memory> // for smart pointers
// Forward declarations to keep compile times fast
class Stage;
class FlightState;
class Environment;
/**
* @brief Represents a complete rocket vehicle composed of stages, motors, and recovery systems.
*
* The Rocket class encapsulates the full vehicle configuration, including mass properties,
* center of gravity (CG), center of pressure (CP), and stability margin calculations.
* It is the central object for design, simulation, and flight state management.
*/
class Rocket {
public:
/**
* @brief Constructs a new Rocket with a given name.
* @param name The name of the rocket.
*/
Rocket(const std::string& name);
/**
* @brief Default destructor.
*/
~Rocket() = default;
/**
* @brief Returns the total mass of the rocket (including all stages and payloads).
* @return Total mass in kilograms.
*/
double getTotalMass() const;
/**
* @brief Returns the total remaining propellant mass of all motors.
* @return Propellant mass in kilograms.
*/
double getTotalPropellantMass() const;
/**
* @brief Returns the current center of gravity (CG) of the rocket.
* @return Distance from reference point (e.g., nose tip) in meters.
*/
double getCenterOfGravity() const;
/**
* @brief Returns the current center of pressure (CP) of the rocket.
* @return Distance from reference point (e.g., nose tip) in meters.
*/
double getCenterOfPressure() const;
/**
* @brief Calculates the rocket's stability margin.
*
* Defined as the normalized distance between CG and CP.
* Positive margin indicates stable configuration.
*
* @return Stability margin (calibers).
*/
double getStabilityMargin() const;
/**
* @brief Adds a new stage to the rocket.
* @param stage A unique_ptr to the Stage object to add.
*/
void addStage(std::unique_ptr<Stage> stage);
/**
* @brief Returns a const reference to the list of stages.
* @return Vector of unique_ptr to Stage objects.
*/
const std::vector<std::unique_ptr<Stage>>& getStages() const;
/**
* @brief Recalculates total mass, CG, CP, and stability margin.
*
* Should be called after any modification to the rocket structure.
*/
void updateMassProperties();
/**
* @brief Prepares the rocket for flight simulation.
*
* Typically called once at simulation setup to adjust for environmental conditions.
*
* @param env The environment (atmospheric conditions) at launch.
*/
void prepareForFlight(const Environment& env);
/**
* @brief Applies a given flight state to the rocket.
*
* Intended for advanced simulation stages, including 6-DoF dynamics.
*
* @param state The current flight state.
*/
void applyFlightState(const FlightState& state);
/**
* @brief Gets the name of the rocket.
* @return Rocket name as a constant reference.
*/
const std::string& getName() const;
/**
* @brief Sets the name of the rocket.
* @param name The new name.
*/
void setName(const std::string& name);
private:
std::string name_; ///< Name of the rocket.
std::vector<std::unique_ptr<Stage>> stages_; ///< List of rocket stages.
// Cached mass properties (updated by updateMassProperties())
double totalMass_; ///< Total mass of the rocket [kg].
double totalPropellantMass_; ///< Total remaining propellant mass [kg].
double centerOfGravity_; ///< Center of gravity location [m].
double centerOfPressure_; ///< Center of pressure location [m].
};
#endif // ROCKET_H

145
include/Stage.h Normal file
View File

@ -0,0 +1,145 @@
#ifndef STAGE_H
#define STAGE_H
#include <string>
#include <vector>
#include <memory>
class Motor;
class Airframe;
class FinSet;
class RecoverySystem;
class Environment;
class FlightState;
/**
* @brief Represents a single stage of a (potentially) multi-stage rocket.
*
* A Stage contains structural components, motors, recovery systems,
* and manages its own mass properties and separation events.
*/
class Stage {
public:
/**
* @brief Constructs a new Stage with a given name.
* @param name The name of the stage.
*/
Stage(const std::string& name);
/**
* @brief Default destructor.
*/
~Stage() = default;
/**
* @brief Adds a motor to the stage.
* @param motor A unique_ptr to the Motor object.
*/
void addMotor(std::unique_ptr<Motor> motor);
/**
* @brief Sets the airframe for the stage.
* @param airframe A unique_ptr to the Airframe object.
*/
void setAirframe(std::unique_ptr<Airframe> airframe);
/**
* @brief Sets the fin set for the stage.
* @param finSet A unique_ptr to the FinSet object.
*/
void setFinSet(std::unique_ptr<FinSet> finSet);
/**
* @brief Sets the recovery system for the stage.
* @param recovery A unique_ptr to the RecoverySystem object.
*/
void setRecoverySystem(std::unique_ptr<RecoverySystem> recovery);
/**
* @brief Returns the total mass of the stage (structure + motors + payload).
* @return Total mass in kilograms.
*/
double getTotalMass() const;
/**
* @brief Returns the current total propellant mass of all motors in the stage.
* @return Propellant mass in kilograms.
*/
double getTotalPropellantMass() const;
/**
* @brief Updates mass properties (e.g., after motor burn or separation).
*/
void updateMassProperties();
/**
* @brief Prepares the stage for flight simulation (e.g., motor ignition sequencing).
* @param env Launch environment.
*/
void prepareForFlight(const Environment& env);
/**
* @brief Updates the stage based on current flight conditions.
* @param state Current flight state.
*/
void applyFlightState(const FlightState& state);
/**
* @brief Checks if the stage should separate (e.g., after burnout or trigger).
* @return True if ready to separate.
*/
bool checkSeparationEvent() const;
/**
* @brief Checks if the recovery system should deploy (e.g., apogee, velocity triggers).
* @return True if recovery deployment condition met.
*/
bool checkRecoveryEvent() const;
/**
* @brief Gets the length of the airframe.
* @return Length in meters (0 if no airframe assigned).
*/
double getAirframeLength() const;
/**
* @brief Calculates the normal force coefficient contribution from the stage's fins.
* @return Normal force coefficient (dimensionless).
*/
double calculateNormalForceCoefficient() const;
/**
* @brief Gets the name of the stage.
* @return Stage name as a constant reference.
*/
const std::string& getName() const;
/**
* @brief Calculates the total thrust vector produced by all motors in this stage.
* @return Thrust vector (Newton) in body-fixed frame (Z-forward).
*/
std::array<double, 3> getTotalThrust() const;
// Only for testing access!
const std::vector<std::unique_ptr<Motor>>& getMotorsForTesting() const { return motors_; }
private:
std::string name_; ///< Name of the stage.
// Core Components
std::vector<std::unique_ptr<Motor>> motors_; ///< List of motors in this stage.
std::unique_ptr<Airframe> airframe_; ///< Structural body and aerodynamic surfaces.
std::unique_ptr<FinSet> finSet_; ///< Fins for aerodynamic stability.
std::unique_ptr<RecoverySystem> recoverySystem_; ///< Recovery deployment system.
// Cached Mass Properties
double totalMass_; ///< Total mass [kg].
double totalPropellantMass_; ///< Remaining propellant [kg].
// Event Flags
bool separationTriggered_; ///< Flag indicating stage separation event.
bool recoveryDeployed_; ///< Flag indicating recovery system deployment.
};
#endif // STAGE_H

View File

@ -0,0 +1,98 @@
#ifndef MATPLOTLIBPLOTTER_H
#define MATPLOTLIBPLOTTER_H
#include "Plotter.h"
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
/**
* @brief Matplotlib-cpp implementation of the Plotter interface.
*/
class MatplotlibPlotter : public Plotter {
public:
virtual ~MatplotlibPlotter() = default;
void plot2D(const std::vector<double>& xData,
const std::vector<double>& yData,
const std::string& title,
const std::string& xLabel,
const std::string& yLabel) override {
plt::figure();
plt::plot(xData, yData);
// Plot any queued markers
for (const auto& marker : markers_) {
plt::axvline(marker.first, 0.0, 1.0, {{"color", "red"}, {"linestyle", "--"}});
plt::text(marker.first, *std::max_element(yData.begin(), yData.end()),
marker.second);
}
plt::title(title);
plt::xlabel(xLabel);
plt::ylabel(yLabel);
plt::grid(true);
plt::show();
// markers_.clear();
}
void addMarker(double xValue, const std::string& label) override {
markers_.emplace_back(xValue, label);
}
void plotPosVelAcc(const std::vector<double>& time,
const std::vector<double>& altitude,
const std::vector<double>& velocity,
const std::vector<double>& acceleration) override {
plt::figure();
plt::subplot(3, 1, 1);
plt::plot(time, altitude);
plt::title("Altitude vs Time");
plt::ylabel("Altitude (m)");
plt::grid(true);
for (const auto& marker : markers_) {
plt::axvline(marker.first, 0.0, 1.0, {{"color", "red"}, {"linestyle", "--"}});
plt::text(marker.first, *std::max_element(altitude.begin(), altitude.end()),
marker.second);
}
plt::subplot(3, 1, 2);
plt::plot(time, velocity);
plt::title("Velocity vs Time");
plt::ylabel("Velocity (m/s)");
plt::grid(true);
for (const auto& marker : markers_) {
plt::axvline(marker.first, 0.0, 1.0, {{"color", "red"}, {"linestyle", "--"}});
plt::text(marker.first, *std::max_element(velocity.begin(), velocity.end()),
marker.second);
}
plt::subplot(3, 1, 3);
plt::plot(time, acceleration);
plt::title("Acceleration vs Time");
plt::xlabel("Time (s)");
plt::ylabel("Acceleration (m/s2)");
plt::grid(true);
for (const auto& marker : markers_) {
plt::axvline(marker.first, 0.0, 1.0, {{"color", "red"}, {"linestyle", "--"}});
plt::text(marker.first, *std::max_element(acceleration.begin(), acceleration.end()),
marker.second);
}
plt::tight_layout();
plt::show();
// markers_.clear();
}
private:
std::vector<std::pair<double, std::string>> markers_;
};
#endif // MATPLOTLIBPLOTTER_H

View File

@ -0,0 +1,51 @@
#ifndef PLOTTER_H
#define PLOTTER_H
#include <vector>
#include <string>
/**
* @brief Abstract interface for plotting flight data.
*/
class Plotter {
public:
virtual ~Plotter() = default;
/**
* @brief Plot a 2D line graph.
*
* @param xData Vector of x-axis values (e.g., time)
* @param yData Vector of y-axis values (e.g., altitude)
* @param title Plot title
* @param xLabel Label for x-axis
* @param yLabel Label for y-axis
*/
virtual void plot2D(const std::vector<double>& xData,
const std::vector<double>& yData,
const std::string& title,
const std::string& xLabel,
const std::string& yLabel) = 0;
/**
* @brief Add a vertical marker at a specific x-axis value.
*
* @param xValue The x position (e.g., time in seconds)
* @param label Text label to display near the marker
*/
virtual void addMarker(double xValue, const std::string& label) = 0;
/**
* @brief Plot altitude, velocity, and acceleration together on a single canvas.
*
* @param time Time points
* @param altitude Altitude (Z position)
* @param velocity Vertical velocity
* @param acceleration Vertical acceleration
*/
virtual void plotPosVelAcc(const std::vector<double>& time,
const std::vector<double>& altitude,
const std::vector<double>& velocity,
const std::vector<double>& acceleration) = 0;
};
#endif // PLOTTER_H

File diff suppressed because it is too large Load Diff

6
main.cpp Normal file
View File

@ -0,0 +1,6 @@
#include "Rocket.h"
int main(int argc, char* argv[]) {
Rocket myRocket("Test Rocket");
}

44
src/Airframe.cpp Normal file
View File

@ -0,0 +1,44 @@
// src/Airframe.cpp
#include "Airframe.h"
// Constructor
Airframe::Airframe(const std::string& name,
double length,
double diameter,
double dryMass,
double dragCoefficient)
: name_(name),
length_(length),
diameter_(diameter),
dryMass_(dryMass),
dragCoefficient_(dragCoefficient)
{}
// Public Methods
double Airframe::getLength() const {
return length_;
}
double Airframe::getDiameter() const {
return diameter_;
}
double Airframe::getDryMass() const {
return dryMass_;
}
double Airframe::getDragCoefficient() const {
return dragCoefficient_;
}
double Airframe::getReferenceArea() const {
// Reference area for drag force = ? * (d/2)^2
const double radius = diameter_ / 2.0;
return 3.14159265358979323846 * radius * radius;
}
const std::string& Airframe::getName() const {
return name_;
}

108
src/Environment.cpp Normal file
View File

@ -0,0 +1,108 @@
// src/Environment.cpp
#include "Environment.h"
#include <cmath> // For pow()
namespace {
// Constants
constexpr double R_EARTH = 6371000.0; // Earth radius (meters)
constexpr double G0 = 9.80665; // Gravity at sea level (m/s2)
constexpr double R_AIR = 287.05; // Specific gas constant for air (J/kg/K)
// US Standard Atmosphere 1976 layers up to 86 km
struct AtmosphereLayer {
double baseAltitude; // meters
double baseTemperature; // Kelvin
double basePressure; // Pascals
double lapseRate; // K/m
};
// Base layer properties precomputed
static const AtmosphereLayer AtmosphereLayers[] = {
{0.0, 288.15, 101325.0, -0.0065},
{11000.0, 216.65, 22632.06, 0.0},
{20000.0, 216.65, 5474.889, 0.001},
{32000.0, 228.65, 868.019, 0.0028},
{47000.0, 270.65, 110.906, 0.0},
{51000.0, 270.65, 66.93887, -0.0028},
{71000.0, 214.65, 3.956420, -0.002},
};
static constexpr int NumAtmosphereLayers = sizeof(AtmosphereLayers) / sizeof(AtmosphereLayer);
//const AtmosphereLayer* Environment::findAtmosphereLayer(double altitude) const {
const AtmosphereLayer* findAtmosphereLayer(double altitude) {
for (int i = NumAtmosphereLayers - 1; i >= 0; --i) {
if (altitude >= AtmosphereLayers[i].baseAltitude) {
return &AtmosphereLayers[i];
}
}
// Should never happen, but fallback
return &AtmosphereLayers[0];
}
} // namespace
// Constructor
Environment::Environment(double surfacePressure,
double surfaceTemperature,
double launchAltitude)
: surfacePressure_(surfacePressure),
surfaceTemperature_(surfaceTemperature),
launchAltitude_(launchAltitude)
{}
// Public Methods
double Environment::getAirDensity(double altitude) const {
double temp = getStandardTemperature(altitude);
double pressure = getStandardPressure(altitude);
return pressure / (R_AIR * temp);
}
double Environment::getGravity(double altitude) const {
return G0 * std::pow(R_EARTH / (R_EARTH + altitude), 2);
}
double Environment::getSurfacePressure() const {
return surfacePressure_;
}
double Environment::getSurfaceTemperature() const {
return surfaceTemperature_;
}
double Environment::getLaunchAltitude() const {
return launchAltitude_;
}
// Private Methods
double Environment::getStandardTemperature(double altitude) const {
const AtmosphereLayer* layer = findAtmosphereLayer(altitude);
double deltaH = altitude - layer->baseAltitude;
return layer->baseTemperature + layer->lapseRate * deltaH;
}
double Environment::getStandardPressure(double altitude) const {
const AtmosphereLayer* layer = findAtmosphereLayer(altitude);
double deltaH = altitude - layer->baseAltitude;
double T = getStandardTemperature(altitude);
double T0 = layer->baseTemperature;
double P0 = layer->basePressure;
double a = layer->lapseRate;
if (a == 0.0) {
// Isothermal layer
return P0 * std::exp(-G0 * deltaH / (R_AIR * T0));
} else {
// Gradient layer
return P0 * std::pow(T0 / T, (G0 / (a * R_AIR)));
}
}

75
src/FinSet.cpp Normal file
View File

@ -0,0 +1,75 @@
// src/FinSet.cpp
#include "FinSet.h"
// Constructor
FinSet::FinSet(const std::string& name,
int numberOfFins,
double rootChord,
double tipChord,
double span,
double sweepLength,
double thickness,
double materialDensity)
: name_(name),
numberOfFins_(numberOfFins),
rootChord_(rootChord),
tipChord_(tipChord),
span_(span),
sweepLength_(sweepLength),
thickness_(thickness),
materialDensity_(materialDensity)
{}
// Public Methods
double FinSet::calculateNormalForceCoefficient() const {
// Simplified thin airfoil theory estimation
// Cn_alpha ? (number of fins) * (planform area) / (reference area)
// Assume reference area (body) is much smaller for initial versions
double planformArea = calculateSingleFinArea();
double effectiveArea = numberOfFins_ * planformArea;
// Return some typical small value scaled by fin count and area
// (In reality, depends heavily on Mach number and sweep angle)
return 2.0 * effectiveArea; // Very basic approximation
}
double FinSet::calculateCenterOfPressure() const {
// Approximate aerodynamic center (x_cp) for trapezoidal fin
// Formula from Barrowman equations (simplified for low-speed flight)
double meanAerodynamicChord = (rootChord_ + tipChord_) / 2.0;
double x_leading_edge = sweepLength_; // Assume sweepLength at root
double x_cp = x_leading_edge + (meanAerodynamicChord / 2.0);
return x_cp;
}
double FinSet::calculateDragArea() const {
// Drag Area = Cd_fins * total projected area
double Cd_fin = 0.01; // Approximate for small rocket fins
double planformArea = calculateSingleFinArea();
double totalArea = numberOfFins_ * planformArea;
return Cd_fin * totalArea;
}
double FinSet::calculateMass() const {
// Volume = area * thickness
double singleArea = calculateSingleFinArea();
double volume = singleArea * thickness_;
double mass = numberOfFins_ * volume * materialDensity_;
return mass;
}
const std::string& FinSet::getName() const {
return name_;
}
// Private Methods
double FinSet::calculateSingleFinArea() const {
// Area of a trapezoid: A = 0.5 * (root + tip) * span
return 0.5 * (rootChord_ + tipChord_) * span_;
}

112
src/FlightSimulator.cpp Normal file
View File

@ -0,0 +1,112 @@
// src/FlightSimulator.cpp
#include "FlightSimulator.h"
#include "Rocket.h"
#include "Environment.h"
#include "ForcesModel.h"
#include "FlightState.h"
#include "Integrator.h"
#include "Stage.h"
#include "Motor.h"
#include <iostream> // Optional for debug output
// Constructor
FlightSimulator::FlightSimulator(std::shared_ptr<Rocket> rocket,
std::shared_ptr<Environment> environment)
: rocket_(rocket),
environment_(environment),
forcesModel_(std::make_unique<ForcesModel>(rocket, environment)),
integrator_(std::make_unique<Integrator>(rocket, forcesModel_)),
hasLaunched_(false) // <-- initialize launch flag
{}
// Public Methods
void FlightSimulator::run(double maxSimulationTime, double timeStep) {
initialize();
FlightState state;
state.setTime(0.0);
// Initial position: launch pad
state.setPosition({0.0, 0.0, environment_->getLaunchAltitude()});
state.setVelocity({0.0, 0.0, 0.0});
state.setAcceleration({0.0, 0.0, 0.0});
flightLog_.clear();
flightLog_.push_back(state);
double currentTime = 0.0;
while (currentTime < maxSimulationTime) {
step(timeStep);
const auto& latestState = flightLog_.back();
if (checkTermination(latestState)) {
break;
}
currentTime += timeStep;
}
}
const std::vector<FlightState>& FlightSimulator::getFlightLog() const {
return flightLog_;
}
// Private Methods
void FlightSimulator::initialize() {
rocket_->prepareForFlight(*environment_);
}
void FlightSimulator::step(double deltaTime) {
FlightState currentState = flightLog_.back(); // Copy latest state
updateMotors(deltaTime); // <-- motors must advance ignition timers
// Compute forces and integrate motion
auto netForce = forcesModel_->computeNetForce(currentState);
integrator_->step(currentState, netForce, deltaTime);
rocket_->applyFlightState(currentState);
handleEvents(currentState);
currentState.setTime(currentState.getTime() + deltaTime);
flightLog_.push_back(currentState);
}
void FlightSimulator::updateMotors(double deltaTime) {
for (const auto& stage : rocket_->getStages()) {
for (auto& motor : stage->getMotorsForTesting()) {
motor->update(deltaTime);
}
}
}
void FlightSimulator::handleEvents(FlightState& /*state*/) {
// TODO: Extend this to handle recovery deployment and staging events.
}
bool FlightSimulator::checkTermination(const FlightState& state) {
const double altitude = state.getPosition()[2];
const double verticalVelocity = state.getVelocity()[2];
if (!hasLaunched_) {
// Detect real liftoff: significant velocity or altitude gain
if (verticalVelocity > 5.0 || altitude > environment_->getLaunchAltitude() + 5.0) {
hasLaunched_ = true;
}
return false; // Always continue until launched
}
// After launch, normal landing detection
if (altitude <= environment_->getLaunchAltitude() + 1.0 && verticalVelocity <= 1.0) {
return true; // Landed
}
return false; // Still flying
}

63
src/FlightState.cpp Normal file
View File

@ -0,0 +1,63 @@
// src/FlightState.cpp
#include "FlightState.h"
// Constructor
FlightState::FlightState()
: position_{0.0, 0.0, 0.0},
velocity_{0.0, 0.0, 0.0},
acceleration_{0.0, 0.0, 0.0},
orientation_{1.0, 0.0, 0.0, 0.0}, // Unit quaternion by default
angularVelocity_{0.0, 0.0, 0.0},
time_(0.0)
{}
// Public Methods
const std::array<double, 3>& FlightState::getPosition() const {
return position_;
}
void FlightState::setPosition(const std::array<double, 3>& pos) {
position_ = pos;
}
const std::array<double, 3>& FlightState::getVelocity() const {
return velocity_;
}
void FlightState::setVelocity(const std::array<double, 3>& vel) {
velocity_ = vel;
}
const std::array<double, 3>& FlightState::getAcceleration() const {
return acceleration_;
}
void FlightState::setAcceleration(const std::array<double, 3>& acc) {
acceleration_ = acc;
}
const std::array<double, 4>& FlightState::getOrientation() const {
return orientation_;
}
void FlightState::setOrientation(const std::array<double, 4>& quat) {
orientation_ = quat;
}
const std::array<double, 3>& FlightState::getAngularVelocity() const {
return angularVelocity_;
}
void FlightState::setAngularVelocity(const std::array<double, 3>& angVel) {
angularVelocity_ = angVel;
}
double FlightState::getTime() const {
return time_;
}
void FlightState::setTime(double time) {
time_ = time;
}

145
src/ForcesModel.cpp Normal file
View File

@ -0,0 +1,145 @@
// src/ForcesModel.cpp
#include "ForcesModel.h"
#include "Rocket.h"
#include "Stage.h"
#include "Motor.h"
#include "Airframe.h"
#include "FinSet.h"
#include "RecoverySystem.h"
#include "Environment.h"
#include "FlightState.h"
#include <cmath> // For sqrt
// Constructor
ForcesModel::ForcesModel(std::shared_ptr<Rocket> rocket,
std::shared_ptr<Environment> environment)
: rocket_(rocket),
environment_(environment)
{}
// Public Methods
std::array<double, 3> ForcesModel::computeNetForce(const FlightState& state) const {
std::array<double, 3> netForce = {0.0, 0.0, 0.0};
// Thrust
auto thrust = computeThrust(state);
for (int i = 0; i < 3; ++i) {
netForce[i] += thrust[i];
}
// Aerodynamic Drag
auto drag = computeAerodynamicDrag(state);
for (int i = 0; i < 3; ++i) {
netForce[i] += drag[i];
}
// Gravity
auto gravity = computeGravity(state);
for (int i = 0; i < 3; ++i) {
netForce[i] += gravity[i];
}
return netForce;
}
std::array<double, 3> ForcesModel::computeNetMoment(const FlightState& /*state*/) const {
// Placeholder: No moments in basic 3-DoF model
return {0.0, 0.0, 0.0};
}
// Private Methods
std::array<double, 3> ForcesModel::computeAerodynamicDrag(const FlightState& state) const {
std::array<double, 3> dragForce = {0.0, 0.0, 0.0};
// Get air density at altitude
double altitude = state.getPosition()[2];
double airDensity = environment_->getAirDensity(altitude);
// Get velocity
const auto& velocity = state.getVelocity();
double speed = std::sqrt(velocity[0]*velocity[0] +
velocity[1]*velocity[1] +
velocity[2]*velocity[2]);
if (speed == 0.0) {
return dragForce; // No drag if stationary
}
// Drag direction is opposite to velocity
std::array<double, 3> dragDirection = {-velocity[0]/speed,
-velocity[1]/speed,
-velocity[2]/speed};
// Approximate total reference area and Cd
double totalReferenceArea = 0.0;
double effectiveDragCoefficient = 0.0;
for (const auto& stage : rocket_->getStages()) {
if (stage->getAirframeLength() > 0.0) {
totalReferenceArea += stage->getAirframeLength(); // Simple approx
effectiveDragCoefficient += 0.75; // Assume average Cd
}
}
// Recovery drag if deployed
for (const auto& stage : rocket_->getStages()) {
// Assume only one recovery system per stage for now
// (Can easily extend)
auto recovery = stage->checkRecoveryEvent(); // Would return a bool now
if (recovery) {
totalReferenceArea += 1.0; // Large area
effectiveDragCoefficient += 1.5; // Large Cd
}
}
if (totalReferenceArea <= 0.0) {
totalReferenceArea = 0.01; // Prevent division by zero
}
// Compute drag force magnitude
double dragMagnitude = 0.5 * airDensity * speed * speed *
effectiveDragCoefficient * totalReferenceArea;
// Apply direction
for (int i = 0; i < 3; ++i) {
dragForce[i] = dragMagnitude * dragDirection[i];
}
return dragForce;
}
std::array<double, 3> ForcesModel::computeThrust(const FlightState& /*state*/) const {
std::array<double, 3> thrustForce = {0.0, 0.0, 0.0};
for (const auto& stage : rocket_->getStages()) {
auto stageThrust = stage->getTotalThrust();
for (int i = 0; i < 3; ++i) {
thrustForce[i] += stageThrust[i];
}
}
return thrustForce;
}
std::array<double, 3> ForcesModel::computeGravity(const FlightState& state) const {
std::array<double, 3> gravityForce = {0.0, 0.0, 0.0};
double altitude = state.getPosition()[2];
// TODO: Make this more robust. Don't accelerate through the ground
if(altitude <= 0.0) {
return {0.0, 0.0, 0.0};
}
double g = environment_->getGravity(altitude);
double totalMass = rocket_->getTotalMass();
gravityForce[2] = -totalMass * g; // Gravity acts downward
return gravityForce;
}

60
src/Integrator.cpp Normal file
View File

@ -0,0 +1,60 @@
// src/Integrator.cpp
#include "Integrator.h"
#include "Rocket.h"
#include "ForcesModel.h"
#include "FlightState.h"
#include <array>
// Constructor
Integrator::Integrator(std::shared_ptr<Rocket> rocket,
std::shared_ptr<ForcesModel> forcesModel)
: rocket_(rocket),
forcesModel_(forcesModel)
{}
// Public Methods
void Integrator::step(FlightState& state, const std::array<double, 3>& netForce, double deltaTime) {
// Basic Euler integration for now
eulerIntegration(state, netForce, deltaTime);
}
// Private Methods
void Integrator::eulerIntegration(FlightState& state,
const std::array<double, 3>& netForce,
double deltaTime) {
// Get current values
auto position = state.getPosition();
auto velocity = state.getVelocity();
auto acceleration = state.getAcceleration();
double mass = rocket_->getTotalMass();
// Update acceleration: a = F / m
if (mass > 0.0) {
for (int i = 0; i < 3; ++i) {
acceleration[i] = netForce[i] / mass;
}
} else {
acceleration = {0.0, 0.0, 0.0}; // Safety fallback
}
// Update velocity: v = v + a * dt
for (int i = 0; i < 3; ++i) {
velocity[i] += acceleration[i] * deltaTime;
}
// Update position: x = x + v * dt
for (int i = 0; i < 3; ++i) {
position[i] += velocity[i] * deltaTime;
}
// Update state
state.setAcceleration(acceleration);
state.setVelocity(velocity);
state.setPosition(position);
}

107
src/Motor.cpp Normal file
View File

@ -0,0 +1,107 @@
#include "Motor.h"
#include <algorithm> // for std::lower_bound
// Constructor
Motor::Motor(const std::string& name, double initialPropellantMass, double totalImpulse)
: name_(name),
initialPropellantMass_(initialPropellantMass),
remainingPropellantMass_(initialPropellantMass),
totalImpulse_(totalImpulse),
ignitionTime_(0.0),
ignited_(false),
burnedOut_(false),
currentThrust_(0.0)
{}
// Public Methods
void Motor::addThrustDataPoint(double time, double thrust) {
thrustCurve_.emplace_back(time, thrust);
}
void Motor::ignite() {
ignitionTime_ = 0.0;
ignited_ = true;
burnedOut_ = false;
}
void Motor::update(double deltaTime) {
if (!ignited_ || burnedOut_) {
currentThrust_ = 0.0;
return;
}
ignitionTime_ += deltaTime;
// Check if we exceed thrust curve duration
if (!thrustCurve_.empty() && ignitionTime_ > thrustCurve_.back().first) {
burnedOut_ = true;
currentThrust_ = 0.0;
remainingPropellantMass_ = 0.0;
return;
}
// Update current thrust using interpolation
currentThrust_ = interpolateThrust(ignitionTime_);
// Estimate propellant burn proportional to impulse usage
double impulsePerSecond = totalImpulse_ / (thrustCurve_.back().first); // approximate
double propellantConsumptionRate = initialPropellantMass_ / (totalImpulse_ / impulsePerSecond);
double deltaPropellant = propellantConsumptionRate * deltaTime;
remainingPropellantMass_ = std::max(remainingPropellantMass_ - deltaPropellant, 0.0);
}
double Motor::getCurrentThrust() const {
return currentThrust_;
}
bool Motor::isBurnedOut() const {
return burnedOut_;
}
double Motor::getRemainingPropellantMass() const {
return remainingPropellantMass_;
}
const std::string& Motor::getName() const {
return name_;
}
// Private Methods
double Motor::interpolateThrust(double time) const {
if (thrustCurve_.empty()) {
return 0.0;
}
// If time is outside bounds
if (time <= thrustCurve_.front().first) {
return thrustCurve_.front().second;
}
if (time >= thrustCurve_.back().first) {
return thrustCurve_.back().second;
}
// Find the two points around the current time
auto it = std::lower_bound(thrustCurve_.begin(), thrustCurve_.end(), std::make_pair(time, 0.0),
[](const std::pair<double, double>& a, const std::pair<double, double>& b) {
return a.first < b.first;
});
if (it == thrustCurve_.begin()) {
return it->second;
}
auto itPrev = std::prev(it);
double t0 = itPrev->first;
double t1 = it->first;
double f0 = itPrev->second;
double f1 = it->second;
// Linear interpolation
double thrust = f0 + (f1 - f0) * (time - t0) / (t1 - t0);
return thrust;
}

62
src/RecoverySystem.cpp Normal file
View File

@ -0,0 +1,62 @@
// src/RecoverySystem.cpp
#include "RecoverySystem.h"
// Constructor
RecoverySystem::RecoverySystem(const std::string& name,
DeploymentType deploymentType,
double triggerValue,
double dragCoefficient,
double referenceArea)
: name_(name),
deploymentType_(deploymentType),
triggerValue_(triggerValue),
dragCoefficient_(dragCoefficient),
referenceArea_(referenceArea),
deployed_(false)
{}
// Public Methods
bool RecoverySystem::checkDeploymentCondition(double altitude,
double velocity,
double time,
bool atApogee) const {
if (deployed_) {
return false; // Already deployed
}
switch (deploymentType_) {
case DeploymentType::Apogee:
return atApogee;
case DeploymentType::Altitude:
return (altitude <= triggerValue_);
case DeploymentType::Timer:
return (time >= triggerValue_);
default:
return false;
}
}
void RecoverySystem::deploy() {
deployed_ = true;
}
bool RecoverySystem::isDeployed() const {
return deployed_;
}
double RecoverySystem::getDragCoefficient() const {
return dragCoefficient_;
}
double RecoverySystem::getReferenceArea() const {
return referenceArea_;
}
const std::string& RecoverySystem::getName() const {
return name_;
}

113
src/Rocket.cpp Normal file
View File

@ -0,0 +1,113 @@
#include "Rocket.h"
#include "Stage.h"
#include "Environment.h"
#include "FlightState.h"
#include "Airframe.h"
#include "FinSet.h"
#include "RecoverySystem.h"
#include "Motor.h"
#include <numeric> // for std::accumulate
// Constructor
Rocket::Rocket(const std::string& name)
: name_(name),
totalMass_(0.0),
totalPropellantMass_(0.0),
centerOfGravity_(0.0),
centerOfPressure_(0.0)
{}
// Public Methods
double Rocket::getTotalMass() const {
return totalMass_;
}
double Rocket::getTotalPropellantMass() const {
return totalPropellantMass_;
}
double Rocket::getCenterOfGravity() const {
return centerOfGravity_;
}
double Rocket::getCenterOfPressure() const {
return centerOfPressure_;
}
double Rocket::getStabilityMargin() const {
// Positive margin (CG ahead of CP) indicates stability.
// Normalize by diameter or calibers if needed later.
return centerOfGravity_ - centerOfPressure_;
}
void Rocket::addStage(std::unique_ptr<Stage> stage) {
stages_.emplace_back(std::move(stage));
}
const std::vector<std::unique_ptr<Stage>>& Rocket::getStages() const {
return stages_;
}
void Rocket::updateMassProperties() {
totalMass_ = 0.0;
totalPropellantMass_ = 0.0;
centerOfGravity_ = 0.0;
centerOfPressure_ = 0.0;
if (stages_.empty()) {
return;
}
double weightedCGSum = 0.0;
double weightedCPSum = 0.0;
double currentZ = 0.0; // Assume stacking stages vertically
for (const auto& stage : stages_) {
stage->updateMassProperties();
double stageMass = stage->getTotalMass();
double stagePropellantMass = stage->getTotalPropellantMass();
totalMass_ += stageMass;
totalPropellantMass_ += stagePropellantMass;
// For center of gravity, weight by mass
weightedCGSum += (currentZ + stage->getAirframeLength() / 2.0) * stageMass;
// For center of pressure, weight by aerodynamic properties
weightedCPSum += (currentZ + stage->getAirframeLength() / 2.0) * stage->calculateNormalForceCoefficient();
currentZ += stage->getAirframeLength(); // Move up for next stage
}
centerOfGravity_ = weightedCGSum / totalMass_;
// Note: CP calculation here is a rough average based on fin normal forces
centerOfPressure_ = weightedCPSum /
std::accumulate(stages_.begin(), stages_.end(), 0.0,
[](double sum, const std::unique_ptr<Stage>& s) {
return sum + s->calculateNormalForceCoefficient();
});
}
void Rocket::prepareForFlight(const Environment& env) {
for (auto& stage : stages_) {
stage->prepareForFlight(env);
}
}
void Rocket::applyFlightState(const FlightState& state) {
for (auto& stage : stages_) {
stage->applyFlightState(state);
}
}
const std::string& Rocket::getName() const {
return name_;
}
void Rocket::setName(const std::string& name) {
name_ = name;
}

127
src/Stage.cpp Normal file
View File

@ -0,0 +1,127 @@
// src/Stage.cpp
#include "Stage.h"
#include "Motor.h"
#include "Airframe.h"
#include "FinSet.h"
#include "RecoverySystem.h"
#include "Environment.h"
#include "FlightState.h"
#include <numeric> // for std::accumulate
#include <algorithm> // for std::all_of
// Constructor
Stage::Stage(const std::string& name)
: name_(name),
totalMass_(0.0),
totalPropellantMass_(0.0),
separationTriggered_(false),
recoveryDeployed_(false)
{}
// Public Methods
void Stage::addMotor(std::unique_ptr<Motor> motor) {
motors_.emplace_back(std::move(motor));
}
void Stage::setAirframe(std::unique_ptr<Airframe> airframe) {
airframe_ = std::move(airframe);
}
void Stage::setFinSet(std::unique_ptr<FinSet> finSet) {
finSet_ = std::move(finSet);
}
void Stage::setRecoverySystem(std::unique_ptr<RecoverySystem> recovery) {
recoverySystem_ = std::move(recovery);
}
double Stage::getTotalMass() const {
return totalMass_;
}
double Stage::getTotalPropellantMass() const {
return totalPropellantMass_;
}
void Stage::updateMassProperties() {
totalMass_ = 0.0;
totalPropellantMass_ = 0.0;
// Add airframe dry mass
if (airframe_) {
totalMass_ += airframe_->getDryMass();
}
// Add motor masses
for (const auto& motor : motors_) {
totalMass_ += motor->getRemainingPropellantMass();
totalPropellantMass_ += motor->getRemainingPropellantMass();
}
// Add fin mass
if (finSet_) {
totalMass_ += finSet_->calculateMass();
}
}
void Stage::prepareForFlight(const Environment& env) {
// Ignite all motors immediately at start (for simplicity now)
for (auto& motor : motors_) {
motor->ignite();
}
}
void Stage::applyFlightState(const FlightState& state) {
// Placeholder for future advanced logic (flex, vibration)
// Currently nothing needed at 3-DoF level
}
bool Stage::checkSeparationEvent() const {
// Simple rule: if all motors burned out, stage is done
bool allBurnedOut = std::all_of(motors_.begin(), motors_.end(),
[](const std::unique_ptr<Motor>& motor) {
return motor->isBurnedOut();
});
return allBurnedOut;
}
bool Stage::checkRecoveryEvent() const {
if (!recoverySystem_ || recoverySystem_->isDeployed()) {
return false;
}
// RecoverySystem handles checking altitude, velocity, etc.
// Here we just provide example usage
return false; // Actual deployment logic will be done in FlightSimulator::handleEvents()
}
const std::string& Stage::getName() const {
return name_;
}
double Stage::getAirframeLength() const {
if (airframe_) {
return airframe_->getLength();
}
return 0.0;
}
double Stage::calculateNormalForceCoefficient() const {
if (finSet_) {
return finSet_->calculateNormalForceCoefficient();
}
return 0.0;
}
std::array<double, 3> Stage::getTotalThrust() const {
std::array<double, 3> totalThrust = {0.0, 0.0, 0.0};
for (const auto& motor : motors_) {
// For now, assume thrust always points along +Z axis
totalThrust[2] += motor->getCurrentThrust();
}
return totalThrust;
}

30
tests/test_airframe.cpp Normal file
View File

@ -0,0 +1,30 @@
// tests/test_airframe.cpp
#include "vendor/catch_amalgamated.hpp"
#include "Airframe.h"
// Bring Approx into scope
using Catch::Approx;
TEST_CASE("Airframe basic behavior", "[airframe]") {
Airframe airframe(
"TestBody",
1.5, // length meters
0.1, // diameter meters
2.0, // dry mass kg
0.75 // drag coefficient (unitless)
);
SECTION("Airframe properties are correctly initialized") {
REQUIRE(airframe.getLength() == Approx(1.5));
REQUIRE(airframe.getDiameter() == Approx(0.1));
REQUIRE(airframe.getDryMass() == Approx(2.0));
REQUIRE(airframe.getDragCoefficient() == Approx(0.75));
REQUIRE(airframe.getName() == "TestBody");
}
SECTION("Reference area calculation is correct") {
double expectedArea = 3.14159265358979323846 * (0.1/2.0) * (0.1/2.0);
REQUIRE(airframe.getReferenceArea() == Approx(expectedArea).epsilon(0.001));
}
}

44
tests/test_finset.cpp Executable file
View File

@ -0,0 +1,44 @@
// tests/test_finset.cpp
#include "vendor/catch_amalgamated.hpp"
#include "FinSet.h"
// Bring Approx into scope
using Catch::Approx;
TEST_CASE("FinSet basic behavior", "[finset]") {
FinSet finSet(
"TestFins",
3, // Number of fins
0.15, // Root chord (m)
0.10, // Tip chord (m)
0.10, // Span (m)
0.05, // Sweep length (m)
0.003, // Thickness (m)
500.0 // Material density (kg/m3)
);
SECTION("FinSet properties are initialized correctly") {
REQUIRE(finSet.getName() == "TestFins");
}
SECTION("Normal force coefficient is positive") {
double Cn = finSet.calculateNormalForceCoefficient();
REQUIRE(Cn > 0.0);
}
SECTION("Center of pressure is reasonable") {
double cp = finSet.calculateCenterOfPressure();
REQUIRE(cp > 0.0);
}
SECTION("Drag area calculation is reasonable") {
double dragArea = finSet.calculateDragArea();
REQUIRE(dragArea > 0.0);
}
SECTION("Mass calculation is reasonable") {
double mass = finSet.calculateMass();
REQUIRE(mass > 0.0);
}
}

70
tests/test_flightstate.cpp Executable file
View File

@ -0,0 +1,70 @@
// tests/test_flightstate.cpp
#include "vendor/catch_amalgamated.hpp"
#include "FlightState.h"
// Bring Approx into scope
using Catch::Approx;
TEST_CASE("FlightState basic behavior", "[flightstate]") {
FlightState state;
SECTION("Initial state values are zero or identity") {
REQUIRE(state.getPosition()[0] == Approx(0.0));
REQUIRE(state.getVelocity()[0] == Approx(0.0));
REQUIRE(state.getAcceleration()[0] == Approx(0.0));
REQUIRE(state.getOrientation()[0] == Approx(1.0)); // w component of unit quaternion
REQUIRE(state.getOrientation()[1] == Approx(0.0));
REQUIRE(state.getTime() == Approx(0.0));
}
SECTION("Can set and get position") {
std::array<double, 3> pos = {10.0, 20.0, 30.0};
state.setPosition(pos);
REQUIRE(state.getPosition()[0] == Approx(10.0));
REQUIRE(state.getPosition()[1] == Approx(20.0));
REQUIRE(state.getPosition()[2] == Approx(30.0));
}
SECTION("Can set and get velocity") {
std::array<double, 3> vel = {1.0, 2.0, 3.0};
state.setVelocity(vel);
REQUIRE(state.getVelocity()[0] == Approx(1.0));
REQUIRE(state.getVelocity()[1] == Approx(2.0));
REQUIRE(state.getVelocity()[2] == Approx(3.0));
}
SECTION("Can set and get acceleration") {
std::array<double, 3> acc = {-1.0, -2.0, -3.0};
state.setAcceleration(acc);
REQUIRE(state.getAcceleration()[0] == Approx(-1.0));
REQUIRE(state.getAcceleration()[1] == Approx(-2.0));
REQUIRE(state.getAcceleration()[2] == Approx(-3.0));
}
SECTION("Can set and get orientation") {
std::array<double, 4> quat = {0.707, 0.0, 0.707, 0.0}; // 90? rotation around Y axis
state.setOrientation(quat);
REQUIRE(state.getOrientation()[0] == Approx(0.707));
REQUIRE(state.getOrientation()[2] == Approx(0.707));
}
SECTION("Can set and get angular velocity") {
std::array<double, 3> angVel = {0.01, 0.02, 0.03};
state.setAngularVelocity(angVel);
REQUIRE(state.getAngularVelocity()[0] == Approx(0.01));
REQUIRE(state.getAngularVelocity()[1] == Approx(0.02));
REQUIRE(state.getAngularVelocity()[2] == Approx(0.03));
}
SECTION("Can set and get time") {
state.setTime(5.5);
REQUIRE(state.getTime() == Approx(5.5));
}
}

2
tests/test_main.cpp Normal file
View File

@ -0,0 +1,2 @@
#define CATCH_CONFIG_MAIN
#include "vendor/catch_amalgamated.hpp"

69
tests/test_motor.cpp Normal file
View File

@ -0,0 +1,69 @@
// tests/test_motor.cpp
#include "vendor/catch_amalgamated.hpp"
#include "Motor.h"
// Bring Approx into local scope
using Catch::Approx;
TEST_CASE("Motor basic behavior", "[motor]") {
Motor testMotor("TestMotor", 0.05, 50.0); // 50 grams propellant, 50 Ns impulse
SECTION("Motor should not be ignited at start") {
REQUIRE(testMotor.isBurnedOut() == false);
REQUIRE(testMotor.getCurrentThrust() == Approx(0.0));
}
SECTION("Motor thrust curve points can be added") {
testMotor.addThrustDataPoint(0.0, 0.0);
testMotor.addThrustDataPoint(0.5, 100.0);
testMotor.addThrustDataPoint(1.0, 0.0);
testMotor.ignite();
testMotor.update(0.25); // halfway to 0.5 seconds
// Should interpolate between 0 and 100 N
REQUIRE(testMotor.getCurrentThrust() > 0.0);
REQUIRE(testMotor.isBurnedOut() == false);
}
SECTION("Motor ignition starts thrust production") {
testMotor.addThrustDataPoint(0.0, 0.0);
testMotor.addThrustDataPoint(0.1, 50.0);
testMotor.addThrustDataPoint(1.5, 50.0);
testMotor.addThrustDataPoint(1.6, 0.0);
testMotor.ignite();
testMotor.update(0.1); // 100ms
REQUIRE(testMotor.getCurrentThrust() > 0.0);
REQUIRE(testMotor.isBurnedOut() == false);
}
SECTION("Motor burns out after thrust curve ends") {
testMotor.addThrustDataPoint(0.0, 0.0);
testMotor.addThrustDataPoint(0.5, 50.0);
testMotor.addThrustDataPoint(1.0, 0.0);
testMotor.ignite();
testMotor.update(2.0); // 2 seconds, way past end
REQUIRE(testMotor.isBurnedOut() == true);
REQUIRE(testMotor.getCurrentThrust() == Approx(0.0));
}
SECTION("Remaining propellant decreases over time") {
testMotor.addThrustDataPoint(0.0, 0.0);
testMotor.addThrustDataPoint(0.5, 100.0);
testMotor.addThrustDataPoint(1.0, 0.0);
testMotor.ignite();
double initialMass = testMotor.getRemainingPropellantMass();
testMotor.update(0.5); // Burn for 0.5 seconds
double remainingMass = testMotor.getRemainingPropellantMass();
REQUIRE(remainingMass < initialMass);
REQUIRE(remainingMass >= 0.0);
}
}

105
tests/test_recoverysystem.cpp Executable file
View File

@ -0,0 +1,105 @@
// tests/test_recoverysystem.cpp
#include "vendor/catch_amalgamated.hpp"
#include "RecoverySystem.h"
// Bring Approx into scope
using Catch::Approx;
TEST_CASE("RecoverySystem basic behavior", "[recoverysystem]") {
RecoverySystem apogeeRecovery(
"MainChute",
RecoverySystem::DeploymentType::Apogee,
0.0, // trigger value ignored for Apogee type
1.5, // drag coefficient
2.0 // reference area (m2)
);
RecoverySystem altitudeRecovery(
"DrogueChute",
RecoverySystem::DeploymentType::Altitude,
300.0, // trigger altitude (meters)
1.2, // drag coefficient
1.0 // reference area (m2)
);
RecoverySystem timerRecovery(
"BackupChute",
RecoverySystem::DeploymentType::Timer,
15.0, // trigger time (seconds)
1.8, // drag coefficient
1.5 // reference area (m2)
);
SECTION("RecoverySystem properties are correctly initialized") {
REQUIRE(apogeeRecovery.getName() == "MainChute");
REQUIRE(altitudeRecovery.getDragCoefficient() == Approx(1.2));
REQUIRE(timerRecovery.getReferenceArea() == Approx(1.5));
}
SECTION("Apogee deployment triggers correctly") {
bool deploy = apogeeRecovery.checkDeploymentCondition(
1000.0, // altitude
-10.0, // descending
10.0, // flight time
true // atApogee
);
REQUIRE(deploy == true);
}
SECTION("Altitude deployment triggers correctly") {
bool deployHigh = altitudeRecovery.checkDeploymentCondition(
500.0, // altitude
-10.0, // descending
10.0, // flight time
false // not necessarily at apogee
);
REQUIRE(deployHigh == false);
bool deployLow = altitudeRecovery.checkDeploymentCondition(
250.0, // below trigger altitude
-10.0, // descending
10.0, // flight time
false
);
REQUIRE(deployLow == true);
}
SECTION("Timer deployment triggers correctly") {
bool deployEarly = timerRecovery.checkDeploymentCondition(
500.0, // altitude
-10.0, // descending
10.0, // flight time (too early)
false
);
REQUIRE(deployEarly == false);
bool deployLate = timerRecovery.checkDeploymentCondition(
500.0, // altitude
-10.0, // descending
20.0, // flight time (after timer)
false
);
REQUIRE(deployLate == true);
}
SECTION("Deployment state tracks correctly") {
RecoverySystem testRecovery(
"TestChute",
RecoverySystem::DeploymentType::Apogee,
0.0,
1.5,
2.0
);
REQUIRE(testRecovery.isDeployed() == false);
testRecovery.deploy();
REQUIRE(testRecovery.isDeployed() == true);
// Once deployed, checkDeploymentCondition should return false
REQUIRE(testRecovery.checkDeploymentCondition(
1000.0, -10.0, 10.0, true) == false);
}
}

View File

@ -0,0 +1,106 @@
// tests/test_rocket_simulator.cpp
#include "vendor/catch_amalgamated.hpp"
#include "Rocket.h"
#include "Stage.h"
#include "Motor.h"
#include "Airframe.h"
#include "FinSet.h"
#include "RecoverySystem.h"
#include "Environment.h"
#include "FlightSimulator.h"
#include "FlightState.h"
#include "Integrator.h"
// Bring Approx into scope
using Catch::Approx;
TEST_CASE("Rocket and FlightSimulator integration test", "[integration]") {
// Setup Environment
auto environment = std::make_shared<Environment>(
101325.0, // surface pressure (Pa)
288.15, // surface temperature (K)
0.0 // launch altitude (m)
);
// Setup Rocket
auto rocket = std::make_shared<Rocket>("IntegrationTestRocket");
auto stage = std::make_unique<Stage>("Stage1");
// Motor
auto motor = std::make_unique<Motor>("TestMotor", 0.05, 50.0); // 50g propellant
motor->addThrustDataPoint(0.0, 0.0);
motor->addThrustDataPoint(0.1, 50.0);
motor->addThrustDataPoint(1.5, 50.0);
motor->addThrustDataPoint(1.6, 0.0);
stage->addMotor(std::move(motor));
// Airframe
auto airframe = std::make_unique<Airframe>("Airframe1",
1.5, // length
0.1, // diameter
2.0, // dry mass
0.75 // drag coefficient
);
stage->setAirframe(std::move(airframe));
// FinSet
auto finset = std::make_unique<FinSet>("TestFins",
3, // 3 fins
0.15, // root chord
0.10, // tip chord
0.10, // span
0.05, // sweep
0.003, // thickness
500.0 // density
);
stage->setFinSet(std::move(finset));
// Recovery
auto recovery = std::make_unique<RecoverySystem>("MainChute",
RecoverySystem::DeploymentType::Apogee,
0.0, // no trigger value needed
1.5, // Cd
2.0 // area
);
stage->setRecoverySystem(std::move(recovery));
rocket->addStage(std::move(stage));
rocket->updateMassProperties();
// Setup FlightSimulator
FlightSimulator simulator(rocket, environment);
SECTION("Full flight simulation runs and reaches apogee") {
simulator.run(20.0, 0.01); // Simulate 20 seconds with 10ms step
const auto& flightLog = simulator.getFlightLog();
REQUIRE(flightLog.size() > 0);
double maxAltitude = 0.0;
double landingAltitude = flightLog.back().getPosition()[2];
for (const auto& state : flightLog) {
double alt = state.getPosition()[2];
if (alt > maxAltitude) {
maxAltitude = alt;
}
}
REQUIRE(maxAltitude > 0.0); // Rocket climbed
REQUIRE(landingAltitude <= 1.0); // Rocket landed (near ground)
// Optional: check that apogee was reached early in flight
size_t apogeeIndex = 0;
for (size_t i = 1; i < flightLog.size(); ++i) {
if (flightLog[i].getPosition()[2] < flightLog[i-1].getPosition()[2]) {
apogeeIndex = i - 1;
break;
}
}
REQUIRE(apogeeIndex > 0); // Apogee was found
}
}

93
tests/test_stage.cpp Normal file
View File

@ -0,0 +1,93 @@
// tests/test_stage.cpp
#include "vendor/catch_amalgamated.hpp"
#include "Stage.h"
#include "Motor.h"
#include "Airframe.h"
#include "FinSet.h"
#include "RecoverySystem.h"
#include "Environment.h"
// Bring Approx into scope
using Catch::Approx;
TEST_CASE("Stage basic behavior", "[stage]") {
Stage stage("TestStage");
SECTION("Stage initially has zero mass and no components") {
REQUIRE(stage.getTotalMass() == Approx(0.0));
REQUIRE(stage.getTotalPropellantMass() == Approx(0.0));
REQUIRE(stage.getAirframeLength() == Approx(0.0));
REQUIRE(stage.calculateNormalForceCoefficient() == Approx(0.0));
}
SECTION("Adding a motor updates propellant mass") {
auto motor = std::make_unique<Motor>("TestMotor", 0.05, 50.0); // 50 grams
stage.addMotor(std::move(motor));
stage.updateMassProperties();
REQUIRE(stage.getTotalPropellantMass() > 0.0);
REQUIRE(stage.getTotalMass() > 0.0);
}
SECTION("Adding an airframe updates dry mass and length") {
auto airframe = std::make_unique<Airframe>("BodyTube",
1.2, // length meters
0.1, // diameter meters
1.5, // dry mass kg
0.75 // drag coefficient
);
double expectedLength = airframe->getLength();
double expectedMass = airframe->getDryMass();
stage.setAirframe(std::move(airframe));
stage.updateMassProperties();
REQUIRE(stage.getAirframeLength() == Approx(expectedLength));
REQUIRE(stage.getTotalMass() >= Approx(expectedMass));
}
SECTION("Adding fins provides stability contribution") {
auto fins = std::make_unique<FinSet>("BasicFins",
3, // 3 fins
0.15, // root chord
0.10, // tip chord
0.10, // span
0.05, // sweep length
0.003, // thickness
500.0 // material density
);
stage.setFinSet(std::move(fins));
REQUIRE(stage.calculateNormalForceCoefficient() > 0.0);
}
SECTION("Stage thrust calculation sums motor thrusts") {
auto motor1 = std::make_unique<Motor>("Motor1", 0.03, 30.0);
auto motor2 = std::make_unique<Motor>("Motor2", 0.02, 20.0);
motor1->addThrustDataPoint(0.0, 0.0);
motor1->addThrustDataPoint(0.5, 50.0);
motor1->addThrustDataPoint(1.0, 0.0);
motor2->addThrustDataPoint(0.0, 0.0);
motor2->addThrustDataPoint(0.5, 30.0);
motor2->addThrustDataPoint(1.0, 0.0);
stage.addMotor(std::move(motor1));
stage.addMotor(std::move(motor2));
stage.updateMassProperties();
stage.prepareForFlight(*(new Environment(101325.0, 288.15, 0.0))); // Dummy environment
// Simulate a half second into flight
for (auto& motor : stage.getMotorsForTesting()) {
motor->update(0.5);
}
auto thrustVector = stage.getTotalThrust();
REQUIRE(thrustVector[2] > 0.0);
}
}

11817
tests/vendor/catch_amalgamated.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

14135
tests/vendor/catch_amalgamated.hpp vendored Normal file

File diff suppressed because it is too large Load Diff