Compare commits

...

No commits in common. "f3e44efb3475d8b13dcc66eace57bedf101985af" and "2ae05214f69a93d705db8bdc178c6d5ffc388714" have entirely different histories.

55 changed files with 24713 additions and 234 deletions

5
.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
target
assets/tmp
assets/external
*.blend1
extra

4485
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

36
Cargo.toml Normal file
View file

@ -0,0 +1,36 @@
[package]
name = "outfly"
version = "0.5.3"
edition = "2021"
homepage = "https://codeberg.org/hut/outfly"
repository = "https://codeberg.org/hut/outfly"
categories = ["game", "aerospace", "simulation"]
keywords = ["game", "space", "3d"]
license = "GPL-3.0-only"
rust-version = "1.76.0"
[dependencies]
regex = "1"
bevy = { version = "0.13.1", default-features = false, features = ["jpeg", "bevy_asset", "bevy_audio", "bevy_scene", "bevy_winit", "bevy_core_pipeline", "bevy_pbr", "bevy_gltf", "bevy_render", "bevy_text", "bevy_ui", "multi-threaded", "png", "tonemapping_luts", "vorbis", "x11"]}
bevy_xpbd_3d = { version = "0.4.2", default-features = false, features = ["3d", "f64", "parry-f64", "parallel", "async-collider"] }
bevy_embedded_assets = "0.10.2"
fastrand = "2.0.2"
[features]
dev = ["bevy/dynamic_linking", "bevy/file_watcher"]
wasm = ["bevy/webgl2"]
wayland = ["bevy/wayland"]
[profile.dev]
opt-level = 1
[profile.dev.package."*"]
opt-level = 3 # high optimizations for dependencies, but not for our code
[profile.release]
lto = true
opt-level = 'z'
codegen-units = 1
incremental = false
debug = false
strip = true

232
LICENSE
View file

@ -1,232 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
outfly
Copyright (C) 2024 hut
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
outfly Copyright (C) 2024 hut
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

228
README.md
View file

