├── .github ├── dependabot.yml └── workflows │ └── planetoid.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── client ├── .gitattributes ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── fonts │ ├── BebasNeue-Regular.ttf │ └── OFL.txt ├── images │ └── space.webp ├── index.html ├── planetoid.wasm ├── sounds │ ├── explosion.wav │ ├── laser.wav │ ├── thrust.wav │ └── victory.wav └── src │ ├── asteroid.rs │ ├── bullet.rs │ ├── collision.rs │ ├── gameover.rs │ ├── main.rs │ ├── network.rs │ ├── screen.rs │ ├── ship.rs │ └── sound.rs ├── images ├── infra.png ├── multiplayer_game.jpg ├── planetoid_native.jpg └── planetoid_wasm32.jpg ├── server ├── .dockerignore ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── MavenWrapperDownloader.java │ │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── fr │ │ │ └── uggla │ │ │ ├── Game.java │ │ │ ├── Games.java │ │ │ ├── Player.java │ │ │ ├── Players.java │ │ │ └── resteasyjackson │ │ │ ├── JacksonResource.java │ │ │ └── MyObjectMapperCustomizer.java │ └── resources │ │ ├── application.properties │ │ └── import.sql │ └── test │ └── java │ └── fr │ └── uggla │ ├── NativePlayersIT.java │ └── PlayersTest.java └── worker ├── .dockerignore ├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── docker │ ├── Dockerfile.jvm │ ├── Dockerfile.legacy-jar │ ├── Dockerfile.native │ └── Dockerfile.native-distroless ├── java │ └── fr │ │ └── uggla │ │ ├── GameData.java │ │ └── Planetoid.java └── resources │ ├── META-INF │ └── resources │ │ ├── chat.html │ │ └── index.html │ └── application.properties └── test └── java └── fr └── uggla ├── NativeplanetoidIT.java ├── PlanetoidTest.java └── undertowwebsockets └── GameDataSocketTest.java /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "maven" # See documentation for possible values 9 | directory: "/server" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | 13 | - package-ecosystem: "maven" # See documentation for possible values 14 | directory: "/worker" # Location of package manifests 15 | schedule: 16 | interval: "weekly" 17 | 18 | - package-ecosystem: "cargo" # See documentation for possible values 19 | directory: "/client" # Location of package manifests 20 | schedule: 21 | interval: "weekly" 22 | -------------------------------------------------------------------------------- /.github/workflows/planetoid.yml: -------------------------------------------------------------------------------- 1 | name: Planetoid 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build_client_linux_and_wasm: 14 | name: Build clients Linux and Wasm 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | 20 | - name: Install package dependencies 21 | run: sudo apt-get update && sudo apt-get install -y pkg-config libx11-dev libxi-dev libgl1-mesa-dev libasound2-dev 22 | 23 | - name: Test docker version 24 | run: docker --version 25 | 26 | - name: Build for target x86_64-unknown-linux-gnu 27 | working-directory: ./client 28 | run: cargo build 29 | 30 | - name: Run clippy for target x86_64-unknown-linux-gnu 31 | working-directory: ./client 32 | run: cargo clippy >clippy.output 2>&1 ; cat clippy.output ;! egrep -q "warning|error:" clippy.output 33 | 34 | - name: Run tests 35 | working-directory: ./client 36 | run: cargo test 37 | 38 | - name: Add wasm32-unknown-unknown target 39 | run: rustup target add wasm32-unknown-unknown 40 | 41 | - name: Build for target wasm32-unknown-unknown 42 | working-directory: ./client 43 | run: cargo build --target wasm32-unknown-unknown 44 | 45 | - name: Run clippy for target wasm32-unknown-unknown 46 | working-directory: ./client 47 | run: cargo clippy --target wasm32-unknown-unknown >clippy.output 2>&1 ; cat clippy.output ;! egrep -q "warning|error:" clippy.output 48 | 49 | - name: Prepare produced files 50 | run: | 51 | mkdir -p planetoid-linux-x86_64 planetoid-wasm 52 | cp client/target/debug/planetoid planetoid-linux-x86_64 53 | cp -r client/sounds planetoid-linux-x86_64 54 | cp client/index.html planetoid-wasm 55 | cp client/target/wasm32-unknown-unknown/debug/planetoid.wasm planetoid-wasm 56 | cp -r client/sounds planetoid-wasm 57 | tar zcvvf planetoid-linux-x86_64.tar.gz planetoid-linux-x86_64 58 | tar zcvvf planetoid-wasm.tar.gz planetoid-wasm 59 | 60 | - name: 'Upload planetoid-linux-x86_64.tar.gz' 61 | uses: actions/upload-artifact@v2 62 | with: 63 | name: planetoid-linux-x86_64.tar.gz 64 | path: planetoid-linux-x86_64.tar.gz 65 | retention-days: 1 66 | 67 | - name: 'Upload planetoid-wasm.tar.gz' 68 | uses: actions/upload-artifact@v2 69 | with: 70 | name: planetoid-wasm.tar.gz 71 | path: planetoid-wasm.tar.gz 72 | retention-days: 1 73 | 74 | - name: 'Login to Docker registry' 75 | env: 76 | registry_password: ${{ secrets.DOCKER_HUB_PASSWORD }} 77 | run: echo "$registry_password" | docker login -u uggla --password-stdin 78 | if: github.ref == 'refs/heads/main' 79 | 80 | - name: 'Build Docker image' 81 | working-directory: ./client 82 | run: docker build -t planetoid . 83 | if: github.ref == 'refs/heads/main' 84 | 85 | - name: 'Tag Docker image' 86 | working-directory: ./client 87 | run: docker tag planetoid:latest uggla/planetoid:latest 88 | if: github.ref == 'refs/heads/main' 89 | 90 | - name: 'Push Docker image to registry' 91 | run: docker push uggla/planetoid 92 | if: github.ref == 'refs/heads/main' 93 | 94 | - name: 'Logout and clean credentials' 95 | run: docker logout && rm -f /home/runner/.docker/config.json 96 | if: github.ref == 'refs/heads/main' 97 | 98 | build_client_macos: 99 | name: Build clients MacOS 100 | runs-on: macos-latest 101 | 102 | steps: 103 | - uses: actions/checkout@v2 104 | 105 | - name: Build for target x86_64-apple-darwin 106 | working-directory: ./client 107 | run: cargo build 108 | 109 | - name: Run tests 110 | working-directory: ./client 111 | run: cargo test 112 | 113 | - name: Prepare produced files 114 | run: | 115 | mkdir -p planetoid-macos-x86_64 116 | cp client/target/debug/planetoid planetoid-macos-x86_64 117 | cp -r client/sounds planetoid-macos-x86_64 118 | tar zcvvf planetoid-macos-x86_64.tar.gz planetoid-macos-x86_64 119 | 120 | - name: 'Upload planetoid-macos-x86_64.tar.gz' 121 | uses: actions/upload-artifact@v2 122 | with: 123 | name: planetoid-macos-x86_64.tar.gz 124 | path: planetoid-macos-x86_64.tar.gz 125 | retention-days: 1 126 | 127 | 128 | build_client_windows: 129 | name: Build client windows 130 | runs-on: windows-latest 131 | 132 | steps: 133 | - uses: actions/checkout@v2 134 | 135 | - name: Build for target x86_64-pc-windows-msvc 136 | working-directory: ./client 137 | run: cargo build 138 | 139 | - name: Run tests 140 | working-directory: ./client 141 | run: cargo test 142 | 143 | - name: Prepare produced files 144 | run: | 145 | new-item -Name planetoid-windows -ItemType directory 146 | Copy-Item -Path "client\target\debug\planetoid.exe" -Destination "planetoid-windows" 147 | Copy-Item -Path "client\sounds" -Destination "planetoid-windows" -Recurse 148 | Compress-Archive -Path planetoid-windows -DestinationPath planetoid-windows.zip 149 | 150 | - name: 'Upload planetoid-windows.zip' 151 | uses: actions/upload-artifact@v2 152 | with: 153 | name: planetoid-windows.zip 154 | path: planetoid-windows.zip 155 | retention-days: 1 156 | 157 | 158 | build_maven: 159 | name: Build server and worker 160 | runs-on: ubuntu-latest 161 | 162 | steps: 163 | - uses: actions/checkout@v2 164 | 165 | - name: Set up JDK 11 166 | uses: actions/setup-java@v2 167 | with: 168 | java-version: '11' 169 | distribution: 'adopt' 170 | 171 | - name: Build server with Maven 172 | working-directory: ./server 173 | run: mvn package -Dquarkus.package.type=uber-jar 174 | 175 | - name: Build worker with Maven 176 | working-directory: ./worker 177 | run: mvn package -Dquarkus.package.type=uber-jar 178 | 179 | - name: Prepare produced files 180 | run: | 181 | mkdir -p planetoid-server planetoid-worker 182 | cp server/target/planetoid-server-1.0.0-SNAPSHOT-runner.jar planetoid-server 183 | cp worker/target/planetoid-worker-1.0.0-SNAPSHOT-runner.jar planetoid-worker 184 | tar zcvvf planetoid-server.tar.gz planetoid-server 185 | tar zcvvf planetoid-worker.tar.gz planetoid-worker 186 | 187 | - name: 'Upload planetoid-server.tar.gz' 188 | uses: actions/upload-artifact@v2 189 | with: 190 | name: planetoid-server.tar.gz 191 | path: planetoid-server.tar.gz 192 | retention-days: 1 193 | 194 | - name: 'Upload planetoid-worker.tar.gz' 195 | uses: actions/upload-artifact@v2 196 | with: 197 | name: planetoid-worker.tar.gz 198 | path: planetoid-worker.tar.gz 199 | retention-days: 1 200 | 201 | 202 | create_github_release: 203 | name: Create Github release 204 | runs-on: ubuntu-latest 205 | if: github.ref == 'refs/heads/main' 206 | needs: [build_client_linux_and_wasm, build_client_windows, build_client_macos, build_maven] 207 | 208 | steps: 209 | - uses: actions/checkout@v2 210 | 211 | - name: Download all workflow run artifacts 212 | uses: actions/download-artifact@v2 213 | 214 | - uses: "marvinpinto/action-automatic-releases@latest" 215 | name: Create a Github release 216 | with: 217 | repo_token: "${{ secrets.GITHUB_TOKEN }}" 218 | automatic_release_tag: latest 219 | title: Planetoid 220 | files: | 221 | planetoid-server.tar.gz 222 | planetoid-worker.tar.gz 223 | planetoid-windows.zip 224 | planetoid-linux-x86_64.tar.gz 225 | planetoid-macos-x86_64.tar.gz 226 | planetoid-wasm.tar.gz 227 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 8 | #Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # MSVC Windows builds of rustc generate these, which store debugging information 14 | *.pdb 15 | 16 | # Idea 17 | .idea 18 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | . 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 René Ribaud 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Planetoid 2 | 3 | [![Planetoid](https://github.com/uggla/planetoid/actions/workflows/planetoid.yml/badge.svg)](https://github.com/uggla/planetoid/actions/workflows/planetoid.yml) 4 | 5 | Planetoid is a toy project to demonstrate and learn several technologies. 6 | The goal is to create a little multiplayer [asteriod](https://en.wikipedia.org/wiki/Asteroids_(video_game)) game clone. 7 | * Server-side is composed of 2 parts: 8 | * A server based on a [Quarkus](https://quarkus.io/) application. The goal of this application will be to: 9 | * Show games in progress and terminated with participants and winner. 10 | * Allow users to authenticate and add comments to a specific game. 11 | * Launch workers to allow several games in parallel, each with individual players. 12 | * A worker based on a [Quarkus](https://quarkus.io/) application using websockets derived from the chat example. The goal of this application is currently to: 13 | * Pass game messages between clients. 14 | * Client-side is a [Rust](https://www.rust-lang.org/) application using [macroquad](https://github.com/not-fl3/macroquad) framework. It was also derived from the asteroid example but refactored in a more object-oriented code. It can be compiled as: 15 | * A native application that will use websockets ([tungstenite](https://github.com/snapview/tungstenite-rs)) to share game data. Only Linux has been fully tested so far, but it should run on Windows/MacOs as well. 16 | * A wasm32 application that can be run in a browser. Currently, websockets are not implemented, but the game can be played in solo mode. 17 | * Deployment on [Kubernetes](https://kubernetes.io/) for the server and the required infrastructure to capture metrics ([Prometheus](https://prometheus.io/) / [Grafana](https://grafana.com/)) as well as authentication ([Keycloak](https://www.keycloak.org/)) and persistance ([Postgres](https://www.postgresql.org/)). 18 | 19 | 20 | This project is in an early stage, so many features are missing and need to be implemented. However, as stated initially, the goal is not to propose a real game but a demo to explain and share these technologies. 21 | 22 | 23 | ## Targeted infra overview 24 | ![infra](images/infra.png) 25 | 26 | ## Project current status 27 | * Clients (native and wasm) can be built and run. Wasm can only run solo mode. 28 | * Worker allows playing a multiplayer game: 29 | * Native client can share the game with a spectator. A spectator is another native client started in the spectator mode. 30 | * Multiplayer game. A native client can be run as host, and several guests can connect to destroy asteroids together. 31 | * Server is a WIP. It is currently just exposing two tables with hibernate/panache and a couple of API routes. 32 | 33 | 34 | ## Authors 35 | 36 | - [@Uggla](https://www.github.com/Uggla) 37 | 38 | ## Game controls 39 | * `Right` and `left` arrow keys to turn the ship right and left. 40 | * `Space` key to shoot. 41 | * `F` key to display fps. 42 | * `Esc` key to quit the game. 43 | 44 | ## Demo 45 | An online demo can be played [here](https://planetoid.uggla.fr). 46 | 47 | *Note:* 48 | * *only solo mode is available online.* 49 | * *loading the game can take time.* 50 | 51 | ## Screenshots 52 | 53 | Native application: 54 | ![App native screenshot](images/planetoid_native.jpg) 55 | 56 | Running the wasm application into Firefox: 57 | ![App wasm32 screenshot](images/planetoid_wasm32.jpg) 58 | 59 | Multiplayer game: 60 | ![multiplayer game screenshot](images/multiplayer_game.jpg) 61 | 62 | 63 | ## Binaries 64 | Binaries are available here: 65 | [Binary releases](https://github.com/uggla/planetoid/releases) 66 | 67 | ## Run Locally (mainly for development purposes) 68 | 69 | 1. Clone the project 70 | 71 | ```bash 72 | git clone https://github.com/uggla/planetoid 73 | ``` 74 | 75 | 2. Go to the project directory 76 | 77 | ```bash 78 | cd planetoid 79 | ``` 80 | 81 | ### Worker 82 | 83 | 1. Install OpenJDK 11 following the instructions [here](https://adoptopenjdk.net/installation.html#) or install it using your distribution package manager. 84 | Ex on Fedora 85 | 86 | ```bash 87 | dnf install java-11-openjdk-devel 88 | ``` 89 | 90 | 2. Install maven > 3.6 following the instructions [here](https://maven.apache.org/install.html) or install it using your distribution package manager. Ex on Fedora: 91 | 92 | ```bash 93 | dnf install maven 94 | ``` 95 | 96 | 3. Go to the worker directory and run the worker in dev mode 97 | 98 | ```bash 99 | cd worker 100 | mvn compile quarkus:dev 101 | ``` 102 | *Note: Maven will download a lot of dependencies from the internet* 103 | 104 | ### Client 105 | 106 | #### Native client 107 | 1. Install Rust following the instructions [here](https://www.rust-lang.org/fr/learn/get-started). 108 | 109 | *Tips: the rustup method is the simplest one.* 110 | 111 | 2. Install required library for macroquad 112 | 113 | * Ubuntu system dependencies 114 | ```bash 115 | apt install pkg-config libx11-dev libxi-dev libgl1-mesa-dev libasound2-dev 116 | ``` 117 | 118 | * Fedora system dependencies 119 | ```bash 120 | dnf install libX11-devel libXi-devel mesa-libGL-devel alsa-lib-devel 121 | ``` 122 | 123 | * Windows system 124 | ``` 125 | No dependencies are required for Windows or MacOS 126 | ``` 127 | 128 | 3. Go to the client directory and run the native client 129 | ```bash 130 | cd client 131 | cargo run 132 | ``` 133 | 134 | #### Wasm32 client 135 | 136 | 1. Follow the above instruction of the native client. 137 | 138 | 2. Install basic-http-server 139 | ```bash 140 | cargo install basic-http-server 141 | ``` 142 | 143 | 3. Add the wasm32 compilation target 144 | ```bash 145 | rustup target add wasm32-unknown-unknown 146 | ``` 147 | 148 | 4. Go to the client directory and run the native client 149 | ```bash 150 | cd client 151 | cargo build --target wasm32-unknown-unknown 152 | ``` 153 | 154 | 5. Serve the files and open the browser 155 | ```bash 156 | basic-http-server 157 | xdg-open http://127.0.0.1:4000 158 | ``` 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | ## Native client usage 171 | ``` 172 | Planetoid 0.1.0 173 | Planetoid is an asteroid clone. 174 | 175 | USAGE: 176 | planetoid [FLAGS] [OPTIONS] 177 | 178 | FLAGS: 179 | -d, --debug Debug mode (_ (error), -d (info), -dd (debug), -ddd (trace)) 180 | -g, --god God mode 181 | --help Prints help information 182 | -s, --solo Solo mode, do not connect to network 183 | -V, --version Prints version information 184 | 185 | OPTIONS: 186 | -h, --host Host [default: localhost] 187 | -m, --mode Network mode [default: host] [possible values: host, guest, spectator] 188 | -n, --name Player name [default: planetoid] 189 | -p, --port Port [default: 8080] 190 | ``` 191 | 192 | ### Examples 193 | #### Running in solo mode 194 | `cargo run -- -s` 195 | 196 | #### Running in network mode with a spectator 197 | On the first terminal: 198 | `cargo run -- -m host -n Planetoid` 199 | 200 | On the second terminal: 201 | `cargo run -- -m spectator -n "Planetoid spectator"` 202 | 203 | #### Running in network mode, debug and as god 204 | `-dd`: debug, allows to see messages sent to the web socket. 205 | 206 | `-g`: god mode, player ship cannot be destroyed. 207 | 208 | `-n`: player name (default: planetoid) 209 | 210 | `cargo run -- -m host -dd -g -n Planetoid` 211 | 212 | #### Running in network mode with host and guest 213 | On the first terminal: 214 | `cargo run -- -m host -n Planetoid` 215 | 216 | On the second terminal: 217 | `cargo run -- -m guest -n "Planetoid guest"` 218 | -------------------------------------------------------------------------------- /client/.gitattributes: -------------------------------------------------------------------------------- 1 | *.wav binary 2 | *.webp binary 3 | *.ttf binary 4 | -------------------------------------------------------------------------------- /client/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "planetoid" 3 | version = "0.1.0" 4 | authors = ["Uggla "] 5 | edition = "2021" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | macroquad = "0.3.15" 11 | url = '2.2.2' 12 | serde = {version = "1.0.136", features = ["derive"]} 13 | serde_json = "1.0.79" 14 | structopt = "0.3.26" 15 | log = "0.4.16" 16 | 17 | [dependencies.simple_logger] 18 | version = "2.1.0" 19 | # default-features = false 20 | # features = ["timestamps_utc","colors","stderr"] 21 | 22 | [target.'cfg(not(target_arch = "wasm32"))'.dependencies] 23 | tungstenite = '0.17.2' 24 | -------------------------------------------------------------------------------- /client/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx 2 | LABEL org.opencontainers.image.authors="Uggla@free.fr" 3 | COPY planetoid.wasm /usr/share/nginx/html 4 | COPY index.html /usr/share/nginx/html 5 | COPY sounds /usr/share/nginx/html/sounds 6 | COPY images /usr/share/nginx/html/images 7 | COPY fonts /usr/share/nginx/html/fonts 8 | RUN sed -i '/application\/zip/a \ application/wasm wasm;' /etc/nginx/mime.types 9 | -------------------------------------------------------------------------------- /client/fonts/BebasNeue-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/client/fonts/BebasNeue-Regular.ttf -------------------------------------------------------------------------------- /client/fonts/OFL.txt: -------------------------------------------------------------------------------- 1 | Copyright © 2010 by Dharma Type. 2 | 3 | This Font Software is licensed under the SIL Open Font License, Version 1.1. 4 | This license is copied below, and is also available with a FAQ at: 5 | http://scripts.sil.org/OFL 6 | 7 | 8 | ----------------------------------------------------------- 9 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 10 | ----------------------------------------------------------- 11 | 12 | PREAMBLE 13 | The goals of the Open Font License (OFL) are to stimulate worldwide 14 | development of collaborative font projects, to support the font creation 15 | efforts of academic and linguistic communities, and to provide a free and 16 | open framework in which fonts may be shared and improved in partnership 17 | with others. 18 | 19 | The OFL allows the licensed fonts to be used, studied, modified and 20 | redistributed freely as long as they are not sold by themselves. The 21 | fonts, including any derivative works, can be bundled, embedded, 22 | redistributed and/or sold with any software provided that any reserved 23 | names are not used by derivative works. The fonts and derivatives, 24 | however, cannot be released under any other type of license. The 25 | requirement for fonts to remain under this license does not apply 26 | to any document created using the fonts or their derivatives. 27 | 28 | DEFINITIONS 29 | "Font Software" refers to the set of files released by the Copyright 30 | Holder(s) under this license and clearly marked as such. This may 31 | include source files, build scripts and documentation. 32 | 33 | "Reserved Font Name" refers to any names specified as such after the 34 | copyright statement(s). 35 | 36 | "Original Version" refers to the collection of Font Software components as 37 | distributed by the Copyright Holder(s). 38 | 39 | "Modified Version" refers to any derivative made by adding to, deleting, 40 | or substituting -- in part or in whole -- any of the components of the 41 | Original Version, by changing formats or by porting the Font Software to a 42 | new environment. 43 | 44 | "Author" refers to any designer, engineer, programmer, technical 45 | writer or other person who contributed to the Font Software. 46 | 47 | PERMISSION & CONDITIONS 48 | Permission is hereby granted, free of charge, to any person obtaining 49 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 50 | redistribute, and sell modified and unmodified copies of the Font 51 | Software, subject to the following conditions: 52 | 53 | 1) Neither the Font Software nor any of its individual components, 54 | in Original or Modified Versions, may be sold by itself. 55 | 56 | 2) Original or Modified Versions of the Font Software may be bundled, 57 | redistributed and/or sold with any software, provided that each copy 58 | contains the above copyright notice and this license. These can be 59 | included either as stand-alone text files, human-readable headers or 60 | in the appropriate machine-readable metadata fields within text or 61 | binary files as long as those fields can be easily viewed by the user. 62 | 63 | 3) No Modified Version of the Font Software may use the Reserved Font 64 | Name(s) unless explicit written permission is granted by the corresponding 65 | Copyright Holder. This restriction only applies to the primary font name as 66 | presented to the users. 67 | 68 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 69 | Software shall not be used to promote, endorse or advertise any 70 | Modified Version, except to acknowledge the contribution(s) of the 71 | Copyright Holder(s) and the Author(s) or with their explicit written 72 | permission. 73 | 74 | 5) The Font Software, modified or unmodified, in part or in whole, 75 | must be distributed entirely under this license, and must not be 76 | distributed under any other license. The requirement for fonts to 77 | remain under this license does not apply to any document created 78 | using the Font Software. 79 | 80 | TERMINATION 81 | This license becomes null and void if any of the above conditions are 82 | not met. 83 | 84 | DISCLAIMER 85 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 86 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 87 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 88 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 89 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 90 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 91 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 92 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 93 | OTHER DEALINGS IN THE FONT SOFTWARE. 94 | -------------------------------------------------------------------------------- /client/images/space.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/client/images/space.webp -------------------------------------------------------------------------------- /client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Planetoid 6 | 43 | 44 | 45 | 46 |

