commit 7af74680e935bf6c356196eb65460467fa56a675 Author: Siphonight Date: Sun Nov 15 13:53:07 2026 +0100 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) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c0aa0c0 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..14282e5 --- /dev/null +++ b/README.md @@ -0,0 +1,150 @@ +# Lost Sector — Portage moderne (desktop 2026 + Android) + +[![Build](https://img.shields.io/badge/build-Gradle%209.9.1-green)](#) [![Android](https://img.shields.io/badge/Android-API%2024%2B-brightgreen)](#) [![JDK](https://img.shields.io/badge/JDK-21-orange)](#) + +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. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..eb4f617 --- /dev/null +++ b/TODO.md @@ -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: ` 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 diff --git a/android-app/build.gradle b/android-app/build.gradle new file mode 100644 index 0000000..d54438a --- /dev/null +++ b/android-app/build.gradle @@ -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' + } +} diff --git a/android-app/src/main/AndroidManifest.xml b/android-app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2034afb --- /dev/null +++ b/android-app/src/main/AndroidManifest.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/android-app/src/main/java/com/ezardlabs/lostsector/AndroidGameActivity.java b/android-app/src/main/java/com/ezardlabs/lostsector/AndroidGameActivity.java new file mode 100644 index 0000000..b5abf7a --- /dev/null +++ b/android-app/src/main/java/com/ezardlabs/lostsector/AndroidGameActivity.java @@ -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(); + } +} diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..89fa700 --- /dev/null +++ b/build.gradle @@ -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') +} diff --git a/dethsquare/.gitignore b/dethsquare/.gitignore new file mode 100644 index 0000000..3933271 --- /dev/null +++ b/dethsquare/.gitignore @@ -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 diff --git a/dethsquare/README.md b/dethsquare/README.md new file mode 100644 index 0000000..2a2d692 --- /dev/null +++ b/dethsquare/README.md @@ -0,0 +1 @@ +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/59e1c9e9b1b04406a4bcdf81515488fc)](https://www.codacy.com/app/8-Bit-Warframe/Dethsquare-Engine) \ No newline at end of file diff --git a/dethsquare/android/.gitignore b/dethsquare/android/.gitignore new file mode 100644 index 0000000..76b1f64 --- /dev/null +++ b/dethsquare/android/.gitignore @@ -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 diff --git a/dethsquare/android/build.gradle b/dethsquare/android/build.gradle new file mode 100644 index 0000000..e69de29 diff --git a/dethsquare/android/libs/android-4.4.jar b/dethsquare/android/libs/android-4.4.jar new file mode 100644 index 0000000..b9d655e Binary files /dev/null and b/dethsquare/android/libs/android-4.4.jar differ diff --git a/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidAudioUtils.java b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidAudioUtils.java new file mode 100644 index 0000000..8c5c903 --- /dev/null +++ b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidAudioUtils.java @@ -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 sources = new HashMap<>(); // id -> SoundPool soundId + private final HashMap loopingPlayers = new HashMap<>(); // id -> MediaPlayer + private final HashMap loadedPaths = new HashMap<>(); // path -> SoundPool soundId + private final HashMap looping = new HashMap<>(); + private final HashMap pendingLoops = new HashMap<>(); + private final HashMap positions = new HashMap<>(); // id -> {x, y} + private final HashMap activeStreams = new HashMap<>(); // id -> SoundPool streamId + private final HashMap 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 paths = new HashMap<>(); + + private String pathOf(int id) { + return paths.get(id); + } +} diff --git a/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidIOUtils.java b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidIOUtils.java new file mode 100644 index 0000000..3e49a1e --- /dev/null +++ b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidIOUtils.java @@ -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 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 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)); + } +} diff --git a/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidLauncher.java b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidLauncher.java new file mode 100644 index 0000000..d57a80b --- /dev/null +++ b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidLauncher.java @@ -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; + } + } +} diff --git a/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidPrefUtils.java b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidPrefUtils.java new file mode 100644 index 0000000..ec9c920 --- /dev/null +++ b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidPrefUtils.java @@ -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); + } +} diff --git a/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidRenderUtils.java b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidRenderUtils.java new file mode 100644 index 0000000..751e3e4 --- /dev/null +++ b/dethsquare/android/src/main/java/com/ezardlabs/dethsquare/util/AndroidRenderUtils.java @@ -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 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 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]; + } +} diff --git a/dethsquare/base/build.gradle b/dethsquare/base/build.gradle new file mode 100644 index 0000000..a85ad22 --- /dev/null +++ b/dethsquare/base/build.gradle @@ -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 +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugCircleBase.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugCircleBase.java new file mode 100644 index 0000000..0006599 --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugCircleBase.java @@ -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; + } +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugGraphic.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugGraphic.java new file mode 100644 index 0000000..b1eaeff --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugGraphic.java @@ -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); +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugRectBase.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugRectBase.java new file mode 100644 index 0000000..09c55df --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/debug/DebugRectBase.java @@ -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; + } +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/AudioUtils.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/AudioUtils.java new file mode 100644 index 0000000..8950cee --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/AudioUtils.java @@ -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(); +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/BaseGame.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/BaseGame.java new file mode 100644 index 0000000..7b6e5be --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/BaseGame.java @@ -0,0 +1,6 @@ +package com.ezardlabs.dethsquare.util; + +public abstract class BaseGame implements GameListeners { + + public abstract void create(); +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Dethsquare.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Dethsquare.java new file mode 100644 index 0000000..041cef6 --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Dethsquare.java @@ -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"); + } + } +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/GameListeners.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/GameListeners.java new file mode 100644 index 0000000..fe2a793 --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/GameListeners.java @@ -0,0 +1,115 @@ +package com.ezardlabs.dethsquare.util; + +import java.util.ArrayList; + +public interface GameListeners { + ArrayList updateListeners = new ArrayList<>(); + ArrayList postUpdateListeners = new ArrayList<>(); + ArrayList renderListeners = new ArrayList<>(); + ArrayList resizeListeners = new ArrayList<>(); + ArrayList mouseListeners = new ArrayList<>(); + ArrayList keyListeners = new ArrayList<>(); + ArrayList 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); + } +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/GameLog.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/GameLog.java new file mode 100644 index 0000000..a2f3687 --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/GameLog.java @@ -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(); + } +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/IOUtils.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/IOUtils.java new file mode 100644 index 0000000..f55774a --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/IOUtils.java @@ -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); +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Launcher.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Launcher.java new file mode 100644 index 0000000..42dbc41 --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Launcher.java @@ -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); + } + } +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Matrix.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Matrix.java new file mode 100644 index 0000000..cfa23f3 --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/Matrix.java @@ -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; + } + } +} diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/PrefUtils.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/PrefUtils.java new file mode 100644 index 0000000..8aaaa70 --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/PrefUtils.java @@ -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); +} \ No newline at end of file diff --git a/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/RenderUtils.java b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/RenderUtils.java new file mode 100644 index 0000000..9970dee --- /dev/null +++ b/dethsquare/base/src/main/java/com/ezardlabs/dethsquare/util/RenderUtils.java @@ -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 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"); + } + } +} diff --git a/dethsquare/build.gradle b/dethsquare/build.gradle new file mode 100644 index 0000000..4332e38 --- /dev/null +++ b/dethsquare/build.gradle @@ -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. + */ diff --git a/dethsquare/core/.gitignore b/dethsquare/core/.gitignore new file mode 100644 index 0000000..3933271 --- /dev/null +++ b/dethsquare/core/.gitignore @@ -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 diff --git a/dethsquare/core/build.gradle b/dethsquare/core/build.gradle new file mode 100644 index 0000000..0d4697d --- /dev/null +++ b/dethsquare/core/build.gradle @@ -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' +} diff --git a/dethsquare/core/gradlew b/dethsquare/core/gradlew new file mode 100644 index 0000000..9aa616c --- /dev/null +++ b/dethsquare/core/gradlew @@ -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 "$@" diff --git a/dethsquare/core/gradlew.bat b/dethsquare/core/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/dethsquare/core/gradlew.bat @@ -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 diff --git a/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioListener.java b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioListener.java new file mode 100644 index 0000000..5c1adce --- /dev/null +++ b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioListener.java @@ -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); + } +} diff --git a/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioManager.java b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioManager.java new file mode 100644 index 0000000..5ac234c --- /dev/null +++ b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioManager.java @@ -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 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(); + } +} diff --git a/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioSource.java b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioSource.java new file mode 100644 index 0000000..7fc9689 --- /dev/null +++ b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/AudioSource.java @@ -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; + } + } +} diff --git a/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Bounded.java b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Bounded.java new file mode 100644 index 0000000..0271546 --- /dev/null +++ b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Bounded.java @@ -0,0 +1,8 @@ +package com.ezardlabs.dethsquare; + +public interface Bounded { + + RectF getBounds(); + + GameObject getGameObject(); +} diff --git a/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Camera.java b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Camera.java new file mode 100644 index 0000000..5986fd9 --- /dev/null +++ b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Camera.java @@ -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; + } +} diff --git a/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Collider.java b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Collider.java new file mode 100644 index 0000000..5ae40c8 --- /dev/null +++ b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Collider.java @@ -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 normalColliders = new ArrayList<>(); + public static final ArrayList staticColliders = new ArrayList<>(); + public static final ArrayList triggerColliders = new ArrayList<>(); + public static QuadTree 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 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; + } +} diff --git a/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Component.java b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Component.java new file mode 100644 index 0000000..f8b8803 --- /dev/null +++ b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/Component.java @@ -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 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[] 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 + "'"; + } + } + } +} diff --git a/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/GameObject.java b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/GameObject.java new file mode 100644 index 0000000..bed43a4 --- /dev/null +++ b/dethsquare/core/src/main/java/com/ezardlabs/dethsquare/GameObject.java @@ -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 newObjects = new ArrayList<>(); + /** + * List of all {@link GameObject GameObjects} to be destroyed at the end of the current frame + */ + private static final HashMap destroyedObjects = new HashMap<>(); +// private static final ArrayList destroyedObjects = new ArrayList<>(); + /** + * Root of all {@link GameObject GameObjects} currently in the game world + */ + static final GameObject rootObject = new GameObject(""); + /** + * Structure containing all tags currently in use in the game world + */ + private static final HashMap> tags = new HashMap<>(); + /** + * List of all {@link GameObject GameObjects} whose components have been modified in some way since last frame + */ + private static final ArrayList 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 components = new ArrayList<>(); + /** + * List of {@link Script Scripts} currently attached to this {@link GameObject} + */ + private final ArrayList