@ -1,3 +1,227 @@
# outfly
# OutFly
A wholesome 3D space game in the rings of Jupiter
![screenshot](doc/images/screenshot1.jpg)
OutFly is an atmospheric, open world, 100% hard sci-fi 3D game that throws you into the [Rings of Jupiter](https://en.wikipedia.org/wiki/Rings_of_Jupiter) with a self-sufficient sportswear space suit that will take you anywhere.
Imagine a blend of [Fallout](https://en.wikipedia.org/wiki/Fallout_%28series%29) and [Outer Wilds](https://en.wikipedia.org/wiki/Outer_Wilds) with a splash of [Firefly](https://en.wikipedia.org/wiki/Firefly_%28TV_series%29), where you are free to explore the breathtaking expanse of the Jupiter system and discover what life could be like after hundreds of years of space colonization.
This game aims to respect the player as much as possible. It doesn't waste your time: Despite the vastness of space, nothing takes too long. Speed cheats are active by default, allowing you to visit places you normally couldn't, without passing out from the g-forces. There are no anxiety-causing features (apart of, maybe, space itself), no loading screens, nothing to micromanage, not even save games. You can plunge into the game any time you feel like it, and it's up to you whether you just want to soak in the beautiful scenery, engage with the survival mechanics [still in development], or dive into the game story [still in development]. And finally, it's not just DRM-free but completely open source, allowing you to tinker on any part of the game to your liking.
Key features:
- Open source forever
- Open world, realistic hard sci-fi, atmospheric, deadly
- Accurate star chart. Can you spot the constellations?
- Cross platform (verified on Linux & Windows)
- Written in [Rust](https://www.rust-lang.org) with the [Bevy game engine](https://bevyengine.org)
- Status: Early access, not much content
Links:
- [Source code](https://codeberg.org/hut/outfly)
- [itch.io page](https://wholesomevacuum.itch.io/outfly)
- [Chatroom](https://matrix.to/#/#outfly:pub.solar)
![screenshot](doc/images/screenshot2.jpg)
# Key Bindings
- Space: Slow down (or match velocity)
- AWSD/Shift/Ctrl: Accelerate
- R: Rotate (hold & move mouse)
- E: Interact: Talk to people, enter vehicles
- Q: Exit vehicle
- JKULIO: Mouseless camera rotation
- Augmented Reality: (toggle with Tab)
- Left click: Target objects
- Right click: Zoom
- Settings
- Tab: Toggle HUD/AR
- F11: Toggle fullscreen
- F: Toggle 3rd person view
- T: Toggle music
- M: Toggle sound effects
- Cheats
- G: Toggle god mode / cheats
- V/B: Impossible acceleration forward/backward
- Shift+V/B: Same as V/B, but a thousand times faster
- C: Impossibly instant stopping
# System Requirements
- Screen, keyboard
- Operating System: Linux, Windows, MacOS
- Ideally, a graphics card with Vulkan support
If your GPU does not support Vulkan, try rendering with OpenGL by setting the environment variable `WGPU_BACKEND` to `gl`, like:
```
WGPU_BACKEND=gl ./outfly
or
WGPU_BACKEND=gl cargo run
```
However, this may result in poor performance and visual glitches.
# Running OutFly
1. Download a release for your operating system at https://codeberg.org/hut/outfly/releases
2. On Linux, you need the dependency packages: `glibc libcap gcc-libs alsa-lib systemd-libs`. These are the names for ArchLinux, they may differ on your distribution.
3. Unpack and run the outfly/outfly.exe executable.
1. On Windows, just double-click on outfly.exe
2. On Linux, open the console and type this:
```
cd [path-to-extracted-outfly-directory]
./outfly
```
# Building
If there is no package for the version or operating system that you need, or if you wish to tinker on the game, you can also build outfly yourself.
For development, it's recommended to use `--features dev` to enable dynamic linking for faster compile times, e.g. like this:
```
cargo [run|build] --features dev
```
## On Linux
Install the build dependencies. On ArchLinux, it's the following, though you can replace `rust` with `rustup`:
```
pacman -S rust libx11 pkgconf alsa-lib
```
Then run the following commands, replacing `[URL]` with the clone URL of the git repository:
```
git clone [URL]
cd outfly
cargo run --release
```
NOTE: Audio is muted by default when run through `cargo run`, unless you add `--release`
## Building for Windows on Linux
```
rustup target add x86_64-pc-windows-gnu
pacman -S mingw-w64-toolchain # on ArchLinux. other distros have their equivalent package
cargo build --target=x86_64-pc-windows-gnu --release
```
More information here: https://bevy-cheatbook.github.io/setup/cross/linux-windows.html
## Building on Mac OS
Install homebrew, and then get the following dependencies:
```
brew install pkg-config molten-vk rustup
rustup-init
```
Download, compile and run the game:
```
git clone [URL]
cd outfly
cargo run --release
```
## Building for WASM/Browser
This is a work in progress, for now these are just some general hints:
```
git clone [URL]
cd outfly
rustup target install wasm32-unknown-unknown
pacman -S wasm-bindgen binaryen
mkdir outfly_wasm
cargo build --release --target wasm32-unknown-unknown
wasm-bindgen --out-name outfly --out-dir outfly_wasm --target web target/wasm32-unknown-unknown/release/outfly.wasm
wasm-opt -Oz --output wasm/outfly_bg.wasm wasm/outfly_bg.wasm
echo '<script type="module">import init from "./outfly.js"; init()</script>' > wasm/index.html
python -m http.server -d wasm
```
# Changelog
- Git:
- Implement zooming with right click (AR only)
- Implement targeting objects with left click (AR only)
- Implement matching velocity to targeted objects with space
- Implement damage from g-forces
- Implement god mode
- Fix crash by avoiding legacy fullscreen mode
- v0.5.3:
- Implement death & respawning
- Add wholesome conversation with Icarus
- Add satellite
- NPCs will now slow back down if they're pushed
- v0.5.2:
- Change BGM to Cinematic Cello by Aleksey Chistilin
- Fix vehicle exiting
- v0.5.1:
- Fix asteroid despawning
- Add cheat codes
- Add moon Thebe
- v0.5.0:
- Implement dynamically spawning asteroids all over the ring
- Changed from 32-bit to 64-bit precision physics
- Center rendering coordinate system on player to fix visual glitches
- v0.4.1: Add visible ring around Jupiter
- v0.4.0:
- Implement physics, collisions
- Implement 3rd person view
- Implement realistic camera control with pitch/yaw/rotation
- Add Galilean moons (Io, Europa, Ganymede, Callisto)
- Add light sources, better illumination of pizzeria
- Add mysterious monoliths
- v0.3.0:
- Implement vehicles
- Add MeteorAceGT racing vehicle
- Add background music "Dead Space Style Ambient Music"
- Add custom font Yupiter based on ZCOOL QingKe HuangYou
- v0.2.0:
- Add Jupiter
- Add new pizzeria model with neon sign
- Add astronaut suit model OutFly™ SecondSkyn
- Add more conversations
- Implement parser for "defs.txt" to spawn world objects and chats
- v0.1.3: Add pizzeria
- v0.1.2:
- Replace skybox with accurate star chart
- Implement conversation system
- v0.1.1: Better sky box and HUD
- v0.1.0: First release with basic controls, HUD, sounds, skybox, sun
# Credits and License
- Source code: GPL Version 3.0
- 3D models: Original art, placed under the Creative Commons CC0 License
- Photographs of celestial bodies: By NASA, public domain
- Original sound files:
- wakeup.ogg: Creative Commons CC0 License
- Other sound files: [Pixabay Content License](https://pixabay.com/service/license-summary)
- https://pixabay.com/sound-effects/typosonic-typing-192811
- https://pixabay.com/sound-effects/click-button-140881
- https://pixabay.com/sound-effects/data-transmission-sound-from-14664-72309
- https://pixabay.com/sound-effects/thrusters-loopwav-14699
- https://pixabay.com/sound-effects/rocket-loop-99748
- https://pixabay.com/sound-effects/350cc-bike-firing-32391
- https://pixabay.com/sound-effects/electricity-6353
- https://pixabay.com/sound-effects/ducati-696-monster-33217
- https://pixabay.com/sound-effects/high-energy-humming-195612
- https://pixabay.com/sound-effects/box-crash-106687
- https://pixabay.com/sound-effects/electric-fan-motor-blades-removed-13169
- Music: [Cinematic Cello](https://pixabay.com/music/build-up-scenes-cinematic-cello-115667) by [Aleksey Chistilin](https://pixabay.com/users/lexin_music-28841948/), [Pixabay Content License](https://pixabay.com/service/license-summary)
- Star chart based on the [HYG Stellar database](https://github.com/astronexus/HYG-Database)
- Font Yupiter-Regular.ttf is placed under the SIL OPEN FONT LICENSE Version 1.1 and is based on:
- Noto Sans Symbols 2, Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols)
- ZCOOL QingKe HuangYou, Copyright 2018 The ZCOOL QingKe HuangYou Project Authors (https://www.github.com/googlefonts/zcool-qingke-huangyou)
- Noto Sans SC, Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'.

2
assets/KEEP_THIS_CLEAN Normal file
View file

@ -0,0 +1,2 @@
Please remove any unneeded files in the asset directory.
The entire directory will be bundled in the release binary.

Binary file not shown.

Binary file not shown.

BIN
assets/models/asteroid.glb Normal file

Binary file not shown.

BIN
assets/models/asteroid2.glb Normal file

Binary file not shown.

BIN
assets/models/error.glb Normal file

Binary file not shown.

BIN
assets/models/lightorb.glb Normal file

Binary file not shown.

BIN
assets/models/monolith.glb Normal file

Binary file not shown.

Binary file not shown.

BIN
assets/models/moonlet.glb Normal file

Binary file not shown.

BIN
assets/models/pizzasign.glb Normal file

Binary file not shown.

BIN
assets/models/pizzeria2.glb Normal file

Binary file not shown.

BIN
assets/models/satellite.glb Normal file

Binary file not shown.

Binary file not shown.

BIN
assets/models/suit.glb Normal file

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,87 @@
#import bevy_pbr::{
mesh_view_bindings::globals,
forward_io::VertexOutput,
}
@group(2) @binding(0) var<uniform> ring_radius: f32;
@group(2) @binding(1) var<uniform> jupiter_radius: f32;
const jupiter_radius_Mm: f32 = 71.492;
const brightness = 0.025;
fn smooth_edge(start: f32, end: f32, value: f32) -> f32 {
var x: f32 = (value - start) / (end - start);
return 4 * x * x * (1 - x * x);
}
fn ring_density(radius: f32) -> f32 {
// NOTE: Keep this in sync with src/nature.rs::ring_density
// Input: distance to center of jupiter in million meters
// Output: relative brightness of the ring
let halo_inner: f32 = 92.0;
let halo_outer: f32 = 122.5;
let main_inner: f32 = 122.5;
let main_outer: f32 = 129.0;
let amalthea_inner: f32 = 129.0;
let amalthea_outer: f32 = 182.0;
let thebe_inner: f32 = 129.0;
let thebe_outer: f32 = 229.0;
let metis_notch_center: f32 = 128.0;
let metis_notch_width: f32 = 0.6;
let halo_brightness: f32 = 0.75;
let main_brightness: f32 = 1.0;
let almathea_brightness: f32 = 0.5;
let thebe_brightness: f32 = 0.5;
var density: f32 = 0.0;
if (radius >= halo_inner && radius <= halo_outer) {
density = halo_brightness * smooth_edge(halo_inner, halo_outer, radius);
} else if (radius >= main_inner && radius <= main_outer) {
var metis_notch_effect: f32 = 1.0;
if (radius > metis_notch_center - metis_notch_width * 0.5 && radius < metis_notch_center + metis_notch_width * 0.5) {
metis_notch_effect = 0.5 * (1.0 - smooth_edge(metis_notch_center - metis_notch_width * 0.5, metis_notch_center + metis_notch_width * 0.5, radius));
}
density = main_brightness * metis_notch_effect * smooth_edge(main_inner, main_outer, radius);
} else {
if (radius >= amalthea_inner && radius <= amalthea_outer) {
density = almathea_brightness * smooth_edge(amalthea_inner, amalthea_outer, radius);
}
if (radius >= thebe_inner && radius <= thebe_outer) {
density += thebe_brightness * smooth_edge(thebe_inner, thebe_outer, radius);
}
}
return density;
}
@fragment
fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
let jupiter_percent = jupiter_radius / ring_radius;
let color = vec3<f32>(0.3, 0.3, 0.3);
var alpha = brightness;
let r_uv = 2 * distance(in.uv, vec2<f32>(0.5));
let r = r_uv * ring_radius / jupiter_radius * jupiter_radius_Mm;
alpha *= ring_density(r);
alpha -= 0.001;
if alpha <= 0.0 {
return vec4<f32>(color, 0.0);
}
if in.uv[0] < 0.5 {
let dist = (0.5 - in.uv[0]) * 2.0; // 0.0=jupiter's center, 1.0=edge of the ring
let side_dist = abs(in.uv[1] - 0.5);
let cutoff = 0.5 * jupiter_percent * cos(dist);
if side_dist < cutoff {
return vec4<f32>(color, 0.0);
}
let fuzzy_boundary = 0.01;
if side_dist < cutoff + fuzzy_boundary {
return vec4<f32>(color, alpha * (side_dist - cutoff) / fuzzy_boundary);
}
}
return vec4<f32>(color, alpha);
}

BIN
assets/sounds/bikestart.ogg Normal file

Binary file not shown.

Binary file not shown.

BIN
assets/sounds/connect.ogg Normal file

Binary file not shown.

BIN
assets/sounds/crash.ogg Normal file

Binary file not shown.

Binary file not shown.

BIN
assets/sounds/ion.ogg Normal file

Binary file not shown.

BIN
assets/sounds/rocket.ogg Normal file

Binary file not shown.

BIN
assets/sounds/thruster.ogg Normal file

Binary file not shown.

Binary file not shown.

BIN
assets/sounds/wakeup.ogg Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

BIN
assets/textures/europa.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

BIN
assets/textures/io.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

BIN
assets/textures/jupiter.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

BIN
doc/images/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
doc/images/screenshot1.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

BIN
doc/images/screenshot2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

103
doc/scripts/generate_starchart.py Executable file
View file

@ -0,0 +1,103 @@
#!/usr/bin/env python
# This script requires the following file in the extra/ directory:
# https://github.com/astronexus/HYG-Database/blob/cbd21013d2bb89732b893be357a6f41836dbe614/hyg/CURRENT/hygdata_v41.csv
import csv
import sys
import math
import re
PATH = "extra/hygdata_v41.csv"
#def entry(ra_hour, ra_min, ra_sec, dec_deg, dec_min, dec_sec, mag, name, color_index):
# return [
# ra_hour*15 + ra_min*0.25 + ra_sec*0.004166,
# dec_deg + dec_min/60 + dec_sec/3600,
# mag,
# name,
# color_index,
# ]
#
#
#CUSTOM_ENTRIES = [
# entry(0, 42, 44.3, 41, 16, 9, 3.44-15, 0.63, "Andromeda Galaxy"),
#]
# Lower apparent magnitude = brighter.
# Sun = -26.7
# Sirius = -1.44
# Betelgeuse = 0.45
# Polaris (north star) = 1.97
# Meissa (orion's head, 8th brightest star in orion) = 3.33
MAX_APPARENT_MAGNITUDE = 7.0
print("// This file was autogenerated by \"genrate_starchart.py\" using data from the")
print("// HYG database: https://github.com/astronexus/HYG-Database/tree/main/hyg")
print("// License: CC BY-SA 4.0: https://creativecommons.org/licenses/by-sa/4.0/")
print("")
print("// Each star's values: [x, y, z, magnitude, color index, distance, name]")
print("pub const STARS: &[(f32; f32, f32, f32, f32, f32, str)] = &[")
def render(ra, dec, mag, ci, dist, name):
# Takes ra/deg in degrees
ra = float(ra)
dec = float(dec)
mag = float(mag)
name = re.sub(r'\s+', ' ', name)
distance = 1.0
ra_radians = math.radians(ra * 15) # ra is in [0, 24], multiplying by 15 gives degrees in [0, 360]
dec_radians = math.radians(dec)
#print(f"ra_radians={ra_radians}, dec_radians={dec_radians}, dec={dec}, ra={ra}", file=sys.stderr)
x = distance * math.cos(dec_radians) * math.cos(-ra_radians)
y = distance * math.cos(dec_radians) * math.sin(-ra_radians)
z = distance * math.sin(dec_radians)
# Correct for differences in coordinate system axes
x, y, z = x, z, y
#brightness = 2.512 ** (0 - mag)
print(f' ({x:.04}, {y:.04}, {z:.04}, {mag:.04}, {ci}, {dist}, "{name}"),')
def clean_name(string):
return "".join([c for c in string if c.isalnum() or c in ' -_'])
total = 0
count = 0
count_extra = 0
entries = []
with open(PATH, "r", encoding="utf-8") as f:
for entry in csv.DictReader(f):
entries.append(entry)
entries.sort(key=lambda entry: float(entry['mag']))
for entry in entries:
total += 1
ra = entry['ra']
dec = entry['dec']
mag = entry['mag']
ci = entry['ci']
dist = entry['dist']
name = clean_name(entry['proper'])
if not name:
name = clean_name(entry['bf'])
if not name:
name = clean_name(entry['gl'])
if not all([ra, dec, mag, ci]):
continue
if float(mag) > MAX_APPARENT_MAGNITUDE:
continue
render(ra, dec, mag, ci, dist, name)
count += 1
#for entry in CUSTOM_ENTRIES:
# render(entry[0], entry[1], entry[2], entry[3], entry[4])
# count_extra += 1
print("];")
print(f"Wrote {count} stars (total={total}) + {count_extra} extra entries.", file=sys.stderr)

32
doc/scripts/pack.sh Executable file
View file

@ -0,0 +1,32 @@
#!/bin/sh
# A script to package release binaries + README.md into zip files.
# Usage: cd outfly; doc/scripts/pack.sh
set -e
if [ "$1" == "-b" ]; then
cargo build --release
cargo build --target=x86_64-pc-windows-gnu --release
fi
VERSION="$(sed -nr 's/^\s*version\s*=\s*"(.*)"\s*$/\1/p' Cargo.toml)"
test -z "$VERSION" && echo 'Error: Could not extract version from Cargo.toml' && exit
echo "Extracted version from Cargo.toml: $VERSION"
TMPPATH=ZIP_TMP_PATH
mkdir "$TMPPATH"
cd "$TMPPATH"
SRCPATH="outfly_v$VERSION"
mkdir "$SRCPATH"
cp ../README.md "$SRCPATH"
cp ../target/x86_64-pc-windows-gnu/release/outfly.exe "$SRCPATH"
zip -v -r -9 ../"outfly_v${VERSION}_windows.zip" "$SRCPATH"
rm "$SRCPATH"/outfly.exe
cp ../target/release/outfly "$SRCPATH"
zip -v -r -9 ../"outfly_v${VERSION}_linux.zip" "$SRCPATH"
cd ..
rm -rf "$TMPPATH"

479
src/actor.rs Normal file
View file

@ -0,0 +1,479 @@
use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;
use bevy::scene::SceneInstance;
use bevy::math::DVec3;
use crate::{actor, audio, camera, chat, commands, effects, hud, nature, settings, world};
pub const ENGINE_SPEED_FACTOR: f32 = 30.0;
const MAX_TRANSMISSION_DISTANCE: f32 = 60.0;
const MAX_INTERACT_DISTANCE: f32 = 30.0;
pub struct ActorPlugin;
impl Plugin for ActorPlugin {
fn build(&self, app: &mut App) {
app.add_systems(PreUpdate, (
handle_player_death,
));
app.add_systems(FixedUpdate, (
update_physics_lifeforms,
handle_wants_maxrotation,
handle_wants_maxvelocity,
handle_gforce,
));
app.add_systems(Update, (
handle_input,
handle_collisions,
handle_damage,
));
app.add_systems(PostUpdate, (
handle_vehicle_enter_exit,
));
app.add_event::<VehicleEnterExitEvent>();
app.add_event::<PlayerDiesEvent>();
}
}
#[derive(Event)] pub struct PlayerDiesEvent;
#[derive(Event)]
pub struct VehicleEnterExitEvent {
vehicle: Entity,
driver: Entity,
is_entering: bool,
is_player: bool
}
#[derive(Component)]
pub struct Actor {
pub id: String,
pub name: Option<String>,
pub camdistance: f32,
}
impl Default for Actor {
fn default() -> Self {
Self {
id: "".to_string(),
name: None,
camdistance: 15.0,
}
}
}
#[derive(Component)]
pub struct HitPoints {
pub current: f32,
pub max: f32,
pub damage: f32,
}
impl Default for HitPoints {
fn default() -> Self {
Self {
current: 100.0,
max: 100.0,
damage: 0.0,
}
}
}
#[derive(Component)]
pub struct ExperiencesGForce {
pub gforce: f32,
pub damage_threshold: f32,
pub visual_effect_threshold: f32,
pub visual_effect: f32,
pub last_linear_velocity: DVec3,
pub ignore_gforce_seconds: f32,
}
impl Default for ExperiencesGForce { fn default() -> Self { Self {
gforce: 0.0,
damage_threshold: 100.0,
visual_effect_threshold: 20.0,
visual_effect: 0.0,
last_linear_velocity: DVec3::splat(0.0),
ignore_gforce_seconds: 0.0,
}}}
#[derive(Component)] pub struct Player; // Attached to the suit of the player
#[derive(Component)] pub struct PlayerDrivesThis; // Attached to the entered vehicle
#[derive(Component)] pub struct PlayerCamera; // Attached to the actor to use as point of view
#[derive(Component)] pub struct ActorEnteringVehicle;
#[derive(Component)] pub struct ActorVehicleBeingEntered;
#[derive(Component)] pub struct WantsMaxRotation(pub f64);
#[derive(Component)] pub struct WantsMaxVelocity(pub f64);
#[derive(Component)]
pub struct LifeForm {
pub is_alive: bool,
pub adrenaline: f32,
pub adrenaline_baseline: f32,
pub adrenaline_jolt: f32,
}
impl Default for LifeForm { fn default() -> Self { Self {
is_alive: true,
adrenaline: 0.3,
adrenaline_baseline: 0.3,
adrenaline_jolt: 0.0,
}}}
#[derive(Component)]
pub struct Vehicle {
stored_drivers_collider: Option<Collider>,
}
impl Default for Vehicle { fn default() -> Self { Self {
stored_drivers_collider: None,
}}}
#[derive(Copy, Clone, PartialEq)]
pub enum EngineType {
Monopropellant,
Rocket,
Ion,
}
#[derive(Component)]
pub struct Engine {
pub thrust_forward: f32,
pub thrust_back: f32,
pub thrust_sideways: f32,
pub reaction_wheels: f32,
pub engine_type: EngineType,
pub warmup_seconds: f32,
pub current_warmup: f32,
}
impl Default for Engine {
fn default() -> Self {
Self {
thrust_forward: 1.0,
thrust_back: 1.0,
thrust_sideways: 1.0,
reaction_wheels: 1.0,
engine_type: EngineType::Monopropellant,
warmup_seconds: 1.5,
current_warmup: 0.0,
}
}
}
#[derive(Component)]
pub struct Suit {
pub oxygen: f32,
pub power: f32,
pub oxygen_max: f32,
pub power_max: f32,
pub integrity: f32, // [0.0 - 1.0]
}
impl Default for Suit { fn default() -> Self { SUIT_SIMPLE } }
const SUIT_SIMPLE: Suit = Suit {
power: 1e5,
power_max: 1e5,
oxygen: nature::OXY_D,
oxygen_max: nature::OXY_D,
integrity: 1.0,
};
pub fn update_physics_lifeforms(
time: Res<Time>,
mut query: Query<(&mut LifeForm, &mut HitPoints, &mut Suit, &LinearVelocity)>,
) {
let d = time.delta_seconds();
for (mut lifeform, mut hp, mut suit, velocity) in query.iter_mut() {
if lifeform.adrenaline_jolt.abs() > 1e-3 {
lifeform.adrenaline_jolt *= 0.99;
}
else {
lifeform.adrenaline_jolt = 0.0
}
let speed = velocity.length();
if speed > 1000.0 {
lifeform.adrenaline += 0.001;
}
lifeform.adrenaline = (lifeform.adrenaline - 0.0001 + lifeform.adrenaline_jolt * 0.01).clamp(0.0, 1.0);
let mut oxygen_drain = nature::OXY_S;
let integr_threshold = 0.5;
if suit.integrity < integr_threshold {
// The oxygen drain from suit integrity scales with (2 - 2x)^4,
// which is a function with ~16 at x=0 and 0 at x=1.
// Furthermore, x is divided by the integrity threshold (e.g. 0.5)
// to squeeze the function horizontally, and change the range for
// the x parameter from [0-1] to [0-integritythreshold]
//
// 16 |.
// |.
// |'.
// | '.
// | '..
// |______''....
// x=0 x=1
let drain_scaling = (2.0 - 2.0 * suit.integrity / integr_threshold).powf(4.0);
oxygen_drain += suit.oxygen * 0.01 * drain_scaling;
}
suit.oxygen = (suit.oxygen - oxygen_drain*d).clamp(0.0, suit.oxygen_max);
if suit.oxygen <= 0.0 {
hp.damage += 1.0 * d;
}
}
}
pub fn handle_input(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
settings: ResMut<settings::Settings>,
q_talker: Query<(&chat::Talker, &Transform), (Without<actor::Player>, Without<Camera>)>,
player: Query<Entity, With<actor::Player>>,
q_camera: Query<&Transform, With<Camera>>,
q_vehicles: Query<(Entity, &Transform), (With<actor::Vehicle>, Without<actor::Player>, Without<Camera>)>,
mut ew_conv: EventWriter<chat::StartConversationEvent>,
mut ew_vehicle: EventWriter<VehicleEnterExitEvent>,
q_player_drives: Query<Entity, With<PlayerDrivesThis>>,
) {
if q_camera.is_empty() || player.is_empty() {
return;
}
let camtrans = q_camera.get_single().unwrap();
let player_entity = player.get_single().unwrap();
if keyboard_input.just_pressed(settings.key_interact) {
// Talking to people
let objects: Vec<(chat::Talker, &Transform)> = q_talker
.iter()
.map(|(talker, transform)| (talker.clone(), transform))
.collect();
// TODO: replace Transform.translation with Position
if let (Some(talker), dist) = camera::find_closest_target::<chat::Talker>(objects, camtrans) {
if dist <= MAX_TRANSMISSION_DISTANCE {
ew_conv.send(chat::StartConversationEvent{talker: talker.clone()});
}
}
// Entering Vehicles
if q_player_drives.is_empty() {
let objects: Vec<(Entity, &Transform)> = q_vehicles
.iter()
.collect();
if let (Some(entity), dist) = camera::find_closest_target::<Entity>(objects, camtrans) {
if dist <= MAX_INTERACT_DISTANCE {
commands.entity(entity).insert(ActorVehicleBeingEntered);
commands.entity(player_entity).insert(ActorEnteringVehicle);
ew_vehicle.send(VehicleEnterExitEvent{
vehicle: entity,
driver: player_entity,
is_entering: q_player_drives.is_empty(),
is_player: true,
});
}
}
}
}
else if keyboard_input.just_pressed(settings.key_vehicle) {
// Exiting Vehicles
for vehicle_entity in &q_player_drives {
commands.entity(vehicle_entity).insert(ActorVehicleBeingEntered);
commands.entity(player_entity).insert(ActorEnteringVehicle);
ew_vehicle.send(VehicleEnterExitEvent{
vehicle: vehicle_entity,
driver: player_entity,
is_entering: false,
is_player: true,
});
break;
}
}
}
pub fn handle_vehicle_enter_exit(
mut commands: Commands,
mut er_vehicle: EventReader<VehicleEnterExitEvent>,
mut q_drivers: Query<(Entity, &mut Visibility, Option<&Collider>), (Without<ActorVehicleBeingEntered>, With<ActorEnteringVehicle>)>,
mut q_vehicles: Query<(Entity, &mut Vehicle, &mut Visibility), (With<ActorVehicleBeingEntered>, Without<ActorEnteringVehicle>)>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
) {
for event in er_vehicle.read() {
for (driver, mut driver_vis, driver_collider) in q_drivers.iter_mut() {
if driver == event.driver {
for (vehicle, mut vehicle_component, mut vehicle_vis) in q_vehicles.iter_mut() {
if !event.is_player {
continue;
}
if vehicle == event.vehicle {
if event.is_entering {
// Entering Vehicle
if let Some(collider) = driver_collider {
vehicle_component.stored_drivers_collider = Some(collider.clone());
}
commands.entity(driver).remove::<RigidBody>();
*driver_vis = Visibility::Hidden; //seems to have no effect...
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::EnterVehicle));
commands.entity(driver).remove::<PlayerCamera>();
commands.entity(driver).remove::<Collider>();
commands.entity(vehicle).insert(PlayerCamera);
commands.entity(vehicle).insert(PlayerDrivesThis);
}
else {
// Exiting Vehicle
if let Some(collider) = &vehicle_component.stored_drivers_collider {
commands.entity(driver).insert(collider.clone());
}
commands.entity(driver).insert(RigidBody::Dynamic);
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Switch));
commands.entity(vehicle).remove::<PlayerCamera>();
commands.entity(driver).insert(PlayerCamera);
commands.entity(vehicle).remove::<PlayerDrivesThis>();
*vehicle_vis = Visibility::Visible;
}
}
}
}
}
}
}
fn handle_collisions(
mut collision_event_reader: EventReader<CollisionStarted>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
q_player: Query<(Entity, Option<&Player>), With<PlayerCamera>>,
mut q_player_lifeform: Query<(&mut LifeForm, &mut Suit), With<Player>>,
) {
if let (Ok((player, player_maybe)), Ok((mut lifeform, mut suit))) = (q_player.get_single(), q_player_lifeform.get_single_mut()) {
for CollisionStarted(entity1, entity2) in collision_event_reader.read() {
if *entity1 == player || *entity2 == player {
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Crash));
lifeform.adrenaline_jolt += 0.1;
if player_maybe.is_some() {
suit.integrity -= 0.03;
}
}
}
}
}
fn handle_wants_maxrotation(
//time: Res<Time>,
mut query: Query<(&mut AngularVelocity, &Engine, &WantsMaxRotation)>,
) {
let epsilon = 0.0001;
//let d = time.delta_seconds();
for (mut v_ang, engine, maxrot) in &mut query {
let total = v_ang.0.length();
if total <= maxrot.0 + epsilon {
if total > maxrot.0 {
v_ang.0 = DVec3::splat(0.0);
}
}
else {
let angular_slowdown: f64 = (2.0 - engine.reaction_wheels.powf(0.01).clamp(1.001, 1.1)) as f64;
v_ang.0 *= angular_slowdown;
}
}
}
fn handle_wants_maxvelocity(
time: Res<Time>,
mut query: Query<(&mut LinearVelocity, &Engine, &WantsMaxVelocity)>,
) {
let dt = time.delta_seconds();
let epsilon = 0.0001;
for (mut v, engine, maxv) in &mut query {
let total = v.0.length();
if total <= maxv.0 + epsilon {
if total > maxv.0 {
v.0 = DVec3::splat(0.0);
}
// already not moving
continue;
}
// TODO: respect engine parameters for different thrusts for different directions
let avg_thrust = (engine.thrust_forward + engine.thrust_back + engine.thrust_sideways) / 3.0;
let acceleration = (avg_thrust * dt) as f64 * -v.0;
v.0 += acceleration;
if v.0.length() + epsilon < acceleration.length() {
v.0 = DVec3::splat(0.0);
}
}
}
fn handle_player_death(
mut cmd: Commands,
mut er_playerdies: EventReader<PlayerDiesEvent>,
q_scenes: Query<(Entity, &SceneInstance), With<world::DespawnOnPlayerDeath>>,
q_noscenes: Query<Entity, (With<world::DespawnOnPlayerDeath>, Without<SceneInstance>)>,
ew_spawn: EventWriter<commands::SpawnEvent>,
mut scene_spawner: ResMut<SceneSpawner>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
mut ew_effect: EventWriter<effects::SpawnEffectEvent>,
mut log: ResMut<hud::Log>,
settings: Res<settings::Settings>,
) {
for _ in er_playerdies.read() {
if settings.god_mode {
return;
}
for entity in &q_noscenes {
cmd.entity(entity).despawn();
}
for (entity, sceneinstance) in &q_scenes {
cmd.entity(entity).despawn();
scene_spawner.despawn_instance(**sceneinstance);
}
log.clear();
//cmd.run_system(commands::load_defs); // why is it so complicated to get SystemId?
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::WakeUp));
ew_effect.send(effects::SpawnEffectEvent {
class: effects::Effects::FadeIn(Color::MAROON),
duration: 1.0,
});
commands::load_defs(ew_spawn);
return;
}
}
fn handle_damage(
mut ew_playerdies: EventWriter<PlayerDiesEvent>,
mut q_hp: Query<(&mut HitPoints, Option<&Player>), Changed<HitPoints>>,
settings: Res<settings::Settings>,
) {
for (mut hp, player_maybe) in &mut q_hp {
if player_maybe.is_some() {
if !settings.god_mode {
hp.current -= hp.damage;
}
if hp.current <= 0.0 {
ew_playerdies.send(PlayerDiesEvent);
}
}
else {
hp.current -= hp.damage;
}
hp.damage = 0.0;
}
}
fn handle_gforce(
time: Res<Time>,
mut q_actor: Query<(&LinearVelocity, &mut HitPoints, &mut ExperiencesGForce)>,
) {
let dt = time.delta_seconds();
let factor = 1.0 / dt / nature::EARTH_GRAVITY;
for (v, mut hp, mut gforce) in &mut q_actor {
gforce.gforce = factor * (v.0 - gforce.last_linear_velocity).length() as f32;
gforce.last_linear_velocity = v.0;
if gforce.ignore_gforce_seconds > 0.0 {
gforce.ignore_gforce_seconds -= dt;
continue;
}
if gforce.gforce > gforce.damage_threshold {
hp.damage += (gforce.gforce - gforce.damage_threshold).powf(2.0) / 3000.0;
}
if gforce.visual_effect > 0.0001 {
gforce.visual_effect *= 0.984;
}
else if gforce.visual_effect > 0.0 {
gforce.visual_effect = 0.0;
}
if gforce.gforce > gforce.visual_effect_threshold {
gforce.visual_effect += (gforce.gforce - gforce.visual_effect_threshold).powf(2.0) / 300000.0
}
}
}

216
src/audio.rs Normal file
View file