Planetoid

47 |
48 |

Control

49 |
    50 |
  • Right and left arrow keys to turn the ship right and left.
  • 51 |
  • Space key to shoot.
  • 52 |
  • F key to display fps.
  • 53 |
54 |
55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /client/planetoid.wasm: -------------------------------------------------------------------------------- 1 | target/wasm32-unknown-unknown/debug/planetoid.wasm -------------------------------------------------------------------------------- /client/sounds/explosion.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/client/sounds/explosion.wav -------------------------------------------------------------------------------- /client/sounds/laser.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/client/sounds/laser.wav -------------------------------------------------------------------------------- /client/sounds/thrust.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/client/sounds/thrust.wav -------------------------------------------------------------------------------- /client/sounds/victory.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/client/sounds/victory.wav -------------------------------------------------------------------------------- /client/src/asteroid.rs: -------------------------------------------------------------------------------- 1 | use crate::collision::Collided; 2 | use crate::screen; 3 | use macroquad::prelude::*; 4 | use serde::de::{self, Deserializer, MapAccess, Visitor}; 5 | use serde::ser::{SerializeStruct, Serializer}; 6 | use serde::{Deserialize, Serialize}; 7 | use std::cmp::Ordering; 8 | use std::collections::BTreeMap; 9 | use std::fmt; 10 | 11 | #[derive(Serialize, Deserialize, Clone, Debug)] 12 | pub struct Asteroids { 13 | count: usize, 14 | asteroids: BTreeMap, 15 | } 16 | 17 | impl Asteroids { 18 | pub fn generate_field(name: String, number: usize) -> Self { 19 | let mut asteroids = BTreeMap::new(); 20 | for item in 0..number { 21 | let asteroid = Asteroid::new(); 22 | asteroids.insert(format!("{}_{:06}", name, item), asteroid); 23 | } 24 | 25 | Self { 26 | count: number, 27 | asteroids, 28 | } 29 | } 30 | 31 | pub fn add_asteroid(&mut self, name: String, asteroid: Asteroid) { 32 | self.asteroids 33 | .insert(format!("{}_{:06}", name, self.count), asteroid); 34 | self.count += 1; 35 | } 36 | 37 | #[cfg(not(target_arch = "wasm32"))] 38 | pub fn refresh_last_updated(&mut self, last_updated: f64) { 39 | for asteroid in self.asteroids.values_mut() { 40 | asteroid.set_last_updated(last_updated); 41 | } 42 | } 43 | 44 | pub fn get_asteroids(&mut self) -> &mut BTreeMap { 45 | &mut self.asteroids 46 | } 47 | 48 | pub fn is_empty(&self) -> bool { 49 | self.asteroids.is_empty() 50 | } 51 | } 52 | 53 | #[cfg(not(target_arch = "wasm32"))] 54 | pub fn synchronize_asteroids(field1: &mut Asteroids, field2: Asteroids) { 55 | for (key_field2, value_field2) in &field2.asteroids { 56 | match field1.asteroids.get(key_field2) { 57 | None => { 58 | field1 59 | .asteroids 60 | .insert(key_field2.clone(), value_field2.clone()); 61 | field1.count += 1; 62 | } 63 | 64 | Some(value_field1) => { 65 | if !value_field1.collided 66 | && value_field2.last_updated() > value_field1.last_updated() 67 | { 68 | *field1.asteroids.get_mut(key_field2).unwrap() = value_field2.clone(); 69 | } 70 | } 71 | } 72 | } 73 | } 74 | 75 | #[derive(Debug)] 76 | pub struct Asteroid { 77 | pos: Vec2, 78 | vel: Vec2, 79 | rot: f32, 80 | rot_speed: f32, 81 | size: f32, 82 | sides: u8, 83 | collided: bool, 84 | last_updated: f64, 85 | } 86 | 87 | impl Asteroid { 88 | pub fn new() -> Self { 89 | Self { 90 | pos: screen::center() 91 | + Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.)).normalize() 92 | * screen_width().min(screen_height()) 93 | / 2., 94 | vel: Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.)), 95 | rot: 0., 96 | rot_speed: rand::gen_range(-2., 2.), 97 | size: screen_width().min(screen_height()) / 10., 98 | sides: 8, 99 | collided: false, 100 | last_updated: 0., 101 | } 102 | } 103 | 104 | #[allow(dead_code)] 105 | pub fn new_pos_and_size(x: f32, y: f32, size: f32) -> Self { 106 | Self { 107 | pos: Vec2::new(x, y), 108 | vel: Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.)), 109 | rot: 0., 110 | rot_speed: rand::gen_range(-2., 2.), 111 | size, 112 | sides: 8, 113 | collided: false, 114 | last_updated: 0., 115 | } 116 | } 117 | 118 | pub fn new_split( 119 | pos: Vec2, 120 | velx: f32, 121 | vely: f32, 122 | size: f32, 123 | sides: u8, 124 | last_updated: f64, 125 | ) -> Vec { 126 | let mut new_asteroids = Vec::new(); 127 | 128 | let asteroid1 = Self { 129 | pos, 130 | vel: Vec2::new(vely, -velx).normalize() * rand::gen_range(1., 3.), 131 | rot: rand::gen_range(0., 360.), 132 | rot_speed: rand::gen_range(-2., 2.), 133 | size: size * 0.8, 134 | sides: sides - 1, 135 | collided: false, 136 | last_updated, 137 | }; 138 | 139 | let asteroid2 = Self { 140 | pos, 141 | vel: Vec2::new(-vely, velx).normalize(), 142 | rot: rand::gen_range(0., 360.), 143 | rot_speed: rand::gen_range(-2., 2.), 144 | size: size * 0.8, 145 | sides: sides - 1, 146 | collided: false, 147 | last_updated, 148 | }; 149 | 150 | new_asteroids.push(asteroid1); 151 | new_asteroids.push(asteroid2); 152 | new_asteroids 153 | } 154 | 155 | pub fn update_pos(&mut self) { 156 | self.pos += self.vel; 157 | self.pos = screen::wrap_around(&self.pos); 158 | self.rot += self.rot_speed; 159 | } 160 | 161 | pub fn draw(&self) { 162 | draw_poly_lines( 163 | self.pos.x, self.pos.y, self.sides, self.size, self.rot, 2., BLACK, 164 | ) 165 | } 166 | 167 | pub fn sides(&self) -> u8 { 168 | self.sides 169 | } 170 | 171 | pub fn collided(&self) -> bool { 172 | self.collided 173 | } 174 | 175 | pub fn set_collided(&mut self, collided: bool) { 176 | self.collided = collided; 177 | } 178 | 179 | pub fn last_updated(&self) -> f64 { 180 | self.last_updated 181 | } 182 | 183 | pub fn set_last_updated(&mut self, last_updated: f64) { 184 | self.last_updated = last_updated; 185 | } 186 | } 187 | 188 | impl Collided for Asteroid { 189 | fn pos(&self) -> Vec2 { 190 | self.pos 191 | } 192 | 193 | fn size(&self) -> f32 { 194 | self.size 195 | } 196 | } 197 | 198 | impl Serialize for Asteroid { 199 | fn serialize(&self, serializer: S) -> Result 200 | where 201 | S: Serializer, 202 | { 203 | let mut state = serializer.serialize_struct("Asteroid", 8)?; 204 | state.serialize_field("pos", &vec![&self.pos[0], &self.pos[1]])?; 205 | state.serialize_field("vel", &vec![&self.vel[0], &self.vel[1]])?; 206 | state.serialize_field("rot", &self.rot)?; 207 | state.serialize_field("rot_speed", &self.rot_speed)?; 208 | state.serialize_field("size", &self.size)?; 209 | state.serialize_field("sides", &self.sides)?; 210 | state.serialize_field("collided", &self.collided)?; 211 | state.serialize_field("last_updated", &self.last_updated)?; 212 | state.end() 213 | } 214 | } 215 | 216 | impl<'de> Deserialize<'de> for Asteroid { 217 | fn deserialize(deserializer: D) -> Result 218 | where 219 | D: Deserializer<'de>, 220 | { 221 | enum Field { 222 | Pos, 223 | Vel, 224 | Rot, 225 | RotSpeed, 226 | Size, 227 | Sides, 228 | Collided, 229 | LastUpdated, 230 | } 231 | 232 | impl<'de> Deserialize<'de> for Field { 233 | fn deserialize(deserializer: D) -> Result 234 | where 235 | D: Deserializer<'de>, 236 | { 237 | struct FieldVisitor; 238 | 239 | impl<'de> Visitor<'de> for FieldVisitor { 240 | type Value = Field; 241 | 242 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 243 | formatter.write_str( 244 | "`pos`, `vel`, `rot`, `rot_speed`, `size`, `sides`, `collided` or `last_updated`", 245 | ) 246 | } 247 | 248 | fn visit_str(self, value: &str) -> Result 249 | where 250 | E: de::Error, 251 | { 252 | match value { 253 | "pos" => Ok(Field::Pos), 254 | "vel" => Ok(Field::Vel), 255 | "rot" => Ok(Field::Rot), 256 | "rot_speed" => Ok(Field::RotSpeed), 257 | "size" => Ok(Field::Size), 258 | "sides" => Ok(Field::Sides), 259 | "collided" => Ok(Field::Collided), 260 | "last_updated" => Ok(Field::LastUpdated), 261 | _ => Err(de::Error::unknown_field(value, FIELDS)), 262 | } 263 | } 264 | } 265 | 266 | deserializer.deserialize_identifier(FieldVisitor) 267 | } 268 | } 269 | 270 | struct AsteroidVisitor; 271 | 272 | impl<'de> Visitor<'de> for AsteroidVisitor { 273 | type Value = Asteroid; 274 | 275 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 276 | formatter.write_str("struct Asteroid") 277 | } 278 | 279 | fn visit_map(self, mut map: V) -> Result 280 | where 281 | V: MapAccess<'de>, 282 | { 283 | let mut pos: Option> = None; 284 | let mut vel: Option> = None; 285 | let mut rot = None; 286 | let mut rot_speed = None; 287 | let mut size = None; 288 | let mut sides = None; 289 | let mut collided = None; 290 | let mut last_updated = None; 291 | while let Some(key) = map.next_key()? { 292 | match key { 293 | Field::Pos => { 294 | if pos.is_some() { 295 | return Err(de::Error::duplicate_field("pos")); 296 | } 297 | pos = Some(map.next_value()?); 298 | } 299 | Field::Vel => { 300 | if vel.is_some() { 301 | return Err(de::Error::duplicate_field("vel")); 302 | } 303 | vel = Some(map.next_value()?); 304 | } 305 | Field::Rot => { 306 | if rot.is_some() { 307 | return Err(de::Error::duplicate_field("rot")); 308 | } 309 | rot = Some(map.next_value()?); 310 | } 311 | Field::RotSpeed => { 312 | if rot_speed.is_some() { 313 | return Err(de::Error::duplicate_field("rot_speed")); 314 | } 315 | rot_speed = Some(map.next_value()?); 316 | } 317 | Field::Size => { 318 | if size.is_some() { 319 | return Err(de::Error::duplicate_field("size")); 320 | } 321 | size = Some(map.next_value()?); 322 | } 323 | Field::Sides => { 324 | if sides.is_some() { 325 | return Err(de::Error::duplicate_field("sides")); 326 | } 327 | sides = Some(map.next_value()?); 328 | } 329 | Field::Collided => { 330 | if collided.is_some() { 331 | return Err(de::Error::duplicate_field("collided")); 332 | } 333 | collided = Some(map.next_value()?); 334 | } 335 | Field::LastUpdated => { 336 | if last_updated.is_some() { 337 | return Err(de::Error::duplicate_field("last_updated")); 338 | } 339 | last_updated = Some(map.next_value()?); 340 | } 341 | } 342 | } 343 | let pos = pos.ok_or_else(|| de::Error::missing_field("pos"))?; 344 | let vel = vel.ok_or_else(|| de::Error::missing_field("vel"))?; 345 | let rot = rot.ok_or_else(|| de::Error::missing_field("rot"))?; 346 | let rot_speed = rot_speed.ok_or_else(|| de::Error::missing_field("rot_speed"))?; 347 | let size = size.ok_or_else(|| de::Error::missing_field("size"))?; 348 | let sides = sides.ok_or_else(|| de::Error::missing_field("sides"))?; 349 | let collided = collided.ok_or_else(|| de::Error::missing_field("collided"))?; 350 | let last_updated = 351 | last_updated.ok_or_else(|| de::Error::missing_field("last_updated"))?; 352 | Ok(Asteroid { 353 | pos: Vec2::new(pos[0], pos[1]), 354 | vel: Vec2::new(vel[0], vel[1]), 355 | rot, 356 | rot_speed, 357 | size, 358 | sides, 359 | collided, 360 | last_updated, 361 | }) 362 | } 363 | } 364 | 365 | const FIELDS: &[&str] = &[ 366 | "pos", 367 | "vel", 368 | "rot", 369 | "rot_speed", 370 | "size", 371 | "sides", 372 | "collided", 373 | "last_updated", 374 | ]; 375 | deserializer.deserialize_struct("Asteroid", FIELDS, AsteroidVisitor) 376 | } 377 | } 378 | 379 | impl Clone for Asteroid { 380 | fn clone(&self) -> Self { 381 | Self { 382 | pos: self.pos, 383 | vel: self.vel, 384 | rot: self.rot, 385 | rot_speed: self.rot_speed, 386 | size: self.size, 387 | sides: self.sides, 388 | collided: self.collided, 389 | last_updated: self.last_updated, 390 | } 391 | } 392 | } 393 | 394 | impl PartialOrd for Asteroid { 395 | fn partial_cmp(&self, other: &Self) -> Option { 396 | self.last_updated.partial_cmp(&other.last_updated) 397 | } 398 | } 399 | 400 | impl PartialEq for Asteroid { 401 | fn eq(&self, other: &Self) -> bool { 402 | self.last_updated == other.last_updated 403 | } 404 | } 405 | 406 | #[cfg(test)] 407 | mod tests { 408 | use std::time::SystemTime; 409 | 410 | use super::*; 411 | 412 | #[test] 413 | fn asteroid_serialize_deserialize_test() { 414 | let asteroid = Asteroid { 415 | pos: Vec2::new(1., 1.), 416 | vel: Vec2::new(2., 2.), 417 | rot: 1., 418 | rot_speed: 1., 419 | size: 1., 420 | sides: 8, 421 | collided: false, 422 | last_updated: 0., 423 | }; 424 | let serialize = serde_json::to_string(&asteroid).unwrap(); 425 | dbg!(&serialize); 426 | let deserialize: Asteroid = serde_json::from_str(&serialize).unwrap(); 427 | let serialize2 = serde_json::to_string(&deserialize).unwrap(); 428 | dbg!(&serialize2); 429 | assert_eq!(serialize, serialize2); 430 | assert_eq!(asteroid.pos, deserialize.pos); 431 | assert_eq!(asteroid.vel, deserialize.vel); 432 | assert_eq!(asteroid.rot, deserialize.rot); 433 | assert_eq!(asteroid.rot_speed, deserialize.rot_speed); 434 | assert_eq!(asteroid.size, deserialize.size); 435 | assert_eq!(asteroid.sides, deserialize.sides); 436 | assert_eq!(asteroid.collided, deserialize.collided); 437 | assert_eq!(asteroid.last_updated, deserialize.last_updated); 438 | } 439 | 440 | #[test] 441 | fn gen_rand_test() { 442 | // This is not a real test just a snippet to check how the quad-rand crate is working 443 | // If the random generator is feed with the same seed, it gives random numbers, but the 444 | // numbers are the same between 2 runs. 445 | // Using the UNIX_EPOCH as the seed avoid to use the same seed between runs. 446 | rand::srand( 447 | SystemTime::now() 448 | .duration_since(SystemTime::UNIX_EPOCH) 449 | .unwrap() 450 | .as_secs(), 451 | ); 452 | 453 | for _i in 0..10 { 454 | dbg!(rand::rand()); 455 | } 456 | dbg!(rand::rand()); 457 | } 458 | 459 | #[test] 460 | fn compare_asteroid_test() { 461 | let mut asteroid1 = Asteroid::new_pos_and_size(0., 0., 10.); 462 | let mut asteroid2 = Asteroid::new_pos_and_size(0., 0., 10.); 463 | asteroid1.set_last_updated(0.0); 464 | asteroid2.set_last_updated(2.0); 465 | assert!(asteroid1 < asteroid2); 466 | asteroid1.set_last_updated(3.0); 467 | asteroid2.set_last_updated(2.0); 468 | assert!(asteroid1 > asteroid2); 469 | asteroid1.set_last_updated(3.0); 470 | asteroid2.set_last_updated(3.0); 471 | assert!(asteroid1 == asteroid2); 472 | } 473 | 474 | #[test] 475 | fn asteroid_synchronize_asteroid_are_the_same_test() { 476 | let mut asteroid1 = Asteroid::new_pos_and_size(0., 0., 10.); 477 | let mut asteroid2 = Asteroid::new_pos_and_size(0., 0., 10.); 478 | asteroid1.set_last_updated(0.0); 479 | asteroid2.set_last_updated(2.0); 480 | 481 | let asteroids = BTreeMap::new(); 482 | let asteroids_c = asteroids.clone(); 483 | 484 | let mut field1 = Asteroids { 485 | count: 0, 486 | asteroids, 487 | }; 488 | 489 | let mut field2 = Asteroids { 490 | count: 0, 491 | asteroids: asteroids_c, 492 | }; 493 | 494 | field1.add_asteroid("f1".to_string(), asteroid1.clone()); 495 | field1.add_asteroid("f1".to_string(), asteroid2.clone()); 496 | field2.add_asteroid("f1".to_string(), asteroid1.clone()); 497 | field2.add_asteroid("f1".to_string(), asteroid2.clone()); 498 | 499 | synchronize_asteroids(&mut field1, field2); 500 | assert!(field1.asteroids.get("f1_000000").unwrap() == &asteroid1); 501 | assert!(field1.asteroids.get("f1_000001").unwrap() == &asteroid2); 502 | } 503 | 504 | #[test] 505 | fn asteroid_synchronize_new_asteroid_in_field2_test() { 506 | let mut asteroid1 = Asteroid::new_pos_and_size(0., 0., 10.); 507 | let mut asteroid2 = Asteroid::new_pos_and_size(0., 0., 10.); 508 | let asteroid3 = Asteroid::new_pos_and_size(0., 0., 20.); 509 | asteroid1.set_last_updated(0.0); 510 | asteroid2.set_last_updated(2.0); 511 | 512 | let asteroids = BTreeMap::new(); 513 | let asteroids_c = asteroids.clone(); 514 | 515 | let mut field1 = Asteroids { 516 | count: 0, 517 | asteroids, 518 | }; 519 | 520 | let mut field2 = Asteroids { 521 | count: 0, 522 | asteroids: asteroids_c, 523 | }; 524 | 525 | field1.add_asteroid("f1".to_string(), asteroid1.clone()); 526 | field1.add_asteroid("f1".to_string(), asteroid2.clone()); 527 | field2.add_asteroid("f2".to_string(), asteroid1.clone()); 528 | field2.add_asteroid("f2".to_string(), asteroid2.clone()); 529 | field2.add_asteroid("f2".to_string(), asteroid3.clone()); 530 | 531 | synchronize_asteroids(&mut field1, field2); 532 | assert!(field1.asteroids.get("f1_000000").unwrap() == &asteroid1); 533 | assert!(field1.asteroids.get("f1_000001").unwrap() == &asteroid2); 534 | assert!(field1.asteroids.get("f2_000002").unwrap() == &asteroid3); 535 | } 536 | 537 | #[test] 538 | fn asteroid_synchronize_new_asteroid_in_field1_test() { 539 | let mut asteroid1 = Asteroid::new_pos_and_size(0., 0., 10.); 540 | let mut asteroid2 = Asteroid::new_pos_and_size(0., 0., 10.); 541 | let asteroid3 = Asteroid::new_pos_and_size(0., 0., 20.); 542 | asteroid1.set_last_updated(0.0); 543 | asteroid2.set_last_updated(2.0); 544 | 545 | let asteroids = BTreeMap::new(); 546 | let asteroids_c = asteroids.clone(); 547 | 548 | let mut field1 = Asteroids { 549 | count: 0, 550 | asteroids, 551 | }; 552 | 553 | let mut field2 = Asteroids { 554 | count: 0, 555 | asteroids: asteroids_c, 556 | }; 557 | 558 | field1.add_asteroid("f1".to_string(), asteroid1.clone()); 559 | field1.add_asteroid("f1".to_string(), asteroid2.clone()); 560 | field2.add_asteroid("f1".to_string(), asteroid1.clone()); 561 | field2.add_asteroid("f1".to_string(), asteroid2.clone()); 562 | field2.add_asteroid("f1".to_string(), asteroid3.clone()); 563 | 564 | synchronize_asteroids(&mut field1, field2); 565 | assert!(field1.asteroids.get("f1_000000").unwrap() == &asteroid1); 566 | assert!(field1.asteroids.get("f1_000001").unwrap() == &asteroid2); 567 | assert!(field1.asteroids.get("f1_000002").unwrap() == &asteroid3); 568 | } 569 | 570 | #[test] 571 | fn asteroid_synchronize_asteroid_updated_in_field2_test() { 572 | let mut asteroid1 = Asteroid::new_pos_and_size(0., 0., 10.); 573 | let mut asteroid2 = Asteroid::new_pos_and_size(0., 0., 10.); 574 | let mut asteroid3 = Asteroid::new_pos_and_size(0., 0., 10.); 575 | asteroid1.set_last_updated(0.0); 576 | asteroid2.set_last_updated(2.0); 577 | asteroid3.set_last_updated(50.0); 578 | 579 | let asteroids = BTreeMap::new(); 580 | let asteroids_c = asteroids.clone(); 581 | 582 | let mut field1 = Asteroids { 583 | count: 0, 584 | asteroids, 585 | }; 586 | 587 | let mut field2 = Asteroids { 588 | count: 0, 589 | asteroids: asteroids_c, 590 | }; 591 | 592 | field1.add_asteroid("f1".to_string(), asteroid1.clone()); 593 | field1.add_asteroid("f1".to_string(), asteroid2.clone()); 594 | field2.add_asteroid("f1".to_string(), asteroid1.clone()); 595 | field2.add_asteroid("f1".to_string(), asteroid3.clone()); 596 | 597 | synchronize_asteroids(&mut field1, field2); 598 | assert!(field1.asteroids.get("f1_000000").unwrap() == &asteroid1); 599 | assert!(field1.asteroids.get("f1_000001").unwrap() == &asteroid3); 600 | } 601 | 602 | #[test] 603 | fn asteroid_synchronize_asteroid_not_updated_in_field2_test() { 604 | let mut asteroid1 = Asteroid::new_pos_and_size(0., 0., 10.); 605 | let mut asteroid2 = Asteroid::new_pos_and_size(0., 0., 10.); 606 | let mut asteroid3 = Asteroid::new_pos_and_size(0., 0., 10.); 607 | asteroid1.set_last_updated(0.0); 608 | asteroid2.set_last_updated(60.0); 609 | asteroid3.set_last_updated(50.0); 610 | 611 | let asteroids = BTreeMap::new(); 612 | let asteroids_c = asteroids.clone(); 613 | 614 | let mut field1 = Asteroids { 615 | count: 0, 616 | asteroids, 617 | }; 618 | 619 | let mut field2 = Asteroids { 620 | count: 0, 621 | asteroids: asteroids_c, 622 | }; 623 | 624 | field1.add_asteroid("f1".to_string(), asteroid1.clone()); 625 | field1.add_asteroid("f1".to_string(), asteroid2.clone()); 626 | field2.add_asteroid("f1".to_string(), asteroid1.clone()); 627 | field2.add_asteroid("f1".to_string(), asteroid3.clone()); 628 | 629 | synchronize_asteroids(&mut field1, field2); 630 | assert!(field1.asteroids.get("f1_000000").unwrap() == &asteroid1); 631 | assert!(field1.asteroids.get("f1_000001").unwrap() == &asteroid2); 632 | } 633 | 634 | #[test] 635 | fn asteroid_refresh_last_updated_test() { 636 | let asteroid1 = Asteroid::new_pos_and_size(0., 0., 10.); 637 | let asteroid2 = Asteroid::new_pos_and_size(0., 0., 10.); 638 | let asteroid3 = Asteroid::new_pos_and_size(0., 0., 10.); 639 | 640 | let asteroids = BTreeMap::new(); 641 | 642 | let mut field = Asteroids { 643 | count: 0, 644 | asteroids, 645 | }; 646 | 647 | field.add_asteroid("f1".to_string(), asteroid1.clone()); 648 | field.add_asteroid("f1".to_string(), asteroid2.clone()); 649 | field.add_asteroid("f1".to_string(), asteroid3.clone()); 650 | 651 | field.refresh_last_updated(10.0); 652 | 653 | assert_eq!( 654 | field.asteroids.get("f1_000000").unwrap().last_updated(), 655 | 10. 656 | ); 657 | assert_eq!( 658 | field.asteroids.get("f1_000001").unwrap().last_updated(), 659 | 10. 660 | ); 661 | assert_eq!( 662 | field.asteroids.get("f1_000002").unwrap().last_updated(), 663 | 10. 664 | ); 665 | } 666 | 667 | #[test] 668 | fn asteroid_synchronize_asteroid_already_collided_test() { 669 | let mut asteroid1 = Asteroid::new_pos_and_size(0., 0., 10.); 670 | let mut asteroid2 = Asteroid::new_pos_and_size(0., 0., 10.); 671 | let mut asteroid3 = Asteroid::new_pos_and_size(0., 0., 10.); 672 | asteroid1.set_last_updated(0.0); 673 | asteroid2.set_last_updated(2.0); 674 | asteroid2.set_collided(true); 675 | asteroid3.set_last_updated(50.0); 676 | 677 | let asteroids = BTreeMap::new(); 678 | let asteroids_c = asteroids.clone(); 679 | 680 | let mut field1 = Asteroids { 681 | count: 0, 682 | asteroids, 683 | }; 684 | 685 | let mut field2 = Asteroids { 686 | count: 0, 687 | asteroids: asteroids_c, 688 | }; 689 | 690 | field1.add_asteroid("f1".to_string(), asteroid1.clone()); 691 | field1.add_asteroid("f1".to_string(), asteroid2.clone()); 692 | field2.add_asteroid("f1".to_string(), asteroid1.clone()); 693 | field2.add_asteroid("f1".to_string(), asteroid3.clone()); 694 | 695 | synchronize_asteroids(&mut field1, field2); 696 | assert!(field1.asteroids.get("f1_000000").unwrap() == &asteroid1); 697 | assert!(field1.asteroids.get("f1_000001").unwrap() == &asteroid2); 698 | } 699 | } 700 | -------------------------------------------------------------------------------- /client/src/bullet.rs: -------------------------------------------------------------------------------- 1 | use crate::collision::Collided; 2 | use macroquad::prelude::*; 3 | use serde::de::{self, Deserializer, MapAccess, Visitor}; 4 | use serde::ser::{SerializeStruct, Serializer}; 5 | use serde::{Deserialize, Serialize}; 6 | use std::fmt; 7 | 8 | #[derive(Debug)] 9 | pub struct Bullet { 10 | pos: Vec2, 11 | vel: Vec2, 12 | shot_at: f64, 13 | size: f32, 14 | collided: bool, 15 | } 16 | 17 | impl Bullet { 18 | pub fn new(pos: Vec2, vel: Vec2, shot_at: f64, collided: bool) -> Self { 19 | Self { 20 | pos, 21 | vel, 22 | shot_at, 23 | collided, 24 | size: 2., 25 | } 26 | } 27 | 28 | pub fn draw(&self) { 29 | draw_circle(self.pos.x, self.pos.y, 2., BLACK); 30 | } 31 | 32 | pub fn update_pos(&mut self) { 33 | self.pos += self.vel; 34 | } 35 | 36 | pub fn shot_at(&self) -> f64 { 37 | self.shot_at 38 | } 39 | 40 | pub fn set_collided(&mut self, collided: bool) { 41 | self.collided = collided; 42 | } 43 | 44 | pub fn collided(&self) -> bool { 45 | self.collided 46 | } 47 | 48 | pub fn vel(&self) -> Vec2 { 49 | self.vel 50 | } 51 | } 52 | 53 | impl Collided for Bullet { 54 | fn pos(&self) -> Vec2 { 55 | self.pos 56 | } 57 | 58 | fn size(&self) -> f32 { 59 | self.size 60 | } 61 | } 62 | 63 | impl Serialize for Bullet { 64 | fn serialize(&self, serializer: S) -> Result 65 | where 66 | S: Serializer, 67 | { 68 | let mut state = serializer.serialize_struct("Bullet", 5)?; 69 | state.serialize_field("pos", &vec![&self.pos[0], &self.pos[1]])?; 70 | state.serialize_field("vel", &vec![&self.vel[0], &self.vel[1]])?; 71 | state.serialize_field("shot_at", &self.shot_at)?; 72 | state.serialize_field("size", &self.size)?; 73 | state.serialize_field("collided", &self.collided)?; 74 | state.end() 75 | } 76 | } 77 | 78 | impl<'de> Deserialize<'de> for Bullet { 79 | fn deserialize(deserializer: D) -> Result 80 | where 81 | D: Deserializer<'de>, 82 | { 83 | enum Field { 84 | Pos, 85 | Vel, 86 | ShotAt, 87 | Size, 88 | Collided, 89 | } 90 | 91 | impl<'de> Deserialize<'de> for Field { 92 | fn deserialize(deserializer: D) -> Result 93 | where 94 | D: Deserializer<'de>, 95 | { 96 | struct FieldVisitor; 97 | 98 | impl<'de> Visitor<'de> for FieldVisitor { 99 | type Value = Field; 100 | 101 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 102 | formatter.write_str("`pos`, `vel`, `shot_at`, `size` or `collided`") 103 | } 104 | 105 | fn visit_str(self, value: &str) -> Result 106 | where 107 | E: de::Error, 108 | { 109 | match value { 110 | "pos" => Ok(Field::Pos), 111 | "vel" => Ok(Field::Vel), 112 | "shot_at" => Ok(Field::ShotAt), 113 | "size" => Ok(Field::Size), 114 | "collided" => Ok(Field::Collided), 115 | _ => Err(de::Error::unknown_field(value, FIELDS)), 116 | } 117 | } 118 | } 119 | 120 | deserializer.deserialize_identifier(FieldVisitor) 121 | } 122 | } 123 | 124 | struct BulletVisitor; 125 | 126 | impl<'de> Visitor<'de> for BulletVisitor { 127 | type Value = Bullet; 128 | 129 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 130 | formatter.write_str("struct Bullet") 131 | } 132 | 133 | fn visit_map(self, mut map: V) -> Result 134 | where 135 | V: MapAccess<'de>, 136 | { 137 | let mut pos: Option> = None; 138 | let mut vel: Option> = None; 139 | let mut shot_at = None; 140 | let mut size = None; 141 | let mut collided = None; 142 | while let Some(key) = map.next_key()? { 143 | match key { 144 | Field::Pos => { 145 | if pos.is_some() { 146 | return Err(de::Error::duplicate_field("pos")); 147 | } 148 | pos = Some(map.next_value()?); 149 | } 150 | Field::Vel => { 151 | if vel.is_some() { 152 | return Err(de::Error::duplicate_field("vel")); 153 | } 154 | vel = Some(map.next_value()?); 155 | } 156 | Field::ShotAt => { 157 | if shot_at.is_some() { 158 | return Err(de::Error::duplicate_field("shot_at")); 159 | } 160 | shot_at = Some(map.next_value()?); 161 | } 162 | Field::Size => { 163 | if size.is_some() { 164 | return Err(de::Error::duplicate_field("size")); 165 | } 166 | size = Some(map.next_value()?); 167 | } 168 | Field::Collided => { 169 | if collided.is_some() { 170 | return Err(de::Error::duplicate_field("collided")); 171 | } 172 | collided = Some(map.next_value()?); 173 | } 174 | } 175 | } 176 | let pos = pos.ok_or_else(|| de::Error::missing_field("pos"))?; 177 | let vel = vel.ok_or_else(|| de::Error::missing_field("vel"))?; 178 | let shot_at = shot_at.ok_or_else(|| de::Error::missing_field("shot_at"))?; 179 | let size = size.ok_or_else(|| de::Error::missing_field("size"))?; 180 | let collided = collided.ok_or_else(|| de::Error::missing_field("collided"))?; 181 | Ok(Bullet { 182 | pos: Vec2::new(pos[0], pos[1]), 183 | vel: Vec2::new(vel[0], vel[1]), 184 | shot_at, 185 | size, 186 | collided, 187 | }) 188 | } 189 | } 190 | 191 | const FIELDS: &[&str] = &["pos", "vel", "shot_at", "size", "collided"]; 192 | deserializer.deserialize_struct("Bullet", FIELDS, BulletVisitor) 193 | } 194 | } 195 | 196 | impl Clone for Bullet { 197 | fn clone(&self) -> Self { 198 | Self { 199 | pos: self.pos, 200 | vel: self.vel, 201 | shot_at: self.shot_at, 202 | size: self.size, 203 | collided: self.collided, 204 | } 205 | } 206 | } 207 | 208 | #[cfg(test)] 209 | mod tests { 210 | use super::*; 211 | 212 | #[test] 213 | fn bullet_serialize_deserialize_test() { 214 | let bullet = Bullet { 215 | pos: Vec2::new(1., 1.), 216 | vel: Vec2::new(2., 2.), 217 | shot_at: 1., 218 | size: 1., 219 | collided: false, 220 | }; 221 | let serialize = serde_json::to_string(&bullet).unwrap(); 222 | dbg!(&serialize); 223 | let deserialize: Bullet = serde_json::from_str(&serialize).unwrap(); 224 | let serialize2 = serde_json::to_string(&deserialize).unwrap(); 225 | dbg!(&serialize2); 226 | assert_eq!(serialize, serialize2); 227 | assert_eq!(bullet.pos, deserialize.pos); 228 | assert_eq!(bullet.vel, deserialize.vel); 229 | assert_eq!(bullet.shot_at, deserialize.shot_at); 230 | assert_eq!(bullet.size, deserialize.size); 231 | assert_eq!(bullet.collided, deserialize.collided); 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /client/src/collision.rs: -------------------------------------------------------------------------------- 1 | use macroquad::prelude::*; 2 | 3 | use crate::{ 4 | asteroid::{Asteroid, Asteroids}, 5 | ship::Ship, 6 | }; 7 | 8 | pub trait Collided { 9 | fn size(&self) -> f32; 10 | fn pos(&self) -> Vec2; 11 | } 12 | 13 | pub fn is_collided(obj1: &A, obj2: &B) -> bool { 14 | (obj1.pos() - obj2.pos()).length() < obj1.size() + obj2.size() 15 | } 16 | 17 | pub fn manage_collisions( 18 | players: &mut [Ship], 19 | asteroids: &mut Asteroids, 20 | name: String, 21 | god: bool, 22 | mode: &str, 23 | frame_t: f64, 24 | sync_t: f64, 25 | ) { 26 | let mut opponents = players.to_vec(); 27 | for ship in players.iter_mut() { 28 | ship_vs_asteroids(ship, asteroids, name.clone(), god, mode, sync_t); 29 | ship_vs_opponents(ship, &mut opponents); 30 | 31 | // Garbage collect bullets every 1.5s (bullets can almost cross the screen). 32 | // This needs to be done only on the local ship as frame_t make sens 33 | // only for the local data 34 | if ship.name() == name { 35 | ship.bullets 36 | .retain(|bullet| bullet.shot_at() + 1.5 > frame_t); 37 | } 38 | 39 | // Garbage collect asteroids collided every 200ms. 40 | // This is mandatory to keep the messages small and limit the bandwidth. 41 | asteroids.get_asteroids().retain(|_key, value| { 42 | (value.last_updated() + 0.2) > (get_time() - sync_t) || !value.collided() 43 | }); 44 | } 45 | 46 | for ship_index in 0..players.len() { 47 | if opponents[ship_index].collided() { 48 | players[ship_index].set_collided(true); 49 | } 50 | } 51 | } 52 | 53 | fn ship_vs_asteroids( 54 | ship: &mut Ship, 55 | asteroids: &mut Asteroids, 56 | name: String, 57 | god: bool, 58 | mode: &str, 59 | sync_t: f64, 60 | ) { 61 | let mut new_asteroids = Vec::new(); 62 | for asteroid in asteroids.get_asteroids().values_mut() { 63 | if is_collided(asteroid, ship) && !god && mode != "spectator" { 64 | ship.set_collided(true); 65 | } 66 | ship_bullet_vs_asteroid(ship, asteroid, &mut new_asteroids, sync_t); 67 | } 68 | 69 | // Send new asteroids created only for this player. 70 | if ship.name() == name { 71 | for asteroid in new_asteroids { 72 | asteroids.add_asteroid(name.clone(), asteroid); 73 | } 74 | } 75 | } 76 | 77 | fn ship_bullet_vs_asteroid( 78 | ship: &mut Ship, 79 | asteroid: &mut Asteroid, 80 | new_asteroids: &mut Vec, 81 | sync_t: f64, 82 | ) { 83 | for bullet in ship.bullets.iter_mut() { 84 | if !bullet.collided() && !asteroid.collided() && is_collided(asteroid, bullet) { 85 | asteroid.set_collided(true); 86 | asteroid.set_last_updated(get_time() - sync_t); 87 | bullet.set_collided(true); 88 | // Split asteroid into 2 smaller parts except if we have a square. 89 | if asteroid.sides() > 4 { 90 | *new_asteroids = Asteroid::new_split( 91 | asteroid.pos(), 92 | bullet.vel().x, 93 | bullet.vel().y, 94 | asteroid.size(), 95 | asteroid.sides(), 96 | asteroid.last_updated(), 97 | ); 98 | } 99 | break; 100 | } 101 | } 102 | } 103 | 104 | fn ship_vs_opponents(ship: &mut Ship, opponents: &mut [Ship]) { 105 | for opponent in opponents.iter_mut() { 106 | if opponent.name() != ship.name() { 107 | ship_bullet_vs_opponents(ship, opponent); 108 | } 109 | } 110 | } 111 | 112 | fn ship_bullet_vs_opponents(ship: &mut Ship, opponent: &mut Ship) { 113 | for bullet in ship.bullets.iter_mut() { 114 | if is_collided(opponent, bullet) { 115 | bullet.set_collided(true); 116 | opponent.set_collided(true); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /client/src/gameover.rs: -------------------------------------------------------------------------------- 1 | use crate::asteroid::Asteroids; 2 | use crate::ship::Ship; 3 | use crate::sound::Sound; 4 | use crate::MAX_ASTEROIDS; 5 | use macroquad::prelude::*; 6 | 7 | #[allow(clippy::too_many_arguments)] 8 | pub fn manage_gameover( 9 | players: &mut Vec, 10 | asteroids: &mut Asteroids, 11 | mode: &str, 12 | name: &str, 13 | frame_count: &mut u32, 14 | gameover: &mut bool, 15 | gameover_msg_sent: &mut bool, 16 | sound: &mut Sound, 17 | ) { 18 | // Take care this part is executed in a loop ! 19 | // host is looping until the enter key is pressed 20 | clear_background(LIGHTGRAY); 21 | let mut status = "Game over."; 22 | let font_size = 30.; 23 | 24 | if asteroids.is_empty() { 25 | status = "You win !"; 26 | sound.victory(); 27 | } 28 | 29 | let text: String = if mode == "host" { 30 | format!("{} Press [enter] to play again.", status) 31 | } else { 32 | format!("{} Wait host player to restart game.", status) 33 | }; 34 | 35 | let text_size = measure_text(&text, None, font_size as _, 1.0); 36 | draw_text( 37 | &text, 38 | screen_width() / 2. - text_size.width / 2., 39 | screen_height() / 2. - text_size.height / 2., 40 | font_size, 41 | DARKGRAY, 42 | ); 43 | 44 | if mode != "host" || is_key_down(KeyCode::Enter) { 45 | log::info!("Restarting game."); 46 | players.clear(); 47 | players.push(Ship::new(String::from(name))); 48 | *gameover = false; 49 | *gameover_msg_sent = false; 50 | *asteroids = Asteroids::generate_field(String::from(name), 0); 51 | sound.reset_played_sound(); 52 | if mode == "host" { 53 | *asteroids = Asteroids::generate_field(String::from(name), MAX_ASTEROIDS); 54 | } 55 | *frame_count = 0; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /client/src/main.rs: -------------------------------------------------------------------------------- 1 | mod asteroid; 2 | mod bullet; 3 | mod collision; 4 | mod gameover; 5 | #[cfg(not(target_arch = "wasm32"))] 6 | mod network; 7 | mod screen; 8 | mod ship; 9 | mod sound; 10 | use crate::asteroid::Asteroids; 11 | use crate::collision::manage_collisions; 12 | #[cfg(not(target_arch = "wasm32"))] 13 | use crate::network::{ 14 | connect_stream, connect_ws, deserialize_host_data, serialize_guest_data, serialize_host_data, 15 | wait_synchronization_data, 16 | }; 17 | use crate::{gameover::manage_gameover, ship::Ship}; 18 | use macroquad::prelude::*; 19 | #[cfg(not(target_arch = "wasm32"))] 20 | use simple_logger::SimpleLogger; 21 | use sound::Sound; 22 | #[cfg(not(target_arch = "wasm32"))] 23 | use std::{net::TcpStream, sync::mpsc, thread, thread::sleep, time::Duration}; 24 | use structopt::clap::{crate_name, crate_version}; 25 | use structopt::StructOpt; 26 | #[cfg(not(target_arch = "wasm32"))] 27 | use tungstenite::Message; 28 | #[cfg(not(target_arch = "wasm32"))] 29 | use url::Url; 30 | 31 | #[derive(StructOpt, Debug)] 32 | #[structopt(name = crate_name!(), version = crate_version!())] 33 | /// Planetoid is an asteroid clone. 34 | 35 | struct Opt { 36 | /// Debug mode (ϕ (error), -d (info), -dd (debug), -ddd (trace)) 37 | #[cfg(not(target_arch = "wasm32"))] 38 | #[structopt(short, long, parse(from_occurrences))] 39 | debug: u8, 40 | 41 | /// Host 42 | #[cfg(not(target_arch = "wasm32"))] 43 | #[structopt(short, long, default_value = "localhost")] 44 | host: String, 45 | 46 | /// Port 47 | #[cfg(not(target_arch = "wasm32"))] 48 | #[structopt(short, long, default_value = "8080")] 49 | port: u16, 50 | 51 | /// God mode 52 | #[structopt(short, long)] 53 | god: bool, 54 | 55 | /// Network mode 56 | #[structopt(short, long, default_value = "host", possible_values = &["host","guest","spectator"])] 57 | mode: String, 58 | 59 | /// Solo mode, do not connect to network 60 | #[cfg(not(target_arch = "wasm32"))] 61 | #[structopt(short, long, conflicts_with = "mode")] 62 | solo: bool, 63 | 64 | /// Display fps 65 | #[structopt(short, long)] 66 | fps: bool, 67 | 68 | /// Player name 69 | #[structopt(short, long, default_value = "planetoid")] 70 | name: String, 71 | } 72 | 73 | const MAX_ASTEROIDS: usize = 10; 74 | 75 | fn window_conf() -> Conf { 76 | Conf { 77 | window_title: String::from("Planetoid"), 78 | fullscreen: false, 79 | window_width: 1024, 80 | window_height: 768, 81 | window_resizable: false, 82 | 83 | ..Default::default() 84 | } 85 | } 86 | 87 | #[cfg(not(target_arch = "wasm32"))] 88 | fn get_log_level(debug_occurence: u8) -> log::LevelFilter { 89 | match debug_occurence { 90 | 0 => log::LevelFilter::Error, 91 | 1 => log::LevelFilter::Info, 92 | 2 => log::LevelFilter::Debug, 93 | 3 => log::LevelFilter::Trace, 94 | _ => log::LevelFilter::Error, 95 | } 96 | } 97 | 98 | fn display_fps(fps: &mut i32, frame_t: f64, fps_refresh: &mut f64) { 99 | if frame_t - *fps_refresh > 0.2 { 100 | *fps = get_fps(); 101 | *fps_refresh = frame_t; 102 | } 103 | let text = format!("{} fps", fps); 104 | let font_size = 30.; 105 | draw_text(&text, 5., 20., font_size, DARKGRAY) 106 | } 107 | 108 | #[macroquad::main(window_conf)] 109 | async fn main() { 110 | // Seed random generator 111 | rand::srand(miniquad::date::now() as u64); 112 | 113 | let opt = Opt::from_args(); 114 | 115 | #[cfg(not(target_arch = "wasm32"))] 116 | let log_level = get_log_level(opt.debug); 117 | 118 | #[cfg(not(target_arch = "wasm32"))] 119 | SimpleLogger::new() 120 | .with_utc_timestamps() 121 | .with_level(log_level) 122 | .init() 123 | .unwrap(); 124 | log::debug!("{:#?}", opt); 125 | log::info!("Starting game."); 126 | 127 | let mut show_fps = opt.fps; 128 | let mut fps: i32 = 0; 129 | let mut gameover = false; 130 | let mut gameover_msg_sent = false; 131 | #[cfg(not(target_arch = "wasm32"))] 132 | let mut host_msg_received: bool = false; 133 | // Timing values 134 | let mut lastshot_t = get_time(); 135 | let mut thrust_t = get_time(); 136 | let mut fps_t = get_time(); 137 | let mut debounce_t = get_time(); 138 | 139 | let mut sound = Sound::new().await; 140 | 141 | #[allow(unused_mut)] 142 | let mut sync_t: f64 = 0.0; 143 | let mut players: Vec = vec![Ship::new(String::from(&opt.name))]; 144 | 145 | let mut asteroids: Asteroids = Asteroids::generate_field(opt.name.clone(), 0); 146 | if opt.mode == "host" { 147 | asteroids = Asteroids::generate_field(opt.name.clone(), MAX_ASTEROIDS); 148 | } 149 | 150 | #[cfg(not(target_arch = "wasm32"))] 151 | let (tx_from_socket, rx_from_socket) = mpsc::channel(); 152 | #[cfg(not(target_arch = "wasm32"))] 153 | let (tx_to_socket, rx_to_socket) = mpsc::channel(); 154 | 155 | #[cfg(not(target_arch = "wasm32"))] 156 | if !opt.solo { 157 | let url = Url::parse(&format!( 158 | "ws://{}:{}/gamedata/{}", 159 | &opt.host, &opt.port, &opt.name 160 | )) 161 | .expect("Cannot parse url."); 162 | 163 | // Thread to manage network web socket 164 | // This thread uses a channel to pass messages to the main thread (game) 165 | thread::spawn(move || { 166 | let stream: TcpStream = connect_stream(&url); 167 | let (mut socket, _response) = connect_ws(url, &stream).unwrap(); 168 | loop { 169 | match rx_to_socket.try_recv() { 170 | Ok(msg) => socket 171 | .write_message(Message::Text(msg)) 172 | .expect("Cannot write to WebSocket."), 173 | Err(mpsc::TryRecvError::Empty) => (), 174 | Err(mpsc::TryRecvError::Disconnected) => panic!("Client disconnected."), 175 | }; 176 | 177 | if let Ok(msg) = socket.read_message() { 178 | tx_from_socket.send(msg).unwrap(); 179 | } 180 | sleep(Duration::from_millis(5)); 181 | } 182 | }); 183 | 184 | wait_synchronization_data( 185 | &rx_from_socket, 186 | &tx_to_socket, 187 | &opt.name, 188 | &opt.mode, 189 | &mut asteroids, 190 | &mut players, 191 | &mut gameover, 192 | &mut host_msg_received, 193 | &mut sync_t, 194 | ); 195 | } 196 | 197 | let mut frame_count: u32 = 0; 198 | let time_before_entering_loop = get_time(); 199 | 200 | // Game loop 201 | loop { 202 | #[cfg(not(target_arch = "wasm32"))] 203 | if !opt.solo { 204 | loop { 205 | let _received = match rx_from_socket.try_recv() { 206 | Ok(msg) => { 207 | deserialize_host_data( 208 | &opt.name, 209 | &opt.mode, 210 | msg, 211 | &mut asteroids, 212 | &mut players, 213 | &mut gameover, 214 | &mut host_msg_received, 215 | &mut sync_t, 216 | ); 217 | } 218 | Err(mpsc::TryRecvError::Empty) => (break), 219 | Err(mpsc::TryRecvError::Disconnected) => panic!("Disconnected"), 220 | }; 221 | } 222 | 223 | if frame_count > 4 && opt.mode == "host" { 224 | tx_to_socket 225 | .send(serialize_host_data( 226 | &mut asteroids, 227 | &mut players, 228 | &mut gameover, 229 | )) 230 | .unwrap(); 231 | frame_count = 0; 232 | } 233 | 234 | if host_msg_received && opt.mode == "guest" { 235 | for ship in players.iter() { 236 | if ship.name() == opt.name { 237 | tx_to_socket 238 | .send(serialize_guest_data(ship, &mut asteroids)) 239 | .unwrap(); 240 | } 241 | } 242 | host_msg_received = false; 243 | } 244 | } 245 | 246 | if gameover { 247 | // Send a last message to all guests that the game is over 248 | #[cfg(not(target_arch = "wasm32"))] 249 | if !opt.solo && opt.mode == "host" && !gameover_msg_sent { 250 | tx_to_socket 251 | .send(serialize_host_data( 252 | &mut asteroids, 253 | &mut players, 254 | &mut gameover, 255 | )) 256 | .unwrap(); 257 | frame_count = 0; 258 | gameover_msg_sent = true; 259 | } 260 | 261 | manage_gameover( 262 | &mut players, 263 | &mut asteroids, 264 | &opt.mode, 265 | &opt.name, 266 | &mut frame_count, 267 | &mut gameover, 268 | &mut gameover_msg_sent, 269 | &mut sound, 270 | ); 271 | 272 | // Display frame but do not increase frame_count to not send new messages 273 | next_frame().await; 274 | 275 | // Guest will be blocked waiting for the next message from the host 276 | // The host will send a new message as soon as the user will hit enter 277 | #[cfg(not(target_arch = "wasm32"))] 278 | if !opt.solo { 279 | wait_synchronization_data( 280 | &rx_from_socket, 281 | &tx_to_socket, 282 | &opt.name, 283 | &opt.mode, 284 | &mut asteroids, 285 | &mut players, 286 | &mut gameover, 287 | &mut host_msg_received, 288 | &mut sync_t, 289 | ); 290 | } 291 | continue; 292 | } 293 | 294 | let frame_t = get_time() - time_before_entering_loop; 295 | for ship in players.iter_mut() { 296 | ship.slow_down(); 297 | } 298 | 299 | if opt.mode != "spectator" { 300 | if is_key_down(KeyCode::Up) { 301 | for ship in players.iter_mut() { 302 | if ship.name() == opt.name && !ship.collided() { 303 | ship.accelerate(); 304 | if frame_t - thrust_t > 0.5 { 305 | sound.thrust(); 306 | thrust_t = frame_t; 307 | } 308 | } 309 | } 310 | } 311 | 312 | if is_key_down(KeyCode::Space) && frame_t - lastshot_t > 0.1 { 313 | for ship in players.iter_mut() { 314 | if ship.name() == opt.name && !ship.collided() { 315 | ship.shoot(frame_t); 316 | sound.laser(); 317 | } 318 | } 319 | lastshot_t = frame_t; 320 | } 321 | 322 | if is_key_down(KeyCode::Right) { 323 | for ship in players.iter_mut() { 324 | if ship.name() == opt.name && !ship.collided() { 325 | ship.set_rot(ship.rot() + 5.); 326 | } 327 | } 328 | } else if is_key_down(KeyCode::Left) { 329 | for ship in players.iter_mut() { 330 | if ship.name() == opt.name && !ship.collided() { 331 | ship.set_rot(ship.rot() - 5.); 332 | } 333 | } 334 | } 335 | } 336 | if is_key_down(KeyCode::F) && frame_t - debounce_t > 0.2 { 337 | if show_fps { 338 | show_fps = false; 339 | } else { 340 | show_fps = true; 341 | } 342 | debounce_t = frame_t; 343 | } 344 | 345 | if cfg!(not(target_arch = "wasm32")) && is_key_down(KeyCode::Escape) { 346 | break; 347 | } 348 | 349 | for ship in players.iter_mut() { 350 | ship.update_pos(); 351 | } 352 | 353 | for ship in players.iter_mut() { 354 | for bullet in ship.bullets.iter_mut() { 355 | bullet.update_pos(); 356 | } 357 | } 358 | 359 | for asteroid in asteroids.get_asteroids().values_mut() { 360 | asteroid.update_pos(); 361 | } 362 | 363 | manage_collisions( 364 | &mut players, 365 | &mut asteroids, 366 | opt.name.clone(), 367 | opt.god, 368 | &opt.mode, 369 | frame_t, 370 | sync_t, 371 | ); 372 | 373 | if players 374 | .iter() 375 | .any(|ship| ship.name() == opt.name && ship.collided()) 376 | { 377 | sound.explosion(); 378 | } 379 | 380 | if asteroids.is_empty() || players.iter().all(|ship| ship.collided()) { 381 | gameover = true; 382 | } 383 | 384 | clear_background(LIGHTGRAY); 385 | for ship in &players { 386 | for bullet in ship.bullets.iter() { 387 | if !bullet.collided() { 388 | bullet.draw(); 389 | } 390 | } 391 | } 392 | 393 | for asteroid in asteroids.get_asteroids().values_mut() { 394 | if !asteroid.collided() { 395 | asteroid.draw(); 396 | } 397 | } 398 | 399 | for ship in &players { 400 | if !ship.collided() { 401 | if ship.name() == opt.name { 402 | ship.draw(BLACK); 403 | } else { 404 | ship.draw(RED); 405 | } 406 | } 407 | } 408 | 409 | log::trace!("{} fps", get_fps()); 410 | if show_fps { 411 | display_fps(&mut fps, frame_t, &mut fps_t); 412 | } 413 | next_frame().await; 414 | frame_count += 1; 415 | } 416 | } 417 | -------------------------------------------------------------------------------- /client/src/network.rs: -------------------------------------------------------------------------------- 1 | use crate::asteroid::synchronize_asteroids; 2 | use crate::{asteroid::Asteroids, ship::Ship}; 3 | use macroquad::prelude::get_time; 4 | use serde::{Deserialize, Serialize}; 5 | use std::sync::mpsc::{Receiver, Sender}; 6 | use std::{ 7 | error::Error, 8 | net::{TcpStream, ToSocketAddrs}, 9 | }; 10 | use tungstenite::{client, http::Response}; 11 | use tungstenite::{Message, WebSocket}; 12 | use url::Url; 13 | 14 | type WebSocketResult = Result>; 15 | pub fn connect_stream(url: &Url) -> TcpStream { 16 | let addr = (url.host_str().unwrap(), url.port().unwrap()) 17 | .to_socket_addrs() 18 | .unwrap() 19 | .last() 20 | .expect("Cannot get host and port from url."); 21 | 22 | log::debug!("Connect to TcpStream {}:{}", addr.ip(), addr.port()); 23 | TcpStream::connect(addr).expect("Cannot connect to specified address.") 24 | } 25 | 26 | pub fn connect_ws( 27 | url: Url, 28 | stream: &TcpStream, 29 | ) -> WebSocketResult<(WebSocket<&TcpStream>, Response<()>)> { 30 | log::debug!("Connect to WebSocket url {}", url); 31 | let (socket, response) = client(url, stream).expect("Cannot connect to specified url."); 32 | 33 | stream 34 | .set_nonblocking(true) 35 | .expect("set_nonblocking call failed"); 36 | 37 | log::info!("Connected to the server"); 38 | log::info!("Response HTTP code: {}", response.status()); 39 | 40 | Ok((socket, response)) 41 | } 42 | 43 | #[derive(Serialize, Deserialize)] 44 | struct GameData { 45 | asteroids: Asteroids, 46 | players: Vec, 47 | gameover: bool, 48 | } 49 | 50 | #[allow(clippy::too_many_arguments)] 51 | pub fn deserialize_host_data( 52 | name: &str, 53 | mode: &str, 54 | msg: Message, 55 | asteroids: &mut Asteroids, 56 | players: &mut Vec, 57 | gameover: &mut bool, 58 | host_msg_received: &mut bool, 59 | sync_t: &mut f64, 60 | ) { 61 | if let Message::Text(msg) = msg { 62 | log::debug!("{}", msg); 63 | if msg.contains("Hello from ") { 64 | let name = msg.strip_prefix("Hello from ").unwrap(); 65 | players.push(Ship::new(String::from(name))); 66 | *sync_t = get_time(); 67 | asteroids.refresh_last_updated(get_time() - *sync_t); 68 | } 69 | 70 | if mode == "host" && msg.contains("GuestData: ") { 71 | let msg = msg.strip_prefix("GuestData: ").unwrap(); 72 | let guestdata: GuestData = serde_json::from_str(msg).unwrap(); 73 | let opponent = guestdata.ship; 74 | for ship in players.iter_mut() { 75 | if ship.name() == opponent.name() { 76 | *ship = opponent.clone(); 77 | } 78 | } 79 | synchronize_asteroids(asteroids, guestdata.asteroids); 80 | } 81 | 82 | if mode != "host" && msg.contains("GameData: ") { 83 | let msg = msg.strip_prefix("GameData: ").unwrap(); 84 | 85 | // Backup player ship 86 | let mut current_ship: Ship = Ship::new(name.to_string()); 87 | for ship in players.clone() { 88 | if ship.name() == name { 89 | current_ship = ship; 90 | } 91 | } 92 | 93 | let gamedata: GameData = serde_json::from_str(msg).unwrap(); 94 | synchronize_asteroids(asteroids, gamedata.asteroids); 95 | *gameover = gamedata.gameover; 96 | *players = gamedata.players; 97 | 98 | // Restore current ship 99 | for ship in players { 100 | if ship.name() == name { 101 | *ship = current_ship.clone(); 102 | } 103 | } 104 | *host_msg_received = true; 105 | } 106 | } 107 | } 108 | 109 | pub fn serialize_host_data( 110 | asteroids: &mut Asteroids, 111 | players: &mut [Ship], 112 | gameover: &mut bool, 113 | ) -> String { 114 | let gamedata = GameData { 115 | asteroids: asteroids.clone(), 116 | players: players.to_vec(), 117 | gameover: *gameover, 118 | }; 119 | 120 | format!("GameData: {}", serde_json::to_string(&gamedata).unwrap()) 121 | } 122 | 123 | #[derive(Serialize, Deserialize)] 124 | struct GuestData { 125 | asteroids: Asteroids, 126 | ship: Ship, 127 | } 128 | 129 | pub fn serialize_guest_data(ship: &Ship, asteroids: &mut Asteroids) -> String { 130 | let guestdata = GuestData { 131 | asteroids: asteroids.clone(), 132 | ship: ship.clone(), 133 | }; 134 | format!("GuestData: {}", serde_json::to_string(&guestdata).unwrap()) 135 | } 136 | 137 | #[allow(clippy::too_many_arguments)] 138 | pub fn wait_synchronization_data( 139 | rx_from_socket: &Receiver, 140 | tx_to_socket: &Sender, 141 | name: &str, 142 | mode: &str, 143 | asteroids: &mut Asteroids, 144 | players: &mut Vec, 145 | gameover: &mut bool, 146 | host_msg_received: &mut bool, 147 | sync_t: &mut f64, 148 | ) { 149 | if mode != "host" { 150 | log::info!("Waiting synchronization data"); 151 | loop { 152 | let msg = rx_from_socket.recv().unwrap(); 153 | deserialize_host_data( 154 | name, 155 | mode, 156 | msg, 157 | asteroids, 158 | players, 159 | gameover, 160 | host_msg_received, 161 | sync_t, 162 | ); 163 | if !asteroids.is_empty() { 164 | break; 165 | } 166 | } 167 | 168 | if mode == "guest" { 169 | tx_to_socket.send(format!("Hello from {}", name)).unwrap(); 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /client/src/screen.rs: -------------------------------------------------------------------------------- 1 | use macroquad::prelude::*; 2 | pub fn wrap_around(pos: &Vec2) -> Vec2 { 3 | let mut wrapped_pos = Vec2::new(pos.x, pos.y); 4 | if wrapped_pos.x > screen_width() { 5 | wrapped_pos.x = 0.; 6 | } 7 | if wrapped_pos.x < 0. { 8 | wrapped_pos.x = screen_width() 9 | } 10 | if wrapped_pos.y > screen_height() { 11 | wrapped_pos.y = 0.; 12 | } 13 | if wrapped_pos.y < 0. { 14 | wrapped_pos.y = screen_height() 15 | } 16 | wrapped_pos 17 | } 18 | 19 | pub fn center() -> Vec2 { 20 | Vec2::new(screen_width() / 2., screen_height() / 2.) 21 | } 22 | -------------------------------------------------------------------------------- /client/src/ship.rs: -------------------------------------------------------------------------------- 1 | use crate::screen; 2 | use crate::{bullet::Bullet, collision::Collided}; 3 | use macroquad::prelude::*; 4 | use serde::de::{self, Deserializer, MapAccess, Visitor}; 5 | use serde::ser::{SerializeStruct, Serializer}; 6 | use serde::{Deserialize, Serialize}; 7 | use std::fmt; 8 | 9 | #[derive(Debug)] 10 | pub struct Ship { 11 | name: String, 12 | pos: Vec2, 13 | vel: Vec2, 14 | acc: Vec2, 15 | rot: f32, 16 | size: f32, 17 | collided: bool, 18 | pub bullets: Vec, 19 | } 20 | 21 | impl Ship { 22 | pub const HEIGHT: f32 = 25.; 23 | pub const BASE: f32 = 22.; 24 | const DACC_FACTOR: f32 = 30.; 25 | const ACC_FACTOR: f32 = 3.; 26 | pub fn new(name: String) -> Self { 27 | Self { 28 | name, 29 | // pos: screen::center(), 30 | // Temporary for debugging 31 | pos: Vec2::new( 32 | rand::gen_range(0., screen_width()), 33 | rand::gen_range(0., screen_height()), 34 | ), 35 | vel: Vec2::new(0., 0.), 36 | acc: Vec2::new(0., 0.), 37 | rot: 0., 38 | size: Ship::HEIGHT / 3., 39 | collided: false, 40 | bullets: Vec::new(), 41 | } 42 | } 43 | 44 | pub fn rotation(&self) -> f32 { 45 | self.rot.to_radians() 46 | } 47 | 48 | pub fn draw(&self, color: Color) { 49 | let v1 = Vec2::new( 50 | self.pos.x + self.rotation().sin() * Ship::HEIGHT / 2., 51 | self.pos.y - self.rotation().cos() * Ship::HEIGHT / 2., 52 | ); 53 | let v2 = Vec2::new( 54 | self.pos.x 55 | - self.rotation().cos() * Ship::BASE / 2. 56 | - self.rotation().sin() * Ship::HEIGHT / 2., 57 | self.pos.y - self.rotation().sin() * Ship::BASE / 2. 58 | + self.rotation().cos() * Ship::HEIGHT / 2., 59 | ); 60 | let v3 = Vec2::new( 61 | self.pos.x + self.rotation().cos() * Ship::BASE / 2. 62 | - self.rotation().sin() * Ship::HEIGHT / 2., 63 | self.pos.y 64 | + self.rotation().sin() * Ship::BASE / 2. 65 | + self.rotation().cos() * Ship::HEIGHT / 2., 66 | ); 67 | let v1_2 = Vec2::new( 68 | self.pos.x + self.rotation().sin() * Ship::HEIGHT / 4., 69 | self.pos.y - self.rotation().cos() * Ship::HEIGHT / 4., 70 | ); 71 | let v2_2 = Vec2::new( 72 | self.pos.x 73 | - self.rotation().cos() * Ship::BASE / 4. 74 | - self.rotation().sin() * Ship::HEIGHT / 4., 75 | self.pos.y - self.rotation().sin() * Ship::BASE / 4. 76 | + self.rotation().cos() * Ship::HEIGHT / 4., 77 | ); 78 | let v3_2 = Vec2::new( 79 | self.pos.x + self.rotation().cos() * Ship::BASE / 4. 80 | - self.rotation().sin() * Ship::HEIGHT / 4., 81 | self.pos.y 82 | + self.rotation().sin() * Ship::BASE / 4. 83 | + self.rotation().cos() * Ship::HEIGHT / 4., 84 | ); 85 | draw_triangle_lines(v1, v2, v3, 2., color); 86 | draw_triangle_lines(v1_2, v2_2, v3_2, 2., color); 87 | } 88 | 89 | pub fn slow_down(&mut self) { 90 | self.acc = -self.vel() / Ship::DACC_FACTOR; 91 | } 92 | 93 | pub fn accelerate(&mut self) { 94 | self.acc = Vec2::new(self.rotation().sin(), -self.rotation().cos()) / Ship::ACC_FACTOR; 95 | } 96 | 97 | pub fn update_pos(&mut self) { 98 | self.vel += self.acc; 99 | if self.vel.length() > 10. { 100 | self.vel = self.vel.normalize() * 10.; 101 | } 102 | self.pos += self.vel; 103 | self.pos = screen::wrap_around(&self.pos); 104 | } 105 | 106 | pub fn name(&self) -> String { 107 | self.name.clone() 108 | } 109 | 110 | pub fn vel(&self) -> Vec2 { 111 | self.vel 112 | } 113 | 114 | pub fn rot(&self) -> f32 { 115 | self.rot 116 | } 117 | 118 | pub fn set_rot(&mut self, rot: f32) { 119 | self.rot = rot; 120 | } 121 | 122 | pub fn collided(&self) -> bool { 123 | self.collided 124 | } 125 | 126 | pub fn set_collided(&mut self, collided: bool) { 127 | self.collided = collided; 128 | } 129 | 130 | pub fn shoot(&mut self, frame_t: f64) { 131 | let rot_vec = Vec2::new(self.rotation().sin(), -self.rotation().cos()); 132 | self.bullets.push(Bullet::new( 133 | self.pos() + rot_vec * Ship::HEIGHT / 2., 134 | rot_vec * 7., 135 | frame_t, 136 | false, 137 | )); 138 | } 139 | } 140 | 141 | impl Collided for Ship { 142 | fn pos(&self) -> Vec2 { 143 | self.pos 144 | } 145 | 146 | fn size(&self) -> f32 { 147 | self.size 148 | } 149 | } 150 | 151 | impl Serialize for Ship { 152 | fn serialize(&self, serializer: S) -> Result 153 | where 154 | S: Serializer, 155 | { 156 | let mut state = serializer.serialize_struct("Ship", 8)?; 157 | state.serialize_field("name", &self.name)?; 158 | state.serialize_field("pos", &vec![&self.pos[0], &self.pos[1]])?; 159 | state.serialize_field("vel", &vec![&self.vel[0], &self.vel[1]])?; 160 | state.serialize_field("acc", &vec![&self.acc[0], &self.acc[1]])?; 161 | state.serialize_field("rot", &self.rot)?; 162 | state.serialize_field("size", &self.size)?; 163 | state.serialize_field("collided", &self.collided)?; 164 | state.serialize_field("bullets", &self.bullets)?; 165 | state.end() 166 | } 167 | } 168 | 169 | impl<'de> Deserialize<'de> for Ship { 170 | fn deserialize(deserializer: D) -> Result 171 | where 172 | D: Deserializer<'de>, 173 | { 174 | enum Field { 175 | Name, 176 | Pos, 177 | Vel, 178 | Acc, 179 | Rot, 180 | Size, 181 | Collided, 182 | Bullets, 183 | } 184 | 185 | impl<'de> Deserialize<'de> for Field { 186 | fn deserialize(deserializer: D) -> Result 187 | where 188 | D: Deserializer<'de>, 189 | { 190 | struct FieldVisitor; 191 | 192 | impl<'de> Visitor<'de> for FieldVisitor { 193 | type Value = Field; 194 | 195 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 196 | formatter.write_str( 197 | "`name`, `pos`, `vel`, `acc`, `rot`, `size`, `collided` or `bullets`", 198 | ) 199 | } 200 | 201 | fn visit_str(self, value: &str) -> Result 202 | where 203 | E: de::Error, 204 | { 205 | match value { 206 | "name" => Ok(Field::Name), 207 | "pos" => Ok(Field::Pos), 208 | "vel" => Ok(Field::Vel), 209 | "acc" => Ok(Field::Acc), 210 | "rot" => Ok(Field::Rot), 211 | "size" => Ok(Field::Size), 212 | "collided" => Ok(Field::Collided), 213 | "bullets" => Ok(Field::Bullets), 214 | _ => Err(de::Error::unknown_field(value, FIELDS)), 215 | } 216 | } 217 | } 218 | 219 | deserializer.deserialize_identifier(FieldVisitor) 220 | } 221 | } 222 | 223 | struct ShipVisitor; 224 | 225 | impl<'de> Visitor<'de> for ShipVisitor { 226 | type Value = Ship; 227 | 228 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 229 | formatter.write_str("struct Ship") 230 | } 231 | 232 | fn visit_map(self, mut map: V) -> Result 233 | where 234 | V: MapAccess<'de>, 235 | { 236 | let mut name = None; 237 | let mut pos: Option> = None; 238 | let mut vel: Option> = None; 239 | let mut acc: Option> = None; 240 | let mut rot = None; 241 | let mut size = None; 242 | let mut collided = None; 243 | let mut bullets: Option> = None; 244 | while let Some(key) = map.next_key()? { 245 | match key { 246 | Field::Name => { 247 | if name.is_some() { 248 | return Err(de::Error::duplicate_field("name")); 249 | } 250 | name = Some(map.next_value()?); 251 | } 252 | Field::Pos => { 253 | if pos.is_some() { 254 | return Err(de::Error::duplicate_field("pos")); 255 | } 256 | pos = Some(map.next_value()?); 257 | } 258 | Field::Vel => { 259 | if vel.is_some() { 260 | return Err(de::Error::duplicate_field("vel")); 261 | } 262 | vel = Some(map.next_value()?); 263 | } 264 | Field::Acc => { 265 | if acc.is_some() { 266 | return Err(de::Error::duplicate_field("vel")); 267 | } 268 | acc = Some(map.next_value()?); 269 | } 270 | Field::Rot => { 271 | if rot.is_some() { 272 | return Err(de::Error::duplicate_field("rot")); 273 | } 274 | rot = Some(map.next_value()?); 275 | } 276 | Field::Size => { 277 | if size.is_some() { 278 | return Err(de::Error::duplicate_field("size")); 279 | } 280 | size = Some(map.next_value()?); 281 | } 282 | Field::Collided => { 283 | if collided.is_some() { 284 | return Err(de::Error::duplicate_field("collided")); 285 | } 286 | collided = Some(map.next_value()?); 287 | } 288 | Field::Bullets => { 289 | if bullets.is_some() { 290 | return Err(de::Error::duplicate_field("bullets")); 291 | } 292 | bullets = Some(map.next_value()?); 293 | } 294 | } 295 | } 296 | let name = name.ok_or_else(|| de::Error::missing_field("name"))?; 297 | let pos = pos.ok_or_else(|| de::Error::missing_field("pos"))?; 298 | let vel = vel.ok_or_else(|| de::Error::missing_field("vel"))?; 299 | let acc = acc.ok_or_else(|| de::Error::missing_field("acc"))?; 300 | let rot = rot.ok_or_else(|| de::Error::missing_field("rot"))?; 301 | let size = size.ok_or_else(|| de::Error::missing_field("size"))?; 302 | let collided = collided.ok_or_else(|| de::Error::missing_field("collided"))?; 303 | let bullets = bullets.ok_or_else(|| de::Error::missing_field("bullets"))?; 304 | Ok(Ship { 305 | name, 306 | pos: Vec2::new(pos[0], pos[1]), 307 | vel: Vec2::new(vel[0], vel[1]), 308 | acc: Vec2::new(acc[0], acc[1]), 309 | rot, 310 | size, 311 | collided, 312 | bullets, 313 | }) 314 | } 315 | } 316 | 317 | const FIELDS: &[&str] = &[ 318 | "name", "pos", "vel", "acc", "rot", "size", "collided", "bullets", 319 | ]; 320 | deserializer.deserialize_struct("Ship", FIELDS, ShipVisitor) 321 | } 322 | } 323 | 324 | impl Clone for Ship { 325 | fn clone(&self) -> Self { 326 | Self { 327 | name: self.name.clone(), 328 | pos: self.pos, 329 | vel: self.vel, 330 | acc: self.acc, 331 | rot: self.rot, 332 | size: self.size, 333 | collided: self.collided, 334 | bullets: self.bullets.clone(), 335 | } 336 | } 337 | } 338 | 339 | #[cfg(test)] 340 | mod tests { 341 | use super::*; 342 | 343 | #[test] 344 | fn ship_serialize_deserialize_test() { 345 | let mut bullets: Vec = Vec::new(); 346 | 347 | let bullet = Bullet::new(Vec2::new(1., 1.), Vec2::new(2., 2.), 5., false); 348 | bullets.push(bullet); 349 | 350 | let bullet2 = Bullet::new(Vec2::new(2., 1.), Vec2::new(3., 2.), 6., true); 351 | bullets.push(bullet2); 352 | 353 | let ship = Ship { 354 | name: String::from("Uggla"), 355 | pos: Vec2::new(1., 1.), 356 | vel: Vec2::new(2., 2.), 357 | acc: Vec2::new(3., 3.), 358 | rot: 1., 359 | size: 1., 360 | collided: false, 361 | bullets, 362 | }; 363 | let serialize = serde_json::to_string(&ship).unwrap(); 364 | dbg!(&serialize); 365 | let deserialize: Ship = serde_json::from_str(&serialize).unwrap(); 366 | let serialize2 = serde_json::to_string(&deserialize).unwrap(); 367 | assert_eq!(serialize, serialize2); 368 | assert_eq!(ship.name, deserialize.name); 369 | assert_eq!(ship.pos, deserialize.pos); 370 | assert_eq!(ship.vel, deserialize.vel); 371 | assert_eq!(ship.acc, deserialize.acc); 372 | assert_eq!(ship.rot, deserialize.rot); 373 | assert_eq!(ship.size, deserialize.size); 374 | assert_eq!(ship.collided, deserialize.collided); 375 | assert_eq!(ship.bullets[0].pos(), deserialize.bullets[0].pos()); 376 | assert_eq!(ship.bullets[0].vel(), deserialize.bullets[0].vel()); 377 | assert_eq!(ship.bullets[0].shot_at(), deserialize.bullets[0].shot_at()); 378 | assert_eq!(ship.bullets[0].size(), deserialize.bullets[0].size()); 379 | assert_eq!( 380 | ship.bullets[0].collided(), 381 | deserialize.bullets[0].collided() 382 | ); 383 | assert_eq!(ship.bullets[1].pos(), deserialize.bullets[1].pos()); 384 | assert_eq!(ship.bullets[1].vel(), deserialize.bullets[1].vel()); 385 | assert_eq!(ship.bullets[1].shot_at(), deserialize.bullets[1].shot_at()); 386 | assert_eq!(ship.bullets[1].size(), deserialize.bullets[1].size()); 387 | assert_eq!( 388 | ship.bullets[1].collided(), 389 | deserialize.bullets[1].collided() 390 | ); 391 | } 392 | 393 | #[test] 394 | fn ship_clone_test() { 395 | let mut bullets: Vec = Vec::new(); 396 | 397 | let bullet = Bullet::new(Vec2::new(1., 1.), Vec2::new(2., 2.), 5., false); 398 | bullets.push(bullet); 399 | 400 | let ship = Ship { 401 | name: String::from("Uggla"), 402 | pos: Vec2::new(1., 1.), 403 | vel: Vec2::new(2., 2.), 404 | acc: Vec2::new(3., 3.), 405 | rot: 1., 406 | size: 1., 407 | collided: false, 408 | bullets, 409 | }; 410 | 411 | let ship_clone = ship.clone(); 412 | 413 | assert_eq!(ship.name, ship_clone.name); 414 | assert_eq!(ship.pos, ship_clone.pos); 415 | assert_eq!(ship.vel, ship_clone.vel); 416 | assert_eq!(ship.acc, ship_clone.acc); 417 | assert_eq!(ship.rot, ship_clone.rot); 418 | assert_eq!(ship.size, ship_clone.size); 419 | assert_eq!(ship.collided, ship_clone.collided); 420 | assert_eq!(ship.bullets[0].pos(), ship_clone.bullets[0].pos()); 421 | assert_eq!(ship.bullets[0].vel(), ship_clone.bullets[0].vel()); 422 | assert_eq!(ship.bullets[0].shot_at(), ship_clone.bullets[0].shot_at()); 423 | assert_eq!(ship.bullets[0].size(), ship_clone.bullets[0].size()); 424 | } 425 | } 426 | -------------------------------------------------------------------------------- /client/src/sound.rs: -------------------------------------------------------------------------------- 1 | use macroquad::{audio, prelude::*}; 2 | 3 | pub struct Sound { 4 | laser: macroquad::audio::Sound, 5 | thrust: macroquad::audio::Sound, 6 | // Use a tuple (Sound, already_played) 7 | explosion: (macroquad::audio::Sound, bool), 8 | victory: (macroquad::audio::Sound, bool), 9 | } 10 | 11 | impl Sound { 12 | pub async fn new() -> Self { 13 | set_pc_assets_folder("sounds"); 14 | Self { 15 | laser: audio::load_sound("laser.wav").await.unwrap(), 16 | thrust: audio::load_sound("thrust.wav").await.unwrap(), 17 | explosion: (audio::load_sound("explosion.wav").await.unwrap(), false), 18 | victory: (audio::load_sound("victory.wav").await.unwrap(), false), 19 | } 20 | } 21 | 22 | pub fn laser(&self) { 23 | audio::play_sound_once(self.laser); 24 | } 25 | 26 | pub fn thrust(&self) { 27 | audio::play_sound_once(self.thrust); 28 | } 29 | 30 | pub fn explosion(&mut self) { 31 | if !self.explosion.1 { 32 | audio::play_sound_once(self.explosion.0); 33 | self.explosion.1 = true; 34 | } 35 | } 36 | 37 | pub fn victory(&mut self) { 38 | if !self.victory.1 { 39 | audio::play_sound_once(self.victory.0); 40 | self.victory.1 = true; 41 | } 42 | } 43 | 44 | pub fn reset_played_sound(&mut self) { 45 | self.victory.1 = false; 46 | self.explosion.1 = false; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /images/infra.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/images/infra.png -------------------------------------------------------------------------------- /images/multiplayer_game.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/images/multiplayer_game.jpg -------------------------------------------------------------------------------- /images/planetoid_native.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/images/planetoid_native.jpg -------------------------------------------------------------------------------- /images/planetoid_wasm32.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/images/planetoid_wasm32.jpg -------------------------------------------------------------------------------- /server/.dockerignore: -------------------------------------------------------------------------------- 1 | * 2 | !target/*-runner 3 | !target/*-runner.jar 4 | !target/lib/* 5 | !target/quarkus-app/* -------------------------------------------------------------------------------- /server/.gitignore: -------------------------------------------------------------------------------- 1 | #Maven 2 | target/ 3 | pom.xml.tag 4 | pom.xml.releaseBackup 5 | pom.xml.versionsBackup 6 | release.properties 7 | 8 | # Eclipse 9 | .project 10 | .classpath 11 | .settings/ 12 | bin/ 13 | 14 | # IntelliJ 15 | .idea 16 | *.ipr 17 | *.iml 18 | *.iws 19 | 20 | # NetBeans 21 | nb-configuration.xml 22 | 23 | # Visual Studio Code 24 | .vscode 25 | .factorypath 26 | 27 | # OSX 28 | .DS_Store 29 | 30 | # Vim 31 | *.swp 32 | *.swo 33 | 34 | # patch 35 | *.orig 36 | *.rej 37 | 38 | # Local environment 39 | .env 40 | 41 | # Archives 42 | *.zip -------------------------------------------------------------------------------- /server/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /server/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- 1 | # code-with-quarkus project 2 | 3 | This project uses Quarkus, the Supersonic Subatomic Java Framework. 4 | 5 | If you want to learn more about Quarkus, please visit its website: https://quarkus.io/ . 6 | 7 | ## Running the application in dev mode 8 | 9 | You can run your application in dev mode that enables live coding using: 10 | ```shell script 11 | ./mvnw compile quarkus:dev 12 | ``` 13 | 14 | > **_NOTE:_** Quarkus now ships with a Dev UI, which is available in dev mode only at http://localhost:8080/q/dev/. 15 | 16 | ## Packaging and running the application 17 | 18 | The application can be packaged using: 19 | ```shell script 20 | ./mvnw package 21 | ``` 22 | It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. 23 | Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. 24 | 25 | If you want to build an _über-jar_, execute the following command: 26 | ```shell script 27 | ./mvnw package -Dquarkus.package.type=uber-jar 28 | ``` 29 | 30 | The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. 31 | 32 | ## Creating a native executable 33 | 34 | You can create a native executable using: 35 | ```shell script 36 | ./mvnw package -Pnative 37 | ``` 38 | 39 | Or, if you don't have GraalVM installed, you can run the native executable build in a container using: 40 | ```shell script 41 | ./mvnw package -Pnative -Dquarkus.native.container-build=true 42 | ``` 43 | 44 | You can then execute your native executable with: `./target/code-with-quarkus-1.0.0-SNAPSHOT-runner` 45 | 46 | If you want to learn more about building native executables, please consult https://quarkus.io/guides/maven-tooling.html. 47 | 48 | ## Related guides 49 | 50 | - RESTEasy JAX-RS ([guide](https://quarkus.io/guides/rest-json)): REST endpoint framework implementing JAX-RS and more 51 | 52 | ## Provided examples 53 | 54 | ### RESTEasy JAX-RS example 55 | 56 | REST is easy peasy with this Hello World RESTEasy resource. 57 | 58 | [Related guide section...](https://quarkus.io/guides/getting-started#the-jax-rs-resources) 59 | 60 | ### RESTEasy JSON serialisation using Jackson 61 | 62 | This example demonstrate RESTEasy JSON serialisation by letting you list, add and remove quark types from a list. Quarked! 63 | 64 | [Related guide section...](https://quarkus.io/guides/rest-json#creating-your-first-json-rest-service) 65 | 66 | 67 | ## Curl commands 68 | ``` 69 | curl -H 'Content-Type:application/json' -v http://localhost:8080/players' 70 | curl -H 'Content-Type:application/json' -v -XPOST http://localhost:8080/players -d '{"name":"titi"}' 71 | curl -H 'Content-Type:application/json' -v -XPOST http://localhost:8080/games -d '{"gamedate":"2021-06-18"}' 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /server/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /server/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | fr.uggla 6 | planetoid-server 7 | 1.0.0-SNAPSHOT 8 | 9 | 3.10.1 10 | true 11 | 11 12 | 11 13 | UTF-8 14 | UTF-8 15 | quarkus-universe-bom 16 | io.quarkus 17 | 2.7.5.Final 18 | 3.0.0-M6 19 | 20 | 21 | 22 | 23 | ${quarkus.platform.group-id} 24 | ${quarkus.platform.artifact-id} 25 | ${quarkus.platform.version} 26 | pom 27 | import 28 | 29 | 30 | 31 | 32 | 33 | io.quarkus 34 | quarkus-hibernate-orm-panache 35 | 36 | 37 | io.quarkus 38 | quarkus-resteasy 39 | 40 | 41 | io.quarkus 42 | quarkus-resteasy-jackson 43 | 44 | 45 | io.quarkus 46 | quarkus-jdbc-postgresql 47 | 48 | 49 | io.quarkus 50 | quarkus-arc 51 | 52 | 53 | io.quarkus 54 | quarkus-junit5 55 | test 56 | 57 | 58 | io.rest-assured 59 | rest-assured 60 | test 61 | 62 | 63 | io.quarkus 64 | quarkus-hibernate-validator 65 | 66 | 67 | 68 | 69 | 70 | ${quarkus.platform.group-id} 71 | quarkus-maven-plugin 72 | ${quarkus.platform.version} 73 | true 74 | 75 | 76 | 77 | build 78 | generate-code 79 | generate-code-tests 80 | 81 | 82 | 83 | 84 | 85 | maven-compiler-plugin 86 | ${compiler-plugin.version} 87 | 88 | ${maven.compiler.parameters} 89 | 90 | 91 | 92 | maven-surefire-plugin 93 | ${surefire-plugin.version} 94 | 95 | 96 | org.jboss.logmanager.LogManager 97 | ${maven.home} 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | native 106 | 107 | 108 | native 109 | 110 | 111 | 112 | 113 | 114 | maven-failsafe-plugin 115 | ${surefire-plugin.version} 116 | 117 | 118 | 119 | integration-test 120 | verify 121 | 122 | 123 | 124 | ${project.build.directory}/${project.build.finalName}-runner 125 | org.jboss.logmanager.LogManager 126 | ${maven.home} 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | native 136 | 137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /server/src/main/java/fr/uggla/Game.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | 4 | import io.quarkus.hibernate.orm.panache.PanacheEntity; 5 | 6 | import javax.persistence.*; 7 | import java.util.Date; 8 | import java.util.HashSet; 9 | import java.util.Set; 10 | 11 | @Entity 12 | public class Game extends PanacheEntity { 13 | Date gamedate; 14 | @ManyToMany(cascade = { CascadeType.ALL }) 15 | @JoinTable( 16 | name = "Game_Player", 17 | joinColumns = { @JoinColumn(name = "game_id") }, 18 | inverseJoinColumns = { @JoinColumn(name = "player_id") } 19 | ) 20 | Set player = new HashSet<>(); 21 | } -------------------------------------------------------------------------------- /server/src/main/java/fr/uggla/Games.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | import io.quarkus.hibernate.orm.panache.PanacheQuery; 4 | 5 | import javax.transaction.Transactional; 6 | import javax.ws.rs.*; 7 | import javax.ws.rs.core.MediaType; 8 | import javax.ws.rs.core.Response; 9 | import java.util.Date; 10 | import java.util.List; 11 | import java.util.Set; 12 | import java.util.stream.Collectors; 13 | 14 | import org.jboss.logging.Logger; 15 | 16 | @Path("/games") 17 | @Produces(MediaType.APPLICATION_JSON) 18 | @Consumes(MediaType.APPLICATION_JSON) 19 | public class Games { 20 | private static final Logger LOG = Logger.getLogger(Games.class); 21 | 22 | @GET 23 | public Set games() { 24 | List allGames = Game.listAll(); 25 | return allGames.stream().map(game -> game.gamedate).collect(Collectors.toSet()); 26 | } 27 | 28 | @Transactional 29 | @POST 30 | public Response add(Game truc) { 31 | try { 32 | Game game = new Game(); 33 | game.gamedate = new Date(); 34 | PanacheQuery player2 = Game.find("from Player where name='titi'"); 35 | player2.page(io.quarkus.panache.common.Page.ofSize(25)); 36 | List firstPage = player2.list(); 37 | LOG.info(firstPage.get(0).name); 38 | game.player.add(firstPage.get(0)); 39 | game.persist(); 40 | return Response.ok(game).status(201).build(); 41 | } catch (Exception e) { 42 | LOG.error(e); 43 | return Response.serverError().build(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /server/src/main/java/fr/uggla/Player.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | 4 | import io.quarkus.hibernate.orm.panache.PanacheEntity; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.ManyToMany; 8 | import javax.validation.constraints.NotBlank; 9 | import java.util.HashSet; 10 | import java.util.Set; 11 | 12 | @Entity 13 | public class Player extends PanacheEntity { 14 | @NotBlank 15 | public String name; 16 | @ManyToMany(mappedBy = "player") 17 | private Set game = new HashSet<>(); 18 | } -------------------------------------------------------------------------------- /server/src/main/java/fr/uggla/Players.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | import javax.transaction.Transactional; 4 | import javax.ws.rs.*; 5 | import javax.ws.rs.core.MediaType; 6 | import javax.ws.rs.core.Response; 7 | import java.util.List; 8 | import java.util.Set; 9 | import java.util.stream.Collectors; 10 | 11 | 12 | @Path("/players") 13 | @Produces(MediaType.APPLICATION_JSON) 14 | @Consumes(MediaType.APPLICATION_JSON) 15 | public class Players { 16 | 17 | @GET 18 | public Set players() { 19 | List allPlayers = Player.listAll(); 20 | return allPlayers.stream().map(player -> player.name).collect(Collectors.toSet()); 21 | } 22 | 23 | @Transactional 24 | @POST 25 | public Response add(Player player) { 26 | try { 27 | player.persist(); 28 | return Response.ok(player).status(201).build(); 29 | } catch (Exception e) { 30 | return Response.serverError().build(); 31 | } 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /server/src/main/java/fr/uggla/resteasyjackson/JacksonResource.java: -------------------------------------------------------------------------------- 1 | package main.java.fr.uggla.resteasyjackson; 2 | 3 | import javax.ws.rs.*; 4 | import javax.ws.rs.core.MediaType; 5 | import java.util.Collections; 6 | import java.util.LinkedHashMap; 7 | import java.util.Set; 8 | 9 | @Path("/resteasy-jackson/quarks") 10 | @Produces(MediaType.APPLICATION_JSON) 11 | @Consumes(MediaType.APPLICATION_JSON) 12 | public class JacksonResource { 13 | 14 | private final Set quarks = Collections.newSetFromMap(Collections.synchronizedMap(new LinkedHashMap<>())); 15 | 16 | public JacksonResource() { 17 | quarks.add(new Quark("Up", "The up quark or u quark (symbol: u) is the lightest of all quarks, a type of elementary particle, and a major constituent of matter.")); 18 | quarks.add(new Quark("Strange", "The strange quark or s quark (from its symbol, s) is the third lightest of all quarks, a type of elementary particle.")); 19 | quarks.add(new Quark("Charm", "The charm quark, charmed quark or c quark (from its symbol, c) is the third most massive of all quarks, a type of elementary particle.")); 20 | quarks.add(new Quark("???", null)); 21 | } 22 | 23 | @GET 24 | public Set list() { 25 | return quarks; 26 | } 27 | 28 | @POST 29 | public Set add(Quark quark) { 30 | quarks.add(quark); 31 | return quarks; 32 | } 33 | 34 | @DELETE 35 | public Set delete(Quark quark) { 36 | quarks.removeIf(existingQuark -> existingQuark.name.contentEquals(quark.name)); 37 | return quarks; 38 | } 39 | 40 | public static class Quark { 41 | public String name; 42 | public String description; 43 | 44 | public Quark() { 45 | } 46 | 47 | public Quark(String name, String description) { 48 | this.name = name; 49 | this.description = description; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /server/src/main/java/fr/uggla/resteasyjackson/MyObjectMapperCustomizer.java: -------------------------------------------------------------------------------- 1 | package main.java.fr.uggla.resteasyjackson; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import io.quarkus.jackson.ObjectMapperCustomizer; 6 | 7 | import javax.inject.Singleton; 8 | 9 | @Singleton 10 | public class MyObjectMapperCustomizer implements ObjectMapperCustomizer { 11 | 12 | @Override 13 | public void customize(ObjectMapper objectMapper) { 14 | // To suppress serializing properties with null values 15 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /server/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | quarkus.datasource.db-kind = postgresql 2 | quarkus.datasource.username = planetoid 3 | quarkus.datasource.password = planetoid 4 | 5 | quarkus.hibernate-orm.database.generation=drop-and-create 6 | #quarkus.http.test-port=52697 7 | 8 | quarkus.datasource.devservices=true 9 | quarkus.datasource.devservices.image-name=postgres:13.2 10 | -------------------------------------------------------------------------------- /server/src/main/resources/import.sql: -------------------------------------------------------------------------------- 1 | insert into player values 2 | (1,'Planetoid'), 3 | (2,'Uggla'), 4 | (3,'Rose'); 5 | 6 | alter sequence hibernate_sequence restart with 4; -------------------------------------------------------------------------------- /server/src/test/java/fr/uggla/NativePlayersIT.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | import io.quarkus.test.junit.NativeImageTest; 4 | 5 | @NativeImageTest 6 | public class NativePlayersIT extends PlayersTest { 7 | 8 | // Execute the same tests but in native mode. 9 | } -------------------------------------------------------------------------------- /server/src/test/java/fr/uggla/PlayersTest.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | import io.quarkus.test.junit.QuarkusTest; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import static io.restassured.RestAssured.given; 7 | import static org.hamcrest.CoreMatchers.is; 8 | 9 | @QuarkusTest 10 | public class PlayersTest { 11 | 12 | @Test 13 | public void testPlayersEndpoint() { 14 | given() 15 | .when().get("/players") 16 | .then() 17 | .statusCode(200) 18 | .body(is("[\"Uggla\",\"Rose\",\"Planetoid\"]")); 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /worker/.dockerignore: -------------------------------------------------------------------------------- 1 | * 2 | !target/*-runner 3 | !target/*-runner.jar 4 | !target/lib/* 5 | !target/quarkus-app/* -------------------------------------------------------------------------------- /worker/.gitignore: -------------------------------------------------------------------------------- 1 | #Maven 2 | target/ 3 | pom.xml.tag 4 | pom.xml.releaseBackup 5 | pom.xml.versionsBackup 6 | release.properties 7 | 8 | # Eclipse 9 | .project 10 | .classpath 11 | .settings/ 12 | bin/ 13 | 14 | # IntelliJ 15 | .idea 16 | *.ipr 17 | *.iml 18 | *.iws 19 | 20 | # NetBeans 21 | nb-configuration.xml 22 | 23 | # Visual Studio Code 24 | .vscode 25 | .factorypath 26 | 27 | # OSX 28 | .DS_Store 29 | 30 | # Vim 31 | *.swp 32 | *.swo 33 | 34 | # patch 35 | *.orig 36 | *.rej 37 | 38 | # Local environment 39 | .env 40 | -------------------------------------------------------------------------------- /worker/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /worker/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /worker/README.md: -------------------------------------------------------------------------------- 1 | # planetoid project 2 | 3 | This project uses Quarkus, the Supersonic Subatomic Java Framework. 4 | 5 | If you want to learn more about Quarkus, please visit its website: https://quarkus.io/ . 6 | 7 | ## Running the application in dev mode 8 | 9 | You can run your application in dev mode that enables live coding using: 10 | ```shell script 11 | ./mvnw compile quarkus:dev 12 | ``` 13 | 14 | > **_NOTE:_** Quarkus now ships with a Dev UI, which is available in dev mode only at http://localhost:8080/q/dev/. 15 | 16 | ## Packaging and running the application 17 | 18 | The application can be packaged using: 19 | ```shell script 20 | ./mvnw package 21 | ``` 22 | It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. 23 | Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. 24 | 25 | If you want to build an _über-jar_, execute the following command: 26 | ```shell script 27 | ./mvnw package -Dquarkus.package.type=uber-jar 28 | ``` 29 | 30 | The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. 31 | 32 | ## Creating a native executable 33 | 34 | You can create a native executable using: 35 | ```shell script 36 | ./mvnw package -Pnative 37 | ``` 38 | 39 | Or, if you don't have GraalVM installed, you can run the native executable build in a container using: 40 | ```shell script 41 | ./mvnw package -Pnative -Dquarkus.native.container-build=true 42 | ``` 43 | 44 | You can then execute your native executable with: `./target/planetoid-1.0.0-SNAPSHOT-runner` 45 | 46 | If you want to learn more about building native executables, please consult https://quarkus.io/guides/maven-tooling.html. 47 | 48 | ## Related guides 49 | 50 | - WebSockets ([guide](https://quarkus.io/guides/websockets)): WebSocket communication channel support 51 | - RESTEasy JAX-RS ([guide](https://quarkus.io/guides/rest-json)): REST endpoint framework implementing JAX-RS and more 52 | 53 | ## Provided examples 54 | 55 | ### RESTEasy JAX-RS example 56 | 57 | REST is easy peasy with this Hello World RESTEasy resource. 58 | 59 | [Related guide section...](https://quarkus.io/guides/getting-started#the-jax-rs-resources) 60 | 61 | ### RESTEasy JSON serialisation using Jackson 62 | 63 | This example demonstrate RESTEasy JSON serialisation by letting you list, add and remove quark types from a list. Quarked! 64 | 65 | [Related guide section...](https://quarkus.io/guides/rest-json#creating-your-first-json-rest-service) 66 | 67 | ### WebSockets example using Undertow 68 | 69 | Discover WebSockets using Undertow with this cool supersonic chat example. Open multiple tabs to simulate different users. 70 | 71 | [Related guide section...](https://quarkus.io/guides/websockets) 72 | -------------------------------------------------------------------------------- /worker/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /worker/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /worker/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | fr.uggla 6 | planetoid-worker 7 | 1.0.0-SNAPSHOT 8 | 9 | 3.10.1 10 | true 11 | 11 12 | 11 13 | UTF-8 14 | UTF-8 15 | quarkus-universe-bom 16 | io.quarkus 17 | 2.7.5.Final 18 | 3.0.0-M6 19 | 20 | 21 | 22 | 23 | ${quarkus.platform.group-id} 24 | ${quarkus.platform.artifact-id} 25 | ${quarkus.platform.version} 26 | pom 27 | import 28 | 29 | 30 | 31 | 32 | 33 | io.quarkus 34 | quarkus-websockets 35 | 36 | 37 | io.quarkus 38 | quarkus-resteasy 39 | 40 | 41 | io.quarkus 42 | quarkus-resteasy-jackson 43 | 44 | 45 | io.quarkus 46 | quarkus-arc 47 | 48 | 49 | io.quarkus 50 | quarkus-undertow-websockets 51 | 52 | 53 | io.quarkus 54 | quarkus-junit5 55 | test 56 | 57 | 58 | io.rest-assured 59 | rest-assured 60 | test 61 | 62 | 63 | 64 | 65 | 66 | ${quarkus.platform.group-id} 67 | quarkus-maven-plugin 68 | ${quarkus.platform.version} 69 | true 70 | 71 | 72 | 73 | build 74 | generate-code 75 | generate-code-tests 76 | 77 | 78 | 79 | 80 | 81 | maven-compiler-plugin 82 | ${compiler-plugin.version} 83 | 84 | ${maven.compiler.parameters} 85 | 86 | 87 | 88 | maven-surefire-plugin 89 | ${surefire-plugin.version} 90 | 91 | 92 | org.jboss.logmanager.LogManager 93 | ${maven.home} 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | native 102 | 103 | 104 | native 105 | 106 | 107 | 108 | 109 | 110 | maven-failsafe-plugin 111 | ${surefire-plugin.version} 112 | 113 | 114 | 115 | integration-test 116 | verify 117 | 118 | 119 | 120 | ${project.build.directory}/${project.build.finalName}-runner 121 | org.jboss.logmanager.LogManager 122 | ${maven.home} 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | native 132 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /worker/src/main/docker/Dockerfile.jvm: -------------------------------------------------------------------------------- 1 | #### 2 | # This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode 3 | # 4 | # Before building the container image run: 5 | # 6 | # ./mvnw package 7 | # 8 | # Then, build the image with: 9 | # 10 | # docker build -f src/fr/docker/Dockerfile.jvm -t quarkus/planetoid-jvm . 11 | # 12 | # Then run the container using: 13 | # 14 | # docker run -i --rm -p 8080:8080 quarkus/planetoid-jvm 15 | # 16 | # If you want to include the debug port into your docker image 17 | # you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 18 | # 19 | # Then run the container using : 20 | # 21 | # docker run -i --rm -p 8080:8080 -p 5005:5005 -e JAVA_ENABLE_DEBUG="true" quarkus/planetoid-jvm 22 | # 23 | ### 24 | FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3 25 | 26 | ARG JAVA_PACKAGE=java-11-openjdk-headless 27 | ARG RUN_JAVA_VERSION=1.3.8 28 | ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' 29 | # Install java and the run-java script 30 | # Also set up permissions for user `1001` 31 | RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \ 32 | && microdnf update \ 33 | && microdnf clean all \ 34 | && mkdir /deployments \ 35 | && chown 1001 /deployments \ 36 | && chmod "g+rwX" /deployments \ 37 | && chown 1001:root /deployments \ 38 | && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \ 39 | && chown 1001 /deployments/run-java.sh \ 40 | && chmod 540 /deployments/run-java.sh \ 41 | && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/conf/security/java.security 42 | 43 | # Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. 44 | ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" 45 | # We make four distinct layers so if there are application changes the library layers can be re-used 46 | COPY --chown=1001 target/quarkus-app/lib/ /deployments/lib/ 47 | COPY --chown=1001 target/quarkus-app/*.jar /deployments/ 48 | COPY --chown=1001 target/quarkus-app/app/ /deployments/app/ 49 | COPY --chown=1001 target/quarkus-app/quarkus/ /deployments/quarkus/ 50 | 51 | EXPOSE 8080 52 | USER 1001 53 | 54 | ENTRYPOINT [ "/deployments/run-java.sh" ] 55 | -------------------------------------------------------------------------------- /worker/src/main/docker/Dockerfile.legacy-jar: -------------------------------------------------------------------------------- 1 | #### 2 | # This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode 3 | # 4 | # Before building the container image run: 5 | # 6 | # ./mvnw package -Dquarkus.package.type=legacy-jar 7 | # 8 | # Then, build the image with: 9 | # 10 | # docker build -f src/fr/docker/Dockerfile.legacy-jar -t quarkus/planetoid-legacy-jar . 11 | # 12 | # Then run the container using: 13 | # 14 | # docker run -i --rm -p 8080:8080 quarkus/planetoid-legacy-jar 15 | # 16 | # If you want to include the debug port into your docker image 17 | # you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 18 | # 19 | # Then run the container using : 20 | # 21 | # docker run -i --rm -p 8080:8080 -p 5005:5005 -e JAVA_ENABLE_DEBUG="true" quarkus/planetoid-legacy-jar 22 | # 23 | ### 24 | FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3 25 | 26 | ARG JAVA_PACKAGE=java-11-openjdk-headless 27 | ARG RUN_JAVA_VERSION=1.3.8 28 | ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' 29 | # Install java and the run-java script 30 | # Also set up permissions for user `1001` 31 | RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \ 32 | && microdnf update \ 33 | && microdnf clean all \ 34 | && mkdir /deployments \ 35 | && chown 1001 /deployments \ 36 | && chmod "g+rwX" /deployments \ 37 | && chown 1001:root /deployments \ 38 | && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \ 39 | && chown 1001 /deployments/run-java.sh \ 40 | && chmod 540 /deployments/run-java.sh \ 41 | && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/conf/security/java.security 42 | 43 | # Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. 44 | ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" 45 | COPY target/lib/* /deployments/lib/ 46 | COPY target/*-runner.jar /deployments/app.jar 47 | 48 | EXPOSE 8080 49 | USER 1001 50 | 51 | ENTRYPOINT [ "/deployments/run-java.sh" ] 52 | -------------------------------------------------------------------------------- /worker/src/main/docker/Dockerfile.native: -------------------------------------------------------------------------------- 1 | #### 2 | # This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode 3 | # 4 | # Before building the container image run: 5 | # 6 | # ./mvnw package -Pnative 7 | # 8 | # Then, build the image with: 9 | # 10 | # docker build -f src/fr/docker/Dockerfile.native -t quarkus/planetoid . 11 | # 12 | # Then run the container using: 13 | # 14 | # docker run -i --rm -p 8080:8080 quarkus/planetoid 15 | # 16 | ### 17 | FROM registry.access.redhat.com/ubi8/ubi-minimal:8.3 18 | WORKDIR /work/ 19 | RUN chown 1001 /work \ 20 | && chmod "g+rwX" /work \ 21 | && chown 1001:root /work 22 | COPY --chown=1001:root target/*-runner /work/application 23 | 24 | EXPOSE 8080 25 | USER 1001 26 | 27 | CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] 28 | -------------------------------------------------------------------------------- /worker/src/main/docker/Dockerfile.native-distroless: -------------------------------------------------------------------------------- 1 | #### 2 | # This Dockerfile is used in order to build a distroless container that runs the Quarkus application in native (no JVM) mode 3 | # 4 | # Before building the container image run: 5 | # 6 | # ./mvnw package -Pnative 7 | # 8 | # Then, build the image with: 9 | # 10 | # docker build -f src/fr/docker/Dockerfile.native-distroless -t quarkus/planetoid . 11 | # 12 | # Then run the container using: 13 | # 14 | # docker run -i --rm -p 8080:8080 quarkus/planetoid 15 | # 16 | ### 17 | FROM quay.io/quarkus/quarkus-distroless-image:1.0 18 | COPY target/*-runner /application 19 | 20 | EXPOSE 8080 21 | USER nonroot 22 | 23 | CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] 24 | -------------------------------------------------------------------------------- /worker/src/main/java/fr/uggla/GameData.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.charset.StandardCharsets; 5 | import java.util.Map; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | import javax.enterprise.context.ApplicationScoped; 9 | import javax.websocket.OnClose; 10 | import javax.websocket.OnError; 11 | import javax.websocket.OnMessage; 12 | import javax.websocket.OnOpen; 13 | import javax.websocket.server.PathParam; 14 | import javax.websocket.server.ServerEndpoint; 15 | import javax.websocket.Session; 16 | 17 | @ServerEndpoint("/gamedata/{username}") 18 | @ApplicationScoped 19 | public class GameData { 20 | 21 | Map sessions = new ConcurrentHashMap<>(); 22 | 23 | @OnOpen 24 | public void onOpen(Session session, @PathParam("username") String username) { 25 | sessions.put(username, session); 26 | broadcast("User " + username + " joined"); 27 | } 28 | 29 | @OnClose 30 | public void onClose(Session session, @PathParam("username") String username) { 31 | sessions.remove(username); 32 | } 33 | 34 | @OnError 35 | public void onError(Session session, @PathParam("username") String username, Throwable throwable) { 36 | sessions.remove(username); 37 | broadcast("User " + username + " left on error: " + throwable); 38 | } 39 | 40 | // Example using binary message 41 | // @OnMessage 42 | // public void onMessage(ByteBuffer message, @PathParam("username") String username) { 43 | // String msg = StandardCharsets.UTF_8.decode(message).toString(); 44 | // System.out.println("Received msg:" + msg ); 45 | // broadcast(">> " + username + ": " + msg); 46 | // } 47 | @OnMessage 48 | public void onMessage(String message, @PathParam("username") String username) { 49 | System.out.println("Received msg:" + message); 50 | // broadcast(">> " + username + ": " + message); 51 | broadcast(message); 52 | } 53 | 54 | private void broadcast(String message) { 55 | sessions.values().forEach(s -> { 56 | s.getAsyncRemote().sendObject(message, result -> { 57 | if (result.getException() != null) { 58 | System.out.println("Unable to send message: " + result.getException()); 59 | } 60 | }); 61 | }); 62 | } 63 | } -------------------------------------------------------------------------------- /worker/src/main/java/fr/uggla/Planetoid.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | import javax.ws.rs.GET; 4 | import javax.ws.rs.Path; 5 | import javax.ws.rs.Produces; 6 | import javax.ws.rs.core.MediaType; 7 | 8 | @Path("/hello") 9 | public class Planetoid { 10 | 11 | @GET 12 | @Produces(MediaType.TEXT_PLAIN) 13 | public String hello() { 14 | return "Hello this is Planetoid !"; 15 | } 16 | } -------------------------------------------------------------------------------- /worker/src/main/resources/META-INF/resources/chat.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Quarkus Supersonic Chat! 7 | 8 | 9 | 10 | 18 | 19 | 20 | 21 | 28 |
29 |
30 |
31 | 32 | 33 |
34 |
35 |
36 |
37 | 39 |
40 |
41 | 42 | 43 |
44 | 45 |
46 | 47 | 48 | 49 | 50 | 51 | 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /worker/src/main/resources/META-INF/resources/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | planetoid - 1.0.0-SNAPSHOT 6 | 108 | 109 | 110 | 111 | 114 | 115 |
116 |
117 |

