Portage Lost Sector 2026 : jeu + moteur Dethsquare + back-end Android fusionnés en un dépôt unique
- Build modernisé : Gradle 9.9.1 / JDK 21 / LWJGL 3.3.6 (ex Gradle 3.5-rc-2 / JDK 8 / LWJGL 3.1.2) - Back-end Android complet : rendu GLES 3.0, audio SoundPool+MediaPlayer, IO assets, launcher GLSurfaceView, HUD de contrôles tactiles (TouchControls) - Logging multi-plateforme GameLog (LS-*) - Corrections : contexte GL 3.2 core (macOS), fuites core->desktop, Input Android, TMX via AssetManager, JSONException, purge tags destroyAll, reload DefenseMission - README + TODO (roadmap reconstruite depuis le Trello et les dépôts de l'org amont) Sources amont : github.com/8-Bit-Warframe (dépôts du 2017, abandonnés)
This commit is contained in:
commit
7af74680e9
78
.gitignore
vendored
Normal file
78
.gitignore
vendored
Normal file
@ -0,0 +1,78 @@
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### JetBrains template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff:
|
||||
.idea/workspace.xml
|
||||
.idea/tasks.xml
|
||||
.idea/dictionaries
|
||||
.idea/vcs.xml
|
||||
.idea/jsLibraryMappings.xml
|
||||
|
||||
# Sensitive or high-churn files:
|
||||
.idea/dataSources.ids
|
||||
.idea/dataSources.xml
|
||||
.idea/dataSources.local.xml
|
||||
.idea/sqlDataSources.xml
|
||||
.idea/dynamic.xml
|
||||
.idea/uiDesigner.xml
|
||||
|
||||
# Gradle:
|
||||
.idea/gradle.xml
|
||||
.idea/libraries
|
||||
|
||||
# Mongo Explorer plugin:
|
||||
.idea/mongoSettings.xml
|
||||
|
||||
## File-based project format:
|
||||
*.iws
|
||||
|
||||
## Plugin-specific files:
|
||||
|
||||
# IntelliJ
|
||||
/out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
### Java template
|
||||
*.class
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
### Gradle template
|
||||
.gradle
|
||||
build/
|
||||
|
||||
# Ignore Gradle GUI config
|
||||
gradle-app.setting
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
|
||||
# Cache of project
|
||||
.gradletasknamecache
|
||||
|
||||
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
|
||||
# gradle/wrapper/gradle-wrapper.properties
|
||||
|
||||
gradle.properties
|
||||
local.properties
|
||||
.DS_Store
|
||||
150
README.md
Normal file
150
README.md
Normal file
@ -0,0 +1,150 @@
|
||||
# Lost Sector — Portage moderne (desktop 2026 + Android)
|
||||
|
||||
[](#) [](#) [](#)
|
||||
|
||||
Portage du jeu open source **Lost Sector** (ARPG/platformer rétro fan-made de
|
||||
Warframe, abandonné fin 2017 par l'équipe 8-Bit Warframe) vers l'écosystème
|
||||
moderne : **Gradle 9 / JDK 21 / LWJGL 3.3** côté desktop, et un **back-end
|
||||
Android complet** (OpenGL ES 3.0 + contrôles tactiles) construit sur
|
||||
l'abstraction plateforme du moteur Dethsquare — restée inachevée chez les
|
||||
développeurs d'origine.
|
||||
|
||||
Dépôt unique : le jeu (`lost-sector/`), le moteur (`dethsquare/`) et
|
||||
l'application Android (`android-app/`) sont fusionnés ici (à l'origine trois
|
||||
dépôts GitHub séparés reliés par des submodules). Sources amont :
|
||||
`github.com/8-Bit-Warframe/{Lost-Sector, Dethsquare-Engine, Lost-Sector-desktop}`.
|
||||
|
||||
## Fonctionnalités
|
||||
|
||||
| Fonctionnalité | Desktop | Android | État |
|
||||
|---|---|---|---|
|
||||
| Menu principal / Settings / Quit | ✅ | ✅ | Testé |
|
||||
| Mission Défense (cryopods, vagues, Director) | ✅ | ✅ | Testé, 2 missions d'affilée sans crash |
|
||||
| Menu Settings + persistance audio | ✅ | ✅ SharedPreferences | Testé sur émulateur |
|
||||
| HUD de contrôles tactiles (A/D, JUMP, pause) | — | ✅ | Testé sur émulateur |
|
||||
| Rendu | OpenGL 3.2 core (macOS/Linux/Win) | OpenGL ES 3.0 | |
|
||||
| Audio | OpenAL (LWJGL) | SoundPool + MediaPlayer | Musique en boucle : TODO |
|
||||
| Génération procédurale / Survival / Exterminate | ✅ code | non testé | |
|
||||
| Multiplayer | code présent, serveurs morts | idem | voir TODO.md |
|
||||
|
||||
## Installation
|
||||
|
||||
### Desktop (macOS/Linux/Windows)
|
||||
|
||||
Prérequis : JDK 21 (toolchain Gradle).
|
||||
|
||||
```bash
|
||||
git clone git@gitea.cloudyfy.fr:Siphonight/lost-sector-port.git
|
||||
cd lost-sector-port
|
||||
./gradlew run # lance le jeu (fenêtre plein écran)
|
||||
./gradlew installDist # distribuable : build/install/LostSector/bin/LostSector
|
||||
```
|
||||
|
||||
macOS : l'argument JVM `-XstartOnFirstThread` est ajouté automatiquement par le
|
||||
build (exigence GLFW).
|
||||
|
||||
### Android
|
||||
|
||||
Prérequis : SDK Android (AGP 9.5.1, compileSdk 36), `local.properties` pointant
|
||||
vers le SDK (`sdk.dir=...`, non versionné).
|
||||
|
||||
```bash
|
||||
./gradlew :android-app:assembleDebug
|
||||
adb install -r android-app/build/outputs/apk/debug/android-app-debug.apk
|
||||
adb shell am start -n fr.siphonight.lostsectorport/com.ezardlabs.lostsector.AndroidGameActivity
|
||||
```
|
||||
|
||||
Émulateur recommandé : image système `arm64-v8a` (Macs Apple Silicon) avec
|
||||
`-gpu host`.
|
||||
|
||||
## Désinstallation / retour arrière
|
||||
|
||||
- **Desktop** : supprimer le dossier du dépôt et les préférences créées par le
|
||||
jeu (PlayerPrefs JVM).
|
||||
- **Android** : `adb uninstall fr.siphonight.lostsectorport`.
|
||||
- **Code amont** : les sources d'origine restent sur
|
||||
`github.com/8-Bit-Warframe` ; l'historique complet des dépôts séparés y est
|
||||
conservé (ce dépôt fusionne le contenu au moment du portage, branche
|
||||
`android-port` de chaque dépôt amont).
|
||||
|
||||
## Utilisation
|
||||
|
||||
- **Desktop** : A/D = déplacement, ESPACE = saut (×2), clic gauche = mélée,
|
||||
clic droit = tir, touches 1-3 = pouvoirs de Frost, F1-F3 = changer d'arme
|
||||
(triche d'origine), ÉCHAP = menu.
|
||||
- **Android (HUD tactile)** :
|
||||
- boutons **A** / **D** (bas gauche) = déplacement ;
|
||||
- bouton **JUMP** (droite) = saut / double saut ;
|
||||
- bouton **II** (haut gauche) = menu en jeu (ÉCHAP) ;
|
||||
- toucher **n'importe où ailleurs** = clic maintenu (mélée en jeu,
|
||||
sélection dans les menus).
|
||||
|
||||
## Configuration
|
||||
|
||||
| Clé | Où | Défaut | Effet |
|
||||
|---|---|---|---|
|
||||
| `platform` | `gradle.properties` | `desktop` | Back-end du moteur pour le build JVM (`desktop`\|`android`) |
|
||||
| `sdk.dir` | `local.properties` | — | Chemin du SDK Android (machine-spécifique, gitignoré) |
|
||||
| `audio_master_volume` etc. | Android SharedPreferences | 5 (échelle 0-15) | Volumes modifiables dans le jeu, persistés |
|
||||
| PlayerPrefs (desktop) | implémentation JVM | 5 | mêmes clés |
|
||||
|
||||
## Architecture technique
|
||||
|
||||
```
|
||||
lost-sector-port/
|
||||
├── lost-sector/ code du jeu (~7 000 lignes Java 8, ex-submodule)
|
||||
├── dethsquare/ moteur 2D custom "Unity-like" (ex-submodule)
|
||||
│ ├── base/ abstractions (Launcher, GameLog, interfaces *Utils)
|
||||
│ ├── core/ moteur (GameObject/Collider/Renderer/TMX/réseau)
|
||||
│ ├── desktop/ back-end LWJGL 3.3 (GLFW + GL 3.2 core + OpenAL)
|
||||
│ └── android/ back-end Android (GLES 3.0 + SoundPool/MediaPlayer)
|
||||
├── android-app/ application AGP 9 : compile jeu+moteur+backend en 1 APK
|
||||
│ (srcDirs pointant vers les paquets ci-dessus,
|
||||
│ assets = ressources du jeu)
|
||||
└── src/ launcher desktop (com.ezardlabs.lostsector.Main)
|
||||
```
|
||||
|
||||
Points d'ancrage du portage (patch → cible) :
|
||||
|
||||
| Patch | Cible | Consommateurs |
|
||||
|---|---|---|
|
||||
| Contexte GL 3.2 core | `DesktopLauncher` ctor | tout rendu desktop (macOS sinon contexte 2.1) |
|
||||
| `Screen.setCursorVisible` via `RenderUtils` | `core/Screen`, `RenderUtils`, `DesktopRenderUtils` | supprime la fuite core→desktop (bloquait tout build Android) |
|
||||
| `Debug` no-op neutre | `core/debug/Debug` | debug visuel (ex-GL11 immédiat, incompatible core/GLES) |
|
||||
| `Input.update()` : Android traite touches **et** touches virtuelles | `core/Input` | contrôles tactiles |
|
||||
| `Input.injectKeyDown/injectKeyUp` | `core/Input` | TouchControls (touches virtuelles) |
|
||||
| `TMXLoader` via `Dethsquare.IO` | `core/tmx/TMXLoader` | chargement des maps sur Android (assets ∉ classpath) |
|
||||
| `JSONException` catché | `Animations`, `Material`, `Matchmaker*`, `Layers` | org.json checked (Android) vs unchecked (Maven) |
|
||||
| Guards `calculateMatrices` | 2 back-ends render | évite GL_INVALID_OPERATION avant init shader |
|
||||
| `destroyAll()` purge `tags` | `core/GameObject` | fuite d'état inter-niveaux (cryopods fantômes) |
|
||||
| `DefenseMission.load()` recrée `director` | jeu | crash au 2ᵉ chargement de mission (bug upstream) |
|
||||
| HUD tactile | `lost-sector/.../hud/TouchControls` | Android uniquement (attaché en 1ᵉʳ de chaque niveau) |
|
||||
|
||||
## Maintenance
|
||||
|
||||
- **Regénérer les index de ressources** (`files.lsd`, requis pour lister les
|
||||
assets) : automatique à chaque build via la tâche `:lost-sector:indexResources`
|
||||
(câblée sur `processResources` desktop et `mergeAssets` Android).
|
||||
- **Vérifier le bon fonctionnement** :
|
||||
- desktop : `./gradlew run` → menu → Play → mission visible ;
|
||||
- Android : `adb logcat -s LS-INIT LS-LEVEL LS-MAP LS-MISSION LS-INPUT LS-AUDIO LS-RENDER LS-PREFAB`
|
||||
→ séquence `Dethsquare init` → `game.create() done` → `Level 'defense' fully loaded`.
|
||||
- **Dépannage** :
|
||||
- *écran noir Android sans crash* : vérifier que l'Activity appelle bien
|
||||
`launcher.launch(new Game())` (sinon `onDrawFrame` ne fait rien) ;
|
||||
- *crash `No context is current`* au premier rendu desktop : contexte legacy
|
||||
→ vérifier les window hints GL 3.2 core ;
|
||||
- *NPE `Map.getWidth()`* : TMX non trouvé → assets/index `files.lsd` ;
|
||||
- *émulateur qui meurt* : "Guest Angle unstable" API ≥ 36 — relancer,
|
||||
éventuellement `-gpu swiftshader_indirect`.
|
||||
- **Points d'ancrage à revérifier** après mise à jour du moteur : les patches
|
||||
listés ci-dessus (grep `GameLog`, `RenderUtils`, `Dethsquare.IO`,
|
||||
`TouchControls.attach`).
|
||||
|
||||
## Limitations connues (phase 1)
|
||||
|
||||
- Musique Android : boucle non fiable (`setLoop` après `play` ignoré) — TODO.
|
||||
- Sprites du HUD tactile génériques (rectangles translucides) — TODO sprites dédiés.
|
||||
- Debug graphics non rendus (ex-GL11 immédiat, à refaire en batch).
|
||||
- Multiplayer inopérant (serveurs d'origine éteints — voir TODO.md).
|
||||
- Aucune licence en amont : port perso OK, publication à négocier.
|
||||
127
TODO.md
Normal file
127
TODO.md
Normal file
@ -0,0 +1,127 @@
|
||||
# TODO — Portage Lost Sector & reprise des chantiers d'origine
|
||||
|
||||
Feuille de route consolidée : **①** la roadmap Trello originale de l'équipe
|
||||
(2017-2018, reconstruite depuis l'export JSON du board), **②** ce que révèlent
|
||||
les autres dépôts de l'org GitHub (Server, Matchmaking-Server, Website,
|
||||
Website-Hooks, Dethsquare-Engine-*, Lost-Sector-Unity, Lost-Sector-Map-Editor,
|
||||
NavMesh-Debugger), **③** les bugs découverts pendant le portage, **④** le
|
||||
reste du portage Android.
|
||||
|
||||
---
|
||||
|
||||
## 1. Ce qui a été fait (portage, 2026)
|
||||
|
||||
- [x] Build modernisé : Gradle 3.5-rc-2 → 9.9.1, JDK 8 → 21, LWJGL 3.1.2 → 3.3.6,
|
||||
purged shadow/launch4j/butler (distribution desktop via `installDist`)
|
||||
- [x] Desktop 2026 fonctionnel (macOS ARM inclus) : contexte GL 3.2 core,
|
||||
callback d'erreur GLFW lisible, icône sautée sur macOS
|
||||
- [x] Back-end Android complet : GLES 3.0 (batch de quads porté), BitmapFactory,
|
||||
SoundPool/MediaPlayer, AssetManager, SharedPreferences, GLSurfaceView
|
||||
- [x] Application AGP (`android-app`) : jeu + moteur + backend en 1 APK
|
||||
- [x] Contrôles tactiles POC (zones gauche/droite + 2ᵉ doigt = saut)
|
||||
- [x] Logging multi-plateforme `GameLog` (LS-INIT/LEVEL/MAP/MISSION/INPUT/
|
||||
AUDIO/RENDER/PREFAB), branché sur logcat Android et stdout desktop
|
||||
- [x] Bugs corrigés en chemin (voir §4)
|
||||
- [x] Mission Défense jouable sur émulateur, Settings + persistance testés
|
||||
|
||||
## 2. Roadmap originale de l'équipe (Trello, état au 21/07/2018)
|
||||
|
||||
### High Priority (non fait en 2017 — resté en l'état)
|
||||
- [ ] **Survival missions** (code présent : SurvivalLevel, à tester/peaufiner)
|
||||
- [ ] **Extermination missions** (TODO dans le code : forcer le nombre d'ennemis,
|
||||
`ExterminateMission.java:32`)
|
||||
- [ ] **More complete procedural map generation** (`map/procedural/`, les
|
||||
segments + connecteurs existent depuis le proto Unity 2015)
|
||||
- [ ] Spawn points pour missions infinies (fait en 2017 : `SpawnPoint.java`)
|
||||
|
||||
### In Progress en 2017 (chantiers interrompus)
|
||||
- [ ] **Multiplayer** : stability, missions/objectives, damage system, enemies,
|
||||
weapons, pickups, lockers — le matchmaker UDP (2 joueurs max, P2P direct)
|
||||
est fonctionnel côté serveur (`Matchmaking-Server`), le client engine a
|
||||
Network*/Matchmaker* ; les serveurs d'origine sont éteints
|
||||
→ **self-hoster** (Node, repo `Server` ou `Matchmaking-Server`) puis
|
||||
pointer `Matchmaker` dessus
|
||||
- [ ] **Auth flow** : backend JWT + système d'amis complets côté serveur
|
||||
(`Server/backend`, `/login`, `/register`, `/user/friends*`) — aucun
|
||||
client in-game
|
||||
- [ ] **Matchmaker par user IDs** au lieu d'IPs (carte Trello #41)
|
||||
- [ ] **Java → Kotlin** (carte #44, motivée par la stabilité) — pertinence
|
||||
discutable pour un port ; en revanche Java 8 → 11+ serait utile
|
||||
- [ ] **Smart camera** (`SmartCamera.java` existe, debug flag inclus)
|
||||
- [ ] **Updated AI behaviours** (`ai/Behaviour.java` builder pattern présent)
|
||||
|
||||
### Medium Priority
|
||||
- [ ] **Stealth system** (crouch, bruit, détection, herbes hautes) — rien
|
||||
d'existant, gros chantier gameplay
|
||||
- [ ] **Kubrow/sentinel AI** — `Kubrow.java` existe + NavMesh avec liens
|
||||
JUMP/FALL (preuve : `kubrow-map.lsmap` dans NavMesh-Debugger, 2016)
|
||||
- [ ] Enemies jumping across gaps (NavMesh le supporte déjà)
|
||||
- [ ] Tweak hitboxes "pretty much everything"
|
||||
- [ ] "Grips" pour armes (équipement rapide) — fait pour ranged en 2017
|
||||
|
||||
### Low Priority
|
||||
- [ ] **Archwing** (aucune trace de code)
|
||||
- [ ] **Parallax backgrounds** (le Map-Editor 2016 avait des ParallaxLayer)
|
||||
- [ ] Merge image/animation directories (fait en 2017)
|
||||
|
||||
## 3. Ce que les dépôts annexes révèlent (à ne pas perdre)
|
||||
|
||||
- **Serveurs** : backend auth+amis fonctionnel (MongoDB, JWT), matchmaker UDP
|
||||
avec probation ; forums Angular prévus côté site mais backend jamais écrit ;
|
||||
pas de cloud-save/leaderboard nulle part.
|
||||
- **Version Unity (2015)** : proto plateformer+tir, génération par connecteurs
|
||||
— concept repris tel quel dans le jeu Java (connecteurs TMX typés).
|
||||
Aucune Warframe/mission "perdue" dedans (Frost seul).
|
||||
- **Map-Editor maison (2016)** : remplacé par Tiled/TMX ; ne jamais ressusciter.
|
||||
- **NavMesh-Debugger** : le NavMesh du jeu n'a pas changé depuis 2016.
|
||||
- **CI/CD d'origine** (`Website-Hooks`) : builds nightly via webhook GitHub —
|
||||
remplaçable par une Action GitHub si on distribue à nouveau.
|
||||
|
||||
## 4. Bugs corrigés pendant le portage (conserver en mémoire)
|
||||
|
||||
| Bug | Fichier | Cause racine |
|
||||
|---|---|---|
|
||||
| Crash au 1ᵉʳ rendu sur macOS | `DesktopLauncher` | contexte legacy 2.1 sans hints GL 3.2 core |
|
||||
| `65548: <pointeur>` dans les logs | `DesktopLauncher` | description d'erreur GLFW imprimée comme un nombre |
|
||||
| Écran noir Android | `AndroidGameActivity` | `launch(new Game())` jamais appelé |
|
||||
| Menus muets sur Android | `core/Input` | branche ANDROID ne consommait pas les touches virtuelles |
|
||||
| NPE au chargement de map | `core/tmx/TMXLoader` | assets Android ∉ classpath (getResourceAsStream null) |
|
||||
| Crash au 2ᵉ chargement de mission | `DefenseMission` | `director = null` en fin de mission + instance réutilisée (bug upstream, aussi desktop) |
|
||||
| Cryopods fantômes (2 au lieu de 1) | `core/GameObject` | `destroyAll()` ne purgeait pas le registre des tags (upstream) |
|
||||
| Compilation Android impossible | `Screen`, `Debug` | fuites core→desktop (GL11/DesktopLauncher référencés du core) |
|
||||
| JSONException non catchées | `Animations`, `Material`, `Matchmaker*` | org.json checked (Android) vs unchecked (Maven récent) |
|
||||
|
||||
## 5. Reste du portage Android (phase 1 finition)
|
||||
|
||||
- [ ] **HUD de contrôles virtuels** dessiné (joystick + boutons saut/mélée/tir/
|
||||
pouvoirs 1-3) à la place des zones POC — avec les sprites du HUD existant
|
||||
- [ ] **Musique en boucle fiable** : MediaPlayer dès `setLoop(id, true)`
|
||||
(aujourd'hui : boucle seulement si appelé avant play)
|
||||
- [ ] Vérifier `AudioListener`/atténuation spatiale en jeu (SFX des ennemis)
|
||||
- [ ] Orientation : forcer paysage dès la 1ᵉʳ frame (l'émulateur reste en
|
||||
portrait sans capteurs) + ratio 16:9 letterboxé
|
||||
- [ ] Perf : remplacer `parallelStream` du rendu par du séquentiel (GC mobile),
|
||||
pooling des tableaux de batch
|
||||
- [ ] Icône d'app (aucune ressource Android : icône système par défaut)
|
||||
- [ ] Tester Survival / Exterminate / procedural / explore sur Android
|
||||
- [ ] Mode debug graphics portable (rendu des DebugGraphics en batch)
|
||||
|
||||
## 6. Chantiers de code du jeu (petits, concrets)
|
||||
|
||||
- [ ] `Player.ability4Check()` : dé-commenter l'Avalanche (4ᵉ pouvoir Frost)
|
||||
et le tester (code existant, désactivé en 2017)
|
||||
- [ ] `ExterminateMission.java:32` : forcer le nombre d'ennemis
|
||||
- [ ] `Rigidbody.java:4` : déplacer `MAX_MOVEMENT` dans `Physics`
|
||||
- [ ] `PumpkinDeraCrewman` : ajuster le collider citrouille (TODO d'origine)
|
||||
- [ ] `GraphicsEngine.java:82` : culling réel des renderers invisibles
|
||||
- [ ] Squelette d'une 2ᵉ Warframe (classe `Warframe` générique prête) —
|
||||
nécessite des assets (sprites/anim JSON) : blocage artistique
|
||||
|
||||
## 7. Décisions à prendre
|
||||
|
||||
- [ ] Licence : contacter l'équipe d'origine (repo dormant, aucune LICENSE)
|
||||
avant toute publication (Play Store inclus)
|
||||
- [ ] Distribution desktop : réintégrer shadowJar si besoin de distribuer
|
||||
- [ ] Kotlin ou pas (carte Trello #44) — recommandation : non, rester Java
|
||||
- [ ] Multi : self-host du matchmaker (2 joueurs, P2P) — faisable, mais
|
||||
faible valeur tant que le solo n'est pas enrichi
|
||||
77
android-app/build.gradle
Normal file
77
android-app/build.gradle
Normal file
@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Module application Android du portage Lost Sector.
|
||||
*
|
||||
* Choix d'architecture : plutôt que de reprendre le module java `:android`
|
||||
* hérité de 2017 (build.gradle vide, stub android-4.4.jar, jamais câblé), ce
|
||||
* module AGP compile TOUTES les sources du jeu et du moteur en un seul
|
||||
* artefact :
|
||||
* - src/main/java : backend Android (launcher, GLES)
|
||||
* - ../lost-sector/src/main/java : code du jeu
|
||||
* - ../dethsquare/{core,base}/src/main/java : cœur du moteur (Java pur)
|
||||
* - ../dethsquare/android/src/main/java : backend Android du moteur
|
||||
*
|
||||
* Inclusion par srcDirs plutôt que dépendances `project()` : le module `:core`
|
||||
* est un java-library JVM (avec LWJGL en dépendance) qu'AGP ne peut pas
|
||||
* consommer tel quel, et la boucle :core -> :android -> :core du build 2017
|
||||
* serait circulaire. Les assets reprennent les ressources du jeu (atlas,
|
||||
* maps TMX, audio) + les shaders du core.
|
||||
*
|
||||
* Pas d'AndroidX ni de dépendance externe : org.json est intégré à Android,
|
||||
* et le jeu n'utilise rien d'autre (commons-io/LWJGL restent desktop-only).
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'com.ezardlabs.lostsector'
|
||||
compileSdk 36
|
||||
|
||||
defaultConfig {
|
||||
// Id d'application distinct du projet d'origine (jamais distribué) :
|
||||
// à ajuster avant toute publication.
|
||||
applicationId 'fr.siphonight.lostsectorport'
|
||||
minSdk 24 // java.util.stream (parallelStream dans GraphicsEngine)
|
||||
targetSdk 36
|
||||
versionCode 1
|
||||
versionName '0.2.2'
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
main {
|
||||
java.srcDirs = [
|
||||
'src/main/java',
|
||||
'../lost-sector/src/main/java',
|
||||
'../dethsquare/core/src/main/java',
|
||||
'../dethsquare/base/src/main/java',
|
||||
'../dethsquare/android/src/main/java'
|
||||
]
|
||||
assets.srcDirs = [
|
||||
'../lost-sector/src/main/resources',
|
||||
'../dethsquare/core/src/main/resources'
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
lint {
|
||||
// Portage WIP : le lint ne doit pas bloquer le build.
|
||||
abortOnError false
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Les index files.lsd (référencés par AndroidIOUtils.listFileNames) sont
|
||||
* générés dans lost-sector/src/main/resources à chaque build : les tâches de
|
||||
* fusion d'assets AGP doivent s'exécuter APRÈS leur régénération.
|
||||
*/
|
||||
afterEvaluate {
|
||||
tasks.matching { it.name.contains('Merge') && it.name.contains('Assets') }.configureEach {
|
||||
dependsOn ':lost-sector:indexResources'
|
||||
}
|
||||
}
|
||||
32
android-app/src/main/AndroidManifest.xml
Normal file
32
android-app/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Manifest du portage Android de Lost Sector.
|
||||
|
||||
- Thème système NoTitleBar.Fullscreen : pas d'AndroidX (le jeu n'utilise
|
||||
aucune lib Android tierce), le plein écran est suffisant.
|
||||
- sensorLandscape + configChanges : l'Activity n'est jamais recréée (le jeu
|
||||
assume un référentiel horizontal 1920px de large).
|
||||
-->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<application
|
||||
android:label="Lost Sector"
|
||||
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
|
||||
android:allowBackup="true"
|
||||
android:hardwareAccelerated="false">
|
||||
<!-- hardwareAccelerated=false : le rendu est 100% GLSurfaceView/EGL,
|
||||
pas de canvas View accéléré nécessaire. -->
|
||||
|
||||
<activity
|
||||
android:name=".AndroidGameActivity"
|
||||
android:exported="true"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@ -0,0 +1,59 @@
|
||||
package com.ezardlabs.lostsector;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.os.Bundle;
|
||||
import android.view.WindowManager;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.AndroidAudioUtils;
|
||||
import com.ezardlabs.dethsquare.util.AndroidLauncher;
|
||||
|
||||
/*
|
||||
* Point d'entrée Android du jeu (équivalent de Main.java côté desktop).
|
||||
*
|
||||
* Fullscreen immersif + paysage verrouillé : le jeu a été dessiné pour un
|
||||
* référentiel 1920x1080 en ScaleMode.WIDTH, la rotation casserait la mise en
|
||||
* page des menus. La config landscape/hard-key est déclarée dans le manifest
|
||||
* pour éviter toute recréation de l'Activity en cours de partie.
|
||||
*/
|
||||
public class AndroidGameActivity extends Activity {
|
||||
private AndroidLauncher launcher;
|
||||
private AndroidAudioUtils audio;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
|
||||
launcher = new AndroidLauncher(this);
|
||||
launcher.attachTo(this);
|
||||
|
||||
// Équivalent de Main.main : DesktopLauncher().launch(new Game()).
|
||||
// launch() mémorise le BaseGame ; la création effective se fait dans
|
||||
// GLSurfaceView.Renderer.onSurfaceChanged (ordre desktop préservé).
|
||||
launcher.launch(new Game());
|
||||
|
||||
// Raccroche le cycle de vie audio : le pipeline desktop n'a pas
|
||||
// d'équivalent (le son meurt avec le process), sur Android il faut
|
||||
// couper/reprendre explicitement en multitâche.
|
||||
audio = (AndroidAudioUtils) launcher.getAudio();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouchEvent(android.view.MotionEvent event) {
|
||||
launcher.onTouchEvent(event);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
if (audio != null) audio.pauseAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
if (audio != null) audio.resumeAll();
|
||||
}
|
||||
}
|
||||
35
build.gradle
Normal file
35
build.gradle
Normal file
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Build racine du portage Lost Sector (modernisation 2026).
|
||||
*
|
||||
* L'ancien build (Gradle 3.5-rc-2, 2017) embarquait shadow/launch4j/butler pour
|
||||
* produire jar + .exe + push itch.io. Le portage Android n'a pas besoin de
|
||||
* cette chaîne de publication : on garde uniquement le plugin `application`,
|
||||
* suffisant pour `./gradlew run` et `./gradlew installDist`.
|
||||
* Le fat-jar (shadow) sera réintroduit plus tard si besoin de distribuer.
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id 'application'
|
||||
// AGP déclaré ici (apply false) : seul :android-app l'applique, mais le
|
||||
// classpath des plugins se résout au niveau racine.
|
||||
id 'com.android.application' version '9.5.1' apply false
|
||||
}
|
||||
|
||||
version = '0.2.2'
|
||||
|
||||
application {
|
||||
mainClass = 'com.ezardlabs.lostsector.Main'
|
||||
|
||||
/*
|
||||
* macOS : GLFW impose d'être initialisé sur le thread principal de la JVM
|
||||
* (-XstartOnFirstThread), sinon crash natif au lancement. Sans effet utile
|
||||
* ailleurs, on ne l'ajoute donc que sur macOS.
|
||||
*/
|
||||
if (org.gradle.internal.os.OperatingSystem.current().isMacOsX()) {
|
||||
applicationDefaultJvmArgs = ['-XstartOnFirstThread']
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':lost-sector')
|
||||
}
|
||||
29
dethsquare/.gitignore
vendored
Normal file
29
dethsquare/.gitignore
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### Java template
|
||||
*.class
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
### Gradle template
|
||||
.gradle
|
||||
build/
|
||||
|
||||
# Ignore Gradle GUI config
|
||||
gradle-app.setting
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
|
||||
# Cache of project
|
||||
.gradletasknamecache
|
||||
|
||||
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
|
||||
# gradle/wrapper/gradle-wrapper.properties
|
||||
1
dethsquare/README.md
Normal file
1
dethsquare/README.md
Normal file
@ -0,0 +1 @@
|
||||
[](https://www.codacy.com/app/8-Bit-Warframe/Dethsquare-Engine)
|
||||
32
dethsquare/android/.gitignore
vendored
Normal file
32
dethsquare/android/.gitignore
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### Java template
|
||||
*.class
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Avoid ignoring jars in the libs folder
|
||||
!libs/*.jar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
### Gradle template
|
||||
.gradle
|
||||
build/
|
||||
|
||||
# Ignore Gradle GUI config
|
||||
gradle-app.setting
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
|
||||
# Cache of project
|
||||
.gradletasknamecache
|
||||
|
||||
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
|
||||
# gradle/wrapper/gradle-wrapper.properties
|
||||
0
dethsquare/android/build.gradle
Normal file
0
dethsquare/android/build.gradle
Normal file
BIN
dethsquare/android/libs/android-4.4.jar
Normal file
BIN
dethsquare/android/libs/android-4.4.jar
Normal file
Binary file not shown.
@ -0,0 +1,252 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.AudioAttributes;
|
||||
import android.media.MediaPlayer;
|
||||
import android.media.SoundPool;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
|
||||
/*
|
||||
* Back-end audio Android, équivalent fonctionnel de DesktopAudioUtils (OpenAL).
|
||||
*
|
||||
* Deux moteurs cohabitent :
|
||||
* - SoundPool pour les SFX courts (tirs, coups, pickups) : décodage natif ogg,
|
||||
* latence faible, plusieurs streams simultanés ;
|
||||
* - MediaPlayer pour les clips en boucle (musique) : SoundPool ne sait pas
|
||||
* basculer un son déjà chargé en boucle infinie.
|
||||
*
|
||||
* L'audio spatialisé simple du desktop (modèle OpenAL INVERSE_DISTANCE_CLAMPED,
|
||||
* référence 500, portée max 4000, z = 0) est réimplémenté en Java : on calcule
|
||||
* le gain en fonction de la distance listener <-> source et on l'applique au
|
||||
* stream actif. Suffisant pour un jeu 2D à une couche de profondeur.
|
||||
*
|
||||
* Limitation connue (phase 1) : setLoop(id, true) appelé APRÈS le premier
|
||||
* play() sur un clip SoundPool n'est pas appliqué rétroactivement (SoundPool
|
||||
* ne boucle qu'au déclenchement). Le jeu appelle toujours setLoop avant play
|
||||
* pour la musique, donc ce cas ne se produit pas en pratique.
|
||||
*/
|
||||
public class AndroidAudioUtils implements AudioUtils {
|
||||
private static final float REFERENCE_DISTANCE = 500f;
|
||||
private static final float MAX_DISTANCE = 4000f;
|
||||
|
||||
private final Context context;
|
||||
private final SoundPool soundPool;
|
||||
private final HashMap<Integer, Integer> sources = new HashMap<>(); // id -> SoundPool soundId
|
||||
private final HashMap<Integer, MediaPlayer> loopingPlayers = new HashMap<>(); // id -> MediaPlayer
|
||||
private final HashMap<String, Integer> loadedPaths = new HashMap<>(); // path -> SoundPool soundId
|
||||
private final HashMap<Integer, Boolean> looping = new HashMap<>();
|
||||
private final HashMap<Integer, Boolean> pendingLoops = new HashMap<>();
|
||||
private final HashMap<Integer, float[]> positions = new HashMap<>(); // id -> {x, y}
|
||||
private final HashMap<Integer, Integer> activeStreams = new HashMap<>(); // id -> SoundPool streamId
|
||||
private final HashMap<Integer, Float> baseVolumes = new HashMap<>(); // id -> dernier volume demandé
|
||||
|
||||
private float listenerX = 0;
|
||||
private float listenerY = 0;
|
||||
|
||||
public AndroidAudioUtils(Context context) {
|
||||
this.context = context;
|
||||
AudioAttributes attrs = new AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_GAME)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.build();
|
||||
soundPool = new SoundPool.Builder().setMaxStreams(24).setAudioAttributes(attrs).build();
|
||||
soundPool.setOnLoadCompleteListener((sp, sampleId, status) -> {
|
||||
// Chargement SoundPool asynchrone : on mémorise juste la boucle
|
||||
// demandée pendant le chargement, play() la consommera ensuite.
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void create(int id, String path) {
|
||||
GameLog.d("LS-AUDIO", "create id=" + id + " path=" + path);
|
||||
try {
|
||||
android.content.res.AssetFileDescriptor fd = context.getAssets().openFd(path);
|
||||
int soundId = soundPool.load(fd, 0);
|
||||
fd.close();
|
||||
sources.put(id, soundId);
|
||||
loadedPaths.put(path, soundId);
|
||||
pendingLoops.put(id, false);
|
||||
paths.put(id, path); // conservé pour recréer un MediaPlayer au play() en boucle
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
throw new Dethsquare.ResourceNotFoundError(path);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void play(int id) {
|
||||
Integer soundId = sources.get(id);
|
||||
if (soundId == null) return;
|
||||
|
||||
GameLog.d("LS-AUDIO", "play id=" + id + " loop=" + looping.get(id));
|
||||
|
||||
if (Boolean.TRUE.equals(looping.get(id))) {
|
||||
// Musique : MediaPlayer (boucle fiable et gapless)
|
||||
MediaPlayer player = loopingPlayers.get(id);
|
||||
if (player == null) {
|
||||
try {
|
||||
android.content.res.AssetFileDescriptor fd = context.getAssets().openFd(pathOf(id));
|
||||
player = new MediaPlayer();
|
||||
player.setAudioAttributes(new AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_GAME)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build());
|
||||
player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
|
||||
fd.close();
|
||||
player.setLooping(true);
|
||||
player.prepare();
|
||||
loopingPlayers.put(id, player);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
}
|
||||
applyPosition(id, player);
|
||||
player.start();
|
||||
return;
|
||||
}
|
||||
|
||||
// SFX : volume calculé depuis la position monde au moment du déclenchement
|
||||
float volume = baseVolumes.containsKey(id) ? baseVolumes.get(id) : 1f;
|
||||
volume *= attenuation(id);
|
||||
int streamId = soundPool.play(soundId, volume, volume, 1, 0, 1f);
|
||||
activeStreams.put(id, streamId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pause(int id) {
|
||||
MediaPlayer player = loopingPlayers.get(id);
|
||||
if (player != null && player.isPlaying()) player.pause();
|
||||
Integer stream = activeStreams.get(id);
|
||||
// SoundPool ne permet pas de mettre en pause un stream précis sans
|
||||
// l'arrêter : on coupe le volume (les SFX sont courts, l'effet est
|
||||
// équivalent en pratique).
|
||||
if (stream != null) soundPool.setVolume(stream, 0f, 0f);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop(int id) {
|
||||
MediaPlayer player = loopingPlayers.get(id);
|
||||
if (player != null) {
|
||||
player.stop();
|
||||
try {
|
||||
player.prepare();
|
||||
player.seekTo(0);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
Integer stream = activeStreams.get(id);
|
||||
if (stream != null) soundPool.stop(stream);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLoop(int id, boolean loop) {
|
||||
looping.put(id, loop);
|
||||
pendingLoops.put(id, loop);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVolume(int id, float volume) {
|
||||
baseVolumes.put(id, volume);
|
||||
MediaPlayer player = loopingPlayers.get(id);
|
||||
if (player != null) {
|
||||
// Le volume fourni par AudioManager inclut déjà le mix
|
||||
// master/music/sfx : on n'applique QUE ce volume aux MediaPlayer.
|
||||
player.setVolume(volume, volume);
|
||||
}
|
||||
// Les SFX recombinent ce volume avec l'atténuation spatiale au play().
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAudioPosition(int id, float x, float y) {
|
||||
positions.put(id, new float[]{x, y});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setListenerPosition(float x, float y) {
|
||||
listenerX = x;
|
||||
listenerY = y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(int id) {
|
||||
Integer soundId = sources.remove(id);
|
||||
if (soundId != null) soundPool.unload(soundId);
|
||||
MediaPlayer player = loopingPlayers.remove(id);
|
||||
if (player != null) player.release();
|
||||
activeStreams.remove(id);
|
||||
looping.remove(id);
|
||||
positions.remove(id);
|
||||
baseVolumes.remove(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroyAll() {
|
||||
for (Integer soundId : sources.values()) {
|
||||
soundPool.unload(soundId);
|
||||
}
|
||||
sources.clear();
|
||||
for (MediaPlayer player : loopingPlayers.values()) {
|
||||
player.release();
|
||||
}
|
||||
loopingPlayers.clear();
|
||||
activeStreams.clear();
|
||||
looping.clear();
|
||||
positions.clear();
|
||||
baseVolumes.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
destroyAll();
|
||||
soundPool.release();
|
||||
}
|
||||
|
||||
/** Appelé depuis Activity.onPause() : coupe tout (mises en veille, multitâche). */
|
||||
public void pauseAll() {
|
||||
soundPool.autoPause();
|
||||
for (MediaPlayer player : loopingPlayers.values()) {
|
||||
if (player.isPlaying()) player.pause();
|
||||
}
|
||||
}
|
||||
|
||||
/** Appelé depuis Activity.onResume() : reprend la musique en boucle. */
|
||||
public void resumeAll() {
|
||||
soundPool.autoResume();
|
||||
for (MediaPlayer player : loopingPlayers.values()) {
|
||||
player.start();
|
||||
}
|
||||
}
|
||||
|
||||
private float attenuation(int id) {
|
||||
float[] pos = positions.get(id);
|
||||
if (pos == null) return 1f;
|
||||
float dx = pos[0] - listenerX;
|
||||
float dy = pos[1] - listenerY;
|
||||
float distance = (float) Math.sqrt(dx * dx + dy * dy);
|
||||
if (distance <= REFERENCE_DISTANCE) return 1f;
|
||||
if (distance >= MAX_DISTANCE) return 0f;
|
||||
// Modèle inverse distance (équivalent simplifié d'OpenAL
|
||||
// AL_INVERSE_DISTANCE_CLAMPED : gain = ref / dist, borné).
|
||||
return REFERENCE_DISTANCE / distance;
|
||||
}
|
||||
|
||||
private void applyPosition(int id, MediaPlayer player) {
|
||||
// Les MediaPlayer ne servent qu'à la musique (déclarée sans position
|
||||
// monde) : hook présent pour la cohérence de l'API.
|
||||
float[] pos = positions.get(id);
|
||||
if (pos == null) return;
|
||||
float gain = attenuation(id) * (baseVolumes.containsKey(id) ? baseVolumes.get(id) : 1f);
|
||||
player.setVolume(gain, gain);
|
||||
}
|
||||
|
||||
/** Re-trouve le chemin d'asset associé à un id (stocké au create). */
|
||||
private final HashMap<Integer, String> paths = new HashMap<>();
|
||||
|
||||
private String pathOf(int id) {
|
||||
return paths.get(id);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,87 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import android.content.res.AssetManager;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/*
|
||||
* Back-end IO Android : toutes les ressources du jeu vivent dans le dossier
|
||||
* `assets/` de l'APK (les répertoires src/main/resources des submodules
|
||||
* lost-sector et dethsquare/core sont mappés comme assets dans le build).
|
||||
*
|
||||
* Le chemin demandé (ex "images/enemies/atlas.png") est utilisé tel quel comme
|
||||
* chemin d'asset — même convention que le classpath côté desktop, ce qui rend
|
||||
* le code du jeu et du core transparent à la plateforme.
|
||||
*/
|
||||
public class AndroidIOUtils implements IOUtils {
|
||||
private final AssetManager assets;
|
||||
|
||||
public AndroidIOUtils(AssetManager assets) {
|
||||
this.assets = assets;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getInputStream(String path) {
|
||||
try {
|
||||
return assets.open(path);
|
||||
} catch (IOException e) {
|
||||
// Même contrat que ClassLoader.getSystemResourceAsStream côté desktop :
|
||||
// null quand la ressource n'existe pas (les appelants testent le null
|
||||
// et lèvent ResourceNotFoundError).
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getFileLines(String path) {
|
||||
BufferedReader reader = getReader(path);
|
||||
if (reader == null) {
|
||||
return new String[0];
|
||||
}
|
||||
ArrayList<String> data = new ArrayList<>();
|
||||
try {
|
||||
String temp;
|
||||
while ((temp = reader.readLine()) != null) {
|
||||
data.add(temp);
|
||||
}
|
||||
reader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return new String[0];
|
||||
}
|
||||
return data.toArray(new String[data.size()]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] listFileNames(String dirPath) {
|
||||
/*
|
||||
* Le moteur ne sait pas énumérer le contenu d'un jar/d'un APK : il lit
|
||||
* l'index `files.lsd` généré à chaque build par la tâche Gradle
|
||||
* indexResources (voir lost-sector/build.gradle). Les fichiers *.lsd
|
||||
* doivent donc bien être inclus dans les assets — d'où le câblage
|
||||
* processResources -> indexResources côté desktop, et mergeAssets ->
|
||||
* indexResources côté Android.
|
||||
*/
|
||||
try (BufferedReader reader = getReader(dirPath + "/files.lsd")) {
|
||||
ArrayList<String> list = new ArrayList<>();
|
||||
String temp;
|
||||
while ((temp = reader.readLine()) != null) {
|
||||
list.add(temp);
|
||||
}
|
||||
return list.toArray(new String[list.size()]);
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to load " + dirPath + " files.lsd");
|
||||
e.printStackTrace();
|
||||
return new String[0];
|
||||
}
|
||||
}
|
||||
|
||||
public BufferedReader getReader(String path) {
|
||||
InputStream is = getInputStream(path);
|
||||
return is == null ? null : new BufferedReader(new InputStreamReader(is));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,211 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.opengl.GLSurfaceView;
|
||||
import android.view.MotionEvent;
|
||||
|
||||
import com.ezardlabs.dethsquare.Input;
|
||||
import com.ezardlabs.dethsquare.util.BaseGame;
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare.Platform;
|
||||
import com.ezardlabs.dethsquare.util.GameLog;
|
||||
|
||||
import javax.microedition.khronos.egl.EGLConfig;
|
||||
import javax.microedition.khronos.opengles.GL10;
|
||||
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.Platform.ANDROID;
|
||||
import static android.opengl.GLES30.GL_COLOR_BUFFER_BIT;
|
||||
import static android.opengl.GLES30.GL_DEPTH_BUFFER_BIT;
|
||||
import static android.opengl.GLES30.glClear;
|
||||
import static android.opengl.GLES30.glClearColor;
|
||||
|
||||
/*
|
||||
* Back-end launcher Android : équivalent de DesktopLauncher (GLFW), construit
|
||||
* sur GLSurfaceView.
|
||||
*
|
||||
* POURQUOI GLSurfaceView : le moteur impose une boucle update()/render()
|
||||
* séquentielle sur le thread GL (DesktopLauncher.launch, DesktopLauncher.java:
|
||||
* 331-340). GLSurfaceView fournit exactement ça : un thread GL dédié qui
|
||||
* appelle onSurfaceCreated -> onSurfaceChanged -> onDrawFrame en continu, et
|
||||
* gère EGL/contexte/pause-resume nativement.
|
||||
*
|
||||
* Ordre d'initialisation calqué sur le desktop : sur desktop, le contexte GL
|
||||
* et le resize ont lieu AVANT game.create() (DesktopLauncher ctor + launch).
|
||||
* GLSurfaceView appelle onSurfaceCreated AVANT onSurfaceChanged, donc
|
||||
* game.create() est différé au premier onSurfaceChanged pour conserver cet
|
||||
* ordre (le jeu lit Screen.width dès le menu).
|
||||
*
|
||||
* Entrées : les MotionEvents sont envoyés au core via Input.addTouch/moveTouch/
|
||||
* removeTouch/cancelTouch (consommés par Input.update() sur la branche
|
||||
* ANDROID). Toute la synthèse de contrôles (boutons virtuels, clic souris) vit
|
||||
* dans TouchControls, côté jeu — le launcher reste un simple pont
|
||||
* MotionEvent -> Input.
|
||||
*/
|
||||
public class AndroidLauncher extends Launcher implements GLSurfaceView.Renderer {
|
||||
private final Context context;
|
||||
private GLSurfaceView glView;
|
||||
private BaseGame game;
|
||||
private boolean initialised = false;
|
||||
private boolean created = false;
|
||||
|
||||
public AndroidLauncher(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
/** À appeler depuis Activity.onCreate : crée et installe la vue GL. */
|
||||
public void attachTo(Activity activity) {
|
||||
glView = new GLSurfaceView(activity);
|
||||
glView.setEGLContextClientVersion(3); // GLES 3.0 : requis par AndroidRenderUtils
|
||||
glView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); // RGBA8888 + depth 16 (pixel art + blending)
|
||||
glView.setRenderer(this);
|
||||
glView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
|
||||
activity.setContentView(glView);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Platform getPlatform() {
|
||||
return ANDROID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AudioUtils getAudio() {
|
||||
// Instance unique (surcharge avec élargissement de visibilité) : le
|
||||
// cycle de vie Android (pause/resume) doit toucher la MÊME instance
|
||||
// que celle enregistrée dans Dethsquare.init().
|
||||
if (audio == null) {
|
||||
audio = new AndroidAudioUtils(context);
|
||||
}
|
||||
return audio;
|
||||
}
|
||||
|
||||
private AndroidAudioUtils audio;
|
||||
|
||||
@Override
|
||||
protected IOUtils getIO() {
|
||||
return new AndroidIOUtils(context.getAssets());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PrefUtils getPrefs() {
|
||||
return new AndroidPrefUtils(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected RenderUtils getRender() {
|
||||
return new AndroidRenderUtils();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void launch(BaseGame game) {
|
||||
// Sur Android, la boucle est pilotée par GLSurfaceView : il n'y a rien à
|
||||
// faire ici (contrairement à DesktopLauncher.launch qui tourne une
|
||||
// while-loop GLFW). launch() ne sert qu'à recevoir le BaseGame.
|
||||
this.game = game;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
|
||||
if (!initialised) {
|
||||
// Sink de logs Android avant toute initialisation : tout le reste
|
||||
// (init moteur, chargement du jeu) est ainsi tracé dans logcat.
|
||||
GameLog.setSink(new GameLog.Sink() {
|
||||
@Override
|
||||
public void debug(String tag, String message) {
|
||||
android.util.Log.d(tag, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String tag, String message) {
|
||||
android.util.Log.i(tag, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String tag, String message) {
|
||||
android.util.Log.w(tag, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String tag, String message) {
|
||||
android.util.Log.e(tag, message);
|
||||
}
|
||||
});
|
||||
init(); // Dethsquare.init(...) : installe audio/io/prefs/render
|
||||
initialised = true;
|
||||
}
|
||||
glClearColor(0, 0, 0, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSurfaceChanged(GL10 gl, int width, int height) {
|
||||
GameLog.i("LS-INIT", "Surface changed: " + width + "x" + height);
|
||||
onResize(width, height); // -> Screen/GuiRenderer recalculent leurs échelles
|
||||
|
||||
if (!created && game != null) {
|
||||
GameLog.i("LS-INIT", "game.create() start");
|
||||
game.create();
|
||||
created = true;
|
||||
GameLog.i("LS-INIT", "game.create() done");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDrawFrame(GL10 gl) {
|
||||
if (!created) return;
|
||||
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
update(); // Launcher : updateListeners puis postUpdateListeners
|
||||
render(); // Launcher : renderListeners (GraphicsEngine y est accroché)
|
||||
}
|
||||
|
||||
/*
|
||||
* Convertit les MotionEvents en touches brutes pour le core
|
||||
* (Input.addTouch/moveTouch/removeTouch/cancelTouch, consommées par
|
||||
* Input.update() sur la branche ANDROID).
|
||||
*
|
||||
* Toute la SYNTHESE de contrôles (clavier virtuel, clic souris) vit dans
|
||||
* le HUD de jeu TouchControls (côté jeu, instancié en premier dans chaque
|
||||
* niveau) : c'est lui qui fait le hit-test des boutons et injecte les
|
||||
* touches via Input.injectKeyDown/injectKeyUp. Le launcher reste un
|
||||
* simple pont MotionEvent -> Input.
|
||||
*/
|
||||
public void onTouchEvent(MotionEvent event) {
|
||||
int action = event.getActionMasked();
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
case MotionEvent.ACTION_POINTER_DOWN:
|
||||
int pointerDownIndex = action == MotionEvent.ACTION_DOWN ? 0
|
||||
: event.getActionIndex();
|
||||
int downId = event.getPointerId(pointerDownIndex);
|
||||
float downX = event.getX(pointerDownIndex);
|
||||
float downY = event.getY(pointerDownIndex);
|
||||
GameLog.d("LS-INPUT", "touch down id=" + downId + " (" + (int) downX + "," + (int) downY + ")");
|
||||
Input.addTouch(downId, downX, downY);
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
for (int i = 0; i < event.getPointerCount(); i++) {
|
||||
Input.moveTouch(event.getPointerId(i), event.getX(i), event.getY(i));
|
||||
}
|
||||
break;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_POINTER_UP:
|
||||
int upIndex = action == MotionEvent.ACTION_UP
|
||||
? 0 : event.getActionIndex();
|
||||
int upId = event.getPointerId(upIndex);
|
||||
float upX = event.getX(upIndex);
|
||||
float upY = event.getY(upIndex);
|
||||
GameLog.d("LS-INPUT", "touch up id=" + upId + " (" + (int) upX + "," + (int) upY + ")");
|
||||
Input.removeTouch(upId, upX, upY);
|
||||
break;
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
for (int i = 0; i < event.getPointerCount(); i++) {
|
||||
int cancelId = event.getPointerId(i);
|
||||
GameLog.d("LS-INPUT", "touch cancel id=" + cancelId);
|
||||
Input.cancelTouch(cancelId, event.getX(i), event.getY(i));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.preference.PreferenceManager;
|
||||
|
||||
public class AndroidPrefUtils implements PrefUtils {
|
||||
private final SharedPreferences prefs;
|
||||
|
||||
public AndroidPrefUtils(Context context) {
|
||||
prefs = PreferenceManager.getDefaultSharedPreferences(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBoolean(String key, boolean value) {
|
||||
prefs.edit().putBoolean(key, value).commit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInt(String key, int value) {
|
||||
prefs.edit().putInt(key, value).commit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFloat(String key, float value) {
|
||||
prefs.edit().putFloat(key, value).commit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setString(String key, String value) {
|
||||
prefs.edit().putString(key, value).commit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getBoolean(String key, boolean defaultValue) {
|
||||
return prefs.getBoolean(key, defaultValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getInt(String key, int defaultValue) {
|
||||
return prefs.getInt(key, defaultValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getFloat(String key, float defaultValue) {
|
||||
return prefs.getFloat(key, defaultValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getString(String key, String defaultValue) {
|
||||
return prefs.getString(key, defaultValue);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,388 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.opengl.GLES30;
|
||||
import android.opengl.GLUtils;
|
||||
|
||||
import com.ezardlabs.dethsquare.debug.DebugGraphic;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.FloatBuffer;
|
||||
import java.nio.ShortBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.IO;
|
||||
import static android.opengl.GLES30.GL_BLEND;
|
||||
import static android.opengl.GLES30.GL_DYNAMIC_DRAW;
|
||||
import static android.opengl.GLES30.GL_ELEMENT_ARRAY_BUFFER;
|
||||
import static android.opengl.GLES30.GL_FALSE;
|
||||
import static android.opengl.GLES30.GL_FLOAT;
|
||||
import static android.opengl.GLES30.GL_NEAREST;
|
||||
import static android.opengl.GLES30.GL_ONE;
|
||||
import static android.opengl.GLES30.GL_ONE_MINUS_SRC_ALPHA;
|
||||
import static android.opengl.GLES30.GL_SRC_ALPHA;
|
||||
import static android.opengl.GLES30.GL_TEXTURE0;
|
||||
import static android.opengl.GLES30.GL_TEXTURE_2D;
|
||||
import static android.opengl.GLES30.GL_TEXTURE_MAG_FILTER;
|
||||
import static android.opengl.GLES30.GL_TEXTURE_MIN_FILTER;
|
||||
import static android.opengl.GLES30.GL_TRIANGLES;
|
||||
import static android.opengl.GLES30.GL_UNSIGNED_SHORT;
|
||||
import static android.opengl.GLES30.glActiveTexture;
|
||||
import static android.opengl.GLES30.glBindBuffer;
|
||||
import static android.opengl.GLES30.glBindTexture;
|
||||
import static android.opengl.GLES30.glBindVertexArray;
|
||||
import static android.opengl.GLES30.glBlendFuncSeparate;
|
||||
import static android.opengl.GLES30.glBufferData;
|
||||
import static android.opengl.GLES30.glDeleteTextures;
|
||||
import static android.opengl.GLES30.glDrawElements;
|
||||
import static android.opengl.GLES30.glEnable;
|
||||
import static android.opengl.GLES30.glEnableVertexAttribArray;
|
||||
import static android.opengl.GLES30.glGetAttribLocation;
|
||||
import static android.opengl.GLES30.glGetUniformLocation;
|
||||
import static android.opengl.GLES30.glTexParameteri;
|
||||
import static android.opengl.GLES30.glUniform1i;
|
||||
import static android.opengl.GLES30.glUniformMatrix4fv;
|
||||
import static android.opengl.GLES30.glUseProgram;
|
||||
import static android.opengl.GLES30.glVertexAttribPointer;
|
||||
import static android.opengl.GLES30.glViewport;
|
||||
|
||||
/*
|
||||
* Back-end rendu Android : OpenGL ES 3.0, port direct de DesktopRenderUtils.
|
||||
*
|
||||
* Le pipeline est identique au desktop (batch de quads indexés : sommets 3D +
|
||||
* UVs + couleurs par sommet, un seul shader de texture, matrices ortho
|
||||
* partagées monde/GUI) — seules trois choses changent :
|
||||
*
|
||||
* 1. Les shaders : GLSL "#version 330 core" n'existe pas en GLES ; les
|
||||
* équivalents "#version 300 es" sont embarqués ci-dessous (ils doivent
|
||||
* différer de la version desktop de toute façon — précision implicite,
|
||||
* in/out). Le dossier shaders/ du core reste dans les assets mais n'est
|
||||
* pas chargé ici.
|
||||
* 2. Le décodage d'image : BitmapFactory + GLUtils.texImage2D remplacent
|
||||
* STBImage + glTexImage2D (GLUtils gère l'upload RGBA nativement).
|
||||
* 3. Le rendu debug : DesktopRenderUtils dessine les DebugGraphics via la
|
||||
* matrice legacy GL11 (glPushMatrix/glVertex*) qui n'existe ni en core GL
|
||||
* ni en GLES -> volontairement NON PORTÉ (no-op). Voir Debug.java.
|
||||
*
|
||||
* Différences de binding LWJGL vs GLES Android : les fonctions GLES prennent
|
||||
* des tableaux + offsets explicites (glGenTextures(n, int[], offset)) et des
|
||||
* Buffer (pas des float[]) — d'où les helpers genTexture/genBuffer et les
|
||||
* FloatBuffer.wrap/ShortBuffer.wrap dans render().
|
||||
*/
|
||||
public class AndroidRenderUtils implements RenderUtils {
|
||||
// Mêmes uniforms/attributs que le shader desktop (shaders/texture/*.glsl),
|
||||
// en GLSL ES 3.0.
|
||||
private static final String VERTEX_SHADER =
|
||||
"#version 300 es\n" +
|
||||
"uniform mat4 transform;\n" +
|
||||
"in vec2 position;\n" +
|
||||
"in vec2 texCoords;\n" +
|
||||
"in vec4 colour;\n" +
|
||||
"out vec2 vTexCoords;\n" +
|
||||
"out vec4 vColour;\n" +
|
||||
"void main() {\n" +
|
||||
" vTexCoords = texCoords;\n" +
|
||||
" vColour = colour;\n" +
|
||||
" gl_Position = transform * vec4(position, 0.0, 1.0);\n" +
|
||||
"}\n";
|
||||
|
||||
private static final String FRAGMENT_SHADER =
|
||||
"#version 300 es\n" +
|
||||
"precision mediump float;\n" + // pas de précision par défaut en fragment (ES)
|
||||
"uniform sampler2D texUnit;\n" +
|
||||
"in vec2 vTexCoords;\n" +
|
||||
"in vec4 vColour;\n" +
|
||||
"out vec4 g_FragColor;\n" +
|
||||
"void main() {\n" +
|
||||
" vec4 tex = texture(texUnit, vTexCoords);\n" +
|
||||
" g_FragColor = vec4(tex.r * vColour.r, tex.g * vColour.g, tex.b * vColour.b, tex.a * vColour.a);\n" +
|
||||
"}\n";
|
||||
|
||||
private final HashMap<String, int[]> textures = new HashMap<>();
|
||||
|
||||
private int program = -1;
|
||||
private int positionLoc;
|
||||
private int transformLoc;
|
||||
private int texCoordsLoc;
|
||||
private int colourLoc;
|
||||
private int vertexArray;
|
||||
private int vertexBuffer;
|
||||
private int indexBuffer;
|
||||
private int texCoordBuffer;
|
||||
private int colourBuffer;
|
||||
|
||||
private final float[] projection = new float[16];
|
||||
private final float[] view = new float[16];
|
||||
private final float[] projectionAndView = new float[16];
|
||||
|
||||
private final float[] guiView = new float[16];
|
||||
private final float[] guiProjectionAndView = new float[16];
|
||||
|
||||
private float cameraX = 0;
|
||||
private float cameraY = 0;
|
||||
private float scale = 1;
|
||||
private int screenWidth = 1920;
|
||||
private int screenHeight = 1080;
|
||||
|
||||
private boolean initialised = false;
|
||||
|
||||
@Override
|
||||
public int[] loadImage(String path) {
|
||||
int[] cached = textures.get(path);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
int[] returnVals = new int[3];
|
||||
|
||||
InputStream in = IO.getInputStream(path);
|
||||
if (in == null) {
|
||||
throw new ImageNotFoundError(path);
|
||||
}
|
||||
|
||||
try {
|
||||
Bitmap bitmap = BitmapFactory.decodeStream(in);
|
||||
if (bitmap == null) {
|
||||
throw new ImageNotFoundError(path);
|
||||
}
|
||||
in.close();
|
||||
|
||||
if (program == -1) {
|
||||
program = createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
|
||||
glUseProgram(program);
|
||||
glUniform1i(glGetUniformLocation(program, "texUnit"), 0);
|
||||
}
|
||||
|
||||
int texture = genTexture();
|
||||
|
||||
// ARGB_8888 : les atlas du jeu exploitent le canal alpha (pixel art
|
||||
// avec transparence), la config par défaut du Bitmap pourrait être
|
||||
// RGB_565 et casser le blending.
|
||||
Bitmap rgba = bitmap.getConfig() == Bitmap.Config.ARGB_8888
|
||||
? bitmap
|
||||
: bitmap.copy(Bitmap.Config.ARGB_8888, false);
|
||||
|
||||
glBindTexture(GL_TEXTURE_2D, texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
|
||||
GLUtils.texImage2D(GL_TEXTURE_2D, 0, rgba, 0);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
|
||||
GameLog.d("LS-RENDER", "texture loaded: " + path + " -> tex " + texture
|
||||
+ " (" + rgba.getWidth() + "x" + rgba.getHeight() + ")");
|
||||
|
||||
returnVals[0] = texture;
|
||||
returnVals[1] = rgba.getWidth();
|
||||
returnVals[2] = rgba.getHeight();
|
||||
textures.put(path, returnVals);
|
||||
|
||||
if (rgba != bitmap) rgba.recycle();
|
||||
bitmap.recycle();
|
||||
|
||||
return returnVals;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return new int[3];
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int loadShaderProgram(String vertexPath, String fragmentPath) {
|
||||
// Utilisé uniquement par des shaders du jeu chargés depuis des fichiers ;
|
||||
// sur Android le seul programme est le shader de texture embarqué.
|
||||
return createProgram(readFile(vertexPath), readFile(fragmentPath));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int loadShaderProgram(String path) {
|
||||
return loadShaderProgram(path + "/vert.glsl", path + "/frag.glsl");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getUniformLocation(int program, String name) {
|
||||
return glGetUniformLocation(program, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getAttributeLocation(int program, String name) {
|
||||
return glGetAttribLocation(program, name);
|
||||
}
|
||||
|
||||
private int createProgram(String vertexSource, String fragmentSource) {
|
||||
int vert = loadShader(GLES30.GL_VERTEX_SHADER, vertexSource);
|
||||
int frag = loadShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource);
|
||||
|
||||
int program = GLES30.glCreateProgram();
|
||||
GLES30.glAttachShader(program, vert);
|
||||
GLES30.glAttachShader(program, frag);
|
||||
GLES30.glLinkProgram(program);
|
||||
int[] status = new int[1];
|
||||
GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, status, 0);
|
||||
if (status[0] == GL_FALSE) {
|
||||
String log = GLES30.glGetProgramInfoLog(program);
|
||||
throw new IllegalStateException("Shader link error: " + log);
|
||||
}
|
||||
glUseProgram(program);
|
||||
return program;
|
||||
}
|
||||
|
||||
private int loadShader(int type, String source) {
|
||||
int shader = GLES30.glCreateShader(type);
|
||||
GLES30.glShaderSource(shader, source);
|
||||
GLES30.glCompileShader(shader);
|
||||
int[] status = new int[1];
|
||||
GLES30.glGetShaderiv(shader, GLES30.GL_COMPILE_STATUS, status, 0);
|
||||
if (status[0] == GL_FALSE) {
|
||||
String log = GLES30.glGetShaderInfoLog(shader);
|
||||
throw new IllegalStateException("Shader compile error (" + type + "): " + log);
|
||||
}
|
||||
return shader;
|
||||
}
|
||||
|
||||
private String readFile(String path) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String line : IO.getFileLines(path)) {
|
||||
sb.append(line).append('\n');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(int textureName, float[] vertices, float[] uvs, short[] indices, float[] colours, int num) {
|
||||
if (!initialised) {
|
||||
glEnable(GL_BLEND);
|
||||
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
|
||||
|
||||
positionLoc = glGetAttribLocation(program, "position");
|
||||
transformLoc = glGetUniformLocation(program, "transform");
|
||||
texCoordsLoc = glGetAttribLocation(program, "texCoords");
|
||||
colourLoc = glGetAttribLocation(program, "colour");
|
||||
|
||||
vertexArray = genVertexArray(); // VAO
|
||||
vertexBuffer = genBuffer();
|
||||
texCoordBuffer = genBuffer();
|
||||
colourBuffer = genBuffer();
|
||||
glBindVertexArray(vertexArray);
|
||||
|
||||
indexBuffer = genBuffer();
|
||||
|
||||
initialised = true;
|
||||
}
|
||||
|
||||
glBindTexture(GL_TEXTURE_2D, textureName);
|
||||
|
||||
glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBuffer);
|
||||
glBufferData(GLES30.GL_ARRAY_BUFFER, vertices.length * 4, FloatBuffer.wrap(vertices), GL_DYNAMIC_DRAW);
|
||||
glVertexAttribPointer(positionLoc, 3, GL_FLOAT, false, 0, 0);
|
||||
glEnableVertexAttribArray(positionLoc);
|
||||
|
||||
glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBuffer);
|
||||
glBufferData(GLES30.GL_ARRAY_BUFFER, uvs.length * 4, FloatBuffer.wrap(uvs), GL_DYNAMIC_DRAW);
|
||||
glVertexAttribPointer(texCoordsLoc, 2, GL_FLOAT, false, 0, 0);
|
||||
glEnableVertexAttribArray(texCoordsLoc);
|
||||
|
||||
glBindBuffer(GLES30.GL_ARRAY_BUFFER, colourBuffer);
|
||||
glBufferData(GLES30.GL_ARRAY_BUFFER, colours.length * 4, FloatBuffer.wrap(colours), GL_DYNAMIC_DRAW);
|
||||
glVertexAttribPointer(colourLoc, 4, GL_FLOAT, false, 0, 0);
|
||||
glEnableVertexAttribArray(colourLoc);
|
||||
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.length * 2, ShortBuffer.wrap(indices), GL_DYNAMIC_DRAW);
|
||||
|
||||
glDrawElements(GL_TRIANGLES, num * 6, GL_UNSIGNED_SHORT, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(ArrayList<DebugGraphic> debugGraphics) {
|
||||
// Périmètre exclu de la phase 1 (voir doc de classe et Debug.java).
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroyAllTextures() {
|
||||
for (int[] data : textures.values()) {
|
||||
glDeleteTextures(1, new int[]{data[0]}, 0);
|
||||
}
|
||||
textures.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCameraPosition(float x, float y) {
|
||||
this.cameraX = Math.round(x);
|
||||
this.cameraY = Math.round(y);
|
||||
|
||||
calculateMatrices();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setScale(float scale) {
|
||||
this.scale = scale;
|
||||
|
||||
calculateMatrices();
|
||||
}
|
||||
|
||||
private void calculateMatrices() {
|
||||
java.util.Arrays.fill(projection, 0);
|
||||
java.util.Arrays.fill(view, 0);
|
||||
java.util.Arrays.fill(projectionAndView, 0);
|
||||
java.util.Arrays.fill(guiView, 0);
|
||||
java.util.Arrays.fill(guiProjectionAndView, 0);
|
||||
|
||||
Matrix.orthoM(projection, 0, screenWidth, screenHeight, 0, 0, 50);
|
||||
|
||||
Matrix.setLookAtM(view, 0, 0, 1, 0, 0, 0, 0, 1, 0);
|
||||
System.arraycopy(view, 0, guiView, 0, view.length);
|
||||
Matrix.translateM(view, -cameraX, -cameraY, 0);
|
||||
|
||||
Matrix.multiplyMM(projectionAndView, projection, view);
|
||||
Matrix.multiplyMM(guiProjectionAndView, projection, guiView);
|
||||
|
||||
/*
|
||||
* Le program/transformLoc ne sont valides qu'après le premier rendu
|
||||
* (init dans render()) : avant, glUniformMatrix4fv sur le programme 0
|
||||
* génère un GL_INVALID_OPERATION silencieux (spam de logs dans le
|
||||
* transiteur GL de l'émulateur). Les matrices seront re-poussées au
|
||||
* premier setGuiRenderMode de toute façon.
|
||||
*/
|
||||
if (program != -1 && transformLoc != 0) {
|
||||
glUniformMatrix4fv(transformLoc, 1, false, projectionAndView, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setScreenSize(int width, int height) {
|
||||
this.screenWidth = width;
|
||||
this.screenHeight = height;
|
||||
|
||||
glViewport(0, 0, width, height);
|
||||
|
||||
calculateMatrices();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGuiRenderMode(boolean guiRenderMode) {
|
||||
glUniformMatrix4fv(transformLoc, 1, false,
|
||||
guiRenderMode ? guiProjectionAndView : projectionAndView, 0);
|
||||
}
|
||||
|
||||
// ---- Helpers bindings GLES (tableaux + offsets explicites) ----
|
||||
|
||||
private static int genTexture() {
|
||||
int[] names = new int[1];
|
||||
GLES30.glGenTextures(1, names, 0);
|
||||
return names[0];
|
||||
}
|
||||
|
||||
private static int genBuffer() {
|
||||
int[] names = new int[1];
|
||||
GLES30.glGenBuffers(1, names, 0);
|
||||
return names[0];
|
||||
}
|
||||
|
||||
private static int genVertexArray() {
|
||||
int[] names = new int[1];
|
||||
GLES30.glGenVertexArrays(1, names, 0);
|
||||
return names[0];
|
||||
}
|
||||
}
|
||||
21
dethsquare/base/build.gradle
Normal file
21
dethsquare/base/build.gradle
Normal file
@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Module `base` du moteur Dethsquare : abstractions multi-plateformes
|
||||
* (Launcher, BaseGame, interfaces AudioUtils/IOUtils/PrefUtils/RenderUtils).
|
||||
* Aucune dépendance : le code est du Java pur.
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id 'java-library'
|
||||
}
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
// Le moteur cible Java 8 (contrainte historique du projet, et prérequis
|
||||
// pour la désugarisation côté Android plus tard).
|
||||
options.release = 8
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
package com.ezardlabs.dethsquare.debug;
|
||||
|
||||
abstract class DebugCircleBase extends DebugGraphic {
|
||||
protected float x;
|
||||
protected float y;
|
||||
protected float radius;
|
||||
|
||||
DebugCircleBase(float x, float y, float radius, float red, float green, float blue) {
|
||||
super(red, green, blue);
|
||||
this.x = x;
|
||||
this.y =y ;
|
||||
this.radius = radius;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
package com.ezardlabs.dethsquare.debug;
|
||||
|
||||
public abstract class DebugGraphic {
|
||||
public final float red;
|
||||
public final float green;
|
||||
public final float blue;
|
||||
|
||||
DebugGraphic(float red, float green, float blue) {
|
||||
this.red = red;
|
||||
this.green = green;
|
||||
this.blue = blue;
|
||||
}
|
||||
|
||||
public abstract void draw(float cameraX, float cameraY, float scale);
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
package com.ezardlabs.dethsquare.debug;
|
||||
|
||||
abstract class DebugRectBase extends DebugGraphic {
|
||||
protected final float x;
|
||||
protected final float y;
|
||||
protected final float width;
|
||||
protected final float height;
|
||||
|
||||
DebugRectBase(float x, float y, float width, float height, float red, float green, float blue) {
|
||||
super(red, green, blue);
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,84 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
/**
|
||||
* Interface for managing audio in a platform-specific way
|
||||
*/
|
||||
public interface AudioUtils {
|
||||
/**
|
||||
* Create and initialise the audio from the given path
|
||||
*
|
||||
* @param id The ID of the audio clip
|
||||
* @param path The path to the audio file
|
||||
*/
|
||||
void create(int id, String path);
|
||||
|
||||
/**
|
||||
* Play the audio file associated with the given audio clip ID
|
||||
*
|
||||
* @param id The ID of the audio clip
|
||||
*/
|
||||
void play(int id);
|
||||
|
||||
/**
|
||||
* Pause the audio file associated with the given audio clip ID
|
||||
*
|
||||
* @param id The ID of the audio clip
|
||||
*/
|
||||
void pause(int id);
|
||||
|
||||
/**
|
||||
* Stop the audio file associated with the given audio clip ID
|
||||
*
|
||||
* @param id The ID of the audio clip
|
||||
*/
|
||||
void stop(int id);
|
||||
|
||||
/**
|
||||
* Specify whether the audio clip with the given ID should loop or not
|
||||
*
|
||||
* @param id The ID of the audio clip
|
||||
* @param loop Whether to loop or not
|
||||
*/
|
||||
void setLoop(int id, boolean loop);
|
||||
|
||||
/**
|
||||
* Specify the volume of the audio clip with the given ID
|
||||
*
|
||||
* @param id The ID of the audio clip
|
||||
* @param volume The volume to set
|
||||
*/
|
||||
void setVolume(int id, float volume);
|
||||
|
||||
/**
|
||||
* Specify the location in the game world of an audio clip
|
||||
* @param id The ID of the audio clip
|
||||
* @param x The x coordinate of the audio clip
|
||||
* @param y The y coordinate of hte audio clip
|
||||
*/
|
||||
void setAudioPosition(int id, float x, float y);
|
||||
|
||||
/**
|
||||
* Specify the location in the game world of an audio listener
|
||||
* @param x The x coordinate of the audio listener
|
||||
* @param y The y coordinate of the audio listener
|
||||
*/
|
||||
void setListenerPosition(float x, float y);
|
||||
|
||||
/**
|
||||
* Destroy the audio file associated with the given audio clip ID
|
||||
*
|
||||
* @param id The ID of the audio clip
|
||||
*/
|
||||
void destroy(int id);
|
||||
|
||||
/**
|
||||
* Free all memory currently being used for managing, storing and
|
||||
* playing audio
|
||||
*/
|
||||
void destroyAll();
|
||||
|
||||
/**
|
||||
* Cleanly shutdown OpenAL
|
||||
*/
|
||||
void shutdown();
|
||||
}
|
||||
@ -0,0 +1,6 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
public abstract class BaseGame implements GameListeners {
|
||||
|
||||
public abstract void create();
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
public final class Dethsquare {
|
||||
public static Platform PLATFORM;
|
||||
public static AudioUtils AUDIO;
|
||||
public static IOUtils IO;
|
||||
public static PrefUtils PREFS;
|
||||
public static RenderUtils RENDER;
|
||||
|
||||
public enum Platform {
|
||||
ANDROID,
|
||||
DESKTOP
|
||||
}
|
||||
|
||||
public static void init(Platform platform, AudioUtils audio, IOUtils io, PrefUtils prefs, RenderUtils render) {
|
||||
PLATFORM = platform;
|
||||
AUDIO = audio;
|
||||
IO = io;
|
||||
PREFS = prefs;
|
||||
RENDER = render;
|
||||
GameLog.i("LS-INIT", "Dethsquare init: platform=" + platform
|
||||
+ " audio=" + audio.getClass().getSimpleName()
|
||||
+ " io=" + io.getClass().getSimpleName()
|
||||
+ " prefs=" + prefs.getClass().getSimpleName()
|
||||
+ " render=" + render.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
static class ResourceNotFoundError extends Error {
|
||||
|
||||
ResourceNotFoundError(String path) {
|
||||
super("Resource at '" + path + "' was not found");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,115 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public interface GameListeners {
|
||||
ArrayList<UpdateListener> updateListeners = new ArrayList<>();
|
||||
ArrayList<PostUpdateListener> postUpdateListeners = new ArrayList<>();
|
||||
ArrayList<RenderListener> renderListeners = new ArrayList<>();
|
||||
ArrayList<ResizeListener> resizeListeners = new ArrayList<>();
|
||||
ArrayList<MouseListener> mouseListeners = new ArrayList<>();
|
||||
ArrayList<KeyListener> keyListeners = new ArrayList<>();
|
||||
ArrayList<GamepadListener> gamepadListeners = new ArrayList<>();
|
||||
|
||||
ScreenSize screenSize = new ScreenSize();
|
||||
|
||||
class ScreenSize {
|
||||
public int width = 0;
|
||||
public int height = 0;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return width + ", " + height;
|
||||
}
|
||||
}
|
||||
|
||||
static void addUpdateListener(UpdateListener updateListener) {
|
||||
updateListeners.add(updateListener);
|
||||
}
|
||||
|
||||
static void removeUpdateListener(UpdateListener updateListener) {
|
||||
updateListeners.remove(updateListener);
|
||||
}
|
||||
|
||||
static void addPostUpdateListener(PostUpdateListener postUpdateListener) {
|
||||
postUpdateListeners.add(postUpdateListener);
|
||||
}
|
||||
|
||||
static void removePostUpdateListener(PostUpdateListener postUpdateListener) {
|
||||
postUpdateListeners.remove(postUpdateListener);
|
||||
}
|
||||
|
||||
static void addRenderListener(RenderListener renderListener) {
|
||||
renderListeners.add(renderListener);
|
||||
}
|
||||
|
||||
static void removeRenderListener(RenderListener renderListener) {
|
||||
renderListeners.remove(renderListener);
|
||||
}
|
||||
|
||||
static void addResizeListener(ResizeListener resizeListener) {
|
||||
resizeListeners.add(resizeListener);
|
||||
}
|
||||
|
||||
static void removeResizeListener(ResizeListener resizeListener) {
|
||||
resizeListeners.remove(resizeListener);
|
||||
}
|
||||
|
||||
static void addMouseListener(MouseListener mouseListener) {
|
||||
mouseListeners.add(mouseListener);
|
||||
}
|
||||
|
||||
static void removeMouseListener(MouseListener mouseListener) {
|
||||
mouseListeners.remove(mouseListener);
|
||||
}
|
||||
|
||||
static void addKeyListener(KeyListener keyListener) {
|
||||
keyListeners.add(keyListener);
|
||||
}
|
||||
|
||||
static void removeKeyListener(KeyListener keyListener) {
|
||||
keyListeners.remove(keyListener);
|
||||
}
|
||||
|
||||
static void addGamepadListener(GamepadListener gamepadListener) {
|
||||
gamepadListeners.add(gamepadListener);
|
||||
}
|
||||
|
||||
static void removeGamepadListener(GamepadListener gamepadListener) {
|
||||
gamepadListeners.remove(gamepadListener);
|
||||
}
|
||||
|
||||
interface UpdateListener {
|
||||
void onUpdate();
|
||||
}
|
||||
|
||||
interface PostUpdateListener {
|
||||
void onPostUpdate();
|
||||
}
|
||||
|
||||
interface RenderListener {
|
||||
void onRender();
|
||||
}
|
||||
|
||||
interface ResizeListener {
|
||||
void onResize(int width, int height);
|
||||
}
|
||||
|
||||
interface MouseListener {
|
||||
void onMove(int x, int y);
|
||||
void onButtonDown(int index);
|
||||
void onButtonUp(int index);
|
||||
}
|
||||
|
||||
interface KeyListener {
|
||||
void onKeyDown(String key);
|
||||
void onKeyUp(String key);
|
||||
}
|
||||
|
||||
interface GamepadListener {
|
||||
void onConnectionStateChanged(boolean connected);
|
||||
void onButtonDown(String button);
|
||||
void onButtonUp(String button);
|
||||
void onAxis(String axis, float value);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,97 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
/*
|
||||
* Journalisation multi-plateformes du moteur et du jeu.
|
||||
*
|
||||
* POURQUOI cette classe : le projet est un portage d'un jeu abandonné en 2017,
|
||||
* sans documentation ni tests — le seul moyen de diagnostiquer un bug est de
|
||||
* suivre ce qui se passe en EXÉCUTION, sur toutes les plateformes (desktop et
|
||||
* Android) avec la même API et le même format de messages.
|
||||
*
|
||||
* Design :
|
||||
* - statique et sans dépendance, comme le reste de `base` ;
|
||||
* - le SINK est fourni par le back-end plateforme : System.out/err sur
|
||||
* desktop (défaut), android.util.Log sur Android (branché par
|
||||
* AndroidLauncher.init()). Le code du moteur/jeu n'a donc AUCUNE
|
||||
* connaissance de la plateforme ;
|
||||
* - 4 niveaux : debug/info/warn/error. `debug` est réservé aux événements
|
||||
* répétitifs (entrées utilisateur, textures, boucle) : leur volume est
|
||||
* maîtrisé par le throttling aux sites d'appel.
|
||||
*
|
||||
* Conventions de tags (préfixe LS-, lisible dans logcat comme en console) :
|
||||
* LS-INIT initialisation moteur/plateforme
|
||||
* LS-LEVEL chargement de niveau (LevelManager)
|
||||
* LS-MAP maps TMX / procédural (MapManager, TMXLoader)
|
||||
* LS-MISSION logique de mission (DefenseMission, Director...)
|
||||
* LS-INPUT entrées (touches, touches tactiles, synthèse clavier Android)
|
||||
* LS-RENDER rendu (textures, shaders, tailles d'écran)
|
||||
* LS-AUDIO audio (création/lecture/pause des clips)
|
||||
* LS-PREFAB instanciation/destruction de GameObjects
|
||||
*/
|
||||
public final class GameLog {
|
||||
public interface Sink {
|
||||
void debug(String tag, String message);
|
||||
|
||||
void info(String tag, String message);
|
||||
|
||||
void warn(String tag, String message);
|
||||
|
||||
void error(String tag, String message);
|
||||
}
|
||||
|
||||
/** Sink par défaut desktop : console standard/erreur. */
|
||||
private static final Sink SYSTEM_SINK = new Sink() {
|
||||
@Override
|
||||
public void debug(String tag, String message) {
|
||||
System.out.println(tag + "/D: " + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String tag, String message) {
|
||||
System.out.println(tag + "/I: " + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String tag, String message) {
|
||||
System.err.println(tag + "/W: " + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String tag, String message) {
|
||||
System.err.println(tag + "/E: " + message);
|
||||
}
|
||||
};
|
||||
|
||||
private static Sink sink = SYSTEM_SINK;
|
||||
|
||||
private GameLog() {
|
||||
}
|
||||
|
||||
/** Remplace le sink (utilisé par AndroidLauncher pour android.util.Log). */
|
||||
public static void setSink(Sink newSink) {
|
||||
if (newSink != null) {
|
||||
sink = newSink;
|
||||
}
|
||||
}
|
||||
|
||||
public static void d(String tag, String message) {
|
||||
sink.debug(tag, message);
|
||||
}
|
||||
|
||||
public static void i(String tag, String message) {
|
||||
sink.info(tag, message);
|
||||
}
|
||||
|
||||
public static void w(String tag, String message) {
|
||||
sink.warn(tag, message);
|
||||
}
|
||||
|
||||
public static void e(String tag, String message) {
|
||||
sink.error(tag, message);
|
||||
}
|
||||
|
||||
public static void e(String tag, String message, Throwable t) {
|
||||
sink.error(tag, message);
|
||||
t.printStackTrace();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
|
||||
public interface IOUtils {
|
||||
BufferedReader getReader(String path);
|
||||
|
||||
String[] listFileNames(String dirPath);
|
||||
|
||||
InputStream getInputStream(String path);
|
||||
|
||||
String[] getFileLines(String path);
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare.Platform;
|
||||
|
||||
public abstract class Launcher implements GameListeners {
|
||||
|
||||
protected void init() {
|
||||
Dethsquare.init(getPlatform(), getAudio(), getIO(), getPrefs(), getRender());
|
||||
}
|
||||
|
||||
protected abstract Platform getPlatform();
|
||||
|
||||
protected abstract AudioUtils getAudio();
|
||||
|
||||
protected abstract IOUtils getIO();
|
||||
|
||||
protected abstract PrefUtils getPrefs();
|
||||
|
||||
protected abstract RenderUtils getRender();
|
||||
|
||||
public abstract void launch(BaseGame game);
|
||||
|
||||
protected final void update() {
|
||||
if (!updateListeners.isEmpty()) {
|
||||
for (Object o : updateListeners.toArray()) {
|
||||
((UpdateListener) o).onUpdate();
|
||||
}
|
||||
}
|
||||
if (!postUpdateListeners.isEmpty()) {
|
||||
for (Object o : postUpdateListeners.toArray()) {
|
||||
((PostUpdateListener) o).onPostUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected final void render() {
|
||||
renderListeners.forEach(RenderListener::onRender);
|
||||
}
|
||||
|
||||
protected final void onResize(int width, int height) {
|
||||
screenSize.width = width;
|
||||
screenSize.height = height;
|
||||
for (ResizeListener resizeListener : resizeListeners) {
|
||||
resizeListener.onResize(width, height);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,128 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
final class Matrix {
|
||||
|
||||
static void clear(float[] matrix) {
|
||||
Arrays.fill(matrix, 0);
|
||||
}
|
||||
|
||||
static void setIdentityM(float[] matrix) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
matrix[i] = 0;
|
||||
}
|
||||
for (int i = 0; i < 16; i += 5) {
|
||||
matrix[i] = 1.0f;
|
||||
}
|
||||
}
|
||||
|
||||
static float length(float x, float y, float z) {
|
||||
return (float) Math.sqrt(x * x + y * y + z * z);
|
||||
}
|
||||
|
||||
static void multiplyMM(float[] result, float[] lhs, float[] rhs) {
|
||||
for (int a = 0; a <= 12; a += 4) {
|
||||
for (int b = 0; b < 4; b++) {
|
||||
int c;
|
||||
int d;
|
||||
for (c = 0, d = 0; c < 4; c++, d += 4) {
|
||||
result[a + b] += rhs[a + c % 4] * lhs[d + b % 4];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void multiplyMV(float[] result, float[] lhsMatrix, float[] rhsVector) {
|
||||
result[0] = lhsMatrix[0] * rhsVector[0] + lhsMatrix[4] * rhsVector[1] +
|
||||
lhsMatrix[4 * 2] * rhsVector[2] + lhsMatrix[4 * 3] * rhsVector[3];
|
||||
result[1] = lhsMatrix[1] * rhsVector[0] + lhsMatrix[1 + 4] * rhsVector[1] +
|
||||
lhsMatrix[1 + 4 * 2] * rhsVector[2] + lhsMatrix[1 + 4 * 3] * rhsVector[3];
|
||||
result[2] = lhsMatrix[2] * rhsVector[0] + lhsMatrix[2 + 4] * rhsVector[1] +
|
||||
lhsMatrix[2 + 4 * 2] * rhsVector[2] + lhsMatrix[2 + 4 * 3] * rhsVector[3];
|
||||
result[3] = lhsMatrix[3] * rhsVector[0] + lhsMatrix[3 + 4] * rhsVector[1] +
|
||||
lhsMatrix[3 + 4 * 2] * rhsVector[2] + lhsMatrix[3 + 4 * 3] * rhsVector[3];
|
||||
}
|
||||
|
||||
static void orthoM(float[] result, float left, float right, float bottom, float top, float near,
|
||||
float far) {
|
||||
if (left == right) {
|
||||
throw new IllegalArgumentException("left == right");
|
||||
}
|
||||
if (bottom == top) {
|
||||
throw new IllegalArgumentException("bottom == top");
|
||||
}
|
||||
if (near == far) {
|
||||
throw new IllegalArgumentException("near == far");
|
||||
}
|
||||
final float w = 1.0f / (right - left);
|
||||
final float h = 1.0f / (top - bottom);
|
||||
final float d = 1.0f / (far - near);
|
||||
final float x = 2.0f * w;
|
||||
final float y = 2.0f * h;
|
||||
final float z = -2.0f * d;
|
||||
final float tx = -(right + left) * w;
|
||||
final float ty = -(top + bottom) * h;
|
||||
final float tz = -(far + near) * d;
|
||||
result[0] = x;
|
||||
result[5] = y;
|
||||
result[10] = z;
|
||||
result[12] = tx;
|
||||
result[13] = ty;
|
||||
result[14] = tz;
|
||||
result[15] = 1.0f;
|
||||
result[1] = 0.0f;
|
||||
result[2] = 0.0f;
|
||||
result[3] = 0.0f;
|
||||
result[4] = 0.0f;
|
||||
result[6] = 0.0f;
|
||||
result[7] = 0.0f;
|
||||
result[8] = 0.0f;
|
||||
result[9] = 0.0f;
|
||||
result[11] = 0.0f;
|
||||
}
|
||||
|
||||
static void setLookAtM(float[] result, float eyeX, float eyeY, float eyeZ, float centerX,
|
||||
float centerY, float centerZ, float upX, float upY, float upZ) {
|
||||
float fx = centerX - eyeX;
|
||||
float fy = centerY - eyeY;
|
||||
float fz = centerZ - eyeZ;
|
||||
float rlf = 1.0f / Matrix.length(fx, fy, fz);
|
||||
fx *= rlf;
|
||||
fy *= rlf;
|
||||
fz *= rlf;
|
||||
float sx = fy * upZ - fz * upY;
|
||||
float sy = fz * upX - fx * upZ;
|
||||
float sz = fx * upY - fy * upX;
|
||||
float rls = 1.0f / Matrix.length(sx, sy, sz);
|
||||
sx *= rls;
|
||||
sy *= rls;
|
||||
sz *= rls;
|
||||
float ux = sy * fz - sz * fy;
|
||||
float uy = sz * fx - sx * fz;
|
||||
float uz = sx * fy - sy * fx;
|
||||
result[0] = sx;
|
||||
result[1] = ux;
|
||||
result[2] = -fx;
|
||||
result[3] = 0.0f;
|
||||
result[4] = sy;
|
||||
result[5] = uy;
|
||||
result[6] = -fy;
|
||||
result[7] = 0.0f;
|
||||
result[8] = sz;
|
||||
result[9] = uz;
|
||||
result[10] = -fz;
|
||||
result[11] = 0.0f;
|
||||
result[12] = 0.0f;
|
||||
result[13] = 0.0f;
|
||||
result[14] = 0.0f;
|
||||
result[15] = 1.0f;
|
||||
translateM(result, -eyeX, -eyeY, -eyeZ);
|
||||
}
|
||||
|
||||
static void translateM(float[] m, float x, float y, float z) {
|
||||
for (int i = 0; i < 4; i++) {
|
||||
m[12 + i] += m[i] * x + m[4 + i] * y + m[8 + i] * z;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,78 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
/**
|
||||
* Interface for managing preferences in a platform-specific way
|
||||
*/
|
||||
public interface PrefUtils {
|
||||
/**
|
||||
* Set a boolean value
|
||||
*
|
||||
* @param key The name of the preference to modify
|
||||
* @param value The new value for the preference
|
||||
*/
|
||||
void setBoolean(String key, boolean value);
|
||||
|
||||
/**
|
||||
* Set an int value
|
||||
*
|
||||
* @param key The name of the preference to modify
|
||||
* @param value The new value for the preference
|
||||
*/
|
||||
void setInt(String key, int value);
|
||||
|
||||
/**
|
||||
* Set a float value
|
||||
*
|
||||
* @param key The name of the preference to modify
|
||||
* @param value The new value for the preference
|
||||
*/
|
||||
void setFloat(String key, float value);
|
||||
|
||||
/**
|
||||
* Set a string value
|
||||
*
|
||||
* @param key The name of the preference to modify
|
||||
* @param value The new value for the preference
|
||||
*/
|
||||
void setString(String key, String value);
|
||||
|
||||
/**
|
||||
* Retrieve a boolean value
|
||||
*
|
||||
* @param key The name of the preference to retrieve
|
||||
* @param defaultValue Value to return if this preference does not exist
|
||||
* @return Returns the preference value if it exists, or defaultValue if
|
||||
* it does not
|
||||
*/
|
||||
boolean getBoolean(String key, boolean defaultValue);
|
||||
|
||||
/**
|
||||
* Retrieve a boolean value
|
||||
*
|
||||
* @param key The name of the preference to retrieve
|
||||
* @param defaultValue Value to return if this preference does not exist
|
||||
* @return Returns the preference value if it exists, or defaultValue if
|
||||
* it does not
|
||||
*/
|
||||
int getInt(String key, int defaultValue);
|
||||
|
||||
/**
|
||||
* Retrieve a boolean value
|
||||
*
|
||||
* @param key The name of the preference to retrieve
|
||||
* @param defaultValue Value to return if this preference does not exist
|
||||
* @return Returns the preference value if it exists, or defaultValue if
|
||||
* it does not
|
||||
*/
|
||||
float getFloat(String key, float defaultValue);
|
||||
|
||||
/**
|
||||
* Retrieve a boolean value
|
||||
*
|
||||
* @param key The name of the preference to retrieve
|
||||
* @param defaultValue Value to return if this preference does not exist
|
||||
* @return Returns the preference value if it exists, or defaultValue if
|
||||
* it does not
|
||||
*/
|
||||
String getString(String key, String defaultValue);
|
||||
}
|
||||
@ -0,0 +1,46 @@
|
||||
package com.ezardlabs.dethsquare.util;
|
||||
|
||||
import com.ezardlabs.dethsquare.debug.DebugGraphic;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public interface RenderUtils {
|
||||
int[] loadImage(String path);
|
||||
|
||||
int loadShaderProgram(String vertexPath, String fragmentPath);
|
||||
|
||||
int loadShaderProgram(String directory);
|
||||
|
||||
int getUniformLocation(int program, String name);
|
||||
|
||||
int getAttributeLocation(int program, String name);
|
||||
|
||||
void render(int textureName, float[] vertices, float[] uvs, short[] indices, float[] colours, int num);
|
||||
|
||||
void render(ArrayList<DebugGraphic> debugGraphics);
|
||||
|
||||
void destroyAllTextures();
|
||||
|
||||
void setCameraPosition(float x, float y);
|
||||
|
||||
void setScale(float scale);
|
||||
|
||||
void setScreenSize(int width, int height);
|
||||
|
||||
void setGuiRenderMode(boolean guiRenderMode);
|
||||
|
||||
/*
|
||||
* Affiche/masque le curseur souris. Sans effet sur les plateformes sans
|
||||
* curseur (Android) — implémentation par défaut no-op pour éviter d'obliger
|
||||
* chaque back-end à la définir.
|
||||
*/
|
||||
default void setCursorVisible(boolean visible) {
|
||||
}
|
||||
|
||||
class ImageNotFoundError extends Error {
|
||||
|
||||
ImageNotFoundError(String path) {
|
||||
super("Image at " + path + " could not be found");
|
||||
}
|
||||
}
|
||||
}
|
||||
10
dethsquare/build.gradle
Normal file
10
dethsquare/build.gradle
Normal file
@ -0,0 +1,10 @@
|
||||
/*
|
||||
* Racine du moteur Dethsquare (projet `:dethsquare`).
|
||||
*
|
||||
* Aucune source ici : le projet n'existe que pour regrouper les sous-modules
|
||||
* de fichiers du moteur (core/base/desktop/android via settings-dethsquare.gradle)
|
||||
* et pour porter la documentation. La configuration de chaque module se trouve
|
||||
* désormais DANS le build.gradle de chaque module (base/, core/, desktop/),
|
||||
* ce qui remplace l'ancienne configuration croisée `project(':core') {}` de
|
||||
* 2017 — pattern déprécié puis retiré des Gradle modernes.
|
||||
*/
|
||||
29
dethsquare/core/.gitignore
vendored
Normal file
29
dethsquare/core/.gitignore
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### Java template
|
||||
*.class
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
### Gradle template
|
||||
.gradle
|
||||
build/
|
||||
|
||||
# Ignore Gradle GUI config
|
||||
gradle-app.setting
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
|
||||
# Cache of project
|
||||
.gradletasknamecache
|
||||
|
||||
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
|
||||
# gradle/wrapper/gradle-wrapper.properties
|
||||
28
dethsquare/core/build.gradle
Normal file
28
dethsquare/core/build.gradle
Normal file
@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Module `core` du moteur Dethsquare : GameObject/Component/Script, rendu
|
||||
* batché (GraphicsEngine), TMX, réseau, animation. Dépend de `base` et d'un
|
||||
* back-end plateforme choisi par la propriété `platform` (desktop|android),
|
||||
* qui expose l'API LWJGL (desktop) ou GLES (android).
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id 'java-library'
|
||||
}
|
||||
|
||||
def platform = (findProperty('platform') ?: 'desktop').toString()
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.release = 8
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api project(':base')
|
||||
api project(":$platform")
|
||||
implementation 'org.json:json:20240303'
|
||||
}
|
||||
169
dethsquare/core/gradlew
vendored
Normal file
169
dethsquare/core/gradlew
vendored
Normal file
@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn ( ) {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die ( ) {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
|
||||
function splitJvmOpts() {
|
||||
JVM_OPTS=("$@")
|
||||
}
|
||||
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
|
||||
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
|
||||
|
||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
||||
if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then
|
||||
cd "$(dirname "$0")"
|
||||
fi
|
||||
|
||||
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
|
||||
84
dethsquare/core/gradlew.bat
vendored
Normal file
84
dethsquare/core/gradlew.bat
vendored
Normal file
@ -0,0 +1,84 @@
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@ -0,0 +1,11 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
|
||||
public class AudioListener extends Script {
|
||||
|
||||
@Override
|
||||
public void update() {
|
||||
Dethsquare.AUDIO.setListenerPosition(transform.position.x, transform.position.y);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class AudioManager {
|
||||
private static float masterVolume = 0.5f;
|
||||
private static float musicVolume = 0.5f;
|
||||
private static float sfxVolume = 0.5f;
|
||||
private static ArrayList<AudioSource> audioSources = new ArrayList<>();
|
||||
|
||||
public enum AudioGroup {
|
||||
NONE,
|
||||
MUSIC,
|
||||
SFX
|
||||
}
|
||||
|
||||
public static void setMasterVolume(float volume) {
|
||||
rangeCheck(volume);
|
||||
masterVolume = volume;
|
||||
updateVolumes(null);
|
||||
}
|
||||
|
||||
public static void setMusicVolume(float volume) {
|
||||
rangeCheck(volume);
|
||||
musicVolume = volume;
|
||||
updateVolumes(AudioGroup.MUSIC);
|
||||
}
|
||||
|
||||
public static void setSfxVolume(float volume) {
|
||||
rangeCheck(volume);
|
||||
sfxVolume = volume;
|
||||
updateVolumes(AudioGroup.SFX);
|
||||
}
|
||||
|
||||
private static void updateVolumes(AudioGroup audioGroup) {
|
||||
for (AudioSource audioSource : audioSources) {
|
||||
if (audioGroup == null || audioSource.getAudioGroup() == audioGroup) {
|
||||
audioSource.setVolume(audioSource.getVolume());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void addAudioSource(AudioSource audioSource) {
|
||||
audioSources.add(audioSource);
|
||||
}
|
||||
|
||||
static void removeAudioSource(AudioSource audioSource) {
|
||||
audioSources.remove(audioSource);
|
||||
}
|
||||
|
||||
public static float getVolume(float volume, AudioGroup audioGroup) {
|
||||
rangeCheck(volume);
|
||||
switch (audioGroup) {
|
||||
case NONE:
|
||||
return volume * masterVolume;
|
||||
case MUSIC:
|
||||
return volume * musicVolume * masterVolume;
|
||||
case SFX:
|
||||
return volume * sfxVolume * masterVolume;
|
||||
default:
|
||||
return volume * masterVolume;
|
||||
}
|
||||
}
|
||||
|
||||
private static void rangeCheck(float volume) {
|
||||
if (volume < 0 || volume > 1) {
|
||||
throw new IllegalArgumentException("Volume must be between 0 and 1 inclusive");
|
||||
}
|
||||
}
|
||||
|
||||
static void clearAll() {
|
||||
audioSources.clear();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,144 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.AudioManager.AudioGroup;
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.AUDIO;
|
||||
|
||||
public final class AudioSource extends Script {
|
||||
private static final boolean LOOP_DEFAULT = false;
|
||||
private static final float VOLUME_DEFAULT = 1;
|
||||
private static final AudioGroup GROUP_DEFAULT = AudioGroup.NONE;
|
||||
private final AudioClip initial;
|
||||
private int current = -1;
|
||||
private boolean loop;
|
||||
private float volume;
|
||||
private AudioGroup audioGroup;
|
||||
|
||||
public AudioSource() {
|
||||
this(null, LOOP_DEFAULT, VOLUME_DEFAULT, GROUP_DEFAULT);
|
||||
}
|
||||
|
||||
public AudioSource(AudioClip audioClip) {
|
||||
this(audioClip, LOOP_DEFAULT, VOLUME_DEFAULT, GROUP_DEFAULT);
|
||||
}
|
||||
|
||||
public AudioSource(AudioGroup audioGroup) {
|
||||
this(null, LOOP_DEFAULT, VOLUME_DEFAULT, audioGroup);
|
||||
}
|
||||
|
||||
public AudioSource(AudioClip audioClip, boolean loop) {
|
||||
this(audioClip, loop, VOLUME_DEFAULT, GROUP_DEFAULT);
|
||||
}
|
||||
|
||||
public AudioSource(AudioClip audioClip, float volume) {
|
||||
this(audioClip, LOOP_DEFAULT, volume, GROUP_DEFAULT);
|
||||
}
|
||||
|
||||
public AudioSource(AudioClip audioClip, AudioGroup audioGroup) {
|
||||
this(audioClip, false, VOLUME_DEFAULT, audioGroup);
|
||||
}
|
||||
|
||||
public AudioSource(AudioClip audioClip, boolean loop, AudioGroup audioGroup) {
|
||||
this(audioClip, loop, VOLUME_DEFAULT, audioGroup);
|
||||
}
|
||||
|
||||
public AudioSource(AudioClip audioClip, float volume, AudioGroup audioGroup) {
|
||||
this(audioClip, LOOP_DEFAULT, volume, audioGroup);
|
||||
}
|
||||
|
||||
public AudioSource(AudioClip audioClip, boolean loop, float volume) {
|
||||
this(audioClip, loop, volume, GROUP_DEFAULT);
|
||||
}
|
||||
|
||||
public AudioSource(AudioClip audioClip, boolean loop, float volume, AudioGroup audioGroup) {
|
||||
initial = audioClip;
|
||||
this.loop = loop;
|
||||
this.volume = volume;
|
||||
this.audioGroup = audioGroup;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
if (initial != null) {
|
||||
current = initial.id;
|
||||
play();
|
||||
setLoop(loop);
|
||||
setVolume(volume);
|
||||
}
|
||||
AudioManager.addAudioSource(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update() {
|
||||
if (current != -1) {
|
||||
Dethsquare.AUDIO.setAudioPosition(current, transform.position.x, transform.position.y);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void destroy() {
|
||||
stop();
|
||||
AudioManager.removeAudioSource(this);
|
||||
}
|
||||
|
||||
public void play() {
|
||||
AUDIO.play(current);
|
||||
}
|
||||
|
||||
public void pause() {
|
||||
AUDIO.pause(current);
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
AUDIO.stop(current);
|
||||
}
|
||||
|
||||
public void setLoop(boolean loop) {
|
||||
this.loop = loop;
|
||||
AUDIO.setLoop(current, loop);
|
||||
}
|
||||
|
||||
public void setVolume(float volume) {
|
||||
volumeRangeCheck(volume);
|
||||
this.volume = volume;
|
||||
AUDIO.setVolume(current, AudioManager.getVolume(volume, audioGroup));
|
||||
}
|
||||
|
||||
public void setAudioClip(AudioClip audioClip) {
|
||||
current = audioClip.id;
|
||||
}
|
||||
|
||||
public boolean getLoop() {
|
||||
return loop;
|
||||
}
|
||||
|
||||
public float getVolume() {
|
||||
return volume;
|
||||
}
|
||||
|
||||
public AudioGroup getAudioGroup() {
|
||||
return audioGroup;
|
||||
}
|
||||
|
||||
private static void volumeRangeCheck(float volume) {
|
||||
if (volume < 0 || volume > 1) {
|
||||
throw new IllegalArgumentException("Volume must be between 0 and 1 inclusive");
|
||||
}
|
||||
}
|
||||
|
||||
public static final class AudioClip {
|
||||
private static int idCount = 0;
|
||||
private int id;
|
||||
|
||||
public AudioClip(String path) {
|
||||
id = idCount++;
|
||||
AUDIO.create(id, path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return (obj instanceof AudioClip) && ((AudioClip) obj).id == id;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
public interface Bounded {
|
||||
|
||||
RectF getBounds();
|
||||
|
||||
GameObject getGameObject();
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
|
||||
public final class Camera extends Script implements Bounded {
|
||||
public static Camera main;
|
||||
private final RectF bounds = new RectF();
|
||||
private boolean isMain = false;
|
||||
|
||||
public Camera(boolean main) {
|
||||
isMain = main;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
if (isMain) main = this;
|
||||
}
|
||||
|
||||
public void update() {
|
||||
bounds.left = transform.position.x;
|
||||
bounds.top = transform.position.y;
|
||||
bounds.right = bounds.left + Screen.width;
|
||||
bounds.bottom = bounds.top + Screen.height;
|
||||
|
||||
if (main == this) {
|
||||
Dethsquare.RENDER.setCameraPosition(transform.position.x, transform.position.y);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RectF getBounds() {
|
||||
return bounds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GameObject getGameObject() {
|
||||
return gameObject;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,278 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners.UpdateListener;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public final class Collider extends Component implements Bounded {
|
||||
static {
|
||||
GameListeners.addUpdateListener(new UpdateListener() {
|
||||
@Override
|
||||
public void onUpdate() {
|
||||
if (rebuildQuadTree) {
|
||||
qt.build(staticColliders);
|
||||
rebuildQuadTree = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static final ArrayList<Collider> normalColliders = new ArrayList<>();
|
||||
public static final ArrayList<Collider> staticColliders = new ArrayList<>();
|
||||
public static final ArrayList<Collider> triggerColliders = new ArrayList<>();
|
||||
public static QuadTree<Collider> qt = new QuadTree<>(20);
|
||||
private static boolean inited = false;
|
||||
private static boolean rebuildQuadTree = false;
|
||||
public final RectF lastBounds = new RectF();
|
||||
private final float height;
|
||||
private final float width;
|
||||
ArrayList<Collider> possible = new ArrayList<>();
|
||||
private Collider[] triggers = new Collider[0];
|
||||
private boolean isTrigger = false;
|
||||
private final Vector2 offset = new Vector2();
|
||||
|
||||
private final RectF bounds = new RectF();
|
||||
|
||||
public enum CollisionLocation {
|
||||
TOP,
|
||||
RIGHT,
|
||||
BOTTOM,
|
||||
LEFT
|
||||
}
|
||||
|
||||
public class Collision {
|
||||
/**
|
||||
* The {@link Collider} that was hit
|
||||
*/
|
||||
public final Collider collider;
|
||||
/**
|
||||
* The {@link GameObject} of the {@link Collider} that was hit
|
||||
*/
|
||||
public final GameObject gameObject;
|
||||
/**
|
||||
* The side of the {@link Collider} that was involved in the collision
|
||||
*/
|
||||
public final CollisionLocation location;
|
||||
/**
|
||||
* The speed at which the collision occurred
|
||||
*/
|
||||
public final float speed;
|
||||
/**
|
||||
* The {@link Transform} of the {@link Collider} that was hit
|
||||
*/
|
||||
public final Transform transform;
|
||||
/**
|
||||
* The {@link Rigidbody} of the {@link Collider} that was hit
|
||||
*/
|
||||
public final Rigidbody rigidbody;
|
||||
|
||||
Collision(Collider collider, GameObject gameObject, Transform transform, Rigidbody rigidbody,
|
||||
CollisionLocation location, float speed) {
|
||||
this.collider = collider;
|
||||
this.gameObject = gameObject;
|
||||
this.transform = transform;
|
||||
this.rigidbody = rigidbody;
|
||||
this.location = location;
|
||||
this.speed = speed;
|
||||
}
|
||||
}
|
||||
|
||||
public Collider(float width, float height) {
|
||||
this(width, height, 0, 0, false);
|
||||
}
|
||||
|
||||
public Collider(float width, float height, boolean isTrigger) {
|
||||
this(width, height, 0, 0, isTrigger);
|
||||
}
|
||||
|
||||
public Collider(float width, float height, float offsetX, float offsetY) {
|
||||
this(width, height, offsetX, offsetY, false);
|
||||
}
|
||||
|
||||
public Collider(float width, float height, float offsetX, float offsetY, boolean isTrigger) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.offset.set(offsetX, offsetY);
|
||||
this.isTrigger = isTrigger;
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
qt.build(staticColliders);
|
||||
inited = true;
|
||||
}
|
||||
|
||||
static void clearAll() {
|
||||
normalColliders.clear();
|
||||
staticColliders.clear();
|
||||
triggerColliders.clear();
|
||||
qt = new QuadTree<>(20);
|
||||
inited = false;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (gameObject.isStatic) {
|
||||
staticColliders.add(this);
|
||||
if (inited) {
|
||||
rebuildQuadTree = true;
|
||||
}
|
||||
}
|
||||
if (isTrigger) addTrigger();
|
||||
if (!gameObject.isStatic && !isTrigger) normalColliders.add(this);
|
||||
recalculateBounds();
|
||||
}
|
||||
|
||||
private void addTrigger() {
|
||||
triggerColliders.add(this);
|
||||
triggers = new Collider[triggerColliders.size()];
|
||||
}
|
||||
|
||||
private void removeTrigger() {
|
||||
triggerColliders.remove(this);
|
||||
triggers = new Collider[triggerColliders.size()];
|
||||
}
|
||||
|
||||
public void setIsTrigger(boolean isTrigger) {
|
||||
if (isTrigger == this.isTrigger) return;
|
||||
this.isTrigger = isTrigger;
|
||||
if (isTrigger) {
|
||||
addTrigger();
|
||||
} else {
|
||||
removeTrigger();
|
||||
}
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
if (gameObject.isStatic) staticColliders.remove(this);
|
||||
if (isTrigger) removeTrigger();
|
||||
if (!gameObject.isStatic && !isTrigger) normalColliders.remove(this);
|
||||
}
|
||||
|
||||
void move(float x, float y, float xSpeed, float ySpeed) {
|
||||
if (isTrigger) {
|
||||
transform.position.x += x;
|
||||
transform.position.y += y;
|
||||
recalculateBounds();
|
||||
triggerCheck();
|
||||
return;
|
||||
}
|
||||
possible.clear();
|
||||
|
||||
lastBounds.left = bounds.left;
|
||||
lastBounds.top = bounds.top;
|
||||
lastBounds.right = bounds.right;
|
||||
lastBounds.bottom = bounds.bottom;
|
||||
if (x > 0) bounds.right += x;
|
||||
if (x < 0) bounds.left += x;
|
||||
if (y > 0) bounds.bottom += y;
|
||||
if (y < 0) bounds.top += y;
|
||||
|
||||
qt.retrieve(possible, this);
|
||||
|
||||
bounds.left = lastBounds.left;
|
||||
bounds.top = lastBounds.top;
|
||||
bounds.right = lastBounds.right;
|
||||
bounds.bottom = lastBounds.bottom;
|
||||
|
||||
if (possible.isEmpty()) {
|
||||
transform.position.x += x;
|
||||
transform.position.y += y;
|
||||
} else {
|
||||
transform.position.y += y;
|
||||
recalculateBounds();
|
||||
Collider c;
|
||||
for (int i = 0; i < possible.size(); i++) {
|
||||
c = possible.get(i);
|
||||
if (c != this && c != null && !c.isTrigger && RectF.intersects(bounds, c.bounds)) {
|
||||
if (y > 0 && bounds.bottom > c.bounds.top) {
|
||||
transform.position.y = c.bounds.top - bounds.height() - offset.y;
|
||||
gameObject.onCollision(new Collision(c, c.gameObject, c.transform, c.gameObject.rigidbody,
|
||||
CollisionLocation.BOTTOM, ySpeed / Time.fpsScaling60));
|
||||
} else if (y < 0 && bounds.top < c.bounds.bottom) {
|
||||
transform.position.y = c.bounds.bottom - offset.y;
|
||||
if (transform.position.y != lastBounds.top) {
|
||||
gameObject.onCollision(new Collision(c, c.gameObject, c.transform, c.gameObject.rigidbody,
|
||||
CollisionLocation.TOP, ySpeed / Time.fpsScaling60));
|
||||
}
|
||||
}
|
||||
if (gameObject.rigidbody != null) {
|
||||
gameObject.rigidbody.velocity.y = 0;
|
||||
}
|
||||
recalculateBounds();
|
||||
}
|
||||
}
|
||||
transform.position.x += x;
|
||||
recalculateBounds();
|
||||
for (int i = 0; i < possible.size(); i++) {
|
||||
c = possible.get(i);
|
||||
if (c != this && c != null && !c.isTrigger && RectF.intersects(bounds, c.bounds)) {
|
||||
if (x > 0 && bounds.right > c.bounds.left) {
|
||||
transform.position.x = c.bounds.left - bounds.width() - offset.x;
|
||||
if (transform.position.x != lastBounds.left) {
|
||||
gameObject.onCollision(new Collision(c, c.gameObject, c.transform, c.gameObject.rigidbody,
|
||||
CollisionLocation.RIGHT, xSpeed / Time.fpsScaling60));
|
||||
}
|
||||
} else if (x < 0 && bounds.left < c.bounds.right) {
|
||||
transform.position.x = c.bounds.right - offset.x;
|
||||
if (transform.position.x != lastBounds.left) {
|
||||
gameObject.onCollision(new Collision(c, c.gameObject, c.transform, c.gameObject.rigidbody,
|
||||
CollisionLocation.LEFT, xSpeed / Time.fpsScaling60));
|
||||
}
|
||||
}
|
||||
if (gameObject.rigidbody != null) {
|
||||
gameObject.rigidbody.velocity.x = 0;
|
||||
}
|
||||
recalculateBounds();
|
||||
}
|
||||
}
|
||||
}
|
||||
recalculateBounds();
|
||||
triggerCheck();
|
||||
}
|
||||
|
||||
public void recalculateBounds() {
|
||||
bounds.left = transform.position.x + offset.x;
|
||||
bounds.top = transform.position.y + offset.y;
|
||||
bounds.right = transform.position.x + offset.x + width;
|
||||
bounds.bottom = transform.position.y + offset.y + height;
|
||||
}
|
||||
|
||||
public void triggerCheck() {
|
||||
if (isTrigger) {
|
||||
possible.clear();
|
||||
qt.retrieve(possible, this);
|
||||
for (Collider c : possible) {
|
||||
if (RectF.intersects(bounds, c.bounds)) {
|
||||
gameObject.onTriggerEnter(c);
|
||||
}
|
||||
}
|
||||
for (Collider c : normalColliders) {
|
||||
if (c != this && RectF.intersects(bounds, c.bounds)) {
|
||||
gameObject.onTriggerEnter(c);
|
||||
}
|
||||
}
|
||||
for (Collider c : triggerColliders.toArray(triggers)) {
|
||||
if (c != this && c != null && RectF.intersects(bounds, c.bounds)) {
|
||||
c.gameObject.onTriggerEnter(this);
|
||||
gameObject.onTriggerEnter(c);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (Collider c : triggerColliders) {
|
||||
if (c != this && RectF.intersects(bounds, c.bounds)) {
|
||||
c.gameObject.onTriggerEnter(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RectF getBounds() {
|
||||
return bounds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GameObject getGameObject() {
|
||||
return gameObject;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,108 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.Collider.Collision;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Base class for everything attached to {@link GameObject GameObjects}
|
||||
*/
|
||||
public class Component {
|
||||
/**
|
||||
* The {@link GameObject} this component is attached to. A component is always attached to a
|
||||
* {@link GameObject}
|
||||
*/
|
||||
public GameObject gameObject;
|
||||
/**
|
||||
* The {@link Transform} attached to the {@link GameObject} that this {@link Component} is also
|
||||
* attached to (null if there is none attached)
|
||||
*/
|
||||
public Transform transform;
|
||||
/**
|
||||
* Whether or not this {@link Component} is enabled
|
||||
*/
|
||||
public boolean enabled = true;
|
||||
|
||||
void internalStart() {
|
||||
for (Annotation a : getClass().getAnnotations()) {
|
||||
if (a instanceof RequiredComponents) {
|
||||
for (Class<? extends Component> c : ((RequiredComponents) a).value()) {
|
||||
if (!gameObject.hasComponentOfType(c)) {
|
||||
throw new RequiredComponentNotPresentError(gameObject.name, getClass(), c);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when this {@link Component} is first created
|
||||
*/
|
||||
public void start() {
|
||||
// Only used in subclasses
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when this {@link Component} is destroyed
|
||||
*/
|
||||
protected void destroy() {
|
||||
// Only used in subclasses
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the {@link Collider} other enters the trigger
|
||||
*
|
||||
* @param other The other {@link Collider} involved in the collision
|
||||
*/
|
||||
public void onTriggerEnter(Collider other) {
|
||||
// Only used in subclasses
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when this {@link Component}'s {@link Collider} collides with another {@link Collider}
|
||||
*
|
||||
* @param collision the {@link Collision} data associated with this collision
|
||||
*/
|
||||
public void onCollision(Collision collision) {
|
||||
// Only used in subclasses
|
||||
}
|
||||
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RequiredComponents {
|
||||
Class<? extends Component>[] value();
|
||||
}
|
||||
|
||||
private static class RequiredComponentNotPresentError extends Error {
|
||||
|
||||
private RequiredComponentNotPresentError(String gameObjectName, Class component, Class requiredComponent) {
|
||||
super(gameObjectName + ": Could not create " + addIndefiniteArticle(component.getSimpleName()) +
|
||||
" because it requires " + addIndefiniteArticle(requiredComponent.getSimpleName()) +
|
||||
", which was missing");
|
||||
}
|
||||
|
||||
private static String addIndefiniteArticle(String str) {
|
||||
switch (str.charAt(0)) {
|
||||
case 'a':
|
||||
case 'e':
|
||||
case 'i':
|
||||
case 'o':
|
||||
case 'u':
|
||||
case 'A':
|
||||
case 'E':
|
||||
case 'I':
|
||||
case 'O':
|
||||
case 'U':
|
||||
return "an '" + str + "'";
|
||||
default:
|
||||
return "a '" + str + "'";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,695 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.Collider.Collision;
|
||||
import com.ezardlabs.dethsquare.animation.Animator;
|
||||
import com.ezardlabs.dethsquare.graphics.GraphicsEngine;
|
||||
import com.ezardlabs.dethsquare.graphics.Renderer;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
import com.ezardlabs.dethsquare.util.GameLog;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.AUDIO;
|
||||
|
||||
/**
|
||||
* Base class for all entities in the game world
|
||||
*/
|
||||
public final class GameObject implements Serializable {
|
||||
// Add hook into game loop
|
||||
static {
|
||||
GameListeners.addUpdateListener(GameObject::updateAll);
|
||||
}
|
||||
|
||||
/**
|
||||
* List of all {@link GameObject GameObjects} to be instantiated at the end of the current frame
|
||||
*/
|
||||
private static final ArrayList<GameObject> newObjects = new ArrayList<>();
|
||||
/**
|
||||
* List of all {@link GameObject GameObjects} to be destroyed at the end of the current frame
|
||||
*/
|
||||
private static final HashMap<Long, GameObject> destroyedObjects = new HashMap<>();
|
||||
// private static final ArrayList<GameObject> destroyedObjects = new ArrayList<>();
|
||||
/**
|
||||
* Root of all {@link GameObject GameObjects} currently in the game world
|
||||
*/
|
||||
static final GameObject rootObject = new GameObject("<root>");
|
||||
/**
|
||||
* Structure containing all tags currently in use in the game world
|
||||
*/
|
||||
private static final HashMap<String, ArrayList<GameObject>> tags = new HashMap<>();
|
||||
/**
|
||||
* List of all {@link GameObject GameObjects} whose components have been modified in some way since last frame
|
||||
*/
|
||||
private static final ArrayList<GameObject> objectsWithChangedComponents = new ArrayList<>();
|
||||
/**
|
||||
* The name of the {@link GameObject}
|
||||
*/
|
||||
public String name;
|
||||
/**
|
||||
* The tag of this {@link GameObject}. Tags are used to define generic groups of {@link GameObject GameObjects} (e.g. players, enemies, etc)
|
||||
*/
|
||||
private String tag;
|
||||
/**
|
||||
* The layer that this {@link GameObject} is in. Must be in the range of [0..31]
|
||||
*/
|
||||
private int layer = 0;
|
||||
/**
|
||||
* Equivalent to {@code 1 << }{@link #layer}
|
||||
*/
|
||||
private int layerMask = 1;
|
||||
/**
|
||||
* Whether or not the {@link GameObject} is static, i.e. whether or not it will ever move.
|
||||
* Static {@link GameObject GameObjects} can have their rendering and collision optimised
|
||||
*/
|
||||
public final boolean isStatic;
|
||||
/**
|
||||
* List of {@link Component Components} currently attached to this {@link GameObject}
|
||||
*/
|
||||
private final ArrayList<Component> components = new ArrayList<>();
|
||||
/**
|
||||
* List of {@link Script Scripts} currently attached to this {@link GameObject}
|
||||
*/
|
||||
private final ArrayList<Script> scripts = new ArrayList<>();
|
||||
/**
|
||||
* List of {@link Component Components} that have been added to this {@link GameObject} since last frame
|
||||
*/
|
||||
private final ArrayList<Component> newComponents = new ArrayList<>();
|
||||
/**
|
||||
* List of {@link Component Components} that have been removed from this {@link GameObject} since last frame
|
||||
*/
|
||||
private final ArrayList<Class<?>> removedComponents = new ArrayList<>();
|
||||
/**
|
||||
* Fast access to this {@link GameObject}'s {@link Transform} component
|
||||
*/
|
||||
public Transform transform = new Transform(this);
|
||||
/**
|
||||
* Fast access to this {@link GameObject}'s {@link Animator} component
|
||||
*/
|
||||
public Animator animator;
|
||||
/**
|
||||
* Fast access to this {@link GameObject}'s {@link Renderer} component
|
||||
*/
|
||||
public Renderer renderer;
|
||||
/**
|
||||
* Fast access to this {@link GameObject}'s {@link Collider} component
|
||||
*/
|
||||
public Collider collider;
|
||||
/**
|
||||
* Fast access to this {@link GameObject}'s {@link Rigidbody} component
|
||||
*/
|
||||
public Rigidbody rigidbody;
|
||||
/**
|
||||
* The unique identifier for this {@link GameObject}; only used when instantiated across
|
||||
* the network
|
||||
*/
|
||||
public int networkId = -1;
|
||||
/**
|
||||
* Whether or not this {@link GameObject} has been instantiated yet
|
||||
*/
|
||||
private boolean instantiated = false;
|
||||
/**
|
||||
* Whether or not this {@link GameObject} is active
|
||||
*/
|
||||
private boolean active = true;
|
||||
/**
|
||||
* Method that is run when this {@link GameObject} is destroyed
|
||||
*/
|
||||
private Runnable destructionCallback = null;
|
||||
|
||||
public GameObject() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public GameObject(String name, Component... components) {
|
||||
this(name, null, false, components);
|
||||
}
|
||||
|
||||
public GameObject(String name, String tag) {
|
||||
this(name, tag, false);
|
||||
}
|
||||
|
||||
public GameObject(String name, String tag, Component... components) {
|
||||
this(name, tag, false, components);
|
||||
}
|
||||
|
||||
public GameObject(String name, boolean isStatic, Component... components) {
|
||||
this(name, null, isStatic, components);
|
||||
}
|
||||
|
||||
public GameObject(String name, String tag, boolean isStatic, Component... components) {
|
||||
this.name = name;
|
||||
setTag(tag);
|
||||
this.isStatic = isStatic;
|
||||
addComponent(transform, instantiated);
|
||||
for (Component c : components) {
|
||||
addComponent(c, instantiated);
|
||||
}
|
||||
}
|
||||
|
||||
private GameObject(String name, boolean isStatic, Transform transform) {
|
||||
this.name = name;
|
||||
this.isStatic = isStatic;
|
||||
this.transform = transform;
|
||||
addComponent(transform, instantiated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches a {@link Component} to this {@link GameObject}. If a {@link Component} of the same
|
||||
* type is already present, then it is automatically replaced
|
||||
*
|
||||
* @param component The {@link Component} to attach to this {@link GameObject}
|
||||
* @param <T> The type of the {@link Component}
|
||||
* @return The {@link Component} that has just been attached
|
||||
*/
|
||||
public <T extends Component> T addComponent(T component) {
|
||||
return addComponent(component, instantiated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches a {@link Component} to this {@link GameObject}. If a {@link Component} of the same
|
||||
* type is already present, then it is automatically replaced
|
||||
*
|
||||
* @param component The {@link Component} to attach to this {@link GameObject}
|
||||
* @param callStart Whether or not to call the {@link Component#start()} method on the newly
|
||||
* added {@link Component}
|
||||
* @param <T> The type of the {@link Component}
|
||||
* @return The {@link Component} that has just been attached
|
||||
*/
|
||||
private <T extends Component> T addComponent(T component, boolean callStart) {
|
||||
if (component == null) {
|
||||
/*
|
||||
* Garde-fou de diagnostic : un composant null ici signifiait un NPE
|
||||
* obscur ("getClass() on null reference") dans un constructeur
|
||||
* GameObject en amont. On journalise le contexte et on relance avec
|
||||
* un message explicite (le nom du GameObject est en amont du stack).
|
||||
*/
|
||||
GameLog.e("LS-PREFAB", "addComponent(null) on GameObject '" + name + "'");
|
||||
throw new IllegalStateException(
|
||||
"addComponent(null) on GameObject '" + name + "' (caller should pass a real Component)");
|
||||
}
|
||||
if (getComponent(component.getClass()) != null) {
|
||||
throw new ComponentAlreadyExistsError(component);
|
||||
}
|
||||
newComponents.add(component);
|
||||
if (callStart) {
|
||||
objectsWithChangedComponents.add(this);
|
||||
}
|
||||
return component;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a {@link Component} of the given type is attached to
|
||||
* this {@link GameObject}
|
||||
*
|
||||
* @param type The type of the {@link Component}
|
||||
* @return True if the {@link Component} is attached; false otherwise
|
||||
*/
|
||||
public boolean hasComponent(Class<? extends Component> type) {
|
||||
for (Component c : components) {
|
||||
if (c.getClass().equals(type)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (Component c : newComponents) {
|
||||
if (c.getClass().equals(type)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a {@link Component} of the given type or any subclass
|
||||
* of that type is attached to this {@link GameObject}
|
||||
*
|
||||
* @param type The type of the {@link Component}
|
||||
* @return True if the {@link Component} is attached; false otherwise
|
||||
*/
|
||||
public boolean hasComponentOfType(Class<? extends Component> type) {
|
||||
for (Component c : components) {
|
||||
if (type.isAssignableFrom(c.getClass())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (Component c : newComponents) {
|
||||
if (type.isAssignableFrom(c.getClass())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the {@link Component} of the given type if the {@link GameObject} has one
|
||||
* attached, null if it doesn't
|
||||
*
|
||||
* @param type The type of {@link Component} to retrieve
|
||||
*/
|
||||
public <T extends Component> T getComponent(Class<T> type) {
|
||||
for (Component c : components) {
|
||||
if (c.getClass().equals(type)) {
|
||||
return type.cast(c);
|
||||
}
|
||||
}
|
||||
for (Component c : newComponents) {
|
||||
if (c.getClass().equals(type)) {
|
||||
return type.cast(c);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the first {@link Component} of the given type
|
||||
*
|
||||
* @param type The type of the {@link Component} to get
|
||||
* @param <T> The type to automatically cast the result to
|
||||
* @return The first {@link Component} of the given type
|
||||
*/
|
||||
public <T extends Component> T getComponentOfType(Class<T> type) {
|
||||
for (Component c : components) {
|
||||
if (type.isAssignableFrom(c.getClass())) {
|
||||
//noinspection unchecked
|
||||
return (T) c;
|
||||
}
|
||||
}
|
||||
for (Component c : newComponents) {
|
||||
if (type.isAssignableFrom(c.getClass())) {
|
||||
//noinspection unchecked
|
||||
return (T) c;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all {@link Component}s of the given type
|
||||
*
|
||||
* @param type The type of the {@link Component}s to get
|
||||
* @param <T> The type to automatically cast the result to
|
||||
* @return All {@link Component}s of the given type
|
||||
*/
|
||||
public <T extends Component> List<T> getComponentsOfType(Class<T> type) {
|
||||
//noinspection unchecked
|
||||
return Stream.concat(components.stream(), newComponents.stream())
|
||||
.filter(c -> type.isAssignableFrom(c.getClass()))
|
||||
.map(c -> (T) c)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the {@link Component} of the given type from this {@link GameObject} if it exists.
|
||||
* If it doesn't exist then nothing happens
|
||||
*
|
||||
* @param type The type of {@link Component} to remove from this {@link GameObject}
|
||||
* @return The removed {@link Component} if it existed; otherwise null
|
||||
*/
|
||||
public <T extends Component> T removeComponent(Class<T> type) {
|
||||
if (type.equals(Transform.class)) {
|
||||
throw new IllegalArgumentException("Cannot remove the Transform type of a GameObject");
|
||||
}
|
||||
removedComponents.add(type);
|
||||
objectsWithChangedComponents.add(this);
|
||||
for (Component c : components) {
|
||||
if (c.getClass().equals(type)) {
|
||||
//noinspection unchecked
|
||||
return (T) c;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the tag of this {@link GameObject}
|
||||
*
|
||||
* @param tag The tag to give to this {@link GameObject}
|
||||
*/
|
||||
public void setTag(String tag) {
|
||||
if (tag == null) {
|
||||
if (this.tag != null) {
|
||||
tags.get(this.tag).remove(this);
|
||||
if (tags.get(this.tag).size() == 0) {
|
||||
tags.remove(this.tag);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (this.tag == null) {
|
||||
if (!tags.containsKey(tag)) {
|
||||
tags.put(tag, new ArrayList<>());
|
||||
}
|
||||
tags.get(tag).add(this);
|
||||
} else {
|
||||
tags.get(this.tag).remove(this);
|
||||
if (tags.get(this.tag).size() == 0) {
|
||||
tags.remove(this.tag);
|
||||
}
|
||||
if (!tags.containsKey(tag)) {
|
||||
tags.put(tag, new ArrayList<>());
|
||||
}
|
||||
tags.get(tag).add(this);
|
||||
}
|
||||
}
|
||||
this.tag = tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the tag of this {@link GameObject}
|
||||
*
|
||||
* @return The tag of this {@link GameObject}
|
||||
*/
|
||||
public String getTag() {
|
||||
return tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the layer that this {@link GameObject} is in
|
||||
*
|
||||
* @param layer The layer that this {@link GameObject} should be in. Must be in the range [0..31]
|
||||
*/
|
||||
public void setLayer(int layer) {
|
||||
if (layer < 0 || layer > 31) {
|
||||
throw new IllegalArgumentException("Layer must be in the range [0..31]");
|
||||
}
|
||||
this.layer = layer;
|
||||
this.layerMask = 1 << layer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the layer that this {@link GameObject} is in
|
||||
*
|
||||
* @return The layer that this {@link GameObject} is in
|
||||
*/
|
||||
public int getLayer() {
|
||||
return layer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the layer mask for this {@link GameObject}
|
||||
*
|
||||
* @return This {@link GameObject}'s layer mask
|
||||
*/
|
||||
public int getLayerMask() {
|
||||
return layerMask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Activates/deactivates this {@link GameObject}
|
||||
*
|
||||
* @param active Whether to activate or deactivate this {@link GameObject}
|
||||
*/
|
||||
public void setActive(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether or not this {@link GameObject} is active. Note that the {@link GameObject} will only be treated as
|
||||
* active in the game world iff it is active and all parent {@link GameObject GameObjects} are active
|
||||
*
|
||||
* @return Whether or not this {@link GameObject} is active
|
||||
*/
|
||||
public boolean isActiveSelf() {
|
||||
return active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether or not this {@link GameObject} is active and all of its parent {@link GameObject GameObjects} are
|
||||
* active. Note that the {@link GameObject} will only be treated as active in the game world iff it is active and
|
||||
* all parent {@link GameObject GameObjects} are active
|
||||
*
|
||||
* @return Whether or not this {@link GameObject} is active and all of its parent {@link GameObject GameObjects}
|
||||
* are active
|
||||
*/
|
||||
public boolean isActive() {
|
||||
if (transform.getParent() != null) {
|
||||
return active && transform.getParent().gameObject.isActive();
|
||||
} else {
|
||||
return active;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when another {@link Collider} has entered this {@link GameObject GameObject's} trigger {@link Collider}
|
||||
*
|
||||
* @param collider The other {@link Collider} that has entered this {@link GameObject GameObject's} trigger {@link Collider}
|
||||
*/
|
||||
void onTriggerEnter(Collider collider) {
|
||||
for (Component component : components) {
|
||||
component.onTriggerEnter(collider);
|
||||
}
|
||||
}
|
||||
|
||||
void onCollision(Collision collision) {
|
||||
for (int i = 0; i < components.size(); i++) {
|
||||
components.get(i).onCollision(collision);
|
||||
}
|
||||
}
|
||||
|
||||
private void update() {
|
||||
if (Time.isPaused()) {
|
||||
scripts.stream().filter(script -> script.enabled && script.runWhenPaused).forEach(Script::update);
|
||||
} else {
|
||||
scripts.stream().filter(script -> script.enabled).forEach(Script::update);
|
||||
}
|
||||
transform.children.stream()
|
||||
.filter(child -> child.gameObject.active)
|
||||
.map(child -> child.gameObject)
|
||||
.forEachOrdered(GameObject::update);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the given {@link GameObject} within the game world
|
||||
*
|
||||
* @param gameObject The {@link GameObject} to create
|
||||
* @param position The coordinates to create the given {@link GameObject} at
|
||||
* @return The {@link GameObject} that was passed into this method as a parameter
|
||||
*/
|
||||
public static GameObject instantiate(GameObject gameObject, Vector2 position) {
|
||||
return instantiate(gameObject, position, new Vector2(1, 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the given {@link GameObject} within the game world
|
||||
*
|
||||
* @param gameObject The {@link GameObject} to create
|
||||
* @param position The coordinates to create the given {@link GameObject} at
|
||||
* @param scale The scale to create the {@link GameObject} at
|
||||
* @return The {@link GameObject} that was passed into this method as a parameter
|
||||
*/
|
||||
public static GameObject instantiate(GameObject gameObject, Vector2 position, Vector2 scale) {
|
||||
gameObject.transform.position.set(position);
|
||||
gameObject.transform.scale.set(scale);
|
||||
GameObject go = gameObject.copy();
|
||||
newObjects.add(go);
|
||||
objectsWithChangedComponents.add(go);
|
||||
go.instantiated = true;
|
||||
return go;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the given {@link GameObject} from the game world
|
||||
*
|
||||
* @param gameObject The {@link GameObject} to remove from the game world
|
||||
*/
|
||||
public static void destroy(GameObject gameObject) {
|
||||
destroy(gameObject, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the given {@link GameObject} from the game world after a given time period has elapsed
|
||||
*
|
||||
* @param gameObject The {@link GameObject} to remove from the game world
|
||||
* @param delay The time period to wait before the given {@link GameObject} is destroyed
|
||||
*/
|
||||
public static void destroy(GameObject gameObject, long delay) {
|
||||
destroy(gameObject, delay, null);
|
||||
}
|
||||
|
||||
public static void destroy(GameObject gameObject, long delay, Runnable callback) {
|
||||
gameObject.destructionCallback = callback;
|
||||
destroyedObjects.put(System.nanoTime() + delay * 1000000L, gameObject);
|
||||
}
|
||||
|
||||
private void searchDestroyNetworked(int networkId) {
|
||||
if (this.networkId == networkId) {
|
||||
destroy(this);
|
||||
} else if (!transform.children.isEmpty()) {
|
||||
for (Transform child : transform.children) {
|
||||
child.gameObject.searchDestroyNetworked(networkId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the {@link GameObject} with the given network ID from the game world
|
||||
*
|
||||
* @param networkId The network ID of the {@link GameObject} to remove from the game world
|
||||
*/
|
||||
public static void destroy(int networkId) {
|
||||
if (networkId < 0) return;
|
||||
rootObject.searchDestroyNetworked(networkId);
|
||||
}
|
||||
|
||||
static void startAll() {
|
||||
handleCreationDestruction();
|
||||
}
|
||||
|
||||
private static void updateAll() {
|
||||
handleCreationDestruction();
|
||||
|
||||
rootObject.update();
|
||||
}
|
||||
|
||||
static void destroyAll() {
|
||||
rootObject.transform.children.clear();
|
||||
newObjects.clear();
|
||||
destroyedObjects.clear();
|
||||
objectsWithChangedComponents.clear();
|
||||
/*
|
||||
* Purger aussi le registre des tags : sans ça, les GameObjects du
|
||||
* niveau précédent restaient "trouvables" via findAllWithTag au
|
||||
* chargement du niveau suivant (2ᵉ DefenseMission voyait 2 cryopods
|
||||
* au lieu d'1 — fuite d'état inter-niveaux du moteur d'origine).
|
||||
*/
|
||||
tags.clear();
|
||||
GraphicsEngine.clearAll();
|
||||
GraphicsEngine.clearQuadTree();
|
||||
GraphicsEngine.destroyAllTextures();
|
||||
TextureAtlas.clearCache();
|
||||
Collider.clearAll();
|
||||
AUDIO.destroyAll();
|
||||
AudioManager.clearAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all {@link GameObject GameObjects} with the given tag
|
||||
*
|
||||
* @param tag The name of the tag to search all objects for
|
||||
* @return an array of all {@link GameObject GameObjects} with the given tag
|
||||
*/
|
||||
public static GameObject[] findAllWithTag(String tag) {
|
||||
if (tags.containsKey(tag)) {
|
||||
return tags.get(tag).toArray(new GameObject[tags.get(tag).size()]);
|
||||
} else {
|
||||
return new GameObject[0];
|
||||
}
|
||||
}
|
||||
|
||||
private static void handleDestruction() {
|
||||
destroyedObjects.entrySet()
|
||||
.stream()
|
||||
.filter(entry -> entry.getKey() <= System.nanoTime())
|
||||
.forEachOrdered(entry -> {
|
||||
GameObject gameObject = entry.getValue();
|
||||
if (gameObject != null) {
|
||||
for (Component c : gameObject.components) {
|
||||
c.destroy();
|
||||
}
|
||||
gameObject.transform.parent.children.remove(gameObject.transform);
|
||||
newObjects.remove(gameObject);
|
||||
objectsWithChangedComponents.remove(gameObject);
|
||||
if (gameObject.destructionCallback != null) {
|
||||
gameObject.destructionCallback.run();
|
||||
}
|
||||
entry.setValue(null);
|
||||
}
|
||||
});
|
||||
destroyedObjects.entrySet().removeIf(entry -> entry.getValue() == null);
|
||||
}
|
||||
|
||||
private static void handleRemovedComponents(GameObject go) {
|
||||
for (Class clazz : go.removedComponents) {
|
||||
for (Component c : go.components.toArray(new Component[go.components.size()])) {
|
||||
if (c.getClass().equals(clazz)) {
|
||||
if (c instanceof Renderer) {
|
||||
go.renderer = null;
|
||||
} else if (c instanceof Animator) {
|
||||
go.animator = null;
|
||||
} else if (c instanceof Collider) {
|
||||
go.collider = null;
|
||||
} else if (c instanceof Rigidbody) {
|
||||
go.rigidbody = null;
|
||||
}
|
||||
go.components.remove(c);
|
||||
if (c instanceof Script) {
|
||||
go.scripts.remove(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
go.removedComponents.clear();
|
||||
}
|
||||
|
||||
private static ArrayList<Component> handleNewComponents(GameObject go) {
|
||||
ArrayList<Component> temp = new ArrayList<>();
|
||||
for (Component component : go.newComponents) {
|
||||
if (component instanceof Transform) {
|
||||
go.transform = (Transform) component;
|
||||
} else if (component instanceof Renderer) {
|
||||
go.renderer = (Renderer) component;
|
||||
} else if (component instanceof Animator) {
|
||||
go.animator = (Animator) component;
|
||||
} else if (component instanceof Collider) {
|
||||
go.collider = (Collider) component;
|
||||
} else if (component instanceof Rigidbody) {
|
||||
go.rigidbody = (Rigidbody) component;
|
||||
}
|
||||
if (component instanceof Script) {
|
||||
go.scripts.add((Script) component);
|
||||
}
|
||||
component.gameObject = go;
|
||||
component.transform = go.transform;
|
||||
go.components.add(component);
|
||||
temp.add(component);
|
||||
}
|
||||
go.newComponents.clear();
|
||||
return temp;
|
||||
}
|
||||
|
||||
private static void handleCreationDestruction() {
|
||||
handleDestruction();
|
||||
|
||||
newObjects.parallelStream()
|
||||
.filter(gameObject -> gameObject.transform.parent == null)
|
||||
.forEachOrdered(gameObject -> gameObject.transform.setParent(rootObject.transform));
|
||||
|
||||
ArrayList<Component> temp = new ArrayList<>();
|
||||
|
||||
for (GameObject go : objectsWithChangedComponents) {
|
||||
handleRemovedComponents(go);
|
||||
|
||||
temp.addAll(handleNewComponents(go));
|
||||
}
|
||||
|
||||
objectsWithChangedComponents.clear();
|
||||
newObjects.clear();
|
||||
|
||||
for (Component component : temp) {
|
||||
component.internalStart();
|
||||
}
|
||||
}
|
||||
|
||||
private GameObject copy() {
|
||||
GameObject gameObject = new GameObject(name, isStatic, transform);
|
||||
transform.gameObject = gameObject;
|
||||
Stream.concat(components.stream(), newComponents.stream()).forEach(c -> {
|
||||
if (!(c instanceof Transform)) gameObject.addComponent(c);
|
||||
});
|
||||
String tag = this.tag;
|
||||
setTag(null);
|
||||
gameObject.setTag(tag);
|
||||
gameObject.networkId = networkId;
|
||||
return gameObject;
|
||||
}
|
||||
|
||||
private static class ComponentAlreadyExistsError extends Error {
|
||||
|
||||
private ComponentAlreadyExistsError(Component component) {
|
||||
super("Component of type " + component.getClass() + " already exists on this GameObject");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,68 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.graphics.Renderer;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
|
||||
public class GuiRenderer extends Renderer {
|
||||
private static int referenceScreenWidth = 1920;
|
||||
private static int referenceScreenHeight = 1080;
|
||||
private static ScaleMode referenceScreenScaleMode = ScaleMode.WIDTH;
|
||||
static float referenceScreenScale = 1;
|
||||
|
||||
static {
|
||||
GameListeners.addResizeListener((width, height) -> updateReferenceScreenScale());
|
||||
}
|
||||
|
||||
public enum ScaleMode {
|
||||
WIDTH,
|
||||
HEIGHT
|
||||
}
|
||||
|
||||
public GuiRenderer(String imagePath, float width, float height) {
|
||||
super(imagePath, width, height);
|
||||
}
|
||||
|
||||
public GuiRenderer(TextureAtlas textureAtlas, TextureAtlas.Sprite sprite, float width, float height) {
|
||||
super(textureAtlas, sprite, width, height);
|
||||
}
|
||||
|
||||
public boolean hitTest(float x, float y) {
|
||||
return getBounds().contains(x, y);
|
||||
}
|
||||
|
||||
public boolean hitTest(Vector2 position) {
|
||||
return hitTest(position.x, position.y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RectF getBounds() {
|
||||
bounds.set(getXPos() * referenceScreenScale, getYPos() * referenceScreenScale,
|
||||
(getXPos() + width) * referenceScreenScale, (getYPos() + height) * referenceScreenScale);
|
||||
return bounds;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected byte getLayer() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
public static void setReferenceScreenSize(int width, int height, ScaleMode scaleMode) {
|
||||
GuiRenderer.referenceScreenWidth = width;
|
||||
GuiRenderer.referenceScreenHeight = height;
|
||||
GuiRenderer.referenceScreenScaleMode = scaleMode;
|
||||
updateReferenceScreenScale();
|
||||
}
|
||||
|
||||
private static void updateReferenceScreenScale() {
|
||||
switch (referenceScreenScaleMode) {
|
||||
case WIDTH:
|
||||
referenceScreenScale = (float) Screen.width / (float) referenceScreenWidth;
|
||||
break;
|
||||
case HEIGHT:
|
||||
referenceScreenScale = (float) Screen.height / (float) referenceScreenHeight;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,223 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
|
||||
|
||||
public class GuiText extends Component implements Bounded {
|
||||
private final RectF bounds = new RectF();
|
||||
private String text;
|
||||
private TextureAtlas font;
|
||||
private float fontSize;
|
||||
private int depth;
|
||||
private float spaceWidth;
|
||||
private float letterSpacing = -1;
|
||||
private float totalWidth = -1;
|
||||
public GameObject[] characters = new GameObject[0];
|
||||
|
||||
private boolean started = false;
|
||||
|
||||
public GuiText(String text, TextureAtlas font, float fontSize) {
|
||||
this(text, font, fontSize, -1, 0);
|
||||
}
|
||||
|
||||
public GuiText(String text, TextureAtlas font, float fontSize, int depth) {
|
||||
this(text, font, fontSize, -1, depth);
|
||||
}
|
||||
|
||||
public GuiText(String text, TextureAtlas font, float fontSize, float letterSpacing) {
|
||||
this(text, font, fontSize, letterSpacing, 0);
|
||||
}
|
||||
|
||||
public GuiText(String text, TextureAtlas font, float fontSize, float letterSpacing, int depth) {
|
||||
this.text = text;
|
||||
this.font = font;
|
||||
this.fontSize = fontSize;
|
||||
this.letterSpacing = letterSpacing;
|
||||
this.depth = depth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
started = true;
|
||||
calculateSpaceWidth();
|
||||
generateRenderers();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void destroy() {
|
||||
for (int i = 0; i < characters.length; i++) {
|
||||
GameObject.destroy(characters[i], 1);
|
||||
}
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
if (started) generateRenderers();
|
||||
}
|
||||
|
||||
public TextureAtlas getFont() {
|
||||
return font;
|
||||
}
|
||||
|
||||
public void setFont(TextureAtlas font) {
|
||||
this.font = font;
|
||||
calculateSpaceWidth();
|
||||
if (started) generateRenderers();
|
||||
}
|
||||
|
||||
public float getFontSize() {
|
||||
return fontSize;
|
||||
}
|
||||
|
||||
public void setFontSize(float fontSize) {
|
||||
this.fontSize = fontSize;
|
||||
calculateSpaceWidth();
|
||||
if (started) generateRenderers();
|
||||
}
|
||||
|
||||
public float getWidth() {
|
||||
if (totalWidth != -1) return totalWidth;
|
||||
float width = 0;
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
Sprite s = null;
|
||||
boolean shouldContinue = false;
|
||||
switch (text.charAt(i)) {
|
||||
case ' ':
|
||||
width += spaceWidth;
|
||||
shouldContinue = true;
|
||||
break;
|
||||
case '!':
|
||||
s = font.getSprite("exclamation-mark");
|
||||
break;
|
||||
case '?':
|
||||
s = font.getSprite("question-mark");
|
||||
break;
|
||||
case '.':
|
||||
s = font.getSprite("period");
|
||||
break;
|
||||
case ':':
|
||||
s = font.getSprite("colon");
|
||||
break;
|
||||
default:
|
||||
s = font.getSprite(String.valueOf(text.charAt(i)));
|
||||
break;
|
||||
}
|
||||
if (shouldContinue || s == null) continue;
|
||||
|
||||
width += (s.w / s.h) * fontSize + getLetterSpacing();
|
||||
}
|
||||
width -= getLetterSpacing();
|
||||
totalWidth = width;
|
||||
return width;
|
||||
}
|
||||
|
||||
private void generateRenderers() {
|
||||
if (text == null) text = "";
|
||||
|
||||
if (text.length() < characters.length) {
|
||||
for (int i = text.length(); i < characters.length; i++) {
|
||||
characters[i].setActive(false);
|
||||
}
|
||||
} else if (text.length() > characters.length) {
|
||||
GameObject[] temp = new GameObject[text.length()];
|
||||
System.arraycopy(characters, 0, temp, 0, characters.length);
|
||||
characters = temp;
|
||||
}
|
||||
|
||||
/*for (GameObject go : characters) {
|
||||
if (go != null) {
|
||||
GameObject.destroy(go);
|
||||
}
|
||||
}*/
|
||||
|
||||
// characters = new GameObject[text.length()];
|
||||
|
||||
Sprite s;
|
||||
float xOffset = 0;
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
switch (text.charAt(i)) {
|
||||
case ' ':
|
||||
xOffset += spaceWidth;
|
||||
continue;
|
||||
case '!':
|
||||
s = font.getSprite("exclamation-mark");
|
||||
break;
|
||||
case '?':
|
||||
s = font.getSprite("question-mark");
|
||||
break;
|
||||
case '.':
|
||||
s = font.getSprite("period");
|
||||
break;
|
||||
case ':':
|
||||
s = font.getSprite("colon");
|
||||
break;
|
||||
default:
|
||||
s = font.getSprite(String.valueOf(text.charAt(i)));
|
||||
break;
|
||||
}
|
||||
if (s == null) continue;
|
||||
|
||||
float width = (s.w / s.h) * fontSize;
|
||||
|
||||
if (characters[i] == null) {
|
||||
GuiRenderer guiRenderer = new GuiRenderer(font, s, width, fontSize);
|
||||
guiRenderer.setDepth(depth);
|
||||
characters[i] = GameObject.instantiate(new GameObject(String.valueOf(text.charAt(i)), guiRenderer),
|
||||
new Vector2(transform.position.x + xOffset, transform.position.y));
|
||||
characters[i].transform.setParent(transform);
|
||||
} else {
|
||||
//noinspection ConstantConditions
|
||||
characters[i].getComponent(GuiRenderer.class).setSprite(s);
|
||||
}
|
||||
characters[i].setActive(true);
|
||||
|
||||
xOffset += width + getLetterSpacing();
|
||||
}
|
||||
totalWidth = xOffset - getLetterSpacing();
|
||||
|
||||
bounds.set(transform.position.x, transform.position.y, transform.position.x + totalWidth,
|
||||
transform.position.y + fontSize);
|
||||
}
|
||||
|
||||
private void calculateSpaceWidth() {
|
||||
Sprite[] chars = font.getSprites();
|
||||
float total = 0;
|
||||
for (Sprite s : chars) {
|
||||
total += (s.w / s.h) * fontSize;
|
||||
}
|
||||
spaceWidth = total / chars.length;
|
||||
}
|
||||
|
||||
private float getLetterSpacing() {
|
||||
if (letterSpacing >= 0) {
|
||||
return letterSpacing;
|
||||
} else {
|
||||
return Screen.scale * 6.25f;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hitTest(float x, float y) {
|
||||
return getBounds().contains(x, y);
|
||||
}
|
||||
|
||||
public boolean hitTest(Vector2 position) {
|
||||
return hitTest(position.x, position.y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RectF getBounds() {
|
||||
bounds.set(transform.position.x * GuiRenderer.referenceScreenScale,
|
||||
transform.position.y * GuiRenderer.referenceScreenScale,
|
||||
(transform.position.x + totalWidth) * GuiRenderer.referenceScreenScale,
|
||||
(transform.position.y + fontSize) * GuiRenderer.referenceScreenScale);
|
||||
return bounds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GameObject getGameObject() {
|
||||
return gameObject;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,378 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.Touch.TouchPhase;
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners.GamepadListener;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners.KeyListener;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners.MouseListener;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
public final class Input {
|
||||
static {
|
||||
GameListeners.addMouseListener(new MouseListener() {
|
||||
@Override
|
||||
public void onMove(int x, int y) {
|
||||
mousePosition.set(x, y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onButtonDown(int index) {
|
||||
switch (index) {
|
||||
case 1:
|
||||
setKeyDown(KeyCode.MOUSE_LEFT);
|
||||
break;
|
||||
case 2:
|
||||
setKeyDown(KeyCode.MOUSE_MIDDLE);
|
||||
break;
|
||||
case 3:
|
||||
setKeyDown(KeyCode.MOUSE_RIGHT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onButtonUp(int index) {
|
||||
switch (index) {
|
||||
case 1:
|
||||
setKeyUp(KeyCode.MOUSE_LEFT);
|
||||
break;
|
||||
case 2:
|
||||
setKeyUp(KeyCode.MOUSE_MIDDLE);
|
||||
break;
|
||||
case 3:
|
||||
setKeyUp(KeyCode.MOUSE_RIGHT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
GameListeners.addKeyListener(new KeyListener() {
|
||||
@Override
|
||||
public void onKeyDown(String key) {
|
||||
setKeyDown(KeyCode.valueOf(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onKeyUp(String key) {
|
||||
setKeyUp(KeyCode.valueOf(key));
|
||||
}
|
||||
});
|
||||
GameListeners.addGamepadListener(new GamepadListener() {
|
||||
@Override
|
||||
public void onConnectionStateChanged(boolean connected) {
|
||||
controllerConnected = connected;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onButtonDown(String button) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onButtonUp(String button) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAxis(String axis, float value) {
|
||||
}
|
||||
});
|
||||
GameListeners.addUpdateListener(Input::update);
|
||||
}
|
||||
|
||||
public static final Vector2 mousePosition = new Vector2();
|
||||
|
||||
public static Touch[] touches = new Touch[0];
|
||||
|
||||
/**
|
||||
* Each key that has been pressed either has a value of true if it has been pressed down in the current frame, or false if it's been held down for multiple frames
|
||||
*/
|
||||
private static HashMap<KeyCode, Integer> keys = new HashMap<>();
|
||||
private static HashMap<KeyCode, Integer> keyChanges = new HashMap<>();
|
||||
|
||||
private static boolean controllerConnected = false;
|
||||
private static HashMap<Button, Integer> buttons = new HashMap<>();
|
||||
private static HashMap<Axis, Vector2> axes = new HashMap<>();
|
||||
|
||||
public enum Button {
|
||||
A,
|
||||
B,
|
||||
X,
|
||||
Y,
|
||||
UP,
|
||||
DOWN,
|
||||
LEFT,
|
||||
RIGHT,
|
||||
THUMB_LEFT,
|
||||
THUMB_RIGHT,
|
||||
SHOULDER_LEFT,
|
||||
SHOULDER_RIGHT,
|
||||
START,
|
||||
BACK,
|
||||
GUIDE
|
||||
}
|
||||
|
||||
public enum Axis {
|
||||
LEFT,
|
||||
RIGHT,
|
||||
LEFT_RAW,
|
||||
RIGHT_RAW,
|
||||
TRIGGER_LEFT,
|
||||
TRIGGER_RIGHT
|
||||
}
|
||||
|
||||
private static ArrayList<Holder> changesToMake = new ArrayList<>(10);
|
||||
private static ArrayList<Touch> touchesToRemove = new ArrayList<>(10);
|
||||
|
||||
public enum KeyCode {
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
E,
|
||||
F,
|
||||
G,
|
||||
H,
|
||||
I,
|
||||
J,
|
||||
K,
|
||||
L,
|
||||
M,
|
||||
N,
|
||||
O,
|
||||
P,
|
||||
Q,
|
||||
R,
|
||||
S,
|
||||
T,
|
||||
U,
|
||||
V,
|
||||
W,
|
||||
X,
|
||||
Y,
|
||||
Z,
|
||||
ALPHA_0,
|
||||
ALPHA_1,
|
||||
ALPHA_2,
|
||||
ALPHA_3,
|
||||
ALPHA_4,
|
||||
ALPHA_5,
|
||||
ALPHA_6,
|
||||
ALPHA_7,
|
||||
ALPHA_8,
|
||||
ALPHA_9,
|
||||
SPACE,
|
||||
ENTER,
|
||||
ESCAPE,
|
||||
BACKSPACE,
|
||||
DELETE,
|
||||
F1,
|
||||
F2,
|
||||
F3,
|
||||
F4,
|
||||
F5,
|
||||
F6,
|
||||
F7,
|
||||
F8,
|
||||
F9,
|
||||
F10,
|
||||
F11,
|
||||
F12,
|
||||
MOUSE_LEFT,
|
||||
MOUSE_RIGHT,
|
||||
MOUSE_MIDDLE
|
||||
}
|
||||
|
||||
private static class Holder {
|
||||
int id;
|
||||
float x;
|
||||
float y;
|
||||
TouchPhase phase;
|
||||
|
||||
Holder(int id, float x, float y, TouchPhase phase) {
|
||||
this.id = id;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.phase = phase;
|
||||
}
|
||||
}
|
||||
|
||||
public static void update() {
|
||||
switch (Dethsquare.PLATFORM) {
|
||||
case ANDROID:
|
||||
/*
|
||||
* Les DEUX passes sont nécessaires sur Android :
|
||||
* - updateTouches() consomme la file des MotionEvents bruts
|
||||
* (alimentée par AndroidLauncher) ;
|
||||
* - updateKeys() consomme les changements de touches VIRTUELLES
|
||||
* (le launcher synthétise A/D/SPACE/clic via les listeners,
|
||||
* car le code du jeu n'écoute que clavier+souris) et fait
|
||||
* vieillir/supprimer les touches terminées. En 2017 cette
|
||||
* branche n'appelait que updateTouches() : les touches
|
||||
* virtuelles n'étaient jamais consommées (chantier abandonné).
|
||||
*/
|
||||
updateTouches();
|
||||
updateKeys();
|
||||
break;
|
||||
case DESKTOP:
|
||||
updateKeys();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void updateTouches() {
|
||||
Holder holder;
|
||||
for (int i = 0; i < changesToMake.size(); i++) {
|
||||
switch ((holder = changesToMake.get(i)).phase) {
|
||||
case BEGAN:
|
||||
Touch[] temp = new Touch[touches.length + 1];
|
||||
System.arraycopy(touches, 0, temp, 0, touches.length);
|
||||
temp[touches.length] = new Touch(holder.id, new Vector2(holder.x, holder.y));
|
||||
touches = temp;
|
||||
break;
|
||||
case MOVED:
|
||||
for (Touch t : touches) {
|
||||
if (t.fingerId == holder.id && t.lastModified < Time.frameCount) {
|
||||
t.phase = Touch.TouchPhase.MOVED;
|
||||
t.position.set(holder.x, holder.y);
|
||||
t.lastModified = Time.frameCount;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case STATIONARY:
|
||||
break;
|
||||
case ENDED:
|
||||
for (Touch t : touches) {
|
||||
if (t.fingerId == holder.id) {
|
||||
t.phase = Touch.TouchPhase.ENDED;
|
||||
t.position.set(holder.x, holder.y);
|
||||
t.lastModified = Time.frameCount;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case CANCELLED:
|
||||
for (Touch t : touches) {
|
||||
if (t.fingerId == holder.id) {
|
||||
t.phase = Touch.TouchPhase.CANCELLED;
|
||||
t.position.set(holder.x, holder.y);
|
||||
t.lastModified = Time.frameCount;
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
changesToMake.clear();
|
||||
}
|
||||
|
||||
private static void updateKeys() {
|
||||
for (KeyCode keyCode : keys.keySet().toArray(new KeyCode[keys.size()])) {
|
||||
switch (keys.get(keyCode)) {
|
||||
case 0:
|
||||
keys.put(keyCode, 1);
|
||||
break;
|
||||
case 2:
|
||||
keys.remove(keyCode);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
keys.putAll(keyChanges);
|
||||
keyChanges.clear();
|
||||
//noinspection ForLoopReplaceableByForEach
|
||||
for (int i = 0; i < touches.length; i++) {
|
||||
if ((touches[i].phase == Touch.TouchPhase.ENDED || touches[i].phase == Touch.TouchPhase.CANCELLED) &&
|
||||
touches[i].lastModified < Time.frameCount) {
|
||||
touchesToRemove.add(touches[i]);
|
||||
} else if (touches[i].lastModified < Time.frameCount) {
|
||||
touches[i].lastModified = Time.frameCount;
|
||||
touches[i].phase = Touch.TouchPhase.STATIONARY;
|
||||
}
|
||||
}
|
||||
if (!touchesToRemove.isEmpty()) {
|
||||
Touch[] temp = new Touch[touches.length - touchesToRemove.size()];
|
||||
int count = 0;
|
||||
//noinspection ForLoopReplaceableByForEach
|
||||
for (int i = 0; i < touches.length; i++) {
|
||||
if (!touchesToRemove.contains(touches[i])) {
|
||||
temp[count++] = touches[i];
|
||||
}
|
||||
}
|
||||
touchesToRemove.clear();
|
||||
touches = temp;
|
||||
}
|
||||
}
|
||||
|
||||
static void clearAll() {
|
||||
keys.clear();
|
||||
keyChanges.clear();
|
||||
changesToMake.clear();
|
||||
touches = new Touch[0];
|
||||
touchesToRemove.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Injecte un état "touche enfoncée" pour une touche VIRTUELLE.
|
||||
*
|
||||
* POURQUOI : sur Android, il n'y a ni clavier ni souris physiques — les
|
||||
* contrôles virtuels du jeu (TouchControls) traduisent les touches
|
||||
* tactiles en touches logiques via ces méthodes, qui alimentent la même
|
||||
* machine à états que les callbacks GLFW du desktop. Même contrat que
|
||||
* setKeyDown, mais public pour les back-ends.
|
||||
*/
|
||||
public static void injectKeyDown(KeyCode keyCode) {
|
||||
setKeyDown(keyCode);
|
||||
}
|
||||
|
||||
/** @see #injectKeyDown(KeyCode) */
|
||||
public static void injectKeyUp(KeyCode keyCode) {
|
||||
setKeyUp(keyCode);
|
||||
}
|
||||
|
||||
private static void setKeyDown(KeyCode keyCode) {
|
||||
if (!keys.containsKey(keyCode)) keyChanges.put(keyCode, 0);
|
||||
}
|
||||
|
||||
private static void setKeyUp(KeyCode keyCode) {
|
||||
keyChanges.put(keyCode, 2);
|
||||
}
|
||||
|
||||
public static boolean getKeyDown(KeyCode keyCode) {
|
||||
return keys.containsKey(keyCode) && keys.get(keyCode) == 0;
|
||||
}
|
||||
|
||||
public static boolean getKey(KeyCode keyCode) {
|
||||
return keys.containsKey(keyCode) && keys.get(keyCode) < 2;
|
||||
}
|
||||
|
||||
public static boolean getKeyUp(KeyCode keyCode) {
|
||||
return keys.containsKey(keyCode) && keys.get(keyCode) == 2;
|
||||
}
|
||||
|
||||
public static void addTouch(int id, float x, float y) {
|
||||
changesToMake.add(new Holder(id, x, y, TouchPhase.BEGAN));
|
||||
}
|
||||
|
||||
public static void moveTouch(int id, float x, float y) {
|
||||
changesToMake.add(new Holder(id, x, y, TouchPhase.MOVED));
|
||||
}
|
||||
|
||||
public static void removeTouch(int id, float x, float y) {
|
||||
changesToMake.add(new Holder(id, x, y, TouchPhase.ENDED));
|
||||
}
|
||||
|
||||
public static void cancelTouch(int id, float x, float y) {
|
||||
changesToMake.add(new Holder(id, x, y, TouchPhase.CANCELLED));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,115 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class Layers {
|
||||
private static final String[] LAYERS = {
|
||||
"Default", // 0
|
||||
null, // 1
|
||||
null, // 2
|
||||
null, // 3
|
||||
null, // 4
|
||||
null, // 5
|
||||
null, // 6
|
||||
null, // 7
|
||||
null, // 8
|
||||
null, // 9
|
||||
null, // 10
|
||||
null, // 11
|
||||
null, // 12
|
||||
null, // 13
|
||||
null, // 14
|
||||
null, // 15
|
||||
null, // 16
|
||||
null, // 17
|
||||
null, // 18
|
||||
null, // 19
|
||||
null, // 20
|
||||
null, // 21
|
||||
null, // 22
|
||||
null, // 23
|
||||
null, // 24
|
||||
null, // 25
|
||||
null, // 26
|
||||
null, // 27
|
||||
null, // 28
|
||||
null, // 29
|
||||
null, // 30
|
||||
null // 31
|
||||
};
|
||||
static {
|
||||
parseLayersConfig();
|
||||
}
|
||||
|
||||
private static void parseLayersConfig() {
|
||||
InputStream is = Dethsquare.IO.getInputStream("config/layers.json");
|
||||
if (is != null) {
|
||||
try(BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
|
||||
StringBuilder data = new StringBuilder();
|
||||
String temp;
|
||||
while ((temp = reader.readLine()) != null) {
|
||||
data.append(temp).append(" ");
|
||||
}
|
||||
JSONArray json = new JSONArray(data.toString());
|
||||
for (int i = 0; i < json.length(); i++) {
|
||||
parseLayer(json.getJSONObject(i));
|
||||
}
|
||||
} catch (IOException | JSONException e) {
|
||||
// JSONException : checked côté Android (framework), unchecked
|
||||
// dans le jar Maven desktop — le multi-catch compile partout.
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void parseLayer(JSONObject layerObject) {
|
||||
try {
|
||||
int layer = layerObject.getInt("layer");
|
||||
String name = layerObject.getString("name");
|
||||
if (layer > 7 && layer < 32) {
|
||||
LAYERS[layer] = name;
|
||||
} else {
|
||||
throw new MalformedLayerException();
|
||||
}
|
||||
} catch(JSONException e) {
|
||||
throw new MalformedLayerException();
|
||||
}
|
||||
}
|
||||
|
||||
public static int getLayer(String name) {
|
||||
if (name == null) return -1;
|
||||
for (int i = 0; i < LAYERS.length; i++) {
|
||||
if (name.equalsIgnoreCase(LAYERS[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int getLayerMask(String... layerNames) {
|
||||
int mask = 0;
|
||||
for (String name : layerNames) {
|
||||
int layer = getLayer(name);
|
||||
if (layer > -1) {
|
||||
mask |= 1 << layer;
|
||||
}
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
private static class MalformedLayerException extends RuntimeException {
|
||||
|
||||
private MalformedLayerException() {
|
||||
super("Layer config file is malformed - please validate it against the layer schema");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,5 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
public abstract class Level {
|
||||
public abstract void onLoad();
|
||||
}
|
||||
@ -0,0 +1,63 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.graphics.GraphicsEngine;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
import com.ezardlabs.dethsquare.util.GameLog;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class LevelManager {
|
||||
static {
|
||||
GameListeners.addPostUpdateListener(LevelManager::onPostUpdate);
|
||||
}
|
||||
|
||||
private static HashMap<String, Level> levels = new HashMap<>();
|
||||
private static String currentLevelName;
|
||||
private static String nextLevelName;
|
||||
|
||||
public static void registerLevel(String name, Level level) {
|
||||
levels.put(name, level);
|
||||
GameLog.i("LS-LEVEL", "Registered level '" + name + "' (" + level.getClass().getSimpleName() + ")");
|
||||
}
|
||||
|
||||
public static void loadLevel(String name) {
|
||||
if (nextLevelName != null) {
|
||||
throw new IllegalStateException("Cannot load a level whilst another level is being loaded");
|
||||
}
|
||||
GameLog.i("LS-LEVEL", "loadLevel('" + name + "') requested (current='" + currentLevelName + "')");
|
||||
nextLevelName = name;
|
||||
}
|
||||
|
||||
private static void onPostUpdate() {
|
||||
if (nextLevelName != null) {
|
||||
String levelName = nextLevelName;
|
||||
GameLog.i("LS-LEVEL", "Loading level '" + levelName + "': destroyAll + onLoad...");
|
||||
Time.pause();
|
||||
GameObject.destroyAll();
|
||||
|
||||
currentLevelName = nextLevelName;
|
||||
Level level = levels.get(nextLevelName);
|
||||
level.onLoad();
|
||||
GameLog.i("LS-LEVEL", "Level '" + levelName + "' onLoad() done");
|
||||
|
||||
GameObject.startAll();
|
||||
GraphicsEngine.init();
|
||||
Collider.init();
|
||||
|
||||
Input.clearAll();
|
||||
|
||||
nextLevelName = null;
|
||||
|
||||
Time.resume();
|
||||
GameLog.i("LS-LEVEL", "Level '" + levelName + "' fully loaded");
|
||||
}
|
||||
}
|
||||
|
||||
public static Level getCurrentLevel() {
|
||||
return levels.get(currentLevelName);
|
||||
}
|
||||
|
||||
public static String getCurrentLevelName() {
|
||||
return currentLevelName;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
/**
|
||||
* Extra functions to supplement {@link java.lang.Math java.lang.Mathf}
|
||||
*/
|
||||
public class Mathf {
|
||||
|
||||
public static float clamp(float value, float min, float max) {
|
||||
if (value < min) {
|
||||
return min;
|
||||
} else if (value > max) {
|
||||
return max;
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,77 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.QuadTree.RayCollision;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Physics {
|
||||
|
||||
public static RaycastHit raycast(Vector2 origin, Vector2 direction, float distance, int layerMask) {
|
||||
direction.normalise();
|
||||
Vector2 end = new Vector2(origin.x + direction.x * distance, origin.y + direction.y * distance);
|
||||
RaycastHit raycastHit = null;
|
||||
HashSet<Collider> temp = new HashSet<>(
|
||||
Collider.staticColliders.size() + Collider.normalColliders.size() + Collider.triggerColliders.size());
|
||||
temp.addAll(Collider.staticColliders);
|
||||
temp.addAll(Collider.normalColliders);
|
||||
temp.addAll(Collider.triggerColliders);
|
||||
for (Collider c : temp) {
|
||||
if ((c.gameObject.getLayerMask() & layerMask) == c.gameObject.getLayerMask()) {
|
||||
Vector2 hit = c.getBounds().intersect(origin, end);
|
||||
if (hit != null) {
|
||||
if (raycastHit == null) {
|
||||
raycastHit = new RaycastHit(hit, Vector2.distance(origin, hit), c.transform, c);
|
||||
} else if (Vector2.distance(origin, hit) < raycastHit.distance) {
|
||||
raycastHit.point = hit;
|
||||
raycastHit.distance = Vector2.distance(origin, hit);
|
||||
raycastHit.transform = c.transform;
|
||||
raycastHit.collider = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return raycastHit;
|
||||
}
|
||||
|
||||
public static RaycastHit raycastOptimised(Vector2 origin, Vector2 direction, float distance, int layerMask) {
|
||||
direction.normalise();
|
||||
Vector2 end = new Vector2(origin.x + direction.x * distance, origin.y + direction.y * distance);
|
||||
|
||||
final RayCollision<Collider> collision = QuadTree.getRayCollision(Collider.qt, origin, end, layerMask);
|
||||
System.out.println("Halfway: " + collision.point);
|
||||
Stream.concat(Collider.normalColliders.stream(), Collider.triggerColliders.stream())
|
||||
.parallel()
|
||||
.filter(collider -> (collider.gameObject.getLayerMask() & layerMask) == collider.gameObject.getLayerMask())
|
||||
.forEach(collider -> {
|
||||
Vector2 intersect = collider.getBounds().intersect(origin, end);
|
||||
if (intersect != null) {
|
||||
double dist = Vector2.distance(origin, intersect);
|
||||
if (dist < collision.distance) {
|
||||
System.out.println(collider.gameObject.name);
|
||||
collision.set(collider, intersect, dist);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (collision.distance != Double.MAX_VALUE) {
|
||||
return new RaycastHit(collision.point, collision.distance, collision.bounded.transform,
|
||||
collision.bounded.gameObject.collider);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static class RaycastHit {
|
||||
public Collider collider;
|
||||
public double distance;
|
||||
public Vector2 point;
|
||||
public Transform transform;
|
||||
|
||||
RaycastHit(Vector2 point, double distance, Transform transform, Collider collider) {
|
||||
this.point = point;
|
||||
this.distance = distance;
|
||||
this.transform = transform;
|
||||
this.collider = collider;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.PREFS;
|
||||
|
||||
public final class PlayerPrefs {
|
||||
|
||||
public static void setBoolean(String key, boolean value) {
|
||||
PREFS.setBoolean(key, value);
|
||||
}
|
||||
|
||||
public static void setInt(String key, int value) {
|
||||
PREFS.setInt(key, value);
|
||||
}
|
||||
|
||||
public static void setFloat(String key, float value) {
|
||||
PREFS.setFloat(key, value);
|
||||
}
|
||||
|
||||
public static void setString(String key, String value) {
|
||||
PREFS.setString(key, value);
|
||||
}
|
||||
|
||||
public static boolean getBoolean(String key, boolean defaultValue) {
|
||||
return PREFS.getBoolean(key, defaultValue);
|
||||
}
|
||||
|
||||
public static int getInt(String key, int defaultValue) {
|
||||
return PREFS.getInt(key, defaultValue);
|
||||
}
|
||||
|
||||
public static float getFloat(String key, float defaultValue) {
|
||||
return PREFS.getFloat(key, defaultValue);
|
||||
}
|
||||
|
||||
public static String getString(String key, String defaultValue) {
|
||||
return PREFS.getString(key, defaultValue);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,209 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final class QuadTree<T extends Bounded> {
|
||||
private final RectF bounds;
|
||||
private final int maxObjects;
|
||||
private final QuadTree[] nodes = new QuadTree[4];
|
||||
private final ArrayList<T> objects;
|
||||
private final TreeMap<Double, Integer> map = new TreeMap<>();
|
||||
private boolean built = false;
|
||||
|
||||
public QuadTree(int maxObjects) {
|
||||
this(maxObjects, new RectF());
|
||||
}
|
||||
|
||||
private QuadTree(int maxObjects, RectF bounds) {
|
||||
this.bounds = bounds;
|
||||
this.maxObjects = maxObjects;
|
||||
this.objects = new ArrayList<>(maxObjects);
|
||||
}
|
||||
|
||||
public void build(List<T> objects) {
|
||||
float left = 0;
|
||||
float top = 0;
|
||||
float right = 0;
|
||||
float bottom = 0;
|
||||
for (Bounded b : objects) {
|
||||
if (b.getBounds().left < left) {
|
||||
left = b.getBounds().left;
|
||||
}
|
||||
if (b.getBounds().left > right) {
|
||||
right = b.getBounds().right;
|
||||
}
|
||||
if (b.getBounds().top < top) {
|
||||
top = b.getBounds().top;
|
||||
}
|
||||
if (b.getBounds().left > right) {
|
||||
bottom = b.getBounds().bottom;
|
||||
}
|
||||
}
|
||||
float width = right - left;
|
||||
float height = bottom - top;
|
||||
if (width > height) {
|
||||
bounds.set(left, top, left + width, top + width);
|
||||
} else if (top > left) {
|
||||
bounds.set(left, top, left + height, top + height);
|
||||
}
|
||||
for (T b : objects) {
|
||||
if (b.getGameObject() == null || b.getGameObject().isStatic) {
|
||||
insert(b);
|
||||
}
|
||||
}
|
||||
built = true;
|
||||
}
|
||||
|
||||
public boolean isBuilt() {
|
||||
return built;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
Arrays.fill(nodes, null);
|
||||
objects.clear();
|
||||
map.clear();
|
||||
}
|
||||
|
||||
private void insert(T object) {
|
||||
if (isLeaf()) {
|
||||
objects.add(object);
|
||||
if (objects.size() > maxObjects) {
|
||||
split();
|
||||
loop:
|
||||
while (!objects.isEmpty()) {
|
||||
T item = objects.remove(0);
|
||||
for (QuadTree node : nodes) {
|
||||
if (node.bounds.contains(item.getBounds())) {
|
||||
node.insert(item);
|
||||
continue loop;
|
||||
}
|
||||
}
|
||||
for (QuadTree node : nodes) {
|
||||
if (node.bounds.intersects(item.getBounds())) {
|
||||
node.insert(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (QuadTree node : nodes) {
|
||||
if (node.bounds.contains(object.getBounds())) {
|
||||
node.insert(object);
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (QuadTree node : nodes) {
|
||||
if (node.bounds.intersects(object.getBounds())) {
|
||||
node.insert(object);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void split() {
|
||||
float subWidth = bounds.width() / 2f;
|
||||
float subHeight = bounds.height() / 2f;
|
||||
float x = bounds.left;
|
||||
float y = bounds.top;
|
||||
// top left
|
||||
nodes[0] = new QuadTree(maxObjects, new RectF(x, y, x + subWidth, y + subHeight));
|
||||
// top right
|
||||
nodes[1] = new QuadTree(maxObjects, new RectF(x + subWidth, y, x + (subWidth * 2), y + subHeight));
|
||||
// bottom left
|
||||
nodes[2] = new QuadTree(maxObjects, new RectF(x, y + subHeight, x + subWidth, y + (subHeight * 2)));
|
||||
// bottom right
|
||||
nodes[3] = new QuadTree(maxObjects,
|
||||
new RectF(x + subWidth, y + subHeight, x + (subWidth * 2), y + (subHeight * 2)));
|
||||
}
|
||||
|
||||
private boolean isLeaf() {
|
||||
return nodes[0] == null;
|
||||
}
|
||||
|
||||
public void retrieve(ArrayList<T> returnObjects, Bounded b) {
|
||||
retrieve(returnObjects, b.getBounds());
|
||||
}
|
||||
|
||||
ArrayList<T> retrieve(ArrayList<T> returnObjects, RectF bounds) {
|
||||
if (!isLeaf()) {
|
||||
for (QuadTree qt : nodes) {
|
||||
if (qt.bounds.contains(bounds)) {
|
||||
return qt.retrieve(returnObjects, bounds);
|
||||
}
|
||||
}
|
||||
for (QuadTree qt : nodes) {
|
||||
if (RectF.intersects(qt.bounds, bounds)) {
|
||||
qt.retrieve(returnObjects, bounds);
|
||||
}
|
||||
}
|
||||
if (!returnObjects.isEmpty()) return returnObjects;
|
||||
}
|
||||
returnObjects.addAll(objects);
|
||||
return returnObjects;
|
||||
}
|
||||
|
||||
static <T extends Bounded> RayCollision<T> getRayCollision(QuadTree<T> qt, Vector2 start, Vector2 end,
|
||||
int layerMask) {
|
||||
return getRayCollision(qt, start, end, layerMask, new RayCollision<>());
|
||||
}
|
||||
|
||||
private static <T extends Bounded> RayCollision<T> getRayCollision(QuadTree<T> qt, Vector2 start, Vector2 end,
|
||||
int layerMask, RayCollision<T> collision) {
|
||||
if (qt.bounds.intersect(start, end) != null) {
|
||||
if (qt.isLeaf()) {
|
||||
Vector2 temp;
|
||||
double dist;
|
||||
for (T object : qt.objects) {
|
||||
temp = object.getBounds().intersect(start, end);
|
||||
if (temp != null) {
|
||||
dist = Vector2.distance(start, temp);
|
||||
if (dist < collision.distance && (object.getGameObject().getLayerMask() & layerMask) ==
|
||||
object.getGameObject().getLayerMask()) {
|
||||
collision.set(object, temp, dist);
|
||||
}
|
||||
}
|
||||
}
|
||||
return collision;
|
||||
} else {
|
||||
qt.map.clear();
|
||||
Vector2 intersect;
|
||||
for (int i = 0; i < qt.nodes.length; i++) {
|
||||
intersect = qt.nodes[i].bounds.intersect(start, end);
|
||||
qt.map.put(intersect == null ? Double.MAX_VALUE : Vector2.distance(start, intersect), i);
|
||||
}
|
||||
for (Double d : qt.map.keySet()) {
|
||||
if (d < collision.distance) {
|
||||
RayCollision<T> temp = getRayCollision(qt.nodes[qt.map.get(d)], start, end, layerMask,
|
||||
collision);
|
||||
collision.set(temp);
|
||||
}
|
||||
}
|
||||
return collision;
|
||||
}
|
||||
} else {
|
||||
return collision;
|
||||
}
|
||||
}
|
||||
|
||||
static class RayCollision<T extends Bounded> {
|
||||
T bounded = null;
|
||||
Vector2 point = null;
|
||||
double distance = Double.MAX_VALUE;
|
||||
|
||||
void set(RayCollision<T> collision) {
|
||||
bounded = collision.bounded;
|
||||
point = collision.point;
|
||||
distance = collision.distance;
|
||||
}
|
||||
|
||||
void set(T bounded, Vector2 point, double distance) {
|
||||
this.bounded = bounded;
|
||||
this.point = point;
|
||||
this.distance = distance;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,589 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
|
||||
/**
|
||||
* RectF holds four float coordinates for a rectangle. The rectangle is
|
||||
* represented by the coordinates of its 4 edges (left, top, right bottom).
|
||||
* These fields can be accessed directly. Use width() and height() to retrieve
|
||||
* the rectangle's width and height. Note: most methods do not check to see that
|
||||
* the coordinates are sorted correctly (i.e. left <= right and top <= bottom).
|
||||
*/
|
||||
public final class RectF {
|
||||
public float left;
|
||||
public float top;
|
||||
public float right;
|
||||
public float bottom;
|
||||
|
||||
private Vector2[] temp = {new Vector2(), new Vector2(), new Vector2(), new Vector2()};
|
||||
|
||||
/**
|
||||
* Create a new empty RectF. All coordinates are initialized to 0.
|
||||
*/
|
||||
public RectF() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new rectangle with the specified coordinates. Note: no range
|
||||
* checking is performed, so the caller must ensure that left <= right and
|
||||
* top <= bottom.
|
||||
*
|
||||
* @param left The X coordinate of the left side of the rectangle
|
||||
* @param top The Y coordinate of the top of the rectangle
|
||||
* @param right The X coordinate of the right side of the rectangle
|
||||
* @param bottom The Y coordinate of the bottom of the rectangle
|
||||
*/
|
||||
public RectF(float left, float top, float right, float bottom) {
|
||||
this.left = left;
|
||||
this.top = top;
|
||||
this.right = right;
|
||||
this.bottom = bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new rectangle, initialized with the values in the specified
|
||||
* rectangle (which is left unmodified).
|
||||
*
|
||||
* @param r The rectangle whose coordinates are copied into the new
|
||||
* rectangle.
|
||||
*/
|
||||
public RectF(RectF r) {
|
||||
if (r == null) {
|
||||
left = top = right = bottom = 0.0f;
|
||||
} else {
|
||||
left = r.left;
|
||||
top = r.top;
|
||||
right = r.right;
|
||||
bottom = r.bottom;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
RectF r = (RectF) o;
|
||||
return left == r.left && top == r.top && right == r.right && bottom == r.bottom;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "RectF(" + left + ", " + top + ", " + right + ", " + bottom + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a string representation of the rectangle in a compact form.
|
||||
*/
|
||||
public String toShortString() {
|
||||
return toShortString(new StringBuilder(32));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a string representation of the rectangle in a compact form.
|
||||
*
|
||||
* @hide
|
||||
*/
|
||||
public String toShortString(StringBuilder sb) {
|
||||
sb.setLength(0);
|
||||
sb.append('[');
|
||||
sb.append(left);
|
||||
sb.append(',');
|
||||
sb.append(top);
|
||||
sb.append("][");
|
||||
sb.append(right);
|
||||
sb.append(',');
|
||||
sb.append(bottom);
|
||||
sb.append(']');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Print short representation to given writer.
|
||||
*
|
||||
* @hide
|
||||
*/
|
||||
public void printShortString(PrintWriter pw) {
|
||||
pw.print('[');
|
||||
pw.print(left);
|
||||
pw.print(',');
|
||||
pw.print(top);
|
||||
pw.print("][");
|
||||
pw.print(right);
|
||||
pw.print(',');
|
||||
pw.print(bottom);
|
||||
pw.print(']');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the rectangle is empty (left >= right or top >= bottom)
|
||||
*/
|
||||
public final boolean isEmpty() {
|
||||
return left >= right || top >= bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the rectangle's width. This does not check for a valid rectangle
|
||||
* (i.e. left <= right) so the result may be negative.
|
||||
*/
|
||||
public final float width() {
|
||||
return right - left;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the rectangle's height. This does not check for a valid rectangle
|
||||
* (i.e. top <= bottom) so the result may be negative.
|
||||
*/
|
||||
public final float height() {
|
||||
return bottom - top;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the horizontal center of the rectangle. This does not check for
|
||||
* a valid rectangle (i.e. left <= right)
|
||||
*/
|
||||
public final float centerX() {
|
||||
return (left + right) * 0.5f;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the vertical center of the rectangle. This does not check for
|
||||
* a valid rectangle (i.e. top <= bottom)
|
||||
*/
|
||||
public final float centerY() {
|
||||
return (top + bottom) * 0.5f;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the rectangle to (0,0,0,0)
|
||||
*/
|
||||
public void setEmpty() {
|
||||
left = right = top = bottom = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the rectangle's coordinates to the specified values. Note: no range
|
||||
* checking is performed, so it is up to the caller to ensure that
|
||||
* left <= right and top <= bottom.
|
||||
*
|
||||
* @param left The X coordinate of the left side of the rectangle
|
||||
* @param top The Y coordinate of the top of the rectangle
|
||||
* @param right The X coordinate of the right side of the rectangle
|
||||
* @param bottom The Y coordinate of the bottom of the rectangle
|
||||
*/
|
||||
public void set(float left, float top, float right, float bottom) {
|
||||
this.left = left;
|
||||
this.top = top;
|
||||
this.right = right;
|
||||
this.bottom = bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the coordinates from src into this rectangle.
|
||||
*
|
||||
* @param src The rectangle whose coordinates are copied into this
|
||||
* rectangle.
|
||||
*/
|
||||
public void set(RectF src) {
|
||||
this.left = src.left;
|
||||
this.top = src.top;
|
||||
this.right = src.right;
|
||||
this.bottom = src.bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify the width of the rectangle by setting its right coordinate to its left coordinate
|
||||
* plus the given width
|
||||
*
|
||||
* @param width The width that you want the rectangle to be
|
||||
*/
|
||||
public void setWidth(float width) {
|
||||
right = left + width;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Modify the height of the rectangle by setting its bottom coordinate to its top coordinate
|
||||
* plus the given height
|
||||
*
|
||||
* @param height The height that you want the rectangle to be
|
||||
*/
|
||||
public void setHeight(float height) {
|
||||
bottom = top + height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset the rectangle by adding dx to its left and right coordinates, and
|
||||
* adding dy to its top and bottom coordinates.
|
||||
*
|
||||
* @param dx The amount to add to the rectangle's left and right coordinates
|
||||
* @param dy The amount to add to the rectangle's top and bottom coordinates
|
||||
*/
|
||||
public void offset(float dx, float dy) {
|
||||
left += dx;
|
||||
top += dy;
|
||||
right += dx;
|
||||
bottom += dy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset the rectangle to a specific (left, top) position,
|
||||
* keeping its width and height the same.
|
||||
*
|
||||
* @param newLeft The new "left" coordinate for the rectangle
|
||||
* @param newTop The new "top" coordinate for the rectangle
|
||||
*/
|
||||
public void offsetTo(float newLeft, float newTop) {
|
||||
right += newLeft - left;
|
||||
bottom += newTop - top;
|
||||
left = newLeft;
|
||||
top = newTop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inset the rectangle by (dx,dy). If dx is positive, then the sides are
|
||||
* moved inwards, making the rectangle narrower. If dx is negative, then the
|
||||
* sides are moved outwards, making the rectangle wider. The same holds true
|
||||
* for dy and the top and bottom.
|
||||
*
|
||||
* @param dx The amount to add(subtract) from the rectangle's left(right)
|
||||
* @param dy The amount to add(subtract) from the rectangle's top(bottom)
|
||||
*/
|
||||
public void inset(float dx, float dy) {
|
||||
left += dx;
|
||||
top += dy;
|
||||
right -= dx;
|
||||
bottom -= dy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if (x,y) is inside the rectangle. The left and top are
|
||||
* considered to be inside, while the right and bottom are not. This means
|
||||
* that for a x,y to be contained: left <= x < right and top <= y < bottom.
|
||||
* An empty rectangle never contains any point.
|
||||
*
|
||||
* @param x The X coordinate of the point being tested for containment
|
||||
* @param y The Y coordinate of the point being tested for containment
|
||||
* @return true iff (x,y) are contained by the rectangle, where containment
|
||||
* means left <= x < right and top <= y < bottom
|
||||
*/
|
||||
public boolean contains(float x, float y) {
|
||||
return left < right && top < bottom // check for empty first
|
||||
&& x >= left && x < right && y >= top && y < bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true iff the 4 specified sides of a rectangle are inside or equal
|
||||
* to this rectangle. i.e. is this rectangle a superset of the specified
|
||||
* rectangle. An empty rectangle never contains another rectangle.
|
||||
*
|
||||
* @param left The left side of the rectangle being tested for containment
|
||||
* @param top The top of the rectangle being tested for containment
|
||||
* @param right The right side of the rectangle being tested for containment
|
||||
* @param bottom The bottom of the rectangle being tested for containment
|
||||
* @return true iff the the 4 specified sides of a rectangle are inside or
|
||||
* equal to this rectangle
|
||||
*/
|
||||
public boolean contains(float left, float top, float right, float bottom) {
|
||||
// check for empty first
|
||||
return this.left < this.right && this.top < this.bottom
|
||||
// now check for containment
|
||||
&& this.left <= left && this.top <= top && this.right >= right && this.bottom >= bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true iff the specified rectangle r is inside or equal to this
|
||||
* rectangle. An empty rectangle never contains another rectangle.
|
||||
*
|
||||
* @param r The rectangle being tested for containment.
|
||||
* @return true iff the specified rectangle r is inside or equal to this
|
||||
* rectangle
|
||||
*/
|
||||
public boolean contains(RectF r) {
|
||||
// check for empty first
|
||||
return this.left < this.right && this.top < this.bottom
|
||||
// now check for containment
|
||||
&& left <= r.left && top <= r.top && right >= r.right && bottom >= r.bottom;
|
||||
}
|
||||
|
||||
public boolean contains(Vector2 a, Vector2 b) {
|
||||
return contains(a.x, a.y) && contains(b.x, b.y);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the rectangle specified by left,top,right,bottom intersects this
|
||||
* rectangle, return true and set this rectangle to that intersection,
|
||||
* otherwise return false and do not change this rectangle. No check is
|
||||
* performed to see if either rectangle is empty. Note: To just test for
|
||||
* intersection, use intersects()
|
||||
*
|
||||
* @param left The left side of the rectangle being intersected with this
|
||||
* rectangle
|
||||
* @param top The top of the rectangle being intersected with this rectangle
|
||||
* @param right The right side of the rectangle being intersected with this
|
||||
* rectangle.
|
||||
* @param bottom The bottom of the rectangle being intersected with this
|
||||
* rectangle.
|
||||
* @return true if the specified rectangle and this rectangle intersect
|
||||
* (and this rectangle is then set to that intersection) else
|
||||
* return false and do not change this rectangle.
|
||||
*/
|
||||
public boolean intersect(float left, float top, float right, float bottom) {
|
||||
if (this.left < right && left < this.right && this.top < bottom && top < this.bottom) {
|
||||
if (this.left < left) {
|
||||
this.left = left;
|
||||
}
|
||||
if (this.top < top) {
|
||||
this.top = top;
|
||||
}
|
||||
if (this.right > right) {
|
||||
this.right = right;
|
||||
}
|
||||
if (this.bottom > bottom) {
|
||||
this.bottom = bottom;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* If the specified rectangle intersects this rectangle, return true and set
|
||||
* this rectangle to that intersection, otherwise return false and do not
|
||||
* change this rectangle. No check is performed to see if either rectangle
|
||||
* is empty. To just test for intersection, use intersects()
|
||||
*
|
||||
* @param r The rectangle being intersected with this rectangle.
|
||||
* @return true if the specified rectangle and this rectangle intersect
|
||||
* (and this rectangle is then set to that intersection) else
|
||||
* return false and do not change this rectangle.
|
||||
*/
|
||||
public boolean intersect(RectF r) {
|
||||
return intersect(r.left, r.top, r.right, r.bottom);
|
||||
}
|
||||
|
||||
/**
|
||||
* If rectangles a and b intersect, return true and set this rectangle to
|
||||
* that intersection, otherwise return false and do not change this
|
||||
* rectangle. No check is performed to see if either rectangle is empty.
|
||||
* To just test for intersection, use intersects()
|
||||
*
|
||||
* @param a The first rectangle being intersected with
|
||||
* @param b The second rectangle being intersected with
|
||||
* @return true iff the two specified rectangles intersect. If they do, set
|
||||
* this rectangle to that intersection. If they do not, return
|
||||
* false and do not change this rectangle.
|
||||
*/
|
||||
public boolean setIntersect(RectF a, RectF b) {
|
||||
if (a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom) {
|
||||
left = Math.max(a.left, b.left);
|
||||
top = Math.max(a.top, b.top);
|
||||
right = Math.min(a.right, b.right);
|
||||
bottom = Math.min(a.bottom, b.bottom);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if this rectangle intersects the specified rectangle.
|
||||
* In no event is this rectangle modified. No check is performed to see
|
||||
* if either rectangle is empty. To record the intersection, use intersect()
|
||||
* or setIntersect().
|
||||
*
|
||||
* @param left The left side of the rectangle being tested for intersection
|
||||
* @param top The top of the rectangle being tested for intersection
|
||||
* @param right The right side of the rectangle being tested for
|
||||
* intersection
|
||||
* @param bottom The bottom of the rectangle being tested for intersection
|
||||
* @return true iff the specified rectangle intersects this rectangle. In
|
||||
* no event is this rectangle modified.
|
||||
*/
|
||||
public boolean intersects(float left, float top, float right, float bottom) {
|
||||
return this.left < right && left < this.right && this.top < bottom && top < this.bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if this rectangle intersects the specified rectangle.
|
||||
* In no event is this rectangle modified. No check is performed to see
|
||||
* if either rectangle is empty. To record the intersection, use intersect()
|
||||
* or setIntersect().
|
||||
*
|
||||
* @param r The rectangle being tested for intersection
|
||||
* @return true iff the specified rectangle intersects this rectangle. In
|
||||
* no event is this rectangle modified.
|
||||
*/
|
||||
public boolean intersects(RectF r) {
|
||||
return this.left < r.right && r.left < this.right && this.top < r.bottom && r.top < this.bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true iff the two specified rectangles intersect. In no event are
|
||||
* either of the rectangles modified. To record the intersection,
|
||||
* use intersect() or setIntersect().
|
||||
*
|
||||
* @param a The first rectangle being tested for intersection
|
||||
* @param b The second rectangle being tested for intersection
|
||||
* @return true iff the two specified rectangles intersect. In no event are
|
||||
* either of the rectangles modified.
|
||||
*/
|
||||
public static boolean intersects(RectF a, RectF b) {
|
||||
return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a line intersects with this rectangle
|
||||
*
|
||||
* @param a The start point of the line
|
||||
* @param b The end point of the line
|
||||
* @return The intersect point if one exists; null otherwise
|
||||
*/
|
||||
public Vector2 intersect(Vector2 a, Vector2 b) {
|
||||
boolean[] intersects = {
|
||||
// left
|
||||
intersect(a.x, a.y, b.x, b.y, left, top, left, bottom, this.temp[0]),
|
||||
// top
|
||||
intersect(a.x, a.y, b.x, b.y, left, top, right, top, this.temp[1]),
|
||||
// right
|
||||
intersect(a.x, a.y, b.x, b.y, right, top, right, bottom, this.temp[2]),
|
||||
// bottom
|
||||
intersect(a.x, a.y, b.x, b.y, left, bottom, right, bottom, this.temp[3])};
|
||||
|
||||
double current;
|
||||
double min = Double.MAX_VALUE;
|
||||
int best = -1;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
if (intersects[i] && (current = Vector2.distance(a, temp[i])) < min) {
|
||||
min = current;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best == -1 ? null : temp[best];
|
||||
}
|
||||
|
||||
private boolean intersect(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4,
|
||||
Vector2 returnVal) {
|
||||
// vertical check
|
||||
if (x1 == x2) {
|
||||
if (x3 == x4) {
|
||||
// both vertical
|
||||
return false;
|
||||
} else {
|
||||
// argument line is vertical; test line is not vertical
|
||||
float a2 = (y4 - y3) / (x4 - x3);
|
||||
float b2 = y3 - a2 * x3;
|
||||
float yIntercept = a2 * x3 + b2;
|
||||
if (Math.min(x3, x4) <= x1 && x1 <= Math.max(x3, x4) && y1 <= yIntercept && yIntercept <= y2) {
|
||||
returnVal.set(x1, yIntercept);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (x3 == x4) {
|
||||
// argument line is not vertical; test line is vertical
|
||||
float a1 = (y2 - y1) / (x2 - x1);
|
||||
float b1 = y1 - a1 * x1;
|
||||
float yIntercept = a1 * x3 + b1;
|
||||
if (Math.min(x1, x2) <= x3 && x3 <= Math.max(x1, x2) && y3 <= yIntercept && yIntercept <= y4) {
|
||||
returnVal.set(x3, yIntercept);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// neither line is vertical
|
||||
float a1 = (y2 - y1) / (x2 - x1);
|
||||
float b1 = y1 - a1 * x1;
|
||||
float a2 = (y4 - y3) / (x4 - x3);
|
||||
float b2 = y3 - a2 * x3;
|
||||
|
||||
float x0 = -(b1 - b2) / (a1 - a2);
|
||||
float y0 = a1 * x0 + b1;
|
||||
if (Math.min(x1, x2) < x0 && x0 < Math.max(x1, x2) && Math.min(x3, x4) < x0 && x0 < Math.max(x3, x4)) {
|
||||
returnVal.set(x0, y0);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update this Rect to enclose itself and the specified rectangle. If the
|
||||
* specified rectangle is empty, nothing is done. If this rectangle is empty
|
||||
* it is set to the specified rectangle.
|
||||
*
|
||||
* @param left The left edge being unioned with this rectangle
|
||||
* @param top The top edge being unioned with this rectangle
|
||||
* @param right The right edge being unioned with this rectangle
|
||||
* @param bottom The bottom edge being unioned with this rectangle
|
||||
*/
|
||||
public void union(float left, float top, float right, float bottom) {
|
||||
if ((left < right) && (top < bottom)) {
|
||||
if ((this.left < this.right) && (this.top < this.bottom)) {
|
||||
if (this.left > left) this.left = left;
|
||||
if (this.top > top) this.top = top;
|
||||
if (this.right < right) this.right = right;
|
||||
if (this.bottom < bottom) this.bottom = bottom;
|
||||
} else {
|
||||
this.left = left;
|
||||
this.top = top;
|
||||
this.right = right;
|
||||
this.bottom = bottom;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update this Rect to enclose itself and the specified rectangle. If the
|
||||
* specified rectangle is empty, nothing is done. If this rectangle is empty
|
||||
* it is set to the specified rectangle.
|
||||
*
|
||||
* @param r The rectangle being unioned with this rectangle
|
||||
*/
|
||||
public void union(RectF r) {
|
||||
union(r.left, r.top, r.right, r.bottom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update this Rect to enclose itself and the [x,y] coordinate. There is no
|
||||
* check to see that this rectangle is non-empty.
|
||||
*
|
||||
* @param x The x coordinate of the point to add to the rectangle
|
||||
* @param y The y coordinate of the point to add to the rectangle
|
||||
*/
|
||||
public void union(float x, float y) {
|
||||
if (x < left) {
|
||||
left = x;
|
||||
} else if (x > right) {
|
||||
right = x;
|
||||
}
|
||||
if (y < top) {
|
||||
top = y;
|
||||
} else if (y > bottom) {
|
||||
bottom = y;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap top/bottom or left/right if there are flipped (i.e. left > right
|
||||
* and/or top > bottom). This can be called if
|
||||
* the edges are computed separately, and may have crossed over each other.
|
||||
* If the edges are already correct (i.e. left <= right and top <= bottom)
|
||||
* then nothing is done.
|
||||
*/
|
||||
public void sort() {
|
||||
if (left > right) {
|
||||
float temp = left;
|
||||
left = right;
|
||||
right = temp;
|
||||
}
|
||||
if (top > bottom) {
|
||||
float temp = top;
|
||||
top = bottom;
|
||||
bottom = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
public final class Rigidbody extends Script {
|
||||
private static final float MAX_MOVEMENT = 50; // TODO move into Collider/Physics
|
||||
public Vector2 velocity = new Vector2(0, 0.9375f);
|
||||
public float gravity = 1.25f;
|
||||
|
||||
@Override
|
||||
public void update() {
|
||||
if (Time.frameCount > 5) {
|
||||
velocity.y += gravity * Time.fpsScaling60;
|
||||
if (velocity.y > 78.125f) velocity.y = 78.125f;
|
||||
|
||||
float x = velocity.x * Time.fpsScaling60;
|
||||
float y = velocity.y * Time.fpsScaling60;
|
||||
float xAbs = Math.abs(velocity.x * Time.fpsScaling60);
|
||||
float yAbs = Math.abs(velocity.y * Time.fpsScaling60);
|
||||
if (xAbs > yAbs && xAbs > MAX_MOVEMENT) {
|
||||
int iterations = (int) (x / MAX_MOVEMENT);
|
||||
float ratio = MAX_MOVEMENT / x;
|
||||
for (int i = 0; i < iterations; i++) {
|
||||
transform.translate(x * ratio, y * ratio);
|
||||
}
|
||||
ratio = (x % MAX_MOVEMENT) / x;
|
||||
transform.translate(x * ratio, y * ratio);
|
||||
} else if (yAbs > xAbs && yAbs > MAX_MOVEMENT) {
|
||||
int iterations = (int) (y / MAX_MOVEMENT);
|
||||
float ratio = MAX_MOVEMENT / y;
|
||||
for (int i = 0; i < iterations; i++) {
|
||||
transform.translate(x * ratio, y * ratio);
|
||||
}
|
||||
ratio = (y % MAX_MOVEMENT) / y;
|
||||
transform.translate(x * ratio, y * ratio);
|
||||
} else {
|
||||
transform.translate(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare.Platform;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
|
||||
public final class Screen {
|
||||
/**
|
||||
* The current width of the screen
|
||||
*/
|
||||
public static int width = 0;
|
||||
/**
|
||||
* The current height of the screen
|
||||
*/
|
||||
public static int height = 0;
|
||||
/**
|
||||
* The current scaling to apply to objects
|
||||
*/
|
||||
public static float scale = 1;
|
||||
|
||||
// Listen for resize events
|
||||
static {
|
||||
GameListeners.addResizeListener((width, height) -> {
|
||||
Screen.scale = (float) width / 1920f;
|
||||
Screen.width = width;
|
||||
Screen.height = height;
|
||||
Dethsquare.RENDER.setScreenSize(Screen.width, Screen.height);
|
||||
Dethsquare.RENDER.setScale(Screen.scale);
|
||||
});
|
||||
Screen.width = GameListeners.screenSize.width;
|
||||
Screen.height = GameListeners.screenSize.height;
|
||||
Screen.scale = (float) Screen.width / 1920f;
|
||||
Dethsquare.RENDER.setScreenSize(Screen.width, Screen.height);
|
||||
Dethsquare.RENDER.setScale(Screen.scale);
|
||||
}
|
||||
|
||||
public static void setCursorVisible(boolean visible) {
|
||||
/*
|
||||
* Passe par l'abstraction RenderUtils plutôt que DesktopLauncher
|
||||
* directement : le core ne doit pas dépendre d'un back-end concret
|
||||
* (cette fuite core->desktop empêchait toute compilation Android).
|
||||
*/
|
||||
Dethsquare.RENDER.setCursorVisible(visible);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
/**
|
||||
* Base class for all interactive {@link Component Components}
|
||||
*/
|
||||
public class Script extends Component {
|
||||
/**
|
||||
* Determines whether or not this class' {@link #update()} method should be called even when the game has been
|
||||
* paused using {@link Time#pause()}
|
||||
*/
|
||||
protected boolean runWhenPaused = false;
|
||||
|
||||
/**
|
||||
* Called every frame
|
||||
*/
|
||||
public void update() {
|
||||
// Only used in subclasses
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,85 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class StateMachine<T extends Enum> {
|
||||
private final HashMap<T, Transition<T>[]> stateTransitions = new HashMap<>();
|
||||
private final ArrayList<Transition<T>> anyTransitions = new ArrayList<>();
|
||||
private T state;
|
||||
|
||||
public void init(T initialState) {
|
||||
state = initialState;
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public final void addState(T name, Transition<T>... transitions) {
|
||||
stateTransitions.put(name, transitions);
|
||||
}
|
||||
|
||||
public final void addTransitionFromAnyState(Transition<T> transition) {
|
||||
anyTransitions.add(transition);
|
||||
}
|
||||
|
||||
public void update() {
|
||||
for (Transition<T> transition : anyTransitions) {
|
||||
if (transition.getTargetState() != state && transition.isValid()) {
|
||||
state = transition.execute();
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (Transition<T> transition : stateTransitions.get(state)) {
|
||||
if (transition.isValid()) {
|
||||
state = transition.execute();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public T getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(T state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public static class Transition<T> {
|
||||
private final T targetState;
|
||||
private final Condition condition;
|
||||
private final Action action;
|
||||
|
||||
public Transition(T targetState, Condition condition) {
|
||||
this(targetState, condition, null);
|
||||
}
|
||||
|
||||
public Transition(T targetState, Condition condition, Action action) {
|
||||
this.targetState = targetState;
|
||||
this.condition = condition;
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
T getTargetState() {
|
||||
return targetState;
|
||||
}
|
||||
|
||||
boolean isValid() {
|
||||
return condition.check();
|
||||
}
|
||||
|
||||
T execute() {
|
||||
if (action != null) {
|
||||
action.run();
|
||||
}
|
||||
return targetState;
|
||||
}
|
||||
}
|
||||
|
||||
public interface Condition {
|
||||
boolean check();
|
||||
}
|
||||
|
||||
public interface Action {
|
||||
void run();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,122 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.IO;
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.RENDER;
|
||||
|
||||
public final class TextureAtlas {
|
||||
private static final HashMap<String, TextureAtlas> cache = new HashMap<>();
|
||||
private final String imagePath;
|
||||
private final String mapPath;
|
||||
private final HashMap<String, Sprite> atlas = new HashMap<>();
|
||||
public int textureName = -1;
|
||||
public int width;
|
||||
public int height;
|
||||
|
||||
public static TextureAtlas load(String directory) {
|
||||
return load(directory + "/atlas.png", directory + "/atlas.txt", 0, 0);
|
||||
}
|
||||
|
||||
public static TextureAtlas load(String imagePath, String mapPath) {
|
||||
return load(imagePath, mapPath, 0, 0);
|
||||
}
|
||||
|
||||
public static TextureAtlas load(String imagePath, int tileWidth, int tileHeight) {
|
||||
return load(imagePath, null, tileWidth, tileHeight);
|
||||
}
|
||||
|
||||
private static TextureAtlas load(String imagePath, String mapPath, int tileWidth, int tileHeight) {
|
||||
String key = imagePath + mapPath;
|
||||
if (cache.containsKey(key)) {
|
||||
return cache.get(key);
|
||||
} else {
|
||||
TextureAtlas ta = new TextureAtlas(imagePath, mapPath, tileWidth, tileHeight);
|
||||
cache.put(key, ta);
|
||||
return ta;
|
||||
}
|
||||
}
|
||||
|
||||
private TextureAtlas(String imagePath, String mapPath, int tileWidth, int tileHeight) {
|
||||
this.imagePath = imagePath;
|
||||
this.mapPath = mapPath;
|
||||
|
||||
int[] data = RENDER.loadImage(imagePath);
|
||||
|
||||
textureName = data[0];
|
||||
width = data[1];
|
||||
height = data[2];
|
||||
|
||||
if (mapPath == null) {
|
||||
int count = 0;
|
||||
for (int y = 0; y < height; y += tileHeight) {
|
||||
for (int x = 0; x < width; x += tileWidth) {
|
||||
atlas.put(String.valueOf(count++),
|
||||
new Sprite((float) x / width, (float) y / height, (float) tileWidth / width,
|
||||
(float) tileHeight / height));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
String temp;
|
||||
BufferedReader reader = IO.getReader(mapPath);
|
||||
while ((temp = reader.readLine()) != null) {
|
||||
String[] split = temp.split(" = ");
|
||||
String[] split2 = split[1].split(" ");
|
||||
atlas.put(split[0],
|
||||
new Sprite(Float.parseFloat(split2[0]) / width, Float.parseFloat(split2[1]) / height,
|
||||
Float.parseFloat(split2[2]) / width, Float.parseFloat(split2[3]) / height));
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Sprite getSprite(String name) {
|
||||
if (!atlas.containsKey(name)) throw new SpriteNotFoundInAtlasError(name, mapPath);
|
||||
return atlas.get(name);
|
||||
}
|
||||
|
||||
public Sprite[] getSprites() {
|
||||
return atlas.values().toArray(new Sprite[atlas.size()]);
|
||||
}
|
||||
|
||||
public String getImagePath() {
|
||||
return imagePath;
|
||||
}
|
||||
|
||||
public String getMapPath() {
|
||||
return mapPath;
|
||||
}
|
||||
|
||||
public static void clearCache() {
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
public static class Sprite {
|
||||
public float u;
|
||||
public float v;
|
||||
public float w;
|
||||
public float h;
|
||||
|
||||
public Sprite(float u, float v, float w, float h) {
|
||||
this.u = u;
|
||||
this.v = v;
|
||||
this.w = w;
|
||||
this.h = h;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "Sprite(u: " + u + ", v: " + v + ", w: " + w + ", h: " + h + ")";
|
||||
}
|
||||
}
|
||||
|
||||
private static class SpriteNotFoundInAtlasError extends Error {
|
||||
|
||||
private SpriteNotFoundInAtlasError(String spriteName, String atlasPath) {
|
||||
super("Sprite '" + spriteName + "' was not found in the atlas located at " + atlasPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,81 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners.UpdateListener;
|
||||
|
||||
public final class Time {
|
||||
static {
|
||||
// Add hook into game loop
|
||||
GameListeners.addUpdateListener(new UpdateListener() {
|
||||
long last = System.currentTimeMillis();
|
||||
|
||||
@Override
|
||||
public void onUpdate() {
|
||||
long now = System.currentTimeMillis();
|
||||
deltaTime = now - last - pauseTime;
|
||||
pauseTime = 0;
|
||||
fpsScaling60 = deltaTime / frameTime60fps;
|
||||
last = now;
|
||||
frameCount++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Amount of time that a single frame of a game running at 60fps should take
|
||||
*/
|
||||
private static final float frameTime60fps = 1000f / 60f;
|
||||
/**
|
||||
* Whether or not the game is paused
|
||||
*/
|
||||
private static boolean paused = false;
|
||||
/**
|
||||
* The time at which the game was paused
|
||||
*/
|
||||
private static long pauseStartTime = 0;
|
||||
/**
|
||||
* The amount of time that the game has been paused for
|
||||
*/
|
||||
private static long pauseTime = 0;
|
||||
/**
|
||||
* The time in seconds it took to complete the last frame
|
||||
*/
|
||||
public static float deltaTime = frameTime60fps;
|
||||
/**
|
||||
* Multiply movement quantities by this amount so that it scales with a variable frame rate
|
||||
*/
|
||||
public static float fpsScaling60 = deltaTime / frameTime60fps;
|
||||
/**
|
||||
* The total number of frames that have passed
|
||||
*/
|
||||
public static long frameCount;
|
||||
/**
|
||||
* The time at the beginning of this frame. This is the time in seconds since the start of the game
|
||||
*/
|
||||
public static float time;
|
||||
|
||||
/**
|
||||
* Pause the game
|
||||
*/
|
||||
public static void pause() {
|
||||
paused = true;
|
||||
pauseStartTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume the game
|
||||
*/
|
||||
public static void resume() {
|
||||
paused = false;
|
||||
pauseTime = System.currentTimeMillis() - pauseStartTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether or not the game is currently paused
|
||||
*
|
||||
* @return whether or not the game is currently paused
|
||||
*/
|
||||
public static boolean isPaused() {
|
||||
return paused;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
public final class Touch {
|
||||
public final int fingerId;
|
||||
public final Vector2 position;
|
||||
public final Vector2 startPosition;
|
||||
public TouchPhase phase = TouchPhase.BEGAN;
|
||||
public long lastModified = 0;
|
||||
|
||||
public enum TouchPhase {
|
||||
/**
|
||||
* A finger touched the screen
|
||||
*/
|
||||
BEGAN,
|
||||
/**
|
||||
* A finger moved on the screen
|
||||
*/
|
||||
MOVED,
|
||||
/**
|
||||
* A finger is touching the screen but hasn't moved
|
||||
*/
|
||||
STATIONARY,
|
||||
/**
|
||||
* A finger was lifted from the screen. This is the final phase of a touch
|
||||
*/
|
||||
ENDED,
|
||||
/**
|
||||
* The system cancelled tracking for the touch
|
||||
*/
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
public Touch(int fingerId, Vector2 position) {
|
||||
this.fingerId = fingerId;
|
||||
this.position = position;
|
||||
this.startPosition = new Vector2(position.x, position.y);
|
||||
this.lastModified = Time.frameCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Touch(fingerId=" + fingerId + ", phase=" + phase + ")";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,89 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
import com.ezardlabs.dethsquare.Vector2.Vector2ChangeListener;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* {@link Component} that contains the position of a {@link GameObject}
|
||||
*/
|
||||
public final class Transform extends Component {
|
||||
public Vector2 position = new Vector2();
|
||||
public Vector2 scale = new Vector2(1, 1);
|
||||
|
||||
Transform parent;
|
||||
ArrayList<Transform> children = new ArrayList<>();
|
||||
|
||||
Transform(GameObject gameObject) {
|
||||
this.gameObject = gameObject;
|
||||
position.setVector2ChangeListener(new Vector2ChangeListener() {
|
||||
@Override
|
||||
public void onVector2Changed(float xDiff, float yDiff) {
|
||||
for (int i = 0; i < children.size(); i++) {
|
||||
Transform child = children.get(i);
|
||||
child.position.set(child.position.x + xDiff, child.position.y + yDiff);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setParent(Transform parent) {
|
||||
setParent(parent, true);
|
||||
}
|
||||
|
||||
private void setParent(Transform parent, boolean addChild) {
|
||||
this.parent = parent;
|
||||
if (addChild) parent.addChild(this, false);
|
||||
}
|
||||
|
||||
public Transform getParent() {
|
||||
return parent == null || parent.gameObject == GameObject.rootObject ? null : parent;
|
||||
}
|
||||
|
||||
public void addChild(Transform child) {
|
||||
addChild(this, true);
|
||||
}
|
||||
|
||||
private void addChild(Transform child, boolean setParent) {
|
||||
children.add(child);
|
||||
if (setParent) child.setParent(this, false);
|
||||
}
|
||||
|
||||
public Transform getChild(int index) {
|
||||
return children.get(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the {@link GameObject} that this {@link Transform} is attached to. If the {@link GameObject} has a {@link Collider} attached, then the physics
|
||||
*
|
||||
* @param x
|
||||
* @param y
|
||||
*/
|
||||
public void translate(float x, float y) {
|
||||
translate(x, y, x, y);
|
||||
}
|
||||
|
||||
void translate(float x, float y, float xSpeed, float ySpeed) {
|
||||
if (gameObject.isStatic) throw new StaticObjectMovedError(gameObject);
|
||||
if (x == 0 && y == 0) return;
|
||||
float startX = position.x;
|
||||
float startY = position.y;
|
||||
if (gameObject.collider == null) {
|
||||
position.x += x;
|
||||
position.y += y;
|
||||
} else {
|
||||
gameObject.collider.move(x, y, xSpeed, ySpeed);
|
||||
}
|
||||
for (int i = 0; i < children.size(); i++) {
|
||||
children.get(i).translate(position.x - startX, position.y - startY);
|
||||
}
|
||||
}
|
||||
|
||||
private static class StaticObjectMovedError extends Error {
|
||||
|
||||
private StaticObjectMovedError(GameObject staticGameObject) {
|
||||
super("Tried to move GameObject '" + staticGameObject.name + "', but it is " +
|
||||
"marked as static and static objects cannot be moved");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,214 @@
|
||||
package com.ezardlabs.dethsquare;
|
||||
|
||||
/**
|
||||
* Representation of 2D vectors and points
|
||||
*/
|
||||
public final class Vector2 {
|
||||
public float x;
|
||||
public float y;
|
||||
private Vector2ChangeListener listener;
|
||||
|
||||
public static final Vector2 UP = new Vector2(0, -1);
|
||||
public static final Vector2 DOWN = new Vector2(0, 1);
|
||||
public static final Vector2 LEFT = new Vector2(1, 0);
|
||||
public static final Vector2 RIGHT = new Vector2(-1, 0);
|
||||
|
||||
/**
|
||||
* Shorthand for writing Vector2(0, 0)
|
||||
*/
|
||||
public Vector2() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new vector with the given x and y components
|
||||
*/
|
||||
public Vector2(float x, float y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new vector that has the same x and y values as the source vector
|
||||
*/
|
||||
public Vector2(Vector2 source) {
|
||||
this.x = source.x;
|
||||
this.y = source.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the x and y components of the vector
|
||||
*
|
||||
* @param x the new x component
|
||||
* @param y the new y component
|
||||
*/
|
||||
public void set(float x, float y) {
|
||||
if (listener != null) listener.onVector2Changed(x - this.x, y - this.y);
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the x and y components of the vector to be the same as teh given source vector
|
||||
*
|
||||
* @param source the source vector to copy x and y component values from
|
||||
*/
|
||||
public void set(Vector2 source) {
|
||||
if (listener != null) listener.onVector2Changed(source.x - x, source.y - y);
|
||||
x = source.x;
|
||||
y = source.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new {@link Vector2} that has been offset by the given parameters
|
||||
*
|
||||
* @param x The amount to offset the x coordinate by
|
||||
* @param y The amount to offset the y coordinate by
|
||||
* @return The offset {@link Vector2}
|
||||
*/
|
||||
public Vector2 offset(float x, float y) {
|
||||
return new Vector2(this.x + x, this.y + y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of this vector
|
||||
* <p>
|
||||
* If you want to compare the magnitudes of 2 vectors then it is advisable to compare their
|
||||
* square magnitudes({@link #sqrMagnitude()}) as they are faster to compute
|
||||
*
|
||||
* @return The length of this vector
|
||||
*/
|
||||
public double magnitude() {
|
||||
return Math.sqrt(x * x + y * y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the squared length of this vector
|
||||
*
|
||||
* @return The squared length of this vector
|
||||
*/
|
||||
public float sqrMagnitude() {
|
||||
return x * x + y * y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes this vector have a magnitude of 1
|
||||
* <p>
|
||||
* Note that this method modifies the vector it is called on; if you want to keep the vector
|
||||
* unchanged, then use {@link #normalised()} instead
|
||||
*/
|
||||
public void normalise() {
|
||||
double length = Math.sqrt(x * x + y * y);
|
||||
if (length != 0) {
|
||||
x /= length;
|
||||
y /= length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns this vector with a magnitude of 1
|
||||
* <p>
|
||||
* Not that this method does not modify the vector it is called on; if you want to modify the
|
||||
* vector then use {@link #normalise()} instead
|
||||
*
|
||||
* @return The normalised version of this vector
|
||||
*/
|
||||
public Vector2 normalised() {
|
||||
Vector2 v = new Vector2(this);
|
||||
v.normalise();
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiplies the vector by the given value
|
||||
* <p>
|
||||
* Note that this method modifies the vector it is called on; if you want to keep the vector
|
||||
* unchanged, then use {@link #multipliedBy(float)} instead
|
||||
*
|
||||
* @param multiplier The amount to multiply the vector by
|
||||
*/
|
||||
public void multiplyBy(float multiplier) {
|
||||
x *= multiplier;
|
||||
y *= multiplier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns this vector multiplied by the given value
|
||||
* <p>
|
||||
* Not that this method does not modify the vector it is called on; if you want to modify the
|
||||
* vector then use {@link #multiplyBy(float)} instead
|
||||
*
|
||||
* @param multiplier The amount to multiply the vector by
|
||||
* @return A new vector, equal to the vector this method was called on multiplied by the given value
|
||||
*/
|
||||
public Vector2 multipliedBy(float multiplier) {
|
||||
return new Vector2(x * multiplier, y * multiplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Divides the vector by the given value
|
||||
* <p>
|
||||
* Note that this method modifies the vector it is called on; if you want to keep the vector
|
||||
* unchanged, then use {@link #dividedBy(float)} instead
|
||||
*
|
||||
* @param divider The amount to divide the vector by
|
||||
*/
|
||||
public void divideBy(float divider) {
|
||||
x /= divider;
|
||||
y /= divider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns this vector divided by the given value
|
||||
* <p>
|
||||
* Not that this method does not modify the vector it is called on; if you want to modify the
|
||||
* vector then use {@link #divideBy(float)} instead
|
||||
*
|
||||
* @param divider The amount to multiply the vector by
|
||||
* @return A new vector, equal to the vector this method was called on multiplied by the given value
|
||||
*/
|
||||
public Vector2 dividedBy(float divider) {
|
||||
return new Vector2(x / divider, y / divider);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the distance between 2 coordinate points
|
||||
*
|
||||
* @param x1 the first point's x coordinate
|
||||
* @param y1 the first point's y coordinate
|
||||
* @param x2 the second point's x coordinate
|
||||
* @param y2 the second point's y coordinate
|
||||
* @return The distance between the 2 points
|
||||
*/
|
||||
public static double distance(double x1, double y1, double x2, double y2) {
|
||||
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the distance between 2 vector points
|
||||
*
|
||||
* @param a the first point
|
||||
* @param b the second point
|
||||
* @return The distance between the 2 points
|
||||
*/
|
||||
public static double distance(Vector2 a, Vector2 b) {
|
||||
return distance(a.x, a.y, b.x, b.y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Vector2(" + x + ", " + y + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return o instanceof Vector2 && ((Vector2) o).x == x && ((Vector2) o).y == y;
|
||||
}
|
||||
|
||||
void setVector2ChangeListener(Vector2ChangeListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
interface Vector2ChangeListener {
|
||||
void onVector2Changed(float xDiff, float yDiff);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,83 @@
|
||||
package com.ezardlabs.dethsquare.animation;
|
||||
|
||||
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
|
||||
import com.ezardlabs.dethsquare.Vector2;
|
||||
|
||||
public final class Animation {
|
||||
public final String name;
|
||||
final Sprite[] frames;
|
||||
final FrameData[] frameData;
|
||||
AnimationType type;
|
||||
AnimationListener listener;
|
||||
|
||||
public Animation(String name, Sprite[] frames, FrameData[] frameData, AnimationType type) {
|
||||
this(name, frames, frameData, type, null);
|
||||
}
|
||||
|
||||
public Animation(String name, Sprite[] frames, FrameData[] frameData, AnimationType type,
|
||||
AnimationListener listener) {
|
||||
this.name = name;
|
||||
this.frames = frames;
|
||||
this.type = type.clone();
|
||||
this.frameData = frameData;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
public void setAnimationType(AnimationType type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public void setAnimationListener(AnimationListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
static class FrameData {
|
||||
private final int width;
|
||||
private final int height;
|
||||
private final Vector2[] offsets;
|
||||
private final long duration;
|
||||
|
||||
FrameData(int width, int height, Vector2 offset, long duration) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.offsets = new Vector2[]{offset};
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
FrameData(int width, int height, Vector2[] offsets, long duration) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.offsets = offsets;
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
Vector2 getOffset(float scale) {
|
||||
if (offsets.length == 1) return offsets[0];
|
||||
if (scale > 0) {
|
||||
return offsets[0];
|
||||
} else {
|
||||
return offsets[1];
|
||||
}
|
||||
}
|
||||
|
||||
long getDuration() {
|
||||
return duration;
|
||||
}
|
||||
}
|
||||
|
||||
public interface AnimationListener {
|
||||
void onAnimatedStarted(Animator animator);
|
||||
|
||||
void onFrame(Animator animator, int frameNum);
|
||||
|
||||
void onAnimationFinished(Animator animator);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,69 @@
|
||||
package com.ezardlabs.dethsquare.animation;
|
||||
|
||||
public abstract class AnimationType implements Cloneable {
|
||||
/**
|
||||
* An animation that runs a single time, from start to end
|
||||
*/
|
||||
public static final AnimationType ONE_SHOT = new AnimationType() {
|
||||
@Override
|
||||
public int update(int currentFrame, int numFrames) {
|
||||
if (currentFrame < numFrames - 1) return currentFrame + 1;
|
||||
else return -1;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* An animation that oscillates between its start and end points
|
||||
*/
|
||||
public static final AnimationType OSCILLATE = new AnimationType() {
|
||||
private int direction = 1;
|
||||
|
||||
@Override
|
||||
public int update(int currentFrame, int numFrames) {
|
||||
int frame = currentFrame + direction;
|
||||
if (frame == 0 || frame == numFrames - 1) {
|
||||
direction *= -1;
|
||||
}
|
||||
return frame;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* An animation that plays through from start to end, restarting when finished
|
||||
*/
|
||||
public static final AnimationType LOOP = new AnimationType() {
|
||||
@Override
|
||||
public int update(int currentFrame, int numFrames) {
|
||||
int frame = currentFrame + 1;
|
||||
if (frame == numFrames) frame = 0;
|
||||
return frame;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* An animation that will be defined later in code
|
||||
*/
|
||||
public static final AnimationType CUSTOM = new AnimationType() {
|
||||
@Override
|
||||
public int update(int currentFrame, int numFrames) {
|
||||
throw new RuntimeException("Custom animations should be defined in code");
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Describes how the animation should progress, based on the current frame
|
||||
*
|
||||
* @param currentFrame The frame that the animation is currently at
|
||||
* @param numFrames The total number of frames in the animation
|
||||
* @return The next frame in the animation to go to
|
||||
*/
|
||||
public abstract int update(int currentFrame, int numFrames);
|
||||
|
||||
@Override
|
||||
public AnimationType clone() {
|
||||
try {
|
||||
return (AnimationType) super.clone();
|
||||
} catch (CloneNotSupportedException | ClassCastException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,261 @@
|
||||
package com.ezardlabs.dethsquare.animation;
|
||||
|
||||
import com.ezardlabs.dethsquare.animation.Animation.FrameData;
|
||||
import com.ezardlabs.dethsquare.TextureAtlas;
|
||||
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
|
||||
import com.ezardlabs.dethsquare.Vector2;
|
||||
import com.ezardlabs.dethsquare.animation.Animations.Validator.ValidationError;
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class Animations {
|
||||
private static HashMap<String, Animation[]> cache = new HashMap<>();
|
||||
|
||||
public static Animation[] load(String path, TextureAtlas ta) {
|
||||
return load(path, ta, null);
|
||||
}
|
||||
|
||||
public static Animation[] load(String path, TextureAtlas ta, Validator validator) {
|
||||
String cacheKey = path + ta.getImagePath() + ta.getMapPath();
|
||||
Animation[] anims;
|
||||
|
||||
if (cache.containsKey(cacheKey)) {
|
||||
anims = cache.get(cacheKey);
|
||||
} else {
|
||||
try {
|
||||
AnimationData data = AnimationData.parse(path);
|
||||
anims = data.getAnimations(ta);
|
||||
} catch (JSONException e) {
|
||||
/*
|
||||
* JSONException est checked côté Android mais unchecked (Runtime-
|
||||
* Exception) dans le jar Maven récent utilisé côté desktop : on
|
||||
* catche ici pour compiler sur les deux plateformes et on
|
||||
* relance en RuntimeException avec le chemin fautif.
|
||||
*/
|
||||
throw new RuntimeException("Invalid animation file: " + path, e);
|
||||
}
|
||||
if (validator != null && !validator.validate(anims)) {
|
||||
throw new ValidationError(path);
|
||||
}
|
||||
cache.put(cacheKey, anims);
|
||||
}
|
||||
|
||||
Animation[] animations = new Animation[anims.length];
|
||||
System.arraycopy(anims, 0, animations, 0, anims.length);
|
||||
return animations;
|
||||
}
|
||||
|
||||
private static class AnimationData {
|
||||
private final HashSet<DataAnimation> animations = new HashSet<>();
|
||||
private Defaults defaults;
|
||||
|
||||
private AnimationData() {
|
||||
}
|
||||
|
||||
private Animation[] getAnimations(TextureAtlas ta) {
|
||||
Animation[] animations = new Animation[this.animations.size()];
|
||||
int count = 0;
|
||||
for (DataAnimation da : this.animations) {
|
||||
animations[count++] = da.toAnimation(ta);
|
||||
}
|
||||
return animations;
|
||||
}
|
||||
|
||||
private static AnimationData parse(String path) throws JSONException {
|
||||
JSONObject json = new JSONObject(String.join(" ", Dethsquare.IO.getFileLines(path + "/anim.json")));
|
||||
|
||||
AnimationData data;
|
||||
if (json.has("extends")) {
|
||||
data = parse(json.getString("extends"));
|
||||
} else {
|
||||
data = new AnimationData();
|
||||
}
|
||||
|
||||
if (json.has("defaults")) {
|
||||
data.defaults = Defaults.parse(json.getJSONObject("defaults"));
|
||||
}
|
||||
|
||||
for (DataAnimation da : DataAnimation.parseArray(json.getJSONArray("animations"), data.defaults)) {
|
||||
if (!data.animations.add(da)) {
|
||||
data.animations.remove(da);
|
||||
data.animations.add(da);
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
private static Vector2[] parseOffsets(JSONObject offset) throws JSONException {
|
||||
if (offset.has("x") && offset.has("y")) {
|
||||
return new Vector2[]{new Vector2(offset.getInt("x"), offset.getInt("y"))};
|
||||
} else if (offset.has("normal") && offset.has("flipped")) {
|
||||
return new Vector2[]{parseOffsets(offset.getJSONObject("normal"))[0], parseOffsets(
|
||||
offset.getJSONObject("flipped"))[0]};
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported offset type");
|
||||
}
|
||||
}
|
||||
|
||||
private static class Defaults {
|
||||
private final int width;
|
||||
private final int height;
|
||||
private final Vector2[] offset;
|
||||
private final long duration;
|
||||
|
||||
private Defaults(int width, int height, Vector2[] offset, long duration) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.offset = offset;
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
private static Defaults parse(JSONObject json) throws JSONException {
|
||||
return new Defaults(json.getInt("width"), json.getInt("height"),
|
||||
parseOffsets(json.getJSONObject("offset")), json.getLong("duration"));
|
||||
}
|
||||
}
|
||||
|
||||
private static class DataAnimation {
|
||||
private final String name;
|
||||
private final ArrayList<DataSprite> sprites;
|
||||
private final String type;
|
||||
|
||||
private DataAnimation(String name, ArrayList<DataSprite> sprites, String type) {
|
||||
this.name = name;
|
||||
this.sprites = sprites;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
private Animation toAnimation(TextureAtlas ta) {
|
||||
Sprite[] sprites = new Sprite[this.sprites.size()];
|
||||
FrameData[] frameData = new FrameData[this.sprites.size()];
|
||||
|
||||
int count = 0;
|
||||
for (DataSprite ds : this.sprites) {
|
||||
sprites[count] = ds.toSprite(ta);
|
||||
frameData[count++] = ds.toFrameData();
|
||||
}
|
||||
|
||||
AnimationType animationType;
|
||||
switch (type) {
|
||||
case "ONE_SHOT":
|
||||
animationType = AnimationType.ONE_SHOT;
|
||||
break;
|
||||
case "LOOP":
|
||||
animationType = AnimationType.LOOP;
|
||||
break;
|
||||
case "OSCILLATE":
|
||||
animationType = AnimationType.OSCILLATE;
|
||||
break;
|
||||
case "CUSTOM":
|
||||
animationType = AnimationType.CUSTOM;
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("No animation type was specified for '" + name + "'");
|
||||
}
|
||||
return new Animation(name, sprites, frameData, animationType);
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
return (o instanceof DataAnimation) && (((DataAnimation) o).name.equals(name));
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return name.hashCode();
|
||||
}
|
||||
|
||||
private static ArrayList<DataAnimation> parseArray(JSONArray array, Defaults defaults) throws JSONException {
|
||||
ArrayList<DataAnimation> animations = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < array.length(); i++) {
|
||||
animations.add(parse(array.getJSONObject(i), defaults));
|
||||
}
|
||||
|
||||
return animations;
|
||||
}
|
||||
|
||||
private static DataAnimation parse(JSONObject json, Defaults defaults) throws JSONException {
|
||||
ArrayList<DataSprite> sprites = new ArrayList<>();
|
||||
JSONArray array = json.getJSONArray("sprites");
|
||||
|
||||
if (json.has("defaults")) {
|
||||
defaults = Defaults.parse(json.getJSONObject("defaults"));
|
||||
}
|
||||
|
||||
for (int i = 0; i < array.length(); i++) {
|
||||
sprites.add(DataSprite.parse(array.getJSONObject(i), defaults));
|
||||
}
|
||||
|
||||
return new DataAnimation(json.getString("name"), sprites, json.getString("type"));
|
||||
}
|
||||
|
||||
private static class DataSprite {
|
||||
private final String name;
|
||||
private final int width;
|
||||
private final int height;
|
||||
private final Vector2[] offset;
|
||||
private final long duration;
|
||||
|
||||
private DataSprite(String name, int width, int height, Vector2[] offset, long duration) {
|
||||
this.name = name;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.offset = offset;
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
private Sprite toSprite(TextureAtlas ta) {
|
||||
return ta.getSprite(name);
|
||||
}
|
||||
|
||||
private FrameData toFrameData() {
|
||||
return new FrameData(width, height, offset, duration);
|
||||
}
|
||||
|
||||
private static DataSprite parse(JSONObject json, Defaults defaults) throws JSONException {
|
||||
return new DataSprite(json.getString("name"),
|
||||
json.has("width") ? json.getInt("width") : defaults.width,
|
||||
json.has("height") ? json.getInt("height") : defaults.height,
|
||||
json.has("offset") ? parseOffsets(json.getJSONObject("offset")) : defaults.offset,
|
||||
json.has("duration") ? json.getLong("duration") : defaults.duration);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class Validator {
|
||||
private final String[] requiredAnimations;
|
||||
|
||||
public Validator(String... requiredAnimations) {
|
||||
this.requiredAnimations = requiredAnimations;
|
||||
}
|
||||
|
||||
private boolean validate(Animation[] animations) {
|
||||
for (String s : requiredAnimations) {
|
||||
boolean found = false;
|
||||
for (Animation a : animations) {
|
||||
if (a.name.equals(s)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static class ValidationError extends Error {
|
||||
|
||||
ValidationError(String path) {
|
||||
System.err.println("Animation validation failed for " + path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,148 @@
|
||||
package com.ezardlabs.dethsquare.animation;
|
||||
|
||||
import com.ezardlabs.dethsquare.Component.RequiredComponents;
|
||||
import com.ezardlabs.dethsquare.graphics.Renderer;
|
||||
import com.ezardlabs.dethsquare.Script;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
@RequiredComponents(Renderer.class)
|
||||
public final class Animator extends Script implements Iterable<Animation> {
|
||||
private Animation[] animations;
|
||||
private int index = -1;
|
||||
private int frame = -2;
|
||||
private long nextFrameTime = 0;
|
||||
private boolean finished = false;
|
||||
|
||||
public Animator(Animation... animations) {
|
||||
this.animations = animations;
|
||||
}
|
||||
|
||||
public void setAnimations(Animation... animations) {
|
||||
this.animations = animations;
|
||||
}
|
||||
|
||||
public void addAnimations(Animation... animations) {
|
||||
Animation[] newAnimations = new Animation[this.animations.length + animations.length];
|
||||
System.arraycopy(this.animations, 0, newAnimations, 0, this.animations.length);
|
||||
System.arraycopy(animations, 0, newAnimations, this.animations.length, animations.length);
|
||||
this.animations = newAnimations;
|
||||
}
|
||||
|
||||
private void setFrame(int frame) {
|
||||
if (frame != this.frame) {
|
||||
this.frame = frame;
|
||||
if (frame != -1) {
|
||||
this.nextFrameTime = System.currentTimeMillis() + animations[index].frameData[frame].getDuration();
|
||||
setRendererData(animations[index], frame);
|
||||
// gameObject.renderer.setSprite(animations[index].frames[frame]);
|
||||
// gameObject.renderer.setData(animations[index].frameData[frame]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setRendererData(Animation animation, int frame) {
|
||||
gameObject.renderer.setSprite(animation.frames[frame]);
|
||||
gameObject.renderer.setSize(animation.frameData[frame].getWidth(), animation.frameData[frame].getHeight());
|
||||
gameObject.renderer.setOffsets(animation.frameData[frame].getOffset(transform.scale.x));
|
||||
}
|
||||
|
||||
public void update() {
|
||||
int startFrame = frame;
|
||||
if (index == -1 || frame == -1) return;
|
||||
int tempFrame;
|
||||
if (System.currentTimeMillis() >= nextFrameTime) {
|
||||
nextFrameTime += animations[index].frameData[frame].getDuration();
|
||||
tempFrame = animations[index].type.update(frame, animations[index].frames.length);
|
||||
if (tempFrame == -1) {
|
||||
if (!finished) {
|
||||
if (animations[index].listener != null) {
|
||||
animations[index].listener.onAnimationFinished(this);
|
||||
}
|
||||
finished = true;
|
||||
}
|
||||
setFrame(tempFrame);
|
||||
return;
|
||||
} else {
|
||||
finished = false;
|
||||
}
|
||||
setFrame(tempFrame);
|
||||
} else {
|
||||
tempFrame = frame;
|
||||
}
|
||||
if (tempFrame != startFrame && animations[index].listener != null) {
|
||||
animations[index].listener.onFrame(this, tempFrame);
|
||||
}
|
||||
}
|
||||
|
||||
private void resetAndStart(int i) {
|
||||
index = i;
|
||||
frame = -2;
|
||||
setFrame(0);
|
||||
finished = false;
|
||||
if (animations[index].listener != null) animations[index].listener.onAnimatedStarted(this);
|
||||
}
|
||||
|
||||
public void play(String animationName) {
|
||||
play(animationName, false);
|
||||
}
|
||||
|
||||
public void play(String animationName, boolean refresh) {
|
||||
if (refresh && index > -1) {
|
||||
if (animations[index].name.equals(animationName)) {
|
||||
if (finished) {
|
||||
resetAndStart(index);
|
||||
return;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < animations.length; i++) {
|
||||
if (i != index && animations[i].name.equals(animationName)) {
|
||||
resetAndStart(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Animation getCurrentAnimation() {
|
||||
if (index == -1) return null;
|
||||
else return animations[index];
|
||||
}
|
||||
|
||||
public int getCurrentAnimationId() {
|
||||
return index;
|
||||
}
|
||||
|
||||
public void setCurrentAnimationId(int animationId) {
|
||||
index = animationId;
|
||||
}
|
||||
|
||||
public int getCurrentAnimationFrame() {
|
||||
return frame == -1 ? 0 : frame;
|
||||
}
|
||||
|
||||
public void setCurrentAnimationFrame(int frame) {
|
||||
setFrame(frame);
|
||||
}
|
||||
|
||||
public boolean isFinished() {
|
||||
return finished;
|
||||
}
|
||||
|
||||
public Animation getAnimation(String name) {
|
||||
for (Animation animation : animations) {
|
||||
if (animation.name.equals(name)) {
|
||||
return animation;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<Animation> iterator() {
|
||||
return new ObjectIterator<>(animations);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
package com.ezardlabs.dethsquare.animation;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
final class ObjectIterator<T> implements Iterator<T> {
|
||||
private final T[] objects;
|
||||
private int current = -1;
|
||||
|
||||
public ObjectIterator(T[] objects) {
|
||||
this.objects = objects;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return current >= objects.length - 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T next() {
|
||||
return objects[++current];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
package com.ezardlabs.dethsquare.debug;
|
||||
|
||||
import com.ezardlabs.dethsquare.Vector2;
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/*
|
||||
* Point d'entrée des graphiques de debug (cercles/rects affichés une frame).
|
||||
*
|
||||
* Historique : le core référençait directement DebugCircle/DebugRect du module
|
||||
* desktop (dessin GL11 legacy : glBegin/glPushMatrix), ce qui empêchait la
|
||||
* compilation Android et planterait aussi sur un contexte GL core 3.2 moderne
|
||||
* (API immédiate supprimée). Les implémentations concrètes sont donc désormais
|
||||
* des no-op définies ICI, indépendantes de la plateforme :
|
||||
* - les graphiques sont accumulés et "consommés" par renderAll() sans être
|
||||
* dessinés ;
|
||||
* - le backend desktop garde ses classes GL11 (inutilisées) pour référence ;
|
||||
* - un vrai rendu debug multi-plateforme passerait par RenderUtils
|
||||
* (TODO : redessiner les DebugGraphics en batch GLES/GL core si besoin).
|
||||
*
|
||||
* Usage réel dans le jeu : SmartCamera (debug flag, désactivé en prod).
|
||||
*/
|
||||
public class Debug {
|
||||
static {
|
||||
GameListeners.addRenderListener(Debug::renderAll);
|
||||
}
|
||||
private static ArrayList<DebugGraphic> debugGraphics = new ArrayList<>();
|
||||
|
||||
public static void drawCircle(Vector2 position, float radius, float red, float green, float blue) {
|
||||
debugGraphics.add(new Circle(position.x, position.y, radius, red, green, blue));
|
||||
}
|
||||
|
||||
public static void drawRect(Vector2 position, float width, float height, float red, float green, float blue) {
|
||||
debugGraphics.add(new Rect(position.x, position.y, width, height, red, green, blue));
|
||||
}
|
||||
|
||||
private static void renderAll() {
|
||||
Dethsquare.RENDER.render(debugGraphics);
|
||||
debugGraphics.clear();
|
||||
}
|
||||
|
||||
// Implémentations no-op, package-private (même package que les bases).
|
||||
private static class Circle extends DebugCircleBase {
|
||||
Circle(float x, float y, float radius, float red, float green, float blue) {
|
||||
super(x, y, radius, red, green, blue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(float cameraX, float cameraY, float scale) {
|
||||
// Voir doc de classe : rendu debug non porté (phase 1).
|
||||
}
|
||||
}
|
||||
|
||||
private static class Rect extends DebugRectBase {
|
||||
Rect(float x, float y, float width, float height, float red, float green, float blue) {
|
||||
super(x, y, width, height, red, green, blue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(float cameraX, float cameraY, float scale) {
|
||||
// Voir doc de classe : rendu debug non porté (phase 1).
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,192 @@
|
||||
package com.ezardlabs.dethsquare.graphics;
|
||||
|
||||
import com.ezardlabs.dethsquare.Camera;
|
||||
import com.ezardlabs.dethsquare.QuadTree;
|
||||
import com.ezardlabs.dethsquare.RectF;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.RENDER;
|
||||
|
||||
public class GraphicsEngine {
|
||||
// Add hook into game loop
|
||||
static {
|
||||
GameListeners.addRenderListener(GraphicsEngine::render);
|
||||
}
|
||||
|
||||
private static final ArrayList<Renderer> renderers = new ArrayList<>();
|
||||
private static final QuadTree<Renderer> qt = new QuadTree<>(30);
|
||||
|
||||
private static float[] vertices = new float[0];
|
||||
private static short[] indices = new short[0];
|
||||
private static float[] uvs = new float[0];
|
||||
private static float[] colours = new float[0];
|
||||
|
||||
private static int verticesLength = 0;
|
||||
private static int indicesLength = 0;
|
||||
private static int uvsLength = 0;
|
||||
private static int coloursLength = 0;
|
||||
|
||||
private static ArrayList<Renderer> visible = new ArrayList<>();
|
||||
|
||||
public static void register(Renderer renderer) {
|
||||
renderers.add(renderer);
|
||||
|
||||
verticesLength += 12;
|
||||
indicesLength += 6;
|
||||
uvsLength += 8;
|
||||
coloursLength += 48;
|
||||
}
|
||||
|
||||
public static void deregister(Renderer renderer) {
|
||||
renderers.remove(renderer);
|
||||
|
||||
verticesLength -= 12;
|
||||
indicesLength -= 6;
|
||||
uvsLength -= 8;
|
||||
coloursLength -= 48;
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
List<Renderer> staticRenderers = renderers.parallelStream()
|
||||
.peek(r -> r.getBounds()
|
||||
.set(r.transform.position.x, r.transform.position.y,
|
||||
r.transform.position.x + r.width,
|
||||
r.transform.position.y + r.height))
|
||||
.filter(renderer -> renderer.gameObject.isStatic)
|
||||
.collect(Collectors.toList());
|
||||
qt.build(staticRenderers);
|
||||
renderers.removeAll(staticRenderers);
|
||||
}
|
||||
|
||||
public static void clearAll() {
|
||||
renderers.clear();
|
||||
}
|
||||
|
||||
public static void destroyAllTextures() {
|
||||
RENDER.destroyAllTextures();
|
||||
}
|
||||
|
||||
public static void clearQuadTree() {
|
||||
qt.reset();
|
||||
}
|
||||
|
||||
private static void render() {
|
||||
visible.clear();
|
||||
qt.retrieve(visible, Camera.main);
|
||||
|
||||
visible.addAll(renderers); // TODO only add renderers that are visible
|
||||
|
||||
render(visible);
|
||||
}
|
||||
|
||||
private static void render(ArrayList<Renderer> renderers) {
|
||||
renderers.parallelStream()
|
||||
.filter(renderer -> renderer.enabled && renderer.gameObject.isActive())
|
||||
.collect(Collectors.groupingBy(Renderer::getKey, TreeMap::new, Collectors.toList()))
|
||||
.forEach((key, renderersList) -> {
|
||||
setupRenderData(renderersList);
|
||||
RENDER.setGuiRenderMode(key >>> 61 > 1);
|
||||
RENDER.render((int) (key & 16777215L), vertices, uvs, indices, colours, renderersList.size());
|
||||
});
|
||||
}
|
||||
|
||||
private static void setupRenderData(List<Renderer> renderers) {
|
||||
int i = 0;
|
||||
int last = 0;
|
||||
Renderer r;
|
||||
for (int j = 0; j < renderers.size(); j++) {
|
||||
r = renderers.get(j);
|
||||
|
||||
setupVertices(r, i);
|
||||
|
||||
setupIndices(i, last);
|
||||
last = last + 4;
|
||||
|
||||
setupUVs(r, i);
|
||||
|
||||
setupColours(r, i);
|
||||
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
private static void setupVertices(Renderer r, int i) {
|
||||
if (vertices.length != verticesLength) {
|
||||
vertices = new float[verticesLength];
|
||||
}
|
||||
RectF bounds = r.getBounds();
|
||||
vertices[(i * 12)] = vertices[(i * 12) + 3] = bounds.left;
|
||||
vertices[(i * 12) + 1] = vertices[(i * 12) + 10] = bounds.bottom;
|
||||
vertices[(i * 12) + 2] = vertices[(i * 12) + 5] = vertices[(i * 12) + 8] = vertices[(i * 12) + 11] = r.getDepth();
|
||||
vertices[(i * 12) + 4] = vertices[(i * 12) + 7] = bounds.top;
|
||||
vertices[(i * 12) + 6] = vertices[(i * 12) + 9] = bounds.right;
|
||||
}
|
||||
|
||||
private static void setupIndices(int i, int last) {
|
||||
if (indices.length != indicesLength) {
|
||||
indices = new short[indicesLength];
|
||||
}
|
||||
indices[(i * 6)] = indices[(i * 6) + 3] = (short) (last);
|
||||
indices[(i * 6) + 1] = (short) (last + 1);
|
||||
indices[(i * 6) + 2] = indices[(i * 6) + 4] = (short) (last + 2);
|
||||
indices[(i * 6) + 5] = (short) (last + 3);
|
||||
}
|
||||
|
||||
private static void setupUVs(Renderer r, int i) {
|
||||
if (uvs.length != uvsLength) {
|
||||
uvs = new float[uvsLength];
|
||||
}
|
||||
if (r.transform.scale.x < 0 && r.transform.scale.y < 0) {
|
||||
uvs[(i * 8) + 6] = r.sprite.u;
|
||||
uvs[(i * 8) + 7] = r.sprite.v;
|
||||
uvs[(i * 8) + 4] = r.sprite.u;
|
||||
uvs[(i * 8) + 5] = r.sprite.v + r.sprite.h;
|
||||
uvs[(i * 8) + 2] = r.sprite.u + r.sprite.w;
|
||||
uvs[(i * 8) + 3] = r.sprite.v + r.sprite.h;
|
||||
uvs[(i * 8)] = r.sprite.u + r.sprite.w;
|
||||
uvs[(i * 8) + 1] = r.sprite.v;
|
||||
} else if (r.transform.scale.x < 0) {
|
||||
uvs[(i * 8) + 4] = r.sprite.u;
|
||||
uvs[(i * 8) + 5] = r.sprite.v;
|
||||
uvs[(i * 8) + 6] = r.sprite.u;
|
||||
uvs[(i * 8) + 7] = r.sprite.v + r.sprite.h;
|
||||
uvs[(i * 8)] = r.sprite.u + r.sprite.w;
|
||||
uvs[(i * 8) + 1] = r.sprite.v + r.sprite.h;
|
||||
uvs[(i * 8) + 2] = r.sprite.u + r.sprite.w;
|
||||
uvs[(i * 8) + 3] = r.sprite.v;
|
||||
} else if (r.transform.scale.y < 0) {
|
||||
uvs[(i * 8)] = r.sprite.u;
|
||||
uvs[(i * 8) + 1] = r.sprite.v;
|
||||
uvs[(i * 8) + 2] = r.sprite.u;
|
||||
uvs[(i * 8) + 3] = r.sprite.v + r.sprite.h;
|
||||
uvs[(i * 8) + 4] = r.sprite.u + r.sprite.w;
|
||||
uvs[(i * 8) + 5] = r.sprite.v + r.sprite.h;
|
||||
uvs[(i * 8) + 6] = r.sprite.u + r.sprite.w;
|
||||
uvs[(i * 8) + 7] = r.sprite.v;
|
||||
} else {
|
||||
uvs[(i * 8) + 2] = r.sprite.u;
|
||||
uvs[(i * 8) + 3] = r.sprite.v;
|
||||
uvs[(i * 8)] = r.sprite.u;
|
||||
uvs[(i * 8) + 1] = r.sprite.v + r.sprite.h;
|
||||
uvs[(i * 8) + 6] = r.sprite.u + r.sprite.w;
|
||||
uvs[(i * 8) + 7] = r.sprite.v + r.sprite.h;
|
||||
uvs[(i * 8) + 4] = r.sprite.u + r.sprite.w;
|
||||
uvs[(i * 8) + 5] = r.sprite.v;
|
||||
}
|
||||
}
|
||||
|
||||
private static void setupColours(Renderer r, int i) {
|
||||
if (colours.length != coloursLength) {
|
||||
colours = new float[coloursLength];
|
||||
}
|
||||
colours[i * 16] = colours[i * 16 + 4] = colours[i * 16 + 8] = colours[i * 16 + 12] = r.getTint()[0];
|
||||
colours[i * 16 + 1] = colours[i * 16 + 5] = colours[i * 16 + 9] = colours[i * 16 + 13] = r.getTint()[1];
|
||||
colours[i * 16 + 2] = colours[i * 16 + 6] = colours[i * 16 + 10] = colours[i * 16 + 14] = r.getTint()[2];
|
||||
colours[i * 16 + 3] = colours[i * 16 + 7] = colours[i * 16 + 11] = colours[i * 16 + 15] = r.getTint()[3];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,90 @@
|
||||
package com.ezardlabs.dethsquare.graphics;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class Material {
|
||||
private static HashMap<String, Material> cache = new HashMap<>();
|
||||
private static int idCount = 0;
|
||||
|
||||
private final int id;
|
||||
private final int shader;
|
||||
private final HashMap<String, Integer> uniformMapping;
|
||||
private final HashMap<String, Integer> attributeMapping;
|
||||
|
||||
private Material(int shader, HashMap<String, Integer> uniformMapping, HashMap<String, Integer> attributeMapping) {
|
||||
this.id = idCount++;
|
||||
this.shader = shader;
|
||||
this.uniformMapping = uniformMapping;
|
||||
this.attributeMapping = attributeMapping;
|
||||
}
|
||||
|
||||
public static Material load(String path) {
|
||||
if (cache.containsKey(path)) {
|
||||
return cache.get(path).copy();
|
||||
} else {
|
||||
// JSONException est checked côté Android, unchecked dans le jar
|
||||
// Maven desktop : catch ici pour compiler sur les deux plateformes.
|
||||
try {
|
||||
JSONObject json = new JSONObject(String.join(" ", Dethsquare.IO.getFileLines(path)));
|
||||
|
||||
int shader = parseShader(json);
|
||||
HashMap<String, Integer> uniformMapping = parseVariables(shader, json, true);
|
||||
HashMap<String, Integer> attributeMapping = parseVariables(shader, json, false);
|
||||
|
||||
Material material = new Material(shader, uniformMapping, attributeMapping);
|
||||
cache.put(path, material);
|
||||
return material;
|
||||
} catch (JSONException e) {
|
||||
throw new RuntimeException("Invalid material file: " + path, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int parseShader(JSONObject json) {
|
||||
try {
|
||||
JSONObject shaderObject = json.getJSONObject("shader");
|
||||
return Dethsquare.RENDER.loadShaderProgram(shaderObject.getString("vertex"),
|
||||
shaderObject.getString("fragment"));
|
||||
} catch (JSONException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static HashMap<String, Integer> parseVariables(int shader, JSONObject json, boolean global) {
|
||||
HashMap<String, Integer> map = new HashMap<>();
|
||||
try {
|
||||
JSONArray properties = json.getJSONArray("properties");
|
||||
for (int i = 0; i < properties.length(); i++) {
|
||||
JSONObject property = properties.getJSONObject(i);
|
||||
if (global) {
|
||||
if (property.has("global") && property.getBoolean("global")) {
|
||||
String name = property.getString("name");
|
||||
map.put(name, Dethsquare.RENDER.getUniformLocation(shader, name));
|
||||
}
|
||||
} else {
|
||||
if (!property.has("global") || (property.has("global") && !property.getBoolean("global"))) {
|
||||
String name = property.getString("name");
|
||||
map.put(name, Dethsquare.RENDER.getAttributeLocation(shader, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
private Material copy() {
|
||||
return new Material(shader, new HashMap<>(uniformMapping), new HashMap<>(attributeMapping));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,255 @@
|
||||
package com.ezardlabs.dethsquare.graphics;
|
||||
|
||||
import com.ezardlabs.dethsquare.Bounded;
|
||||
import com.ezardlabs.dethsquare.Component;
|
||||
import com.ezardlabs.dethsquare.GameObject;
|
||||
import com.ezardlabs.dethsquare.RectF;
|
||||
import com.ezardlabs.dethsquare.Screen;
|
||||
import com.ezardlabs.dethsquare.TextureAtlas;
|
||||
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
|
||||
import com.ezardlabs.dethsquare.Vector2;
|
||||
|
||||
import static com.ezardlabs.dethsquare.util.Dethsquare.RENDER;
|
||||
|
||||
public class Renderer extends Component implements Bounded, Comparable<Renderer> {
|
||||
private static final int DEPTH_OFFSET = 100000;
|
||||
private static final int MIN_DEPTH = -DEPTH_OFFSET;
|
||||
private static final int MAX_DEPTH = DEPTH_OFFSET;
|
||||
/**
|
||||
* <table cellspacing="10">
|
||||
* <tr>
|
||||
* <td>0 (1 bit):</td>
|
||||
* <td>ignored</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>1 - 2 (2 bits):</td>
|
||||
* <td>layer:</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td></td>
|
||||
* <td>
|
||||
* <ul style="list-style:none">
|
||||
* <li>game = 0</li>
|
||||
* <li>game fullscreen effect = 1</li>
|
||||
* <li>HUD = 2</li>
|
||||
* <li>total fullscreen effect = 3</li>
|
||||
* </ul>
|
||||
* </td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>3 - 5 (3 bits):</td>
|
||||
* <td>viewport</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>6 - 7 (2 bits):</td>
|
||||
* <td>translucency type (opaque, translucent (space for normal/additive/subtractive subtypes)):</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td></td>
|
||||
* <td>
|
||||
* <ul>
|
||||
* <li>opaque = 0</li>
|
||||
* <li>translucent = 1</li>
|
||||
* </ul>
|
||||
* </td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>8 - 39 (32 bits):</td>
|
||||
* <td>depth</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>40 - 63 (24 bits):</td>
|
||||
* <td>texture ID</td>
|
||||
* </tr>
|
||||
* </table>
|
||||
* <br/><br/>
|
||||
* <table cellspacing="10">
|
||||
* <tr>
|
||||
* <td>0</td>
|
||||
* <td>00</td>
|
||||
* <td>000</td>
|
||||
* <td>00</td>
|
||||
* <td>00000000000000000000000000000000</td>
|
||||
* <td>000000000000000000000000</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>ignored</td>
|
||||
* <td>layer</td>
|
||||
* <td>viewport</td>
|
||||
* <td>translucency</td>
|
||||
* <td>depth</td>
|
||||
* <td>texture ID</td>
|
||||
* </tr>
|
||||
* </table>
|
||||
*/
|
||||
private long key = 0;
|
||||
|
||||
public Sprite sprite = new Sprite(0, 0, 0, 0);
|
||||
public float width;
|
||||
public float height;
|
||||
private int depth = 0;
|
||||
private final float[] tint = {
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1
|
||||
};
|
||||
protected final RectF bounds = new RectF();
|
||||
|
||||
public int textureName = -1;
|
||||
public float xOffset;
|
||||
public float yOffset;
|
||||
|
||||
public Renderer() {
|
||||
}
|
||||
|
||||
public Renderer(String imagePath, float width, float height) {
|
||||
setImage(imagePath, width, height);
|
||||
setKeyLayer();
|
||||
}
|
||||
|
||||
public Renderer(TextureAtlas textureAtlas, Sprite sprite, float width, float height) {
|
||||
setTextureAtlas(textureAtlas, width, height);
|
||||
this.sprite = sprite;
|
||||
setKeyLayer();
|
||||
}
|
||||
|
||||
public Renderer(TextureAtlas textureAtlas) {
|
||||
setTextureAtlas(textureAtlas);
|
||||
setKeyLayer();
|
||||
}
|
||||
|
||||
public long getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
private void setTextureName(int textureName) {
|
||||
this.textureName = textureName;
|
||||
// clear material section id key
|
||||
key = key &~ 16777215L;
|
||||
// set material section of key
|
||||
key |= textureName;
|
||||
}
|
||||
|
||||
public void setImage(String imagePath, float width, float height) {
|
||||
int[] data = RENDER.loadImage(imagePath);
|
||||
setTextureName(data[0]);
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
sprite.u = sprite.v = 0;
|
||||
sprite.w = sprite.h = 1;
|
||||
}
|
||||
|
||||
public void setSprite(Sprite sprite) {
|
||||
this.sprite = sprite;
|
||||
}
|
||||
|
||||
public void setSize(float width, float height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public void setOffsets(float xOffset, float yOffset) {
|
||||
this.xOffset = xOffset;
|
||||
this.yOffset = yOffset;
|
||||
}
|
||||
|
||||
public void setOffsets(Vector2 offsets) {
|
||||
xOffset = offsets.x;
|
||||
yOffset = offsets.y;
|
||||
}
|
||||
|
||||
public void setTextureAtlas(TextureAtlas textureAtlas) {
|
||||
setTextureName(textureAtlas.textureName);
|
||||
}
|
||||
|
||||
public void setTextureAtlas(TextureAtlas textureAtlas, float spriteWidth, float spriteHeight) {
|
||||
setTextureName(textureAtlas.textureName);
|
||||
width = spriteWidth;
|
||||
height = spriteHeight;
|
||||
}
|
||||
|
||||
public void setTint(float red, float green, float blue) {
|
||||
tint[0] = red;
|
||||
tint[1] = green;
|
||||
tint[2] = blue;
|
||||
}
|
||||
|
||||
public void setTint(float red, float green, float blue, float alpha) {
|
||||
tint[0] = red;
|
||||
tint[1] = green;
|
||||
tint[2] = blue;
|
||||
tint[3] = alpha;
|
||||
}
|
||||
|
||||
public void setDepth(int depth) {
|
||||
if (depth < MIN_DEPTH || depth > MAX_DEPTH) {
|
||||
throw new IllegalArgumentException("Depth must be between " + MIN_DEPTH + " and " + MAX_DEPTH);
|
||||
}
|
||||
this.depth = depth + DEPTH_OFFSET;
|
||||
// clear depth section of key
|
||||
key = key &~ 72057594021150720L;
|
||||
// set depth section
|
||||
key |= Integer.toUnsignedLong(this.depth) << 24;
|
||||
}
|
||||
|
||||
public int getDepth() {
|
||||
return depth;
|
||||
}
|
||||
|
||||
public float[] getTint() {
|
||||
return tint;
|
||||
}
|
||||
|
||||
protected float getXPos() {
|
||||
return transform.position.x + xOffset;
|
||||
}
|
||||
|
||||
protected float getYPos() {
|
||||
return transform.position.y + yOffset;
|
||||
}
|
||||
|
||||
private void setKeyLayer() {
|
||||
byte layer = getLayer();
|
||||
if (layer < 0 || layer > 3) {
|
||||
throw new IllegalArgumentException("Layer must be between 0 and 3 inclusive");
|
||||
} else {
|
||||
// clear layer section of key
|
||||
key = key &~ 6917529027641081856L;
|
||||
// set layer section of key
|
||||
//noinspection NumericOverflow
|
||||
key |= (long) layer << 61;
|
||||
}
|
||||
}
|
||||
|
||||
protected byte getLayer() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
GraphicsEngine.register(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void destroy() {
|
||||
GraphicsEngine.deregister(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RectF getBounds() {
|
||||
bounds.set(getXPos() * Screen.scale, getYPos() * Screen.scale, (getXPos() + width) * Screen.scale,
|
||||
(getYPos() + height) * Screen.scale);
|
||||
return bounds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GameObject getGameObject() {
|
||||
return gameObject;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Renderer r) {
|
||||
return Long.compare(key, r.key);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
package com.ezardlabs.dethsquare.graphics;
|
||||
|
||||
import com.ezardlabs.dethsquare.TextureAtlas;
|
||||
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
|
||||
public class Texture {
|
||||
private int textureName;
|
||||
private TextureAtlas textureAtlas;
|
||||
private Sprite sprite;
|
||||
|
||||
public Texture(TextureAtlas textureAtlas) {
|
||||
this(textureAtlas, new Sprite(0, 0, 1, 1));
|
||||
}
|
||||
|
||||
public Texture(TextureAtlas textureAtlas, String spriteName) {
|
||||
this(textureAtlas, textureAtlas.getSprite(spriteName));
|
||||
}
|
||||
|
||||
public Texture(TextureAtlas textureAtlas, Sprite sprite) {
|
||||
textureName = textureAtlas.textureName;
|
||||
}
|
||||
|
||||
public Texture(String imagePath) {
|
||||
textureName = Dethsquare.RENDER.loadImage(imagePath)[1];
|
||||
textureAtlas = null;
|
||||
}
|
||||
|
||||
public void setSprite(Sprite sprite) {
|
||||
this.sprite = sprite;
|
||||
}
|
||||
|
||||
int getTextureName() {
|
||||
return textureName;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,6 @@
|
||||
package com.ezardlabs.dethsquare.modding;
|
||||
|
||||
public abstract class Mod {
|
||||
|
||||
public abstract void load();
|
||||
}
|
||||
@ -0,0 +1,126 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import com.ezardlabs.dethsquare.multiplayer.Network.UDPReader;
|
||||
import com.ezardlabs.dethsquare.multiplayer.Network.UDPWriter;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners.UpdateListener;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketException;
|
||||
|
||||
public class Matchmaker implements NetworkConstants {
|
||||
private UDPReader udpReader;
|
||||
private UDPWriter udpWriter;
|
||||
private MatchmakingGame game;
|
||||
private long lastGamePing = 0;
|
||||
|
||||
public Matchmaker(InetAddress ip, int serverPort) {
|
||||
DatagramSocket socket = null;
|
||||
try {
|
||||
socket = new DatagramSocket();
|
||||
} catch (SocketException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (socket == null) {
|
||||
throw new IllegalStateException("Failed to create matchmaking socket");
|
||||
} else {
|
||||
udpReader = new UDPReader(socket);
|
||||
udpWriter = new UDPWriter(socket, new InetSocketAddress[]{new InetSocketAddress(ip, serverPort)});
|
||||
udpReader.start();
|
||||
udpWriter.start();
|
||||
Network.init();
|
||||
}
|
||||
}
|
||||
|
||||
public void findGame(MatchmakingListener listener) {
|
||||
udpWriter.sendMessage(getJsonMessage(MATCHMAKING_JOIN, false).toString().getBytes());
|
||||
GameListeners.addUpdateListener(new UpdateListener() {
|
||||
@Override
|
||||
public void onUpdate() {
|
||||
if (game != null && System.currentTimeMillis() - lastGamePing > PING_INTERVAL) {
|
||||
udpWriter.sendMessage(getJsonMessage(GAME_PING, true).toString().getBytes());
|
||||
lastGamePing = System.currentTimeMillis();
|
||||
}
|
||||
synchronized (udpReader.udpMessages) {
|
||||
while (!udpReader.udpMessages.isEmpty()) {
|
||||
try {
|
||||
JSONObject json = new JSONObject(new String(udpReader.udpMessages.remove(0)));
|
||||
String message = json.getString("message");
|
||||
switch (message) {
|
||||
case GAME_CREATE:
|
||||
setGame(MatchmakingGame.fromJson(json.getJSONObject("game")));
|
||||
Network.createGame();
|
||||
if (listener.onCreateGame()) {
|
||||
udpWriter.sendMessage(getJsonMessage(GAME_CREATE, true).toString().getBytes());
|
||||
}
|
||||
break;
|
||||
case GAME_JOIN:
|
||||
MatchmakingGame game = MatchmakingGame.fromJson(json.getJSONObject("game"));
|
||||
setGame(game);
|
||||
Network.joinGame(game, json.getInt("playerId"));
|
||||
listener.onGameFound(game);
|
||||
Network.requestState();
|
||||
udpWriter.sendMessage(getJsonMessage(GAME_JOIN, true).toString().getBytes());
|
||||
break;
|
||||
case PLAYER_JOIN:
|
||||
Network.addPlayer(MatchmakingPlayer.fromJson(json.getJSONObject("player")));
|
||||
break;
|
||||
default:
|
||||
listener.onError("Unknown error");
|
||||
break;
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
/*
|
||||
* JSONException est checked côté Android (framework)
|
||||
* mais unchecked dans le jar Maven desktop : catch
|
||||
* requis pour compiler sur les deux. Une réponse
|
||||
* malformée du serveur est ignorée (feature
|
||||
* multiplayer hors service de toute façon — les
|
||||
* serveurs d'origine sont éteints).
|
||||
*/
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void setGame(MatchmakingGame game) {
|
||||
this.game = game;
|
||||
}
|
||||
|
||||
private MatchmakingGame getGame() {
|
||||
return game;
|
||||
}
|
||||
|
||||
private JSONObject getJsonMessage(String message, boolean includeGame) {
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("udpPort", Network.getUdpPort());
|
||||
json.put("tcpPort", Network.getTcpPort());
|
||||
json.put("message", message);
|
||||
if (includeGame) {
|
||||
json.put("gameId", getGame().getId());
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
// Impossible en pratique (pas de clé dupliquée) : JSONException est
|
||||
// checked côté Android, catch requis pour compiler.
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
public interface MatchmakingListener {
|
||||
boolean onCreateGame();
|
||||
|
||||
void onGameFound(MatchmakingGame game);
|
||||
|
||||
void onError(String error);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class MatchmakingGame {
|
||||
private final int id;
|
||||
private final MatchmakingPlayer[] players;
|
||||
|
||||
private MatchmakingGame(int id, MatchmakingPlayer[] players) {
|
||||
this.id = id;
|
||||
this.players = players;
|
||||
}
|
||||
|
||||
int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public MatchmakingPlayer[] getPlayers() {
|
||||
return players;
|
||||
}
|
||||
|
||||
static MatchmakingGame fromJson(JSONObject object) {
|
||||
// JSONException est checked côté Android : les appelants (Matchmaker)
|
||||
// catchent déjà, on propage.
|
||||
try {
|
||||
JSONArray jsonPlayers = object.getJSONArray("players");
|
||||
MatchmakingPlayer[] players = new MatchmakingPlayer[jsonPlayers.length()];
|
||||
for (int i = 0; i < jsonPlayers.length(); i++) {
|
||||
if (!jsonPlayers.isNull(i)) {
|
||||
players[i] = MatchmakingPlayer.fromJson(jsonPlayers.getJSONObject(i));
|
||||
}
|
||||
}
|
||||
return new MatchmakingGame(object.getInt("id"), players);
|
||||
} catch (JSONException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
class MatchmakingPlayer {
|
||||
private String ip;
|
||||
private int udpPort;
|
||||
private int tcpPort;
|
||||
private final int id;
|
||||
|
||||
private MatchmakingPlayer(String ip, int udpPort, int tcpPort, int id) {
|
||||
this.ip = ip;
|
||||
this.udpPort = udpPort;
|
||||
this.tcpPort = tcpPort;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
String getIp() {
|
||||
return ip;
|
||||
}
|
||||
|
||||
public int getUdpPort() {
|
||||
return udpPort;
|
||||
}
|
||||
|
||||
public int getTcpPort() {
|
||||
return tcpPort;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
static MatchmakingPlayer fromJson(JSONObject object) {
|
||||
// JSONException est checked côté Android : le caller (Matchmaker) catche.
|
||||
try {
|
||||
return new MatchmakingPlayer(object.getString("ip"), object.getInt("udpPort"), object.getInt("tcpPort"),
|
||||
object.getInt("id"));
|
||||
} catch (JSONException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,493 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import com.ezardlabs.dethsquare.GameObject;
|
||||
import com.ezardlabs.dethsquare.Vector2;
|
||||
import com.ezardlabs.dethsquare.prefabs.PrefabManager;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners;
|
||||
import com.ezardlabs.dethsquare.util.GameListeners.UpdateListener;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.SocketException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class Network {
|
||||
private static UpdateListener updateListener;
|
||||
|
||||
private static UDPWriter udpOut;
|
||||
private static UDPReader udpIn;
|
||||
private static final InetSocketAddress[] udpAddresses = new InetSocketAddress[4];
|
||||
private static final TCPWriter[] tcpOut = new TCPWriter[4];
|
||||
|
||||
private static final int START_PORT = 2828;
|
||||
private static DatagramSocket datagramSocket;
|
||||
private static ServerSocket serverSocket;
|
||||
private static int udpPort = -1;
|
||||
private static int tcpPort = -1;
|
||||
|
||||
private static int playerId = 0;
|
||||
private static boolean host = true;
|
||||
|
||||
private static int networkIdCounter = 1;
|
||||
private static HashMap<Integer, InstantiationData> networkObjects = new HashMap<>();
|
||||
|
||||
private static final long UPDATES_PER_SECOND = 60;
|
||||
private static long lastUpdate = 0;
|
||||
|
||||
private static final String DIVIDER = "|";
|
||||
private static final String SPLIT_DIVIDER = Pattern.quote(DIVIDER);
|
||||
private static final String INSTANTIATE = "instantiate";
|
||||
private static final String DESTROY = "destroy";
|
||||
private static final String REQUEST_STATE = "request_state";
|
||||
|
||||
public enum Protocol {
|
||||
UDP,
|
||||
TCP
|
||||
}
|
||||
|
||||
static void init() {
|
||||
datagramSocket = getNewDatagramSocket();
|
||||
udpPort = datagramSocket.getLocalPort();
|
||||
serverSocket = getNewServerSocket(udpPort + 1);
|
||||
tcpPort = serverSocket.getLocalPort();
|
||||
|
||||
UPnPManager.discover();
|
||||
UPnPManager.addPortMapping(udpPort, Protocol.UDP, "Lost Sector UDP " + udpPort);
|
||||
UPnPManager.addPortMapping(tcpPort, Protocol.TCP, "Lost Sector TCP " + tcpPort);
|
||||
|
||||
udpOut = new UDPWriter(datagramSocket, udpAddresses);
|
||||
udpOut.start();
|
||||
udpIn = new UDPReader(datagramSocket);
|
||||
udpIn.start();
|
||||
new TCPServer(serverSocket).start();
|
||||
}
|
||||
|
||||
static DatagramSocket getNewDatagramSocket() {
|
||||
return getNewDatagramSocket(START_PORT);
|
||||
}
|
||||
|
||||
static DatagramSocket getNewDatagramSocket(int startPort) {
|
||||
int port = startPort;
|
||||
DatagramSocket ds;
|
||||
while (true) {
|
||||
try {
|
||||
ds = new DatagramSocket(port);
|
||||
break;
|
||||
} catch (SocketException ignored) {
|
||||
}
|
||||
port++;
|
||||
}
|
||||
return ds;
|
||||
}
|
||||
|
||||
static ServerSocket getNewServerSocket() {
|
||||
return getNewServerSocket(START_PORT);
|
||||
}
|
||||
|
||||
static ServerSocket getNewServerSocket(int startPort) {
|
||||
int port = startPort;
|
||||
ServerSocket ss;
|
||||
while (true) {
|
||||
try {
|
||||
ss = new ServerSocket(port);
|
||||
break;
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
return ss;
|
||||
}
|
||||
|
||||
static int getUdpPort() {
|
||||
return udpPort;
|
||||
}
|
||||
|
||||
static int getTcpPort() {
|
||||
return tcpPort;
|
||||
}
|
||||
|
||||
public static int getPlayerId() {
|
||||
return playerId;
|
||||
}
|
||||
|
||||
static int getNewNetworkId() {
|
||||
return networkIdCounter++;
|
||||
}
|
||||
|
||||
public static boolean isHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
private static void update() {
|
||||
if (System.currentTimeMillis() >= lastUpdate + 1000 / UPDATES_PER_SECOND) {
|
||||
lastUpdate = System.currentTimeMillis();
|
||||
ByteBuffer data = ByteBuffer.allocate(
|
||||
NetworkBehaviour.totalSize + (NetworkBehaviour.myNetworkBehaviours.size() * 8));
|
||||
for (NetworkBehaviour nb : NetworkBehaviour.myNetworkBehaviours.values()) {
|
||||
data.putInt(nb.getNetworkId());
|
||||
data.putShort(nb.getSize());
|
||||
data.put(nb.onSend());
|
||||
}
|
||||
udpOut.sendMessage(data.array());
|
||||
}
|
||||
synchronized (udpIn.udpMessages) {
|
||||
while (!udpIn.udpMessages.isEmpty()) {
|
||||
int count = 0;
|
||||
ByteBuffer data = ByteBuffer.wrap(udpIn.udpMessages.remove(0));
|
||||
NetworkBehaviour nb;
|
||||
while (count < data.capacity()) {
|
||||
data.position(count);
|
||||
int networkId = data.getInt(count);
|
||||
if (networkId == 0) break;
|
||||
int size = data.getShort(count + 4);
|
||||
nb = NetworkBehaviour.otherNetworkBehaviours.get(networkId);
|
||||
if (nb != null) {
|
||||
nb.onReceive(data, count + 6);
|
||||
}
|
||||
count += size + 6;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void createGame() {
|
||||
host = true;
|
||||
GameListeners.addUpdateListener(Network::update);
|
||||
}
|
||||
|
||||
static void joinGame(MatchmakingGame game, int playerId) {
|
||||
host = false;
|
||||
Network.playerId = playerId;
|
||||
networkIdCounter = playerId * (Integer.MAX_VALUE / 4) + 1;
|
||||
for (MatchmakingPlayer player : game.getPlayers()) {
|
||||
if (player.getId() != playerId) {
|
||||
addPlayer(player);
|
||||
}
|
||||
}
|
||||
GameListeners.addUpdateListener(Network::update);
|
||||
}
|
||||
|
||||
static void addPlayer(MatchmakingPlayer player) {
|
||||
udpAddresses[player.getId()] = new InetSocketAddress(player.getIp(), player.getUdpPort());
|
||||
udpOut.setAddresses(udpAddresses);
|
||||
try {
|
||||
System.out.println("Attempting to connect to TCP port " + player.getTcpPort());
|
||||
tcpOut[player.getId()] = new TCPWriter(new Socket(player.getIp(), player.getTcpPort()));
|
||||
tcpOut[player.getId()].start();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
static class UDPReader extends Thread {
|
||||
private final DatagramSocket socket;
|
||||
final ArrayList<byte[]> udpMessages = new ArrayList<>();
|
||||
|
||||
UDPReader(DatagramSocket socket) {
|
||||
super("UDPReader");
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
|
||||
while (true) {
|
||||
socket.receive(packet);
|
||||
synchronized (udpMessages) {
|
||||
udpMessages.add(packet.getData());
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static class UDPWriter extends Thread {
|
||||
private final DatagramSocket socket;
|
||||
private final ArrayList<byte[]> messages = new ArrayList<>();
|
||||
private final DatagramPacket[] packets;
|
||||
|
||||
UDPWriter(DatagramSocket socket, SocketAddress[] addresses) {
|
||||
super("UDPWriter");
|
||||
this.socket = socket;
|
||||
packets = new DatagramPacket[addresses.length];
|
||||
for (int i = 0; i < packets.length; i++) {
|
||||
if (addresses[i] == null) {
|
||||
packets[i] = null;
|
||||
} else {
|
||||
packets[i] = new DatagramPacket(new byte[0], 0, addresses[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
synchronized (messages) {
|
||||
messages.wait();
|
||||
while (!messages.isEmpty()) {
|
||||
byte[] message = messages.remove(0);
|
||||
for (int i = 0; i < packets.length; i++) {
|
||||
if (packets[i] != null) {
|
||||
packets[i].setData(message);
|
||||
socket.send(packets[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException | InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
void sendMessage(byte[] message) {
|
||||
synchronized (messages) {
|
||||
messages.add(message);
|
||||
messages.notify();
|
||||
}
|
||||
}
|
||||
|
||||
void setAddresses(SocketAddress[] addresses) {
|
||||
for (int i = 0; i < packets.length; i++) {
|
||||
if (addresses[i] == null) {
|
||||
packets[i] = null;
|
||||
} else {
|
||||
packets[i] = new DatagramPacket(new byte[0], 0, addresses[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class TCPServer extends Thread {
|
||||
private final ServerSocket serverSocket;
|
||||
|
||||
TCPServer(ServerSocket serverSocket) {
|
||||
super("TCPServer");
|
||||
this.serverSocket = serverSocket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
while (true) {
|
||||
new TCPReader(serverSocket.accept()).start();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class TCPReader extends Thread {
|
||||
private final Socket socket;
|
||||
|
||||
TCPReader(Socket socket) {
|
||||
super("TCPReader");
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
|
||||
socket.setKeepAlive(true);
|
||||
while (socket.isConnected()) {
|
||||
String command = in.readLine();
|
||||
if (command != null) {
|
||||
switch (command) {
|
||||
case INSTANTIATE:
|
||||
processInstantiation(in.readLine());
|
||||
break;
|
||||
case DESTROY:
|
||||
processDestruction(in.readLine());
|
||||
break;
|
||||
case REQUEST_STATE:
|
||||
sendState(in.readLine());
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown command:" + command);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
in.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class TCPWriter extends Thread {
|
||||
private final Socket socket;
|
||||
private final ArrayList<String[]> messages = new ArrayList<>();
|
||||
private boolean initialising = true;
|
||||
|
||||
TCPWriter(Socket socket) {
|
||||
super("TCPWriter");
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
|
||||
while (true) {
|
||||
synchronized (messages) {
|
||||
if (!initialising) {
|
||||
messages.wait();
|
||||
initialising = false;
|
||||
}
|
||||
while (!messages.isEmpty()) {
|
||||
String[] s = messages.remove(0);
|
||||
out.write(s[0]);
|
||||
out.newLine();
|
||||
out.write(s[1]);
|
||||
out.newLine();
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException | InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
void sendMessage(String command, String message) {
|
||||
if (message.contains("\n") || message.contains("\r")) {
|
||||
throw new IllegalArgumentException("Message cannot contain newline characters");
|
||||
}
|
||||
synchronized (messages) {
|
||||
messages.add(new String[]{command, message});
|
||||
messages.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class InstantiationData {
|
||||
final String prefabName;
|
||||
final Vector2 position;
|
||||
final int playerId;
|
||||
final GameObject gameObject;
|
||||
|
||||
private InstantiationData(String prefabName, Vector2 position, int playerId, GameObject gameObject) {
|
||||
this.prefabName = prefabName;
|
||||
this.position = position;
|
||||
this.playerId = playerId;
|
||||
this.gameObject = gameObject;
|
||||
}
|
||||
}
|
||||
|
||||
public static GameObject instantiate(String prefabName, Vector2 position) {
|
||||
return instantiate(prefabName, position, tcpOut);
|
||||
}
|
||||
|
||||
private static GameObject instantiate(String prefabName, Vector2 position, TCPWriter... tcpWriters) {
|
||||
GameObject gameObject = PrefabManager.loadPrefab(prefabName);
|
||||
gameObject.networkId = getNewNetworkId();
|
||||
InstantiationData data = new InstantiationData(prefabName, position, playerId, gameObject);
|
||||
String message = getInstantiationMessage(data);
|
||||
for (TCPWriter writer : tcpWriters) {
|
||||
if (writer != null) {
|
||||
writer.sendMessage(INSTANTIATE, message);
|
||||
}
|
||||
}
|
||||
GameObject go = GameObject.instantiate(gameObject, position);
|
||||
networkObjects.put(go.networkId, data);
|
||||
return go;
|
||||
}
|
||||
|
||||
private static String getInstantiationMessage(InstantiationData data) {
|
||||
List<NetworkBehaviour> networkBehaviours = data.gameObject.getComponentsOfType(NetworkBehaviour.class);
|
||||
HashMap<String, Integer> networkIds = new HashMap<>();
|
||||
for (NetworkBehaviour nb : networkBehaviours) {
|
||||
networkIds.put(nb.getClass().getCanonicalName(), nb.getNetworkId());
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (PrefabManager.prefabExists(data.prefabName + "_other")) {
|
||||
sb.append(data.prefabName).append("_other").append(DIVIDER);
|
||||
} else {
|
||||
sb.append(data.prefabName).append(DIVIDER);
|
||||
}
|
||||
sb.append(data.gameObject.networkId).append(DIVIDER);
|
||||
sb.append(data.position.x).append(DIVIDER);
|
||||
sb.append(data.position.y).append(DIVIDER);
|
||||
sb.append(playerId).append(DIVIDER);
|
||||
for (String key : networkIds.keySet()) {
|
||||
sb.append(key).append(DIVIDER).append(networkIds.get(key)).append(DIVIDER);
|
||||
}
|
||||
String message = sb.toString();
|
||||
message = message.substring(0, message.length() - 1);
|
||||
return message;
|
||||
}
|
||||
|
||||
private static void processInstantiation(String message) throws IOException {
|
||||
String[] split = message.split(SPLIT_DIVIDER);
|
||||
GameObject gameObject = PrefabManager.loadPrefab(split[0]);
|
||||
gameObject.networkId = Integer.parseInt(split[1]);
|
||||
Vector2 position = new Vector2(Float.parseFloat(split[2]), Float.parseFloat(split[3]));
|
||||
int playerId = Integer.parseInt(split[4]);
|
||||
List<NetworkBehaviour> networkBehaviours = gameObject.getComponentsOfType(NetworkBehaviour.class);
|
||||
HashMap<String, Integer> networkIds = new HashMap<>();
|
||||
for (int i = 0; i < networkBehaviours.size(); i++) {
|
||||
networkIds.put(split[5 + (i * 2)], Integer.parseInt(split[6 + (i * 2)]));
|
||||
}
|
||||
for (NetworkBehaviour nb : networkBehaviours) {
|
||||
nb.setPlayerId(playerId);
|
||||
nb.setNetworkId(networkIds.get(nb.getClass().getCanonicalName()));
|
||||
}
|
||||
GameObject go = GameObject.instantiate(gameObject, position);
|
||||
networkObjects.put(go.networkId, new InstantiationData(split[0], position, playerId, gameObject));
|
||||
}
|
||||
|
||||
public static void destroy(GameObject gameObject) {
|
||||
GameObject.destroy(gameObject);
|
||||
handleGameObjectDestruction(gameObject);
|
||||
}
|
||||
|
||||
public static void destroy(GameObject gameObject, long delay) {
|
||||
GameObject.destroy(gameObject, delay, () -> handleGameObjectDestruction(gameObject));
|
||||
}
|
||||
|
||||
private static void handleGameObjectDestruction(GameObject gameObject) {
|
||||
networkObjects.remove(gameObject.networkId);
|
||||
for (TCPWriter writer : tcpOut) {
|
||||
if (writer != null) {
|
||||
writer.sendMessage(DESTROY, String.valueOf(gameObject.networkId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void processDestruction(String message) throws IOException {
|
||||
int networkId = Integer.parseInt(message);
|
||||
GameObject.destroy(networkId);
|
||||
networkObjects.remove(networkId);
|
||||
}
|
||||
|
||||
static void requestState() {
|
||||
tcpOut[0].sendMessage(REQUEST_STATE, String.valueOf(playerId));
|
||||
}
|
||||
|
||||
private static void sendState(String in) {
|
||||
int id = Integer.parseInt(in);
|
||||
for (InstantiationData data : networkObjects.values()) {
|
||||
if (data.playerId != id) {
|
||||
System.out.println(playerId + ": Instantiation send: " + getInstantiationMessage(data));
|
||||
tcpOut[id].sendMessage(INSTANTIATE, getInstantiationMessage(data));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import com.ezardlabs.dethsquare.animation.Animator;
|
||||
import com.ezardlabs.dethsquare.Component.RequiredComponents;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
@RequiredComponents(Animator.class)
|
||||
public class NetworkAnimator extends NetworkBehaviour {
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
super.start();
|
||||
assert gameObject.animator != null;
|
||||
gameObject.animator.enabled = getPlayerId() == Network.getPlayerId();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ByteBuffer onSend() {
|
||||
data.position(0);
|
||||
data.putShort(0, (short) gameObject.animator.getCurrentAnimationId()); // 0 - 1
|
||||
data.putShort(2, (short) gameObject.animator.getCurrentAnimationFrame()); // 2 - 3
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onReceive(ByteBuffer data, int index) {
|
||||
gameObject.animator.setCurrentAnimationId(data.getShort(index));
|
||||
gameObject.animator.setCurrentAnimationFrame(data.getShort(index + 2));
|
||||
}
|
||||
|
||||
@Override
|
||||
public short getSize() {
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import com.ezardlabs.dethsquare.Component;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.HashMap;
|
||||
|
||||
public abstract class NetworkBehaviour extends Component {
|
||||
static HashMap<Integer, NetworkBehaviour> myNetworkBehaviours = new HashMap<>();
|
||||
static HashMap<Integer, NetworkBehaviour> otherNetworkBehaviours = new HashMap<>();
|
||||
static int totalSize = 0;
|
||||
private int networkId;
|
||||
private int playerId = -1;
|
||||
protected final ByteBuffer data = ByteBuffer.allocate(getSize());
|
||||
|
||||
public NetworkBehaviour() {
|
||||
networkId = Network.getNewNetworkId();
|
||||
playerId = Network.getPlayerId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
if (playerId == Network.getPlayerId()) {
|
||||
myNetworkBehaviours.put(networkId, this);
|
||||
totalSize += getSize();
|
||||
} else {
|
||||
otherNetworkBehaviours.put(networkId, this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void destroy() {
|
||||
if (playerId == Network.getPlayerId()) {
|
||||
myNetworkBehaviours.remove(networkId);
|
||||
totalSize -= getSize();
|
||||
} else {
|
||||
otherNetworkBehaviours.remove(networkId);
|
||||
}
|
||||
}
|
||||
|
||||
void setNetworkId(int networkId) {
|
||||
this.networkId = networkId;
|
||||
}
|
||||
|
||||
public int getNetworkId() {
|
||||
return networkId;
|
||||
}
|
||||
|
||||
void setPlayerId(int playerId) {
|
||||
this.playerId = playerId;
|
||||
}
|
||||
|
||||
public int getPlayerId() {
|
||||
return playerId;
|
||||
}
|
||||
|
||||
protected abstract ByteBuffer onSend();
|
||||
|
||||
protected abstract void onReceive(ByteBuffer data, int index);
|
||||
|
||||
public abstract short getSize();
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
public interface NetworkConstants {
|
||||
String MATCHMAKING_JOIN = "matchmaking_join";
|
||||
String MATCHMAKING_PING = "matchmaking_ping";
|
||||
String MATCHMAKING_LEAVE = "matchmaking_leave";
|
||||
|
||||
String GAME_CREATE = "game_create";
|
||||
String GAME_JOIN = "game_join";
|
||||
String GAME_PING = "game_ping";
|
||||
String GAME_LEAVE = "game_leave";
|
||||
|
||||
String PLAYER_JOIN = "player_join";
|
||||
String PLAYER_LEAVE = "player_leave";
|
||||
|
||||
int PING_INTERVAL = 1000;
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import com.ezardlabs.dethsquare.Component.RequiredComponents;
|
||||
import com.ezardlabs.dethsquare.graphics.Renderer;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
@RequiredComponents(Renderer.class)
|
||||
public class NetworkRenderer extends NetworkBehaviour {
|
||||
|
||||
@Override
|
||||
protected ByteBuffer onSend() {
|
||||
data.position(0);
|
||||
data.putFloat(0, gameObject.renderer.width); // 0 - 3
|
||||
data.putFloat(4, gameObject.renderer.height); // 4 - 7
|
||||
data.putFloat(8, gameObject.renderer.xOffset); // 8 - 11
|
||||
data.putFloat(12, gameObject.renderer.yOffset); // 12 - 15
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onReceive(ByteBuffer data, int index) {
|
||||
gameObject.renderer.setSize(data.getFloat(index), data.getFloat(index + 4));
|
||||
gameObject.renderer.setOffsets(data.getFloat(index + 8), data.getFloat(index + 12));
|
||||
}
|
||||
|
||||
@Override
|
||||
public short getSize() {
|
||||
return 16;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import com.ezardlabs.dethsquare.Component.RequiredComponents;
|
||||
import com.ezardlabs.dethsquare.Transform;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
@RequiredComponents(Transform.class)
|
||||
public class NetworkTransform extends NetworkBehaviour {
|
||||
|
||||
@Override
|
||||
protected ByteBuffer onSend() {
|
||||
data.position(0);
|
||||
data.putFloat(0, transform.position.x); // 0 - 3
|
||||
data.putFloat(4, transform.position.y); // 4 - 7
|
||||
data.putFloat(8, transform.scale.x); // 8 - 11
|
||||
data.putFloat(12, transform.scale.y); // 12 - 15
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onReceive(ByteBuffer data, int index) {
|
||||
transform.position.set(data.getFloat(index), data.getFloat(index + 4));
|
||||
if (gameObject.collider != null) {
|
||||
gameObject.collider.recalculateBounds();
|
||||
gameObject.collider.triggerCheck();
|
||||
}
|
||||
transform.scale.set(data.getFloat(index + 8), data.getFloat(index + 12));
|
||||
}
|
||||
|
||||
@Override
|
||||
public short getSize() {
|
||||
return 16;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,347 @@
|
||||
package com.ezardlabs.dethsquare.multiplayer;
|
||||
|
||||
import com.ezardlabs.dethsquare.multiplayer.Network.Protocol;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.Attributes;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
import org.xml.sax.XMLReader;
|
||||
import org.xml.sax.helpers.DefaultHandler;
|
||||
import org.xml.sax.helpers.XMLReaderFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
class UPnPManager {
|
||||
private static final String IP = "239.255.255.250";
|
||||
private static final int PORT = 1900;
|
||||
private static final String[] SEARCH_TYPES = {"urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1"};
|
||||
private static String location;
|
||||
private static String baseUrl;
|
||||
private static ArrayList<String[]> services = new ArrayList<>();
|
||||
|
||||
private static List<InetAddress> getLocalInetAddresses() {
|
||||
List<InetAddress> arrayIPAddress = new ArrayList<>();
|
||||
|
||||
// Get all network interfaces
|
||||
Enumeration<NetworkInterface> networkInterfaces;
|
||||
try {
|
||||
networkInterfaces = NetworkInterface.getNetworkInterfaces();
|
||||
} catch (SocketException e) {
|
||||
return arrayIPAddress;
|
||||
}
|
||||
|
||||
if (networkInterfaces == null) return arrayIPAddress;
|
||||
|
||||
// For every suitable network interface, get all IP addresses
|
||||
while (networkInterfaces.hasMoreElements()) {
|
||||
NetworkInterface card = networkInterfaces.nextElement();
|
||||
|
||||
try {
|
||||
// skip devices, not suitable to search gateways for
|
||||
if (card.isLoopback() || card.isPointToPoint() || card.isVirtual() || !card.isUp()) continue;
|
||||
} catch (SocketException e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Enumeration<InetAddress> addresses = card.getInetAddresses();
|
||||
|
||||
while (addresses.hasMoreElements()) {
|
||||
InetAddress inetAddress = addresses.nextElement();
|
||||
int index = arrayIPAddress.size();
|
||||
|
||||
if (!Inet4Address.class.isInstance(inetAddress)) continue;
|
||||
|
||||
arrayIPAddress.add(index, inetAddress);
|
||||
}
|
||||
}
|
||||
|
||||
return arrayIPAddress;
|
||||
}
|
||||
|
||||
private static class DiscoveryThread extends Thread {
|
||||
private final InetAddress address;
|
||||
|
||||
private DiscoveryThread(InetAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
DatagramSocket socket = new DatagramSocket(0, address);
|
||||
socket.setSoTimeout(3000);
|
||||
outer:
|
||||
for (String searchType : SEARCH_TYPES) {
|
||||
String message = "M-SEARCH * HTTP/1.1\r\nHOST: " + IP + ":" + PORT + "\r\nST: " + searchType +
|
||||
"\r\nMAN: \"ssdp:discover\"\r\nMX: 3\r\n\r\n";
|
||||
byte[] messageBytes = message.getBytes();
|
||||
DatagramPacket packet = new DatagramPacket(messageBytes, messageBytes.length,
|
||||
InetAddress.getByName(IP), PORT);
|
||||
socket.send(packet);
|
||||
|
||||
int count = -1;
|
||||
|
||||
boolean waitingPacket = true;
|
||||
while (waitingPacket) {
|
||||
count++;
|
||||
DatagramPacket receivePacket = new DatagramPacket(new byte[1536], 1536);
|
||||
try {
|
||||
socket.receive(receivePacket);
|
||||
byte[] receivedData = new byte[receivePacket.getLength()];
|
||||
System.arraycopy(receivePacket.getData(), 0, receivedData, 0, receivePacket.getLength());
|
||||
|
||||
String data = new String(receivedData);
|
||||
|
||||
StringTokenizer st = new StringTokenizer(data, "\n");
|
||||
|
||||
while (st.hasMoreTokens()) {
|
||||
String line = st.nextToken().trim();
|
||||
|
||||
if (line.isEmpty()) continue;
|
||||
|
||||
if (line.startsWith("HTTP/1.") || line.startsWith("NOTIFY *")) continue;
|
||||
|
||||
String key = line.substring(0, line.indexOf(':'));
|
||||
String value =
|
||||
line.length() > key.length() + 1 ? line.substring(key.length() + 1) : null;
|
||||
|
||||
key = key.trim();
|
||||
if (value != null) {
|
||||
value = value.trim();
|
||||
}
|
||||
|
||||
if (key.compareToIgnoreCase("location") == 0) {
|
||||
location = value;
|
||||
}
|
||||
}
|
||||
|
||||
URLConnection conn = new URL(location).openConnection();
|
||||
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
Document doc = builder.parse(conn.getInputStream());
|
||||
|
||||
Element root = doc.getDocumentElement();
|
||||
parseXML(root);
|
||||
|
||||
if (baseUrl == null) {
|
||||
URL url = new URL(location);
|
||||
baseUrl = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort();
|
||||
}
|
||||
} catch (SocketTimeoutException ste) {
|
||||
System.err.println("Timed out waiting for UPnP discovery response: " + count);
|
||||
waitingPacket = false;
|
||||
} catch (ParserConfigurationException | SAXException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (!services.isEmpty()) {
|
||||
break outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void discover() {
|
||||
List<InetAddress> localAddresses = getLocalInetAddresses();
|
||||
ArrayList<DiscoveryThread> discoveryThreads = new ArrayList<>(localAddresses.size());
|
||||
for (InetAddress address : localAddresses) {
|
||||
DiscoveryThread discoveryThread = new DiscoveryThread(address);
|
||||
discoveryThreads.add(discoveryThread);
|
||||
discoveryThread.start();
|
||||
}
|
||||
for (DiscoveryThread discoveryThread : discoveryThreads) {
|
||||
try {
|
||||
discoveryThread.join();
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void parseXML(Node element) {
|
||||
switch (element.getNodeName()) {
|
||||
case "root":
|
||||
NodeList children = element.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
Node child = children.item(i);
|
||||
if ("URLBase".equals(child.getNodeName())) {
|
||||
baseUrl = child.getTextContent();
|
||||
} else if ("device".equals(child.getNodeName())) {
|
||||
parseXML(child);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "deviceList":
|
||||
children = element.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if ("device".equals(children.item(i).getNodeName())) {
|
||||
parseXML(children.item(i));
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "device":
|
||||
children = element.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if ("serviceList".equals(children.item(i).getNodeName()) ||
|
||||
"deviceList".equals(children.item(i).getNodeName())) {
|
||||
parseXML(children.item(i));
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "serviceList":
|
||||
children = element.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if ("service".equals(children.item(i).getNodeName())) {
|
||||
parseXML(children.item(i));
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "service":
|
||||
children = element.getChildNodes();
|
||||
boolean breakOuterLoop = false;
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
Node child = children.item(i);
|
||||
if ("serviceType".equals(child.getNodeName()) &&
|
||||
Arrays.asList(SEARCH_TYPES).contains(child.getTextContent())) {
|
||||
for (int j = 0; j < children.getLength(); j++) {
|
||||
Node child2 = children.item(j);
|
||||
if ("controlURL".equals(child2.getNodeName())) {
|
||||
services.add(new String[]{child.getTextContent(), child2.getTextContent()});
|
||||
breakOuterLoop = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (breakOuterLoop) break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void sendSOAPMessage(String action, String service, String url, Map<String, String> args) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
|
||||
sb.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
|
||||
"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
|
||||
sb.append("<s:Body>");
|
||||
sb.append("<m:").append(action).append(" xmlns:m=\"").append(service).append("\">");
|
||||
for (String s : args.keySet()) {
|
||||
sb.append("<").append(s).append(">").append(args.get(s)).append("</").append(s).append(">");
|
||||
}
|
||||
sb.append("</m:").append(action).append(">");
|
||||
sb.append("</s:Body>");
|
||||
sb.append("</s:Envelope>");
|
||||
String message = sb.toString();
|
||||
|
||||
try {
|
||||
URL postUrl = new URL(url);
|
||||
HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
|
||||
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setReadTimeout(5000);
|
||||
conn.setDoOutput(true);
|
||||
conn.setRequestProperty("Content-Type", "text/xml");
|
||||
conn.setRequestProperty("SOAPAction", "\"" + service + "#" + action + "\"");
|
||||
conn.setRequestProperty("Connection", "Close");
|
||||
|
||||
byte[] messageBytes = message.getBytes();
|
||||
|
||||
conn.setRequestProperty("Content-Length", String.valueOf(messageBytes.length));
|
||||
|
||||
conn.getOutputStream().write(messageBytes);
|
||||
|
||||
Map<String, String> nameValue = new HashMap<>();
|
||||
XMLReader parser = XMLReaderFactory.createXMLReader();
|
||||
parser.setContentHandler(new DefaultHandler() {
|
||||
private String currentElement;
|
||||
|
||||
@Override
|
||||
public void startElement(String uri, String localName, String qName,
|
||||
Attributes attributes) throws SAXException {
|
||||
currentElement = localName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endElement(String uri, String localName, String qName) throws SAXException {
|
||||
currentElement = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void characters(char[] ch, int start, int length) throws SAXException {
|
||||
if (currentElement != null) {
|
||||
String value = new String(ch, start, length);
|
||||
String old = nameValue.put(currentElement, value);
|
||||
if (old != null) {
|
||||
nameValue.put(currentElement, old + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (conn.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
|
||||
try {
|
||||
parser.parse(new InputSource(conn.getErrorStream()));
|
||||
} catch (SAXException ignored) {
|
||||
}
|
||||
conn.disconnect();
|
||||
} else {
|
||||
parser.parse(new InputSource(conn.getInputStream()));
|
||||
conn.disconnect();
|
||||
}
|
||||
|
||||
conn.disconnect();
|
||||
} catch (IOException | SAXException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
static void addPortMapping(int port, Protocol protocol, String description) {
|
||||
HashMap<String, String> args = new HashMap<>();
|
||||
args.put("NewRemoteHost", "");
|
||||
args.put("NewExternalPort", String.valueOf(port));
|
||||
args.put("NewProtocol", protocol.toString());
|
||||
args.put("NewInternalPort", String.valueOf(port));
|
||||
try {
|
||||
args.put("NewInternalClient", InetAddress.getLocalHost().getHostAddress());
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
args.put("NewEnabled", "1");
|
||||
args.put("NewPortMappingDescription", description == null ? "" : description);
|
||||
args.put("NewLeaseDuration", "0");
|
||||
|
||||
for (String[] s : services) {
|
||||
sendSOAPMessage("AddPortMapping", s[0], baseUrl + s[1], args);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,7 @@
|
||||
package com.ezardlabs.dethsquare.prefabs;
|
||||
|
||||
import com.ezardlabs.dethsquare.GameObject;
|
||||
|
||||
public interface PrefabCreator {
|
||||
GameObject create();
|
||||
}
|
||||
@ -0,0 +1,85 @@
|
||||
package com.ezardlabs.dethsquare.prefabs;
|
||||
|
||||
import com.ezardlabs.dethsquare.GameObject;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class PrefabManager {
|
||||
private static HashMap<String, PrefabCreator> prefabs = new HashMap<>();
|
||||
|
||||
|
||||
/**
|
||||
* Register a prefabricated {@link GameObject}
|
||||
*
|
||||
* @param name The name to identify the prefab with
|
||||
* @param prefab The {@link PrefabCreator} used to create the GameObject
|
||||
*/
|
||||
public static void addPrefab(String name, PrefabCreator prefab) {
|
||||
if (name.endsWith("_other")) {
|
||||
throw new IllegalArgumentException("Prefab name cannot end with \"_other\"");
|
||||
} else {
|
||||
prefabs.put(name, prefab);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a prefabricated {@link GameObject} that can be instantiated across clients
|
||||
*
|
||||
* @param name The name to identify the prefab with
|
||||
* @param prefab The {@link PrefabCreator} used to create the GameObject
|
||||
* @param otherPrefab An alternate {@link PrefabCreator} to be used for instantiation on
|
||||
* every client except the caller - for example, you could have a
|
||||
* prefab for a player object that has a script that accepts input on
|
||||
* one client, but not on other clients. Can be null, in which case the
|
||||
* same {@link PrefabCreator} will be used on all clients
|
||||
*/
|
||||
public static void addPrefab(String name, PrefabCreator prefab, PrefabCreator otherPrefab) {
|
||||
if (name.endsWith("_other")) {
|
||||
throw new IllegalArgumentException("Prefab name cannot end with '_other'");
|
||||
} else {
|
||||
prefabs.put(name, prefab);
|
||||
prefabs.put(name + "_other", otherPrefab);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether or not a prefab exists
|
||||
*
|
||||
* @param name The name of the prefab
|
||||
* @return Whether or not a prefab with the given name exists
|
||||
*/
|
||||
public static boolean prefabExists(String name) {
|
||||
return prefabs.containsKey(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the prefab with the given name
|
||||
*
|
||||
* @param name The name of the prefab to load
|
||||
* @return The {@link GameObject} prefab with the given name
|
||||
*/
|
||||
public static GameObject loadPrefab(String name) {
|
||||
PrefabCreator prefab = prefabs.get(name);
|
||||
if (prefab == null) {
|
||||
throw new PrefabNotFoundException("Prefab '" + name + "' not found");
|
||||
} else {
|
||||
return prefab.create();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters the prefab with the given name
|
||||
*
|
||||
* @param name The name of the prefab to unregister
|
||||
*/
|
||||
public static void removePrefab(String name) {
|
||||
prefabs.remove(name);
|
||||
}
|
||||
|
||||
private static class PrefabNotFoundException extends RuntimeException {
|
||||
|
||||
private PrefabNotFoundException(String prefabName) {
|
||||
super("Prefab '" + prefabName + "' not found");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
package com.ezardlabs.dethsquare.tmx;
|
||||
|
||||
/**
|
||||
* Created by Benjamin on 2016-04-09.
|
||||
*/
|
||||
public class Layer {
|
||||
private String name;
|
||||
private int width;
|
||||
private int height;
|
||||
|
||||
private Tile[] tiles;
|
||||
|
||||
public Layer(String name, int width, int height, Tile[] tiles) {
|
||||
this.name = name;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.tiles = tiles;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return this.width;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return this.height;
|
||||
}
|
||||
|
||||
public Tile[] getTiles() {
|
||||
return this.tiles;
|
||||
}
|
||||
|
||||
public Tile getTile(int idx) {
|
||||
return this.tiles[idx];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,75 @@
|
||||
package com.ezardlabs.dethsquare.tmx;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* Created by Benjamin on 2016-04-09.
|
||||
*/
|
||||
public class Map {
|
||||
private String filePath;
|
||||
|
||||
private int width;
|
||||
private int height;
|
||||
private int tileWidth;
|
||||
private int tileHeight;
|
||||
|
||||
private ArrayList<TileSet> tileSets;
|
||||
|
||||
private ArrayList<Layer> tileLayers;
|
||||
private ArrayList<ObjectGroup> objectGroups;
|
||||
|
||||
public Map(String filePath, int width, int height, int tileWidth, int tileHeight) {
|
||||
this.filePath = filePath;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.tileWidth = tileWidth;
|
||||
this.tileHeight = tileHeight;
|
||||
this.tileSets = new ArrayList<>();
|
||||
this.tileLayers = new ArrayList<>();
|
||||
this.objectGroups = new ArrayList<>();
|
||||
}
|
||||
|
||||
public String getFilePath() {
|
||||
return this.filePath;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return this.width;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return this.height;
|
||||
}
|
||||
|
||||
public int getTileWidth() {
|
||||
return this.tileWidth;
|
||||
}
|
||||
|
||||
public int getTileHeight() {
|
||||
return this.tileHeight;
|
||||
}
|
||||
|
||||
public ArrayList<TileSet> getTileSets() {
|
||||
return this.tileSets;
|
||||
}
|
||||
|
||||
public ArrayList<Layer> getTileLayers() {
|
||||
return this.tileLayers;
|
||||
}
|
||||
|
||||
public ArrayList<ObjectGroup> getObjectGroups() {
|
||||
return this.objectGroups;
|
||||
}
|
||||
|
||||
public void addTileSet(TileSet tileSet) {
|
||||
this.tileSets.add(tileSet);
|
||||
}
|
||||
|
||||
public void addTileLayer(Layer layer) {
|
||||
this.tileLayers.add(layer);
|
||||
}
|
||||
|
||||
public void addObjectGroup(ObjectGroup objectGroup) {
|
||||
this.objectGroups.add(objectGroup);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
package com.ezardlabs.dethsquare.tmx;
|
||||
|
||||
/**
|
||||
* Created by Benjamin on 2016-04-26.
|
||||
*/
|
||||
public class ObjectGroup {
|
||||
private String name;
|
||||
private TMXObject[] objects;
|
||||
|
||||
public ObjectGroup(String name, TMXObject[] objects) {
|
||||
this.name = name;
|
||||
this.objects = objects;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public TMXObject[] getObjects() {
|
||||
return objects;
|
||||
}
|
||||
|
||||
public void setObjects(TMXObject[] objects) {
|
||||
this.objects = objects;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,278 @@
|
||||
package com.ezardlabs.dethsquare.tmx;
|
||||
|
||||
import com.ezardlabs.dethsquare.util.Dethsquare;
|
||||
import com.ezardlabs.dethsquare.util.GameLog;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
/**
|
||||
* Created by Benjamin on 2016-04-16.
|
||||
*/
|
||||
public class TMXLoader {
|
||||
private String fileName;
|
||||
private Map map;
|
||||
|
||||
public TMXLoader(String fileName, boolean external) {
|
||||
this.fileName = fileName;
|
||||
this.map = null;
|
||||
loadMap(this.fileName, external);
|
||||
}
|
||||
|
||||
public Map getMap() {
|
||||
return this.map;
|
||||
}
|
||||
|
||||
public void loadMap(String filePath) {
|
||||
loadMap(filePath, false);
|
||||
}
|
||||
|
||||
public void loadMap(String filePath, boolean external) {
|
||||
try {
|
||||
int lastSlash = filePath.lastIndexOf("/");
|
||||
String folder = "";
|
||||
String file = filePath;
|
||||
if (lastSlash >= 0) {
|
||||
folder = filePath.substring(0, lastSlash);
|
||||
file = filePath.substring(lastSlash + 1, filePath.length());
|
||||
}
|
||||
|
||||
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
|
||||
Document doc;
|
||||
if (external) {
|
||||
doc = dBuilder.parse(new FileInputStream(new File(filePath)));
|
||||
} else {
|
||||
/*
|
||||
* Ressources via l'abstraction IO (Dethsquare.IO) plutôt que le
|
||||
* classloader : sur Android les assets ne sont PAS sur le
|
||||
* classpath, le getResourceAsStream renvoyait null et la map
|
||||
* restait null (crash MapManager.loadTMX).
|
||||
*/
|
||||
InputStream in = Dethsquare.IO.getInputStream(filePath);
|
||||
if (in == null) {
|
||||
throw new Exception("Map not found: " + filePath);
|
||||
}
|
||||
doc = dBuilder.parse(in);
|
||||
}
|
||||
doc.getDocumentElement().normalize();
|
||||
Element root = doc.getDocumentElement();
|
||||
if (!root.getNodeName().equals("map")) {
|
||||
throw new Exception("Invalid map file.");
|
||||
}
|
||||
NamedNodeMap rootAttrs = root.getAttributes();
|
||||
|
||||
// Load map properties
|
||||
// String version = rootAttrs.getNamedItem("version").getNodeValue();
|
||||
// String orientation = rootAttrs.getNamedItem("orientation").getNodeValue();
|
||||
// String renderOrder = rootAttrs.getNamedItem("renderorder").getNodeValue();
|
||||
|
||||
int mapWidth = Integer.parseInt(rootAttrs.getNamedItem("width").getNodeValue());
|
||||
int mapHeight = Integer.parseInt(rootAttrs.getNamedItem("height").getNodeValue());
|
||||
int mapTileWidth = Integer.parseInt(rootAttrs.getNamedItem("tilewidth").getNodeValue());
|
||||
int mapTileHeight = Integer.parseInt(rootAttrs.getNamedItem("tileheight").getNodeValue());
|
||||
this.map = new Map(filePath, mapWidth, mapHeight, mapTileWidth, mapTileHeight);
|
||||
GameLog.i("LS-MAP", "TMX '" + filePath + "': " + mapWidth + "x" + mapHeight
|
||||
+ " tiles of " + mapTileWidth + "x" + mapTileHeight
|
||||
+ ", " + root.getElementsByTagName("tileset").getLength() + " tileset(s), "
|
||||
+ root.getElementsByTagName("objectgroup").getLength() + " objectgroup(s)");
|
||||
|
||||
// Load tileSets
|
||||
NodeList tileSetNodes = root.getElementsByTagName("tileset");
|
||||
for (int i = 0; i < tileSetNodes.getLength(); i++) {
|
||||
Node node = tileSetNodes.item(i);
|
||||
NamedNodeMap nodeAttrs = node.getAttributes();
|
||||
int firstGid = Integer.parseInt(nodeAttrs.getNamedItem("firstgid").getNodeValue());
|
||||
Node source = nodeAttrs.getNamedItem("source");
|
||||
TileSet tileSet = null;
|
||||
if (source == null) {
|
||||
tileSet = loadTMXTileSet(null, node, firstGid);
|
||||
} else {
|
||||
tileSet = loadTMXTileSet(folder + "/" + source.getNodeValue(), firstGid);
|
||||
}
|
||||
if (tileSet != null) {
|
||||
this.map.addTileSet(tileSet);
|
||||
}
|
||||
}
|
||||
|
||||
// Load tile layers
|
||||
NodeList tileLayers = root.getElementsByTagName("layer");
|
||||
for (int i = 0; i < tileLayers.getLength(); i++) {
|
||||
Node node = tileLayers.item(i);
|
||||
NamedNodeMap nodeAttrs = node.getAttributes();
|
||||
Node nodeIsVisible = nodeAttrs.getNamedItem("visible");
|
||||
boolean isVisible = nodeIsVisible == null ? true : Boolean.getBoolean(nodeIsVisible.getNodeValue());
|
||||
if (!isVisible) {
|
||||
continue;
|
||||
}
|
||||
String layerName = nodeAttrs.getNamedItem("name").getNodeValue();
|
||||
int layerWidth = Integer.parseInt(nodeAttrs.getNamedItem("width").getNodeValue());
|
||||
int layerHeight = Integer.parseInt(nodeAttrs.getNamedItem("height").getNodeValue());
|
||||
NodeList childNodes = node.getChildNodes();
|
||||
Tile[] tiles = null;
|
||||
for (int j = 0; j < childNodes.getLength(); j++) {
|
||||
if (childNodes.item(j).getNodeName().equals("data")) {
|
||||
tiles = loadTMXTiles(childNodes.item(j), layerWidth, layerHeight);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (tiles == null) {
|
||||
throw new Exception("Cannot load tiles for layer: " + layerName);
|
||||
}
|
||||
this.map.addTileLayer(new Layer(layerName, layerWidth, layerHeight, tiles));
|
||||
}
|
||||
|
||||
// Load object layers
|
||||
NodeList nodeListObjectGroups = doc.getElementsByTagName("objectgroup");
|
||||
for (int i = 0; i < nodeListObjectGroups.getLength(); i++) {
|
||||
Node nodeObjectGroup = nodeListObjectGroups.item(i);
|
||||
NamedNodeMap objectGroupAttrs = nodeObjectGroup.getAttributes();
|
||||
Node nodeObjectGroupName = objectGroupAttrs.getNamedItem("name");
|
||||
String objectGroupName = "";
|
||||
if (nodeObjectGroupName != null) {
|
||||
objectGroupName = nodeObjectGroupName.getNodeValue();
|
||||
}
|
||||
ArrayList<TMXObject> tmxObjects = new ArrayList<>();
|
||||
NodeList nodeObjects = nodeObjectGroup.getChildNodes();
|
||||
for (int j = 0; j < nodeObjects.getLength(); j++) {
|
||||
Node node = nodeObjects.item(j);
|
||||
if (!node.getNodeName().equals("object")) {
|
||||
continue;
|
||||
}
|
||||
NamedNodeMap attrs = node.getAttributes();
|
||||
Node nodeId = attrs.getNamedItem("id");
|
||||
int id = 0;
|
||||
if (nodeId != null) {
|
||||
id = Integer.parseUnsignedInt(nodeId.getNodeValue());
|
||||
}
|
||||
Node nodeName = attrs.getNamedItem("name");
|
||||
String name = "";
|
||||
if (nodeName != null) {
|
||||
name = nodeName.getNodeValue();
|
||||
}
|
||||
Node nodeType = attrs.getNamedItem("type");
|
||||
String type = "";
|
||||
if (nodeType != null) {
|
||||
type = nodeType.getNodeValue();
|
||||
}
|
||||
int x = Integer.parseInt(attrs.getNamedItem("x").getNodeValue());
|
||||
int y = Integer.parseInt(attrs.getNamedItem("y").getNodeValue());
|
||||
int width = Integer.parseInt(attrs.getNamedItem("width").getNodeValue());
|
||||
int height = Integer.parseInt(attrs.getNamedItem("height").getNodeValue());
|
||||
Properties props = new Properties();
|
||||
if (node instanceof Element) {
|
||||
NodeList nlProperties = ((Element) node).getElementsByTagName("properties");
|
||||
if (nlProperties != null && nlProperties.getLength() > 0) {
|
||||
Node nodeProperties = nlProperties.item(0);
|
||||
NodeList nlPropItems = nodeProperties.getChildNodes();
|
||||
for (int k = 0; k < nlPropItems.getLength(); k++) {
|
||||
Node p = nlPropItems.item(k);
|
||||
if (p.getNodeName().equals("property")) {
|
||||
NamedNodeMap pAttrs = p.getAttributes();
|
||||
Node nodePropName = pAttrs.getNamedItem("name");
|
||||
Node nodePropValue = pAttrs.getNamedItem("value");
|
||||
if (nodePropName != null && nodePropValue != null) {
|
||||
props.setProperty(nodePropName.getNodeValue(), nodePropValue.getNodeValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tmxObjects.add(new TMXObject(id, name, type, x, y, width, height, props));
|
||||
}
|
||||
map.addObjectGroup(
|
||||
new ObjectGroup(objectGroupName, tmxObjects.toArray(new TMXObject[tmxObjects.size()])));
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public TileSet loadTMXTileSet(String filePath, int firstGid) {
|
||||
TileSet tileSet = null;
|
||||
try {
|
||||
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
|
||||
// Ressources via l'abstraction IO (cf. loadMap : assets Android).
|
||||
InputStream in = Dethsquare.IO
|
||||
.getInputStream(new URI(filePath).normalize().getPath());
|
||||
if (in == null) {
|
||||
throw new Exception("Tileset not found: " + filePath);
|
||||
}
|
||||
Document doc = dBuilder.parse(in);
|
||||
doc.getDocumentElement().normalize();
|
||||
Element root = doc.getDocumentElement();
|
||||
tileSet = loadTMXTileSet(filePath, root, firstGid);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return tileSet;
|
||||
}
|
||||
|
||||
public TileSet loadTMXTileSet(String filePath, Node root, int firstGid) {
|
||||
if (filePath == null) filePath = "";
|
||||
NamedNodeMap rootAttrs = root.getAttributes();
|
||||
String name = rootAttrs.getNamedItem("name").getNodeValue();
|
||||
int tileWidth = Integer.parseInt(rootAttrs.getNamedItem("tilewidth").getNodeValue());
|
||||
int tileHeight = Integer.parseInt(rootAttrs.getNamedItem("tileheight").getNodeValue());
|
||||
int tileCount = Integer.parseInt(rootAttrs.getNamedItem("tilecount").getNodeValue());
|
||||
String imageSource = "";
|
||||
int imageWidth = 0;
|
||||
int imageHeight = 0;
|
||||
Tile[] tiles = new Tile[tileCount];
|
||||
NodeList rootChildren = root.getChildNodes();
|
||||
for (int i = 0; i < rootChildren.getLength(); i++) {
|
||||
if (rootChildren.item(i).getNodeName().equals("image")) {
|
||||
NamedNodeMap childAttrs = rootChildren.item(i).getAttributes();
|
||||
imageSource = childAttrs.getNamedItem("source").getNodeValue();
|
||||
imageWidth = Integer.parseInt(childAttrs.getNamedItem("width").getNodeValue());
|
||||
imageHeight = Integer.parseInt(childAttrs.getNamedItem("height").getNodeValue());
|
||||
} else if (rootChildren.item(i).getNodeName().equals("tile")) {
|
||||
NamedNodeMap childAttrs = rootChildren.item(i).getAttributes();
|
||||
Node nodeGid = childAttrs.getNamedItem("gid");
|
||||
if (nodeGid == null) {
|
||||
nodeGid = childAttrs.getNamedItem("id");
|
||||
}
|
||||
int gid = Integer.parseInt(nodeGid.getNodeValue());
|
||||
tiles[gid] = new Tile(gid);
|
||||
}
|
||||
}
|
||||
TileSet tileSet = new TileSet(filePath, name, firstGid, tileWidth, tileHeight, tileCount);
|
||||
tileSet.setImage(imageSource, imageWidth, imageHeight);
|
||||
return tileSet;
|
||||
}
|
||||
|
||||
public Tile[] loadTMXTiles(Node data, int layerWidth, int layerHeight) {
|
||||
NodeList childNodes = data.getChildNodes();
|
||||
// Tile[] mapTiles = new Tile[layerWidth * layerHeight];
|
||||
ArrayList<Tile> arrTiles = new ArrayList<>();
|
||||
for (int i = 0; i < childNodes.getLength(); i++) {
|
||||
String nodeName = childNodes.item(i).getNodeName();
|
||||
if (childNodes.item(i).getNodeName().equals("tile")) {
|
||||
Node node = childNodes.item(i);
|
||||
NamedNodeMap attrs = node.getAttributes();
|
||||
Node gid = childNodes.item(i).getAttributes().getNamedItem("gid");
|
||||
if (gid == null) {
|
||||
gid = childNodes.item(i).getAttributes().getNamedItem("id");
|
||||
}
|
||||
// mapTiles[i / 2] = new Tile(Integer.parseInt(gid.getNodeValue()));
|
||||
arrTiles.add(new Tile(gid == null ? 0 : Integer.parseUnsignedInt(gid.getNodeValue())));
|
||||
}
|
||||
}
|
||||
return arrTiles.toArray(new Tile[layerWidth * layerHeight]);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,96 @@
|
||||
package com.ezardlabs.dethsquare.tmx;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Created by Benjamin on 2016-04-26.
|
||||
*/
|
||||
public class TMXObject {
|
||||
private int id;
|
||||
private String name;
|
||||
private String type;
|
||||
private int x;
|
||||
private int y;
|
||||
private int width;
|
||||
private int height;
|
||||
private Properties properties;
|
||||
|
||||
public TMXObject(int id, String name, String type, int x, int y, int width, int height, Properties properties) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.type = type;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public void setX(int x) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public void setY(int y) {
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public String getProperty(String key) {
|
||||
return this.properties.getProperty(key);
|
||||
}
|
||||
|
||||
public String getProperty(String key, String defaultValue) {
|
||||
return this.properties.getProperty(key, defaultValue);
|
||||
}
|
||||
|
||||
public void setProperty(String key, String value) {
|
||||
this.properties.setProperty(key, value);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
package com.ezardlabs.dethsquare.tmx;
|
||||
|
||||
/**
|
||||
* Created by Benjamin on 2016-04-09.
|
||||
*/
|
||||
public class Tile {// Bits on the far end of the 32-bit global tile ID are used for tile flags
|
||||
private static final int FLIPPED_HORIZONTALLY_FLAG = 0x80000000;
|
||||
private static final int FLIPPED_VERTICALLY_FLAG = 0x40000000;
|
||||
private static final int FLIPPED_DIAGONALLY_FLAG = 0x20000000;
|
||||
|
||||
private long gid;
|
||||
private boolean flipH;
|
||||
private boolean flipV;
|
||||
private boolean flipD;
|
||||
|
||||
public Tile(int gid) {
|
||||
this.flipH = (gid & FLIPPED_HORIZONTALLY_FLAG) != 0;
|
||||
this.flipV = (gid & FLIPPED_VERTICALLY_FLAG) != 0;
|
||||
this.flipD = (gid & FLIPPED_DIAGONALLY_FLAG) != 0;
|
||||
this.gid = gid & (~(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG | FLIPPED_DIAGONALLY_FLAG));
|
||||
}
|
||||
|
||||
public long getGid() {
|
||||
return this.gid;
|
||||
}
|
||||
|
||||
public boolean isFlippedHorizontal() {
|
||||
return this.flipH;
|
||||
}
|
||||
|
||||
public boolean isFlippedVertical() {
|
||||
return this.flipV;
|
||||
}
|
||||
|
||||
public boolean isFlippedDiagonal() {
|
||||
return this.flipD;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,84 @@
|
||||
package com.ezardlabs.dethsquare.tmx;
|
||||
|
||||
/**
|
||||
* Created by Benjamin on 2016-04-09.
|
||||
*/
|
||||
public class TileSet {
|
||||
private String filePath;
|
||||
private String name;
|
||||
private int firstGid;
|
||||
private int tileWidth;
|
||||
private int tileHeight;
|
||||
private int tileCount;
|
||||
private String imageSource;
|
||||
private int imageWidth;
|
||||
private int imageHeight;
|
||||
|
||||
private Tile[] tiles;
|
||||
|
||||
public TileSet(String filePath, String name, int firstGid, int tileWidth, int tileHeight, int tileCount) {
|
||||
this.filePath = filePath;
|
||||
this.name = name;
|
||||
this.firstGid = firstGid;
|
||||
this.tileWidth = tileWidth;
|
||||
this.tileHeight = tileHeight;
|
||||
this.tileCount = tileCount;
|
||||
this.imageSource = "";
|
||||
this.imageWidth = 0;
|
||||
this.imageHeight = 0;
|
||||
}
|
||||
|
||||
public void setImage(String imageSource, int width, int height) {
|
||||
this.imageSource = imageSource;
|
||||
this.imageWidth = width;
|
||||
this.imageHeight = height;
|
||||
}
|
||||
|
||||
public String getFilePath() {
|
||||
return this.filePath;
|
||||
}
|
||||
|
||||
public void setFilePath(String filePath) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getFirstGid() {
|
||||
return firstGid;
|
||||
}
|
||||
|
||||
public int getTileWidth() {
|
||||
return tileWidth;
|
||||
}
|
||||
|
||||
public int getTileHeight() {
|
||||
return tileHeight;
|
||||
}
|
||||
|
||||
public int getTileCount() {
|
||||
return tileCount;
|
||||
}
|
||||
|
||||
public String getImageSource() {
|
||||
return imageSource;
|
||||
}
|
||||
|
||||
public int getImageWidth() {
|
||||
return imageWidth;
|
||||
}
|
||||
|
||||
public int getImageHeight() {
|
||||
return imageHeight;
|
||||
}
|
||||
|
||||
public Tile[] getTiles() {
|
||||
return tiles;
|
||||
}
|
||||
}
|
||||
12
dethsquare/core/src/main/resources/shaders/texture/frag.glsl
Normal file
12
dethsquare/core/src/main/resources/shaders/texture/frag.glsl
Normal file
@ -0,0 +1,12 @@
|
||||
#version 330 core
|
||||
|
||||
uniform sampler2D texUnit;
|
||||
in vec2 vTexCoords;
|
||||
in vec4 vColour;
|
||||
|
||||
out vec4 g_FragColor;
|
||||
|
||||
void main() {
|
||||
vec4 tex = texture(texUnit, vTexCoords);
|
||||
g_FragColor = vec4(tex.r * vColour.r, tex.g * vColour.g, tex.b * vColour.b, tex.a * vColour.a);
|
||||
}
|
||||
15
dethsquare/core/src/main/resources/shaders/texture/vert.glsl
Normal file
15
dethsquare/core/src/main/resources/shaders/texture/vert.glsl
Normal file
@ -0,0 +1,15 @@
|
||||
#version 330 core
|
||||
|
||||
uniform mat4 transform;
|
||||
in vec2 position;
|
||||
in vec2 texCoords;
|
||||
in vec4 colour;
|
||||
|
||||
out vec2 vTexCoords;
|
||||
out vec4 vColour;
|
||||
|
||||
void main() {
|
||||
vTexCoords = texCoords;
|
||||
vColour = colour;
|
||||
gl_Position = transform * vec4(position, 0.0, 1.0);
|
||||
}
|
||||
29
dethsquare/desktop/.gitignore
vendored
Normal file
29
dethsquare/desktop/.gitignore
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### Java template
|
||||
*.class
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
### Gradle template
|
||||
.gradle
|
||||
build/
|
||||
|
||||
# Ignore Gradle GUI config
|
||||
gradle-app.setting
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
|
||||
# Cache of project
|
||||
.gradletasknamecache
|
||||
|
||||
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
|
||||
# gradle/wrapper/gradle-wrapper.properties
|
||||
73
dethsquare/desktop/build.gradle
Normal file
73
dethsquare/desktop/build.gradle
Normal file
@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Module `desktop` du moteur Dethsquare : back-end LWJGL 3 pour macOS/Linux/
|
||||
* Windows. Implémente les abstractions de `base` (DesktopLauncher/GLFW pour la
|
||||
* fenêtre et les entrées, DesktopRenderUtils/OpenGL pour le rendu batché,
|
||||
* DesktopAudioUtils/OpenAL pour le son, DesktopIOUtils pour les fichiers,
|
||||
* DesktopPrefUtils pour les préférences).
|
||||
*
|
||||
* Migration LWJGL 3.1.2 -> 3.3.x (modernisation 2026) :
|
||||
* - la 3.1.2 (2016) ne tourne plus proprement sur les JVM récentes (module
|
||||
* system, Unsafe) ; la 3.3.x est officiellement compatible Java 9+ et
|
||||
* fournit des natives macOS ARM (Apple Silicon) qui n'existaient pas ;
|
||||
* - l'API utilisée par le moteur (GL11/GL20/GL30, GLFW, AL10/ALC10, STB,
|
||||
* BufferUtils, MemoryStack) est inchangée entre ces deux versions, donc
|
||||
* aucune modification du code Java n'a été nécessaire.
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id 'java-library'
|
||||
}
|
||||
|
||||
def lwjglVersion = '3.3.6'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.release = 8
|
||||
}
|
||||
|
||||
/*
|
||||
* Sélection des natives LWJGL en fonction de l'OS/l'architecture de la machine
|
||||
* qui construit le projet. Les natives sont en `runtimeOnly` : les jars de
|
||||
* natives ne contiennent que des .so/.dylib/.dll, jamais du bytecode.
|
||||
*/
|
||||
def lwjglNatives = {
|
||||
def os = org.gradle.internal.os.OperatingSystem.current()
|
||||
def arch = System.getProperty('os.arch')
|
||||
if (os.isMacOsX()) {
|
||||
return arch.contains('aarch64') ? 'natives-macos-arm64' : 'natives-macos'
|
||||
}
|
||||
if (os.isWindows()) {
|
||||
return arch.contains('aarch64') ? 'natives-windows-arm64' : 'natives-windows'
|
||||
}
|
||||
if (arch.contains('aarch64')) return 'natives-linux-arm64'
|
||||
if (arch.contains('arm')) return 'natives-linux-arm32'
|
||||
return 'natives-linux'
|
||||
}.call()
|
||||
|
||||
dependencies {
|
||||
// `base` : interfaces plateforme-abstraites implémentées par ce module.
|
||||
api project(':base')
|
||||
|
||||
// BOM LWJGL : pilote les versions des artefacts listés ensuite (pas besoin
|
||||
// de répéter lwjglVersion sur chaque ligne).
|
||||
api platform("org.lwjgl:lwjgl-bom:$lwjglVersion")
|
||||
|
||||
// Modules LWJGL utilisés par le moteur :
|
||||
// - lwjgl : cœur (MemoryUtil, MemoryStack, BufferUtils)
|
||||
// - lwjgl-glfw : fenêtre + clavier/souris (DesktopLauncher)
|
||||
// - lwjgl-opengl : rendu (DesktopRenderUtils)
|
||||
// - lwjgl-openal : audio spatialisé (DesktopAudioUtils)
|
||||
// - lwjgl-stb : décodage images (STBImage) et ogg (STBVorbis)
|
||||
['', '-glfw', '-opengl', '-openal', '-stb'].each { module ->
|
||||
api "org.lwjgl:lwjgl$module"
|
||||
runtimeOnly "org.lwjgl:lwjgl$module::${lwjglNatives}"
|
||||
}
|
||||
|
||||
// commons-io : copie de flux dans DesktopAudioUtils/DesktopIOUtils.
|
||||
implementation 'commons-io:commons-io:2.16.1'
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
package com.ezardlabs.dethsquare.debug;
|
||||
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
class DebugCircle extends DebugCircleBase {
|
||||
|
||||
DebugCircle(float x, float y, float radius, float red, float green, float blue) {
|
||||
super(x, y, radius, red, green, blue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(float cameraX, float cameraY, float scale) {
|
||||
GL11.glDisable(GL11.GL_TEXTURE_2D);
|
||||
GL11.glLineWidth(3);
|
||||
GL11.glBegin(GL11.GL_LINE_LOOP);
|
||||
GL11.glColor3f(red, green, blue);
|
||||
for (int i = 0; i < 20; i++) {
|
||||
float theta = 2f * 3.1415926f * (float) i / 20f;
|
||||
float x = (float) (radius * Math.cos(theta) * scale);
|
||||
float y = (float) (radius * Math.sin(theta) * scale);
|
||||
GL11.glVertex3f(this.x + x - cameraX, this.y + y - cameraY, 9999999);
|
||||
}
|
||||
GL11.glEnd();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
package com.ezardlabs.dethsquare.debug;
|
||||
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
public class DebugRect extends DebugRectBase {
|
||||
|
||||
DebugRect(float x, float y, float width, float height, float red, float green, float blue) {
|
||||
super(x, y, width, height, red, green, blue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void draw(float cameraX, float cameraY, float scale) {
|
||||
GL11.glLineWidth(3);
|
||||
GL11.glBegin(GL11.GL_LINE_LOOP);
|
||||
GL11.glColor3f(red, green, blue);
|
||||
GL11.glVertex3f((x - cameraX) * scale, (y - cameraY) * scale, 9999999);
|
||||
GL11.glVertex3f((x + width - cameraX) * scale, (y - cameraY) * scale, 9999999);
|
||||
GL11.glVertex3f((x + width - cameraX) * scale, (y + height - cameraY) * scale, 9999999);
|
||||
GL11.glVertex3f((x - cameraX) * scale, (y + height - cameraY) * scale, 9999999);
|
||||
GL11.glEnd();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user