@ -0,0 +1,216 @@
use bevy::prelude::*;
use bevy::audio::{PlaybackMode, Volume};
use crate::settings;
const ASSET_CLICK: &str = "sounds/click-button-140881-crop.ogg";
const ASSET_SWITCH: &str = "sounds/typosonic-typing-192811-crop.ogg";
const ASSET_INCOMING_MESSAGE: &str = "sounds/connect.ogg";
const ASSET_PING: &str = "sounds/connect.ogg";
const ASSET_CONNECT: &str = "sounds/connect.ogg";
const ASSET_BGM: &str = "music/Aleksey Chistilin - Cinematic Cello.ogg";
const ASSET_THRUSTER: &str = "sounds/thruster.ogg";
const ASSET_ROCKET: &str = "sounds/rocket.ogg";
const ASSET_ION: &str = "sounds/ion.ogg";
const ASSET_WAKEUP: &str = "sounds/wakeup.ogg";
const ASSET_BIKESTART: &str = "sounds/bikestart.ogg";
const ASSET_CRASH: &str = "sounds/crash.ogg";
const ASSET_ELECTRICMOTOR: &str = "sounds/electricmotor.ogg";
pub struct AudioPlugin;
impl Plugin for AudioPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup);
app.add_systems(Update, toggle_bgm);
app.add_systems(PostUpdate, play_sfx);
app.add_systems(PostUpdate, update_music);
app.add_event::<PlaySfxEvent>();
app.add_event::<ToggleMusicEvent>();
}
}
pub enum Sfx {
IncomingChatMessage,
Click,
Switch,
Ping,
Connect,
EnterVehicle,
Crash,
WakeUp,
None,
}
#[derive(Event)] pub struct PlaySfxEvent(pub Sfx);
#[derive(Event)] pub struct ToggleMusicEvent();
#[derive(Component)] pub struct ComponentBGM;
#[derive(Component)] pub struct ComponentThrusterSound;
#[derive(Component)] pub struct ComponentRocketSound;
#[derive(Component)] pub struct ComponentIonSound;
#[derive(Component)] pub struct ComponentElectricMotorSound;
#[derive(Component)] struct SoundBGM(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundClick(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundSwitch(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundIncomingMessage(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundPing(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundConnect(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundBikeStart(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundCrash(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundWakeUp(Handle<AudioSource>);
pub fn setup(
mut commands: Commands,
settings: Res<settings::Settings>,
asset_server: Res<AssetServer>,
) {
commands.spawn((
ComponentBGM,
AudioBundle {
source: SoundBGM(asset_server.load(ASSET_BGM)).0.clone(),
settings: PlaybackSettings {
mode: PlaybackMode::Loop,
paused: settings.hud_active || settings.mute_music,
..default()
},
},
));
commands.spawn((
ComponentThrusterSound,
AudioBundle {
source: asset_server.load(ASSET_THRUSTER),
settings: PlaybackSettings {
mode: PlaybackMode::Loop,
paused: true,
..default()
},
},
));
commands.spawn((
ComponentRocketSound,
AudioBundle {
source: asset_server.load(ASSET_ROCKET),
settings: PlaybackSettings {
mode: PlaybackMode::Loop,
paused: true,
..default()
},
},
));
commands.spawn((
ComponentIonSound,
AudioBundle {
source: asset_server.load(ASSET_ION),
settings: PlaybackSettings {
mode: PlaybackMode::Loop,
paused: true,
..default()
},
},
));
commands.spawn((
ComponentElectricMotorSound,
AudioBundle {
source: asset_server.load(ASSET_ELECTRICMOTOR),
settings: PlaybackSettings {
mode: PlaybackMode::Loop,
volume: Volume::new(0.5),
paused: true,
..default()
},
},
));
commands.insert_resource(SoundClick(asset_server.load(ASSET_CLICK)));
commands.insert_resource(SoundSwitch(asset_server.load(ASSET_SWITCH)));
commands.insert_resource(SoundIncomingMessage(asset_server.load(ASSET_INCOMING_MESSAGE)));
commands.insert_resource(SoundPing(asset_server.load(ASSET_PING)));
commands.insert_resource(SoundConnect(asset_server.load(ASSET_CONNECT)));
commands.insert_resource(SoundBikeStart(asset_server.load(ASSET_BIKESTART)));
commands.insert_resource(SoundCrash(asset_server.load(ASSET_CRASH)));
commands.insert_resource(SoundWakeUp(asset_server.load(ASSET_WAKEUP)));
}
pub fn toggle_bgm(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut evwriter_toggle: EventWriter<ToggleMusicEvent>,
mut evwriter_sfx: EventWriter<PlaySfxEvent>,
mut settings: ResMut<settings::Settings>,
) {
if keyboard_input.just_pressed(KeyCode::KeyT) {
settings.mute_music ^= true;
evwriter_sfx.send(PlaySfxEvent(Sfx::Click));
evwriter_toggle.send(ToggleMusicEvent());
}
if keyboard_input.just_pressed(KeyCode::KeyM) {
settings.mute_sfx ^= true;
evwriter_sfx.send(PlaySfxEvent(Sfx::Click));
evwriter_toggle.send(ToggleMusicEvent());
}
}
pub fn play_sfx(
mut commands: Commands,
settings: Res<settings::Settings>,
mut events_sfx: EventReader<PlaySfxEvent>,
sound_click: Res<SoundClick>,
sound_switch: Res<SoundSwitch>,
sound_incoming_message: Res<SoundIncomingMessage>,
sound_ping: Res<SoundPing>,
sound_connect: Res<SoundConnect>,
sound_bikestart: Res<SoundBikeStart>,
sound_crash: Res<SoundCrash>,
sound_wakeup: Res<SoundWakeUp>,
) {
if settings.mute_sfx && !events_sfx.is_empty() {
events_sfx.clear();
}
for sfx in events_sfx.read() {
match sfx.0 {
Sfx::None => { continue; }
_ => {}
}
commands.spawn(AudioBundle {
source: match sfx.0 {
Sfx::Switch => sound_switch.0.clone(),
Sfx::Click => sound_click.0.clone(),
Sfx::IncomingChatMessage => sound_incoming_message.0.clone(),
Sfx::Ping => sound_ping.0.clone(),
Sfx::Connect => sound_connect.0.clone(),
Sfx::EnterVehicle => sound_bikestart.0.clone(),
Sfx::Crash => sound_crash.0.clone(),
Sfx::WakeUp => sound_wakeup.0.clone(),
Sfx::None => sound_ping.0.clone(),
},
settings: PlaybackSettings::DESPAWN,
});
}
}
pub fn str2sfx(sfx_label: &str) -> Sfx {
return match sfx_label {
"switch" => Sfx::Switch,
"click" => Sfx::Click,
"chat" => Sfx::IncomingChatMessage,
"ping" => Sfx::Ping,
"connect" => Sfx::Connect,
"entervehicle" => Sfx::EnterVehicle,
"crash" => Sfx::Crash,
_ => Sfx::None,
};
}
pub fn update_music(
mut events: EventReader<ToggleMusicEvent>,
bgm_controller: Query<&AudioSink, With<ComponentBGM>>,
settings: Res<settings::Settings>,
) {
if !events.is_empty() {
events.clear();
if let Ok(bgm_sink) = bgm_controller.get_single() {
if settings.mute_music {
bgm_sink.pause();
}
else {
bgm_sink.play();
}
}
}
}

419
src/camera.rs Normal file
View file

@ -0,0 +1,419 @@
use bevy::prelude::*;
use bevy::input::mouse::MouseMotion;
use bevy::window::PrimaryWindow;
use bevy::core_pipeline::bloom::{BloomCompositeMode, BloomSettings};
use bevy::core_pipeline::tonemapping::Tonemapping;
use bevy::pbr::CascadeShadowConfigBuilder;
use bevy::transform::TransformSystem;
use bevy::math::{DVec3, DQuat};
use bevy_xpbd_3d::prelude::*;
use std::f32::consts::PI;
use crate::{actor, audio, hud, settings};
pub struct CameraPlugin;
impl Plugin for CameraPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup_camera);
app.add_systems(Update, handle_input);
app.add_systems(Update, manage_player_actor.after(handle_input));
app.add_systems(PostUpdate, sync_camera_to_player
.after(PhysicsSet::Sync)
.after(apply_input_to_player)
.before(TransformSystem::TransformPropagate));
app.add_systems(Update, update_fov);
app.add_systems(PostUpdate, apply_input_to_player
.after(PhysicsSet::Sync)
.before(TransformSystem::TransformPropagate));
}
}
pub fn setup_camera(
mut commands: Commands,
) {
// Add player
commands.spawn((
Camera3dBundle {
camera: Camera {
hdr: true, // HDR is required for bloom
clear_color: ClearColorConfig::Custom(Color::BLACK),
..default()
},
tonemapping: Tonemapping::TonyMcMapface,
transform: Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
..default()
},
BloomSettings {
composite_mode: BloomCompositeMode::EnergyConserving,
..default()
},
));
// Add Light from the Sun
commands.spawn(DirectionalLightBundle {
directional_light: DirectionalLight {
illuminance: 1000.0,
shadows_enabled: false,
..default()
},
transform: Transform::from_rotation(Quat::from_rotation_y(PI/2.0)),
cascade_shadow_config: CascadeShadowConfigBuilder {
first_cascade_far_bound: 7.0,
maximum_distance: 25.0,
..default()
}
.into(),
..default()
});
}
pub fn sync_camera_to_player(
settings: Res<settings::Settings>,
mut q_camera: Query<&mut Transform, (With<Camera>, Without<actor::PlayerCamera>)>,
q_playercam: Query<(&actor::Actor, &Transform), (With<actor::PlayerCamera>, Without<Camera>)>,
) {
if q_camera.is_empty() || q_playercam.is_empty() {
return;
}
let mut camera_transform = q_camera.get_single_mut().unwrap();
let (actor, player_transform) = q_playercam.get_single().unwrap();
// Rotation
camera_transform.rotation = player_transform.rotation * Quat::from_array([0.0, -1.0, 0.0, 0.0]);
// Translation
if settings.third_person {
camera_transform.translation = player_transform.translation + camera_transform.rotation * (actor.camdistance * Vec3::new(0.0, 0.2, 1.0));
}
else {
camera_transform.translation = player_transform.translation;
}
}
pub fn update_fov(
q_player: Query<&actor::ExperiencesGForce, With<actor::Player>>,
mouse_input: Res<ButtonInput<MouseButton>>,
mut settings: ResMut<settings::Settings>,
mut q_camera: Query<&mut Projection, With<Camera>>,
) {
if let (Ok(gforce), Ok(mut projection)) = (q_player.get_single(), q_camera.get_single_mut())
{
let fov: f32;
if settings.hud_active && mouse_input.pressed(settings.key_zoom) {
fov = settings.zoom_fov.to_radians();
if !settings.is_zooming {
settings.is_zooming = true;
}
} else {
fov = (gforce.visual_effect * settings.fov_highspeed + settings.fov).to_radians();
if settings.is_zooming {
settings.is_zooming = false;
}
};
*projection = Projection::Perspective(PerspectiveProjection { fov: fov, ..default() });
}
}
pub fn handle_input(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut settings: ResMut<settings::Settings>,
) {
if keyboard_input.just_pressed(settings.key_camera) {
settings.third_person ^= true;
}
}
fn manage_player_actor(
settings: Res<settings::Settings>,
mut q_playercam: Query<&mut Visibility, With<actor::PlayerCamera>>,
mut q_hiddenplayer: Query<(&mut Visibility, &mut Position, &mut Rotation, &mut LinearVelocity, &mut AngularVelocity), (With<actor::Player>, Without<actor::PlayerCamera>)>,
q_ride: Query<(&Transform, &Position, &Rotation, &LinearVelocity, &AngularVelocity), (With<actor::PlayerDrivesThis>, Without<actor::Player>)>,
) {
for mut vis in &mut q_playercam {
if settings.third_person {
*vis = Visibility::Inherited;
}
else {
*vis = Visibility::Hidden;
}
}
for (mut vis, mut pos, mut rot, mut v, mut angv) in &mut q_hiddenplayer {
// If we are riding a vehicle, place the player at the position where
// it would be after exiting the vehicle.
// I would rather place it in the center of the vehicle, but at the time
// of writing, I couldn't set the position/rotation of the player *during*
// exiting the vehicle, so I'm doing it here instead, as a workaround.
*vis = Visibility::Hidden;
if let Ok((ride_trans, ride_pos, ride_rot, ride_v, ride_angv)) = q_ride.get_single() {
pos.0 = ride_pos.0 + DVec3::from(ride_trans.rotation * Vec3::new(0.0, 0.0, ride_trans.scale.z * 2.0));
rot.0 = ride_rot.0 * DQuat::from_array([-1.0, 0.0, 0.0, 0.0]);
*v = ride_v.clone();
*angv = ride_angv.clone();
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn apply_input_to_player(
time: Res<Time>,
settings: Res<settings::Settings>,
mut windows: Query<&mut Window, With<PrimaryWindow>>,
mut mouse_events: EventReader<MouseMotion>,
key_input: Res<ButtonInput<KeyCode>>,
thruster_sound_controller: Query<&AudioSink, With<audio::ComponentThrusterSound>>,
rocket_sound_controller: Query<&AudioSink, With<audio::ComponentRocketSound>>,
ion_sound_controller: Query<&AudioSink, With<audio::ComponentIonSound>>,
electricmotor_sound_controller: Query<&AudioSink, With<audio::ComponentElectricMotorSound>>,
q_target: Query<&LinearVelocity, (With<hud::IsTargeted>, Without<actor::PlayerCamera>)>,
mut q_playercam: Query<(
&Transform,
&mut actor::Engine,
&mut AngularVelocity,
&mut LinearVelocity,
&mut ExternalTorque,
), (With<actor::PlayerCamera>, Without<Camera>)>,
) {
let dt = time.delta_seconds();
let mut play_thruster_sound = false;
let mut axis_input: DVec3 = DVec3::ZERO;
let window_result = windows.get_single_mut();
let mut focused = true;
if window_result.is_ok() {
focused = window_result.unwrap().focused;
}
let target_v: DVec3 = if let Ok(target) = q_target.get_single() {
target.0
} else {
DVec3::splat(0.0)
};
if let Ok((player_transform, mut engine, mut angularvelocity, mut v, mut torque)) = q_playercam.get_single_mut() {
// Handle key input
if focused {
if key_input.pressed(settings.key_forward) {
axis_input.z += 1.2;
}
if key_input.pressed(settings.key_back) {
axis_input.z -= 1.2;
}
if key_input.pressed(settings.key_right) {
axis_input.x -= 1.2;
}
if key_input.pressed(settings.key_left) {
axis_input.x += 1.2;
}
if key_input.pressed(settings.key_up) {
axis_input.y += 1.2;
}
if key_input.pressed(settings.key_down) {
axis_input.y -= 1.2;
}
if key_input.pressed(settings.key_stop) {
let stop_direction = (target_v - v.0).normalize();
if stop_direction.length_squared() > 0.3 {
axis_input += 1.0 * DVec3::from(player_transform.rotation.inverse() * stop_direction.as_vec3());
}
}
}
// In typical games we would normalize the input vector so that diagonal movement is as
// fast as forward or sideways movement. But here, we merely clamp each direction to an
// absolute maximum of 1, since every thruster can be used separately. If the forward
// thrusters and the leftward thrusters are active at the same time, then of course the
// total diagonal acceleration is faster than the forward acceleration alone.
axis_input = axis_input.clamp(DVec3::splat(-1.0), DVec3::splat(1.0));
// Apply movement update
let forward_factor = engine.current_warmup * (if axis_input.z > 0.0 {
engine.thrust_forward
} else {
engine.thrust_back
});
let right_factor = engine.thrust_sideways * engine.current_warmup;
let up_factor = engine.thrust_sideways * engine.current_warmup;
let factor = DVec3::new(right_factor as f64, up_factor as f64, forward_factor as f64);
if axis_input.length_squared() > 0.003 {
let acceleration_global: DVec3 = DVec3::from(player_transform.rotation * (axis_input * factor).as_vec3());
let mut acceleration_total: DVec3 = (actor::ENGINE_SPEED_FACTOR * dt) as f64 * acceleration_global;
let threshold = 1e-5;
if key_input.pressed(settings.key_stop) {
// Decelerate (or match velocity to target_v)
let dv = v.0 - target_v;
for i in 0..3 {
if dv[i].abs() < threshold {
v[i] = target_v[i];
}
else if dv[i].signum() != (dv[i] + acceleration_total[i]).signum() {
// Almost stopped, but we overshot v=0
v[i] = target_v[i];
acceleration_total[i] = 0.0;
}
}
}
v.0 += acceleration_total;
engine.current_warmup = (engine.current_warmup + dt / engine.warmup_seconds).clamp(0.0, 1.0);
play_thruster_sound = true;
}
else {
engine.current_warmup = (engine.current_warmup - dt / engine.warmup_seconds).clamp(0.0, 1.0);
}
// Handle mouse input and mouse-like key bindings
let mut play_reactionwheel_sound = false;
let mut mouse_delta = Vec2::ZERO;
let mut pitch_yaw_rot = Vec3::ZERO;
let sensitivity_factor = if settings.is_zooming { settings.zoom_sensitivity_factor } else { 1.0 };
let mouseless_sensitivity = 40.0 * sensitivity_factor;
if key_input.pressed(settings.key_mouseup) {
pitch_yaw_rot[0] -= mouseless_sensitivity;
}
if key_input.pressed(settings.key_mousedown) {
pitch_yaw_rot[0] += mouseless_sensitivity;
}
if key_input.pressed(settings.key_mouseleft) {
pitch_yaw_rot[1] += mouseless_sensitivity; }
if key_input.pressed(settings.key_mouseright) {
pitch_yaw_rot[1] -= mouseless_sensitivity;
}
if key_input.pressed(settings.key_rotateleft) {
pitch_yaw_rot[2] -= mouseless_sensitivity;
}
if key_input.pressed(settings.key_rotateright) {
pitch_yaw_rot[2] += mouseless_sensitivity;
}
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
if mouse_delta != Vec2::ZERO {
if key_input.pressed(settings.key_rotate) {
pitch_yaw_rot[2] += mouse_delta.x;
} else {
pitch_yaw_rot[0] += mouse_delta.y;
pitch_yaw_rot[1] -= mouse_delta.x;
}
}
let angular_slowdown: f64 = (2.0 - engine.reaction_wheels.powf(0.01).clamp(1.001, 1.1)) as f64;
if pitch_yaw_rot.length_squared() > 1.0e-18 {
play_reactionwheel_sound = true;
pitch_yaw_rot *= settings.mouse_sensitivity * sensitivity_factor * engine.reaction_wheels;
torque.apply_torque(DVec3::from(
player_transform.rotation * Vec3::new(
pitch_yaw_rot[0] * 2.0,
pitch_yaw_rot[1],
pitch_yaw_rot[2])));
angularvelocity.0 *= angular_slowdown.clamp(0.97, 1.0) as f64;
}
else {
if angularvelocity.length_squared() > 1.0e-18 {
angularvelocity.0 *= angular_slowdown;
}
else {
angularvelocity.0 = DVec3::splat(0.0);
}
}
// Play sound effects
if let Ok(sink) = electricmotor_sound_controller.get_single() {
let volume = sink.volume();
let speed = sink.speed();
let action = pitch_yaw_rot.length_squared().powf(0.2) * 0.0005;
if play_reactionwheel_sound && !settings.mute_sfx {
sink.set_volume((volume + action).clamp(0.0, 1.0));
sink.set_speed((speed + action * 0.2).clamp(0.2, 0.5));
sink.play()
} else {
if volume <= 0.01 {
sink.pause()
} else {
sink.set_volume((volume - 0.01).clamp(0.0, 1.0));
sink.set_speed((speed - 0.03).clamp(0.2, 0.5));
}
}
}
if let Ok(sink) = thruster_sound_controller.get_single() {
if play_thruster_sound && !settings.mute_sfx && engine.engine_type == actor::EngineType::Monopropellant {
sink.play()
} else {
sink.pause()
}
}
if let Ok(sink) = rocket_sound_controller.get_single() {
if play_thruster_sound && !settings.mute_sfx && engine.engine_type == actor::EngineType::Rocket {
sink.play()
} else {
sink.pause()
}
}
if let Ok(sink) = ion_sound_controller.get_single() {
if play_thruster_sound && !settings.mute_sfx && engine.engine_type == actor::EngineType::Ion {
sink.play()
} else {
sink.pause()
}
}
}
}
// Find the closest world object that the player is looking at
#[inline]
pub fn find_closest_target<TargetSpecifier>(
objects: Vec<(TargetSpecifier, &Transform)>,
camera_transform: &Transform,
) -> (Option<TargetSpecifier>, f32)
where TargetSpecifier: Clone
{
let mut closest_entity: Option<TargetSpecifier> = None;
let mut closest_distance: f32 = f32::MAX;
let target_vector: Vec3 = (camera_transform.rotation * Vec3::new(0.0, 0.0, -1.0))
.normalize_or_zero();
for (entity, trans) in objects {
// Use Transform instead of Position because we're basing this
// not on the player mesh but on the camera, which doesn't have a position.
let (angular_diameter, angle, distance) = calc_angular_diameter_known_target_vector(
trans, camera_transform, &target_vector);
if angle <= angular_diameter.clamp(0.001, PI) {
// It's in the field of view!
//commands.entity(entity).insert(IsTargeted);
if distance < closest_distance {
closest_distance = distance;
closest_entity = Some(entity);
}
}
}
return (closest_entity, closest_distance);
}
#[inline]
pub fn calc_angular_diameter_known_target_vector(
target: &Transform,
camera: &Transform,
target_vector: &Vec3,
) -> (f32, f32, f32) {
let pos_vector: Vec3 = (target.translation - camera.translation)
.normalize_or_zero();
let cosine_of_angle: f32 = target_vector.dot(pos_vector);
let angle: f32 = cosine_of_angle.acos();
let distance: f32 = target.translation.distance(camera.translation);
let leeway: f32 = 1.3;
let angular_diameter: f32 = if distance > 0.0 {
// Angular Diameter
leeway * (target.scale[0] / distance).asin()
}
else {
0.0
};
return (angular_diameter, angle, distance);
}
#[inline]
pub fn calc_angular_diameter(
target: &Transform,
camera: &Transform,
) -> (f32, f32, f32) {
let target_vector: Vec3 = (camera.rotation * Vec3::new(0.0, 0.0, -1.0))
.normalize_or_zero();
return calc_angular_diameter_known_target_vector(target, camera, &target_vector);
}

359
src/chat.rs Normal file
View file

@ -0,0 +1,359 @@
use bevy::prelude::*;
use crate::{actor, audio, hud, settings, world};
pub struct ChatPlugin;
impl Plugin for ChatPlugin {
fn build(&self, app: &mut App) {
app.register_type::<ChatBranch>();
app.add_systems(Update, (
handle_new_conversations,
handle_reply_keys,
handle_send_messages,
handle_conversations,
handle_chat_scripts,
));
app.add_systems(PostUpdate, despawn_old_choices);
app.add_event::<StartConversationEvent>();
app.add_event::<SendMessageEvent>();
app.add_event::<ChatScriptEvent>();
}
}
#[derive(Event)]
pub struct StartConversationEvent {
pub talker: Talker,
}
#[derive(Event)]
pub struct SendMessageEvent {
pub conv_id: String,
pub conv_label: String,
pub text: String,
}
#[derive(Event)]
pub struct ChatScriptEvent {
name: String,
param: String,
param2: String,
}
#[derive(Debug)]
#[derive(Component, Reflect, Default)]
#[reflect(Component)]
pub struct ChatBranch {
pub id: String,
pub name: String,
pub label: String,
pub delay: f64,
pub sound: String,
pub level: String,
pub reply: String,
pub goto: String,
pub choice: String,
pub script: String,
pub script_parameter: String,
pub script_parameter2: String,
}
#[derive(Component)]
pub struct Chat {
pub id: String,
pub label: String,
pub timer: f64,
}
#[derive(Component)]
pub struct ChoiceAvailable {
pub conv_id: String,
pub conv_label: String,
pub recipient: String,
pub text: String,
}
#[derive(Component)]
#[derive(Clone)]
pub struct Talker {
pub pronoun: String,
pub conv_id: String,
}
impl Default for Talker { fn default() -> Self { Self {
pronoun: "they/them".to_string(),
conv_id: "error".to_string(),
}}}
pub fn handle_new_conversations(
mut commands: Commands,
mut er_conv: EventReader<StartConversationEvent>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
q_conv: Query<&Chat>,
time: Res<Time>,
) {
let label = "INIT";
for event in er_conv.read() {
// check for existing chats with this id
let id = &event.talker.conv_id;
let chats: Vec<&Chat> = q_conv.iter().filter(|c| c.id == *id).collect();
if chats.len() > 0 {
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Ping));
continue;
}
// no existing chats yet, let's create a new one
commands.spawn((
Chat {
id: id.to_string(),
label: label.to_string(),
timer: time.elapsed_seconds_f64(),
},
world::DespawnOnPlayerDeath,
));
break;
}
}
fn handle_reply_keys(
keyboard_input: Res<ButtonInput<KeyCode>>,
settings: ResMut<settings::Settings>,
q_choices: Query<&ChoiceAvailable>,
mut evwriter_sendmsg: EventWriter<SendMessageEvent>,
mut evwriter_sfx: EventWriter<audio::PlaySfxEvent>,
) {
let mut selected_choice = 1;
'outer: for key in settings.get_reply_keys() {
if keyboard_input.just_pressed(key) {
let mut count = 1;
for choice in &q_choices {
if count == selected_choice {
evwriter_sfx.send(audio::PlaySfxEvent(audio::Sfx::Click));
evwriter_sendmsg.send(SendMessageEvent {
conv_id: choice.conv_id.clone(),
conv_label: choice.conv_label.clone(),
text: choice.text.clone(),
});
break 'outer;
}
count += 1;
}
}
selected_choice += 1;
}
}
pub fn handle_send_messages(
mut commands: Commands,
mut er_sendmsg: EventReader<SendMessageEvent>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
mut ew_chatscript: EventWriter<ChatScriptEvent>,
mut q_conv: Query<(Entity, &mut Chat)>,
time: Res<Time>,
chat_branches: Query<&ChatBranch>,
mut log: ResMut<hud::Log>,
) {
let now = time.elapsed_seconds_f64();
for event in er_sendmsg.read() {
for (entity, mut chat) in &mut q_conv {
if chat.id != event.conv_id {
continue;
}
if event.conv_label == "EXIT" {
info!("Despawning chat.");
commands.entity(entity).despawn();
continue;
}
let branches: Vec<&ChatBranch> = chat_branches.iter()
.filter(|branch| branch.id == event.conv_id
&& branch.label == event.conv_label
&& branch.choice == event.text)
.collect();
if branches.len() != 1 {
error!("Expected 1 branch with ID '{}', label '{}', choice '{}', but got {}! Aborting conversation.", event.conv_id, event.conv_label, event.text, branches.len());
continue;
}
let branch = branches[0];
// TODO despawn the choices
if !branch.reply.is_empty() {
match branch.level.as_str() {
"chat" => log.chat(branch.reply.clone(), branch.name.clone()),
"info" => log.info(branch.reply.clone()),
"warn" => log.warning(branch.reply.clone()),
_ => (),
}
}
chat.label = branch.goto.clone();
chat.timer = now + branch.delay;
if branch.sound != "" {
let sfx = audio::str2sfx(branch.sound.as_str());
ew_sfx.send(audio::PlaySfxEvent(sfx));
}
let choices: Vec<&ChatBranch> = chat_branches.iter()
.filter(|branch| branch.id == chat.id && branch.label == chat.label)
.collect();
for choice in choices {
if choice.choice.as_str() != hud::CHOICE_NONE {
commands.spawn((
ChoiceAvailable {
conv_id: choice.id.clone(),
conv_label: choice.label.clone(),
recipient: choice.name.clone(),
text: choice.choice.clone(),
},
world::DespawnOnPlayerDeath,
));
}
}
if !branch.script.is_empty() {
ew_chatscript.send(ChatScriptEvent {
name: branch.script.clone(),
param: branch.script_parameter.clone(),
param2: branch.script_parameter2.clone(),
});
}
}
break; // let's only handle one of these per frame
}
}
pub fn handle_conversations(
mut commands: Commands,
mut log: ResMut<hud::Log>,
mut q_conv: Query<(Entity, &mut Chat)>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
mut ew_chatscript: EventWriter<ChatScriptEvent>,
time: Res<Time>,
chat_branches: Query<&ChatBranch>, // TODO: use Table for faster iteration?
) {
let now = time.elapsed_seconds_f64();
for (entity, mut chat) in &mut q_conv {
if chat.label == "EXIT" {
info!("Despawning chat.");
commands.entity(entity).despawn();
continue;
}
if now < chat.timer {
continue;
}
let branches: Vec<&ChatBranch> = chat_branches.iter()
.filter(|branch| branch.id == chat.id
&& branch.label == chat.label
&& branch.choice == "")
.collect();
if branches.len() != 1 {
error!("Expected 1 branch with ID '{}' and label '{}', but got {}! Aborting conversation.", chat.id, chat.label, branches.len());
continue;
}
let branch = branches[0];
if !branch.reply.is_empty() {
match branch.level.as_str() {
"chat" => log.chat(branch.reply.clone(), branch.name.clone()),
"info" => log.info(branch.reply.clone()),
"warn" => log.warning(branch.reply.clone()),
_ => (),
}
}
if chat.label == "EXIT" {
// TODO: isn't this dead code?
continue;
}
chat.label = branch.goto.clone();
if branch.sound != "" {
let sfx = audio::str2sfx(branch.sound.as_str());
ew_sfx.send(audio::PlaySfxEvent(sfx));
}
chat.timer = now + branch.delay;
let choices: Vec<&ChatBranch> = chat_branches.iter()
.filter(|branch| branch.id == chat.id && branch.label == chat.label)
.collect();
for choice in choices {
if choice.choice.as_str() != hud::CHOICE_NONE {
commands.spawn((
ChoiceAvailable {
conv_id: choice.id.clone(),
conv_label: choice.label.clone(),
recipient: choice.name.clone(),
text: choice.choice.clone(),
},
world::DespawnOnPlayerDeath,
));
}
}
if !branch.script.is_empty() {
ew_chatscript.send(ChatScriptEvent {
name: branch.script.clone(),
param: branch.script_parameter.clone(),
param2: branch.script_parameter2.clone(),
});
}
}
}
pub fn handle_chat_scripts(
mut er_chatscript: EventReader<ChatScriptEvent>,
mut q_actor: Query<(&mut actor::Actor, &mut actor::Suit), Without<actor::Player>>,
mut q_player: Query<(&mut actor::Actor, &mut actor::Suit), With<actor::Player>>,
) {
for script in er_chatscript.read() {
match script.name.as_str() {
"refilloxygen" => if let Ok(mut amount) = script.param.parse::<f32>() {
for (mut _actor, mut suit) in q_player.iter_mut() {
if script.param2.is_empty() {
suit.oxygen = (suit.oxygen + amount).clamp(0.0, suit.oxygen_max);
}
else {
let mut found_other = false;
info!("param2={}", script.param2);
for (other_actor, mut other_suit) in q_actor.iter_mut() {
if !other_actor.id.is_empty() {
info!("ID={}", other_actor.id);
}
if other_actor.id == script.param2 {
found_other = true;
amount = amount
.clamp(0.0, other_suit.oxygen)
.clamp(0.0, suit.oxygen_max - suit.oxygen);
other_suit.oxygen = other_suit.oxygen - amount;
suit.oxygen = (suit.oxygen + amount).clamp(0.0, suit.oxygen_max);
break;
}
}
if !found_other {
error!("Script error: could not find actor with ID `{}`", script.param2);
}
}
}
} else {
error!("Invalid parameter for command `{}`: `{}`", script.name, script.param);
}
_ => {}
}
}
}
fn despawn_old_choices(
mut commands: Commands,
q_conv: Query<&Chat>,
q_choices: Query<(Entity, &ChoiceAvailable)>,
) {
let chats: Vec<&Chat> = q_conv.iter().collect();
'outer: for (entity, choice) in &q_choices {
// Let's see if this choice still has a chat in the appropriate state
for chat in &chats {
if choice.conv_id == chat.id && choice.conv_label == chat.label {
continue 'outer;
}
}
// Despawn the choice, since no matching chat was found
commands.entity(entity).despawn();
}
}