Congratulations, you have created a new Quarkus cloud application.

118 | 119 |

What is this page?

120 | 121 |

This page is served by Quarkus. The source is in 122 | src/fr/resources/META-INF/resources/index.html.

123 | 124 |

What are your next steps?

125 | 126 |

If not already done, run the application in dev mode using: ./mvnw compile quarkus:dev. 127 |

128 |
    129 |
  • Your static assets are located in src/fr/resources/META-INF/resources.
  • 130 |
  • Configure your application in src/fr/resources/application.properties.
  • 131 |
  • Quarkus now ships with a Dev UI (available in dev mode only)
  • 132 |
  • Play with the getting started example code located in src/fr/java:
  • 133 |
134 |
135 |

RESTEasy JAX-RS example

136 |

REST is easy peasy with this Hello World RESTEasy resource.

137 |

@Path: /hello

138 |

Related guide section...

139 |
140 |
141 |

RESTEasy JSON serialisation using Jackson

142 |

This example demonstrate RESTEasy JSON serialisation by letting you list, add and remove quark types from a list. Quarked!

143 |

@Path: /resteasy-jackson/quarks/

144 |

Related guide section...

145 |
146 |
147 |

WebSockets example using Undertow

148 |

Discover WebSockets using Undertow with this cool supersonic chat example. Open multiple tabs to simulate different users.

