From bee5e0f11d67e8d9b0622cdf137880c5ccc0531c Mon Sep 17 00:00:00 2001 From: Avii Date: Fri, 14 Aug 2026 23:08:42 +0200 Subject: [PATCH] no clue what the current status is --- .gitignore | 0 Cargo.lock | 0 Cargo.toml | 0 LICENSE | 18 +- config.toml | 0 crates/dcs-grpc/Cargo.toml | 0 crates/dcs-grpc/LICENSE | 1320 ++++++++--------- crates/dcs-grpc/build.rs | 0 .../protos/dcs/atmosphere/v0/atmosphere.proto | 0 .../protos/dcs/coalition/v0/coalition.proto | 0 .../protos/dcs/common/v0/common.proto | 0 .../protos/dcs/controller/v0/controller.proto | 0 .../protos/dcs/custom/v0/custom.proto | 0 crates/dcs-grpc/protos/dcs/dcs.proto | 0 .../dcs-grpc/protos/dcs/group/v0/group.proto | 0 crates/dcs-grpc/protos/dcs/hook/v0/hook.proto | 0 .../protos/dcs/mission/v0/mission.proto | 0 crates/dcs-grpc/protos/dcs/net/v0/net.proto | 0 crates/dcs-grpc/protos/dcs/srs/v0/srs.proto | 0 .../dcs-grpc/protos/dcs/timer/v0/timer.proto | 0 .../protos/dcs/trigger/v0/trigger.proto | 0 crates/dcs-grpc/protos/dcs/unit/v0/unit.proto | 0 .../dcs-grpc/protos/dcs/world/v0/world.proto | 0 crates/dcs-grpc/src/dcs/atmosphere.rs | 0 crates/dcs-grpc/src/dcs/coalition.rs | 0 crates/dcs-grpc/src/dcs/common.rs | 0 crates/dcs-grpc/src/dcs/controller.rs | 0 crates/dcs-grpc/src/dcs/custom.rs | 0 crates/dcs-grpc/src/dcs/group.rs | 0 crates/dcs-grpc/src/dcs/hook.rs | 0 crates/dcs-grpc/src/dcs/mission.rs | 0 crates/dcs-grpc/src/dcs/mod.rs | 0 crates/dcs-grpc/src/dcs/net.rs | 0 crates/dcs-grpc/src/dcs/srs.rs | 0 crates/dcs-grpc/src/dcs/timer.rs | 0 crates/dcs-grpc/src/dcs/trigger.rs | 0 crates/dcs-grpc/src/dcs/unit.rs | 0 crates/dcs-grpc/src/dcs/utils.rs | 0 crates/dcs-grpc/src/dcs/world.rs | 0 crates/dcs-grpc/src/lib.rs | 0 crates/guardian_commands/Cargo.toml | 0 crates/guardian_commands/src/call.rs | 902 +++++------ crates/guardian_commands/src/console.rs | 1098 +++++++------- crates/guardian_commands/src/lib.rs | 0 crates/guardian_commands/src/parser.rs | 388 ++--- crates/guardian_core/Cargo.toml | 0 crates/guardian_core/src/components/awacs.rs | 8 +- .../guardian_core/src/components/callsign.rs | 210 +-- crates/guardian_core/src/components/group.rs | 14 +- .../src/components/grpc_base_url.rs | 188 +-- .../guardian_core/src/components/heading.rs | 8 +- crates/guardian_core/src/components/id.rs | 44 +- crates/guardian_core/src/components/mod.rs | 54 +- crates/guardian_core/src/components/player.rs | 158 +- .../guardian_core/src/components/position.rs | 98 +- crates/guardian_core/src/components/side.rs | 20 +- .../src/components/srs_socket_addr.rs | 68 +- .../src/components/stt_base_url.rs | 164 +- .../guardian_core/src/components/unit_type.rs | 158 +- .../guardian_core/src/components/velocity.rs | 28 +- crates/guardian_core/src/dcs.rs | 58 +- crates/guardian_core/src/dcs/mission.rs | 514 +++---- crates/guardian_core/src/dcs/text.rs | 282 ++-- crates/guardian_core/src/lib.rs | 58 +- crates/guardian_core/src/srs.rs | 3 +- crates/guardian_core/src/srs/frame_queue.rs | 64 +- crates/guardian_core/src/srs/message.rs | 0 .../guardian_core/src/srs/messages_codec.rs | 0 crates/guardian_core/src/srs/voice.rs | 160 +- crates/guardian_core/src/srs/voice_codec.rs | 0 crates/guardian_core/src/srs/voice_command.rs | 0 crates/guardian_core/src/tts.rs | 418 +++--- rust-toolchain.toml | 4 +- src/braa.rs | 194 +-- src/commands/bogeydope.rs | 186 +-- src/commands/cleartripwire.rs | 120 +- src/commands/mod.rs | 46 +- src/commands/radiocheck.rs | 114 +- src/commands/tripwire.rs | 206 +-- src/config.rs | 0 src/main.rs | 0 src/tripwire.rs | 182 +-- 82 files changed, 3778 insertions(+), 3777 deletions(-) mode change 100644 => 100755 .gitignore mode change 100644 => 100755 Cargo.lock mode change 100644 => 100755 Cargo.toml mode change 100644 => 100755 LICENSE mode change 100644 => 100755 config.toml mode change 100644 => 100755 crates/dcs-grpc/Cargo.toml mode change 100644 => 100755 crates/dcs-grpc/LICENSE mode change 100644 => 100755 crates/dcs-grpc/build.rs mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/atmosphere/v0/atmosphere.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/coalition/v0/coalition.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/common/v0/common.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/controller/v0/controller.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/custom/v0/custom.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/dcs.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/group/v0/group.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/hook/v0/hook.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/mission/v0/mission.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/net/v0/net.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/srs/v0/srs.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/timer/v0/timer.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/trigger/v0/trigger.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/unit/v0/unit.proto mode change 100644 => 100755 crates/dcs-grpc/protos/dcs/world/v0/world.proto mode change 100644 => 100755 crates/dcs-grpc/src/dcs/atmosphere.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/coalition.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/common.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/controller.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/custom.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/group.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/hook.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/mission.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/mod.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/net.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/srs.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/timer.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/trigger.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/unit.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/utils.rs mode change 100644 => 100755 crates/dcs-grpc/src/dcs/world.rs mode change 100644 => 100755 crates/dcs-grpc/src/lib.rs mode change 100644 => 100755 crates/guardian_commands/Cargo.toml mode change 100644 => 100755 crates/guardian_commands/src/call.rs mode change 100644 => 100755 crates/guardian_commands/src/console.rs mode change 100644 => 100755 crates/guardian_commands/src/lib.rs mode change 100644 => 100755 crates/guardian_commands/src/parser.rs mode change 100644 => 100755 crates/guardian_core/Cargo.toml mode change 100644 => 100755 crates/guardian_core/src/components/awacs.rs mode change 100644 => 100755 crates/guardian_core/src/components/callsign.rs mode change 100644 => 100755 crates/guardian_core/src/components/group.rs mode change 100644 => 100755 crates/guardian_core/src/components/grpc_base_url.rs mode change 100644 => 100755 crates/guardian_core/src/components/heading.rs mode change 100644 => 100755 crates/guardian_core/src/components/id.rs mode change 100644 => 100755 crates/guardian_core/src/components/mod.rs mode change 100644 => 100755 crates/guardian_core/src/components/player.rs mode change 100644 => 100755 crates/guardian_core/src/components/position.rs mode change 100644 => 100755 crates/guardian_core/src/components/side.rs mode change 100644 => 100755 crates/guardian_core/src/components/srs_socket_addr.rs mode change 100644 => 100755 crates/guardian_core/src/components/stt_base_url.rs mode change 100644 => 100755 crates/guardian_core/src/components/unit_type.rs mode change 100644 => 100755 crates/guardian_core/src/components/velocity.rs mode change 100644 => 100755 crates/guardian_core/src/dcs.rs mode change 100644 => 100755 crates/guardian_core/src/dcs/mission.rs mode change 100644 => 100755 crates/guardian_core/src/dcs/text.rs mode change 100644 => 100755 crates/guardian_core/src/lib.rs mode change 100644 => 100755 crates/guardian_core/src/srs.rs mode change 100644 => 100755 crates/guardian_core/src/srs/frame_queue.rs mode change 100644 => 100755 crates/guardian_core/src/srs/message.rs mode change 100644 => 100755 crates/guardian_core/src/srs/messages_codec.rs mode change 100644 => 100755 crates/guardian_core/src/srs/voice.rs mode change 100644 => 100755 crates/guardian_core/src/srs/voice_codec.rs mode change 100644 => 100755 crates/guardian_core/src/srs/voice_command.rs mode change 100644 => 100755 crates/guardian_core/src/tts.rs mode change 100644 => 100755 rust-toolchain.toml mode change 100644 => 100755 src/braa.rs mode change 100644 => 100755 src/commands/bogeydope.rs mode change 100644 => 100755 src/commands/cleartripwire.rs mode change 100644 => 100755 src/commands/mod.rs mode change 100644 => 100755 src/commands/radiocheck.rs mode change 100644 => 100755 src/commands/tripwire.rs mode change 100644 => 100755 src/config.rs mode change 100644 => 100755 src/main.rs mode change 100644 => 100755 src/tripwire.rs diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/Cargo.lock b/Cargo.lock old mode 100644 new mode 100755 diff --git a/Cargo.toml b/Cargo.toml old mode 100644 new mode 100755 diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 index 9dfb0fb..61c77aa --- a/LICENSE +++ b/LICENSE @@ -1,9 +1,9 @@ -MIT License - -Copyright (c) 2023 Avii - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +MIT License + +Copyright (c) 2023 Avii + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/config.toml b/config.toml old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/Cargo.toml b/crates/dcs-grpc/Cargo.toml old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/LICENSE b/crates/dcs-grpc/LICENSE old mode 100644 new mode 100755 index 29ebfa5..1f84167 --- a/crates/dcs-grpc/LICENSE +++ b/crates/dcs-grpc/LICENSE @@ -1,661 +1,661 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are 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. - - 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. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - 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 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 work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero 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 Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - 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 AGPL, see + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see . \ No newline at end of file diff --git a/crates/dcs-grpc/build.rs b/crates/dcs-grpc/build.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/atmosphere/v0/atmosphere.proto b/crates/dcs-grpc/protos/dcs/atmosphere/v0/atmosphere.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/coalition/v0/coalition.proto b/crates/dcs-grpc/protos/dcs/coalition/v0/coalition.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/common/v0/common.proto b/crates/dcs-grpc/protos/dcs/common/v0/common.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/controller/v0/controller.proto b/crates/dcs-grpc/protos/dcs/controller/v0/controller.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/custom/v0/custom.proto b/crates/dcs-grpc/protos/dcs/custom/v0/custom.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/dcs.proto b/crates/dcs-grpc/protos/dcs/dcs.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/group/v0/group.proto b/crates/dcs-grpc/protos/dcs/group/v0/group.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/hook/v0/hook.proto b/crates/dcs-grpc/protos/dcs/hook/v0/hook.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/mission/v0/mission.proto b/crates/dcs-grpc/protos/dcs/mission/v0/mission.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/net/v0/net.proto b/crates/dcs-grpc/protos/dcs/net/v0/net.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/srs/v0/srs.proto b/crates/dcs-grpc/protos/dcs/srs/v0/srs.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/timer/v0/timer.proto b/crates/dcs-grpc/protos/dcs/timer/v0/timer.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/trigger/v0/trigger.proto b/crates/dcs-grpc/protos/dcs/trigger/v0/trigger.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/unit/v0/unit.proto b/crates/dcs-grpc/protos/dcs/unit/v0/unit.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/protos/dcs/world/v0/world.proto b/crates/dcs-grpc/protos/dcs/world/v0/world.proto old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/atmosphere.rs b/crates/dcs-grpc/src/dcs/atmosphere.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/coalition.rs b/crates/dcs-grpc/src/dcs/coalition.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/common.rs b/crates/dcs-grpc/src/dcs/common.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/controller.rs b/crates/dcs-grpc/src/dcs/controller.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/custom.rs b/crates/dcs-grpc/src/dcs/custom.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/group.rs b/crates/dcs-grpc/src/dcs/group.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/hook.rs b/crates/dcs-grpc/src/dcs/hook.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/mission.rs b/crates/dcs-grpc/src/dcs/mission.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/mod.rs b/crates/dcs-grpc/src/dcs/mod.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/net.rs b/crates/dcs-grpc/src/dcs/net.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/srs.rs b/crates/dcs-grpc/src/dcs/srs.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/timer.rs b/crates/dcs-grpc/src/dcs/timer.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/trigger.rs b/crates/dcs-grpc/src/dcs/trigger.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/unit.rs b/crates/dcs-grpc/src/dcs/unit.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/utils.rs b/crates/dcs-grpc/src/dcs/utils.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/dcs/world.rs b/crates/dcs-grpc/src/dcs/world.rs old mode 100644 new mode 100755 diff --git a/crates/dcs-grpc/src/lib.rs b/crates/dcs-grpc/src/lib.rs old mode 100644 new mode 100755 diff --git a/crates/guardian_commands/Cargo.toml b/crates/guardian_commands/Cargo.toml old mode 100644 new mode 100755 diff --git a/crates/guardian_commands/src/call.rs b/crates/guardian_commands/src/call.rs old mode 100644 new mode 100755 index c2c31d1..1808b05 --- a/crates/guardian_commands/src/call.rs +++ b/crates/guardian_commands/src/call.rs @@ -1,451 +1,451 @@ -use std::fmt::Display; - -use nom::branch::alt; -use nom::bytes::complete::{tag, tag_no_case}; -use nom::character::complete::{alpha1, alphanumeric1, char, multispace0}; -use nom::combinator::{map, opt, recognize}; -use nom::error::ErrorKind; -use nom::sequence::tuple; -use nom::{Err as NomError, IResult}; - -#[derive(Debug)] -pub enum Awacs { - Overlord, - Magic, - Wizard, - Focus, - Darkstar, -} - -#[derive(Debug)] -pub enum Receiver { - Awacs(Awacs), - Atc(String), //airfield name -} - -impl Display for Receiver { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Receiver::Awacs(Awacs::Overlord) => write!(f, "Overlord"), - Receiver::Awacs(Awacs::Magic) => write!(f, "Magic"), - Receiver::Awacs(Awacs::Wizard) => write!(f, "Wizard"), - Receiver::Awacs(Awacs::Focus) => write!(f, "Focus"), - Receiver::Awacs(Awacs::Darkstar) => write!(f, "Darkstar"), - Receiver::Atc(airfield) => write!(f, "{}", airfield.to_owned()), - } - } -} - -// impl ToString for Receiver { -// fn to_string(&self) -> String { -// match self { -// Receiver::Awacs(Awacs::Overlord) => "Overlord".to_string(), -// Receiver::Awacs(Awacs::Darkstar) => "Darkstar".to_string(), -// Receiver::Atc(airfield) => airfield.to_owned(), -// } -// } -// } - -fn parse_receiver(input: &str) -> IResult<&str, Receiver> { - alt(( - map(tag_no_case("overlord"), |_| { - Receiver::Awacs(Awacs::Overlord) - }), - map(tag_no_case("magic"), |_| Receiver::Awacs(Awacs::Magic)), - map(tag_no_case("wizard"), |_| Receiver::Awacs(Awacs::Wizard)), - map(tag_no_case("focus"), |_| Receiver::Awacs(Awacs::Focus)), - map(tag_no_case("darkstar"), |_| { - Receiver::Awacs(Awacs::Darkstar) - }), - map(alphanumeric1, |e: &str| Receiver::Atc(e.to_owned())), // anything else = airfield? airfields _can_ contain spaces though.. soo w... hmm... parsing that is a bitch - ))(input) -} - -#[derive(Debug)] -pub enum Squadron { - Enfield, - Springfield, - Uzi, - Colt, - Dodge, - Ford, - Chevy, - Pontiac, - Viper, - Venom, - Lobo, - Cowboy, - Python, - Rattler, - Panther, - Wolf, - Weasel, - Wild, - Ninja, - Jedi, - Hawg, - Boar, - Pig, - Tusk, - ArmyAir, - Apache, - Crow, - Chaos, - Sioux, - Gatling, - Gunslinger, - Hammerhead, - Bootleg, - Palehorse, - Carnivore, - Saber, - Hornet, - Squid, - Ragin, - Roman, - Sting, - Jury, - Joker, - Ram, - Hawk, - Devil, - Check, - Snake, - Custom(String), -} - -impl ToString for Squadron { - fn to_string(&self) -> String { - match self { - Squadron::Enfield => "Enfield".to_string(), - Squadron::Springfield => "Springfield".to_string(), - Squadron::Uzi => "Uzi".to_string(), - Squadron::Colt => "Colt".to_string(), - Squadron::Dodge => "Dodge".to_string(), - Squadron::Ford => "Ford".to_string(), - Squadron::Chevy => "Chevy".to_string(), - Squadron::Hornet => "Hornet".to_string(), - Squadron::Pontiac => "Pontiac".to_string(), - Squadron::Viper => "Viper".to_string(), - Squadron::Venom => "Venom".to_string(), - Squadron::Lobo => "Lobo".to_string(), - Squadron::Cowboy => "Cowboy".to_string(), - Squadron::Python => "Python".to_string(), - Squadron::Rattler => "Rattler".to_string(), - Squadron::Panther => "Panther".to_string(), - Squadron::Wolf => "Wolf".to_string(), - Squadron::Weasel => "Weasel".to_string(), - Squadron::Wild => "Wild".to_string(), - Squadron::Ninja => "Ninja".to_string(), - Squadron::Jedi => "Jedi".to_string(), - Squadron::Hawg => "Hawg".to_string(), - Squadron::Boar => "Boar".to_string(), - Squadron::Pig => "Pig".to_string(), - Squadron::Tusk => "Tusk".to_string(), - Squadron::ArmyAir => "ArmyAir".to_string(), - Squadron::Apache => "Apache".to_string(), - Squadron::Crow => "Crow".to_string(), - Squadron::Chaos => "Chaos".to_string(), - Squadron::Sioux => "Sioux".to_string(), - Squadron::Gatling => "Gatling".to_string(), - Squadron::Gunslinger => "Gunslinger".to_string(), - Squadron::Hammerhead => "Hammerhead".to_string(), - Squadron::Bootleg => "Bootleg".to_string(), - Squadron::Palehorse => "Palehorse".to_string(), - Squadron::Carnivore => "Carnivore".to_string(), - Squadron::Saber => "Saber".to_string(), - Squadron::Squid => "Squid".to_string(), - Squadron::Ragin => "Ragin".to_string(), - Squadron::Roman => "Roman".to_string(), - Squadron::Sting => "Sting".to_string(), - Squadron::Jury => "Jury".to_string(), - Squadron::Joker => "Joker".to_string(), - Squadron::Ram => "Ram".to_string(), - Squadron::Hawk => "Hawk".to_string(), - Squadron::Devil => "Devil".to_string(), - Squadron::Check => "Check".to_string(), - Squadron::Snake => "Snake".to_string(), - Squadron::Custom(c) => c.to_string(), - } - } -} - -impl std::str::FromStr for Squadron { - type Err = Box; - - fn from_str(s: &str) -> Result { - match s { - "Enfield" => Ok(Squadron::Enfield), - "Springfield" => Ok(Squadron::Springfield), - "Uzi" => Ok(Squadron::Uzi), - "Colt" => Ok(Squadron::Colt), - "Dodge" => Ok(Squadron::Dodge), - "Ford" => Ok(Squadron::Ford), - "Chevy" => Ok(Squadron::Chevy), - "Hornet" => Ok(Squadron::Hornet), - "Pontiac" => Ok(Squadron::Pontiac), - "Viper" => Ok(Squadron::Viper), - "Venom" => Ok(Squadron::Venom), - "Lobo" => Ok(Squadron::Lobo), - "Cowboy" => Ok(Squadron::Cowboy), - "Python" => Ok(Squadron::Python), - "Rattler" => Ok(Squadron::Rattler), - "Panther" => Ok(Squadron::Panther), - "Wolf" => Ok(Squadron::Wolf), - "Weasel" => Ok(Squadron::Weasel), - "Wild" => Ok(Squadron::Wild), - "Ninja" => Ok(Squadron::Ninja), - "Jedi" => Ok(Squadron::Jedi), - "Hawg" => Ok(Squadron::Hawg), - "Boar" => Ok(Squadron::Boar), - "Pig" => Ok(Squadron::Pig), - "Tusk" => Ok(Squadron::Tusk), - "ArmyAir" => Ok(Squadron::ArmyAir), - "Apache" => Ok(Squadron::Apache), - "Crow" => Ok(Squadron::Crow), - "Chaos" => Ok(Squadron::Chaos), - "Sioux" => Ok(Squadron::Sioux), - "Gatling" => Ok(Squadron::Gatling), - "Gunslinger" => Ok(Squadron::Gunslinger), - "Hammerhead" => Ok(Squadron::Hammerhead), - "Bootleg" => Ok(Squadron::Bootleg), - "Palehorse" => Ok(Squadron::Palehorse), - "Carnivore" => Ok(Squadron::Carnivore), - "Saber" => Ok(Squadron::Saber), - "Squid" => Ok(Squadron::Squid), - "Ragin" => Ok(Squadron::Ragin), - "Roman" => Ok(Squadron::Roman), - "Sting" => Ok(Squadron::Sting), - "Jury" => Ok(Squadron::Jury), - "Joker" => Ok(Squadron::Joker), - "Ram" => Ok(Squadron::Ram), - "Hawk" => Ok(Squadron::Hawk), - "Devil" => Ok(Squadron::Devil), - "Check" => Ok(Squadron::Check), - "Snake" => Ok(Squadron::Snake), - c => Ok(Squadron::Custom(c.to_string())), - } - } -} - -#[derive(Debug)] -pub struct Element { - pub squadron: Squadron, - pub group: u8, - pub unit: u8, -} - -impl Display for Element { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "{} {} {}", - self.squadron.to_string(), - self.group, - self.unit - ) - } -} - -fn add_spaces_around_numbers(input: &str) -> String { - let mut result = String::new(); - let mut chars = input.chars().peekable(); - - while let Some(c) = chars.next() { - result.push(c); - - if let Some(next_char) = chars.peek() { - if next_char.is_numeric() { - result.push(' '); - } - } - } - - result -} - -impl std::str::FromStr for Element { - type Err = Box; - - fn from_str(s: &str) -> Result { - let d = add_spaces_around_numbers(s); - let mut d = d.split(' '); - let squadron: Squadron = d.next().unwrap().parse()?; - let group: u8 = d.next().unwrap().parse()?; - let unit: u8 = d.next().unwrap().parse()?; - - Ok(Element { - squadron, - group, - unit, - }) - } -} - -fn parse_element(input: &str) -> IResult<&str, Element> { - let mut parser = tuple(( - alpha1, // Squadron name - opt(multispace0), // Optional whitespace - opt(tuple(( - // Optional group - opt(multispace0), - parse_group_unit, - opt(multispace0), - ))), - opt(char('-')), - opt(tuple(( - // Optional unit - opt(multispace0), - parse_group_unit, - opt(multispace0), - ))), - )); - - let (remainder, (squadron_str, _, group_str, _, unit_str)) = parser(input)?; - - let squadron = match squadron_str.to_lowercase().as_str() { - "enfield" => Squadron::Enfield, - "springfield" => Squadron::Springfield, - "uzi" => Squadron::Uzi, - "colt" => Squadron::Colt, - "dodge" => Squadron::Dodge, - "ford" => Squadron::Ford, - "chevy" => Squadron::Chevy, - "hornet" => Squadron::Hornet, - "pontiac" => Squadron::Pontiac, - "viper" => Squadron::Viper, - "venom" => Squadron::Venom, - "lobo" => Squadron::Lobo, - "cowboy" => Squadron::Cowboy, - "python" => Squadron::Python, - "rattler" => Squadron::Rattler, - "panther" => Squadron::Panther, - "wolf" => Squadron::Wolf, - "weasel" => Squadron::Weasel, - "wild" => Squadron::Wild, - "ninja" => Squadron::Ninja, - "jedi" => Squadron::Jedi, - "hawg" => Squadron::Hawg, - "boar" => Squadron::Boar, - "pig" => Squadron::Pig, - "tusk" => Squadron::Tusk, - "armyair" => Squadron::ArmyAir, - "apache" => Squadron::Apache, - "crow" => Squadron::Crow, - "chaos" => Squadron::Chaos, - "sioux" => Squadron::Sioux, - "gatling" => Squadron::Gatling, - "gunslinger" => Squadron::Gunslinger, - "hammerhead" => Squadron::Hammerhead, - "bootleg" => Squadron::Bootleg, - "palehorse" => Squadron::Palehorse, - "carnivore" => Squadron::Carnivore, - "saber" => Squadron::Saber, - "squid" => Squadron::Squid, - "ragin" => Squadron::Ragin, - "roman" => Squadron::Roman, - "sting" => Squadron::Sting, - "jury" => Squadron::Jury, - "joker" => Squadron::Joker, - "ram" => Squadron::Ram, - "hawk" => Squadron::Hawk, - "devil" => Squadron::Devil, - "check" => Squadron::Check, - "snake" => Squadron::Snake, - c => Squadron::Custom(c.to_string()), - }; - // _ => { - // return Err(NomError::Error(nom::error::Error { - // input: squadron_str, - // code: ErrorKind::Alpha, - // })) - // } - - let group = group_str.unwrap_or((None, 0, None)).1; - let unit = unit_str.unwrap_or((None, 0, None)).1; - - Ok(( - remainder, - Element { - squadron, - group, - unit, - }, - )) -} - -fn parse_group_unit(input: &str) -> IResult<&str, u8> { - let parse_digit = map( - recognize(alt(( - char('0'), - char('1'), - char('2'), - char('3'), - char('4'), - char('5'), - char('6'), - char('7'), - char('8'), - char('9'), - ))), - |s: &str| s.parse::().unwrap(), - ); - - let parse_word = alt(( - map(tag("one"), |_| 1), - map(tag("two"), |_| 2), - map(tag("three"), |_| 3), - map(tag("four"), |_| 4), - map(tag("five"), |_| 5), - map(tag("six"), |_| 6), - map(tag("seven"), |_| 7), - map(tag("eight"), |_| 8), - map(tag("nine"), |_| 9), - )); - - alt((parse_digit, parse_word))(input) -} - -// #[derive(Debug)] -// pub enum Unit { -// NauticalMiles, -// Kilometers, -// } - -// #[derive(Debug)] -// pub enum Call { -// RadioCheck(Awacs, Element), -// Shopping(Awacs, Element), -// LocateAirfield(Awacs, Element, String), -// LocateFriendly(Awacs, Element, Element), -// Tripwire(Awacs, Element, Option, Unit), -// } - -#[derive(Debug)] -pub struct Call { - pub receiver: Receiver, - pub element: Element, - pub command: String, -} - -pub fn parse_call(input: &str) -> IResult<&str, Call> { - let mut parser = tuple((parse_receiver, multispace0, parse_element)); - - let (command, (receiver, _, element)) = parser(input)?; - - if element.group == 0 || element.unit == 0 { - return Err(NomError::Error(nom::error::Error { - input: command, - code: ErrorKind::Digit, - })); - } - - Ok(( - "", - Call { - receiver, - element, - command: command.to_string(), - }, - )) -} +use std::fmt::Display; + +use nom::branch::alt; +use nom::bytes::complete::{tag, tag_no_case}; +use nom::character::complete::{alpha1, alphanumeric1, char, multispace0}; +use nom::combinator::{map, opt, recognize}; +use nom::error::ErrorKind; +use nom::sequence::tuple; +use nom::{Err as NomError, IResult}; + +#[derive(Debug)] +pub enum Awacs { + Overlord, + Magic, + Wizard, + Focus, + Darkstar, +} + +#[derive(Debug)] +pub enum Receiver { + Awacs(Awacs), + Atc(String), //airfield name +} + +impl Display for Receiver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Receiver::Awacs(Awacs::Overlord) => write!(f, "Overlord"), + Receiver::Awacs(Awacs::Magic) => write!(f, "Magic"), + Receiver::Awacs(Awacs::Wizard) => write!(f, "Wizard"), + Receiver::Awacs(Awacs::Focus) => write!(f, "Focus"), + Receiver::Awacs(Awacs::Darkstar) => write!(f, "Darkstar"), + Receiver::Atc(airfield) => write!(f, "{}", airfield.to_owned()), + } + } +} + +// impl ToString for Receiver { +// fn to_string(&self) -> String { +// match self { +// Receiver::Awacs(Awacs::Overlord) => "Overlord".to_string(), +// Receiver::Awacs(Awacs::Darkstar) => "Darkstar".to_string(), +// Receiver::Atc(airfield) => airfield.to_owned(), +// } +// } +// } + +fn parse_receiver(input: &str) -> IResult<&str, Receiver> { + alt(( + map(tag_no_case("overlord"), |_| { + Receiver::Awacs(Awacs::Overlord) + }), + map(tag_no_case("magic"), |_| Receiver::Awacs(Awacs::Magic)), + map(tag_no_case("wizard"), |_| Receiver::Awacs(Awacs::Wizard)), + map(tag_no_case("focus"), |_| Receiver::Awacs(Awacs::Focus)), + map(tag_no_case("darkstar"), |_| { + Receiver::Awacs(Awacs::Darkstar) + }), + map(alphanumeric1, |e: &str| Receiver::Atc(e.to_owned())), // anything else = airfield? airfields _can_ contain spaces though.. soo w... hmm... parsing that is a bitch + ))(input) +} + +#[derive(Debug)] +pub enum Squadron { + Enfield, + Springfield, + Uzi, + Colt, + Dodge, + Ford, + Chevy, + Pontiac, + Viper, + Venom, + Lobo, + Cowboy, + Python, + Rattler, + Panther, + Wolf, + Weasel, + Wild, + Ninja, + Jedi, + Hawg, + Boar, + Pig, + Tusk, + ArmyAir, + Apache, + Crow, + Chaos, + Sioux, + Gatling, + Gunslinger, + Hammerhead, + Bootleg, + Palehorse, + Carnivore, + Saber, + Hornet, + Squid, + Ragin, + Roman, + Sting, + Jury, + Joker, + Ram, + Hawk, + Devil, + Check, + Snake, + Custom(String), +} + +impl ToString for Squadron { + fn to_string(&self) -> String { + match self { + Squadron::Enfield => "Enfield".to_string(), + Squadron::Springfield => "Springfield".to_string(), + Squadron::Uzi => "Uzi".to_string(), + Squadron::Colt => "Colt".to_string(), + Squadron::Dodge => "Dodge".to_string(), + Squadron::Ford => "Ford".to_string(), + Squadron::Chevy => "Chevy".to_string(), + Squadron::Hornet => "Hornet".to_string(), + Squadron::Pontiac => "Pontiac".to_string(), + Squadron::Viper => "Viper".to_string(), + Squadron::Venom => "Venom".to_string(), + Squadron::Lobo => "Lobo".to_string(), + Squadron::Cowboy => "Cowboy".to_string(), + Squadron::Python => "Python".to_string(), + Squadron::Rattler => "Rattler".to_string(), + Squadron::Panther => "Panther".to_string(), + Squadron::Wolf => "Wolf".to_string(), + Squadron::Weasel => "Weasel".to_string(), + Squadron::Wild => "Wild".to_string(), + Squadron::Ninja => "Ninja".to_string(), + Squadron::Jedi => "Jedi".to_string(), + Squadron::Hawg => "Hawg".to_string(), + Squadron::Boar => "Boar".to_string(), + Squadron::Pig => "Pig".to_string(), + Squadron::Tusk => "Tusk".to_string(), + Squadron::ArmyAir => "ArmyAir".to_string(), + Squadron::Apache => "Apache".to_string(), + Squadron::Crow => "Crow".to_string(), + Squadron::Chaos => "Chaos".to_string(), + Squadron::Sioux => "Sioux".to_string(), + Squadron::Gatling => "Gatling".to_string(), + Squadron::Gunslinger => "Gunslinger".to_string(), + Squadron::Hammerhead => "Hammerhead".to_string(), + Squadron::Bootleg => "Bootleg".to_string(), + Squadron::Palehorse => "Palehorse".to_string(), + Squadron::Carnivore => "Carnivore".to_string(), + Squadron::Saber => "Saber".to_string(), + Squadron::Squid => "Squid".to_string(), + Squadron::Ragin => "Ragin".to_string(), + Squadron::Roman => "Roman".to_string(), + Squadron::Sting => "Sting".to_string(), + Squadron::Jury => "Jury".to_string(), + Squadron::Joker => "Joker".to_string(), + Squadron::Ram => "Ram".to_string(), + Squadron::Hawk => "Hawk".to_string(), + Squadron::Devil => "Devil".to_string(), + Squadron::Check => "Check".to_string(), + Squadron::Snake => "Snake".to_string(), + Squadron::Custom(c) => c.to_string(), + } + } +} + +impl std::str::FromStr for Squadron { + type Err = Box; + + fn from_str(s: &str) -> Result { + match s { + "Enfield" => Ok(Squadron::Enfield), + "Springfield" => Ok(Squadron::Springfield), + "Uzi" => Ok(Squadron::Uzi), + "Colt" => Ok(Squadron::Colt), + "Dodge" => Ok(Squadron::Dodge), + "Ford" => Ok(Squadron::Ford), + "Chevy" => Ok(Squadron::Chevy), + "Hornet" => Ok(Squadron::Hornet), + "Pontiac" => Ok(Squadron::Pontiac), + "Viper" => Ok(Squadron::Viper), + "Venom" => Ok(Squadron::Venom), + "Lobo" => Ok(Squadron::Lobo), + "Cowboy" => Ok(Squadron::Cowboy), + "Python" => Ok(Squadron::Python), + "Rattler" => Ok(Squadron::Rattler), + "Panther" => Ok(Squadron::Panther), + "Wolf" => Ok(Squadron::Wolf), + "Weasel" => Ok(Squadron::Weasel), + "Wild" => Ok(Squadron::Wild), + "Ninja" => Ok(Squadron::Ninja), + "Jedi" => Ok(Squadron::Jedi), + "Hawg" => Ok(Squadron::Hawg), + "Boar" => Ok(Squadron::Boar), + "Pig" => Ok(Squadron::Pig), + "Tusk" => Ok(Squadron::Tusk), + "ArmyAir" => Ok(Squadron::ArmyAir), + "Apache" => Ok(Squadron::Apache), + "Crow" => Ok(Squadron::Crow), + "Chaos" => Ok(Squadron::Chaos), + "Sioux" => Ok(Squadron::Sioux), + "Gatling" => Ok(Squadron::Gatling), + "Gunslinger" => Ok(Squadron::Gunslinger), + "Hammerhead" => Ok(Squadron::Hammerhead), + "Bootleg" => Ok(Squadron::Bootleg), + "Palehorse" => Ok(Squadron::Palehorse), + "Carnivore" => Ok(Squadron::Carnivore), + "Saber" => Ok(Squadron::Saber), + "Squid" => Ok(Squadron::Squid), + "Ragin" => Ok(Squadron::Ragin), + "Roman" => Ok(Squadron::Roman), + "Sting" => Ok(Squadron::Sting), + "Jury" => Ok(Squadron::Jury), + "Joker" => Ok(Squadron::Joker), + "Ram" => Ok(Squadron::Ram), + "Hawk" => Ok(Squadron::Hawk), + "Devil" => Ok(Squadron::Devil), + "Check" => Ok(Squadron::Check), + "Snake" => Ok(Squadron::Snake), + c => Ok(Squadron::Custom(c.to_string())), + } + } +} + +#[derive(Debug)] +pub struct Element { + pub squadron: Squadron, + pub group: u8, + pub unit: u8, +} + +impl Display for Element { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{} {} {}", + self.squadron.to_string(), + self.group, + self.unit + ) + } +} + +fn add_spaces_around_numbers(input: &str) -> String { + let mut result = String::new(); + let mut chars = input.chars().peekable(); + + while let Some(c) = chars.next() { + result.push(c); + + if let Some(next_char) = chars.peek() { + if next_char.is_numeric() { + result.push(' '); + } + } + } + + result +} + +impl std::str::FromStr for Element { + type Err = Box; + + fn from_str(s: &str) -> Result { + let d = add_spaces_around_numbers(s); + let mut d = d.split(' '); + let squadron: Squadron = d.next().unwrap().parse()?; + let group: u8 = d.next().unwrap().parse()?; + let unit: u8 = d.next().unwrap().parse()?; + + Ok(Element { + squadron, + group, + unit, + }) + } +} + +fn parse_element(input: &str) -> IResult<&str, Element> { + let mut parser = tuple(( + alpha1, // Squadron name + opt(multispace0), // Optional whitespace + opt(tuple(( + // Optional group + opt(multispace0), + parse_group_unit, + opt(multispace0), + ))), + opt(char('-')), + opt(tuple(( + // Optional unit + opt(multispace0), + parse_group_unit, + opt(multispace0), + ))), + )); + + let (remainder, (squadron_str, _, group_str, _, unit_str)) = parser(input)?; + + let squadron = match squadron_str.to_lowercase().as_str() { + "enfield" => Squadron::Enfield, + "springfield" => Squadron::Springfield, + "uzi" => Squadron::Uzi, + "colt" => Squadron::Colt, + "dodge" => Squadron::Dodge, + "ford" => Squadron::Ford, + "chevy" => Squadron::Chevy, + "hornet" => Squadron::Hornet, + "pontiac" => Squadron::Pontiac, + "viper" => Squadron::Viper, + "venom" => Squadron::Venom, + "lobo" => Squadron::Lobo, + "cowboy" => Squadron::Cowboy, + "python" => Squadron::Python, + "rattler" => Squadron::Rattler, + "panther" => Squadron::Panther, + "wolf" => Squadron::Wolf, + "weasel" => Squadron::Weasel, + "wild" => Squadron::Wild, + "ninja" => Squadron::Ninja, + "jedi" => Squadron::Jedi, + "hawg" => Squadron::Hawg, + "boar" => Squadron::Boar, + "pig" => Squadron::Pig, + "tusk" => Squadron::Tusk, + "armyair" => Squadron::ArmyAir, + "apache" => Squadron::Apache, + "crow" => Squadron::Crow, + "chaos" => Squadron::Chaos, + "sioux" => Squadron::Sioux, + "gatling" => Squadron::Gatling, + "gunslinger" => Squadron::Gunslinger, + "hammerhead" => Squadron::Hammerhead, + "bootleg" => Squadron::Bootleg, + "palehorse" => Squadron::Palehorse, + "carnivore" => Squadron::Carnivore, + "saber" => Squadron::Saber, + "squid" => Squadron::Squid, + "ragin" => Squadron::Ragin, + "roman" => Squadron::Roman, + "sting" => Squadron::Sting, + "jury" => Squadron::Jury, + "joker" => Squadron::Joker, + "ram" => Squadron::Ram, + "hawk" => Squadron::Hawk, + "devil" => Squadron::Devil, + "check" => Squadron::Check, + "snake" => Squadron::Snake, + c => Squadron::Custom(c.to_string()), + }; + // _ => { + // return Err(NomError::Error(nom::error::Error { + // input: squadron_str, + // code: ErrorKind::Alpha, + // })) + // } + + let group = group_str.unwrap_or((None, 0, None)).1; + let unit = unit_str.unwrap_or((None, 0, None)).1; + + Ok(( + remainder, + Element { + squadron, + group, + unit, + }, + )) +} + +fn parse_group_unit(input: &str) -> IResult<&str, u8> { + let parse_digit = map( + recognize(alt(( + char('0'), + char('1'), + char('2'), + char('3'), + char('4'), + char('5'), + char('6'), + char('7'), + char('8'), + char('9'), + ))), + |s: &str| s.parse::().unwrap(), + ); + + let parse_word = alt(( + map(tag("one"), |_| 1), + map(tag("two"), |_| 2), + map(tag("three"), |_| 3), + map(tag("four"), |_| 4), + map(tag("five"), |_| 5), + map(tag("six"), |_| 6), + map(tag("seven"), |_| 7), + map(tag("eight"), |_| 8), + map(tag("nine"), |_| 9), + )); + + alt((parse_digit, parse_word))(input) +} + +// #[derive(Debug)] +// pub enum Unit { +// NauticalMiles, +// Kilometers, +// } + +// #[derive(Debug)] +// pub enum Call { +// RadioCheck(Awacs, Element), +// Shopping(Awacs, Element), +// LocateAirfield(Awacs, Element, String), +// LocateFriendly(Awacs, Element, Element), +// Tripwire(Awacs, Element, Option, Unit), +// } + +#[derive(Debug)] +pub struct Call { + pub receiver: Receiver, + pub element: Element, + pub command: String, +} + +pub fn parse_call(input: &str) -> IResult<&str, Call> { + let mut parser = tuple((parse_receiver, multispace0, parse_element)); + + let (command, (receiver, _, element)) = parser(input)?; + + if element.group == 0 || element.unit == 0 { + return Err(NomError::Error(nom::error::Error { + input: command, + code: ErrorKind::Digit, + })); + } + + Ok(( + "", + Call { + receiver, + element, + command: command.to_string(), + }, + )) +} diff --git a/crates/guardian_commands/src/console.rs b/crates/guardian_commands/src/console.rs old mode 100644 new mode 100755 index 8670314..ea4751c --- a/crates/guardian_commands/src/console.rs +++ b/crates/guardian_commands/src/console.rs @@ -1,549 +1,549 @@ -use bevy::{ - app::{App, Startup, Update}, - ecs::{ - component::Tick, - entity::Entity, - event::{Event, EventReader}, - schedule::IntoSystemConfigs, - system::{ResMut, Resource, SystemMeta, SystemParam}, - world::{unsafe_world_cell::UnsafeWorldCell, World}, - }, - log::warn, -}; -// use bevy::{input::keyboard::KeyboardInput, prelude::*}; -// use bevy_egui::egui::{self, Align, ScrollArea, TextEdit}; -// use bevy_egui::egui::{text::LayoutJob, text_edit::CCursorRange}; -// use bevy_egui::egui::{Context, Id}; -// use bevy_egui::{ -// egui::{epaint::text::cursor::CCursor, Color32, FontId, TextFormat}, -// EguiContexts, -// }; -use clap::{builder::StyledStr, CommandFactory, FromArgMatches}; -use std::collections::BTreeMap; -use std::marker::PhantomData; -use std::mem; - -use crate::{parser, ConsoleSet}; - -type ConsoleCommandEnteredReaderSystemParam = EventReader<'static, 'static, ConsoleCommandEntered>; - -/// A super-trait for command like structures -pub trait Command: NamedCommand + CommandFactory + FromArgMatches + Sized + Resource {} -impl Command for T {} - -/// Trait used to allow uniquely identifying commands at compile time -pub trait NamedCommand { - /// Return the unique command identifier (same as the command "executable") - fn name() -> &'static str; -} - -/// Executed parsed console command. -/// -/// Used to capture console commands which implement [`CommandName`], [`CommandArgs`] & [`CommandHelp`]. -/// These can be easily implemented with the [`ConsoleCommand`](bevy_console_derive::ConsoleCommand) derive macro. -/// -/// # Example -/// -/// ``` -/// # use bevy_console::ConsoleCommand; -/// # use clap::Parser; -/// /// Prints given arguments to the console. -/// #[derive(Parser, ConsoleCommand)] -/// #[command(name = "log")] -/// struct LogCommand { -/// /// Message to print -/// msg: String, -/// /// Number of times to print message -/// num: Option, -/// } -/// -/// fn log_command(mut log: ConsoleCommand) { -/// if let Some(Ok(LogCommand { msg, num })) = log.take() { -/// log.ok(); -/// } -/// } -/// ``` -pub struct ConsoleCommand { - command: Option>, - pub raw: Option, - pub pilot: Option, - pub operator: Option, -} - -impl ConsoleCommand { - /// Returns Some(T) if the command was executed and arguments were valid. - /// - /// This method should only be called once. - /// Consecutive calls will return None regardless if the command occurred. - pub fn take(&mut self) -> Option> { - mem::take(&mut self.command) - } -} - -pub struct ConsoleCommandState { - #[allow(clippy::type_complexity)] - event_reader: ::State, - marker: PhantomData, -} - -unsafe impl SystemParam for ConsoleCommand { - type State = ConsoleCommandState; - type Item<'w, 's> = ConsoleCommand; - - fn init_state(world: &mut World, system_meta: &mut SystemMeta) -> Self::State { - let event_reader = ConsoleCommandEnteredReaderSystemParam::init_state(world, system_meta); - ConsoleCommandState { - event_reader, - marker: PhantomData, - } - } - - #[inline] - unsafe fn get_param<'w, 's>( - state: &'s mut Self::State, - system_meta: &SystemMeta, - world: UnsafeWorldCell<'w>, - change_tick: Tick, - ) -> Self::Item<'w, 's> { - let mut event_reader = ConsoleCommandEnteredReaderSystemParam::get_param( - &mut state.event_reader, - system_meta, - world, - change_tick, - ); - - let command = event_reader.read().find_map(|command| { - for name in parser::parse(T::name()) { - if name == command.command_name { - let clap_command = T::command().no_binary_name(true); - let arg_matches = clap_command.try_get_matches_from(command.args.iter()); - - match arg_matches { - Ok(matches) => match T::from_arg_matches(&matches) { - Ok(from_arg_matches) => { - return Some(Ok(( - from_arg_matches, - command.raw.clone(), - command.pilot, - command.operator, - ))); - } - Err(err) => return Some(Err(err)), - }, - Err(err) => { - return Some(Err(err)); - } - } - } - } - - None - }); - - if let Some(Ok(command)) = command { - return ConsoleCommand { - command: Some(Ok(command.0)), - raw: Some(command.1), - pilot: Some(command.2), - operator: Some(command.3), - }; - } - - ConsoleCommand { - command: None, - raw: None, - pilot: None, - operator: None, - } - } -} -/// Parsed raw console command into `command` and `args`. -#[derive(Clone, Debug, Event)] -pub struct ConsoleCommandEntered { - /// the command definition - pub command_name: String, - /// the raw input string - pub raw: String, - /// Raw parsed arguments - pub args: Vec, - /// Pilot making the request - pub pilot: Entity, - /// Operator responding - pub operator: Entity, -} - -/// Events to print to the console. -#[derive(Clone, Debug, Eq, Event, PartialEq)] -pub struct PrintConsoleLine { - /// Console line - pub line: StyledStr, -} - -impl PrintConsoleLine { - /// Creates a new console line to print. - pub const fn new(line: StyledStr) -> Self { - Self { line } - } -} - -/// Console configuration -#[derive(Clone, Resource, Default)] -pub struct ConsoleConfiguration { - /// Registered console commands - pub commands: BTreeMap, -} - -/// Add a console commands to Bevy app. -pub trait AddConsoleCommand { - /// Add a console command with a given system. - /// - /// This registers the console command so it will print with the built-in `help` console command. - /// - /// # Example - /// - /// ``` - /// # use bevy::prelude::*; - /// # use bevy_console::{AddConsoleCommand, ConsoleCommand}; - /// # use clap::Parser; - /// App::new() - /// .add_console_command::(log_command); - /// # - /// # /// Prints given arguments to the console. - /// # #[derive(Parser, ConsoleCommand)] - /// # #[command(name = "log")] - /// # struct LogCommand; - /// # - /// # fn log_command(mut log: ConsoleCommand) {} - /// ``` - fn add_console_command( - &mut self, - system: impl IntoSystemConfigs, - ) -> &mut Self; -} - -impl AddConsoleCommand for App { - fn add_console_command( - &mut self, - system: impl IntoSystemConfigs, - ) -> &mut Self { - let sys = move |mut config: ResMut| { - for name in crate::parser::parse(T::name()) { - let command = T::command().no_binary_name(true); - if config.commands.contains_key(&name) { - warn!( - "console command '{}' already registered and was overwritten", - name - ); - } - config.commands.insert(name.clone(), command); - } - }; - - self.add_systems(Startup, sys) - .add_systems(Update, system.in_set(ConsoleSet::Commands)) - } -} - -// /// Console open state -// #[derive(Default, Resource)] -// pub struct ConsoleOpen { -// /// Console open -// pub open: bool, -// } - -// #[derive(Resource)] -// pub(crate) struct ConsoleState { -// pub(crate) buf: String, -// pub(crate) scrollback: Vec, -// pub(crate) history: VecDeque, -// pub(crate) history_index: usize, -// } - -// impl Default for ConsoleState { -// fn default() -> Self { -// ConsoleState { -// buf: String::default(), -// scrollback: Vec::new(), -// history: VecDeque::from([StyledStr::new()]), -// history_index: 0, -// } -// } -// } - -// pub(crate) fn console_ui( -// mut egui_context: EguiContexts, -// config: Res, -// mut keyboard_input_events: EventReader, -// keys: Res>, -// mut state: ResMut, -// mut command_entered: EventWriter, -// mut console_open: ResMut, -// ) { -// let keyboard_input_events = keyboard_input_events.iter().collect::>(); -// let ctx = egui_context.ctx_mut(); - -// let pressed = keyboard_input_events -// .iter() -// .any(|code| console_key_pressed(code, &config.keys)); - -// // always close if console open -// // avoid opening console if typing in another text input -// if pressed && (console_open.open || !ctx.wants_keyboard_input()) { -// console_open.open = !console_open.open; -// } - -// if console_open.open { -// egui::Window::new("Console") -// .collapsible(false) -// .default_pos([config.left_pos, config.top_pos]) -// .default_size([config.width, config.height]) -// .resizable(true) -// .show(ctx, |ui| { -// ui.vertical(|ui| { -// let scroll_height = ui.available_height() - 30.0; - -// // Scroll area -// ScrollArea::vertical() -// .auto_shrink([false, false]) -// .stick_to_bottom(true) -// .max_height(scroll_height) -// .show(ui, |ui| { -// ui.vertical(|ui| { -// for line in &state.scrollback { -// let mut text = LayoutJob::default(); - -// text.append( -// &line.to_string(), //TOOD: once clap supports custom styling use it here -// 0f32, -// TextFormat::simple(FontId::monospace(14f32), Color32::GRAY), -// ); - -// ui.label(text); -// } -// }); - -// // Scroll to bottom if console just opened -// if console_open.is_changed() { -// ui.scroll_to_cursor(Some(Align::BOTTOM)); -// } -// }); - -// // Separator -// ui.separator(); - -// // Input -// let text_edit = TextEdit::singleline(&mut state.buf) -// .desired_width(f32::INFINITY) -// .lock_focus(true) -// .font(egui::TextStyle::Monospace); - -// // Handle enter -// let text_edit_response = ui.add(text_edit); -// if text_edit_response.lost_focus() -// && ui.input(|i| i.key_pressed(egui::Key::Enter)) -// { -// if state.buf.trim().is_empty() { -// state.scrollback.push(StyledStr::new()); -// } else { -// let msg = format!("{}{}", config.symbol, state.buf); -// state.scrollback.push(msg.into()); -// let cmd_string = state.buf.clone(); -// state.history.insert(1, cmd_string.into()); -// if state.history.len() > config.history_size + 1 { -// state.history.pop_back(); -// } - -// let mut args = Shlex::new(&state.buf).collect::>(); - -// if !args.is_empty() { -// let command_name = args.remove(0); -// debug!("Command entered: `{command_name}`, with args: `{args:?}`"); - -// let command = config.commands.get(command_name.as_str()); - -// if command.is_some() { -// command_entered -// .send(ConsoleCommandEntered { command_name, args }); -// } else { -// debug!( -// "Command not recognized, recognized commands: `{:?}`", -// config.commands.keys().collect::>() -// ); - -// state.scrollback.push("error: Invalid command".into()); -// } -// } - -// state.buf.clear(); -// } -// } - -// // Clear on ctrl+l -// if keyboard_input_events -// .iter() -// .any(|&k| k.state.is_pressed() && k.key_code == Some(KeyCode::L)) -// && (keys.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight])) -// { -// state.scrollback.clear(); -// } - -// // Handle up and down through history -// if text_edit_response.has_focus() -// && ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) -// && state.history.len() > 1 -// && state.history_index < state.history.len() - 1 -// { -// if state.history_index == 0 && !state.buf.trim().is_empty() { -// *state.history.get_mut(0).unwrap() = state.buf.clone().into(); -// } - -// state.history_index += 1; -// let previous_item = state.history.get(state.history_index).unwrap().clone(); -// state.buf = previous_item.to_string(); - -// set_cursor_pos(ui.ctx(), text_edit_response.id, state.buf.len()); -// } else if text_edit_response.has_focus() -// && ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) -// && state.history_index > 0 -// { -// state.history_index -= 1; -// let next_item = state.history.get(state.history_index).unwrap().clone(); -// state.buf = next_item.to_string(); - -// set_cursor_pos(ui.ctx(), text_edit_response.id, state.buf.len()); -// } - -// // Focus on input -// ui.memory_mut(|m| m.request_focus(text_edit_response.id)); -// }); -// }); -// } -// } - -// pub(crate) fn receive_console_line( -// mut console_state: ResMut, -// mut events: EventReader, -// ) { -// for event in events.iter() { -// let event: &PrintConsoleLine = event; -// console_state.scrollback.push(event.line.clone()); -// } -// } - -// fn console_key_pressed( -// keyboard_input: &KeyboardInput, -// configured_keys: &[ToggleConsoleKey], -// ) -> bool { -// if !keyboard_input.state.is_pressed() { -// return false; -// } - -// for configured_key in configured_keys { -// match configured_key { -// ToggleConsoleKey::KeyCode(configured_key_code) => match keyboard_input.key_code { -// None => continue, -// Some(pressed_key) => { -// if configured_key_code == &pressed_key { -// return true; -// } -// } -// }, -// ToggleConsoleKey::ScanCode(configured_scan_code) => { -// if &keyboard_input.scan_code == configured_scan_code { -// return true; -// } -// } -// } -// } - -// false -// } - -// fn set_cursor_pos(ctx: &Context, id: Id, pos: usize) { -// if let Some(mut state) = TextEdit::load_state(ctx, id) { -// state.set_ccursor_range(Some(CCursorRange::one(CCursor::new(pos)))); -// state.store(ctx, id); -// } -// } - -// #[cfg(test)] -// mod tests { -// use bevy::input::ButtonState; - -// use super::*; - -// #[test] -// fn test_console_key_pressed_scan_code() { -// let input = KeyboardInput { -// scan_code: 41, -// key_code: None, -// state: ButtonState::Pressed, -// window: Entity::PLACEHOLDER, -// }; - -// let config = vec![ToggleConsoleKey::ScanCode(41)]; - -// let result = console_key_pressed(&input, &config); -// assert!(result); -// } - -// #[test] -// fn test_console_wrong_key_pressed_scan_code() { -// let input = KeyboardInput { -// scan_code: 42, -// key_code: None, -// state: ButtonState::Pressed, -// window: Entity::PLACEHOLDER, -// }; - -// let config = vec![ToggleConsoleKey::ScanCode(41)]; - -// let result = console_key_pressed(&input, &config); -// assert!(!result); -// } - -// #[test] -// fn test_console_key_pressed_key_code() { -// let input = KeyboardInput { -// scan_code: 0, -// key_code: Some(KeyCode::Grave), -// state: ButtonState::Pressed, -// window: Entity::PLACEHOLDER, -// }; - -// let config = vec![ToggleConsoleKey::KeyCode(KeyCode::Grave)]; - -// let result = console_key_pressed(&input, &config); -// assert!(result); -// } - -// #[test] -// fn test_console_wrong_key_pressed_key_code() { -// let input = KeyboardInput { -// scan_code: 0, -// key_code: Some(KeyCode::A), -// state: ButtonState::Pressed, -// window: Entity::PLACEHOLDER, -// }; - -// let config = vec![ToggleConsoleKey::KeyCode(KeyCode::Grave)]; - -// let result = console_key_pressed(&input, &config); -// assert!(!result); -// } - -// #[test] -// fn test_console_key_right_key_but_not_pressed() { -// let input = KeyboardInput { -// scan_code: 0, -// key_code: Some(KeyCode::Grave), -// state: ButtonState::Released, -// window: Entity::PLACEHOLDER, -// }; - -// let config = vec![ToggleConsoleKey::KeyCode(KeyCode::Grave)]; - -// let result = console_key_pressed(&input, &config); -// assert!(!result); -// } -// } +use bevy::{ + app::{App, Startup, Update}, + ecs::{ + component::Tick, + entity::Entity, + event::{Event, EventReader}, + schedule::IntoSystemConfigs, + system::{ResMut, Resource, SystemMeta, SystemParam}, + world::{unsafe_world_cell::UnsafeWorldCell, World}, + }, + log::warn, +}; +// use bevy::{input::keyboard::KeyboardInput, prelude::*}; +// use bevy_egui::egui::{self, Align, ScrollArea, TextEdit}; +// use bevy_egui::egui::{text::LayoutJob, text_edit::CCursorRange}; +// use bevy_egui::egui::{Context, Id}; +// use bevy_egui::{ +// egui::{epaint::text::cursor::CCursor, Color32, FontId, TextFormat}, +// EguiContexts, +// }; +use clap::{builder::StyledStr, CommandFactory, FromArgMatches}; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use std::mem; + +use crate::{parser, ConsoleSet}; + +type ConsoleCommandEnteredReaderSystemParam = EventReader<'static, 'static, ConsoleCommandEntered>; + +/// A super-trait for command like structures +pub trait Command: NamedCommand + CommandFactory + FromArgMatches + Sized + Resource {} +impl Command for T {} + +/// Trait used to allow uniquely identifying commands at compile time +pub trait NamedCommand { + /// Return the unique command identifier (same as the command "executable") + fn name() -> &'static str; +} + +/// Executed parsed console command. +/// +/// Used to capture console commands which implement [`CommandName`], [`CommandArgs`] & [`CommandHelp`]. +/// These can be easily implemented with the [`ConsoleCommand`](bevy_console_derive::ConsoleCommand) derive macro. +/// +/// # Example +/// +/// ``` +/// # use bevy_console::ConsoleCommand; +/// # use clap::Parser; +/// /// Prints given arguments to the console. +/// #[derive(Parser, ConsoleCommand)] +/// #[command(name = "log")] +/// struct LogCommand { +/// /// Message to print +/// msg: String, +/// /// Number of times to print message +/// num: Option, +/// } +/// +/// fn log_command(mut log: ConsoleCommand) { +/// if let Some(Ok(LogCommand { msg, num })) = log.take() { +/// log.ok(); +/// } +/// } +/// ``` +pub struct ConsoleCommand { + command: Option>, + pub raw: Option, + pub pilot: Option, + pub operator: Option, +} + +impl ConsoleCommand { + /// Returns Some(T) if the command was executed and arguments were valid. + /// + /// This method should only be called once. + /// Consecutive calls will return None regardless if the command occurred. + pub fn take(&mut self) -> Option> { + mem::take(&mut self.command) + } +} + +pub struct ConsoleCommandState { + #[allow(clippy::type_complexity)] + event_reader: ::State, + marker: PhantomData, +} + +unsafe impl SystemParam for ConsoleCommand { + type State = ConsoleCommandState; + type Item<'w, 's> = ConsoleCommand; + + fn init_state(world: &mut World, system_meta: &mut SystemMeta) -> Self::State { + let event_reader = ConsoleCommandEnteredReaderSystemParam::init_state(world, system_meta); + ConsoleCommandState { + event_reader, + marker: PhantomData, + } + } + + #[inline] + unsafe fn get_param<'w, 's>( + state: &'s mut Self::State, + system_meta: &SystemMeta, + world: UnsafeWorldCell<'w>, + change_tick: Tick, + ) -> Self::Item<'w, 's> { + let mut event_reader = ConsoleCommandEnteredReaderSystemParam::get_param( + &mut state.event_reader, + system_meta, + world, + change_tick, + ); + + let command = event_reader.read().find_map(|command| { + for name in parser::parse(T::name()) { + if name == command.command_name { + let clap_command = T::command().no_binary_name(true); + let arg_matches = clap_command.try_get_matches_from(command.args.iter()); + + match arg_matches { + Ok(matches) => match T::from_arg_matches(&matches) { + Ok(from_arg_matches) => { + return Some(Ok(( + from_arg_matches, + command.raw.clone(), + command.pilot, + command.operator, + ))); + } + Err(err) => return Some(Err(err)), + }, + Err(err) => { + return Some(Err(err)); + } + } + } + } + + None + }); + + if let Some(Ok(command)) = command { + return ConsoleCommand { + command: Some(Ok(command.0)), + raw: Some(command.1), + pilot: Some(command.2), + operator: Some(command.3), + }; + } + + ConsoleCommand { + command: None, + raw: None, + pilot: None, + operator: None, + } + } +} +/// Parsed raw console command into `command` and `args`. +#[derive(Clone, Debug, Event)] +pub struct ConsoleCommandEntered { + /// the command definition + pub command_name: String, + /// the raw input string + pub raw: String, + /// Raw parsed arguments + pub args: Vec, + /// Pilot making the request + pub pilot: Entity, + /// Operator responding + pub operator: Entity, +} + +/// Events to print to the console. +#[derive(Clone, Debug, Eq, Event, PartialEq)] +pub struct PrintConsoleLine { + /// Console line + pub line: StyledStr, +} + +impl PrintConsoleLine { + /// Creates a new console line to print. + pub const fn new(line: StyledStr) -> Self { + Self { line } + } +} + +/// Console configuration +#[derive(Clone, Resource, Default)] +pub struct ConsoleConfiguration { + /// Registered console commands + pub commands: BTreeMap, +} + +/// Add a console commands to Bevy app. +pub trait AddConsoleCommand { + /// Add a console command with a given system. + /// + /// This registers the console command so it will print with the built-in `help` console command. + /// + /// # Example + /// + /// ``` + /// # use bevy::prelude::*; + /// # use bevy_console::{AddConsoleCommand, ConsoleCommand}; + /// # use clap::Parser; + /// App::new() + /// .add_console_command::(log_command); + /// # + /// # /// Prints given arguments to the console. + /// # #[derive(Parser, ConsoleCommand)] + /// # #[command(name = "log")] + /// # struct LogCommand; + /// # + /// # fn log_command(mut log: ConsoleCommand) {} + /// ``` + fn add_console_command( + &mut self, + system: impl IntoSystemConfigs, + ) -> &mut Self; +} + +impl AddConsoleCommand for App { + fn add_console_command( + &mut self, + system: impl IntoSystemConfigs, + ) -> &mut Self { + let sys = move |mut config: ResMut| { + for name in crate::parser::parse(T::name()) { + let command = T::command().no_binary_name(true); + if config.commands.contains_key(&name) { + warn!( + "console command '{}' already registered and was overwritten", + name + ); + } + config.commands.insert(name.clone(), command); + } + }; + + self.add_systems(Startup, sys) + .add_systems(Update, system.in_set(ConsoleSet::Commands)) + } +} + +// /// Console open state +// #[derive(Default, Resource)] +// pub struct ConsoleOpen { +// /// Console open +// pub open: bool, +// } + +// #[derive(Resource)] +// pub(crate) struct ConsoleState { +// pub(crate) buf: String, +// pub(crate) scrollback: Vec, +// pub(crate) history: VecDeque, +// pub(crate) history_index: usize, +// } + +// impl Default for ConsoleState { +// fn default() -> Self { +// ConsoleState { +// buf: String::default(), +// scrollback: Vec::new(), +// history: VecDeque::from([StyledStr::new()]), +// history_index: 0, +// } +// } +// } + +// pub(crate) fn console_ui( +// mut egui_context: EguiContexts, +// config: Res, +// mut keyboard_input_events: EventReader, +// keys: Res>, +// mut state: ResMut, +// mut command_entered: EventWriter, +// mut console_open: ResMut, +// ) { +// let keyboard_input_events = keyboard_input_events.iter().collect::>(); +// let ctx = egui_context.ctx_mut(); + +// let pressed = keyboard_input_events +// .iter() +// .any(|code| console_key_pressed(code, &config.keys)); + +// // always close if console open +// // avoid opening console if typing in another text input +// if pressed && (console_open.open || !ctx.wants_keyboard_input()) { +// console_open.open = !console_open.open; +// } + +// if console_open.open { +// egui::Window::new("Console") +// .collapsible(false) +// .default_pos([config.left_pos, config.top_pos]) +// .default_size([config.width, config.height]) +// .resizable(true) +// .show(ctx, |ui| { +// ui.vertical(|ui| { +// let scroll_height = ui.available_height() - 30.0; + +// // Scroll area +// ScrollArea::vertical() +// .auto_shrink([false, false]) +// .stick_to_bottom(true) +// .max_height(scroll_height) +// .show(ui, |ui| { +// ui.vertical(|ui| { +// for line in &state.scrollback { +// let mut text = LayoutJob::default(); + +// text.append( +// &line.to_string(), //TOOD: once clap supports custom styling use it here +// 0f32, +// TextFormat::simple(FontId::monospace(14f32), Color32::GRAY), +// ); + +// ui.label(text); +// } +// }); + +// // Scroll to bottom if console just opened +// if console_open.is_changed() { +// ui.scroll_to_cursor(Some(Align::BOTTOM)); +// } +// }); + +// // Separator +// ui.separator(); + +// // Input +// let text_edit = TextEdit::singleline(&mut state.buf) +// .desired_width(f32::INFINITY) +// .lock_focus(true) +// .font(egui::TextStyle::Monospace); + +// // Handle enter +// let text_edit_response = ui.add(text_edit); +// if text_edit_response.lost_focus() +// && ui.input(|i| i.key_pressed(egui::Key::Enter)) +// { +// if state.buf.trim().is_empty() { +// state.scrollback.push(StyledStr::new()); +// } else { +// let msg = format!("{}{}", config.symbol, state.buf); +// state.scrollback.push(msg.into()); +// let cmd_string = state.buf.clone(); +// state.history.insert(1, cmd_string.into()); +// if state.history.len() > config.history_size + 1 { +// state.history.pop_back(); +// } + +// let mut args = Shlex::new(&state.buf).collect::>(); + +// if !args.is_empty() { +// let command_name = args.remove(0); +// debug!("Command entered: `{command_name}`, with args: `{args:?}`"); + +// let command = config.commands.get(command_name.as_str()); + +// if command.is_some() { +// command_entered +// .send(ConsoleCommandEntered { command_name, args }); +// } else { +// debug!( +// "Command not recognized, recognized commands: `{:?}`", +// config.commands.keys().collect::>() +// ); + +// state.scrollback.push("error: Invalid command".into()); +// } +// } + +// state.buf.clear(); +// } +// } + +// // Clear on ctrl+l +// if keyboard_input_events +// .iter() +// .any(|&k| k.state.is_pressed() && k.key_code == Some(KeyCode::L)) +// && (keys.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight])) +// { +// state.scrollback.clear(); +// } + +// // Handle up and down through history +// if text_edit_response.has_focus() +// && ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) +// && state.history.len() > 1 +// && state.history_index < state.history.len() - 1 +// { +// if state.history_index == 0 && !state.buf.trim().is_empty() { +// *state.history.get_mut(0).unwrap() = state.buf.clone().into(); +// } + +// state.history_index += 1; +// let previous_item = state.history.get(state.history_index).unwrap().clone(); +// state.buf = previous_item.to_string(); + +// set_cursor_pos(ui.ctx(), text_edit_response.id, state.buf.len()); +// } else if text_edit_response.has_focus() +// && ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) +// && state.history_index > 0 +// { +// state.history_index -= 1; +// let next_item = state.history.get(state.history_index).unwrap().clone(); +// state.buf = next_item.to_string(); + +// set_cursor_pos(ui.ctx(), text_edit_response.id, state.buf.len()); +// } + +// // Focus on input +// ui.memory_mut(|m| m.request_focus(text_edit_response.id)); +// }); +// }); +// } +// } + +// pub(crate) fn receive_console_line( +// mut console_state: ResMut, +// mut events: EventReader, +// ) { +// for event in events.iter() { +// let event: &PrintConsoleLine = event; +// console_state.scrollback.push(event.line.clone()); +// } +// } + +// fn console_key_pressed( +// keyboard_input: &KeyboardInput, +// configured_keys: &[ToggleConsoleKey], +// ) -> bool { +// if !keyboard_input.state.is_pressed() { +// return false; +// } + +// for configured_key in configured_keys { +// match configured_key { +// ToggleConsoleKey::KeyCode(configured_key_code) => match keyboard_input.key_code { +// None => continue, +// Some(pressed_key) => { +// if configured_key_code == &pressed_key { +// return true; +// } +// } +// }, +// ToggleConsoleKey::ScanCode(configured_scan_code) => { +// if &keyboard_input.scan_code == configured_scan_code { +// return true; +// } +// } +// } +// } + +// false +// } + +// fn set_cursor_pos(ctx: &Context, id: Id, pos: usize) { +// if let Some(mut state) = TextEdit::load_state(ctx, id) { +// state.set_ccursor_range(Some(CCursorRange::one(CCursor::new(pos)))); +// state.store(ctx, id); +// } +// } + +// #[cfg(test)] +// mod tests { +// use bevy::input::ButtonState; + +// use super::*; + +// #[test] +// fn test_console_key_pressed_scan_code() { +// let input = KeyboardInput { +// scan_code: 41, +// key_code: None, +// state: ButtonState::Pressed, +// window: Entity::PLACEHOLDER, +// }; + +// let config = vec![ToggleConsoleKey::ScanCode(41)]; + +// let result = console_key_pressed(&input, &config); +// assert!(result); +// } + +// #[test] +// fn test_console_wrong_key_pressed_scan_code() { +// let input = KeyboardInput { +// scan_code: 42, +// key_code: None, +// state: ButtonState::Pressed, +// window: Entity::PLACEHOLDER, +// }; + +// let config = vec![ToggleConsoleKey::ScanCode(41)]; + +// let result = console_key_pressed(&input, &config); +// assert!(!result); +// } + +// #[test] +// fn test_console_key_pressed_key_code() { +// let input = KeyboardInput { +// scan_code: 0, +// key_code: Some(KeyCode::Grave), +// state: ButtonState::Pressed, +// window: Entity::PLACEHOLDER, +// }; + +// let config = vec![ToggleConsoleKey::KeyCode(KeyCode::Grave)]; + +// let result = console_key_pressed(&input, &config); +// assert!(result); +// } + +// #[test] +// fn test_console_wrong_key_pressed_key_code() { +// let input = KeyboardInput { +// scan_code: 0, +// key_code: Some(KeyCode::A), +// state: ButtonState::Pressed, +// window: Entity::PLACEHOLDER, +// }; + +// let config = vec![ToggleConsoleKey::KeyCode(KeyCode::Grave)]; + +// let result = console_key_pressed(&input, &config); +// assert!(!result); +// } + +// #[test] +// fn test_console_key_right_key_but_not_pressed() { +// let input = KeyboardInput { +// scan_code: 0, +// key_code: Some(KeyCode::Grave), +// state: ButtonState::Released, +// window: Entity::PLACEHOLDER, +// }; + +// let config = vec![ToggleConsoleKey::KeyCode(KeyCode::Grave)]; + +// let result = console_key_pressed(&input, &config); +// assert!(!result); +// } +// } diff --git a/crates/guardian_commands/src/lib.rs b/crates/guardian_commands/src/lib.rs old mode 100644 new mode 100755 diff --git a/crates/guardian_commands/src/parser.rs b/crates/guardian_commands/src/parser.rs old mode 100644 new mode 100755 index 98d17fc..a115679 --- a/crates/guardian_commands/src/parser.rs +++ b/crates/guardian_commands/src/parser.rs @@ -1,194 +1,194 @@ -use nom::{ - bytes::complete::tag, - error::{Error, ErrorKind, ParseError}, - sequence::delimited, - IResult, -}; - -// from https://github.com/getreu/parse-hyperlinks/blob/5af034d14aa72ffb9e705da13bf557a564b1bebf/parse-hyperlinks/src/lib.rs#L41 -fn take_until_unbalanced( - opening_bracket: char, - closing_bracket: char, -) -> impl Fn(&str) -> IResult<&str, &str> { - move |i: &str| { - let mut index = 0; - let mut bracket_counter = 0; - while let Some(n) = &i[index..].find(&[opening_bracket, closing_bracket, '\\'][..]) { - index += n; - let mut it = i[index..].chars(); - match it.next() { - Some('\\') => { - // Skip the escape char `\`. - index += '\\'.len_utf8(); - // Skip also the following char. - if let Some(c) = it.next() { - index += c.len_utf8(); - } - } - Some(c) if c == opening_bracket => { - bracket_counter += 1; - index += opening_bracket.len_utf8(); - } - Some(c) if c == closing_bracket => { - // Closing bracket. - bracket_counter -= 1; - index += closing_bracket.len_utf8(); - } - // Can not happen. - _ => unreachable!(), - }; - // We found the unmatched closing bracket. - if bracket_counter == -1 { - // We do not consume it. - index -= closing_bracket.len_utf8(); - return Ok((&i[index..], &i[0..index])); - }; - } - - if bracket_counter == 0 { - Ok(("", i)) - } else { - Err(nom::Err::Error(Error::from_error_kind( - i, - ErrorKind::TakeUntil, - ))) - } - } -} - -fn split(input: &str) -> IResult<&str, &str> { - let mut parser = delimited(tag("["), take_until_unbalanced('[', ']'), tag("]")); - parser(input) -} - -fn inner_parse(input: &str, depth: usize) -> Vec { - let mut output = vec![]; - let start_idx = input.find('[').unwrap_or(input.len()); - - if start_idx > 0 && depth == 0 { - output.push(input[..start_idx].to_string()); - } - - if start_idx == input.len() { - return output; - } - - let input = &input[start_idx..]; - - let splitted = split(input).unwrap(); - - let variants: Vec = splitted - .1 - .split('|') - .map(|v| v.to_string()) - .collect::>(); - - let mut temp = vec![]; - let mut temp_str = String::new(); - for v in &variants { - if v.contains('[') || v.contains(']') { - temp_str.push_str(v); - temp_str.push('|'); - } else { - let len = temp_str.len(); - if len > 0 { - temp.push(temp_str[..len - 1].to_string()); - temp.push(v.to_string()); - } - temp_str.clear(); - } - } - - let variants = if temp.is_empty() { variants } else { temp }; - - // check if variants need expanding - let mut temp = vec![]; - for v in variants { - if v.contains('[') { - let index = v.find('[').unwrap_or(0); - let prepend = &v[..index]; - - let remainder = inner_parse(&v, depth + 1); - for r in &remainder { - let l = format!("{}{}", prepend, r); - temp.push(l); - } - } else { - temp.push(v); - } - } - - let remainder = splitted.0; - let backup = output.clone(); - output.clear(); - - for variant in temp { - if remainder.contains('[') { - let index = remainder.find('[').unwrap_or(0); - let prepend = &remainder[..index]; - - let r2 = inner_parse(remainder, depth + 1); - - if !backup.is_empty() { - for o in &backup { - for r in &r2 { - let l = format!("{}{}{}{}", o, variant, prepend, r); - output.push(l); - } - } - } else { - for r in &r2 { - let l = format!("{}{}{}", variant, prepend, r); - output.push(l); - } - } - } else if !backup.is_empty() { - for o in &backup { - output.push(format!("{}{}{}", o, variant, remainder)); - } - } else { - output.push(format!("{}{}", variant, remainder)); - } - } - - output -} - -pub fn parse(input: &str) -> Vec { - inner_parse(input, 0) -} - -#[test] -fn parse_test() { - // This works - assert_eq!( - parse("[Hello|Goodbye], World!"), - vec!["Hello, World!", "Goodbye, World!"] - ); - - assert_eq!( - parse("[Hello|Goodbye], [World|Moon]!"), - vec![ - "Hello, World!", - "Hello, Moon!", - "Goodbye, World!", - "Goodbye, Moon!", - ] - ); - - assert_eq!( - parse("[[Heading|Bearing] [to|for]|Where is] that"), - vec![ - "Heading to that", - "Heading for that", - "Bearing to that", - "Bearing for that", - "Where is that", - ] - ); - - assert_eq!( - parse("set [warning|tripwire]"), - vec!["set warning", "set tripwire"] - ); -} +use nom::{ + bytes::complete::tag, + error::{Error, ErrorKind, ParseError}, + sequence::delimited, + IResult, +}; + +// from https://github.com/getreu/parse-hyperlinks/blob/5af034d14aa72ffb9e705da13bf557a564b1bebf/parse-hyperlinks/src/lib.rs#L41 +fn take_until_unbalanced( + opening_bracket: char, + closing_bracket: char, +) -> impl Fn(&str) -> IResult<&str, &str> { + move |i: &str| { + let mut index = 0; + let mut bracket_counter = 0; + while let Some(n) = &i[index..].find(&[opening_bracket, closing_bracket, '\\'][..]) { + index += n; + let mut it = i[index..].chars(); + match it.next() { + Some('\\') => { + // Skip the escape char `\`. + index += '\\'.len_utf8(); + // Skip also the following char. + if let Some(c) = it.next() { + index += c.len_utf8(); + } + } + Some(c) if c == opening_bracket => { + bracket_counter += 1; + index += opening_bracket.len_utf8(); + } + Some(c) if c == closing_bracket => { + // Closing bracket. + bracket_counter -= 1; + index += closing_bracket.len_utf8(); + } + // Can not happen. + _ => unreachable!(), + }; + // We found the unmatched closing bracket. + if bracket_counter == -1 { + // We do not consume it. + index -= closing_bracket.len_utf8(); + return Ok((&i[index..], &i[0..index])); + }; + } + + if bracket_counter == 0 { + Ok(("", i)) + } else { + Err(nom::Err::Error(Error::from_error_kind( + i, + ErrorKind::TakeUntil, + ))) + } + } +} + +fn split(input: &str) -> IResult<&str, &str> { + let mut parser = delimited(tag("["), take_until_unbalanced('[', ']'), tag("]")); + parser(input) +} + +fn inner_parse(input: &str, depth: usize) -> Vec { + let mut output = vec![]; + let start_idx = input.find('[').unwrap_or(input.len()); + + if start_idx > 0 && depth == 0 { + output.push(input[..start_idx].to_string()); + } + + if start_idx == input.len() { + return output; + } + + let input = &input[start_idx..]; + + let splitted = split(input).unwrap(); + + let variants: Vec = splitted + .1 + .split('|') + .map(|v| v.to_string()) + .collect::>(); + + let mut temp = vec![]; + let mut temp_str = String::new(); + for v in &variants { + if v.contains('[') || v.contains(']') { + temp_str.push_str(v); + temp_str.push('|'); + } else { + let len = temp_str.len(); + if len > 0 { + temp.push(temp_str[..len - 1].to_string()); + temp.push(v.to_string()); + } + temp_str.clear(); + } + } + + let variants = if temp.is_empty() { variants } else { temp }; + + // check if variants need expanding + let mut temp = vec![]; + for v in variants { + if v.contains('[') { + let index = v.find('[').unwrap_or(0); + let prepend = &v[..index]; + + let remainder = inner_parse(&v, depth + 1); + for r in &remainder { + let l = format!("{}{}", prepend, r); + temp.push(l); + } + } else { + temp.push(v); + } + } + + let remainder = splitted.0; + let backup = output.clone(); + output.clear(); + + for variant in temp { + if remainder.contains('[') { + let index = remainder.find('[').unwrap_or(0); + let prepend = &remainder[..index]; + + let r2 = inner_parse(remainder, depth + 1); + + if !backup.is_empty() { + for o in &backup { + for r in &r2 { + let l = format!("{}{}{}{}", o, variant, prepend, r); + output.push(l); + } + } + } else { + for r in &r2 { + let l = format!("{}{}{}", variant, prepend, r); + output.push(l); + } + } + } else if !backup.is_empty() { + for o in &backup { + output.push(format!("{}{}{}", o, variant, remainder)); + } + } else { + output.push(format!("{}{}", variant, remainder)); + } + } + + output +} + +pub fn parse(input: &str) -> Vec { + inner_parse(input, 0) +} + +#[test] +fn parse_test() { + // This works + assert_eq!( + parse("[Hello|Goodbye], World!"), + vec!["Hello, World!", "Goodbye, World!"] + ); + + assert_eq!( + parse("[Hello|Goodbye], [World|Moon]!"), + vec![ + "Hello, World!", + "Hello, Moon!", + "Goodbye, World!", + "Goodbye, Moon!", + ] + ); + + assert_eq!( + parse("[[Heading|Bearing] [to|for]|Where is] that"), + vec![ + "Heading to that", + "Heading for that", + "Bearing to that", + "Bearing for that", + "Where is that", + ] + ); + + assert_eq!( + parse("set [warning|tripwire]"), + vec!["set warning", "set tripwire"] + ); +} diff --git a/crates/guardian_core/Cargo.toml b/crates/guardian_core/Cargo.toml old mode 100644 new mode 100755 diff --git a/crates/guardian_core/src/components/awacs.rs b/crates/guardian_core/src/components/awacs.rs old mode 100644 new mode 100755 index 785d2bf..0b303d8 --- a/crates/guardian_core/src/components/awacs.rs +++ b/crates/guardian_core/src/components/awacs.rs @@ -1,4 +1,4 @@ -use bevy::ecs::component::Component; - -#[derive(Component)] -pub struct Awacs; +use bevy::ecs::component::Component; + +#[derive(Component)] +pub struct Awacs; diff --git a/crates/guardian_core/src/components/callsign.rs b/crates/guardian_core/src/components/callsign.rs old mode 100644 new mode 100755 index 2d3a668..15e0c00 --- a/crates/guardian_core/src/components/callsign.rs +++ b/crates/guardian_core/src/components/callsign.rs @@ -1,105 +1,105 @@ -use std::{ - borrow::Cow, - hash::{Hash, Hasher}, -}; - -use bevy::{ - ecs::{component::Component, reflect::ReflectComponent}, - reflect::{std_traits::ReflectDefault, Reflect}, - utils::AHasher, -}; - -#[derive(Reflect, Component, Clone)] -#[reflect(Component, Default, Debug)] -pub struct Callsign { - hash: u64, - value: Cow<'static, str>, -} - -impl Default for Callsign { - fn default() -> Self { - Callsign::new("") - } -} - -fn add_spaces_around_numbers(input: &str) -> String { - let mut result = String::new(); - let mut chars = input.chars().peekable(); - - while let Some(c) = chars.next() { - result.push(c); - - if let Some(next_char) = chars.peek() { - if next_char.is_numeric() { - result.push(' '); - } - } - } - - result -} - -impl Callsign { - /// Creates a new [`Callsign`] from any string-like type. - /// - /// The internal hash will be computed immediately. - pub fn new(value: impl Into>) -> Self { - let value = value.into(); - - let mut value = Callsign { value, hash: 0 }; - value.update_hash(); - value - } - - pub fn to_voice(&self) -> String { - let value: String = self.value.to_string(); - let value = value.replace(' ', ""); - let value = value.replace('-', ""); - - add_spaces_around_numbers(&value) - } - - /// Sets the entity's value. - /// - /// The internal hash will be re-computed. - #[inline(always)] - pub fn set(&mut self, value: impl Into>) { - *self = Callsign::new(value); - } - - /// Updates the value of the entity in place. - /// - /// This will allocate a new string if the value was previously - /// created from a borrow. - #[inline(always)] - pub fn mutate(&mut self, f: F) { - f(self.value.to_mut()); - self.update_hash(); - } - - /// Gets the value of the entity as a `&str`. - #[inline(always)] - pub fn as_str(&self) -> &str { - &self.value - } - - fn update_hash(&mut self) { - let mut hasher = AHasher::default(); - self.value.hash(&mut hasher); - self.hash = hasher.finish(); - } -} - -impl std::fmt::Display for Callsign { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.value, f) - } -} - -impl std::fmt::Debug for Callsign { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Debug::fmt(&self.value, f) - } -} +use std::{ + borrow::Cow, + hash::{Hash, Hasher}, +}; + +use bevy::{ + ecs::{component::Component, reflect::ReflectComponent}, + reflect::{std_traits::ReflectDefault, Reflect}, + utils::AHasher, +}; + +#[derive(Reflect, Component, Clone)] +#[reflect(Component, Default, Debug)] +pub struct Callsign { + hash: u64, + value: Cow<'static, str>, +} + +impl Default for Callsign { + fn default() -> Self { + Callsign::new("") + } +} + +fn add_spaces_around_numbers(input: &str) -> String { + let mut result = String::new(); + let mut chars = input.chars().peekable(); + + while let Some(c) = chars.next() { + result.push(c); + + if let Some(next_char) = chars.peek() { + if next_char.is_numeric() { + result.push(' '); + } + } + } + + result +} + +impl Callsign { + /// Creates a new [`Callsign`] from any string-like type. + /// + /// The internal hash will be computed immediately. + pub fn new(value: impl Into>) -> Self { + let value = value.into(); + + let mut value = Callsign { value, hash: 0 }; + value.update_hash(); + value + } + + pub fn to_voice(&self) -> String { + let value: String = self.value.to_string(); + let value = value.replace(' ', ""); + let value = value.replace('-', ""); + + add_spaces_around_numbers(&value) + } + + /// Sets the entity's value. + /// + /// The internal hash will be re-computed. + #[inline(always)] + pub fn set(&mut self, value: impl Into>) { + *self = Callsign::new(value); + } + + /// Updates the value of the entity in place. + /// + /// This will allocate a new string if the value was previously + /// created from a borrow. + #[inline(always)] + pub fn mutate(&mut self, f: F) { + f(self.value.to_mut()); + self.update_hash(); + } + + /// Gets the value of the entity as a `&str`. + #[inline(always)] + pub fn as_str(&self) -> &str { + &self.value + } + + fn update_hash(&mut self) { + let mut hasher = AHasher::default(); + self.value.hash(&mut hasher); + self.hash = hasher.finish(); + } +} + +impl std::fmt::Display for Callsign { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Display::fmt(&self.value, f) + } +} + +impl std::fmt::Debug for Callsign { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.value, f) + } +} diff --git a/crates/guardian_core/src/components/group.rs b/crates/guardian_core/src/components/group.rs old mode 100644 new mode 100755 index 841d1ac..735fe98 --- a/crates/guardian_core/src/components/group.rs +++ b/crates/guardian_core/src/components/group.rs @@ -1,7 +1,7 @@ -use bevy::ecs::component::Component; - -#[derive(Debug, Component)] -pub struct Group { - pub id: u32, - pub unit: u32, -} +use bevy::ecs::component::Component; + +#[derive(Debug, Component)] +pub struct Group { + pub id: u32, + pub unit: u32, +} diff --git a/crates/guardian_core/src/components/grpc_base_url.rs b/crates/guardian_core/src/components/grpc_base_url.rs old mode 100644 new mode 100755 index 30f9fc2..e4cf7a0 --- a/crates/guardian_core/src/components/grpc_base_url.rs +++ b/crates/guardian_core/src/components/grpc_base_url.rs @@ -1,94 +1,94 @@ -use std::{ - borrow::Cow, - hash::{Hash, Hasher}, -}; - -use bevy::{ - ecs::{reflect::ReflectResource, system::Resource}, - reflect::{std_traits::ReflectDefault, Reflect}, - utils::AHasher, -}; -use serde::{Deserialize, Serialize}; - -#[derive(Reflect, Resource, Clone, Deserialize, Serialize)] -#[reflect(Resource, Default, Debug)] -pub struct GrpcBaseUrl { - #[serde(skip)] - hash: u64, - /// The URL of the DCS-gRPC Server - url: Cow<'static, str>, - /// The poll rate for updating the mission situation in secononds. - /// Lower values might cause noticeable ingame lag spikes - poll_rate: Option, -} - -impl Default for GrpcBaseUrl { - fn default() -> Self { - GrpcBaseUrl::new("http://127.0.0.1:50051/", Some(10)) - } -} - -impl GrpcBaseUrl { - /// Creates a new [`GrpcBaseUrl`] from any string-like type. - /// - /// The internal hash will be computed immediately. - pub fn new(url: impl Into>, poll_rate: Option) -> Self { - let url = url.into(); - let mut url = GrpcBaseUrl { - url, - hash: 0, - poll_rate, - }; - url.update_hash(); - url - } - - /// Sets the entity's url. - /// - /// The internal hash will be re-computed. - #[inline(always)] - pub fn set(&mut self, url: impl Into>) { - *self = GrpcBaseUrl::new(url, self.poll_rate); - } - - /// Updates the url of the entity in place. - /// - /// This will allocate a new string if the url was previously - /// created from a borrow. - #[inline(always)] - pub fn mutate(&mut self, f: F) { - f(self.url.to_mut()); - self.update_hash(); - } - - /// Gets the url of the entity as a `&str`. - #[inline(always)] - pub fn as_str(&self) -> &str { - &self.url - } - - #[inline(always)] - pub fn poll_rate(&self) -> Option { - self.poll_rate - } - - fn update_hash(&mut self) { - let mut hasher = AHasher::default(); - self.url.hash(&mut hasher); - self.hash = hasher.finish(); - } -} - -impl std::fmt::Display for GrpcBaseUrl { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.url, f) - } -} - -impl std::fmt::Debug for GrpcBaseUrl { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Debug::fmt(&self.url, f) - } -} +use std::{ + borrow::Cow, + hash::{Hash, Hasher}, +}; + +use bevy::{ + ecs::{reflect::ReflectResource, system::Resource}, + reflect::{std_traits::ReflectDefault, Reflect}, + utils::AHasher, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Reflect, Resource, Clone, Deserialize, Serialize)] +#[reflect(Resource, Default, Debug)] +pub struct GrpcBaseUrl { + #[serde(skip)] + hash: u64, + /// The URL of the DCS-gRPC Server + url: Cow<'static, str>, + /// The poll rate for updating the mission situation in secononds. + /// Lower values might cause noticeable ingame lag spikes + poll_rate: Option, +} + +impl Default for GrpcBaseUrl { + fn default() -> Self { + GrpcBaseUrl::new("http://127.0.0.1:50051/", Some(10)) + } +} + +impl GrpcBaseUrl { + /// Creates a new [`GrpcBaseUrl`] from any string-like type. + /// + /// The internal hash will be computed immediately. + pub fn new(url: impl Into>, poll_rate: Option) -> Self { + let url = url.into(); + let mut url = GrpcBaseUrl { + url, + hash: 0, + poll_rate, + }; + url.update_hash(); + url + } + + /// Sets the entity's url. + /// + /// The internal hash will be re-computed. + #[inline(always)] + pub fn set(&mut self, url: impl Into>) { + *self = GrpcBaseUrl::new(url, self.poll_rate); + } + + /// Updates the url of the entity in place. + /// + /// This will allocate a new string if the url was previously + /// created from a borrow. + #[inline(always)] + pub fn mutate(&mut self, f: F) { + f(self.url.to_mut()); + self.update_hash(); + } + + /// Gets the url of the entity as a `&str`. + #[inline(always)] + pub fn as_str(&self) -> &str { + &self.url + } + + #[inline(always)] + pub fn poll_rate(&self) -> Option { + self.poll_rate + } + + fn update_hash(&mut self) { + let mut hasher = AHasher::default(); + self.url.hash(&mut hasher); + self.hash = hasher.finish(); + } +} + +impl std::fmt::Display for GrpcBaseUrl { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Display::fmt(&self.url, f) + } +} + +impl std::fmt::Debug for GrpcBaseUrl { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.url, f) + } +} diff --git a/crates/guardian_core/src/components/heading.rs b/crates/guardian_core/src/components/heading.rs old mode 100644 new mode 100755 index b116c27..3271690 --- a/crates/guardian_core/src/components/heading.rs +++ b/crates/guardian_core/src/components/heading.rs @@ -1,4 +1,4 @@ -use bevy::ecs::component::Component; - -#[derive(Debug, Component)] -pub struct Heading(pub f64); +use bevy::ecs::component::Component; + +#[derive(Debug, Component)] +pub struct Heading(pub f64); diff --git a/crates/guardian_core/src/components/id.rs b/crates/guardian_core/src/components/id.rs old mode 100644 new mode 100755 index 5f81d22..6b0d780 --- a/crates/guardian_core/src/components/id.rs +++ b/crates/guardian_core/src/components/id.rs @@ -1,22 +1,22 @@ -use bevy::ecs::component::Component; - -#[derive(Debug, Component, Copy, Clone, PartialEq)] -pub struct Id(u32); - -impl Id { - pub fn new(value: u32) -> Self { - Self(value) - } -} - -impl From<&Id> for u32 { - fn from(value: &Id) -> Self { - value.0 - } -} - -impl From for u32 { - fn from(value: Id) -> Self { - value.0 - } -} +use bevy::ecs::component::Component; + +#[derive(Debug, Component, Copy, Clone, PartialEq)] +pub struct Id(u32); + +impl Id { + pub fn new(value: u32) -> Self { + Self(value) + } +} + +impl From<&Id> for u32 { + fn from(value: &Id) -> Self { + value.0 + } +} + +impl From for u32 { + fn from(value: Id) -> Self { + value.0 + } +} diff --git a/crates/guardian_core/src/components/mod.rs b/crates/guardian_core/src/components/mod.rs old mode 100644 new mode 100755 index cea8731..156cafd --- a/crates/guardian_core/src/components/mod.rs +++ b/crates/guardian_core/src/components/mod.rs @@ -1,27 +1,27 @@ -mod awacs; -mod callsign; -mod group; -mod grpc_base_url; -mod heading; -mod id; -mod player; -mod position; -mod side; -mod srs_socket_addr; -mod stt_base_url; -mod unit_type; -mod velocity; - -pub use awacs::*; -pub use callsign::*; -pub use group::*; -pub use grpc_base_url::*; -pub use heading::*; -pub use id::*; -pub use player::*; -pub use position::*; -pub use side::*; -pub use srs_socket_addr::*; -pub use stt_base_url::*; -pub use unit_type::*; -pub use velocity::*; +mod awacs; +mod callsign; +mod group; +mod grpc_base_url; +mod heading; +mod id; +mod player; +mod position; +mod side; +mod srs_socket_addr; +mod stt_base_url; +mod unit_type; +mod velocity; + +pub use awacs::*; +pub use callsign::*; +pub use group::*; +pub use grpc_base_url::*; +pub use heading::*; +pub use id::*; +pub use player::*; +pub use position::*; +pub use side::*; +pub use srs_socket_addr::*; +pub use stt_base_url::*; +pub use unit_type::*; +pub use velocity::*; diff --git a/crates/guardian_core/src/components/player.rs b/crates/guardian_core/src/components/player.rs old mode 100644 new mode 100755 index 6d9836d..d8d90db --- a/crates/guardian_core/src/components/player.rs +++ b/crates/guardian_core/src/components/player.rs @@ -1,79 +1,79 @@ -use std::{ - borrow::Cow, - hash::{Hash, Hasher}, -}; - -use bevy::{ - ecs::{component::Component, reflect::ReflectComponent}, - reflect::{std_traits::ReflectDefault, Reflect}, - utils::AHasher, -}; - -#[derive(Reflect, Component, Clone)] -#[reflect(Component, Default, Debug)] -pub struct Player { - hash: u64, - value: Cow<'static, str>, -} - -impl Default for Player { - fn default() -> Self { - Player::new("") - } -} - -impl Player { - /// Creates a new [`Player`] from any string-like type. - /// - /// The internal hash will be computed immediately. - pub fn new(value: impl Into>) -> Self { - let value = value.into(); - let mut value = Player { value, hash: 0 }; - value.update_hash(); - value - } - - /// Sets the entity's value. - /// - /// The internal hash will be re-computed. - #[inline(always)] - pub fn set(&mut self, value: impl Into>) { - *self = Player::new(value); - } - - /// Updates the value of the entity in place. - /// - /// This will allocate a new string if the value was previously - /// created from a borrow. - #[inline(always)] - pub fn mutate(&mut self, f: F) { - f(self.value.to_mut()); - self.update_hash(); - } - - /// Gets the value of the entity as a `&str`. - #[inline(always)] - pub fn as_str(&self) -> &str { - &self.value - } - - fn update_hash(&mut self) { - let mut hasher = AHasher::default(); - self.value.hash(&mut hasher); - self.hash = hasher.finish(); - } -} - -impl std::fmt::Display for Player { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.value, f) - } -} - -impl std::fmt::Debug for Player { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Debug::fmt(&self.value, f) - } -} +use std::{ + borrow::Cow, + hash::{Hash, Hasher}, +}; + +use bevy::{ + ecs::{component::Component, reflect::ReflectComponent}, + reflect::{std_traits::ReflectDefault, Reflect}, + utils::AHasher, +}; + +#[derive(Reflect, Component, Clone)] +#[reflect(Component, Default, Debug)] +pub struct Player { + hash: u64, + value: Cow<'static, str>, +} + +impl Default for Player { + fn default() -> Self { + Player::new("") + } +} + +impl Player { + /// Creates a new [`Player`] from any string-like type. + /// + /// The internal hash will be computed immediately. + pub fn new(value: impl Into>) -> Self { + let value = value.into(); + let mut value = Player { value, hash: 0 }; + value.update_hash(); + value + } + + /// Sets the entity's value. + /// + /// The internal hash will be re-computed. + #[inline(always)] + pub fn set(&mut self, value: impl Into>) { + *self = Player::new(value); + } + + /// Updates the value of the entity in place. + /// + /// This will allocate a new string if the value was previously + /// created from a borrow. + #[inline(always)] + pub fn mutate(&mut self, f: F) { + f(self.value.to_mut()); + self.update_hash(); + } + + /// Gets the value of the entity as a `&str`. + #[inline(always)] + pub fn as_str(&self) -> &str { + &self.value + } + + fn update_hash(&mut self) { + let mut hasher = AHasher::default(); + self.value.hash(&mut hasher); + self.hash = hasher.finish(); + } +} + +impl std::fmt::Display for Player { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Display::fmt(&self.value, f) + } +} + +impl std::fmt::Debug for Player { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.value, f) + } +} diff --git a/crates/guardian_core/src/components/position.rs b/crates/guardian_core/src/components/position.rs old mode 100644 new mode 100755 index 4c5c13b..44ae824 --- a/crates/guardian_core/src/components/position.rs +++ b/crates/guardian_core/src/components/position.rs @@ -1,49 +1,49 @@ -use bevy::ecs::component::Component; - -#[derive(Debug, Component, Clone)] -pub struct Position { - pub lat: f64, - pub long: f64, - pub altitude: f64, -} -const COMPASS_DRIFT: i32 = -5; - -impl Position { - pub fn distance_to_km(&self, other: &Position) -> f64 { - let radius_of_earth_in_km: f64 = 6371.0; - let delta_lat = (other.lat - self.lat).to_radians(); - let delta_long = (other.long - self.long).to_radians(); - - let a = (delta_lat / 2.0).sin() * (delta_lat / 2.0).sin() - + self.lat.to_radians().cos() - * other.lat.to_radians().cos() - * (delta_long / 2.0).sin() - * (delta_long / 2.0).sin(); - - let c = 2.0 * (a.sqrt().atan2((1.0 - a).sqrt())); - radius_of_earth_in_km * c - } - - pub fn distance_to_nmi(&self, other: &Position) -> f64 { - self.distance_to_km(other) * 0.5399568035 - } - - pub fn get_bearing_to(&self, other: &Position) -> i32 { - let delta_long = (other.long - self.long).to_radians(); - - let y = - (other.long.to_radians() - self.long.to_radians()).sin() * other.lat.to_radians().cos(); - let x = self.lat.to_radians().cos() * other.lat.to_radians().sin() - - self.lat.to_radians().sin() * other.lat.to_radians().cos() * delta_long.cos(); - - (((y.atan2(x).to_degrees() + 360.0) % 360.0) as i32) + COMPASS_DRIFT - } - - pub fn feet(&self) -> f64 { - self.altitude * 3.28084 - } - - pub fn angels(&self) -> i32 { - (self.feet() / 1000.0).round() as i32 - } -} +use bevy::ecs::component::Component; + +#[derive(Debug, Component, Clone)] +pub struct Position { + pub lat: f64, + pub long: f64, + pub altitude: f64, +} +const COMPASS_DRIFT: i32 = -5; + +impl Position { + pub fn distance_to_km(&self, other: &Position) -> f64 { + let radius_of_earth_in_km: f64 = 6371.0; + let delta_lat = (other.lat - self.lat).to_radians(); + let delta_long = (other.long - self.long).to_radians(); + + let a = (delta_lat / 2.0).sin() * (delta_lat / 2.0).sin() + + self.lat.to_radians().cos() + * other.lat.to_radians().cos() + * (delta_long / 2.0).sin() + * (delta_long / 2.0).sin(); + + let c = 2.0 * (a.sqrt().atan2((1.0 - a).sqrt())); + radius_of_earth_in_km * c + } + + pub fn distance_to_nmi(&self, other: &Position) -> f64 { + self.distance_to_km(other) * 0.5399568035 + } + + pub fn get_bearing_to(&self, other: &Position) -> i32 { + let delta_long = (other.long - self.long).to_radians(); + + let y = + (other.long.to_radians() - self.long.to_radians()).sin() * other.lat.to_radians().cos(); + let x = self.lat.to_radians().cos() * other.lat.to_radians().sin() + - self.lat.to_radians().sin() * other.lat.to_radians().cos() * delta_long.cos(); + + (((y.atan2(x).to_degrees() + 360.0) % 360.0) as i32) + COMPASS_DRIFT + } + + pub fn feet(&self) -> f64 { + self.altitude * 3.28084 + } + + pub fn angels(&self) -> i32 { + (self.feet() / 1000.0).round() as i32 + } +} diff --git a/crates/guardian_core/src/components/side.rs b/crates/guardian_core/src/components/side.rs old mode 100644 new mode 100755 index 1c1849f..d1bd631 --- a/crates/guardian_core/src/components/side.rs +++ b/crates/guardian_core/src/components/side.rs @@ -1,10 +1,10 @@ -use bevy::ecs::component::Component; - -#[derive(Debug, Component)] -pub struct All; -#[derive(Debug, Component)] -pub struct Neutral; -#[derive(Debug, Component)] -pub struct Red; -#[derive(Debug, Component)] -pub struct Blue; +use bevy::ecs::component::Component; + +#[derive(Debug, Component)] +pub struct All; +#[derive(Debug, Component)] +pub struct Neutral; +#[derive(Debug, Component)] +pub struct Red; +#[derive(Debug, Component)] +pub struct Blue; diff --git a/crates/guardian_core/src/components/srs_socket_addr.rs b/crates/guardian_core/src/components/srs_socket_addr.rs old mode 100644 new mode 100755 index 68636f4..9e02799 --- a/crates/guardian_core/src/components/srs_socket_addr.rs +++ b/crates/guardian_core/src/components/srs_socket_addr.rs @@ -1,34 +1,34 @@ -use std::net::SocketAddr; - -use bevy::ecs::system::Resource; -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Resource, Clone, Deserialize, Serialize)] -pub struct SrsSocketAddr( - /// The server details for DCS-SRS - SocketAddr, -); - -impl Default for SrsSocketAddr { - fn default() -> Self { - Self("127.0.0.1:5002".parse().unwrap()) - } -} - -impl SrsSocketAddr { - pub fn new(addr: SocketAddr) -> Self { - Self(addr) - } -} - -impl From for SrsSocketAddr { - fn from(value: SocketAddr) -> Self { - Self(value) - } -} - -impl From for SocketAddr { - fn from(value: SrsSocketAddr) -> Self { - value.0 - } -} +use std::net::SocketAddr; + +use bevy::ecs::system::Resource; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Resource, Clone, Deserialize, Serialize)] +pub struct SrsSocketAddr( + /// The server details for DCS-SRS + SocketAddr, +); + +impl Default for SrsSocketAddr { + fn default() -> Self { + Self("127.0.0.1:5002".parse().unwrap()) + } +} + +impl SrsSocketAddr { + pub fn new(addr: SocketAddr) -> Self { + Self(addr) + } +} + +impl From for SrsSocketAddr { + fn from(value: SocketAddr) -> Self { + Self(value) + } +} + +impl From for SocketAddr { + fn from(value: SrsSocketAddr) -> Self { + value.0 + } +} diff --git a/crates/guardian_core/src/components/stt_base_url.rs b/crates/guardian_core/src/components/stt_base_url.rs old mode 100644 new mode 100755 index f5316a9..574d3ef --- a/crates/guardian_core/src/components/stt_base_url.rs +++ b/crates/guardian_core/src/components/stt_base_url.rs @@ -1,82 +1,82 @@ -use std::{ - borrow::Cow, - hash::{Hash, Hasher}, -}; - -use bevy::{ - ecs::{reflect::ReflectResource, system::Resource}, - reflect::{std_traits::ReflectDefault, Reflect}, - utils::AHasher, -}; -use serde::{Deserialize, Serialize}; - -#[derive(Reflect, Resource, Clone, Deserialize, Serialize)] -#[reflect(Resource, Default, Debug)] -pub struct SttBaseUrl { - #[serde(skip)] - hash: u64, - /// The url to the [whisper-web](https://git.avii.nl/Guardian/whisper-web) instance - url: Cow<'static, str>, -} - -impl Default for SttBaseUrl { - fn default() -> Self { - SttBaseUrl::new("http://127.0.0.1:3000/") - } -} - -impl SttBaseUrl { - /// Creates a new [`SttBaseUrl`] from any string-like type. - /// - /// The internal hash will be computed immediately. - pub fn new(url: impl Into>) -> Self { - let url = url.into(); - let mut url = SttBaseUrl { url, hash: 0 }; - url.update_hash(); - url - } - - /// Sets the entity's url. - /// - /// The internal hash will be re-computed. - #[inline(always)] - pub fn set(&mut self, url: impl Into>) { - *self = SttBaseUrl::new(url); - } - - /// Updates the url of the entity in place. - /// - /// This will allocate a new string if the url was previously - /// created from a borrow. - #[inline(always)] - pub fn mutate(&mut self, f: F) { - f(self.url.to_mut()); - self.update_hash(); - } - - /// Gets the url of the entity as a `&str`. - #[inline(always)] - pub fn as_str(&self) -> &str { - &self.url - } - - fn update_hash(&mut self) { - let mut hasher = AHasher::default(); - self.url.hash(&mut hasher); - self.hash = hasher.finish(); - } -} - -impl std::fmt::Display for SttBaseUrl { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.url, f) - } -} - -impl std::fmt::Debug for SttBaseUrl { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Debug::fmt(&self.url, f) - } -} +use std::{ + borrow::Cow, + hash::{Hash, Hasher}, +}; + +use bevy::{ + ecs::{reflect::ReflectResource, system::Resource}, + reflect::{std_traits::ReflectDefault, Reflect}, + utils::AHasher, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Reflect, Resource, Clone, Deserialize, Serialize)] +#[reflect(Resource, Default, Debug)] +pub struct SttBaseUrl { + #[serde(skip)] + hash: u64, + /// The url to the [whisper-web](https://git.avii.nl/Guardian/whisper-web) instance + url: Cow<'static, str>, +} + +impl Default for SttBaseUrl { + fn default() -> Self { + SttBaseUrl::new("http://127.0.0.1:3000/") + } +} + +impl SttBaseUrl { + /// Creates a new [`SttBaseUrl`] from any string-like type. + /// + /// The internal hash will be computed immediately. + pub fn new(url: impl Into>) -> Self { + let url = url.into(); + let mut url = SttBaseUrl { url, hash: 0 }; + url.update_hash(); + url + } + + /// Sets the entity's url. + /// + /// The internal hash will be re-computed. + #[inline(always)] + pub fn set(&mut self, url: impl Into>) { + *self = SttBaseUrl::new(url); + } + + /// Updates the url of the entity in place. + /// + /// This will allocate a new string if the url was previously + /// created from a borrow. + #[inline(always)] + pub fn mutate(&mut self, f: F) { + f(self.url.to_mut()); + self.update_hash(); + } + + /// Gets the url of the entity as a `&str`. + #[inline(always)] + pub fn as_str(&self) -> &str { + &self.url + } + + fn update_hash(&mut self) { + let mut hasher = AHasher::default(); + self.url.hash(&mut hasher); + self.hash = hasher.finish(); + } +} + +impl std::fmt::Display for SttBaseUrl { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Display::fmt(&self.url, f) + } +} + +impl std::fmt::Debug for SttBaseUrl { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.url, f) + } +} diff --git a/crates/guardian_core/src/components/unit_type.rs b/crates/guardian_core/src/components/unit_type.rs old mode 100644 new mode 100755 index c32b9fc..360a762 --- a/crates/guardian_core/src/components/unit_type.rs +++ b/crates/guardian_core/src/components/unit_type.rs @@ -1,79 +1,79 @@ -use std::{ - borrow::Cow, - hash::{Hash, Hasher}, -}; - -use bevy::{ - ecs::{component::Component, reflect::ReflectComponent}, - reflect::{std_traits::ReflectDefault, Reflect}, - utils::AHasher, -}; - -#[derive(Reflect, Component, Clone)] -#[reflect(Component, Default, Debug)] -pub struct UnitType { - hash: u64, - value: Cow<'static, str>, -} - -impl Default for UnitType { - fn default() -> Self { - UnitType::new("") - } -} - -impl UnitType { - /// Creates a new [`UnitType`] from any string-like type. - /// - /// The internal hash will be computed immediately. - pub fn new(value: impl Into>) -> Self { - let value = value.into(); - let mut value = UnitType { value, hash: 0 }; - value.update_hash(); - value - } - - /// Sets the entity's value. - /// - /// The internal hash will be re-computed. - #[inline(always)] - pub fn set(&mut self, value: impl Into>) { - *self = UnitType::new(value); - } - - /// Updates the value of the entity in place. - /// - /// This will allocate a new string if the value was previously - /// created from a borrow. - #[inline(always)] - pub fn mutate(&mut self, f: F) { - f(self.value.to_mut()); - self.update_hash(); - } - - /// Gets the value of the entity as a `&str`. - #[inline(always)] - pub fn as_str(&self) -> &str { - &self.value - } - - fn update_hash(&mut self) { - let mut hasher = AHasher::default(); - self.value.hash(&mut hasher); - self.hash = hasher.finish(); - } -} - -impl std::fmt::Display for UnitType { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.value, f) - } -} - -impl std::fmt::Debug for UnitType { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Debug::fmt(&self.value, f) - } -} +use std::{ + borrow::Cow, + hash::{Hash, Hasher}, +}; + +use bevy::{ + ecs::{component::Component, reflect::ReflectComponent}, + reflect::{std_traits::ReflectDefault, Reflect}, + utils::AHasher, +}; + +#[derive(Reflect, Component, Clone)] +#[reflect(Component, Default, Debug)] +pub struct UnitType { + hash: u64, + value: Cow<'static, str>, +} + +impl Default for UnitType { + fn default() -> Self { + UnitType::new("") + } +} + +impl UnitType { + /// Creates a new [`UnitType`] from any string-like type. + /// + /// The internal hash will be computed immediately. + pub fn new(value: impl Into>) -> Self { + let value = value.into(); + let mut value = UnitType { value, hash: 0 }; + value.update_hash(); + value + } + + /// Sets the entity's value. + /// + /// The internal hash will be re-computed. + #[inline(always)] + pub fn set(&mut self, value: impl Into>) { + *self = UnitType::new(value); + } + + /// Updates the value of the entity in place. + /// + /// This will allocate a new string if the value was previously + /// created from a borrow. + #[inline(always)] + pub fn mutate(&mut self, f: F) { + f(self.value.to_mut()); + self.update_hash(); + } + + /// Gets the value of the entity as a `&str`. + #[inline(always)] + pub fn as_str(&self) -> &str { + &self.value + } + + fn update_hash(&mut self) { + let mut hasher = AHasher::default(); + self.value.hash(&mut hasher); + self.hash = hasher.finish(); + } +} + +impl std::fmt::Display for UnitType { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Display::fmt(&self.value, f) + } +} + +impl std::fmt::Debug for UnitType { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.value, f) + } +} diff --git a/crates/guardian_core/src/components/velocity.rs b/crates/guardian_core/src/components/velocity.rs old mode 100644 new mode 100755 index 0860a25..2bed3ab --- a/crates/guardian_core/src/components/velocity.rs +++ b/crates/guardian_core/src/components/velocity.rs @@ -1,14 +1,14 @@ -use bevy::ecs::component::Component; -use dcs_grpc::dcs::common::v0::Vector; - -#[derive(Debug, Component)] -pub struct Velocity(pub Vector); - -impl Velocity { - pub fn speed(&self) -> f64 { - let x = self.0.x; - let y = self.0.y; - let z = self.0.z; - (x * x + y * y + z * z).sqrt() - } -} +use bevy::ecs::component::Component; +use dcs_grpc::dcs::common::v0::Vector; + +#[derive(Debug, Component)] +pub struct Velocity(pub Vector); + +impl Velocity { + pub fn speed(&self) -> f64 { + let x = self.0.x; + let y = self.0.y; + let z = self.0.z; + (x * x + y * y + z * z).sqrt() + } +} diff --git a/crates/guardian_core/src/dcs.rs b/crates/guardian_core/src/dcs.rs old mode 100644 new mode 100755 index 4a941ff..383f421 --- a/crates/guardian_core/src/dcs.rs +++ b/crates/guardian_core/src/dcs.rs @@ -1,29 +1,29 @@ -pub mod mission; -pub mod text; - -use crate::components::GrpcBaseUrl; - -use mission::MissionPlugin; -use text::TextPlugin; - -// Re-export -pub use dcs_grpc::dcs::common::v0::Coalition; - -use bevy::app::{App, Plugin, ScheduleRunnerPlugin}; -use std::time::Duration; - -pub struct DcsPlugin; - -impl Plugin for DcsPlugin { - fn build(&self, app: &mut App) { - app.world.get_resource_or_insert_with(GrpcBaseUrl::default); - - // Make the app loop forever at 60fps. - app.add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs_f64( - 1.0 / 60.0, - ))); - - app.add_plugins(MissionPlugin); - app.add_plugins(TextPlugin); - } -} +pub mod mission; +pub mod text; + +use crate::components::GrpcBaseUrl; + +use mission::MissionPlugin; +use text::TextPlugin; + +// Re-export +pub use dcs_grpc::dcs::common::v0::Coalition; + +use bevy::app::{App, Plugin, ScheduleRunnerPlugin}; +use std::time::Duration; + +pub struct DcsPlugin; + +impl Plugin for DcsPlugin { + fn build(&self, app: &mut App) { + app.world.get_resource_or_insert_with(GrpcBaseUrl::default); + + // Make the app loop forever at 60fps. + app.add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs_f64( + 1.0 / 60.0, + ))); + + app.add_plugins(MissionPlugin); + app.add_plugins(TextPlugin); + } +} diff --git a/crates/guardian_core/src/dcs/mission.rs b/crates/guardian_core/src/dcs/mission.rs old mode 100644 new mode 100755 index 954318f..ba15a4d --- a/crates/guardian_core/src/dcs/mission.rs +++ b/crates/guardian_core/src/dcs/mission.rs @@ -1,257 +1,257 @@ -use std::time::Duration; - -use crate::{components::*, TokioResource}; -use bevy::{ - app::{App, Plugin, PostUpdate, PreStartup, PreUpdate}, - core::Name, - ecs::{ - component::Component, - entity::Entity, - event::{Event, EventReader, EventWriter}, - query::With, - system::{Commands, Query, Res}, - }, -}; -use crossbeam_channel::{unbounded, Receiver}; -use dcs_grpc::dcs::{ - common::v0::{Coalition, GroupCategory, Unit}, - mission::v0::{ - mission_service_client::MissionServiceClient, stream_units_response::Update, - StreamUnitsRequest, - }, -}; -use tracing::{error, info, warn}; - -#[derive(Clone)] -enum Response { - Disconnected, - Update(Box), -} - -pub struct MissionPlugin; - -impl Plugin for MissionPlugin { - fn build(&self, app: &mut App) { - app.add_event::(); - app.add_event::(); - - app.add_systems(PreStartup, connect_to_grpc); - app.add_systems( - PreUpdate, - (consume_stream_message, update_units, despawn_units), - ) - .add_systems(PostUpdate, cleanup_after_disconnect); - } -} - -fn connect_to_grpc(mut commands: Commands, tokio: Res, url: Res) { - let handle = &tokio.0; - - let (tx, task) = unbounded(); - - let poll_rate = url.poll_rate(); - let url = url.to_string(); - - handle.spawn(async move { - loop { - let Ok(mut client) = MissionServiceClient::connect(url.clone()).await else { - warn!("Connection failed: {}", url); // warn - tokio::time::sleep(Duration::from_secs(5)).await; - continue; - }; - info!("Connected to DCS: {}", url); - - let Ok(mut stream) = client - .stream_units(StreamUnitsRequest { - poll_rate, - max_backoff: Some(30), - category: GroupCategory::Airplane as i32, - }) - .await - else { - return; - }; - - loop { - match stream.get_mut().message().await { - Ok(Some(next)) => { - if let Some(update) = &next.update { - tx.send(Response::Update(Box::new(update.clone()))).ok(); - } - } - Ok(None) => { - break; - } - Err(e) => { - error!("Error from gRPC: {:?}", e); // verbose or debug log - break; - } - } - } - - warn!("Disconnected from DCS: {}", url); // warn - tx.send(Response::Disconnected).ok(); - tokio::time::sleep(Duration::from_secs(5)).await; - } - }); - - commands.spawn(UnitsRequestMessage(task)); -} - -fn cleanup_after_disconnect( - mut commands: Commands, - disconnected: Query>, - entitiews: Query>, -) { - for d in disconnected.iter() { - // if there is one - commands.entity(d).despawn(); - - for ent in entitiews.iter() { - commands.entity(ent).despawn(); - } - } -} - -fn consume_stream_message( - mut commands: Commands, - requests: Query<&UnitsRequestMessage>, - mut ev_unit_updated: EventWriter, - mut ev_unit_gone: EventWriter, -) { - for stream in requests.iter() { - if let Ok(update) = stream.0.try_recv() { - match update { - Response::Update(boxed) => match *boxed { - Update::Gone(unit) => { - ev_unit_gone.send(UnitGoneEvent(unit.id)); - } - Update::Unit(unit) => { - ev_unit_updated.send(UnitUpdatedEvent(unit)); - } - }, - Response::Disconnected => { - commands.spawn(Disconnected); - } - } - } - } -} - -fn update_units( - mut commands: Commands, - units: Query<(Entity, &Id)>, - mut ev: EventReader, -) { - for event in ev.read() { - let event = &event.0; - - let mut e: Option<_> = None; - for (ent, id) in units.iter() { - if &Id::new(event.id) == id { - e = commands.get_entity(ent); - break; - } - } - - if e.is_none() { - e = Some(commands.spawn((Id::new(event.id), Callsign::new(event.callsign.clone())))); - } - - let Some(mut e) = e else { - unreachable!(); - }; - - if let Some(position) = &event.position { - e.insert(Position { - lat: position.lat, - long: position.lon, - altitude: position.alt, - }); - } - - if let Some(orientation) = &event.orientation { - e.insert(Heading(orientation.heading)); - } - - if let Some(velocity) = &event.velocity { - if let Some(velocity) = &velocity.velocity { - e.insert(Velocity(velocity.clone())); - } - } - - if let Some(playername) = &event.player_name { - let playername = playername.clone(); - e.insert(Player::new(playername.clone())); - - if let Some(index) = playername.find('|') { - let custom_callsign = playername[..index].trim().to_string(); - - // testing callsign validity - if guardian_commands::call::parse_call(&format!( - "Overlord {} radio check", - custom_callsign - )) - .is_ok() - { - e.insert(Callsign::new(custom_callsign.clone())); - } - } - } - - if let Some(group) = &event.group { - e.insert(Group { - id: group.id, - unit: event.number_in_group, - }); - } - - e.insert(Name::new(event.name.clone())); - - if ["A-50", "E-3A", "E-2C", "KJ-2000"].contains(&event.r#type.as_str()) { - e.insert(Awacs); - } - - e.insert(UnitType::new(event.r#type.clone())); - - { - e.remove::(); - e.remove::(); - e.remove::(); - e.remove::(); - match Coalition::try_from(event.coalition).expect("Coalition to be correct") { - Coalition::All => e.insert(All), - Coalition::Neutral => e.insert(Neutral), - Coalition::Red => e.insert(Red), - Coalition::Blue => e.insert(Blue), - }; - } - } -} - -fn despawn_units( - mut commands: Commands, - units: Query<(Entity, &Id)>, - mut ev: EventReader, -) { - for event in ev.read() { - let gid = event.0; - for (ent, id) in units.iter() { - if &Id::new(gid) == id { - commands.entity(ent).despawn(); - } - } - } -} - -#[derive(Event)] -struct UnitUpdatedEvent(Unit); - -#[derive(Event)] -struct UnitGoneEvent(u32); - -#[derive(Component)] -struct UnitsRequestMessage(Receiver); - -#[derive(Component)] -struct Disconnected; +use std::time::Duration; + +use crate::{components::*, TokioResource}; +use bevy::{ + app::{App, Plugin, PostUpdate, PreStartup, PreUpdate}, + core::Name, + ecs::{ + component::Component, + entity::Entity, + event::{Event, EventReader, EventWriter}, + query::With, + system::{Commands, Query, Res}, + }, +}; +use crossbeam_channel::{unbounded, Receiver}; +use dcs_grpc::dcs::{ + common::v0::{Coalition, GroupCategory, Unit}, + mission::v0::{ + mission_service_client::MissionServiceClient, stream_units_response::Update, + StreamUnitsRequest, + }, +}; +use tracing::{error, info, warn}; + +#[derive(Clone)] +enum Response { + Disconnected, + Update(Box), +} + +pub struct MissionPlugin; + +impl Plugin for MissionPlugin { + fn build(&self, app: &mut App) { + app.add_event::(); + app.add_event::(); + + app.add_systems(PreStartup, connect_to_grpc); + app.add_systems( + PreUpdate, + (consume_stream_message, update_units, despawn_units), + ) + .add_systems(PostUpdate, cleanup_after_disconnect); + } +} + +fn connect_to_grpc(mut commands: Commands, tokio: Res, url: Res) { + let handle = &tokio.0; + + let (tx, task) = unbounded(); + + let poll_rate = url.poll_rate(); + let url = url.to_string(); + + handle.spawn(async move { + loop { + let Ok(mut client) = MissionServiceClient::connect(url.clone()).await else { + warn!("Connection failed: {}", url); // warn + tokio::time::sleep(Duration::from_secs(5)).await; + continue; + }; + info!("Connected to DCS: {}", url); + + let Ok(mut stream) = client + .stream_units(StreamUnitsRequest { + poll_rate, + max_backoff: Some(30), + category: GroupCategory::Airplane as i32, + }) + .await + else { + return; + }; + + loop { + match stream.get_mut().message().await { + Ok(Some(next)) => { + if let Some(update) = &next.update { + tx.send(Response::Update(Box::new(update.clone()))).ok(); + } + } + Ok(None) => { + break; + } + Err(e) => { + error!("Error from gRPC: {:?}", e); // verbose or debug log + break; + } + } + } + + warn!("Disconnected from DCS: {}", url); // warn + tx.send(Response::Disconnected).ok(); + tokio::time::sleep(Duration::from_secs(5)).await; + } + }); + + commands.spawn(UnitsRequestMessage(task)); +} + +fn cleanup_after_disconnect( + mut commands: Commands, + disconnected: Query>, + entitiews: Query>, +) { + for d in disconnected.iter() { + // if there is one + commands.entity(d).despawn(); + + for ent in entitiews.iter() { + commands.entity(ent).despawn(); + } + } +} + +fn consume_stream_message( + mut commands: Commands, + requests: Query<&UnitsRequestMessage>, + mut ev_unit_updated: EventWriter, + mut ev_unit_gone: EventWriter, +) { + for stream in requests.iter() { + if let Ok(update) = stream.0.try_recv() { + match update { + Response::Update(boxed) => match *boxed { + Update::Gone(unit) => { + ev_unit_gone.send(UnitGoneEvent(unit.id)); + } + Update::Unit(unit) => { + ev_unit_updated.send(UnitUpdatedEvent(unit)); + } + }, + Response::Disconnected => { + commands.spawn(Disconnected); + } + } + } + } +} + +fn update_units( + mut commands: Commands, + units: Query<(Entity, &Id)>, + mut ev: EventReader, +) { + for event in ev.read() { + let event = &event.0; + + let mut e: Option<_> = None; + for (ent, id) in units.iter() { + if &Id::new(event.id) == id { + e = commands.get_entity(ent); + break; + } + } + + if e.is_none() { + e = Some(commands.spawn((Id::new(event.id), Callsign::new(event.callsign.clone())))); + } + + let Some(mut e) = e else { + unreachable!(); + }; + + if let Some(position) = &event.position { + e.insert(Position { + lat: position.lat, + long: position.lon, + altitude: position.alt, + }); + } + + if let Some(orientation) = &event.orientation { + e.insert(Heading(orientation.heading)); + } + + if let Some(velocity) = &event.velocity { + if let Some(velocity) = &velocity.velocity { + e.insert(Velocity(velocity.clone())); + } + } + + if let Some(playername) = &event.player_name { + let playername = playername.clone(); + e.insert(Player::new(playername.clone())); + + if let Some(index) = playername.find('|') { + let custom_callsign = playername[..index].trim().to_string(); + + // testing callsign validity + if guardian_commands::call::parse_call(&format!( + "Overlord {} radio check", + custom_callsign + )) + .is_ok() + { + e.insert(Callsign::new(custom_callsign.clone())); + } + } + } + + if let Some(group) = &event.group { + e.insert(Group { + id: group.id, + unit: event.number_in_group, + }); + } + + e.insert(Name::new(event.name.clone())); + + if ["A-50", "E-3A", "E-2C", "KJ-2000"].contains(&event.r#type.as_str()) { + e.insert(Awacs); + } + + e.insert(UnitType::new(event.r#type.clone())); + + { + e.remove::(); + e.remove::(); + e.remove::(); + e.remove::(); + match Coalition::try_from(event.coalition).expect("Coalition to be correct") { + Coalition::All => e.insert(All), + Coalition::Neutral => e.insert(Neutral), + Coalition::Red => e.insert(Red), + Coalition::Blue => e.insert(Blue), + }; + } + } +} + +fn despawn_units( + mut commands: Commands, + units: Query<(Entity, &Id)>, + mut ev: EventReader, +) { + for event in ev.read() { + let gid = event.0; + for (ent, id) in units.iter() { + if &Id::new(gid) == id { + commands.entity(ent).despawn(); + } + } + } +} + +#[derive(Event)] +struct UnitUpdatedEvent(Unit); + +#[derive(Event)] +struct UnitGoneEvent(u32); + +#[derive(Component)] +struct UnitsRequestMessage(Receiver); + +#[derive(Component)] +struct Disconnected; diff --git a/crates/guardian_core/src/dcs/text.rs b/crates/guardian_core/src/dcs/text.rs old mode 100644 new mode 100755 index 7d284d2..495ede0 --- a/crates/guardian_core/src/dcs/text.rs +++ b/crates/guardian_core/src/dcs/text.rs @@ -1,141 +1,141 @@ -use std::{ - borrow::Cow, - hash::{Hash, Hasher}, -}; - -use bevy::{ - app::{Plugin, PostUpdate}, - ecs::{ - component::Component, - entity::Entity, - query::Added, - reflect::ReflectComponent, - system::{Commands, Query, Res}, - }, - reflect::{std_traits::ReflectDefault, Reflect}, - utils::AHasher, -}; -use dcs_grpc::dcs::trigger::v0::{ - trigger_service_client::TriggerServiceClient, OutTextForUnitRequest, -}; - -use tracing::info; - -use crate::{ - components::{GrpcBaseUrl, Id}, - TokioResource, -}; - -pub struct TextPlugin; - -impl Plugin for TextPlugin { - fn build(&self, app: &mut bevy::prelude::App) { - app.add_systems(PostUpdate, send_text_message); - } -} - -fn send_text_message( - mut commands: Commands, - query: Query<(Entity, &Id, &TextMessage), Added>, - url: Res, - tokio: Res, -) { - for (ent, id, msg) in query.iter() { - let url = url.to_string(); - - if msg.as_str().is_empty() { - commands.entity(ent).remove::(); - continue; - } - - let message = msg.clone(); - let url = url.clone(); - let id: u32 = id.into(); - tokio.0.spawn(async move { - let Ok(mut client) = TriggerServiceClient::connect(url.to_string()).await else { - return; - }; - - let request = OutTextForUnitRequest { - text: message.to_string(), - display_time: 15, - clear_view: false, - unit_id: id, - }; - - info!("> {}", message); - client.out_text_for_unit(request).await.ok(); - }); - - commands.entity(ent).remove::(); - } -} - -#[derive(Reflect, Component, Clone)] -#[reflect(Component, Default, Debug)] -pub struct TextMessage { - hash: u64, - message: Cow<'static, str>, -} - -impl Default for TextMessage { - fn default() -> Self { - TextMessage::new("") - } -} - -impl TextMessage { - /// Creates a new [`TextMessage`] from any string-like type. - /// - /// The internal hash will be computed immediately. - pub fn new(message: impl Into>) -> Self { - let message = message.into(); - let mut message = TextMessage { message, hash: 0 }; - message.update_hash(); - message - } - - /// Sets the entity's message. - /// - /// The internal hash will be re-computed. - #[inline(always)] - pub fn set(&mut self, message: impl Into>) { - *self = TextMessage::new(message); - } - - /// Updates the message of the entity in place. - /// - /// This will allocate a new string if the message was previously - /// created from a borrow. - #[inline(always)] - pub fn mutate(&mut self, f: F) { - f(self.message.to_mut()); - self.update_hash(); - } - - /// Gets the message of the entity as a `&str`. - #[inline(always)] - pub fn as_str(&self) -> &str { - &self.message - } - - fn update_hash(&mut self) { - let mut hasher = AHasher::default(); - self.message.hash(&mut hasher); - self.hash = hasher.finish(); - } -} - -impl std::fmt::Display for TextMessage { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.message, f) - } -} - -impl std::fmt::Debug for TextMessage { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Debug::fmt(&self.message, f) - } -} +use std::{ + borrow::Cow, + hash::{Hash, Hasher}, +}; + +use bevy::{ + app::{Plugin, PostUpdate}, + ecs::{ + component::Component, + entity::Entity, + query::Added, + reflect::ReflectComponent, + system::{Commands, Query, Res}, + }, + reflect::{std_traits::ReflectDefault, Reflect}, + utils::AHasher, +}; +use dcs_grpc::dcs::trigger::v0::{ + trigger_service_client::TriggerServiceClient, OutTextForUnitRequest, +}; + +use tracing::info; + +use crate::{ + components::{GrpcBaseUrl, Id}, + TokioResource, +}; + +pub struct TextPlugin; + +impl Plugin for TextPlugin { + fn build(&self, app: &mut bevy::prelude::App) { + app.add_systems(PostUpdate, send_text_message); + } +} + +fn send_text_message( + mut commands: Commands, + query: Query<(Entity, &Id, &TextMessage), Added>, + url: Res, + tokio: Res, +) { + for (ent, id, msg) in query.iter() { + let url = url.to_string(); + + if msg.as_str().is_empty() { + commands.entity(ent).remove::(); + continue; + } + + let message = msg.clone(); + let url = url.clone(); + let id: u32 = id.into(); + tokio.0.spawn(async move { + let Ok(mut client) = TriggerServiceClient::connect(url.to_string()).await else { + return; + }; + + let request = OutTextForUnitRequest { + text: message.to_string(), + display_time: 15, + clear_view: false, + unit_id: id, + }; + + info!("> {}", message); + client.out_text_for_unit(request).await.ok(); + }); + + commands.entity(ent).remove::(); + } +} + +#[derive(Reflect, Component, Clone)] +#[reflect(Component, Default, Debug)] +pub struct TextMessage { + hash: u64, + message: Cow<'static, str>, +} + +impl Default for TextMessage { + fn default() -> Self { + TextMessage::new("") + } +} + +impl TextMessage { + /// Creates a new [`TextMessage`] from any string-like type. + /// + /// The internal hash will be computed immediately. + pub fn new(message: impl Into>) -> Self { + let message = message.into(); + let mut message = TextMessage { message, hash: 0 }; + message.update_hash(); + message + } + + /// Sets the entity's message. + /// + /// The internal hash will be re-computed. + #[inline(always)] + pub fn set(&mut self, message: impl Into>) { + *self = TextMessage::new(message); + } + + /// Updates the message of the entity in place. + /// + /// This will allocate a new string if the message was previously + /// created from a borrow. + #[inline(always)] + pub fn mutate(&mut self, f: F) { + f(self.message.to_mut()); + self.update_hash(); + } + + /// Gets the message of the entity as a `&str`. + #[inline(always)] + pub fn as_str(&self) -> &str { + &self.message + } + + fn update_hash(&mut self) { + let mut hasher = AHasher::default(); + self.message.hash(&mut hasher); + self.hash = hasher.finish(); + } +} + +impl std::fmt::Display for TextMessage { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Display::fmt(&self.message, f) + } +} + +impl std::fmt::Debug for TextMessage { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.message, f) + } +} diff --git a/crates/guardian_core/src/lib.rs b/crates/guardian_core/src/lib.rs old mode 100644 new mode 100755 index 4f4cffc..5d9c9b3 --- a/crates/guardian_core/src/lib.rs +++ b/crates/guardian_core/src/lib.rs @@ -1,29 +1,29 @@ -pub mod components; -pub mod dcs; -pub mod srs; -mod tts; - -use dcs::DcsPlugin; -use srs::SrsPlugin; - -use bevy::{ - app::{PluginGroup, PluginGroupBuilder}, - ecs::system::Resource, -}; -use tokio::runtime::Handle; - -pub struct DefaultPlugins; - -impl PluginGroup for DefaultPlugins { - fn build(self) -> PluginGroupBuilder { - #[allow(unused_mut)] - let mut group = PluginGroupBuilder::start::() - .add(DcsPlugin) - .add(SrsPlugin); - - group - } -} - -#[derive(Resource)] -pub struct TokioResource(pub Handle); +pub mod components; +pub mod dcs; +pub mod srs; +mod tts; + +use dcs::DcsPlugin; +use srs::SrsPlugin; + +use bevy::{ + app::{PluginGroup, PluginGroupBuilder}, + ecs::system::Resource, +}; +use tokio::runtime::Handle; + +pub struct DefaultPlugins; + +impl PluginGroup for DefaultPlugins { + fn build(self) -> PluginGroupBuilder { + #[allow(unused_mut)] + let mut group = PluginGroupBuilder::start::() + .add(DcsPlugin) + .add(SrsPlugin); + + group + } +} + +#[derive(Resource)] +pub struct TokioResource(pub Handle); diff --git a/crates/guardian_core/src/srs.rs b/crates/guardian_core/src/srs.rs old mode 100644 new mode 100755 index 1cbb314..7ef5a93 --- a/crates/guardian_core/src/srs.rs +++ b/crates/guardian_core/src/srs.rs @@ -261,7 +261,8 @@ fn listen_srs( } } Some(data) = voice_handle.recv() => { - frames.push(synthesize("192.168.0.238:10200", data.as_str()).await?).await; + // TODO: Make this configurable + frames.push(synthesize("192.168.1.3:10200", data.as_str()).await?).await; } Some(data) = voice_stream.next() => { match data { diff --git a/crates/guardian_core/src/srs/frame_queue.rs b/crates/guardian_core/src/srs/frame_queue.rs old mode 100644 new mode 100755 index e964f24..de1a216 --- a/crates/guardian_core/src/srs/frame_queue.rs +++ b/crates/guardian_core/src/srs/frame_queue.rs @@ -1,32 +1,32 @@ -// a queue we can push to at will -// we need to take an item and read async,stream? -// pull from the front, push to the back - -use std::{collections::VecDeque, sync::Arc}; - -use tokio::sync::RwLock; - -pub struct FrameQueue { - backend: Arc>>, -} - -impl FrameQueue { - pub fn new() -> Self { - Self { - backend: Arc::new(RwLock::new(VecDeque::new())), - } - } - pub async fn push(&self, item: T) { - self.backend.write().await.push_back(item); - } - - pub async fn next(&self) -> Option { - self.backend.write().await.pop_front() - } -} - -impl Default for FrameQueue { - fn default() -> Self { - Self::new() - } -} +// a queue we can push to at will +// we need to take an item and read async,stream? +// pull from the front, push to the back + +use std::{collections::VecDeque, sync::Arc}; + +use tokio::sync::RwLock; + +pub struct FrameQueue { + backend: Arc>>, +} + +impl FrameQueue { + pub fn new() -> Self { + Self { + backend: Arc::new(RwLock::new(VecDeque::new())), + } + } + pub async fn push(&self, item: T) { + self.backend.write().await.push_back(item); + } + + pub async fn next(&self) -> Option { + self.backend.write().await.pop_front() + } +} + +impl Default for FrameQueue { + fn default() -> Self { + Self::new() + } +} diff --git a/crates/guardian_core/src/srs/message.rs b/crates/guardian_core/src/srs/message.rs old mode 100644 new mode 100755 diff --git a/crates/guardian_core/src/srs/messages_codec.rs b/crates/guardian_core/src/srs/messages_codec.rs old mode 100644 new mode 100755 diff --git a/crates/guardian_core/src/srs/voice.rs b/crates/guardian_core/src/srs/voice.rs old mode 100644 new mode 100755 index a924108..1b50bcb --- a/crates/guardian_core/src/srs/voice.rs +++ b/crates/guardian_core/src/srs/voice.rs @@ -1,80 +1,80 @@ -use std::{ - borrow::Cow, - hash::{Hash, Hasher}, -}; - -use bevy::{ - ecs::{component::Component, reflect::ReflectComponent}, - reflect::{std_traits::ReflectDefault, Reflect}, - utils::AHasher, -}; - -#[derive(Reflect, Component, Clone)] -#[reflect(Component, Default, Debug)] -pub struct VoiceMessage { - hash: u64, - message: Cow<'static, str>, -} - -impl Default for VoiceMessage { - fn default() -> Self { - VoiceMessage::new("") - } -} - -#[allow(unused)] -impl VoiceMessage { - /// Creates a new [`VoiceMessage`] from any string-like type. - /// - /// The internal hash will be computed immediately. - pub fn new(message: impl Into>) -> Self { - let message = message.into(); - let mut message = VoiceMessage { message, hash: 0 }; - message.update_hash(); - message - } - - /// Sets the entity's message. - /// - /// The internal hash will be re-computed. - #[inline(always)] - pub fn set(&mut self, message: impl Into>) { - *self = VoiceMessage::new(message); - } - - /// Updates the message of the entity in place. - /// - /// This will allocate a new string if the message was previously - /// created from a borrow. - #[inline(always)] - pub fn mutate(&mut self, f: F) { - f(self.message.to_mut()); - self.update_hash(); - } - - /// Gets the message of the entity as a `&str`. - #[inline(always)] - pub fn as_str(&self) -> &str { - &self.message - } - - fn update_hash(&mut self) { - let mut hasher = AHasher::default(); - self.message.hash(&mut hasher); - self.hash = hasher.finish(); - } -} - -impl std::fmt::Display for VoiceMessage { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Display::fmt(&self.message, f) - } -} - -impl std::fmt::Debug for VoiceMessage { - #[inline(always)] - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - std::fmt::Debug::fmt(&self.message, f) - } -} +use std::{ + borrow::Cow, + hash::{Hash, Hasher}, +}; + +use bevy::{ + ecs::{component::Component, reflect::ReflectComponent}, + reflect::{std_traits::ReflectDefault, Reflect}, + utils::AHasher, +}; + +#[derive(Reflect, Component, Clone)] +#[reflect(Component, Default, Debug)] +pub struct VoiceMessage { + hash: u64, + message: Cow<'static, str>, +} + +impl Default for VoiceMessage { + fn default() -> Self { + VoiceMessage::new("") + } +} + +#[allow(unused)] +impl VoiceMessage { + /// Creates a new [`VoiceMessage`] from any string-like type. + /// + /// The internal hash will be computed immediately. + pub fn new(message: impl Into>) -> Self { + let message = message.into(); + let mut message = VoiceMessage { message, hash: 0 }; + message.update_hash(); + message + } + + /// Sets the entity's message. + /// + /// The internal hash will be re-computed. + #[inline(always)] + pub fn set(&mut self, message: impl Into>) { + *self = VoiceMessage::new(message); + } + + /// Updates the message of the entity in place. + /// + /// This will allocate a new string if the message was previously + /// created from a borrow. + #[inline(always)] + pub fn mutate(&mut self, f: F) { + f(self.message.to_mut()); + self.update_hash(); + } + + /// Gets the message of the entity as a `&str`. + #[inline(always)] + pub fn as_str(&self) -> &str { + &self.message + } + + fn update_hash(&mut self) { + let mut hasher = AHasher::default(); + self.message.hash(&mut hasher); + self.hash = hasher.finish(); + } +} + +impl std::fmt::Display for VoiceMessage { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Display::fmt(&self.message, f) + } +} + +impl std::fmt::Debug for VoiceMessage { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.message, f) + } +} diff --git a/crates/guardian_core/src/srs/voice_codec.rs b/crates/guardian_core/src/srs/voice_codec.rs old mode 100644 new mode 100755 diff --git a/crates/guardian_core/src/srs/voice_command.rs b/crates/guardian_core/src/srs/voice_command.rs old mode 100644 new mode 100755 diff --git a/crates/guardian_core/src/tts.rs b/crates/guardian_core/src/tts.rs old mode 100644 new mode 100755 index bbca70e..4fe4fef --- a/crates/guardian_core/src/tts.rs +++ b/crates/guardian_core/src/tts.rs @@ -1,209 +1,209 @@ -use std::io::Cursor; - -use bevy::log; -use dasp::interpolate::sinc::Sinc; -use dasp::ring_buffer; -use dasp::signal; -use dasp::Sample; -use dasp::Signal; - -use hound::WavSpec; -use hound::WavWriter; -use tokio::io::AsyncReadExt; -use tokio::io::AsyncWriteExt; -use tokio::net::TcpStream; -use tokio::net::ToSocketAddrs; - -use serde::Deserialize; -use serde::Serialize; - -#[derive(Debug, Deserialize)] -pub struct Packet { - #[serde(rename = "type")] - pub r#type: String, - pub version: String, - pub data_length: Option, - pub payload_length: Option, -} - -#[derive(Serialize)] -struct RequestData { - text: String, -} - -#[derive(Serialize)] -struct Request { - r#type: String, - data: RequestData, -} - -pub async fn synthesize( - addr: A, - text: &str, -) -> Result>, Box> { - let stream = TcpStream::connect(addr).await?; - - let (mut read, mut write) = tokio::io::split(stream); - - let request = Request { - r#type: "synthesize".to_string(), - data: RequestData { - text: text.to_string(), - }, - }; - - let mut request = serde_json::to_string(&request)?; - request.push('\n'); - - write.write_all(request.as_bytes()).await?; - - let mut str = String::new(); - let mut pcm_buffer: Vec = Vec::new(); - loop { - let Ok(c) = read.read_u8().await else { - log::error!("Unable to read byte"); - break; - }; - - if c == b'\n' { - let Ok(packet) = serde_json::from_str::(&str) else { - log::error!("Unable to read packet from: {}", str); - break; - }; - str = String::new(); - - if let Some(length) = packet.data_length { - let mut buf = (0..length).map(|_| 0u8).collect::>(); - - if let Err(e) = read.read_exact(&mut buf).await { - log::error!("Unable to read data: {:?}", e); - break; - } - }; - - if let Some(length) = packet.payload_length { - let mut buf = (0..length).map(|_| 0u8).collect::>(); - - if let Err(e) = read.read_exact(&mut buf).await { - log::error!("Unable to read data: {:?}", e); - break; - } - - pcm_buffer.append(&mut buf); - } - - match packet.r#type.as_str() { - "audio-start" => { - pcm_buffer.clear(); - } - "audio-stop" => { - log::info!("Audio received, start post-processing"); - break; - } - _ => {} - } - } - str.push(c.into()); - } - - let wav = to_wav(&pcm_buffer)?; - - let Ok(reader) = hound::WavReader::new(&*wav) else { - log::error!("Error opening reader"); - return Err("Error opening reader".into()); - }; - - // pcm_buffer is 22050Hz, need to convert this to 16000Hz - let samples = reader - .into_samples() - .filter_map(Result::ok) - .map(i16::to_sample::); - - let signal = signal::from_interleaved_samples_iter(samples); - - let ring_buffer = ring_buffer::Fixed::from([[0.0]; 100]); - let sinc = Sinc::new(ring_buffer); - - let new_signal = signal.from_hz_to_hz(sinc, 22050.0, 16000.0); - - let spec = WavSpec { - channels: 1, - sample_rate: 16000, - bits_per_sample: 16, - sample_format: hound::SampleFormat::Int, - }; - - let new_wav: Vec = Vec::new(); - let mut new_wav_cursor = Cursor::new(new_wav); - - let mut writer = WavWriter::new(&mut new_wav_cursor, spec).unwrap(); - - for frame in new_signal.until_exhausted() { - writer.write_sample(frame[0].to_sample::()).unwrap(); - } - - writer.flush().unwrap(); - - drop(writer); - - let wav = new_wav_cursor.into_inner(); - let wav = bytes::Bytes::copy_from_slice(&wav); - - Ok(wav_to_opus(wav).await?) -} - -async fn wav_to_opus(wav: bytes::Bytes) -> Result>, audiopus::Error> { - use audiopus::coder::Encoder; - use audiopus::{Application, Channels, SampleRate}; - - tokio::task::spawn_blocking(move || { - let audio_stream = wav - .chunks(2) - .map(|bytes| i16::from_le_bytes(bytes.try_into().unwrap())) - .collect::>(); - - const MONO_20MS: usize = 16000 /* 1 channel */ * 20 / 1000; - let enc = Encoder::new(SampleRate::Hz16000, Channels::Mono, Application::Voip)?; - let mut pos = 0; - let mut output = [0; 256]; - let mut frames = Vec::new(); - - while pos + MONO_20MS < audio_stream.len() { - let len = enc.encode(&audio_stream[pos..(pos + MONO_20MS)], &mut output)?; - frames.push(output[..len].to_vec()); - - pos += MONO_20MS; - } - - Ok::<_, audiopus::Error>(frames) - }) - .await - .unwrap() -} - -fn to_wav(data: &[u8]) -> Result, Box> { - let input_buffer: Vec = Vec::new(); - let mut input_buffer_cursor = Cursor::new(input_buffer); - - let input_spec = WavSpec { - channels: 1, - sample_rate: 22050, - bits_per_sample: 16, - sample_format: hound::SampleFormat::Int, - }; - - let mut input = hound::WavWriter::new(&mut input_buffer_cursor, input_spec)?; - - let audio_stream = data - .chunks(2) - .map(|bytes| i16::from_le_bytes(bytes.try_into().unwrap())) - .collect::>(); - - for frame in audio_stream { - input.write_sample(frame.to_sample::()).unwrap(); - } - - drop(input); - - Ok(input_buffer_cursor.into_inner()) -} +use std::io::Cursor; + +use bevy::log; +use dasp::interpolate::sinc::Sinc; +use dasp::ring_buffer; +use dasp::signal; +use dasp::Sample; +use dasp::Signal; + +use hound::WavSpec; +use hound::WavWriter; +use tokio::io::AsyncReadExt; +use tokio::io::AsyncWriteExt; +use tokio::net::TcpStream; +use tokio::net::ToSocketAddrs; + +use serde::Deserialize; +use serde::Serialize; + +#[derive(Debug, Deserialize)] +pub struct Packet { + #[serde(rename = "type")] + pub r#type: String, + pub version: String, + pub data_length: Option, + pub payload_length: Option, +} + +#[derive(Serialize)] +struct RequestData { + text: String, +} + +#[derive(Serialize)] +struct Request { + r#type: String, + data: RequestData, +} + +pub async fn synthesize( + addr: A, + text: &str, +) -> Result>, Box> { + let stream = TcpStream::connect(addr).await?; + + let (mut read, mut write) = tokio::io::split(stream); + + let request = Request { + r#type: "synthesize".to_string(), + data: RequestData { + text: text.to_string(), + }, + }; + + let mut request = serde_json::to_string(&request)?; + request.push('\n'); + + write.write_all(request.as_bytes()).await?; + + let mut str = String::new(); + let mut pcm_buffer: Vec = Vec::new(); + loop { + let Ok(c) = read.read_u8().await else { + log::error!("Unable to read byte"); + break; + }; + + if c == b'\n' { + let Ok(packet) = serde_json::from_str::(&str) else { + log::error!("Unable to read packet from: {}", str); + break; + }; + str = String::new(); + + if let Some(length) = packet.data_length { + let mut buf = (0..length).map(|_| 0u8).collect::>(); + + if let Err(e) = read.read_exact(&mut buf).await { + log::error!("Unable to read data: {:?}", e); + break; + } + }; + + if let Some(length) = packet.payload_length { + let mut buf = (0..length).map(|_| 0u8).collect::>(); + + if let Err(e) = read.read_exact(&mut buf).await { + log::error!("Unable to read data: {:?}", e); + break; + } + + pcm_buffer.append(&mut buf); + } + + match packet.r#type.as_str() { + "audio-start" => { + pcm_buffer.clear(); + } + "audio-stop" => { + log::info!("Audio received, start post-processing"); + break; + } + _ => {} + } + } + str.push(c.into()); + } + + let wav = to_wav(&pcm_buffer)?; + + let Ok(reader) = hound::WavReader::new(&*wav) else { + log::error!("Error opening reader"); + return Err("Error opening reader".into()); + }; + + // pcm_buffer is 22050Hz, need to convert this to 16000Hz + let samples = reader + .into_samples() + .filter_map(Result::ok) + .map(i16::to_sample::); + + let signal = signal::from_interleaved_samples_iter(samples); + + let ring_buffer = ring_buffer::Fixed::from([[0.0]; 100]); + let sinc = Sinc::new(ring_buffer); + + let new_signal = signal.from_hz_to_hz(sinc, 22050.0, 16000.0); + + let spec = WavSpec { + channels: 1, + sample_rate: 16000, + bits_per_sample: 16, + sample_format: hound::SampleFormat::Int, + }; + + let new_wav: Vec = Vec::new(); + let mut new_wav_cursor = Cursor::new(new_wav); + + let mut writer = WavWriter::new(&mut new_wav_cursor, spec).unwrap(); + + for frame in new_signal.until_exhausted() { + writer.write_sample(frame[0].to_sample::()).unwrap(); + } + + writer.flush().unwrap(); + + drop(writer); + + let wav = new_wav_cursor.into_inner(); + let wav = bytes::Bytes::copy_from_slice(&wav); + + Ok(wav_to_opus(wav).await?) +} + +async fn wav_to_opus(wav: bytes::Bytes) -> Result>, audiopus::Error> { + use audiopus::coder::Encoder; + use audiopus::{Application, Channels, SampleRate}; + + tokio::task::spawn_blocking(move || { + let audio_stream = wav + .chunks(2) + .map(|bytes| i16::from_le_bytes(bytes.try_into().unwrap())) + .collect::>(); + + const MONO_20MS: usize = 16000 /* 1 channel */ * 20 / 1000; + let enc = Encoder::new(SampleRate::Hz16000, Channels::Mono, Application::Voip)?; + let mut pos = 0; + let mut output = [0; 256]; + let mut frames = Vec::new(); + + while pos + MONO_20MS < audio_stream.len() { + let len = enc.encode(&audio_stream[pos..(pos + MONO_20MS)], &mut output)?; + frames.push(output[..len].to_vec()); + + pos += MONO_20MS; + } + + Ok::<_, audiopus::Error>(frames) + }) + .await + .unwrap() +} + +fn to_wav(data: &[u8]) -> Result, Box> { + let input_buffer: Vec = Vec::new(); + let mut input_buffer_cursor = Cursor::new(input_buffer); + + let input_spec = WavSpec { + channels: 1, + sample_rate: 22050, + bits_per_sample: 16, + sample_format: hound::SampleFormat::Int, + }; + + let mut input = hound::WavWriter::new(&mut input_buffer_cursor, input_spec)?; + + let audio_stream = data + .chunks(2) + .map(|bytes| i16::from_le_bytes(bytes.try_into().unwrap())) + .collect::>(); + + for frame in audio_stream { + input.write_sample(frame.to_sample::()).unwrap(); + } + + drop(input); + + Ok(input_buffer_cursor.into_inner()) +} diff --git a/rust-toolchain.toml b/rust-toolchain.toml old mode 100644 new mode 100755 index 292fe49..ec19b69 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,2 @@ -[toolchain] -channel = "stable" +[toolchain] +channel = "stable" diff --git a/src/braa.rs b/src/braa.rs old mode 100644 new mode 100755 index 98fb384..040a4e2 --- a/src/braa.rs +++ b/src/braa.rs @@ -1,97 +1,97 @@ -use std::fmt::Display; - -use guardian_core::components::{Heading, Position}; - -#[derive(Clone)] -pub enum Aspect { - Hot, - Flank, - Cold, -} - -impl std::fmt::Display for Aspect { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Hot => write!(f, "Hot"), - Self::Flank => write!(f, "Flank"), - Self::Cold => write!(f, "Cold"), - } - } -} - -#[derive(Clone)] -pub struct Braa { - bearing: i32, - range: i32, - angels: i32, - aspect: Aspect, -} - -impl Display for Braa { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.to_text()) - } -} - -#[allow(unused)] -impl Braa { - pub fn new(unit_a: &Position, unit_b: &Position, heading_b: &Heading) -> Self { - let bearing = unit_a.get_bearing_to(unit_b); - let range = unit_a.distance_to_nmi(unit_b).round() as i32; - let angels = unit_b.angels(); - let aspect = { - let bearing = unit_b.get_bearing_to(unit_a); - let angle = (bearing - heading_b.0 as i32) % 360; - if (45..135).contains(&angle) { - Aspect::Flank - } else if (135..225).contains(&angle) { - Aspect::Cold - } else if (225..315).contains(&angle) { - Aspect::Flank - } else if !(45..=315).contains(&angle) { - Aspect::Hot - } else { - Aspect::Cold - } - }; - - Self { - bearing, - range, - angels, - aspect, - } - } - - pub fn to_text(&self) -> String { - format!( - "BRA {}° for {}NM at {} thousand {}", - self.bearing, self.range, self.angels, self.aspect - ) - } - - pub fn to_voice(&self) -> String { - let bearing = split(&self.bearing.to_string(), 1); - let range = split(&self.range.to_string(), 1); - format!( - "BRA . . . {} . . . {} . . . {} thousand . . . {}", - bearing, range, self.angels, self.aspect - ) - } -} - -fn split(input: &str, n: usize) -> String { - input - .chars() - .enumerate() - .flat_map(|(i, c)| { - if i != 0 && i % n == 0 { - Some(' ') - } else { - None - } - .into_iter() - .chain(std::iter::once(c)) - }) - .collect::() -} +use std::fmt::Display; + +use guardian_core::components::{Heading, Position}; + +#[derive(Clone)] +pub enum Aspect { + Hot, + Flank, + Cold, +} + +impl std::fmt::Display for Aspect { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Hot => write!(f, "Hot"), + Self::Flank => write!(f, "Flank"), + Self::Cold => write!(f, "Cold"), + } + } +} + +#[derive(Clone)] +pub struct Braa { + bearing: i32, + range: i32, + angels: i32, + aspect: Aspect, +} + +impl Display for Braa { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.to_text()) + } +} + +#[allow(unused)] +impl Braa { + pub fn new(unit_a: &Position, unit_b: &Position, heading_b: &Heading) -> Self { + let bearing = unit_a.get_bearing_to(unit_b); + let range = unit_a.distance_to_nmi(unit_b).round() as i32; + let angels = unit_b.angels(); + let aspect = { + let bearing = unit_b.get_bearing_to(unit_a); + let angle = (bearing - heading_b.0 as i32) % 360; + if (45..135).contains(&angle) { + Aspect::Flank + } else if (135..225).contains(&angle) { + Aspect::Cold + } else if (225..315).contains(&angle) { + Aspect::Flank + } else if !(45..=315).contains(&angle) { + Aspect::Hot + } else { + Aspect::Cold + } + }; + + Self { + bearing, + range, + angels, + aspect, + } + } + + pub fn to_text(&self) -> String { + format!( + "BRA {}° for {}NM at {} thousand {}", + self.bearing, self.range, self.angels, self.aspect + ) + } + + pub fn to_voice(&self) -> String { + let bearing = split(&self.bearing.to_string(), 1); + let range = split(&self.range.to_string(), 1); + format!( + "BRA . . . {} . . . {} . . . {} thousand . . . {}", + bearing, range, self.angels, self.aspect + ) + } +} + +fn split(input: &str, n: usize) -> String { + input + .chars() + .enumerate() + .flat_map(|(i, c)| { + if i != 0 && i % n == 0 { + Some(' ') + } else { + None + } + .into_iter() + .chain(std::iter::once(c)) + }) + .collect::() +} diff --git a/src/commands/bogeydope.rs b/src/commands/bogeydope.rs old mode 100644 new mode 100755 index aefda18..624244f --- a/src/commands/bogeydope.rs +++ b/src/commands/bogeydope.rs @@ -1,93 +1,93 @@ -use bevy::ecs::{ - query::{With, Without}, - system::{Commands, Query, Resource}, -}; -use clap::Parser; -use guardian_commands::{ConsoleCommand, NamedCommand}; -use guardian_core::{components::*, dcs::text::TextMessage, srs::voice::VoiceMessage}; -use tracing::debug; - -use crate::braa::Braa; - -#[derive(Parser, Debug)] -pub struct BogeyDope; - -impl NamedCommand for BogeyDope { - fn name() -> &'static str { - "[shopping|bogey dope]" - } -} - -impl Resource for BogeyDope {} - -pub fn bogey_dope( - mut commands: Commands, - mut cmd: ConsoleCommand, - awacs: Query<&Callsign>, - player: Query<(&Callsign, &Position)>, - npc: Query<(&Position, &Heading, &Velocity), (Without, With)>, -) { - let Some(Ok(BogeyDope)) = cmd.take() else { - return; - }; - let Some(pilot) = &cmd.pilot else { - return; // no pilot - }; - let Some(operator) = &cmd.operator else { - return; - }; - - let Ok((p_callsign, p_pos)) = player.get(*pilot) else { - debug!("no player, died?"); - return; - }; - - let Ok(a_callsign) = awacs.get(*operator) else { - debug!("no awacs, they died?"); - return; - }; - - let mut distance: f64 = f64::MAX; - let mut n = (None, None); - for (n_pos, n_heading, n_velocity) in npc.iter() { - if n_velocity.speed() < 10.0 { - // ignore slow/on-ground units - continue; - } - let d = p_pos.distance_to_nmi(n_pos); - if d < distance { - distance = d; - n = (Some(n_pos), Some(n_heading)); - } - } - - let (Some(n_position), Some(n_heading)) = n else { - let message = format!("{}, {}, {}", p_callsign, a_callsign, "Skies are clear"); - let voice_message = format!( - "{} . . . {} . . . {}", - p_callsign.to_voice(), - a_callsign.to_voice(), - "Skies are clear" - ); - - commands.entity(*pilot).insert(TextMessage::new(message)); - commands - .entity(*operator) - .insert(VoiceMessage::new(voice_message)); - return; - }; - - let bra = Braa::new(p_pos, n_position, n_heading); - let message = format!("{}, {}, {}", p_callsign, a_callsign, bra); - let voice_message = format!( - "{} . . . {} . . . {}", - p_callsign.to_voice(), - a_callsign.to_voice(), - bra.to_voice() - ); - - commands.entity(*pilot).insert(TextMessage::new(message)); - commands - .entity(*operator) - .insert(VoiceMessage::new(voice_message)); -} +use bevy::ecs::{ + query::{With, Without}, + system::{Commands, Query, Resource}, +}; +use clap::Parser; +use guardian_commands::{ConsoleCommand, NamedCommand}; +use guardian_core::{components::*, dcs::text::TextMessage, srs::voice::VoiceMessage}; +use tracing::debug; + +use crate::braa::Braa; + +#[derive(Parser, Debug)] +pub struct BogeyDope; + +impl NamedCommand for BogeyDope { + fn name() -> &'static str { + "[shopping|bogey dope]" + } +} + +impl Resource for BogeyDope {} + +pub fn bogey_dope( + mut commands: Commands, + mut cmd: ConsoleCommand, + awacs: Query<&Callsign>, + player: Query<(&Callsign, &Position)>, + npc: Query<(&Position, &Heading, &Velocity), (Without, With)>, +) { + let Some(Ok(BogeyDope)) = cmd.take() else { + return; + }; + let Some(pilot) = &cmd.pilot else { + return; // no pilot + }; + let Some(operator) = &cmd.operator else { + return; + }; + + let Ok((p_callsign, p_pos)) = player.get(*pilot) else { + debug!("no player, died?"); + return; + }; + + let Ok(a_callsign) = awacs.get(*operator) else { + debug!("no awacs, they died?"); + return; + }; + + let mut distance: f64 = f64::MAX; + let mut n = (None, None); + for (n_pos, n_heading, n_velocity) in npc.iter() { + if n_velocity.speed() < 10.0 { + // ignore slow/on-ground units + continue; + } + let d = p_pos.distance_to_nmi(n_pos); + if d < distance { + distance = d; + n = (Some(n_pos), Some(n_heading)); + } + } + + let (Some(n_position), Some(n_heading)) = n else { + let message = format!("{}, {}, {}", p_callsign, a_callsign, "Skies are clear"); + let voice_message = format!( + "{} . . . {} . . . {}", + p_callsign.to_voice(), + a_callsign.to_voice(), + "Skies are clear" + ); + + commands.entity(*pilot).insert(TextMessage::new(message)); + commands + .entity(*operator) + .insert(VoiceMessage::new(voice_message)); + return; + }; + + let bra = Braa::new(p_pos, n_position, n_heading); + let message = format!("{}, {}, {}", p_callsign, a_callsign, bra); + let voice_message = format!( + "{} . . . {} . . . {}", + p_callsign.to_voice(), + a_callsign.to_voice(), + bra.to_voice() + ); + + commands.entity(*pilot).insert(TextMessage::new(message)); + commands + .entity(*operator) + .insert(VoiceMessage::new(voice_message)); +} diff --git a/src/commands/cleartripwire.rs b/src/commands/cleartripwire.rs old mode 100644 new mode 100755 index 4ad595f..b91318f --- a/src/commands/cleartripwire.rs +++ b/src/commands/cleartripwire.rs @@ -1,60 +1,60 @@ -use bevy::ecs::system::{Commands, Query, Resource}; -use clap::Parser; -use guardian_commands::{ConsoleCommand, NamedCommand}; -use guardian_core::{components::*, dcs::text::TextMessage, srs::voice::VoiceMessage}; -use tracing::debug; - -use crate::tripwire::Tripwire; - -#[derive(Parser, Debug)] -pub struct ClearTripwireCommand; - -impl NamedCommand for ClearTripwireCommand { - fn name() -> &'static str { - "clear [tripwire|warning]" - } -} - -impl Resource for ClearTripwireCommand {} - -pub fn clear_tripwire( - mut commands: Commands, - mut cmd: ConsoleCommand, - callsign: Query<&Callsign>, -) { - let Some(Ok(ClearTripwireCommand)) = cmd.take() else { - return; - }; - let Some(pilot) = &cmd.pilot else { - debug!("no pilot"); - return; - }; - let Some(operator) = &cmd.operator else { - debug!("no operator"); - return; - }; - - let Ok(p_callsign) = callsign.get(*pilot) else { - debug!("no player, died?"); - return; - }; - - let Ok(a_callsign) = callsign.get(*operator) else { - debug!("no awacs, they died?"); - return; - }; - - commands.entity(*pilot).remove::(); - - let message = format!("{}, {}, tripwire cleared", p_callsign, a_callsign); - let message_voice = format!( - "{}, {}, tripwire cleared", - p_callsign.to_voice(), - a_callsign.to_voice(), - ); - - commands.entity(*pilot).insert(TextMessage::new(message)); - commands - .entity(*operator) - .insert(VoiceMessage::new(message_voice)); -} +use bevy::ecs::system::{Commands, Query, Resource}; +use clap::Parser; +use guardian_commands::{ConsoleCommand, NamedCommand}; +use guardian_core::{components::*, dcs::text::TextMessage, srs::voice::VoiceMessage}; +use tracing::debug; + +use crate::tripwire::Tripwire; + +#[derive(Parser, Debug)] +pub struct ClearTripwireCommand; + +impl NamedCommand for ClearTripwireCommand { + fn name() -> &'static str { + "clear [tripwire|warning]" + } +} + +impl Resource for ClearTripwireCommand {} + +pub fn clear_tripwire( + mut commands: Commands, + mut cmd: ConsoleCommand, + callsign: Query<&Callsign>, +) { + let Some(Ok(ClearTripwireCommand)) = cmd.take() else { + return; + }; + let Some(pilot) = &cmd.pilot else { + debug!("no pilot"); + return; + }; + let Some(operator) = &cmd.operator else { + debug!("no operator"); + return; + }; + + let Ok(p_callsign) = callsign.get(*pilot) else { + debug!("no player, died?"); + return; + }; + + let Ok(a_callsign) = callsign.get(*operator) else { + debug!("no awacs, they died?"); + return; + }; + + commands.entity(*pilot).remove::(); + + let message = format!("{}, {}, tripwire cleared", p_callsign, a_callsign); + let message_voice = format!( + "{}, {}, tripwire cleared", + p_callsign.to_voice(), + a_callsign.to_voice(), + ); + + commands.entity(*pilot).insert(TextMessage::new(message)); + commands + .entity(*operator) + .insert(VoiceMessage::new(message_voice)); +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs old mode 100644 new mode 100755 index 1a43501..711dba2 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -1,23 +1,23 @@ -use bevy::app::Plugin; -use guardian_commands::AddConsoleCommand; - -mod bogeydope; -mod cleartripwire; -mod radiocheck; -mod tripwire; - -use bogeydope::*; -use cleartripwire::*; -use radiocheck::*; -use tripwire::*; -pub struct CommandsPlugin; - -impl Plugin for CommandsPlugin { - fn build(&self, app: &mut bevy::prelude::App) { - app.add_plugins(guardian_commands::CommandsPlugin); - app.add_console_command::(bogey_dope); - app.add_console_command::(radio_check); - app.add_console_command::(set_tripwire); - app.add_console_command::(clear_tripwire); - } -} +use bevy::app::Plugin; +use guardian_commands::AddConsoleCommand; + +mod bogeydope; +mod cleartripwire; +mod radiocheck; +mod tripwire; + +use bogeydope::*; +use cleartripwire::*; +use radiocheck::*; +use tripwire::*; +pub struct CommandsPlugin; + +impl Plugin for CommandsPlugin { + fn build(&self, app: &mut bevy::prelude::App) { + app.add_plugins(guardian_commands::CommandsPlugin); + app.add_console_command::(bogey_dope); + app.add_console_command::(radio_check); + app.add_console_command::(set_tripwire); + app.add_console_command::(clear_tripwire); + } +} diff --git a/src/commands/radiocheck.rs b/src/commands/radiocheck.rs old mode 100644 new mode 100755 index 49799ce..221dca5 --- a/src/commands/radiocheck.rs +++ b/src/commands/radiocheck.rs @@ -1,57 +1,57 @@ -use bevy::ecs::system::{Commands, Query, Resource}; -use clap::Parser; -use guardian_commands::{ConsoleCommand, NamedCommand}; -use guardian_core::{components::*, dcs::text::TextMessage, srs::voice::VoiceMessage}; -use tracing::debug; - -#[derive(Parser, Debug)] -pub struct RadioCheck; - -impl NamedCommand for RadioCheck { - fn name() -> &'static str { - "radio check" - } -} - -impl Resource for RadioCheck {} - -pub fn radio_check( - mut commands: Commands, - mut cmd: ConsoleCommand, - callsign: Query<&Callsign>, -) { - let Some(Ok(RadioCheck)) = cmd.take() else { - return; - }; - let Some(pilot) = &cmd.pilot else { - debug!("no pilot"); - return; - }; - let Some(operator) = &cmd.operator else { - debug!("no operator"); - return; - }; - - let Ok(p_callsign) = callsign.get(*pilot) else { - debug!("no player, died?"); - return; - }; - - let Ok(a_callsign) = callsign.get(*operator) else { - debug!("no awacs, they died?"); - return; - }; - - let message = format!("{}, {}, {}", p_callsign, a_callsign, "five by five"); - let voice_message = format!( - "{} . . . {} . . . {}", - p_callsign.to_voice(), - a_callsign.to_voice(), - "five by five" - ); - - commands.entity(*pilot).insert(TextMessage::new(message)); - commands - .entity(*operator) - .insert(VoiceMessage::new(voice_message)); -} +use bevy::ecs::system::{Commands, Query, Resource}; +use clap::Parser; +use guardian_commands::{ConsoleCommand, NamedCommand}; +use guardian_core::{components::*, dcs::text::TextMessage, srs::voice::VoiceMessage}; +use tracing::debug; + +#[derive(Parser, Debug)] +pub struct RadioCheck; + +impl NamedCommand for RadioCheck { + fn name() -> &'static str { + "radio check" + } +} + +impl Resource for RadioCheck {} + +pub fn radio_check( + mut commands: Commands, + mut cmd: ConsoleCommand, + callsign: Query<&Callsign>, +) { + let Some(Ok(RadioCheck)) = cmd.take() else { + return; + }; + let Some(pilot) = &cmd.pilot else { + debug!("no pilot"); + return; + }; + let Some(operator) = &cmd.operator else { + debug!("no operator"); + return; + }; + + let Ok(p_callsign) = callsign.get(*pilot) else { + debug!("no player, died?"); + return; + }; + + let Ok(a_callsign) = callsign.get(*operator) else { + debug!("no awacs, they died?"); + return; + }; + + let message = format!("{}, {}, {}", p_callsign, a_callsign, "five by five"); + let voice_message = format!( + "{} . . . {} . . . {}", + p_callsign.to_voice(), + a_callsign.to_voice(), + "five by five" + ); + + commands.entity(*pilot).insert(TextMessage::new(message)); + commands + .entity(*operator) + .insert(VoiceMessage::new(voice_message)); +} diff --git a/src/commands/tripwire.rs b/src/commands/tripwire.rs old mode 100644 new mode 100755 index 538993a..76a6708 --- a/src/commands/tripwire.rs +++ b/src/commands/tripwire.rs @@ -1,103 +1,103 @@ -use bevy::ecs::system::{Commands, Query, Resource}; -use clap::Parser; -use guardian_commands::{ConsoleCommand, NamedCommand}; -use guardian_core::{components::*, dcs::text::TextMessage, srs::voice::VoiceMessage}; -use tracing::debug; - -use crate::tripwire::Tripwire; - -#[derive(Parser, Debug)] -pub struct TripwireCommand; - -impl NamedCommand for TripwireCommand { - fn name() -> &'static str { - "set [tripwire|warning]" - } -} - -impl Resource for TripwireCommand {} - -pub fn set_tripwire( - mut commands: Commands, - mut cmd: ConsoleCommand, - callsign: Query<&Callsign>, -) { - let Some(Ok(TripwireCommand)) = cmd.take() else { - return; - }; - let Some(pilot) = &cmd.pilot else { - debug!("no pilot"); - return; - }; - let Some(operator) = &cmd.operator else { - debug!("no operator"); - return; - }; - - let Ok(p_callsign) = callsign.get(*pilot) else { - debug!("no player, died?"); - return; - }; - - let Ok(a_callsign) = callsign.get(*operator) else { - debug!("no awacs, they died?"); - return; - }; - let Some(readback) = &cmd.raw else { - debug!("no readback"); - return; - }; - - let mut parts = readback.split(' '); - - // check the last part, if it's a number, interpret as miles - let Some(last) = parts.nth_back(0) else { - debug!("no last part"); - return; - }; - - let distance = match last.parse::() { - Ok(distance) => distance, // a number is found, interpret as miles - Err(_) => { - let Some(maybe_number) = parts.nth_back(0) else { - // Report message garbled.. - return; - }; - - match maybe_number.parse::() { - Ok(n) => { - if last == "kilometers" || last == "km" { - (n as f64 * 0.621371).round() as i32 - } else { - n - } - } - Err(_) => { - // let message = format!("{}, {}. Unable to read, Say again.", caller, receiver); - return; - } - } - } - }; - - // clamp distance between 0 and 120 - let distance = distance.min(120).max(0); - - commands.entity(*pilot).insert(Tripwire::new(distance)); - - let message = format!( - "{}, {}, tripwire set to {} miles", - p_callsign, a_callsign, distance - ); - let message_voice = format!( - "{}, {}, tripwire set to {} miles", - p_callsign.to_voice(), - a_callsign.to_voice(), - distance - ); - - commands.entity(*pilot).insert(TextMessage::new(message)); - commands - .entity(*operator) - .insert(VoiceMessage::new(message_voice)); -} +use bevy::ecs::system::{Commands, Query, Resource}; +use clap::Parser; +use guardian_commands::{ConsoleCommand, NamedCommand}; +use guardian_core::{components::*, dcs::text::TextMessage, srs::voice::VoiceMessage}; +use tracing::debug; + +use crate::tripwire::Tripwire; + +#[derive(Parser, Debug)] +pub struct TripwireCommand; + +impl NamedCommand for TripwireCommand { + fn name() -> &'static str { + "set [tripwire|warning]" + } +} + +impl Resource for TripwireCommand {} + +pub fn set_tripwire( + mut commands: Commands, + mut cmd: ConsoleCommand, + callsign: Query<&Callsign>, +) { + let Some(Ok(TripwireCommand)) = cmd.take() else { + return; + }; + let Some(pilot) = &cmd.pilot else { + debug!("no pilot"); + return; + }; + let Some(operator) = &cmd.operator else { + debug!("no operator"); + return; + }; + + let Ok(p_callsign) = callsign.get(*pilot) else { + debug!("no player, died?"); + return; + }; + + let Ok(a_callsign) = callsign.get(*operator) else { + debug!("no awacs, they died?"); + return; + }; + let Some(readback) = &cmd.raw else { + debug!("no readback"); + return; + }; + + let mut parts = readback.split(' '); + + // check the last part, if it's a number, interpret as miles + let Some(last) = parts.nth_back(0) else { + debug!("no last part"); + return; + }; + + let distance = match last.parse::() { + Ok(distance) => distance, // a number is found, interpret as miles + Err(_) => { + let Some(maybe_number) = parts.nth_back(0) else { + // Report message garbled.. + return; + }; + + match maybe_number.parse::() { + Ok(n) => { + if last == "kilometers" || last == "km" { + (n as f64 * 0.621371).round() as i32 + } else { + n + } + } + Err(_) => { + // let message = format!("{}, {}. Unable to read, Say again.", caller, receiver); + return; + } + } + } + }; + + // clamp distance between 0 and 120 + let distance = distance.min(120).max(0); + + commands.entity(*pilot).insert(Tripwire::new(distance)); + + let message = format!( + "{}, {}, tripwire set to {} miles", + p_callsign, a_callsign, distance + ); + let message_voice = format!( + "{}, {}, tripwire set to {} miles", + p_callsign.to_voice(), + a_callsign.to_voice(), + distance + ); + + commands.entity(*pilot).insert(TextMessage::new(message)); + commands + .entity(*operator) + .insert(VoiceMessage::new(message_voice)); +} diff --git a/src/config.rs b/src/config.rs old mode 100644 new mode 100755 diff --git a/src/main.rs b/src/main.rs old mode 100644 new mode 100755 diff --git a/src/tripwire.rs b/src/tripwire.rs old mode 100644 new mode 100755 index 73be825..d4270b0 --- a/src/tripwire.rs +++ b/src/tripwire.rs @@ -1,91 +1,91 @@ -use bevy::{ - app::{Plugin, Update}, - ecs::{ - component::Component, - entity::Entity, - query::{With, Without}, - system::{Commands, Query}, - }, -}; -use guardian_core::{ - components::*, - dcs::text::TextMessage, - srs::{voice::VoiceMessage, Radio, RadioInfo}, -}; - -use crate::braa::Braa; - -pub struct TripwirePlugin; - -impl Plugin for TripwirePlugin { - fn build(&self, app: &mut bevy::prelude::App) { - app.add_systems(Update, tripwire); - } -} - -fn tripwire( - mut commands: Commands, - awacs: Query<(Entity, &Callsign, &Radio), (With, With, With)>, - mut players: Query<(Entity, &Callsign, &Position, &RadioInfo, &mut Tripwire), With>, - npc: Query<(&Id, &Position, &Heading, &Velocity), (Without, With)>, -) { - // get the players radio frequencies - // match the tuned frequency with one of the awacs' - // broadcast message on that ferquency and as that awacs - - for (ent, awacs, radio) in awacs.iter() { - for (p_ent, p_callsign, p_position, radioinfo, mut p_tripwire) in players.iter_mut() { - // check if user is on the same frequency as awacs - if !radioinfo - .radios - .iter() - .any(|f| f.freq as u64 == radio.frequency && f.modulation == radio.modulation) - { - continue; - } - - for (n_id, n_position, n_heading, n_velocity) in npc.iter() { - if n_velocity.speed() < 10.0 { - // ignore slow/on-ground units - continue; - } - let distance = n_position.distance_to_nmi(p_position); - if distance <= p_tripwire.range && !p_tripwire.reported.contains(n_id) { - p_tripwire.reported.push(*n_id); - - let bra = Braa::new(p_position, n_position, n_heading); - let message = format!("{}, {}, {}", p_callsign, awacs, bra); - let voice_message = format!( - "{} . . . {} . . . {}", - p_callsign.to_voice(), - awacs.to_voice(), - bra.to_voice() - ); - - // commands.spawn((Id::new(player_id.into()), TextMessage::new(message))); - commands.entity(p_ent).insert(TextMessage::new(message)); - commands - .entity(ent) - .insert(VoiceMessage::new(voice_message)); - } else if distance > p_tripwire.range && p_tripwire.reported.contains(n_id) { - p_tripwire.reported.retain(|b| b != n_id); - } - } - } - } -} - -#[derive(Debug, Component)] -pub struct Tripwire { - range: f64, - reported: Vec, -} - -impl Tripwire { - pub fn new(distance: i32) -> Self { - Self { - range: distance as f64, - reported: vec![], - } - } -} +use bevy::{ + app::{Plugin, Update}, + ecs::{ + component::Component, + entity::Entity, + query::{With, Without}, + system::{Commands, Query}, + }, +}; +use guardian_core::{ + components::*, + dcs::text::TextMessage, + srs::{voice::VoiceMessage, Radio, RadioInfo}, +}; + +use crate::braa::Braa; + +pub struct TripwirePlugin; + +impl Plugin for TripwirePlugin { + fn build(&self, app: &mut bevy::prelude::App) { + app.add_systems(Update, tripwire); + } +} + +fn tripwire( + mut commands: Commands, + awacs: Query<(Entity, &Callsign, &Radio), (With, With, With)>, + mut players: Query<(Entity, &Callsign, &Position, &RadioInfo, &mut Tripwire), With>, + npc: Query<(&Id, &Position, &Heading, &Velocity), (Without, With)>, +) { + // get the players radio frequencies + // match the tuned frequency with one of the awacs' + // broadcast message on that ferquency and as that awacs + + for (ent, awacs, radio) in awacs.iter() { + for (p_ent, p_callsign, p_position, radioinfo, mut p_tripwire) in players.iter_mut() { + // check if user is on the same frequency as awacs + if !radioinfo + .radios + .iter() + .any(|f| f.freq as u64 == radio.frequency && f.modulation == radio.modulation) + { + continue; + } + + for (n_id, n_position, n_heading, n_velocity) in npc.iter() { + if n_velocity.speed() < 10.0 { + // ignore slow/on-ground units + continue; + } + let distance = n_position.distance_to_nmi(p_position); + if distance <= p_tripwire.range && !p_tripwire.reported.contains(n_id) { + p_tripwire.reported.push(*n_id); + + let bra = Braa::new(p_position, n_position, n_heading); + let message = format!("{}, {}, {}", p_callsign, awacs, bra); + let voice_message = format!( + "{} . . . {} . . . {}", + p_callsign.to_voice(), + awacs.to_voice(), + bra.to_voice() + ); + + // commands.spawn((Id::new(player_id.into()), TextMessage::new(message))); + commands.entity(p_ent).insert(TextMessage::new(message)); + commands + .entity(ent) + .insert(VoiceMessage::new(voice_message)); + } else if distance > p_tripwire.range && p_tripwire.reported.contains(n_id) { + p_tripwire.reported.retain(|b| b != n_id); + } + } + } + } +} + +#[derive(Debug, Component)] +pub struct Tripwire { + range: f64, + reported: Vec, +} + +impl Tripwire { + pub fn new(distance: i32) -> Self { + Self { + range: distance as f64, + reported: vec![], + } + } +}