704
src/commands.rs Normal file
View file

@ -0,0 +1,704 @@
// This plugin loads "defs.txt" and applies the therein contained commands
extern crate regex;
use bevy::prelude::*;
use bevy_xpbd_3d::prelude::*;
use bevy::math::DVec3;
use crate::{actor, chat, hud, nature, world};
use regex::Regex;
use std::f32::consts::PI;
use std::f64::consts::PI as PI64;
use std::collections::HashMap;
pub struct CommandsPlugin;
impl Plugin for CommandsPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, load_defs);
app.add_systems(Update, spawn_entities);
app.add_event::<SpawnEvent>();
}
}
#[derive(Event)] pub struct SpawnEvent(ParserState);
#[derive(PartialEq, Clone)]
enum DefClass {
Actor,
Chat,
None,
}
#[derive(Clone)]
struct ParserState {
class: DefClass,
// Generic fields
name: Option<String>,
chat: String,
// Actor fields
id: String,
pos: DVec3,
model: String,
model_scale: f32,
rotation: Quat,
velocity: DVec3,
angular_momentum: DVec3,
pronoun: String,
is_sphere: bool,
is_player: bool,
is_lifeform: bool,
is_alive: bool,
is_suited: bool,
is_vehicle: bool,
is_clickable: bool,
has_physics: bool,
wants_maxrotation: Option<f64>,
wants_maxvelocity: Option<f64>,
collider_is_mesh: bool,
thrust_forward: f32,
thrust_sideways: f32,
thrust_back: f32,
reaction_wheels: f32,
warmup_seconds: f32,
engine_type: actor::EngineType,
oxygen: f32,
mass: f64,
collider: Collider,
camdistance: f32,
suit_integrity: f32,
light_brightness: f32,
light_color: Option<Color>,
// Chat fields
delay: f64,
text: String,
level: String,
label: String,
goto: String,
is_choice: bool,
stores_item: bool,
script: String,
script_parameter: String,
script_parameter2: String,
}
impl Default for ParserState {
fn default() -> Self {
let default_actor = actor::Actor::default();
let default_engine = actor::Engine::default();
Self {
class: DefClass::None,
name: None,
chat: "".to_string(),
id: "".to_string(),
pos: DVec3::new(0.0, 0.0, 0.0),
model: "".to_string(),
model_scale: 1.0,
rotation: Quat::IDENTITY,
velocity: DVec3::splat(0.0),
angular_momentum: DVec3::new(0.03, 0.3, 0.09),
pronoun: "they/them".to_string(),
is_sphere: false,
is_player: false,
is_lifeform: false,
is_alive: false,
is_suited: false,
is_vehicle: false,
is_clickable: true,
has_physics: true,
wants_maxrotation: None,
wants_maxvelocity: None,
collider_is_mesh: false,
thrust_forward: default_engine.thrust_forward,
thrust_sideways: default_engine.thrust_forward,
thrust_back: default_engine.thrust_back,
reaction_wheels: default_engine.reaction_wheels,
warmup_seconds: default_engine.warmup_seconds,
engine_type: default_engine.engine_type,
oxygen: nature::OXY_D,
mass: 1.0,
collider: Collider::sphere(1.0),
camdistance: default_actor.camdistance,
suit_integrity: 1.0,
light_brightness: 0.0,
light_color: None,
delay: 0.0,
text: "".to_string(),
level: "chat".to_string(),
label: "".to_string(),
goto: "".to_string(),
is_choice: false,
stores_item: false,
script: "".to_string(),
script_parameter: "".to_string(),
script_parameter2: "".to_string(),
}
}
}
impl ParserState {
fn reset_message(&mut self) {
let default = ParserState::default();
self.label = default.label;
self.delay = default.delay;
self.goto = default.goto;
self.level = default.level;
self.text = default.text;
self.is_choice = default.is_choice;
}
fn as_chatbranch(&self) -> chat::ChatBranch {
return chat::ChatBranch {
id: self.chat.clone(),
name: self.name.clone().unwrap_or("".to_string()),
label: self.label.clone(),
delay: self.delay.clone(),
sound: if self.is_choice { "".to_string() } else { "chat".to_string() },
level: self.level.clone(),
reply: if self.is_choice { "".to_string() } else { self.text.clone() },
choice: if self.is_choice { self.text.clone() } else { "".to_string() },
goto: self.goto.clone(),
script: self.script.clone(),
script_parameter: self.script_parameter.clone(),
script_parameter2: self.script_parameter2.clone(),
}
}
}
pub fn load_defs(
mut ew_spawn: EventWriter<SpawnEvent>,
) {
let re1 = Regex::new(r"^\s*([a-z_-]+)\s+(.*)$").unwrap();
let re2 = Regex::new("\"([^\"]*)\"|(-?[0-9]+[0-9e-]*(?:\\.[0-9e-]+)?)|([a-zA-Z_-][a-zA-Z0-9_-]*)").unwrap();
let defs_string = include_str!("defs.txt");
let mut lines = defs_string.lines();
let mut state = ParserState::default();
let mut command;
let mut parameters;
let mut id2pos: HashMap<String, DVec3> = HashMap::new();
let mut line_nr = -1;
while let Some(line) = lines.next() {
line_nr += 1;
let caps = re1.captures(line);
if caps.is_none() {
if line.trim() != "" {
error!("Syntax Error in definitions line {}: `{}`", line_nr, line);
}
continue;
}
if let Some(caps) = caps {
command = caps.get(1).unwrap().as_str();
parameters = caps.get(2).unwrap().as_str();
}
else {
error!("Failed to read regex captures in line {}: `{}`", line_nr, line);
continue;
}
let mut parts: Vec<&str> = Vec::new();
parts.push(command);
for caps in re2.captures_iter(parameters) {
if let Some(part) = caps.get(1) {
parts.push(&part.as_str());
}
if let Some(part) = caps.get(2) {
parts.push(&part.as_str());
}
if let Some(part) = caps.get(3) {
parts.push(&part.as_str());
}
}
match parts.as_slice() {
// Parsing actors
["actor", x, y, z, model] => {
ew_spawn.send(SpawnEvent(state));
state = ParserState::default();
state.class = DefClass::Actor;
state.model = model.to_string();
if let (Ok(x_float), Ok(y_float), Ok(z_float)) =
(x.parse::<f64>(), y.parse::<f64>(), z.parse::<f64>()) {
state.pos = DVec3::new(x_float, y_float, z_float);
}
else {
error!("Can't parse coordinates as floats in def: {line}");
state = ParserState::default();
continue;
}
}
["relativeto", id] => {
match id2pos.get(&id.to_string()) {
Some(pos) => {
state.pos += *pos;
}
None => {
error!("Specified `relativeto` command but could not find id `{id}`");
continue;
}
}
}
["orbit", radius_str, phase_str] => {
if let (Ok(r), Ok(phase)) = (radius_str.parse::<f64>(), phase_str.parse::<f64>()) {
let phase_deg = phase * PI64 * 2.0;
state.pos = DVec3::new(
state.pos.x + r * phase_deg.cos(),
state.pos.y,
state.pos.z + r * phase_deg.sin(),
);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["sphere", "yes"] => {
state.is_sphere = true;
}
["id", id] => {
state.id = id.to_string();
id2pos.insert(state.id.clone(), state.pos.clone());
}
["alive", "yes"] => {
state.is_alive = true;
state.is_lifeform = true;
state.is_suited = true;
}
["vehicle", "yes"] => {
state.is_vehicle = true;
}
["clickable", "no"] => {
state.is_clickable = false;
}
["moon", "yes"] => {
state.model_scale *= 3.0;
}
["oxygen", amount] => {
if let Ok(amount) = amount.parse::<f32>() {
state.is_lifeform = true;
state.is_suited = true;
state.oxygen = amount;
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["pronoun", pronoun] => {
state.pronoun = pronoun.to_string();
}
["chatid", chat] => {
state.chat = chat.to_string();
}
["scale", scale] => {
if let Ok(scale_float) = scale.parse::<f32>() {
state.model_scale = scale_float;
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["rotationx", rotation_x] => {
if let Ok(rotation_x_float) = rotation_x.parse::<f32>() {
state.rotation *= Quat::from_rotation_x(PI * rotation_x_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["rotationy", rotation_y] => {
if let Ok(rotation_y_float) = rotation_y.parse::<f32>() {
state.rotation *= Quat::from_rotation_y(PI * rotation_y_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["rotationz", rotation_z] => {
if let Ok(rotation_z_float) = rotation_z.parse::<f32>() {
state.rotation *= Quat::from_rotation_z(PI * rotation_z_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["velocity", x, y, z] => {
if let (Ok(x_float), Ok(y_float), Ok(z_float)) =
(x.parse::<f64>(), y.parse::<f64>(), z.parse::<f64>()) {
state.velocity = DVec3::new(x_float, y_float, z_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["angularmomentum", x, y, z] => {
if let (Ok(x_float), Ok(y_float), Ok(z_float)) =
(x.parse::<f64>(), y.parse::<f64>(), z.parse::<f64>()) {
state.angular_momentum = DVec3::new(x_float, y_float, z_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["thrust", forward, back, sideways, reaction_wheels, warmup_time] => {
if let (Ok(forward_float), Ok(back_float), Ok(sideways_float), Ok(reaction_wheels_float), Ok(warmup_time_float)) = (forward.parse::<f32>(), back.parse::<f32>(), sideways.parse::<f32>(), reaction_wheels.parse::<f32>(), warmup_time.parse::<f32>()) {
state.thrust_forward = forward_float;
state.thrust_back = back_float;
state.thrust_sideways = sideways_float;
state.reaction_wheels = reaction_wheels_float;
state.warmup_seconds = warmup_time_float;
}
}
["engine", "rocket"] => {
state.engine_type = actor::EngineType::Rocket;
}
["engine", "ion"] => {
state.engine_type = actor::EngineType::Ion;
}
["engine", "monopropellant"] => {
state.engine_type = actor::EngineType::Monopropellant;
}
["health", value] => {
if let Ok(value_float) = value.parse::<f32>() {
state.suit_integrity = value_float;
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["mass", value] => {
if let Ok(value_float) = value.parse::<f64>() {
state.mass = value_float;
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["physics", "off"] => {
state.has_physics = false;
}
["collider", "sphere", radius] => {
if let Ok(radius_float) = radius.parse::<f64>() {
state.collider = Collider::sphere(radius_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["collider", "capsule", height, radius] => {
if let (Ok(height_float), Ok(radius_float)) = (height.parse::<f64>(), radius.parse::<f64>()) {
state.collider = Collider::capsule(height_float, radius_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["collider", "mesh"] => {
state.collider_is_mesh = true;
}
["player", "yes"] => {
state.is_player = true;
state.is_alive = true;
}
["camdistance", value] => {
if let Ok(value_float) = value.parse::<f32>() {
state.camdistance = value_float;
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["light", color_hex, brightness] => {
if let Ok(brightness_float) = brightness.parse::<f32>() {
if let Ok(color) = Color::hex(color_hex) {
state.light_color = Some(color);
state.light_brightness = brightness_float;
}
else {
error!("Can't parse hexadecimal color code: {line}");
continue;
}
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["wants", "maxrotation", value] => {
// NOTE: requires an engine to slow down velocity
if let Ok(value_float) = value.parse::<f64>() {
state.wants_maxrotation = Some(value_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
["wants", "maxvelocity", value] => {
// NOTE: requires an engine to slow down velocity
if let Ok(value_float) = value.parse::<f64>() {
state.wants_maxvelocity = Some(value_float);
}
else {
error!("Can't parse float: {line}");
continue;
}
}
// Parsing chats
["chat", chat_name] => {
debug!("Registering chat: {}", chat_name);
ew_spawn.send(SpawnEvent(state));
state = ParserState::default();
state.class = DefClass::Chat;
state.chat = chat_name.to_string();
}
["name", name] => {
debug!("Registering name: {}", name);
state.name = Some(name.to_string());
}
["msg", sleep, text] => {
debug!("Registering message (sleep={}): {}", sleep, text);
ew_spawn.send(SpawnEvent(state.clone()));
if let Ok(sleep_float) = sleep.parse::<f64>() {
state.delay = sleep_float;
state.text = text.to_string();
state.stores_item = true;
state.is_choice = false;
} else {
error!("The 'sleep' value for this message is not a float: {}", line);
continue;
}
}
["msg", sleep, label, goto, text] => {
debug!("Registering message (sleep={}): {}", sleep, text);
ew_spawn.send(SpawnEvent(state.clone()));
state.reset_message();
if let Ok(sleep_float) = sleep.parse::<f64>() {
state.delay = sleep_float;
state.text = text.to_string();
state.stores_item = true;
state.is_choice = false;
state.goto = goto.to_string();
state.label = label.to_string();
} else {
error!("The 'sleep' value for this message is not a float: {}", line);
continue;
}
}
["choice", sleep, text] => {
debug!("Registering choice (sleep={}): {}", sleep, text);
ew_spawn.send(SpawnEvent(state.clone()));
state.reset_message();
if let Ok(sleep_float) = sleep.parse::<f64>() {
state.delay = sleep_float;
state.text = text.to_string();
state.stores_item = true;
state.is_choice = true;
} else {
error!("The 'sleep' value for this message is not a float: {}", line);
continue;
}
}
["choice", sleep, label, goto, text] => {
debug!("Registering choice (sleep={}): {}", sleep, text);
ew_spawn.send(SpawnEvent(state.clone()));
state.reset_message();
if let Ok(sleep_float) = sleep.parse::<f64>() {
state.delay = sleep_float;
state.text = text.to_string();
state.stores_item = true;
state.is_choice = true;
state.goto = goto.to_string();
state.label = label.to_string();
} else {
error!("The 'sleep' value for this message is not a float: {}", line);
continue;
}
}
["goto", label] => {
debug!("Registering goto: {}", label);
state.goto = label.to_string();
}
["label", label] => {
debug!("Registering label: {}", label);
state.label = label.to_string();
}
["lvl", level] => {
debug!("Registering level: {}", level);
state.level = level.to_string();
}
["script", scriptname, parameter] => {
state.script = scriptname.to_string();
state.script_parameter = parameter.to_string();
state.script_parameter2 = "".to_string();
}
["script", scriptname, parameter, parameter2] => {
state.script = scriptname.to_string();
state.script_parameter = parameter.to_string();
state.script_parameter2 = parameter2.to_string();
}
_ => {
error!("No match for [{}]", parts.join(","));
}
}
}
ew_spawn.send(SpawnEvent(state));
}
fn spawn_entities(
mut er_spawn: EventReader<SpawnEvent>,
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
for state_wrapper in er_spawn.read() {
let state = &state_wrapper.0;
if state.class == DefClass::Chat {
if state.stores_item {
let mut chat = commands.spawn(state.as_chatbranch());
chat.insert(world::DespawnOnPlayerDeath);
}
}
else if state.class == DefClass::Actor {
let mut actor = commands.spawn_empty();
actor.insert(actor::Actor {
id: state.id.clone(),
name: state.name.clone(),
camdistance: state.camdistance,
..default()
});
actor.insert(SleepingDisabled);
actor.insert(world::DespawnOnPlayerDeath);
actor.insert(actor::HitPoints::default());
actor.insert(Position::from(state.pos));
actor.insert(Rotation::from(state.rotation));
if state.is_sphere {
let sphere_texture_handle: Handle<Image> = asset_server.load(format!("textures/{}.jpg", state.model));
let sphere_handle = meshes.add(Sphere::new(1.0).mesh().uv(128, 128));
let sphere_material_handle = materials.add(StandardMaterial {
base_color_texture: Some(sphere_texture_handle.clone()),
perceptual_roughness: 1.0,
metallic: 0.0,
..default()
});
actor.insert(PbrBundle {
mesh: sphere_handle,
material: sphere_material_handle,
transform: Transform {
scale: Vec3::splat(state.model_scale),
..default()
},
..default()
});
} else {
actor.insert(SceneBundle {
transform: Transform {
scale: Vec3::splat(state.model_scale),
..default()
},
scene: asset_server.load(world::asset_name_to_path(state.model.as_str())),
..default()
});
}
// Physics Parameters
if state.has_physics {
let fix_scale: f64 = 1.0 / (state.model_scale as f64).powf(3.0);
actor.insert(RigidBody::Dynamic);
actor.insert(LinearVelocity(state.velocity));
actor.insert(AngularVelocity(state.angular_momentum));
actor.insert(ColliderDensity((state.mass * fix_scale) as f64));
if state.collider_is_mesh {
actor.insert(AsyncSceneCollider::new(Some(
ComputedCollider::TriMesh
//ComputedCollider::ConvexDecomposition(VHACDParameters::default())
)));
}
else {
actor.insert(state.collider.clone());
}
}
// TODO: angular velocity for objects without collisions, static objects
// Optional Components
if state.is_player {
actor.insert(actor::Player);
actor.insert(actor::PlayerCamera);
}
if state.is_player || state.is_vehicle {
// used to apply mouse movement to actor rotation
actor.insert(ExternalTorque::ZERO.with_persistence(false));
}
if state.is_lifeform {
actor.insert(actor::LifeForm::default());
actor.insert(actor::ExperiencesGForce::default());
actor.insert(actor::Suit {
oxygen: state.oxygen,
oxygen_max: nature::OXY_D,
integrity: state.suit_integrity,
..default()
});
}
if state.is_clickable {
actor.insert(hud::IsClickable {
name: state.name.clone(),
..default()
});
}
if let Some(value) = state.wants_maxrotation {
actor.insert(actor::WantsMaxRotation(value));
}
if let Some(value) = state.wants_maxvelocity {
actor.insert(actor::WantsMaxVelocity(value));
}
if let Some(color) = state.light_color {
actor.insert(PointLightBundle {
point_light: PointLight {
intensity: state.light_brightness,
color: color,
range: 100.0,
radius: 100.0,
..default()
},
..default()
});
}
if !state.chat.is_empty() {
actor.insert(chat::Talker {
conv_id: state.chat.clone(),
..default()
});
}
if state.is_vehicle {
actor.insert(actor::Vehicle::default());
}
if state.is_vehicle || state.is_suited
|| state.thrust_forward > 0.0
|| state.thrust_sideways > 0.0
|| state.thrust_back > 0.0
|| state.reaction_wheels > 0.0
{
actor.insert(actor::Engine {
thrust_forward: state.thrust_forward,
thrust_back: state.thrust_back,
thrust_sideways: state.thrust_sideways,
reaction_wheels: state.reaction_wheels,
warmup_seconds: state.warmup_seconds,
engine_type: state.engine_type,
..default()
});
}
}
}
}

354
src/defs.txt Normal file
View file

@ -0,0 +1,354 @@
actor 0 0 0 jupiter
id jupiter
name Jupiter
scale 71492e3
sphere yes
physics off
rotationx -0.50
rotationz -0.28
angularmomentum 30 30 30
actor 0 593051 0 suit
relativeto jupiter
orbit 226000e3 0.66
player yes
id player
mass 200.0
scale 1
oxygen 0.008
health 0.3
angularmomentum 0 0 0
collider capsule 2 1
thrust 1.2 1 1 300 1.5
rotationy 0.65
engine monopropellant
actor 10 -30 20 MeteorAceGT
name "MeteorAceGT™"
relativeto player
scale 5
vehicle yes
thrust 24.5 4.8 3.3 200000 3
engine ion
collider sphere 1.5
camdistance 50
mass 3000
angularmomentum 0.1 0.1 0.3
actor 0 0 0 io
name Io
relativeto jupiter
orbit 421700e3 0.65
scale 1822e3
rotationy -0.40
angularmomentum 0 0.0001 0
sphere yes
moon yes
physics off
actor 0 0 0 europa
name Europa
relativeto jupiter
orbit 670900e3 0.35
scale 1561e3
rotationy 0.20
angularmomentum 0 0.0001 0
sphere yes
moon yes
physics off
actor 0 0 0 ganymede
name Ganymede
relativeto jupiter
orbit 1070400e3 0.93
scale 2634e3
rotationy -0.40
angularmomentum 0 0.0001 0
sphere yes
moon yes
physics off
actor 0 0 0 callisto
name Callisto
relativeto jupiter
orbit 1882700e3 0.45
scale 2410e3
rotationy -0.40
angularmomentum 0 0.0001 0
sphere yes
moon yes
physics off
actor 0 0 0 moonlet
name Thebe
relativeto jupiter
id thebe
orbit 221900e3 0.66
scale 50e3
mass 430e15
angularmomentum 0 0.025 0
actor 3000 0 0 moonlet
name Moonlet
relativeto player
scale 500
mass 10000000
angularmomentum 0 0.15 0
actor -200 -110 1000 satellite
name "Communications Satellite"
relativeto player
scale 40
wants maxrotation 0
wants maxvelocity 0
thrust 0.05 0.05 0.05 30 1
collider capsule 7.5 1
rotationy 0.5
angularmomentum 0 0 0
mass 10
actor 1000 20 300 monolith
name "Mysterious Monolith 1"
relativeto player
scale 2
mass 1000
rotationx 0.5
wants maxrotation 0.01
angularmomentum 0.0 0.0 0.01
thrust 0 0 0 30 1
actor 10000 2000 -3500 monolith
name "Mysterious Monolith 2"
relativeto player
scale 2
mass 1000
rotationx 0.5
wants maxrotation 0.01
angularmomentum 0.0 0.0 0.01
thrust 0 0 0 30 1
actor -8000 -1000 -100 monolith
name "Mysterious Monolith 3"
relativeto player
scale 2
mass 1000
rotationx 0.5
wants maxrotation 0.01
angularmomentum 0.0 0.0 0.01
thrust 0 0 0 30 1
actor -3300 10 0 pizzeria
name "Pizzeria Asteroid"
relativeto player
id pizzeria
scale 40
mass 1000000
rotationy 0.30
angularmomentum 0 0 0
actor -120 0 20 MeteorAceGT
name "MeteorAceGT™"
relativeto pizzeria
scale 5
vehicle yes
thrust 70 13.7 9.4 200000 20
engine ion
collider sphere 1.5
camdistance 50
mass 3000
angularmomentum 0 0 0.2
actor -100 63 -13 pizzasign
name "Pizzeria Sign"
relativeto pizzeria
scale 20
mass 200
rotationy 0.45
angularmomentum 0 0 0
actor -16 -10 0 lightorb
name "Light Orb"
relativeto pizzeria
scale 0.5
light FF8F4A 1000000
actor -14 -3 -2 lightorb
name "Light Orb"
relativeto pizzeria
scale 0.5
light FF8F4A 1000000
actor -35 0 0 suit
relativeto pizzeria
name "Space Pizza™"
chatid pizzeria
alive yes
mass 200.0
collider capsule 2 1
thrust 1.2 1 1 10 1.5
wants maxrotation 0
wants maxvelocity 0
rotationy 1
angularmomentum 0 0 0
pronoun he
chat pizzeria
name "Space Pizza™"
msg 4 INIT cool "Welcome to Space Pizza™, best pizza around the rings!"
msg 4 cool order "Great to see a customer, we don't get many lately"
msg 50 order special "Would you like to order today's special?"
choice 3 special whatsthespecial "What's the special?"
msg 4 whatsthespecial pineapple "Suspicious Spacefunghi"
msg 4 pineapple smoothie "With free pineapple imiation"
msg 7 smoothie tube "Our pizza smoothies are freshly blended every day"
choice 3 tube wtftube "Wait... pizza smoothie?"
msg 6 wtftube anyway "Huh? Of course, smoothie! How else do you want to get that pizza down your spacesuit feeding tube?"
msg 6 anyway pass "An emulsion of deliciousness!"
msg 30 tube pass "Deliciousness for your spacesuit feeding tube!"
choice 3 pass yourloss "I think I'll pass..."
msg 3 yourloss end "Your loss, mate"
msg 3 pass prank "Hey? Are you still there?"
choice 3 special carved "Wh... what's a pizzeria doing here?"
msg 6 carved work "Hah, beautiful, right? I carved it out this asteroid myself!"
msg 7 work nowwannaorder "You know how much work it was to neutralize the rotation of the asteroid, so my valued customers don't bang against the walls while drinking my pizza?"
msg 20 nowwannaorder special "Now would you like today's special or not?"
choice 3 special ohno "My head hurts, my suit leaks, I think I'm dying..."
msg 20 ohno pressok "Seriously? Let me have a look. Just press the 'Grant Access' button please."
choice 3 pressok virus "[GRANT ACCESS TO SPACESUIT WIFI]"
msg 3 virus bitcoin "MALWARE DETECTED"
lvl warn
msg 6 bitcoin wtf "BITCOIN MINER DETECTED"
lvl warn
choice 5 wtf justchecking "Hey, what are you doing with me?"
msg 6 justchecking suitfucked "Just checking your systems, hang on tight"
msg 5 suitfucked wtfanyway "Yeah, suit's fucked, I'd look out for a repair shop"
msg 5 wtf wtfanyway "Yeah, suit's fucked, I'd look out for a repair shop"
msg 5 wtfanyway special "Anyway, wanna order today's special?"
choice 3 pressok deny "[DENY ACCESS TO SPACESUIT WIFI]"
msg 5 deny pressok2 "Oh come on, do you want my help or not?"
choice 3 pressok2 virus "[GRANT ACCESS TO SPACESUIT WIFI]"
choice 3 pressok2 deny2 "[DENY ACCESS TO SPACESUIT WIFI]"
choice 3 pressok2 deny2 "Fuck off!"
msg 2 deny2 end "Great, the first customer in ages, and they're brain damaged..."
msg 3 pressok2 prank "Hey? Are you still there?"
msg 3 pressok prank "Hey? Are you still there?"
msg 3 special prank "Hey? Are you still there?"
msg 4 prank end "This a prank?"
msg 0 end EXIT "Disconnected."
lvl info
actor 60 -15 -40 suit
relativeto player
name Icarus
chatid hi_icarus
alive yes
mass 200.0
collider capsule 2 1
angularmomentum 0.4 0.2 0.1
rotationy 0.6
rotationx 1
thrust 1.2 1 1 10 1.5
wants maxrotation 0.5
wants maxvelocity 0
pronoun it
chat hi_icarus
name Icarus
msg 4 INIT hi1 "Oh hey, you're awake!"
msg 6 hi1 hi2 "I found you drifting out cold, and decided to watch over you until you get better."
msg 40 hi2 hireply "Took us here behind that moonlet, to shield you from the micros."
choice 1 hireply thx "Thank you!"
msg 6 thx feeling "No worries. Folks are stretched thin around this corner, we gotta watch out for each other."
msg 40 feeling howru "How are you feeling?"
choice 1 hireply didntask "Eh... I didn't ask for this."
msg 6 didntask problem "Sure, 'cause you were unconscious. I just did what felt right. Is there a problem?"
choice 1 problem thx "Nevermind. Thank you."
choice 1 problem end "Leave me alone!"
choice 1 hireply micros "Micros? What's that?"
msg 40 micros microsexplained "Micrometeorites. Those tiny 混蛋 that fly right through you, leaving holes in your suit. And your body."
choice 1 microsexplained thx "Ouch! Thank you so much."
choice 1 microsexplained didntask "Whatever... I didn't ask for this."
msg 40 microsexplained howru "How are you feeling?"
msg 40 hireply howru "How are you feeling?"
choice 1 howru good1 "I feel quite cozy, this space suit feels like a second skin."
msg 4 good1 good2 "Hah, it does, doesn't it?"
msg 4 good2 good3 "But take care, your suit seems to be leaking. I'd patch it up if I were you."
msg 4 good3 good4 "I'm all out of SuitPatch™ SuperGlue™ right now, otherwise i'd share."
msg 40 good4 canihelp "Can I help you with anything else, maybe?"
choice 1 howru headache1 "I got this apocalyptic headache..."
msg 4 headache1 headache2 "Heh, probably related to why you were passed out."
msg 4 headache2 headache3 "Go easy on yourself, I'm sure things will turn for the better."
msg 40 headache3 canihelp "Meanwhile, can I help you with anything?"
choice 1 howru disoriented "I... don't know, I'm pretty disoriented."
msg 40 disoriented canihelp "Oh no. Do you need a lowdown on reality?"
choice 1 canihelp where1 "Where are we?"
msg 4 where1 where2 "This is space, my friend."
msg 4 where2 where3 "That massive crescent over there, that's Juptiter."
msg 4 where3 where4 "We're about 150,000km away from it, on the very outside of it's rings."
msg 4 where4 where5 "This area is called the Thebe gossamer ring."
msg 4 where5 where6 "The moon Thebe is actually pretty close right now, flinging all those micros at us."
choice 4 where6 where6micros "Micros? What's that?"
msg 4 where6micros canihelp "Micrometeorites. Those tiny 混蛋 that fly right through you, leaving holes in your suit. And your body."
msg 40 where6 canihelp "Anything else?"
choice 1 canihelp year1 "What year is this?"
msg 4 year1 year2 "Oh, is your Augmented Reality deactivated?"
msg 40 year2 canihelp "Push the TAB button, your space suit's AR will show you the date and time."
choice 1 canihelp why1 "Why am I here?"
msg 4 why1 why2 "That's a very philosophical question."
msg 4 why2 why3 "I don't know."
msg 40 why3 canihelp "It's probably related to the choices you made so far."
choice 1 canihelp whatnow1 "What should I do?"
msg 4 whatnow1 whatnow2 "Ah, that's the beauty of life."
msg 4 whatnow2 whatnow3 "You can just do whatever you want."
msg 6 whatnow3 whatnow4 "So long as you have the means, and respect people's boundaries."
msg 4 whatnow4 whatnow5 "I'm here mostly for the view and the peace."
msg 4 whatnow5 whatnow6 "Just look at Jupiter, it's mesmerizing, isn't it?"
msg 7 whatnow6 whatnow7 "So far away from everything, nobody expects anything from you."
msg 6 whatnow7 whatnow8 "If you want, you can take my sports racing capsule MeteorAce™ for a ride. It's right over there."
msg 8 whatnow8 whatnow9 "It rides like a punch in the face, don't hurt yourself, ok?"
choice 1 whatnow9 whatnow9tookind "You're too kind!"
msg 4 whatnow9tookind whatnow10 "Ah, don't mention it!"
msg 40 whatnow10 canihelp "There's also a half-decent pizza restaurant over there, look for the neon sign."
msg 40 whatnow9 canihelp "There's also a half-decent pizza restaurant over there, look for the neon sign."
choice 1 canihelp money1 "Do you have some money for me?"
msg 40 money1 money2 "Huh? What is money?"
choice 1 money2 money2currency "Currency? Flat round things that you can exchange for goods and services?"
msg 4 money2currency money2currency2 "Uhm... are you talking about pizza?"
msg 4 money2currency2 money2currency3 "I don't have any pizza with me right now."
msg 4 money2currency3 canihelp "But there's a pizza place right over there, look for the neon sign."
msg 40 money2 canihelp "Well, anyway, need anything else?"
choice 1 canihelp chocolate "I think I'm good for now"
msg 4 canihelp chocolate "Well, anyway."
choice 1 howru alone "I just want to be alone right now"
msg 4 alone end_pizza "Oh, sure. Ping me if you need anything. I'll go back to playing my VR game."
msg 4 howru chocolate "Well, I hope you're ok."
msg 40 chocolate wantchocolate "I got some left-over instant hot chocolate, would you like some?"
choice 1 wantchocolate yeschocolate "Oh yes! Please!"
msg 4 yeschocolate chocolatehere "Here you go, my friend!"
msg 4 chocolatehere pizza "Received 1x ChuggaChug™ Instant Hot Chocolate"
lvl info
msg 4 wantchocolate pizza "I guess not. Well. I think I'll go back to playing my VR game. Ping me if you need anything."
msg 10 pizza end_pizza "Oh and make sure to check out the pizza place!"
choice 1 end_pizza end2 "Will do, bye!"
msg 0 end2 EXIT "Disconnected."
lvl info
msg 0 end_pizza EXIT "Disconnected."
lvl info
msg 0 end EXIT "Disconnected."
lvl info
actor -300 0 40 suit
relativeto player
id drifter
name "Drifter"
chatid drifter
oxygen 0.08
mass 200.0
collider capsule 2 1
chat drifter
name "Drifter"
msg 2 INIT dead "Error: No response"
lvl info
msg 15 dead outcold "No life signs detected"
lvl info
choice 0 outcold EXIT "Damn, it's gotta be moldy in that suit. How long has it been drifting?"
choice 0 outcold EXIT "Harvest some oxygen"
script refilloxygen 1 drifter
msg 0 outcold EXIT ""
chat error
name ERROR
msg 0 INIT EXIT "Unspecified conversation ID"

126
src/effects.rs Normal file
View file

@ -0,0 +1,126 @@
use bevy::prelude::*;
use crate::{camera, settings};
pub struct EffectsPlugin;
impl Plugin for EffectsPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup);
app.add_systems(Startup, spawn_effects.after(setup).after(camera::setup_camera));
app.add_systems(Update, spawn_effects);
app.add_systems(Update, update_fadeblack);
// Blackout disabled for now
//app.add_systems(Update, update_blackout);
app.add_event::<SpawnEffectEvent>();
}
}
#[derive(Clone)]
pub enum Effects {
FadeIn(Color),
}
// Blackout disabled for now
//#[derive(Component)] pub struct BlackOutOverlay;
#[derive(Component)] pub struct FadeBlack;
#[derive(Component)]
pub struct Effect {
pub class: Effects,
pub duration: f64,
pub start_time: f64,
}
#[derive(Event)]
pub struct SpawnEffectEvent {
pub class: Effects,
pub duration: f64,
}
pub fn setup(
settings: Res<settings::Settings>,
mut ew_effect: EventWriter<SpawnEffectEvent>,
) {
if !settings.dev_mode {
ew_effect.send(SpawnEffectEvent { class: Effects::FadeIn(Color::BLACK), duration: 4.0 });
}
// Blackout disabled for now
// commands.spawn((
// BlackOutOverlay,
// NodeBundle {
// style: Style {
// width: Val::Vw(100.0),
// height: Val::Vh(100.0),
// position_type: PositionType::Absolute,
// top: Val::Px(0.0),
// left: Val::Px(0.0),
// ..default()
// },
// background_color: Color::BLACK.into(),
// ..default()
// },
// ));
}
pub fn spawn_effects(
mut commands: Commands,
mut er_effect: EventReader<SpawnEffectEvent>,
time: Res<Time>,
) {
let now = time.elapsed_seconds_f64();
for effect in er_effect.read() {
match effect.class {
Effects::FadeIn(color) => {
commands.spawn((
Effect {
class: effect.class.clone(),
duration: effect.duration,
start_time: now,
},
FadeBlack,
NodeBundle {
style: Style {
width: Val::Vw(100.0),
height: Val::Vh(100.0),
position_type: PositionType::Absolute,
top: Val::Px(0.0),
left: Val::Px(0.0),
..default()
},
background_color: color.into(),
..default()
},
));
},
//_ => {},
}
}
}
pub fn update_fadeblack(
mut commands: Commands,
mut q_effect: Query<(Entity, &Effect, &mut BackgroundColor), With<FadeBlack>>,
time: Res<Time>,
) {
for (entity, effect, mut bgcolor) in &mut q_effect {
let now = time.elapsed_seconds_f64();
if effect.start_time + effect.duration < now {
commands.entity(entity).despawn();
continue;
}
let alpha = (1.3 - 1.3 * (now - effect.start_time) / effect.duration).clamp(0.0, 1.0);
bgcolor.0.set_a(alpha as f32);
}
}
// Blackout disabled for now
//pub fn update_blackout(
// mut q_effect: Query<&mut BackgroundColor, With<BlackOutOverlay>>,
// q_player: Query<&actor::ExperiencesGForce, With<actor::Player>>
//) {
// if let (Ok(gforce), Ok(mut bgcolor)) = (q_player.get_single(), q_effect.get_single_mut()) {
// let threshold = 0.3;
// let factor = 1.0 / (1.0 - threshold);
// let alpha = (factor * (gforce.blackout - threshold)).clamp(0.0, 1.0);
// bgcolor.0.set_a(alpha as f32);
// }
//}

650
src/hud.rs Normal file
View file

@ -0,0 +1,650 @@
use crate::{actor, audio, camera, chat, nature, settings, world};
use bevy::prelude::*;
use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
use bevy::transform::TransformSystem;
use bevy_xpbd_3d::prelude::*;
use bevy::math::DVec3;
use std::collections::VecDeque;
use std::time::SystemTime;
pub const HUD_REFRESH_TIME: f32 = 0.1;
pub const FONT: &str = "fonts/Yupiter-Regular.ttf";
pub const LOG_MAX: usize = 20;
pub const LOG_MAX_TIME_S: u64 = 20;
pub const CHOICE_NONE: &str = "";
pub const AMBIENT_LIGHT: f32 = 0.0; // Space is DARK
pub const AMBIENT_LIGHT_AR: f32 = 15.0;
//pub const REPLY_NUMBERS: [char; 10] = ['❶', '❷', '❸', '❹', '❺', '❻', '❼', '❽', '❾', '⓿'];
//pub const REPLY_NUMBERS: [char; 10] = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩'];
pub const REPLY_NUMBERS: [char; 10] = ['➀', '➁', '➂', '➃', '➄', '➅', '➆', '➇', '➈', '➉'];
pub struct HudPlugin;
impl Plugin for HudPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup);
app.add_systems(Update, (
update_hud,
handle_input,
handle_target_event,
));
app.add_systems(PostUpdate, (
update_target_selectagon
.after(PhysicsSet::Sync)
.after(camera::apply_input_to_player)
.before(TransformSystem::TransformPropagate),
));
app.insert_resource(Log {
logs: VecDeque::with_capacity(LOG_MAX),
needs_rerendering: true,
});
app.insert_resource(FPSUpdateTimer(
Timer::from_seconds(HUD_REFRESH_TIME, TimerMode::Repeating)));
app.add_event::<TargetEvent>();
}
}
#[derive(Event)] pub struct TargetEvent(pub Option<Entity>);
#[derive(Component)] struct GaugesText;
#[derive(Component)] struct ChatText;
#[derive(Component)] struct Reticule;
#[derive(Component)] struct ToggleableHudElement;
#[derive(Component)] struct OnlyHideWhenTogglingHud;
#[derive(Component)] struct Selectagon;
#[derive(Component)] pub struct IsTargeted;
#[derive(Resource)]
struct FPSUpdateTimer(Timer);
pub enum LogLevel {
Warning,
//Error,
Info,
//Debug,
Chat,
//Ping,
Notice,
}
struct Message {
text: String,
sender: String,
level: LogLevel,
time: u64,
}
#[derive(Component)]
pub struct IsClickable {
pub name: Option<String>,
pub distance: Option<f64>,
}
impl Default for IsClickable { fn default() -> Self { Self {
name: None,
distance: None,
}}}
#[derive(Resource)]
pub struct Log {
logs: VecDeque<Message>,
needs_rerendering: bool,
}
impl Log {
pub fn info(&mut self, message: String) {
self.add(message, "System".to_string(), LogLevel::Info);
}
pub fn chat(&mut self, message: String, sender: String) {
self.add(message, sender, LogLevel::Chat);
}
pub fn warning(&mut self, message: String) {
self.add(message, "WARNING".to_string(), LogLevel::Warning);
}
pub fn notice(&mut self, message: String) {
self.add(message, "".to_string(), LogLevel::Notice);
}
pub fn add(&mut self, message: String, sender: String, level: LogLevel) {
if self.logs.len() == LOG_MAX {
self.logs.pop_front();
}
if let Ok(epoch) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
self.logs.push_back(Message {
text: message,
sender: sender,
level: level,
time: epoch.as_secs(),
});
self.needs_rerendering = true;
}
}
pub fn remove_old(&mut self) {
if let Some(message) = self.logs.front() {
if let Ok(epoch) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
if epoch.as_secs() - message.time > LOG_MAX_TIME_S {
self.logs.pop_front();
}
}
}
}
pub fn clear(&mut self) {
self.logs.clear();
}
}
fn setup(
mut commands: Commands,
settings: Res<settings::Settings>,
asset_server: Res<AssetServer>,
mut log: ResMut<Log>,
mut ambient_light: ResMut<AmbientLight>,
) {
log.notice("Resuming from suspend".to_string());
log.notice("WARNING: Oxygen Low".to_string());
let visibility = if settings.hud_active {
Visibility::Inherited
} else {
Visibility::Hidden
};
let mut bundle_fps = TextBundle::from_sections([
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
}
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
},
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
}
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
},
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
}
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
}
),
TextSection::new(
"\n氧 OXYGEN ",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
},
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::MAROON,
..default()
}
),
TextSection::new(
"\nProximity 警告 ",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
},
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
}
),
TextSection::new(
"\nSuit Integrity ",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
},
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
}
),
TextSection::new(
"\nVitals ",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
},
),
TextSection::new(
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
}
),
TextSection::new( // Target
"",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::GRAY,
..default()
}
),
]).with_style(Style {
top: Val::VMin(2.0),
left: Val::VMin(3.0),
..default()
});
bundle_fps.visibility = visibility;
commands.spawn((
GaugesText,
ToggleableHudElement,
bundle_fps,
));
// Add Chat Box
let bundle_chatbox = TextBundle::from_sections([
TextSection::new(
"Warning: System Log Uninitialized",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::rgb(0.7, 0.7, 0.7),
..default()
}
),
TextSection::new(
"\n",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::WHITE,
..default()
}
),
TextSection::new(
"\n\n\n",
TextStyle {
font: asset_server.load(FONT),
font_size: settings.font_size_hud,
color: Color::WHITE,
..default()
}
),
]).with_style(Style {
position_type: PositionType::Absolute,
bottom: Val::VMin(0.0),
left: Val::VMin(0.0),
..default()
}).with_text_justify(JustifyText::Left);
commands.spawn((
NodeBundle {
style: Style {
width: Val::Percent(50.),
align_items: AlignItems::Start,
position_type: PositionType::Absolute,
bottom: Val::Vh(10.0),
left: Val::Vw(25.0),
..default()
},
..default()
},
)).with_children(|parent| {
parent.spawn((
bundle_chatbox,
ChatText,
));
});
commands.spawn((
Reticule,
ToggleableHudElement,
NodeBundle {
style: Style {
width: Val::Px(2.0),
height: Val::Px(2.0),
position_type: PositionType::Absolute,
top: Val::Vh(50.0),
left: Val::Vw(50.0),
..default()
},
visibility: visibility,
background_color: Color::rgb(0.4, 0.4, 0.6).into(),
..default()
},
));
// Selectagon
commands.spawn((
Selectagon,
ToggleableHudElement,
OnlyHideWhenTogglingHud,
SceneBundle {
scene: asset_server.load(world::asset_name_to_path("selectagon")),
visibility: Visibility::Hidden,
..default()
},
));
// AR-related things
ambient_light.brightness = if settings.hud_active {
AMBIENT_LIGHT_AR
} else {
AMBIENT_LIGHT
};
}
fn update_hud(
diagnostics: Res<DiagnosticsStore>,
time: Res<Time>,
mut log: ResMut<Log>,
player: Query<(&actor::HitPoints, &actor::Suit, &actor::ExperiencesGForce), With<actor::Player>>,
q_camera: Query<(&Position, &LinearVelocity), With<actor::PlayerCamera>>,
mut timer: ResMut<FPSUpdateTimer>,
mut query: Query<&mut Text, With<GaugesText>>,
q_choices: Query<&chat::ChoiceAvailable>,
mut query_chat: Query<&mut Text, (With<ChatText>, Without<GaugesText>)>,
query_all_actors: Query<&actor::Actor>,
settings: Res<settings::Settings>,
q_target: Query<(Option<&Position>, &IsClickable), With<IsTargeted>>,
) {
// TODO only when hud is actually on
if timer.0.tick(time.delta()).just_finished() || log.needs_rerendering {
let q_camera_result = q_camera.get_single();
let player = player.get_single();
if player.is_ok() && q_camera_result.is_ok() {
let (hp, suit, gforce) = player.unwrap();
let (pos, cam_v) = q_camera_result.unwrap();
for mut text in &mut query {
text.sections[0].value = format!("2524-03-12 03:02");
if let Some(fps) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS) {
if let Some(value) = fps.smoothed() {
// Update the value of the second section
text.sections[4].value = format!("{value:.0}");
}
}
let power = suit.power / suit.power_max * 100.0;
text.sections[2].value = format!("{power:}%");
let oxy_percent = suit.oxygen / suit.oxygen_max * 100.0;
// the remaining oxygen hud info ignores leaking suits from low integrity
if suit.oxygen > nature::OXY_H {
let oxy_hour = suit.oxygen / nature::OXY_H;
text.sections[7].value = format!("{oxy_percent:.1}% [lasts {oxy_hour:.1} hours]");
} else {
let oxy_min = suit.oxygen / nature::OXY_M;
text.sections[7].value = format!("{oxy_percent:.1}% [lasts {oxy_min:.1} min]");
}
//let adrenaline = lifeform.adrenaline * 990.0 + 10.0;
//text.sections[11].value = format!("{adrenaline:.0}pg/mL");
let vitals = 100.0 * hp.current / hp.max;
text.sections[13].value = format!("{vitals:.0}%");
let all_actors = query_all_actors.iter().len();
text.sections[9].value = format!("{all_actors:.0}");
let integrity = suit.integrity * 100.0;
text.sections[11].value = format!("{integrity:.0}%");
let speed = cam_v.length();
let kmh = speed * 60.0 * 60.0 / 1000.0;
let speed_readable = nature::readable_distance(speed);
let gforce = gforce.gforce;
//text.sections[17].value = format!("{speed_readable}/s / {kmh:.0}km/h / {gforce:.1}g");
// Target display
let dist_scalar: f64;
if let Ok((_, IsClickable { distance: Some(dist), .. })) = q_target.get_single() {
dist_scalar = *dist;
}
else {
let target: Option<DVec3>;
if let Ok((Some(targetpos), _)) = q_target.get_single() {
target = Some(targetpos.0);
}
else if q_target.is_empty() {
target = Some(DVec3::new(0.0, 0.0, 0.0));
}
else {
target = None;
}
if let Some(target_pos) = target {
let dist = pos.0 - target_pos;
dist_scalar = dist.length();
}
else {
dist_scalar = 0.0;
}
}
let target_name: String;
let distance: String;
if dist_scalar.is_nan() {
distance = "UNKNOWN".to_string();
}
else if dist_scalar != 0.0 {
distance = nature::readable_distance(dist_scalar);
}
else {
distance = "ERROR".to_string();
}
if q_target.is_empty() {
text.sections[14].value = format!("\nv {speed_readable}/s + {gforce:.1}g");
}
else {
let targets: Vec<String> = q_target
.iter()
.map(|(_, clickable)| clickable.name.clone().unwrap_or("<unnamed>".to_string()))
.collect();
target_name = targets.join(", ");
text.sections[14].value = format!("\n\nTarget: {target_name}\nDistance: {distance}\nΔv {speed_readable}/s + {gforce:.1}g");
}
}
}
if let Ok(mut chat) = query_chat.get_single_mut() {
// Choices
let mut choices: Vec<String> = Vec::new();
let mut count = 0;
for choice in &q_choices {
if count > 9 {
break;
}
let press_this = REPLY_NUMBERS[count];
let reply = &choice.text;
//let recipient = &choice.recipient;
// TODO: indicate recipients if there's more than one
choices.push(format!("{press_this} {reply}"));
count += 1;
}
if count < 4 {
for _padding in 0..(4-count) {
choices.push(" ".to_string());
}
}
chat.sections[2].value = choices.join("\n");
// Chat Log and System Log
let logfilter = if settings.hud_active {
|_msg: &&Message| { true }
} else {
|msg: &&Message| { match msg.level {
LogLevel::Chat => true,
LogLevel::Warning => true,
LogLevel::Info => true,
_ => false
}}
};
let logs_vec: Vec<String> = log.logs.iter()
.filter(logfilter)
.map(|s| if s.sender.is_empty() {
format!("{}", s.text)
} else {
format!("{}: {}", s.sender, s.text)
}).collect();
chat.sections[0].value = logs_vec.join("\n");
}
log.needs_rerendering = false;
log.remove_old();
}
}
fn handle_input(
keyboard_input: Res<ButtonInput<KeyCode>>,
mouse_input: Res<ButtonInput<MouseButton>>,
mut settings: ResMut<settings::Settings>,
mut q_hud: Query<(&mut Visibility, Option<&OnlyHideWhenTogglingHud>), With<ToggleableHudElement>>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
mut ew_togglemusic: EventWriter<audio::ToggleMusicEvent>,
mut ew_target: EventWriter<TargetEvent>,
mut ambient_light: ResMut<AmbientLight>,
q_objects: Query<(Entity, &Transform), (With<IsClickable>, Without<IsTargeted>, Without<actor::PlayerDrivesThis>, Without<actor::Player>)>,
q_camera: Query<&Transform, With<Camera>>,
) {
if keyboard_input.just_pressed(settings.key_togglehud) {
if settings.hud_active {
for (mut hudelement_visibility, _) in q_hud.iter_mut() {
*hudelement_visibility = Visibility::Hidden;
}
settings.hud_active = false;
ambient_light.brightness = AMBIENT_LIGHT;
}
else {
for (mut hudelement_visibility, only_hide) in q_hud.iter_mut() {
if only_hide.is_none() {
*hudelement_visibility = Visibility::Inherited;
}
}
settings.hud_active = true;
ambient_light.brightness = AMBIENT_LIGHT_AR;
}
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Switch));
ew_togglemusic.send(audio::ToggleMusicEvent());
}
if settings.hud_active && mouse_input.just_pressed(settings.key_selectobject) {
if let Ok(camtrans) = q_camera.get_single() {
let objects: Vec<(Entity, &Transform)> = q_objects.iter().collect();
if let (Some(new_target), _dist) = camera::find_closest_target::<Entity>(objects, camtrans) {
ew_target.send(TargetEvent(Some(new_target)));
}
else {
ew_target.send(TargetEvent(None));
}
}
}
}
fn handle_target_event(
mut commands: Commands,
settings: Res<settings::Settings>,
mut er_target: EventReader<TargetEvent>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
q_target: Query<Entity, With<IsTargeted>>,
) {
let mut play_sfx = false;
for TargetEvent(target) in er_target.read() {
for old_target in &q_target {
commands.entity(old_target).remove::<IsTargeted>();
play_sfx = true;
}
if let Some(entity) = target {
commands.entity(*entity).insert(IsTargeted);
play_sfx = true;
}
if play_sfx && !settings.mute_sfx {
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Click));
}
break; // Only accept a single event per frame
}
}
fn update_target_selectagon(
settings: Res<settings::Settings>,
mut q_selectagon: Query<(&mut Transform, &mut Visibility), (With<Selectagon>, Without<IsTargeted>, Without<Camera>)>,
q_target: Query<&Transform, (With<IsTargeted>, Without<Camera>, Without<Selectagon>)>,
q_camera: Query<&Transform, (With<Camera>, Without<IsTargeted>, Without<Selectagon>)>,
) {
if !settings.hud_active || q_camera.is_empty() {
return;
}
let camera_trans = q_camera.get_single().unwrap();
if let Ok((mut selectagon_trans, mut selectagon_vis)) = q_selectagon.get_single_mut() {
if let Ok(target_trans) = q_target.get_single() {
match *selectagon_vis {
Visibility::Hidden => { *selectagon_vis = Visibility::Visible; },
_ => {}
}
selectagon_trans.translation = target_trans.translation;
selectagon_trans.scale = target_trans.scale;
selectagon_trans.rotation = camera_trans.rotation;
// Enlarge Selectagon to a minimum angular diameter
let (angular_diameter, _, _) = camera::calc_angular_diameter(
&selectagon_trans, camera_trans);
let min_angular_diameter = 2.0f32.to_radians();
if angular_diameter < min_angular_diameter {
selectagon_trans.scale *= min_angular_diameter / angular_diameter;
}
}
else {
match *selectagon_vis {
Visibility::Hidden => {},
_ => { *selectagon_vis = Visibility::Hidden; }
}
}
}
}

99
src/main.rs Normal file
View file

@ -0,0 +1,99 @@
mod actor;
mod audio;
mod camera;
mod chat;
mod commands;
mod effects;
mod hud;
mod settings;
mod stars;
mod world;
#[allow(dead_code)]
mod nature;
use bevy::window::{Window, WindowMode, PrimaryWindow, CursorGrabMode};
use bevy::diagnostic::FrameTimeDiagnosticsPlugin;
use bevy::prelude::*;
use bevy_embedded_assets::{EmbeddedAssetPlugin, PluginMode};
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
if args[1] == "--version" || args[1] == "-v" {
let version = option_env!("CARGO_PKG_VERSION").unwrap();
let name = option_env!("CARGO_PKG_NAME").unwrap();
let homepage = option_env!("CARGO_PKG_HOMEPAGE").unwrap();
println!("{name} {version}");
println!("License: GNU GPL version 3: https://gnu.org/licenses/gpl.html");
println!("{homepage}");
return;
}
}
if cfg!(debug_assertions) {
App::new().add_plugins(OutFlyPlugin).run();
} else {
// In release builds, embed assets into the binary
App::new().add_plugins((
EmbeddedAssetPlugin { mode: PluginMode::ReplaceDefault },
OutFlyPlugin,
)).run();
}
}
pub struct OutFlyPlugin;
impl Plugin for OutFlyPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup);
app.add_systems(Update, handle_input);
app.insert_resource(settings::Settings::default());
app.add_plugins((
DefaultPlugins,//.set(ImagePlugin::default_nearest()),
FrameTimeDiagnosticsPlugin,
actor::ActorPlugin,
audio::AudioPlugin,
camera::CameraPlugin,
chat::ChatPlugin,
commands::CommandsPlugin,
effects::EffectsPlugin,
hud::HudPlugin,
world::WorldPlugin,
));
}
}
fn setup(
mut windows: Query<&mut Window, With<PrimaryWindow>>,
) {
for mut window in &mut windows {
window.cursor.grab_mode = CursorGrabMode::Locked;
window.cursor.visible = false;
window.mode = WindowMode::BorderlessFullscreen;
window.title = "OutFly".to_string();
}
}
fn handle_input(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut settings: ResMut<settings::Settings>,
mut app_exit_events: ResMut<Events<bevy::app::AppExit>>,
mut windows: Query<&mut Window, With<PrimaryWindow>>,
) {
if keyboard_input.pressed(settings.key_exit) {
app_exit_events.send(bevy::app::AppExit);
}
if keyboard_input.just_pressed(settings.key_fullscreen) {
for mut window in &mut windows {
window.mode = if window.mode == WindowMode::Windowed {
WindowMode::BorderlessFullscreen
} else {
WindowMode::Windowed
}
}
}
if keyboard_input.just_pressed(settings.key_restart) {
settings.reset();
}
}

105
src/nature.rs Normal file
View file

@ -0,0 +1,105 @@
// This stuff here, this stuff is messy. Nobody wants to deal with this,
// nobody cares how it works, but I guess we need it as an ingredient for
// the universe *sigh* so here we go.
pub const OXYGEN_USE_KG_PER_S: f32 = 1e-5;
pub const OXY_S: f32 = OXYGEN_USE_KG_PER_S;
pub const OXY_M: f32 = OXYGEN_USE_KG_PER_S * 60.0;
pub const OXY_H: f32 = OXYGEN_USE_KG_PER_S * 60.0 * 60.0;
pub const OXY_D: f32 = OXYGEN_USE_KG_PER_S * 60.0 * 60.0 * 24.0;
pub const LIGHTYEAR2METER: f64 = 9_460_730_472_580_800.0;
pub const PARSEC2METER: f64 = 3.0857e16;
pub const DIST_JUPTER_SUN: f64 = 778479.0e6;
pub const EARTH_GRAVITY: f32 = 9.81;
pub fn star_color_index_to_rgb(color_index: f32) -> (f32, f32, f32) {
let temperature = 4600.0 * ((1.0 / (0.92 * color_index + 1.7)) + (1.0 / (0.92 * color_index + 0.62)));
let (red, green, blue) = if temperature <= 6600.0 {
let red = 255.0;
let green = 99.4708025861 * (temperature / 100.0).ln() - 161.1195681661;
let blue = if temperature <= 2000.0 {
0.0
} else {
138.5177312231 * ((temperature / 100.0) - 10.0).ln() - 305.0447927307
};
(red, green, blue)
} else {
let red = 329.698727446 * ((temperature / 100.0 - 60.0).powf(-0.1332047592));
let green = 288.1221695283 * ((temperature / 100.0 - 60.0).powf(-0.0755148492));
let blue = 255.0;
(red, green, blue)
};
let clamp = |x: f32| -> f32 { (x / 255.0).max(0.0).min(1.0) };
return (clamp(red), clamp(green), clamp(blue))
}
fn smooth_edge(start: f32, end: f32, value: f32) -> f32 {
let x: f32 = (value - start) / (end - start);
return 4.0 * x * x * (1.0 - x * x);
}
pub fn ring_density(radius: f32) -> f32 {
// NOTE: Keep this in sync with assets/shaders/jupiters_rings.wgsl
// Input: distance to center of jupiter in million meters
// Output: relative brightness of the ring
let halo_inner: f32 = 92.0;
let halo_outer: f32 = 122.5;
let main_inner: f32 = 122.5;
let main_outer: f32 = 129.0;
let amalthea_inner: f32 = 129.0;
let amalthea_outer: f32 = 182.0;
let thebe_inner: f32 = 129.0;
let thebe_outer: f32 = 229.0;
let metis_notch_center: f32 = 128.0;
let metis_notch_width: f32 = 0.6;
let halo_brightness: f32 = 0.75;
let main_brightness: f32 = 1.0;
let almathea_brightness: f32 = 0.5;
let thebe_brightness: f32 = 0.5;
let mut density: f32 = 0.0;
if radius >= halo_inner && radius <= halo_outer {
density = halo_brightness * smooth_edge(halo_inner, halo_outer, radius);
} else if radius >= main_inner && radius <= main_outer {
let mut metis_notch_effect: f32 = 1.0;
if radius > metis_notch_center - metis_notch_width * 0.5 && radius < metis_notch_center + metis_notch_width * 0.5 {
metis_notch_effect = 0.5 * (1.0 - smooth_edge(metis_notch_center - metis_notch_width * 0.5, metis_notch_center + metis_notch_width * 0.5, radius));
}
density = main_brightness * metis_notch_effect * smooth_edge(main_inner, main_outer, radius);
} else {
if radius >= amalthea_inner && radius <= amalthea_outer {
density = almathea_brightness * smooth_edge(amalthea_inner, amalthea_outer, radius);
}
if radius >= thebe_inner && radius <= thebe_outer {
density += thebe_brightness * smooth_edge(thebe_inner, thebe_outer, radius);
}
}
return density;
}
pub fn readable_distance(distance: f64) -> String {
let abs_distance = distance.abs();
if abs_distance > LIGHTYEAR2METER * 0.001 {
let lightyears = distance / LIGHTYEAR2METER;
return format!("{lightyears:.3}ly");
}
if abs_distance >= 1.0e10 {
let gigameters = distance * 1.0e-9;
return format!("{gigameters:.1}Gm");
}
if abs_distance >= 1.0e7 {
let megameters = distance * 1.0e-6;
return format!("{megameters:.1}Mm");
}
if abs_distance >= 1.0e4 {
let kilometers = distance * 1.0e-3;
return format!("{kilometers:.1}km");
}
return format!("{distance:.1}m");
}

173
src/settings.rs Normal file
View file

@ -0,0 +1,173 @@
use bevy::prelude::*;
use std::env;
#[derive(Resource)]
pub struct Settings {
pub dev_mode: bool,
pub god_mode: bool,
pub mute_sfx: bool,
pub mute_music: bool,
pub volume_sfx: u8,
pub volume_music: u8,
pub mouse_sensitivity: f32,
pub fov: f32,
pub fov_highspeed: f32,
pub zoom_fov: f32,
pub zoom_sensitivity_factor: f32,
pub font_size_hud: f32,
pub font_size_conversations: f32,
pub hud_active: bool,
pub is_zooming: bool,
pub third_person: bool,
pub key_selectobject: MouseButton,
pub key_zoom: MouseButton,
pub key_togglehud: KeyCode,
pub key_exit: KeyCode,
pub key_restart: KeyCode,
pub key_fullscreen: KeyCode,
pub key_forward: KeyCode,
pub key_back: KeyCode,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub key_run: KeyCode,
pub key_stop: KeyCode,
pub key_interact: KeyCode,
pub key_vehicle: KeyCode,
pub key_camera: KeyCode,
pub key_rotate: KeyCode,
pub key_mouseup: KeyCode,
pub key_mousedown: KeyCode,
pub key_mouseleft: KeyCode,
pub key_mouseright: KeyCode,
pub key_rotateleft: KeyCode,
pub key_rotateright: KeyCode,
pub key_reply1: KeyCode,
pub key_reply2: KeyCode,
pub key_reply3: KeyCode,
pub key_reply4: KeyCode,
pub key_reply5: KeyCode,
pub key_reply6: KeyCode,
pub key_reply7: KeyCode,
pub key_reply8: KeyCode,
pub key_reply9: KeyCode,
pub key_reply10: KeyCode,
pub key_cheat_god_mode: KeyCode,
pub key_cheat_stop: KeyCode,
pub key_cheat_speed: KeyCode,
pub key_cheat_speed_backward: KeyCode,
pub key_cheat_pizza: KeyCode,
pub key_cheat_farview1: KeyCode,
pub key_cheat_farview2: KeyCode,
pub key_cheat_adrenaline_zero: KeyCode,
pub key_cheat_adrenaline_mid: KeyCode,
pub key_cheat_adrenaline_max: KeyCode,
pub key_cheat_die: KeyCode,
}
impl Default for Settings {
fn default() -> Self {
let dev_mode;
let default_mute_sfx = false;
let default_mute_music;
if let Ok(_) = env::var("CARGO") {
// Mute audio by default when run through `cargo`
default_mute_music = cfg!(debug_assertions);
// Enable dev mode when running `cargo run` without `--release`
dev_mode = cfg!(debug_assertions);
}
else {
default_mute_music = false;
dev_mode = false;
}
Settings {
dev_mode: dev_mode,
god_mode: false,
mute_sfx: default_mute_sfx,
mute_music: default_mute_music,
volume_sfx: 100,
volume_music: 100,
mouse_sensitivity: 0.7,
fov: 50.0,
fov_highspeed: 25.0,
zoom_fov: 15.0,
zoom_sensitivity_factor: 0.25,
font_size_hud: 32.0,
font_size_conversations: 32.0,
hud_active: false,
is_zooming: false,
third_person: false,
key_selectobject: MouseButton::Left,
key_zoom: MouseButton::Right,
key_togglehud: KeyCode::Tab,
key_exit: KeyCode::Escape,
key_restart: KeyCode::F12,
key_fullscreen: KeyCode::F11,
key_forward: KeyCode::KeyW,
key_back: KeyCode::KeyS,
key_left: KeyCode::KeyA,
key_right: KeyCode::KeyD,
key_up: KeyCode::ShiftLeft,
key_down: KeyCode::ControlLeft,
key_run: KeyCode::KeyR,
key_stop: KeyCode::Space,
key_interact: KeyCode::KeyE,
key_vehicle: KeyCode::KeyQ,
key_camera: KeyCode::KeyF,
key_rotate: KeyCode::KeyR,
key_mouseup: KeyCode::KeyI,
key_mousedown: KeyCode::KeyK,
key_mouseleft: KeyCode::KeyJ,
key_mouseright: KeyCode::KeyL,
key_rotateleft: KeyCode::KeyU,
key_rotateright: KeyCode::KeyO,
key_reply1: KeyCode::Digit1,
key_reply2: KeyCode::Digit2,
key_reply3: KeyCode::Digit3,
key_reply4: KeyCode::Digit4,
key_reply5: KeyCode::Digit5,
key_reply6: KeyCode::Digit6,
key_reply7: KeyCode::Digit7,
key_reply8: KeyCode::Digit8,
key_reply9: KeyCode::Digit9,
key_reply10: KeyCode::Digit0,
key_cheat_god_mode: KeyCode::KeyG,
key_cheat_stop: KeyCode::KeyC,
key_cheat_speed: KeyCode::KeyV,
key_cheat_speed_backward: KeyCode::KeyB,
key_cheat_pizza: KeyCode::F8,
key_cheat_farview1: KeyCode::F9,
key_cheat_farview2: KeyCode::F10,
key_cheat_adrenaline_zero: KeyCode::F5,
key_cheat_adrenaline_mid: KeyCode::F6,
key_cheat_adrenaline_max: KeyCode::F7,
key_cheat_die: KeyCode::KeyZ,
}
}
}
impl Settings {
pub fn reset(&mut self) {
println!("Resetting settings!");
*self = Self::default();
}
pub fn get_reply_keys(&self) -> [KeyCode; 10] {
return [
self.key_reply1,
self.key_reply2,
self.key_reply3,
self.key_reply4,
self.key_reply5,
self.key_reply6,
self.key_reply7,
self.key_reply8,
self.key_reply9,
self.key_reply10,
];
}
}

15551
src/stars.rs Normal file

File diff suppressed because it is too large Load diff

502
src/world.rs Normal file
View file

@ -0,0 +1,502 @@
use crate::{actor, audio, hud, nature, settings, stars};
use bevy::prelude::*;
use bevy::render::render_resource::{AsBindGroup, ShaderRef};
use bevy::math::{DVec3, I64Vec3};
use bevy::scene::{InstanceId, SceneInstance};
use bevy_xpbd_3d::prelude::*;
use bevy_xpbd_3d::plugins::sync::SyncConfig;
use std::collections::HashMap;
use std::f32::consts::PI;
use fastrand;
const ASTEROID_UPDATE_INTERVAL: f32 = 0.1; // seconds
const ASTEROID_SIZE_FACTOR: f32 = 10.0;
const RING_THICKNESS: f64 = 8.0e6;
const STARS_MAX_MAGNITUDE: f32 = 5.5;
const CENTER_WORLD_ON_PLAYER: bool = true;
const ASTEROID_SPAWN_STEP: f64 = 500.0;
const ASTEROID_VIEW_RADIUS: f64 = 3000.0;
const ASSET_ASTEROID1: &str = "models/asteroid.glb#Scene0";
const ASSET_ASTEROID2: &str = "models/asteroid2.glb#Scene0";
pub fn asset_name_to_path(name: &str) -> &'static str {
match name {
"suit" => "models/suit.glb#Scene0",
"asteroid1" => ASSET_ASTEROID1,
"asteroid2" => ASSET_ASTEROID2,
"moonlet" => "models/moonlet.glb#Scene0",
"monolith" => "models/monolith_neon.glb#Scene0",
"lightorb" => "models/lightorb.glb#Scene0",
"MeteorAceGT" => "models/MeteorAceGT.glb#Scene0",
"satellite" => "models/satellite.glb#Scene0",
"pizzeria" => "models/pizzeria2.glb#Scene0",
"pizzasign" => "models/pizzasign.glb#Scene0",
"selectagon" => "models/selectagon.glb#Scene0",
_ => "models/error.glb#Scene0",
}
}
pub struct WorldPlugin;
impl Plugin for WorldPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup);
app.add_systems(Update, handle_cheats);
app.add_systems(PostUpdate, handle_despawn);
app.add_systems(Update, spawn_despawn_asteroids);
app.add_plugins(PhysicsPlugins::default());
app.add_plugins(MaterialPlugin::<RingMaterial>::default());
//app.add_plugins(PhysicsDebugPlugin::default());
app.insert_resource(Gravity(DVec3::splat(0.0)));
app.insert_resource(AsteroidUpdateTimer(
Timer::from_seconds(ASTEROID_UPDATE_INTERVAL, TimerMode::Repeating)));
app.insert_resource(AsteroidDatabase(Vec::new()));
app.insert_resource(ActiveAsteroids(HashMap::new()));
app.add_event::<DespawnEvent>();
if CENTER_WORLD_ON_PLAYER {
// Disable bevy_xpbd's position->transform sync function
app.insert_resource(SyncConfig {
position_to_transform: false,
transform_to_position: false,
});
// Add own position->transform sync function
app.add_systems(PreUpdate, position_to_transform);
}
}
}
#[derive(Resource)] struct AsteroidUpdateTimer(Timer);
#[derive(Resource)] struct AsteroidDatabase(Vec<AsteroidData>);
#[derive(Resource)] struct ActiveAsteroids(HashMap<I64Vec3, AsteroidData>);
#[derive(Resource)] struct AsteroidModel1(Handle<Scene>);
#[derive(Resource)] struct AsteroidModel2(Handle<Scene>);
#[derive(Component)] struct Asteroid;
#[derive(Component)] pub struct DespawnOnPlayerDeath;
struct AsteroidData {
entity: Entity,
//viewdistance: f64,
}
#[derive(Event)]
pub struct DespawnEvent {
entity: Entity,
sceneinstance: InstanceId,
origin: I64Vec3,
}
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
pub struct RingMaterial {
alpha_mode: AlphaMode,
#[uniform(0)]
ring_radius: f32,
#[uniform(1)]
jupiter_radius: f32,
}
impl Material for RingMaterial {
fn fragment_shader() -> ShaderRef {
"shaders/jupiters_rings.wgsl".into()
}
fn alpha_mode(&self) -> AlphaMode {
self.alpha_mode
}
}
#[derive(Component)]
pub struct Star;
pub fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut materials_custom: ResMut<Assets<RingMaterial>>,
asset_server: Res<AssetServer>,
) {
// Load assets
commands.insert_resource(AsteroidModel1(asset_server.load(ASSET_ASTEROID1)));
commands.insert_resource(AsteroidModel2(asset_server.load(ASSET_ASTEROID2)));
// Generate starmap
let sphere_handle = meshes.add(Sphere::new(1.0));
let mut starcount = 0;
for star in stars::STARS {
let mag = star.3;
if mag > STARS_MAX_MAGNITUDE {
continue;
}
let is_sun = mag < -20.0;
let scale_color = {|color: f32|
if is_sun {
color * 13.0f32
} else {
color * (0.0659663 * mag * mag - 1.09862 * mag + 4.3)
}
};
let scale_size = {|mag: f32|
if is_sun {
40000.0f32
} else {
1000.0 * (0.230299 * mag * mag - 3.09013 * mag + 15.1782)
} * 100.0
};
let (r, g, b) = nature::star_color_index_to_rgb(star.4);
let star_color_handle = materials.add(StandardMaterial {
base_color: Color::rgb(scale_color(r), scale_color(g), scale_color(b)),
unlit: true,
..default()
});
let mesh_distance = 1e9;
let starchart_distance = if is_sun {
Some(nature::DIST_JUPTER_SUN)
} else if star.5 >= 100000.0 {
None
} else {
Some(nature::PARSEC2METER * star.5 as f64)
};
let name = if star.6.is_empty() {
"Uncharted Star".to_string()
} else {
star.6.to_string()
};
commands.spawn((
Star,
hud::IsClickable {
name: Some(name),
distance: starchart_distance,
},
PbrBundle {
mesh: sphere_handle.clone(),
material: star_color_handle,
transform: Transform::from_xyz(
mesh_distance * star.0,
mesh_distance * star.1,
mesh_distance * star.2,
)
.with_scale(Vec3::splat(scale_size(mag))),
..default()
}
));
starcount += 1;
}
info!("Generated {starcount} stars");
// Add shaded ring
let ring_radius = 229_000_000.0;
let jupiter_radius = 71_492_000.0;
commands.spawn((
MaterialMeshBundle {
mesh: meshes.add(Mesh::from(Cylinder::new(ring_radius, 1.0))),
material: materials_custom.add(RingMaterial {
alpha_mode: AlphaMode::Blend,
ring_radius: ring_radius,
jupiter_radius: jupiter_radius,
}),
..default()
},
Position::from_xyz(0.0, 0.0, 0.0),
Rotation::from(Quat::IDENTITY),
//Rotation::from(Quat::from_rotation_x(-0.3f32.to_radians())),
));
}
fn spawn_despawn_asteroids(
time: Res<Time>,
mut timer: ResMut<AsteroidUpdateTimer>,
mut commands: Commands,
q_player: Query<&Position, With<actor::PlayerCamera>>,
mut ew_despawn: EventWriter<DespawnEvent>,
mut db: ResMut<ActiveAsteroids>,
asteroid1_handle: Res<AsteroidModel1>,
asteroid2_handle: Res<AsteroidModel2>,
mut q_asteroid: Query<(Entity, &SceneInstance), With<Asteroid>>,
mut last_player_cell: Local<I64Vec3>,
) {
if !timer.0.tick(time.delta()).just_finished() || q_player.is_empty() {
//if q_player.is_empty() {
return;
}
let player = q_player.get_single().unwrap();
let player_cell = I64Vec3::new(
(player.x / ASTEROID_SPAWN_STEP).round() as i64,
(player.y / ASTEROID_SPAWN_STEP).round() as i64,
(player.z / ASTEROID_SPAWN_STEP).round() as i64,
);
if *last_player_cell == player_cell {
return;
}
*last_player_cell = player_cell;
// Parameters
let view_radius: f64 = ASTEROID_VIEW_RADIUS;
let step: f64 = ASTEROID_SPAWN_STEP;
let stepmax: i64 = (view_radius / step) as i64;
// Despawn far asteroids
let x_min = player_cell.x - stepmax;
let x_max = player_cell.x + stepmax;
let y_min = player_cell.y - stepmax;
let y_max = player_cell.y + stepmax;
let z_min = player_cell.z - stepmax;
let z_max = player_cell.z + stepmax;
for (origin, asteroid) in db.0.iter() {
if origin.x < x_min || origin.x > x_max
|| origin.y < y_min || origin.y > y_max
|| origin.z < z_min || origin.z > z_max
{
let mut despawning_worked = false;
for (ent, sceneinstance) in &mut q_asteroid {
if ent == asteroid.entity {
ew_despawn.send(DespawnEvent {
entity: asteroid.entity,
sceneinstance: **sceneinstance,
origin: origin.clone(),
});
despawning_worked = true;
break;
}
}
if !despawning_worked {
error!("Couldn't despawn asteroid:");
dbg!(origin);
}
}
}
// Density based on the radius alone
let radius_plane = (player.x * player.x + player.z * player.z).sqrt();
let density_r = nature::ring_density((radius_plane / 1e6) as f32);
if density_r < 0.001 {
return;
}
// Density based on radius and the vertical distance to the ring
let normalized_distance = player.y / (RING_THICKNESS / 2.0);
let density = density_r * (-4.0 * normalized_distance.powf(2.0)).exp() as f32;
if density < 0.001 {
return;
}
let mut rng = fastrand::Rng::new();
for x in -stepmax..=stepmax {
for y in -stepmax..=stepmax {
for z in -stepmax..=stepmax {
let origin = I64Vec3::new(
player_cell.x + x as i64,
player_cell.y + y as i64,
player_cell.z + z as i64,
);
if db.0.contains_key(&origin) {
// already in db, nothing to do
continue;
}
// Get a seed based on all of the origin axes
// Probably there's a faster way
rng.seed(origin.x as u64);
let seed = rng.u64(0..u64::MAX).wrapping_add(origin.y as u64);
rng.seed(seed);
let seed = rng.u64(0..u64::MAX).wrapping_add(origin.z as u64);
rng.seed(seed);
let rand_s = rng.f32();
let size_raw: f32 = (rand_s + 1e-4).powf(-0.5) as f32; // -> between ~1 and 100
let size_density = size_raw * density;
if size_density < 0.3 {
continue;
}
if size_raw < 20.0 {
let dist = player_cell.as_dvec3().distance(origin.as_dvec3());
if dist > 6.0 {
continue;
}
}
let size: f32 = ASTEROID_SIZE_FACTOR * size_density;
let rand_x = rng.f64();
let rand_y = rng.f64();
let rand_z = rng.f64();
let rand_c = rng.bool();
let class = if rand_c { 0 } else { 1 };
//let max_viewdist = ASTEROID_VIEW_RADIUS / ASTEROID_SPAWN_STEP;
let wobble = ASTEROID_SPAWN_STEP * 0.5;
let pos = DVec3::new(
origin.x as f64 * ASTEROID_SPAWN_STEP + wobble * rand_x * 2.0 - 1.0,
origin.y as f64 * ASTEROID_SPAWN_STEP + wobble * rand_y * 2.0 - 1.0,
origin.z as f64 * ASTEROID_SPAWN_STEP + wobble * rand_z * 2.0 - 1.0,
);
// Spawn
let mut entity_commands = commands.spawn((
actor::Actor::default(),
RigidBody::Dynamic,
AngularVelocity(DVec3::new(0.1, 0.1, 0.03)),
LinearVelocity(DVec3::new(0.0, 0.0, 0.35)),
Collider::sphere(1.0),
Rotation::from(Quat::from_rotation_y(-PI / 3.)),
Position::new(pos),
Asteroid,
));
let model = match class {
0 => asteroid1_handle.0.clone(),
_ => asteroid2_handle.0.clone(),
};
entity_commands.insert(SceneBundle {
scene: model,
transform: Transform {
scale: Vec3::splat(size),
..default()
},
..default()
});
db.0.insert(origin, AsteroidData {
entity: entity_commands.id(),
//viewdistance: 99999999.0,
});
}
}
}
}
fn handle_despawn(
mut commands: Commands,
mut er_despawn: EventReader<DespawnEvent>,
mut db: ResMut<ActiveAsteroids>,
mut scene_spawner: ResMut<SceneSpawner>,
) {
for despawn in er_despawn.read() {
commands.entity(despawn.entity).despawn();
scene_spawner.despawn_instance(despawn.sceneinstance);
db.0.remove(&despawn.origin);
}
}
fn handle_cheats(
key_input: Res<ButtonInput<KeyCode>>,
mut q_player: Query<(&Transform, &mut Position, &mut LinearVelocity), With<actor::PlayerCamera>>,
mut q_life: Query<(&mut actor::LifeForm, &mut actor::ExperiencesGForce), With<actor::Player>>,
mut ew_playerdies: EventWriter<actor::PlayerDiesEvent>,
mut settings: ResMut<settings::Settings>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
) {
if q_player.is_empty() || q_life.is_empty() {
return;
}
let (trans, mut pos, mut v) = q_player.get_single_mut().unwrap();
let (mut lifeform, mut gforce) = q_life.get_single_mut().unwrap();
let boost = if key_input.pressed(KeyCode::ShiftLeft) {
1e6
} else {
1e3
};
if key_input.just_pressed(settings.key_cheat_god_mode) {
settings.god_mode ^= true;
if settings.god_mode {
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::EnterVehicle));
}
}
if !settings.god_mode && !settings.dev_mode {
return;
}
if key_input.just_pressed(settings.key_cheat_stop) {
gforce.ignore_gforce_seconds = 1.0;
v.0 = DVec3::ZERO;
}
if key_input.pressed(settings.key_cheat_speed) {
gforce.ignore_gforce_seconds = 1.0;
v.0 += DVec3::from(trans.rotation * Vec3::new(0.0, 0.0, boost));
}
if key_input.pressed(settings.key_cheat_speed_backward) {
gforce.ignore_gforce_seconds = 1.0;
v.0 += DVec3::from(trans.rotation * Vec3::new(0.0, 0.0, -boost));
}
if !settings.dev_mode {
return;
}
if key_input.just_pressed(settings.key_cheat_pizza) {
pos.0 = DVec3::new(-303370.0, 0.0, -500000.0);
gforce.ignore_gforce_seconds = 1.0;
}
if key_input.just_pressed(settings.key_cheat_farview1) {
pos.0 = DVec3::new(-1000.0e6, 1000.0e6, -500.0e6);
gforce.ignore_gforce_seconds = 1.0;
}
if key_input.just_pressed(settings.key_cheat_farview2) {
pos.0 = DVec3::new(1000.0e6, 1000.0e6, -500.0e6);
gforce.ignore_gforce_seconds = 1.0;
}
if key_input.pressed(settings.key_cheat_adrenaline_zero) {
lifeform.adrenaline = 0.0;
}
if key_input.pressed(settings.key_cheat_adrenaline_mid) {
lifeform.adrenaline = 0.5;
}
if key_input.pressed(settings.key_cheat_adrenaline_max) {
lifeform.adrenaline = 1.0;
}
if key_input.just_pressed(settings.key_cheat_die) {
ew_playerdies.send(actor::PlayerDiesEvent);
}
}
// A variant of bevy_xpbd_3d::plugins::position_to_transform that adjusts
// the rendering position to center entities at the player camera.
// This avoids rendering glitches when very far away from the origin.
pub fn position_to_transform(
q_player: Query<&Position, With<actor::PlayerCamera>>,
mut q_trans: Query<(&'static mut Transform, &'static Position, &'static Rotation, Option<&'static Parent>)>,
parents: Query<(&'static GlobalTransform, Option<&'static Position>, Option<&'static Rotation>), With<Children>>,
) {
if let Ok(player_pos) = q_player.get_single() {
for (mut transform, pos, rot, parent) in &mut q_trans {
if let Some(parent) = parent {
if let Ok((parent_transform, parent_pos, parent_rot)) = parents.get(**parent) {
// Compute the global transform of the parent using its Position and Rotation
let parent_transform = parent_transform.compute_transform();
let parent_pos = parent_pos.map_or(parent_transform.translation, |pos| {
pos.as_vec3()
// NOTE: I commented out this because it turns a vec3 to a vec4,
// and I don't understand why bevy_xpbd would do that.
//.extend(parent_transform.translation.z)
});
let parent_rot = parent_rot.map_or(parent_transform.rotation, |rot| {
rot.as_quat()
});
let parent_scale = parent_transform.scale;
let parent_transform = Transform::from_translation(parent_pos)
.with_rotation(parent_rot)
.with_scale(parent_scale);
// The new local transform of the child body,
// computed from the its global transform and its parents global transform
let new_transform = GlobalTransform::from(
Transform::from_translation(
pos.as_vec3()
// NOTE: I commented out this because it turns a vec3 to a vec4,
// and I don't understand why bevy_xpbd would do that.
//.extend(parent_pos.z + transform.translation.z * parent_scale.z),
)
.with_rotation(rot.as_quat()),
)
.reparented_to(&GlobalTransform::from(parent_transform));
transform.translation = new_transform.translation;
transform.rotation = new_transform.rotation;
}
} else {
transform.translation = Vec3::new(
(pos.x - player_pos.x) as f32,
(pos.y - player_pos.y) as f32,
(pos.z - player_pos.z) as f32,
);
transform.rotation = rot.as_quat();
}
}
}
}