149 |

@Path: /supersonic-chat.html

150 |

Related guide section...

151 |
152 | 153 |
154 |
155 |
156 |

Application

157 |
    158 |
  • GroupId: fr.uggla
  • 159 |
  • ArtifactId: planetoid
  • 160 |
  • Version: 1.0.0-SNAPSHOT
  • 161 |
  • Quarkus Version: 1.13.3.Final
  • 162 |
163 |
164 |
165 |

Do you like Quarkus?

166 |
    167 |
  • Go give it a star on GitHub.
  • 168 |
169 |
170 |
171 |

Selected extensions guides

172 | 176 |
177 |
178 |

More reading

179 | 185 |
186 |
187 |
188 | 189 | -------------------------------------------------------------------------------- /worker/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uggla/planetoid/639ab82fa42caa79c5da3f2189f1dbacd9d20c53/worker/src/main/resources/application.properties -------------------------------------------------------------------------------- /worker/src/test/java/fr/uggla/NativeplanetoidIT.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | import io.quarkus.test.junit.NativeImageTest; 4 | 5 | @NativeImageTest 6 | public class NativeplanetoidIT extends PlanetoidTest { 7 | 8 | // Execute the same tests but in native mode. 9 | } -------------------------------------------------------------------------------- /worker/src/test/java/fr/uggla/PlanetoidTest.java: -------------------------------------------------------------------------------- 1 | package fr.uggla; 2 | 3 | import io.quarkus.test.junit.QuarkusTest; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import static io.restassured.RestAssured.given; 7 | import static org.hamcrest.CoreMatchers.is; 8 | 9 | @QuarkusTest 10 | public class PlanetoidTest { 11 | 12 | @Test 13 | public void testHelloEndpoint() { 14 | given() 15 | .when().get("/hello") 16 | .then() 17 | .statusCode(200) 18 | .body(is("Hello this is Planetoid !")); 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /worker/src/test/java/fr/uggla/undertowwebsockets/GameDataSocketTest.java: -------------------------------------------------------------------------------- 1 | package fr.uggla.undertowwebsockets; 2 | 3 | import java.net.URI; 4 | import java.util.concurrent.LinkedBlockingDeque; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | import javax.websocket.ClientEndpoint; 8 | import javax.websocket.ContainerProvider; 9 | import javax.websocket.OnMessage; 10 | import javax.websocket.OnOpen; 11 | import javax.websocket.Session; 12 | 13 | import org.junit.jupiter.api.Assertions; 14 | import org.junit.jupiter.api.Test; 15 | 16 | import io.quarkus.test.common.http.TestHTTPResource; 17 | import io.quarkus.test.junit.QuarkusTest; 18 | 19 | @QuarkusTest 20 | public class GameDataSocketTest { 21 | 22 | private static final LinkedBlockingDeque MESSAGES = new LinkedBlockingDeque<>(); 23 | 24 | @TestHTTPResource("/gamedata/planetoid_host") 25 | URI uri; 26 | 27 | @Test 28 | public void testWebsocketGameData() throws Exception { 29 | try (Session session = ContainerProvider.getWebSocketContainer().connectToServer(Client.class, uri)) { 30 | Assertions.assertEquals("CONNECT", MESSAGES.poll(10, TimeUnit.SECONDS)); 31 | Assertions.assertEquals("User planetoid_host joined", MESSAGES.poll(10, TimeUnit.SECONDS)); 32 | Assertions.assertEquals("_ready_", MESSAGES.poll(10, TimeUnit.SECONDS)); 33 | session.getAsyncRemote().sendText("hello world"); 34 | Assertions.assertEquals("hello world", MESSAGES.poll(10, TimeUnit.SECONDS)); 35 | } 36 | } 37 | 38 | @ClientEndpoint 39 | public static class Client { 40 | 41 | @OnOpen 42 | public void open(Session session) { 43 | MESSAGES.add("CONNECT"); 44 | // Send a message to indicate that we are ready, 45 | // as the message handler may not be registered immediately after this callback. 46 | session.getAsyncRemote().sendText("_ready_"); 47 | } 48 | 49 | @OnMessage 50 | void message(String msg) { 51 | MESSAGES.add(msg); 52 | } 53 | 54 | } 55 | 56 | } 57 | --------------------------------------------------------------------------------