Karte: replace the tactical map with the interactive map viewer
The Karte page now embeds a standalone viewer (assets/map/) covering all ten regions - Verteron, Altgard, Elthen, Morheim, Poeta, Ishalgen and the Reshanta maps - with markers and category filters from interactivemap.app. map.php loads it in an iframe because its stylesheet restyles body, button and * globally and would otherwise break the site layout. The tile, marker and icon data (~230 MB, ~39,000 files) is kept out of Git and uploaded by FTP; the README explains where it comes from. Removed with it: own markers and categories, tactic layers, the in-browser map builder, the tile/stitch/viewer tools, the bundled Leaflet, the four map tables in schema.sql and the map.manage / map.tactics permissions. Existing databases keep their old map tables untouched. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
c1dacc6688
commit
c5213b5736
39 changed files with 2275 additions and 5538 deletions
5
.gitignore
vendored
5
.gitignore
vendored
|
|
@ -2,7 +2,6 @@ config.php
|
|||
assets/uploads/avatars/*
|
||||
!assets/uploads/avatars/.htaccess
|
||||
!assets/uploads/avatars/.gitkeep
|
||||
assets/uploads/maps/*
|
||||
!assets/uploads/maps/.htaccess
|
||||
!assets/uploads/maps/.gitkeep
|
||||
# Kacheln, Marker und Icons der Karte (~230 MB) - werden per FTP hochgeladen, siehe README
|
||||
assets/map/data/
|
||||
__pycache__/
|
||||
|
|
|
|||
219
README.md
219
README.md
|
|
@ -18,8 +18,8 @@ und wird später ausgebaut. Fokus dieser Version ist der Mitglieder-/Admin-Berei
|
|||
- Jeder Benutzer kann mehreren Berechtigungsgruppen angehören
|
||||
- Events-Seite: geplante (wiederkehrende) Event-Erinnerungen des Bots ansehen, anlegen,
|
||||
bearbeiten und löschen - synchron mit `/event_planen` / `/event_liste` im Discord
|
||||
- Taktikkarte: gekachelte Zoom-Karte der Spielwelt mit eigenen Markern (Kategorien, Filter,
|
||||
Suche) und Taktik-Ebenen zum Einzeichnen von Sammelpunkten, Routen, Zonen und Notizen
|
||||
- Karte: interaktive Zoom-Karte aller Regionen (Verteron, Altgard, Elthen, Morheim, Poeta,
|
||||
Ishalgen, Reshanta) mit Markern und Kategorie-Filtern
|
||||
- Raids-Seite: zeigt anstehende Raid-Termine, Anforderungen, Gruppen und Anmeldungen,
|
||||
bezogen von einer externen API (`config.php: raids_api`), Filter Aktiv/Archiviert/Alle
|
||||
- "Mein Profil"-Seite: Anzeigename ändern, Passwort ändern, Discord-Verknüpfung verwalten
|
||||
|
|
@ -38,8 +38,7 @@ sql/schema.sql Datenbankstruktur zum Import (z.B. via phpMyAdmin)
|
|||
includes/ PHP-Logik (Datenbank, Auth, Berechtigungen, Layout)
|
||||
index.php, login.php, ... Öffentlich aufrufbare Seiten
|
||||
admin/ Admin-Bereich (Benutzerverwaltung, Berechtigungsgruppen)
|
||||
assets/ CSS, JS, Bilder, mitgelieferte Bibliotheken (assets/vendor/)
|
||||
tools/ Hilfsscripte für die Kommandozeile (z.B. Kartenkacheln erzeugen)
|
||||
assets/ CSS, JS, Bilder, die interaktive Karte (assets/map/)
|
||||
```
|
||||
|
||||
Alles liegt in einem einzigen Verzeichnis, das direkt als Dokumentenstamm/Document Root der
|
||||
|
|
@ -257,200 +256,34 @@ Das Feature braucht eine Erweiterung der Bot-API (`PATCH /api/events/{id}` zum B
|
|||
Bot-Repos (Aion2_RaidPlaner), nicht dieses hier. Nach dem Deployen der Bot-Änderung muss der
|
||||
Bot-Prozess neu gestartet werden.
|
||||
|
||||
### Taktikkarte
|
||||
### Karte
|
||||
|
||||
Eine zoom- und verschiebbare Karte der Spielwelt mit eigenen Markern und darüber liegenden
|
||||
Taktik-Ebenen. Vorbild ist die Bedienung gängiger interaktiver Aion-Karten: links eine Sidebar
|
||||
mit Kategorien (gruppiert, mit Marker-Anzahl hinter jedem Eintrag), Häkchen pro Kategorie bzw.
|
||||
Gruppe, "Alle einblenden"/"Alle ausblenden" und eine Suche; rechts die Karte mit Marker-Popups.
|
||||
Die Seite **Karte** (`map.php`) zeigt eine interaktive Karte aller Regionen: Verteron,
|
||||
Altgard, Elthen, Morheim, Poeta, Ishalgen, Abyss Reshanta A/B sowie Chaotic Middle/Upper
|
||||
Reshanta. Oben wird die Region gewählt, unten links lassen sich die Marker-Kategorien
|
||||
(Orte, Monster, NPCs, Ressourcen, Sammelbares, Quests …) einzeln oder gruppenweise ein- und
|
||||
ausblenden, beim Überfahren eines Markers erscheint sein Name. Zoomen per Mausrad, `+`/`-`
|
||||
oder die Knöpfe oben rechts, verschieben per Ziehen, `0` setzt die Ansicht zurück.
|
||||
|
||||
Wichtig: Diese Seite bringt die **Mechanik** mit, nicht die Daten. Kartenmaterial und Marker
|
||||
pflegt ihr selbst - aus fremden Karten-Seiten werden weder Kacheln noch Marker übernommen.
|
||||
Der Viewer ist ein eigenständiges Paket (HTML/CSS/JS ohne Bibliotheken) unter `assets/map/`
|
||||
und wird von `map.php` per iframe eingebettet - so greift sein Stylesheet nicht auf das
|
||||
Seitenlayout über. Die Seite braucht die Berechtigung `map.view`. Datenbank und Discord-Bot
|
||||
sind nicht beteiligt.
|
||||
|
||||
**Marker.** Mitglieder mit `map.manage` aktivieren oben "Marker setzen" und klicken auf die
|
||||
Karte; im Popup werden Name, Kategorie und eine optionale Beschreibung erfasst. Bestehende
|
||||
Marker lassen sich über ihr Popup bearbeiten oder löschen. Die Kategorien sind zweistufig
|
||||
(Gruppe -> Kategorie) und komplett frei anlegbar, jeweils mit Symbol (Emoji) und Farbe, die
|
||||
zusammen die Marker-Nadel ergeben. Solange noch keine Kategorie existiert, gibt es einen
|
||||
Knopf, der eine Startgliederung (Orte, Sammelbares, NPCs, Quests, Ressourcen, Monster, Gilde)
|
||||
anlegt - danach ist alles frei änderbar.
|
||||
Kacheln, Marker und Icons liegen unter `assets/map/data/` (rund 230 MB, knapp 39.000
|
||||
Dateien) und sind wegen der Größe von Git ausgenommen. Beim Deployen muss dieser Ordner mit
|
||||
hochgeladen werden. Er stammt aus dem Kartenpaket `Aion2_Map_In_Gut_BonzenEdition.zip`
|
||||
(Ordner `data/` darin). Die Daten kommen von [interactivemap.app](https://interactivemap.app/aion2/maps)
|
||||
und lassen sich mit den Scripten unter `assets/map/scripts/` neu herunterladen. Details dazu
|
||||
stehen in `assets/map/README.md`.
|
||||
|
||||
**Taktiken.** Eine Taktik ist eine eigene Zeichenebene über der Karte, die sich unabhängig
|
||||
ein- und ausblenden lässt - z.B. eine pro Festungskampf oder Raid-Route. Mitglieder mit
|
||||
`map.tactics` legen eine Taktik an und zeichnen dann Sammelpunkte, Routen (gestrichelte
|
||||
Linien), Flächen und Textnotizen in frei wählbaren Farben. Routen und Flächen werden per
|
||||
Doppelklick, über den Knopf "Abschließen" oder mit Enter beendet, Esc bricht ab; ein Klick auf
|
||||
ein vorhandenes Objekt löscht es (mit Rückfrage). Beschriftung und Farbe kommen jeweils aus
|
||||
einem kleinen Dialog.
|
||||
Für Verteron, Altgard, Elthen, Morheim, Abyss Reshanta A sowie Chaotic Middle/Upper Reshanta
|
||||
gibt es Marker, Poeta, Ishalgen und Abyss Reshanta B zeigen nur die Karte.
|
||||
|
||||
Marker- und Taktik-Koordinaten werden als Anteil der Kartenbreite/-höhe gespeichert (0..1),
|
||||
nicht in Pixeln. Ein später neu gekacheltes oder höher aufgelöstes Kartenbild verschiebt
|
||||
deshalb nichts.
|
||||
|
||||
Neue Berechtigungen: `map.view` (Karte und Taktiken ansehen), `map.manage` (Marker und
|
||||
Kategorien verwalten) und `map.tactics` (Taktiken anlegen/bearbeiten) müssen bei einem vor
|
||||
diesem Update installierten Account nachträglich unter Berechtigungsgruppen angelegt und
|
||||
zugewiesen werden.
|
||||
|
||||
Die Karte läuft komplett in der Website-Datenbank, der Discord-Bot ist daran nicht beteiligt.
|
||||
Einer bestehenden Datenbank fehlen die vier Kartentabellen. Die Seite erkennt das selbst und
|
||||
zeigt statt eines Fehlers eine Einrichtungsseite mit einem Knopf, der sie anlegt (nur für
|
||||
Konten mit `roles.manage`); ausgeführt werden dabei genau die `CREATE TABLE IF NOT
|
||||
EXISTS`-Befehle aus dem Abschnitt „Taktikkarte" am Ende von `sql/schema.sql`. Wer lieber
|
||||
selbst Hand anlegt, führt diesen Abschnitt einfach in phpMyAdmin aus - beides ist gleichwertig
|
||||
und ändert nichts an vorhandenen Daten.
|
||||
|
||||
Die Kartendarstellung nutzt [Leaflet](https://leafletjs.com) 1.9.4, das unter
|
||||
`assets/vendor/leaflet/` mitgeliefert wird (kein CDN, kein Build-Schritt, keine externe
|
||||
Abhängigkeit zur Laufzeit).
|
||||
|
||||
#### Karte direkt auf der Website bauen
|
||||
|
||||
Der bequemste Weg: auf der Karten-Seite ein Bild auswählen und auf **Karte bauen**
|
||||
drücken. Kein FTP, kein Kommandozeilen-Werkzeug, keine Server-Einstellungen. Solange noch
|
||||
keine Karte hinterlegt ist, steht das Feld direkt auf der Einrichtungsseite; danach findet
|
||||
es sich unter der Karte hinter **Karte neu bauen**.
|
||||
|
||||
Geschnitten wird dabei **im Browser** und hochgeladen werden nur die fertigen 256er-Kacheln.
|
||||
Das ist der entscheidende Punkt auf gewöhnlichem Webspace: ein 50-MB-Kartenbild scheitert
|
||||
sonst an `upload_max_filesize`, das Zerlegen an `memory_limit` und `max_execution_time`, und
|
||||
GD ist auch nicht überall installiert. So braucht der Server nichts davon - er nimmt kleine
|
||||
JPEGs entgegen, prüft sie und legt sie ab.
|
||||
|
||||
Ablauf im Einzelnen:
|
||||
|
||||
1. Bild auswählen oder in das Feld ziehen. Die Seite zeigt sofort Maße, Zoomstufen und die
|
||||
zu erwartende Kachelzahl - und warnt, wenn das Bild für eine scharfe Karte zu klein ist.
|
||||
2. Kartenschlüssel (Ordnername) und Anzeigename werden aus dem Dateinamen vorbelegt, die
|
||||
JPEG-Qualität steht auf 88.
|
||||
3. **Karte bauen** drücken. Der Fortschrittsbalken zählt Zoomstufe und Kacheln mit.
|
||||
4. Am Ende springt die Seite auf die fertige Karte.
|
||||
|
||||
Gebaut wird in einen Nebenordner `<schlüssel>__build`; erst wenn alle Kacheln oben sind,
|
||||
tritt er an die Stelle der bisherigen Karte. Ein Abbruch - per Knopf, durch einen Fehler
|
||||
oder durch Schließen des Browsers - lässt die alte Karte also unangetastet. Der Knopf
|
||||
**Abbrechen** räumt den halbfertigen Ordner gleich mit weg.
|
||||
|
||||
Das Ergebnis ist identisch zu dem, was `tools/make_map_tiles.php` erzeugt (gleiche
|
||||
Zoomstufen, gleiche Kachelnamen, gleiche `tiles.json`) - die Kommandozeilen-Werkzeuge
|
||||
bleiben also für sehr große Bilder oder Stapelverarbeitung weiter nutzbar.
|
||||
|
||||
Die Seite braucht dafür die Berechtigung `map.manage`. Hochgeladen wird ausschließlich in
|
||||
`assets/uploads/maps/`, der Ordner muss für den Webserver beschreibbar sein; eine
|
||||
`.htaccess` dort verhindert, dass Dateien darin jemals als PHP ausgeführt werden.
|
||||
|
||||
#### Kartenbild kacheln
|
||||
|
||||
Die Karte wird als Kachel-Pyramide ausgeliefert: mehrere Zoomstufen aus einem hoch aufgelösten
|
||||
Bild, damit sie auch nah herangezoomt scharf bleibt und nie das ganze Bild auf einmal geladen
|
||||
werden muss. Erzeugt wird sie einmalig lokal (nicht auf dem Webspace):
|
||||
|
||||
```
|
||||
php -d memory_limit=2G tools/make_map_tiles.php verteron "C:\Bilder\verteron.png" --name="Verteron"
|
||||
```
|
||||
|
||||
Der erste Parameter ist der Kartenschlüssel (nur Kleinbuchstaben/Ziffern/`-`/`_`), der zweite
|
||||
das Quellbild (PNG, JPEG oder WebP). Optional: `--name=` für den angezeigten Namen,
|
||||
`--tile-size=` (Standard 256) und `--quality=` (JPEG-Qualität, Standard 82). Das Script braucht die PHP-Erweiterung GD. Meldet es `Die PHP-Erweiterung GD wird benoetigt`, nennt es gleich die php.ini, in die `extension_dir = "ext"` und `extension=gd` gehören - bei manchen PHP-Installationen (z.B. scoop unter Windows) gibt es ab Werk gar keine geladene php.ini, dann muss sie neben `php.exe` neu angelegt werden.
|
||||
|
||||
Das Ergebnis landet in `assets/uploads/maps/<schlüssel>/` (ein Ordner je Zoomstufe plus eine
|
||||
`tiles.json`) und wird per FTP genau dorthin auf den Webspace geladen. Mehr ist nicht nötig:
|
||||
`map.php` findet jeden Unterordner mit einer `tiles.json` von allein. Liegen mehrere Karten
|
||||
dort, erscheint oben in der Sidebar automatisch eine Auswahlliste - eine Region pro Ordner.
|
||||
Die Kacheln selbst sind bewusst von Git ausgenommen (`.gitignore`), damit das Repository nicht
|
||||
mit hunderten Bilddateien vollläuft.
|
||||
|
||||
#### Screenshots zu einem grossen Kartenbild zusammensetzen
|
||||
|
||||
Wie weit sich die Karte auf der Website scharf heranzoomen lässt, hängt einzig an der
|
||||
Auflösung des Ausgangsbildes - der Kachel-Generator hört bei 1:1 auf, über die native
|
||||
Auflösung hinaus kann man gar nicht erst zoomen. Ein einzelner Screenshot der ganzen
|
||||
Weltkarte reicht dafür nicht. Stattdessen im Spiel maximal hineinzoomen, die Karte in
|
||||
Bahnen abfotografieren und die Bilder hiermit zusammensetzen:
|
||||
|
||||
```
|
||||
python tools/stitch_map_screenshots.py shots/ -o verteron.png
|
||||
```
|
||||
|
||||
Das Script findet die Überlappungen selbst (Phasenkorrelation über die FFT, geprüft am
|
||||
normierten Korrelationskoeffizienten der Überlappung), die Reihenfolge der Dateinamen
|
||||
ist egal. Weitere Optionen zeigt `--help`.
|
||||
|
||||
**Zu `--crop`:** optional, und nur nötig, wenn auf jedem Screenshot dieselben festen
|
||||
UI-Elemente liegen (Chat, Minimap, Kartenrahmen) - die bringen die Zuordnung sonst
|
||||
durcheinander. Die vier Zahlen sind **links, oben, rechts, unten in Pixeln und müssen aus
|
||||
deinen eigenen Screenshots abgemessen werden**; irgendwelche Beispielwerte zu übernehmen
|
||||
schneidet dir sonst einen Teil der Karte ab. Miss die Ränder z.B. in Paint oder GIMP nach,
|
||||
oder lass `--crop` zunächst ganz weg und schau dir das Ergebnis an.
|
||||
|
||||
Beim Aufnehmen:
|
||||
|
||||
- immer dieselbe Zoomstufe im Spiel (das Script verschiebt nur, es dreht und skaliert nicht)
|
||||
- mindestens ~30% Überlappung zwischen benachbarten Screenshots
|
||||
- in Bahnen abfahren, eine Reihe komplett, dann die nächste
|
||||
- Fenstermodus ohne Rahmen, damit alle Screenshots exakt gleich gross sind
|
||||
- `--crop` lieber etwas zu grosszügig als zu knapp: mitten im Bild überdeckt ein
|
||||
Nachbar-Screenshot einen stehen gebliebenen UI-Streifen wieder, am äusseren Kartenrand
|
||||
gibt es diesen Nachbarn nicht
|
||||
|
||||
Rechenbeispiel: bei 2560x1440 und einem 6x5-Raster mit 35% Überlappung kommen grob
|
||||
13.000 x 7.000 Pixel heraus - Faktor 5 mehr Detail in jede Richtung als ein einzelner
|
||||
Vollbild-Screenshot. Noch mehr Pixel gibt es über eine höhere Renderauflösung (NVIDIA
|
||||
DSR bzw. AMD VSR lassen das Spiel intern in 4K/5K rendern, auch auf einem 1440p-Monitor)
|
||||
und eine kleinere UI-Skalierung.
|
||||
|
||||
Das Script braucht Python 3.8+ mit numpy und Pillow (`pip install numpy pillow`), läuft
|
||||
lokal und hat mit dem Webspace nichts zu tun.
|
||||
|
||||
Auf Bildschirmen mit hoher Pixeldichte holt die Karte automatisch die nächsthöhere
|
||||
Kachelstufe und zeichnet sie halb so gross (Leaflet `detectRetina`), damit dort nicht
|
||||
hochskaliert und damit unscharf dargestellt wird.
|
||||
|
||||
#### Kachelsatz ohne Datenbank ansehen
|
||||
|
||||
`tools/tile_viewer.html` ist ein eigenständiger Betrachter für einen Kachelsatz - eine
|
||||
einzelne HTML-Datei mit Canvas-Renderer, ohne Datenbank, ohne Anmeldung, ohne
|
||||
Bibliotheken. Praktisch, um frisch erzeugte Kacheln zu prüfen, bevor sie hochgeladen
|
||||
werden, oder um einen Kartensatz weiterzugeben, der nichts mit der Website zu tun hat.
|
||||
|
||||
Ordner mit einem beliebigen Webserver ausliefern und die Datei aufrufen:
|
||||
|
||||
```
|
||||
python -m http.server 8000
|
||||
```
|
||||
|
||||
Alles Wesentliche kommt aus der Adresszeile, die Datei selbst muss nicht angefasst werden:
|
||||
|
||||
| Parameter | Bedeutung | Standard |
|
||||
|---|---|---|
|
||||
| `tiles` | URL-Muster mit den Platzhaltern `{z}`, `{x}`, `{y}` | `tiles/{z}/{x}_{y}.jpg` |
|
||||
| `zmin`, `zmax` | vorhandene Zoomstufen | `2`, `6` |
|
||||
| `tilesize` | Kantenlänge einer Kachel in Pixeln | `256` |
|
||||
| `x`, `y` | Startpunkt in Weltpixeln | Kartenmitte |
|
||||
|
||||
Der Standard passt auf das Ablageschema von `make_map_tiles.php`. Für eine Karte aus
|
||||
`assets/uploads/maps/verteron/` also:
|
||||
|
||||
```
|
||||
tile_viewer.html?tiles=../assets/uploads/maps/verteron/{z}/{x}_{y}.jpg&zmin=0&zmax=5
|
||||
```
|
||||
|
||||
Ein flacher Ordner mit Dateien wie `6_39_35.jpg` geht genauso:
|
||||
|
||||
```
|
||||
tile_viewer.html?tiles=meine_kacheln/{z}_{x}_{y}.jpg&zmin=2&zmax=6
|
||||
```
|
||||
|
||||
Bedienung: ziehen zum Verschieben, Rad oder Pinch zum Zoomen auf den Zeiger, Pfeiltasten,
|
||||
`+`/`-`, `R` setzt die Ansicht zurück. Die Einblendung oben links zeigt Maßstab, aktive
|
||||
Zoomstufe, die Kachel unter dem Zeiger und die Ladezähler; der PNG-Knopf speichert den
|
||||
aktuellen Bildausschnitt.
|
||||
|
||||
Fehlende Kacheln sind eingeplant: der Betrachter merkt sich pro Sitzung, welche Koordinate
|
||||
nicht existiert (ein Versuch, kein Nachfassen), und zeichnet stattdessen entweder die vier
|
||||
feineren Kacheln darunter oder die nächstbeste gröbere darüber. Sichtbare Lücken entstehen
|
||||
dadurch praktisch nie - auch nicht, solange noch geladen wird. Dekodierte Kacheln liegen in
|
||||
einem LRU-Cache mit 512 Einträgen, es laufen höchstens 8 Anfragen gleichzeitig.
|
||||
Die frühere Taktikkarte (eigene Marker, Taktik-Ebenen, Kartenbauer) wurde dadurch ersetzt.
|
||||
Ihre Tabellen `map_categories`, `map_markers`, `map_tactics` und `map_tactic_shapes` sowie
|
||||
die Berechtigungen `map.manage` und `map.tactics` werden nicht mehr benutzt und können bei
|
||||
bestehenden Installationen gelöscht werden.
|
||||
|
||||
### Mitgliederliste
|
||||
|
||||
|
|
|
|||
|
|
@ -1893,7 +1893,7 @@ input.role-weight-input {
|
|||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
/* --- Taktikkarte --- */
|
||||
/* --- Karte --- */
|
||||
|
||||
.app-content.bg-map {
|
||||
background-image: linear-gradient(rgba(20, 20, 20, 0.72), rgba(20, 20, 20, 0.85)), url('/assets/images/Landscapes/web/landscape8-bg.jpg');
|
||||
|
|
@ -1902,454 +1902,14 @@ input.role-weight-input {
|
|||
/* Die Karte braucht mehr Platz als die 1100px der normalen Inhaltsspalte. */
|
||||
.container-wide { max-width: 1600px; }
|
||||
|
||||
.map-page {
|
||||
display: grid;
|
||||
grid-template-columns: 300px minmax(0, 1fr);
|
||||
gap: 1rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.map-sidebar {
|
||||
background: rgba(35, 35, 35, 0.72);
|
||||
backdrop-filter: blur(8px);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
max-height: calc(100vh - 4rem);
|
||||
position: sticky;
|
||||
top: 2rem;
|
||||
}
|
||||
|
||||
.map-sidebar-head { display: flex; flex-direction: column; gap: 0.6rem; }
|
||||
.map-sidebar-head h1 { margin: 0; font-size: 1.4rem; }
|
||||
|
||||
.map-bulk-actions { display: flex; gap: 0.5rem; }
|
||||
.map-bulk-actions button { flex: 1; font-size: 0.8rem; padding: 0.4rem 0.5rem; }
|
||||
|
||||
.map-tabs {
|
||||
display: flex;
|
||||
gap: 0.35rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.map-tab {
|
||||
flex: 1;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
color: var(--text-muted);
|
||||
padding: 0.4rem 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.map-tab:hover { color: var(--text); }
|
||||
.map-tab.active { background: rgba(201, 162, 39, 0.15); color: var(--gold); border-color: var(--gold); }
|
||||
|
||||
.map-tab-count {
|
||||
display: inline-block;
|
||||
margin-left: 0.3rem;
|
||||
padding: 0 0.35rem;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-panel-alt);
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
|
||||
/* Nur die Liste scrollt, Kopf und Reiter bleiben stehen. Wie bei .modal-overlay
|
||||
muss die Sichtbarkeit ueber :not([hidden]) laufen, sonst wuerde "display: flex"
|
||||
das "hidden"-Attribut ueberstimmen und beide Reiter waeren gleichzeitig offen. */
|
||||
.map-panel { display: none; }
|
||||
|
||||
.map-panel:not([hidden]) {
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.map-empty { text-align: center; padding: 1rem 0; }
|
||||
.map-hint { font-size: 0.78rem; margin-top: 0.6rem; }
|
||||
|
||||
.map-group { border-bottom: 1px solid rgba(61, 61, 61, 0.5); padding-bottom: 0.35rem; }
|
||||
.map-group[hidden] { display: none; }
|
||||
.map-group:last-child { border-bottom: none; }
|
||||
|
||||
.map-group-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.3rem 0;
|
||||
}
|
||||
|
||||
.map-group-toggle {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
|
||||
.map-group.collapsed .map-group-toggle { transform: rotate(-90deg); }
|
||||
.map-group.collapsed .map-group-children { display: none; }
|
||||
|
||||
.map-group-label,
|
||||
.map-category-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
cursor: pointer;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.map-group-label { font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.04em; }
|
||||
|
||||
.map-group-label input,
|
||||
.map-category-label input { width: auto; flex-shrink: 0; margin: 0; }
|
||||
|
||||
.map-group-name,
|
||||
.map-category-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.map-group-children { padding-left: 1.1rem; }
|
||||
|
||||
.map-category {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.15rem 0;
|
||||
}
|
||||
|
||||
/* Die Suche blendet nicht passende Kategorien per "hidden" aus - ohne diese Regel
|
||||
wuerde "display: flex" das ueberstimmen (wie bei .modal-overlay). */
|
||||
.map-category[hidden] { display: none; }
|
||||
|
||||
.map-category-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
font-size: 0.7rem;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35) inset;
|
||||
}
|
||||
|
||||
.map-count {
|
||||
font-size: 0.72rem;
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.map-category .icon-button,
|
||||
.map-group-head .icon-button { padding: 0.15rem; opacity: 0; }
|
||||
.map-category:hover .icon-button,
|
||||
.map-group-head:hover .icon-button { opacity: 1; }
|
||||
.map-category .icon-button .icon,
|
||||
.map-group-head .icon-button .icon { width: 14px; height: 14px; }
|
||||
|
||||
.map-add-category,
|
||||
.map-add-tactic { margin-top: 0.5rem; font-size: 0.82rem; }
|
||||
|
||||
.map-tactic {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.35rem 0.4rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.map-tactic:hover { background: var(--bg-panel-alt); }
|
||||
.map-tactic.editing { border-color: var(--gold); background: rgba(201, 162, 39, 0.12); }
|
||||
|
||||
.map-tactic-label { display: flex; align-items: center; gap: 0.45rem; flex: 1; min-width: 0; cursor: pointer; font-size: 0.88rem; }
|
||||
.map-tactic-label input { width: auto; flex-shrink: 0; margin: 0; }
|
||||
.map-tactic-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
/* --- Kartenflaeche --- */
|
||||
|
||||
.map-stage {
|
||||
background: rgba(35, 35, 35, 0.72);
|
||||
backdrop-filter: blur(8px);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 0.75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.map-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.map-toolbar-spacer { flex: 1; }
|
||||
|
||||
.map-tool {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.4rem 0.7rem;
|
||||
background: var(--bg-panel-alt);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
color: var(--text);
|
||||
font-size: 0.82rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Wie bei .modal-overlay: "display: inline-flex" wuerde das "hidden"-Attribut
|
||||
ueberstimmen, deshalb hier explizit ausblenden. */
|
||||
.map-tool[hidden] { display: none; }
|
||||
|
||||
.map-tool:hover { border-color: var(--gold); color: var(--gold); }
|
||||
.map-tool.active { background: rgba(201, 162, 39, 0.2); border-color: var(--gold); color: var(--gold); }
|
||||
.map-tool-finish { border-color: var(--success); color: var(--success); }
|
||||
.map-tool-finish:hover { background: rgba(76, 175, 80, 0.15); border-color: var(--success); color: var(--success); }
|
||||
.map-tool .icon { width: 16px; height: 16px; }
|
||||
|
||||
.map-tool-group { display: none; }
|
||||
|
||||
.map-tool-group:not([hidden]) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
flex-wrap: wrap;
|
||||
padding: 0.3rem 0.5rem;
|
||||
border: 1px dashed var(--gold);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.map-tool-group-label { font-size: 0.8rem; color: var(--gold); font-weight: 600; margin-right: 0.2rem; }
|
||||
|
||||
.map-tool-group input[type="color"] {
|
||||
width: 34px;
|
||||
height: 30px;
|
||||
padding: 2px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-panel-alt);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.map-coords {
|
||||
font-size: 0.78rem;
|
||||
color: var(--text-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
min-width: 5.5rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.map-canvas {
|
||||
height: calc(100vh - 12rem);
|
||||
min-height: 420px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Leaflet faerbt seinen Container per Default hellgrau. Dieselbe Farbe wie die
|
||||
aufgefuellten Randkacheln (siehe tools/make_map_tiles.php) laesst den Rand der
|
||||
Karte nahtlos in die Flaeche uebergehen. */
|
||||
.map-canvas.leaflet-container { background: #14161a; }
|
||||
|
||||
.map-canvas.map-placing { cursor: crosshair; }
|
||||
.map-status { margin: 0; font-size: 0.8rem; min-height: 1.2em; }
|
||||
|
||||
.map-setup-steps { line-height: 1.9; }
|
||||
.map-setup-steps code { word-break: break-all; }
|
||||
|
||||
/* --- Marker und Taktik-Objekte auf der Karte --- */
|
||||
|
||||
.map-marker-icon { background: none; border: none; }
|
||||
|
||||
.map-marker-pin {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 50% 50% 50% 4px;
|
||||
transform: rotate(-45deg);
|
||||
border: 2px solid rgba(0, 0, 0, 0.55);
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.map-marker-glyph { transform: rotate(45deg); font-size: 12px; line-height: 1; }
|
||||
|
||||
.map-marker-icon:hover .map-marker-pin { filter: brightness(1.25); }
|
||||
|
||||
/* Treffer der Suche bleiben sichtbar, alles andere wird nur gedaempft, damit
|
||||
der Zusammenhang auf der Karte erhalten bleibt. Anklickbar sind die gedaempften
|
||||
Marker dann aber nicht mehr - sonst faengt man sie beim Klick auf einen Treffer ab. */
|
||||
.map-marker-filtered { opacity: 0.18; pointer-events: none; }
|
||||
|
||||
.map-shape-point { background: none; border: none; }
|
||||
|
||||
.map-shape-dot {
|
||||
/* Der Viewer zeichnet auf ein Canvas in Fenstergroesse - im iframe also genau so gross
|
||||
wie der Rahmen. 4rem = oberes und unteres Padding von .container. */
|
||||
.map-frame {
|
||||
display: block;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid rgba(0, 0, 0, 0.6);
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
.map-shape-label,
|
||||
.map-shape-text span {
|
||||
display: inline-block;
|
||||
margin-top: 3px;
|
||||
padding: 1px 6px;
|
||||
background: rgba(20, 20, 20, 0.85);
|
||||
width: 100%;
|
||||
height: calc(100vh - 4rem);
|
||||
min-height: 420px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
color: var(--text);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.map-shape-text { background: none; border: none; }
|
||||
.map-shape-text span { border-width: 2px; font-size: 12px; }
|
||||
|
||||
/* Leaflet-Popups an das dunkle Theme anpassen. */
|
||||
.leaflet-popup-content-wrapper,
|
||||
.leaflet-popup-tip {
|
||||
background: var(--bg-panel);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.leaflet-popup-content { margin: 0.7rem 0.9rem; font-size: 0.85rem; }
|
||||
.leaflet-container a.leaflet-popup-close-button { color: var(--text-muted); }
|
||||
|
||||
/* Leaflet misst die Popup-Breite an der natuerlichen Breite des Inhalts. Da der
|
||||
Beschreibungstext umbrechen darf, waere die gemessene Breite sonst nur so breit
|
||||
wie das laengste Wort - deshalb eine sinnvolle Mindestbreite vorgeben. */
|
||||
.map-popup { min-width: 190px; max-width: 260px; }
|
||||
|
||||
.map-popup-title { display: block; font-size: 0.95rem; }
|
||||
.map-popup-category { color: var(--text-muted); font-size: 0.78rem; margin-bottom: 0.4rem; }
|
||||
.map-popup-text { white-space: pre-wrap; }
|
||||
.map-popup-author { color: var(--text-muted); font-size: 0.75rem; margin-top: 0.4rem; }
|
||||
|
||||
.map-popup-edit {
|
||||
margin-top: 0.6rem;
|
||||
padding: 0.25rem 0.6rem;
|
||||
font-size: 0.78rem;
|
||||
background: var(--bg-panel-alt);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 5px;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.map-popup-edit:hover { border-color: var(--gold); color: var(--gold); }
|
||||
|
||||
.leaflet-control-zoom a {
|
||||
background: var(--bg-panel);
|
||||
color: var(--text);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
.leaflet-control-zoom a:hover { background: var(--bg-panel-alt); color: var(--gold); }
|
||||
|
||||
.map-category-form-row { display: grid; grid-template-columns: 1fr 100px; gap: 0.75rem; }
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
.map-page { grid-template-columns: minmax(0, 1fr); }
|
||||
.map-sidebar { position: static; max-height: 60vh; }
|
||||
.map-canvas { height: 60vh; }
|
||||
}
|
||||
|
||||
/* --- Karte aus einem Bild bauen (Browser schneidet, Server nimmt Kacheln an) --- */
|
||||
|
||||
.map-build h2 { margin-top: 0; }
|
||||
|
||||
.map-build-panel { padding: 1rem 1.5rem; }
|
||||
.map-build-panel > summary { cursor: pointer; font-weight: 600; color: var(--gold); }
|
||||
.map-build-panel[open] > summary { margin-bottom: 1rem; }
|
||||
|
||||
.map-build-drop {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
padding: 2rem 1rem;
|
||||
margin: 0.75rem 0;
|
||||
border: 2px dashed var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-panel-alt);
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
transition: border-color 0.15s ease, background 0.15s ease;
|
||||
background: #1a1a2e;
|
||||
}
|
||||
|
||||
.map-build-drop:hover,
|
||||
.map-build-drop.dragging { border-color: var(--gold); background: rgba(201, 162, 39, 0.08); }
|
||||
|
||||
.map-build-drop-text { font-weight: 600; }
|
||||
|
||||
.map-build-info {
|
||||
white-space: pre-line;
|
||||
margin: 0 0 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
min-height: 1.2em;
|
||||
}
|
||||
|
||||
.map-build-info.warn { color: var(--gold); }
|
||||
.map-build-info.error { color: var(--danger); }
|
||||
|
||||
.map-build-fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.map-build-hint { font-size: 0.75rem; margin: 0.2rem 0 0; }
|
||||
|
||||
.map-build-progress {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.map-build-track {
|
||||
flex: 1;
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-panel-alt);
|
||||
border: 1px solid var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.map-build-bar {
|
||||
height: 100%;
|
||||
width: 0;
|
||||
background: var(--gold);
|
||||
transition: width 0.2s ease;
|
||||
}
|
||||
|
||||
.map-build-progress span { font-size: 0.8rem; white-space: nowrap; }
|
||||
|
||||
/* Waehrend des Bauens nichts umstellen, was den laufenden Vorgang betrifft. */
|
||||
.map-build.building .map-build-drop,
|
||||
.map-build.building .map-build-fields { opacity: 0.5; pointer-events: none; }
|
||||
|
|
|
|||
901
assets/js/map.js
901
assets/js/map.js
|
|
@ -1,901 +0,0 @@
|
|||
(function () {
|
||||
'use strict';
|
||||
|
||||
var page = document.querySelector('.map-page');
|
||||
var dataEl = document.getElementById('map-data');
|
||||
if (!page || !dataEl || typeof L === 'undefined') return;
|
||||
|
||||
var data = JSON.parse(dataEl.textContent);
|
||||
var manifest = data.manifest;
|
||||
var mapKey = page.getAttribute('data-map-key');
|
||||
var canManage = page.getAttribute('data-can-manage') === '1';
|
||||
var canTactics = page.getAttribute('data-can-tactics') === '1';
|
||||
var csrfToken = (document.querySelector('meta[name="csrf-token"]') || {}).content || '';
|
||||
|
||||
var statusEl = document.getElementById('map-status');
|
||||
|
||||
function postJson(payload) {
|
||||
payload.csrf_token = csrfToken;
|
||||
payload.map_key = mapKey;
|
||||
return fetch('/map_action.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
}).then(function (response) { return response.json(); });
|
||||
}
|
||||
|
||||
function setStatus(text, isError) {
|
||||
if (!statusEl) return;
|
||||
statusEl.textContent = text || '';
|
||||
statusEl.className = 'map-status text-muted' + (isError ? ' error' : '');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Karte: gekacheltes Bild ohne Geo-Bezug, deshalb CRS.Simple. Alle Marker
|
||||
// liegen als 0..1-Anteil der Bildbreite/-hoehe vor und werden hier ueber
|
||||
// die maximale Zoomstufe in Leaflet-Koordinaten uebersetzt - dadurch bleiben
|
||||
// sie auch dann richtig, wenn die Karte spaeter neu gekachelt wird.
|
||||
// ---------------------------------------------------------------------
|
||||
// Ueber die tiefste vorhandene Kachelebene hinaus darf weiter gezoomt werden; dort
|
||||
// vergroessert Leaflet die tiefsten Kacheln (etwas weicher, aber man kommt naeher
|
||||
// heran). Ohne das waere bei einer flachen Pyramide - eine 1024er-Karte hat nur die
|
||||
// Stufen 0 bis 2 - schon die Startansicht am Anschlag und Hineinzoomen unmoeglich.
|
||||
var EXTRA_ZOOM = 2;
|
||||
var mapMaxZoom = manifest.max_zoom + EXTRA_ZOOM;
|
||||
|
||||
var map = L.map('map-canvas', {
|
||||
crs: L.CRS.Simple,
|
||||
minZoom: manifest.min_zoom,
|
||||
maxZoom: mapMaxZoom,
|
||||
zoomControl: true,
|
||||
attributionControl: false,
|
||||
maxBoundsViscosity: 0.85,
|
||||
doubleClickZoom: false,
|
||||
// Die Zoomstufen der Kachel-Pyramide sind Zweierpotenzen. Ohne Zwischenstufen
|
||||
// koennte die Startansicht die Flaeche nur selten gut ausnutzen (die naechst
|
||||
// groessere Stufe passt meist nicht mehr hinein), deshalb Viertelschritte.
|
||||
zoomSnap: 0.25,
|
||||
zoomDelta: 0.5
|
||||
});
|
||||
|
||||
function toLatLng(x, y) {
|
||||
return map.unproject([x * manifest.width, y * manifest.height], manifest.max_zoom);
|
||||
}
|
||||
|
||||
function toNormalized(latlng) {
|
||||
var point = map.project(latlng, manifest.max_zoom);
|
||||
return [
|
||||
Math.min(1, Math.max(0, point.x / manifest.width)),
|
||||
Math.min(1, Math.max(0, point.y / manifest.height))
|
||||
];
|
||||
}
|
||||
|
||||
// Rund um das Kartenbild liegt noch Leerraum (aufgefuellte Randkacheln). Ein Klick
|
||||
// dorthin wuerde durch das Klemmen in toNormalized() still an den Bildrand rutschen -
|
||||
// deshalb solche Klicks lieber ablehnen als das Objekt woanders abzulegen.
|
||||
function isInsideMap(latlng) {
|
||||
var point = map.project(latlng, manifest.max_zoom);
|
||||
return point.x >= 0 && point.x <= manifest.width
|
||||
&& point.y >= 0 && point.y <= manifest.height;
|
||||
}
|
||||
|
||||
var bounds = L.latLngBounds(toLatLng(0, 1), toLatLng(1, 0));
|
||||
map.setMaxBounds(bounds.pad(0.15));
|
||||
|
||||
L.tileLayer(manifest.url_template, {
|
||||
tileSize: manifest.tile_size,
|
||||
minZoom: manifest.min_zoom,
|
||||
maxZoom: mapMaxZoom,
|
||||
// Bis hierher gibt es wirklich Kacheln - alles darueber wird aus dieser Stufe
|
||||
// hochskaliert, statt Kacheln anzufordern, die es nicht gibt.
|
||||
maxNativeZoom: manifest.max_zoom,
|
||||
bounds: bounds,
|
||||
noWrap: true,
|
||||
// Randkacheln jenseits des Bildes gibt es nicht - statt eines kaputten
|
||||
// Bildes soll dort einfach nichts stehen.
|
||||
errorTileUrl: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
|
||||
}).addTo(map);
|
||||
|
||||
function resetView() {
|
||||
map.fitBounds(bounds, { padding: [8, 8] });
|
||||
}
|
||||
resetView();
|
||||
|
||||
var resetBtn = document.getElementById('map-reset-view');
|
||||
if (resetBtn) resetBtn.addEventListener('click', resetView);
|
||||
|
||||
// Positionsanzeige (praktisch, um Koordinaten durchzugeben)
|
||||
var coordsEl = document.getElementById('map-coords');
|
||||
if (coordsEl) {
|
||||
map.on('mousemove', function (e) {
|
||||
var pos = toNormalized(e.latlng);
|
||||
coordsEl.textContent = (pos[0] * 100).toFixed(1) + ' / ' + (pos[1] * 100).toFixed(1);
|
||||
});
|
||||
map.on('mouseout', function () { coordsEl.textContent = ''; });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Marker
|
||||
// ---------------------------------------------------------------------
|
||||
var categoriesById = {};
|
||||
data.categories.forEach(function (category) { categoriesById[category.id] = category; });
|
||||
|
||||
var markerLayers = {}; // category_id -> L.LayerGroup
|
||||
var markerById = {}; // marker_id -> {data, layer, group}
|
||||
var visibleCategories = {};
|
||||
var searchTerm = '';
|
||||
|
||||
function categoryIcon(category) {
|
||||
return L.divIcon({
|
||||
className: 'map-marker-icon',
|
||||
html: '<span class="map-marker-pin" style="background:' + (category ? category.color : '#c9a227') + '">'
|
||||
+ '<span class="map-marker-glyph">' + (category && category.icon ? category.icon : '') + '</span></span>',
|
||||
iconSize: [26, 26],
|
||||
iconAnchor: [13, 13],
|
||||
popupAnchor: [0, -14]
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value == null ? '' : value)
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||
.replace(/"/g, '"').replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function popupHtml(marker) {
|
||||
var category = categoriesById[marker.category_id];
|
||||
var html = '<div class="map-popup">'
|
||||
+ '<strong class="map-popup-title">' + escapeHtml(marker.name) + '</strong>'
|
||||
+ '<div class="map-popup-category">' + escapeHtml(category ? category.icon + ' ' + category.name : '') + '</div>';
|
||||
if (marker.description) {
|
||||
html += '<div class="map-popup-text">' + escapeHtml(marker.description).replace(/\n/g, '<br>') + '</div>';
|
||||
}
|
||||
if (marker.author) {
|
||||
html += '<div class="map-popup-author">von ' + escapeHtml(marker.author) + '</div>';
|
||||
}
|
||||
if (canManage) {
|
||||
html += '<button type="button" class="map-popup-edit" data-marker-id="' + marker.id + '">Bearbeiten</button>';
|
||||
}
|
||||
return html + '</div>';
|
||||
}
|
||||
|
||||
function layerForCategory(categoryId) {
|
||||
if (!markerLayers[categoryId]) {
|
||||
markerLayers[categoryId] = L.layerGroup();
|
||||
if (visibleCategories[categoryId] !== false) {
|
||||
markerLayers[categoryId].addTo(map);
|
||||
}
|
||||
}
|
||||
return markerLayers[categoryId];
|
||||
}
|
||||
|
||||
function addMarker(markerData) {
|
||||
var category = categoriesById[markerData.category_id];
|
||||
var layer = L.marker(toLatLng(markerData.x, markerData.y), {
|
||||
icon: categoryIcon(category),
|
||||
draggable: false,
|
||||
title: markerData.name
|
||||
});
|
||||
layer.bindPopup(popupHtml(markerData));
|
||||
layer.addTo(layerForCategory(markerData.category_id));
|
||||
|
||||
markerById[markerData.id] = { data: markerData, layer: layer };
|
||||
return layer;
|
||||
}
|
||||
|
||||
data.markers.forEach(addMarker);
|
||||
|
||||
function removeMarker(markerId) {
|
||||
var entry = markerById[markerId];
|
||||
if (!entry) return;
|
||||
var layer = markerLayers[entry.data.category_id];
|
||||
if (layer) layer.removeLayer(entry.layer);
|
||||
delete markerById[markerId];
|
||||
}
|
||||
|
||||
// Sichtbarkeit: Kategorie-Haken UND Suchbegriff muessen passen.
|
||||
function applyFilters() {
|
||||
Object.keys(markerLayers).forEach(function (categoryId) {
|
||||
var wanted = visibleCategories[categoryId] !== false;
|
||||
var layer = markerLayers[categoryId];
|
||||
if (wanted && !map.hasLayer(layer)) layer.addTo(map);
|
||||
if (!wanted && map.hasLayer(layer)) map.removeLayer(layer);
|
||||
});
|
||||
|
||||
if (searchTerm === '') {
|
||||
Object.keys(markerById).forEach(function (id) {
|
||||
var entry = markerById[id];
|
||||
var element = entry.layer.getElement();
|
||||
if (element) element.classList.remove('map-marker-filtered');
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
Object.keys(markerById).forEach(function (id) {
|
||||
var entry = markerById[id];
|
||||
var category = categoriesById[entry.data.category_id];
|
||||
var haystack = (entry.data.name + ' ' + (entry.data.description || '') + ' '
|
||||
+ (category ? category.name : '')).toLowerCase();
|
||||
var element = entry.layer.getElement();
|
||||
if (!element) return;
|
||||
element.classList.toggle('map-marker-filtered', haystack.indexOf(searchTerm) === -1);
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll('.map-category-checkbox').forEach(function (checkbox) {
|
||||
visibleCategories[checkbox.value] = checkbox.checked;
|
||||
checkbox.addEventListener('change', function () {
|
||||
visibleCategories[checkbox.value] = checkbox.checked;
|
||||
syncGroupCheckbox(checkbox.closest('.map-group'));
|
||||
applyFilters();
|
||||
});
|
||||
});
|
||||
|
||||
function syncGroupCheckbox(group) {
|
||||
if (!group) return;
|
||||
var groupBox = group.querySelector('.map-group-checkbox');
|
||||
var boxes = group.querySelectorAll('.map-category-checkbox');
|
||||
if (!groupBox || boxes.length === 0) return;
|
||||
var checked = 0;
|
||||
boxes.forEach(function (box) { if (box.checked) checked++; });
|
||||
groupBox.checked = checked > 0;
|
||||
groupBox.indeterminate = checked > 0 && checked < boxes.length;
|
||||
}
|
||||
|
||||
document.querySelectorAll('.map-group-checkbox').forEach(function (groupBox) {
|
||||
groupBox.addEventListener('change', function () {
|
||||
var group = groupBox.closest('.map-group');
|
||||
group.querySelectorAll('.map-category-checkbox').forEach(function (box) {
|
||||
box.checked = groupBox.checked;
|
||||
visibleCategories[box.value] = box.checked;
|
||||
});
|
||||
groupBox.indeterminate = false;
|
||||
applyFilters();
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('.map-group-toggle').forEach(function (toggle) {
|
||||
toggle.addEventListener('click', function () {
|
||||
var group = toggle.closest('.map-group');
|
||||
var collapsed = group.classList.toggle('collapsed');
|
||||
toggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
|
||||
});
|
||||
});
|
||||
|
||||
function setAllCategories(checked) {
|
||||
document.querySelectorAll('.map-category-checkbox').forEach(function (box) {
|
||||
box.checked = checked;
|
||||
visibleCategories[box.value] = checked;
|
||||
});
|
||||
document.querySelectorAll('.map-group-checkbox').forEach(function (box) {
|
||||
box.checked = checked;
|
||||
box.indeterminate = false;
|
||||
});
|
||||
applyFilters();
|
||||
}
|
||||
|
||||
var showAllBtn = document.getElementById('map-show-all');
|
||||
var hideAllBtn = document.getElementById('map-hide-all');
|
||||
if (showAllBtn) showAllBtn.addEventListener('click', function () { setAllCategories(true); });
|
||||
if (hideAllBtn) hideAllBtn.addEventListener('click', function () { setAllCategories(false); });
|
||||
|
||||
var searchInput = document.getElementById('map-search');
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener('input', function () {
|
||||
searchTerm = searchInput.value.trim().toLowerCase();
|
||||
applyFilters();
|
||||
|
||||
// Kategorien, die nicht zur Suche passen, in der Sidebar ausblenden …
|
||||
document.querySelectorAll('.map-category').forEach(function (row) {
|
||||
var name = (row.getAttribute('data-name') || '').toLowerCase();
|
||||
row.hidden = searchTerm !== '' && name.indexOf(searchTerm) === -1
|
||||
&& !hasMatchingMarker(row.getAttribute('data-category-id'));
|
||||
});
|
||||
|
||||
// … und Gruppen, von denen dadurch nichts mehr uebrig bleibt, gleich mit.
|
||||
document.querySelectorAll('.map-group').forEach(function (group) {
|
||||
var visible = Array.prototype.some.call(
|
||||
group.querySelectorAll('.map-category'),
|
||||
function (row) { return !row.hidden; }
|
||||
);
|
||||
group.hidden = searchTerm !== '' && !visible;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function hasMatchingMarker(categoryId) {
|
||||
return Object.keys(markerById).some(function (id) {
|
||||
var entry = markerById[id];
|
||||
if (String(entry.data.category_id) !== String(categoryId)) return false;
|
||||
return (entry.data.name + ' ' + (entry.data.description || '')).toLowerCase().indexOf(searchTerm) !== -1;
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Sidebar-Reiter ----
|
||||
document.querySelectorAll('.map-tab').forEach(function (tab) {
|
||||
tab.addEventListener('click', function () {
|
||||
document.querySelectorAll('.map-tab').forEach(function (t) { t.classList.remove('active'); });
|
||||
tab.classList.add('active');
|
||||
document.querySelectorAll('.map-panel').forEach(function (panel) {
|
||||
panel.hidden = panel.getAttribute('data-panel') !== tab.getAttribute('data-panel');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
var mapSelect = document.getElementById('map-select');
|
||||
if (mapSelect) {
|
||||
mapSelect.addEventListener('change', function () {
|
||||
window.location.href = '/map.php?map=' + encodeURIComponent(mapSelect.value);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Modals
|
||||
// ---------------------------------------------------------------------
|
||||
function openModal(id) {
|
||||
var modal = document.getElementById(id);
|
||||
if (modal) modal.hidden = false;
|
||||
}
|
||||
function closeModal(id) {
|
||||
var modal = document.getElementById(id);
|
||||
if (!modal) return;
|
||||
modal.hidden = true;
|
||||
var feedback = modal.querySelector('.map-feedback');
|
||||
if (feedback) feedback.textContent = '';
|
||||
}
|
||||
document.querySelectorAll('.modal-overlay').forEach(function (overlay) {
|
||||
var closeBtn = overlay.querySelector('.modal-close');
|
||||
if (closeBtn) closeBtn.addEventListener('click', function () { overlay.hidden = true; });
|
||||
overlay.addEventListener('click', function (e) {
|
||||
if (e.target === overlay) overlay.hidden = true;
|
||||
});
|
||||
});
|
||||
|
||||
function feedback(formId, text, isError) {
|
||||
var form = document.getElementById(formId);
|
||||
if (!form) return;
|
||||
var el = form.querySelector('.map-feedback');
|
||||
if (!el) return;
|
||||
el.textContent = text || '';
|
||||
el.className = 'map-feedback text-muted' + (isError ? ' error' : '');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Marker setzen/bearbeiten
|
||||
// ---------------------------------------------------------------------
|
||||
var markerForm = document.getElementById('map-marker-form');
|
||||
var markerModalTitle = document.getElementById('map-marker-modal-title');
|
||||
var markerDeleteBtn = document.getElementById('map-marker-delete');
|
||||
var placingMarker = false;
|
||||
|
||||
var markerToolBtn = document.getElementById('map-tool-marker');
|
||||
if (markerToolBtn) {
|
||||
markerToolBtn.addEventListener('click', function () {
|
||||
placingMarker = !placingMarker;
|
||||
markerToolBtn.classList.toggle('active', placingMarker);
|
||||
document.getElementById('map-canvas').classList.toggle('map-placing', placingMarker);
|
||||
setStatus(placingMarker ? 'Klicke auf die Karte, um den Marker zu setzen (Esc bricht ab).' : '');
|
||||
});
|
||||
}
|
||||
|
||||
function openMarkerForm(marker, position) {
|
||||
if (!markerForm) return;
|
||||
markerForm.marker_id.value = marker ? marker.id : '';
|
||||
markerForm.name.value = marker ? marker.name : '';
|
||||
markerForm.description.value = marker ? (marker.description || '') : '';
|
||||
markerForm.x.value = marker ? marker.x : position[0];
|
||||
markerForm.y.value = marker ? marker.y : position[1];
|
||||
if (marker) markerForm.category_id.value = String(marker.category_id);
|
||||
markerModalTitle.textContent = marker ? 'Marker bearbeiten' : 'Marker anlegen';
|
||||
markerDeleteBtn.hidden = !marker;
|
||||
openModal('map-marker-modal');
|
||||
markerForm.name.focus();
|
||||
}
|
||||
|
||||
map.on('click', function (e) {
|
||||
if (!drawingShape && (!placingMarker || !canManage)) return;
|
||||
|
||||
if (!isInsideMap(e.latlng)) {
|
||||
setStatus('Dieser Punkt liegt außerhalb der Karte.', true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (drawingShape) { handleDrawClick(e); return; }
|
||||
openMarkerForm(null, toNormalized(e.latlng));
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', function (e) {
|
||||
var inField = /^(INPUT|TEXTAREA|SELECT)$/.test((e.target.tagName || '').toUpperCase());
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
if (placingMarker && markerToolBtn) markerToolBtn.click();
|
||||
if (drawingShape) cancelDrawing();
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' && !inField && drawingShape) {
|
||||
e.preventDefault();
|
||||
finishShape();
|
||||
}
|
||||
});
|
||||
|
||||
// Popup-Buttons entstehen erst beim Oeffnen des Popups, deshalb delegiert.
|
||||
document.addEventListener('click', function (e) {
|
||||
var editBtn = e.target.closest('.map-popup-edit');
|
||||
if (!editBtn) return;
|
||||
var entry = markerById[editBtn.getAttribute('data-marker-id')];
|
||||
if (entry) {
|
||||
map.closePopup();
|
||||
openMarkerForm(entry.data);
|
||||
}
|
||||
});
|
||||
|
||||
if (markerForm) {
|
||||
markerForm.addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
feedback('map-marker-form', 'Wird gespeichert …');
|
||||
|
||||
postJson({
|
||||
action: 'marker_save',
|
||||
marker_id: markerForm.marker_id.value,
|
||||
category_id: markerForm.category_id.value,
|
||||
name: markerForm.name.value,
|
||||
description: markerForm.description.value,
|
||||
x: parseFloat(markerForm.x.value),
|
||||
y: parseFloat(markerForm.y.value)
|
||||
}).then(function (result) {
|
||||
if (result.status !== 'success') {
|
||||
feedback('map-marker-form', result.message, true);
|
||||
return;
|
||||
}
|
||||
window.location.reload();
|
||||
}).catch(function () {
|
||||
feedback('map-marker-form', 'Verbindung fehlgeschlagen.', true);
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('map-marker-cancel').addEventListener('click', function () {
|
||||
closeModal('map-marker-modal');
|
||||
});
|
||||
|
||||
markerDeleteBtn.addEventListener('click', function () {
|
||||
if (!window.confirm('Diesen Marker wirklich löschen?')) return;
|
||||
postJson({ action: 'marker_delete', marker_id: markerForm.marker_id.value })
|
||||
.then(function (result) {
|
||||
if (result.status !== 'success') {
|
||||
feedback('map-marker-form', result.message, true);
|
||||
return;
|
||||
}
|
||||
removeMarker(markerForm.marker_id.value);
|
||||
closeModal('map-marker-modal');
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Kategorien
|
||||
// ---------------------------------------------------------------------
|
||||
var categoryForm = document.getElementById('map-category-form');
|
||||
var categoryDeleteBtn = document.getElementById('map-category-delete');
|
||||
|
||||
var seedBtn = document.getElementById('map-seed-categories');
|
||||
if (seedBtn) {
|
||||
seedBtn.addEventListener('click', function () {
|
||||
seedBtn.disabled = true;
|
||||
postJson({ action: 'category_seed' }).then(function (result) {
|
||||
if (result.status === 'success') {
|
||||
window.location.reload();
|
||||
} else {
|
||||
seedBtn.disabled = false;
|
||||
setStatus(result.message, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
var addCategoryBtn = document.getElementById('map-add-category');
|
||||
if (addCategoryBtn) {
|
||||
addCategoryBtn.addEventListener('click', function () {
|
||||
categoryForm.category_id.value = '';
|
||||
categoryForm.name.value = '';
|
||||
categoryForm.icon.value = '';
|
||||
categoryForm.color.value = '#c9a227';
|
||||
categoryForm.parent_id.value = '0';
|
||||
document.getElementById('map-category-modal-title').textContent = 'Kategorie anlegen';
|
||||
categoryDeleteBtn.hidden = true;
|
||||
openModal('map-category-modal');
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll('.map-category-edit').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
categoryForm.category_id.value = btn.getAttribute('data-category-id');
|
||||
categoryForm.name.value = btn.getAttribute('data-name') || '';
|
||||
categoryForm.icon.value = btn.getAttribute('data-icon') || '';
|
||||
categoryForm.color.value = btn.getAttribute('data-color') || '#c9a227';
|
||||
categoryForm.parent_id.value = btn.getAttribute('data-parent-id') || '0';
|
||||
document.getElementById('map-category-modal-title').textContent = 'Kategorie bearbeiten';
|
||||
categoryDeleteBtn.hidden = false;
|
||||
openModal('map-category-modal');
|
||||
});
|
||||
});
|
||||
|
||||
if (categoryForm) {
|
||||
categoryForm.addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
feedback('map-category-form', 'Wird gespeichert …');
|
||||
postJson({
|
||||
action: 'category_save',
|
||||
category_id: categoryForm.category_id.value,
|
||||
parent_id: categoryForm.parent_id.value,
|
||||
name: categoryForm.name.value,
|
||||
icon: categoryForm.icon.value,
|
||||
color: categoryForm.color.value
|
||||
}).then(function (result) {
|
||||
if (result.status !== 'success') {
|
||||
feedback('map-category-form', result.message, true);
|
||||
return;
|
||||
}
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('map-category-cancel').addEventListener('click', function () {
|
||||
closeModal('map-category-modal');
|
||||
});
|
||||
|
||||
categoryDeleteBtn.addEventListener('click', function () {
|
||||
if (!window.confirm('Kategorie mitsamt allen darin enthaltenen Markern löschen?')) return;
|
||||
postJson({ action: 'category_delete', category_id: categoryForm.category_id.value })
|
||||
.then(function (result) {
|
||||
if (result.status !== 'success') {
|
||||
feedback('map-category-form', result.message, true);
|
||||
return;
|
||||
}
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Taktiken: eigene Zeichenebene je Taktik (Punkte, Routen, Flaechen, Notizen)
|
||||
// ---------------------------------------------------------------------
|
||||
var tacticLayers = {}; // tactic_id -> L.FeatureGroup
|
||||
var tacticsById = {};
|
||||
var activeTacticId = null;
|
||||
var drawingShape = null; // aktuell gezeichneter Typ
|
||||
var drawPoints = [];
|
||||
var drawPreview = null;
|
||||
|
||||
data.tactics.forEach(function (tactic) {
|
||||
tacticsById[tactic.id] = tactic;
|
||||
tacticLayers[tactic.id] = L.featureGroup();
|
||||
tactic.shapes.forEach(function (shape) { drawShape(tactic.id, shape); });
|
||||
});
|
||||
|
||||
function shapeLatLngs(shape) {
|
||||
return shape.points.map(function (point) { return toLatLng(point[0], point[1]); });
|
||||
}
|
||||
|
||||
function drawShape(tacticId, shape) {
|
||||
var group = tacticLayers[tacticId];
|
||||
if (!group) return;
|
||||
var latlngs = shapeLatLngs(shape);
|
||||
var layer;
|
||||
|
||||
if (shape.type === 'route') {
|
||||
layer = L.polyline(latlngs, { color: shape.color, weight: 4, opacity: 0.9, dashArray: '10 6' });
|
||||
} else if (shape.type === 'area') {
|
||||
layer = L.polygon(latlngs, { color: shape.color, weight: 3, opacity: 0.9, fillOpacity: 0.2 });
|
||||
} else if (shape.type === 'text') {
|
||||
layer = L.marker(latlngs[0], {
|
||||
icon: L.divIcon({
|
||||
className: 'map-shape-text',
|
||||
html: '<span style="border-color:' + shape.color + '">' + escapeHtml(shape.label) + '</span>',
|
||||
iconSize: null
|
||||
})
|
||||
});
|
||||
} else {
|
||||
layer = L.marker(latlngs[0], {
|
||||
icon: L.divIcon({
|
||||
className: 'map-shape-point',
|
||||
html: '<span class="map-shape-dot" style="background:' + shape.color + '"></span>'
|
||||
+ (shape.label ? '<span class="map-shape-label">' + escapeHtml(shape.label) + '</span>' : ''),
|
||||
iconSize: null,
|
||||
iconAnchor: [9, 9]
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
if (shape.label && shape.type !== 'text' && shape.type !== 'point') {
|
||||
layer.bindTooltip(shape.label, { permanent: false, sticky: true });
|
||||
}
|
||||
|
||||
layer.shapeId = shape.id;
|
||||
layer.on('click', function (e) {
|
||||
if (!canTactics || activeTacticId !== tacticId || drawingShape) return;
|
||||
L.DomEvent.stopPropagation(e);
|
||||
if (window.confirm('Objekt "' + (shape.label || shape.type) + '" löschen?')) {
|
||||
postJson({ action: 'shape_delete', shape_id: shape.id }).then(function (result) {
|
||||
if (result.status === 'success') {
|
||||
group.removeLayer(layer);
|
||||
setStatus('Objekt gelöscht.');
|
||||
} else {
|
||||
setStatus(result.message, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
group.addLayer(layer);
|
||||
}
|
||||
|
||||
document.querySelectorAll('.map-tactic-checkbox').forEach(function (checkbox) {
|
||||
checkbox.addEventListener('change', function () {
|
||||
var group = tacticLayers[checkbox.value];
|
||||
if (!group) return;
|
||||
if (checkbox.checked) {
|
||||
group.addTo(map);
|
||||
} else {
|
||||
map.removeLayer(group);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Taktik anlegen/bearbeiten ----
|
||||
var tacticForm = document.getElementById('map-tactic-form');
|
||||
var tacticDeleteBtn = document.getElementById('map-tactic-delete');
|
||||
var tacticTools = document.getElementById('map-tactic-tools');
|
||||
var tacticActiveName = document.getElementById('map-tactic-active-name');
|
||||
|
||||
var addTacticBtn = document.getElementById('map-add-tactic');
|
||||
if (addTacticBtn) {
|
||||
addTacticBtn.addEventListener('click', function () {
|
||||
tacticForm.tactic_id.value = '';
|
||||
tacticForm.name.value = '';
|
||||
tacticForm.description.value = '';
|
||||
document.getElementById('map-tactic-modal-title').textContent = 'Taktik anlegen';
|
||||
tacticDeleteBtn.hidden = true;
|
||||
openModal('map-tactic-modal');
|
||||
tacticForm.name.focus();
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelectorAll('.map-tactic-edit').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var row = btn.closest('.map-tactic');
|
||||
var tactic = tacticsById[row.getAttribute('data-tactic-id')];
|
||||
if (!tactic) return;
|
||||
tacticForm.tactic_id.value = tactic.id;
|
||||
tacticForm.name.value = tactic.name;
|
||||
tacticForm.description.value = tactic.description || '';
|
||||
document.getElementById('map-tactic-modal-title').textContent = 'Taktik bearbeiten';
|
||||
tacticDeleteBtn.hidden = false;
|
||||
openModal('map-tactic-modal');
|
||||
});
|
||||
});
|
||||
|
||||
if (tacticForm) {
|
||||
tacticForm.addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
feedback('map-tactic-form', 'Wird gespeichert …');
|
||||
postJson({
|
||||
action: 'tactic_save',
|
||||
tactic_id: tacticForm.tactic_id.value,
|
||||
name: tacticForm.name.value,
|
||||
description: tacticForm.description.value
|
||||
}).then(function (result) {
|
||||
if (result.status !== 'success') {
|
||||
feedback('map-tactic-form', result.message, true);
|
||||
return;
|
||||
}
|
||||
// Eine frisch angelegte Taktik ist noch nicht im DOM - dafuer neu laden
|
||||
// und danach direkt in den Bearbeiten-Modus springen.
|
||||
if (!tacticForm.tactic_id.value) {
|
||||
window.location.href = '/map.php?map=' + encodeURIComponent(mapKey) + '&edit=' + result.tactic_id;
|
||||
return;
|
||||
}
|
||||
closeModal('map-tactic-modal');
|
||||
startTacticEditing(parseInt(tacticForm.tactic_id.value, 10));
|
||||
var row = document.querySelector('.map-tactic[data-tactic-id="' + tacticForm.tactic_id.value + '"] .map-tactic-name');
|
||||
if (row) row.textContent = tacticForm.name.value;
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('map-tactic-cancel').addEventListener('click', function () {
|
||||
closeModal('map-tactic-modal');
|
||||
});
|
||||
|
||||
tacticDeleteBtn.addEventListener('click', function () {
|
||||
if (!window.confirm('Diese Taktik mitsamt allen Objekten löschen?')) return;
|
||||
postJson({ action: 'tactic_delete', tactic_id: tacticForm.tactic_id.value })
|
||||
.then(function (result) {
|
||||
if (result.status !== 'success') {
|
||||
feedback('map-tactic-form', result.message, true);
|
||||
return;
|
||||
}
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function startTacticEditing(tacticId) {
|
||||
if (!canTactics || !tacticsById[tacticId]) return;
|
||||
activeTacticId = tacticId;
|
||||
|
||||
// Beim Bearbeiten muss die Ebene sichtbar sein, sonst zeichnet man ins Leere.
|
||||
var checkbox = document.querySelector('.map-tactic-checkbox[value="' + tacticId + '"]');
|
||||
if (checkbox && !checkbox.checked) {
|
||||
checkbox.checked = true;
|
||||
checkbox.dispatchEvent(new Event('change'));
|
||||
}
|
||||
if (!map.hasLayer(tacticLayers[tacticId])) tacticLayers[tacticId].addTo(map);
|
||||
|
||||
document.querySelectorAll('.map-tactic').forEach(function (row) {
|
||||
row.classList.toggle('editing', row.getAttribute('data-tactic-id') === String(tacticId));
|
||||
});
|
||||
|
||||
if (tacticTools) tacticTools.hidden = false;
|
||||
if (tacticActiveName) tacticActiveName.textContent = tacticsById[tacticId].name;
|
||||
setStatus('Taktik wird bearbeitet - Werkzeug wählen und auf die Karte klicken. Klick auf ein Objekt löscht es.');
|
||||
}
|
||||
|
||||
function stopTacticEditing() {
|
||||
activeTacticId = null;
|
||||
cancelDrawing();
|
||||
if (tacticTools) tacticTools.hidden = true;
|
||||
document.querySelectorAll('.map-tactic').forEach(function (row) { row.classList.remove('editing'); });
|
||||
setStatus('');
|
||||
}
|
||||
|
||||
var tacticCloseBtn = document.getElementById('map-tactic-close');
|
||||
if (tacticCloseBtn) tacticCloseBtn.addEventListener('click', stopTacticEditing);
|
||||
|
||||
document.querySelectorAll('#map-tactic-tools .map-tool[data-shape]').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var shape = btn.getAttribute('data-shape');
|
||||
if (drawingShape === shape) { cancelDrawing(); return; }
|
||||
cancelDrawing();
|
||||
drawingShape = shape;
|
||||
drawPoints = [];
|
||||
btn.classList.add('active');
|
||||
document.getElementById('map-canvas').classList.add('map-placing');
|
||||
if (finishBtn) finishBtn.hidden = shape !== 'route' && shape !== 'area';
|
||||
setStatus(shape === 'route' || shape === 'area'
|
||||
? 'Punkte anklicken, Doppelklick beendet die Form (Esc bricht ab).'
|
||||
: 'Auf die Karte klicken, um das Objekt zu setzen (Esc bricht ab).');
|
||||
});
|
||||
});
|
||||
|
||||
function cancelDrawing() {
|
||||
drawingShape = null;
|
||||
drawPoints = [];
|
||||
if (drawPreview) { map.removeLayer(drawPreview); drawPreview = null; }
|
||||
document.querySelectorAll('#map-tactic-tools .map-tool').forEach(function (b) { b.classList.remove('active'); });
|
||||
document.getElementById('map-canvas').classList.remove('map-placing');
|
||||
if (finishBtn) finishBtn.hidden = true;
|
||||
}
|
||||
|
||||
function currentColor() {
|
||||
var picker = document.getElementById('map-shape-color');
|
||||
return picker ? picker.value : '#c9a227';
|
||||
}
|
||||
|
||||
function handleDrawClick(e) {
|
||||
if (!activeTacticId) return;
|
||||
var position = toNormalized(e.latlng);
|
||||
|
||||
if (drawingShape === 'point' || drawingShape === 'text') {
|
||||
askForLabel(drawingShape, [position]);
|
||||
return;
|
||||
}
|
||||
|
||||
drawPoints.push(position);
|
||||
var latlngs = drawPoints.map(function (p) { return toLatLng(p[0], p[1]); });
|
||||
if (drawPreview) map.removeLayer(drawPreview);
|
||||
drawPreview = drawingShape === 'area'
|
||||
? L.polygon(latlngs, { color: currentColor(), weight: 2, dashArray: '4 4', fillOpacity: 0.12 })
|
||||
: L.polyline(latlngs, { color: currentColor(), weight: 3, dashArray: '4 4' });
|
||||
drawPreview.addTo(map);
|
||||
}
|
||||
|
||||
// Route/Flaeche abschliessen: per Doppelklick, ueber den Button oder mit Enter.
|
||||
// Doppelklick allein reicht nicht - auf Touch-Geraeten loest Doppeltippen kein
|
||||
// zuverlaessiges dblclick aus.
|
||||
function finishShape() {
|
||||
if (!drawingShape || (drawingShape !== 'route' && drawingShape !== 'area')) return;
|
||||
if (drawPoints.length < 2) {
|
||||
setStatus('Bitte mindestens zwei Punkte setzen.', true);
|
||||
return;
|
||||
}
|
||||
askForLabel(drawingShape, drawPoints.slice());
|
||||
}
|
||||
|
||||
map.on('dblclick', function (e) {
|
||||
if (!drawingShape || (drawingShape !== 'route' && drawingShape !== 'area')) return;
|
||||
L.DomEvent.stop(e);
|
||||
finishShape();
|
||||
});
|
||||
|
||||
var finishBtn = document.getElementById('map-shape-finish');
|
||||
if (finishBtn) finishBtn.addEventListener('click', finishShape);
|
||||
|
||||
// Beschriftung/Farbe kommen aus einem eigenen Popup statt aus window.prompt -
|
||||
// dieselbe Optik wie die uebrigen Dialoge der Seite.
|
||||
var shapeForm = document.getElementById('map-shape-form');
|
||||
var pendingShape = null;
|
||||
|
||||
function askForLabel(type, points) {
|
||||
pendingShape = { type: type, points: points };
|
||||
var labels = { point: 'Punkt beschriften', route: 'Route beschriften', area: 'Fläche beschriften', text: 'Notiz eingeben' };
|
||||
document.getElementById('map-shape-modal-title').textContent = labels[type] || 'Objekt beschriften';
|
||||
// Nur die Notiz besteht aus ihrem Text - bei allen anderen ist er optional.
|
||||
document.getElementById('map-shape-label-hint').textContent = type === 'text' ? '(erforderlich)' : '(optional)';
|
||||
shapeForm.label.value = '';
|
||||
shapeForm.color.value = currentColor();
|
||||
openModal('map-shape-modal');
|
||||
shapeForm.label.focus();
|
||||
}
|
||||
|
||||
if (shapeForm) {
|
||||
shapeForm.addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
if (!pendingShape) return;
|
||||
|
||||
var label = shapeForm.label.value.trim();
|
||||
if (pendingShape.type === 'text' && label === '') {
|
||||
feedback('map-shape-form', 'Bitte einen Text für die Notiz eingeben.', true);
|
||||
return;
|
||||
}
|
||||
|
||||
saveShape(pendingShape.type, label, pendingShape.points, shapeForm.color.value);
|
||||
pendingShape = null;
|
||||
closeModal('map-shape-modal');
|
||||
cancelDrawing();
|
||||
});
|
||||
|
||||
document.getElementById('map-shape-cancel').addEventListener('click', function () {
|
||||
pendingShape = null;
|
||||
closeModal('map-shape-modal');
|
||||
cancelDrawing();
|
||||
});
|
||||
|
||||
// Auch Schliessen ueber das X oder einen Klick neben das Popup bricht das
|
||||
// angefangene Zeichnen ab, damit kein Werkzeug aktiv haengen bleibt.
|
||||
document.getElementById('map-shape-modal').addEventListener('click', function (e) {
|
||||
if (e.target.id === 'map-shape-modal' || e.target.closest('.modal-close')) {
|
||||
pendingShape = null;
|
||||
cancelDrawing();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function saveShape(type, label, points, color) {
|
||||
postJson({
|
||||
action: 'shape_save',
|
||||
tactic_id: activeTacticId,
|
||||
type: type,
|
||||
label: label,
|
||||
color: color,
|
||||
points: points
|
||||
}).then(function (result) {
|
||||
if (result.status !== 'success') {
|
||||
setStatus(result.message, true);
|
||||
return;
|
||||
}
|
||||
var shape = { id: result.shape_id, type: type, label: label, color: color, points: points };
|
||||
tacticsById[activeTacticId].shapes.push(shape);
|
||||
drawShape(activeTacticId, shape);
|
||||
setStatus('Objekt gespeichert.');
|
||||
}).catch(function () {
|
||||
setStatus('Verbindung fehlgeschlagen.', true);
|
||||
});
|
||||
}
|
||||
|
||||
// Nach dem Anlegen einer Taktik landet man per ?edit=<id> direkt im Bearbeiten-Modus.
|
||||
var editParam = new URLSearchParams(window.location.search).get('edit');
|
||||
if (editParam) {
|
||||
document.querySelector('.map-tab[data-panel="tactics"]').click();
|
||||
startTacticEditing(parseInt(editParam, 10));
|
||||
}
|
||||
})();
|
||||
|
|
@ -1,387 +0,0 @@
|
|||
(function () {
|
||||
'use strict';
|
||||
|
||||
var panel = document.getElementById('map-build');
|
||||
if (!panel) return;
|
||||
|
||||
var csrfToken = (document.querySelector('meta[name="csrf-token"]') || {}).content || '';
|
||||
|
||||
var fileInput = document.getElementById('map-build-file');
|
||||
var keyInput = document.getElementById('map-build-key');
|
||||
var nameInput = document.getElementById('map-build-name');
|
||||
var qualityInput = document.getElementById('map-build-quality');
|
||||
var startBtn = document.getElementById('map-build-start');
|
||||
var abortBtn = document.getElementById('map-build-abort');
|
||||
var dropZone = document.getElementById('map-build-drop');
|
||||
var infoEl = document.getElementById('map-build-info');
|
||||
var progressBar = document.getElementById('map-build-bar');
|
||||
var progressText = document.getElementById('map-build-progress');
|
||||
|
||||
var TILE_SIZE = 256;
|
||||
var BATCH_SIZE = 12; // Kacheln je Upload-Anfrage
|
||||
var PARALLEL_UPLOADS = 3;
|
||||
var BACKGROUND = '#14161a'; // wie bei tools/make_map_tiles.php
|
||||
|
||||
var selectedFile = null;
|
||||
var cancelled = false;
|
||||
var running = false;
|
||||
|
||||
function setInfo(text, kind) {
|
||||
infoEl.textContent = text || '';
|
||||
infoEl.className = 'map-build-info text-muted' + (kind ? ' ' + kind : '');
|
||||
}
|
||||
|
||||
function setProgress(done, total, label) {
|
||||
var percent = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||
progressBar.style.width = percent + '%';
|
||||
progressText.textContent = label || (percent + '% · ' + done + ' / ' + total + ' Kacheln');
|
||||
}
|
||||
|
||||
/** Zoomstufen wie in tools/make_map_tiles.php: oberste Stufe = Originalgröße. */
|
||||
function maxZoomFor(width, height) {
|
||||
return Math.max(0, Math.ceil(Math.log2(Math.max(width, height) / TILE_SIZE)));
|
||||
}
|
||||
|
||||
function tileCount(width, height, maxZoom) {
|
||||
var total = 0;
|
||||
for (var z = 0; z <= maxZoom; z++) {
|
||||
var scale = Math.pow(2, z - maxZoom);
|
||||
var lw = Math.max(1, Math.round(width * scale));
|
||||
var lh = Math.max(1, Math.round(height * scale));
|
||||
total += Math.ceil(lw / TILE_SIZE) * Math.ceil(lh / TILE_SIZE);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function describe(file, image) {
|
||||
var maxZoom = maxZoomFor(image.width, image.height);
|
||||
var tiles = tileCount(image.width, image.height, maxZoom);
|
||||
var megapixel = (image.width * image.height / 1e6).toFixed(1);
|
||||
|
||||
var text = image.width + ' x ' + image.height + ' Pixel (' + megapixel + ' MP) · '
|
||||
+ 'Zoomstufen 0 bis ' + maxZoom + ' · ' + tiles + ' Kacheln';
|
||||
|
||||
if (Math.max(image.width, image.height) < 4000) {
|
||||
setInfo(text + '\nHinweis: unter 4000 Pixel Kantenlänge wird die Karte beim '
|
||||
+ 'Heranzoomen unscharf. Für ein scharfes Ergebnis die Ingame-Karte '
|
||||
+ 'herangezoomt in Bahnen abfotografieren und vorher zusammensetzen.', 'warn');
|
||||
} else {
|
||||
setInfo(text);
|
||||
}
|
||||
|
||||
return { maxZoom: maxZoom, tiles: tiles };
|
||||
}
|
||||
|
||||
// ---- Datei auswählen ----
|
||||
|
||||
function selectFile(file) {
|
||||
if (!file) return;
|
||||
if (!/^image\//.test(file.type)) {
|
||||
setInfo('Das ist keine Bilddatei.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
selectedFile = file;
|
||||
startBtn.disabled = true;
|
||||
setInfo('Bild wird gelesen …');
|
||||
|
||||
loadImage(file).then(function (image) {
|
||||
selectedFile.image = image;
|
||||
describe(file, image);
|
||||
startBtn.disabled = false;
|
||||
|
||||
if (keyInput.value.trim() === '') {
|
||||
// Dateiname als Vorschlag für den Kartenschlüssel
|
||||
keyInput.value = file.name.replace(/\.[^.]+$/, '')
|
||||
.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48);
|
||||
}
|
||||
if (nameInput.value.trim() === '' && keyInput.value !== '') {
|
||||
nameInput.value = keyInput.value.charAt(0).toUpperCase() + keyInput.value.slice(1);
|
||||
}
|
||||
}).catch(function () {
|
||||
setInfo('Das Bild konnte nicht gelesen werden. Unterstützt werden PNG, JPEG und WebP.', 'error');
|
||||
});
|
||||
}
|
||||
|
||||
function loadImage(file) {
|
||||
// createImageBitmap kommt ohne DOM-Bild aus und ist bei sehr großen Dateien
|
||||
// deutlich sparsamer; der Weg über <img> bleibt als Rückfall.
|
||||
if (typeof createImageBitmap === 'function') {
|
||||
return createImageBitmap(file);
|
||||
}
|
||||
return new Promise(function (resolve, reject) {
|
||||
var url = URL.createObjectURL(file);
|
||||
var img = new Image();
|
||||
img.onload = function () { URL.revokeObjectURL(url); resolve(img); };
|
||||
img.onerror = function () { URL.revokeObjectURL(url); reject(new Error('decode')); };
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
fileInput.addEventListener('change', function () {
|
||||
selectFile(fileInput.files && fileInput.files[0]);
|
||||
});
|
||||
|
||||
['dragenter', 'dragover'].forEach(function (type) {
|
||||
dropZone.addEventListener(type, function (e) {
|
||||
e.preventDefault();
|
||||
dropZone.classList.add('dragging');
|
||||
});
|
||||
});
|
||||
['dragleave', 'drop'].forEach(function (type) {
|
||||
dropZone.addEventListener(type, function (e) {
|
||||
e.preventDefault();
|
||||
dropZone.classList.remove('dragging');
|
||||
});
|
||||
});
|
||||
dropZone.addEventListener('drop', function (e) {
|
||||
selectFile(e.dataTransfer.files && e.dataTransfer.files[0]);
|
||||
});
|
||||
|
||||
// ---- Kacheln schneiden ----
|
||||
|
||||
/**
|
||||
* Erzeugt die Kacheln einer Zoomstufe aus einer Vorlage.
|
||||
*
|
||||
* Die oberste Stufe wird direkt aus dem Originalbild geschnitten (kein Zwischenbild,
|
||||
* das sonst so groß wie das Original wäre und bei großen Karten die Canvas-Grenzen
|
||||
* des Browsers sprengt). Jede weitere Stufe entsteht durch Halbieren der vorherigen -
|
||||
* das liefert saubere Verkleinerungen ohne Treppeneffekte.
|
||||
*/
|
||||
function cutLevel(source, levelWidth, levelHeight, z, quality, onTile) {
|
||||
var cols = Math.ceil(levelWidth / TILE_SIZE);
|
||||
var rows = Math.ceil(levelHeight / TILE_SIZE);
|
||||
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.width = TILE_SIZE;
|
||||
canvas.height = TILE_SIZE;
|
||||
var ctx = canvas.getContext('2d');
|
||||
|
||||
var chain = Promise.resolve();
|
||||
for (var x = 0; x < cols; x++) {
|
||||
for (var y = 0; y < rows; y++) {
|
||||
(function (tx, ty) {
|
||||
chain = chain.then(function () {
|
||||
if (cancelled) return;
|
||||
|
||||
// Randkacheln auf volle Größe auffüllen, damit der Betrachter
|
||||
// sie nicht verzerrt (gleiche Farbe wie das CLI-Werkzeug).
|
||||
ctx.fillStyle = BACKGROUND;
|
||||
ctx.fillRect(0, 0, TILE_SIZE, TILE_SIZE);
|
||||
|
||||
var sw = Math.min(TILE_SIZE, levelWidth - tx * TILE_SIZE);
|
||||
var sh = Math.min(TILE_SIZE, levelHeight - ty * TILE_SIZE);
|
||||
ctx.drawImage(source, tx * TILE_SIZE, ty * TILE_SIZE, sw, sh, 0, 0, sw, sh);
|
||||
|
||||
return new Promise(function (resolve) {
|
||||
canvas.toBlob(function (blob) {
|
||||
onTile(z, tx, ty, blob).then(resolve, resolve);
|
||||
}, 'image/jpeg', quality);
|
||||
});
|
||||
});
|
||||
})(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
return chain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verkleinert eine Vorlage auf genau die Maße der nächstgröberen Zoomstufe.
|
||||
*
|
||||
* Die Zielmaße kommen aus derselben Formel wie in tools/make_map_tiles.php
|
||||
* (round(Originalmaß * 2^(z - maxZoom))), damit beide Wege dieselbe Pyramide
|
||||
* erzeugen. Verkleinert wird immer nur um den Faktor zwei von der vorherigen Stufe
|
||||
* aus - das liefert saubere Ergebnisse ohne Treppeneffekte.
|
||||
*/
|
||||
function levelSize(width, height, z, maxZoom) {
|
||||
var scale = Math.pow(2, z - maxZoom);
|
||||
return {
|
||||
width: Math.max(1, Math.round(width * scale)),
|
||||
height: Math.max(1, Math.round(height * scale))
|
||||
};
|
||||
}
|
||||
|
||||
function resizeTo(source, width, height) {
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
var ctx = canvas.getContext('2d');
|
||||
ctx.imageSmoothingEnabled = true;
|
||||
ctx.imageSmoothingQuality = 'high';
|
||||
ctx.drawImage(source, 0, 0, width, height);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
// ---- Hochladen ----
|
||||
|
||||
function postForm(data) {
|
||||
data.append('csrf_token', csrfToken);
|
||||
return fetch('/map_build_action.php', { method: 'POST', body: data })
|
||||
.then(function (r) { return r.json(); });
|
||||
}
|
||||
|
||||
function uploadBatch(key, batch) {
|
||||
var data = new FormData();
|
||||
data.append('action', 'tiles');
|
||||
data.append('key', key);
|
||||
batch.forEach(function (tile) {
|
||||
data.append('coords[]', tile.z + '_' + tile.x + '_' + tile.y);
|
||||
data.append('tile[]', tile.blob, tile.z + '_' + tile.x + '_' + tile.y + '.jpg');
|
||||
});
|
||||
return postForm(data);
|
||||
}
|
||||
|
||||
// ---- Ablauf ----
|
||||
|
||||
function build() {
|
||||
var file = selectedFile;
|
||||
var image = file.image;
|
||||
var key = keyInput.value.trim().toLowerCase();
|
||||
var quality = Math.min(100, Math.max(40, parseInt(qualityInput.value, 10) || 88)) / 100;
|
||||
|
||||
if (!/^[a-z0-9][a-z0-9_-]{0,48}$/.test(key)) {
|
||||
setInfo('Der Kartenschlüssel darf nur Kleinbuchstaben, Ziffern, - und _ enthalten.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
var maxZoom = maxZoomFor(image.width, image.height);
|
||||
var total = tileCount(image.width, image.height, maxZoom);
|
||||
var done = 0;
|
||||
|
||||
cancelled = false;
|
||||
running = true;
|
||||
startBtn.disabled = true;
|
||||
abortBtn.hidden = false;
|
||||
panel.classList.add('building');
|
||||
setProgress(0, total, 'Wird vorbereitet …');
|
||||
|
||||
var pending = [];
|
||||
var uploads = [];
|
||||
|
||||
function flush(force) {
|
||||
while (pending.length >= BATCH_SIZE || (force && pending.length > 0)) {
|
||||
var batch = pending.splice(0, BATCH_SIZE);
|
||||
var job = uploadBatch(key, batch).then(function (result) {
|
||||
if (result.status !== 'success') throw new Error(result.message || 'Upload fehlgeschlagen.');
|
||||
done += batch.length;
|
||||
setProgress(done, total);
|
||||
});
|
||||
uploads.push(job);
|
||||
}
|
||||
// Nicht unbegrenzt viele Anfragen gleichzeitig offen halten.
|
||||
if (uploads.length >= PARALLEL_UPLOADS) {
|
||||
var waiting = uploads;
|
||||
uploads = [];
|
||||
return Promise.all(waiting);
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
function onTile(z, x, y, blob) {
|
||||
if (cancelled || !blob) return Promise.resolve();
|
||||
pending.push({ z: z, x: x, y: y, blob: blob });
|
||||
return flush(false);
|
||||
}
|
||||
|
||||
var data = new FormData();
|
||||
data.append('action', 'begin');
|
||||
data.append('key', key);
|
||||
data.append('name', nameInput.value.trim());
|
||||
data.append('width', image.width);
|
||||
data.append('height', image.height);
|
||||
data.append('tile_size', TILE_SIZE);
|
||||
data.append('max_zoom', maxZoom);
|
||||
|
||||
postForm(data).then(function (result) {
|
||||
if (result.status !== 'success') throw new Error(result.message);
|
||||
|
||||
// Von der feinsten Stufe abwärts: die oberste Stufe wird direkt aus dem
|
||||
// Originalbild geschnitten, jede gröbere aus der jeweils vorherigen.
|
||||
//
|
||||
// Wichtig: Vorlage und Maße dürfen NICHT beim Aufbau der Kette eingefangen
|
||||
// werden - zu dem Zeitpunkt zeigen sie noch auf das Original, verkleinert
|
||||
// wird ja erst beim Abarbeiten. Deshalb stehen sie außen und werden in
|
||||
// jedem Schritt frisch gelesen.
|
||||
var chain = Promise.resolve();
|
||||
var source = image;
|
||||
var levelWidth = image.width;
|
||||
var levelHeight = image.height;
|
||||
|
||||
for (var z = maxZoom; z >= 0; z--) {
|
||||
(function (level) {
|
||||
chain = chain.then(function () {
|
||||
if (cancelled) return;
|
||||
|
||||
if (level !== maxZoom) {
|
||||
var size = levelSize(image.width, image.height, level, maxZoom);
|
||||
source = resizeTo(source, size.width, size.height);
|
||||
levelWidth = size.width;
|
||||
levelHeight = size.height;
|
||||
}
|
||||
|
||||
setProgress(done, total, 'Zoomstufe ' + level + ' · ' + done + ' / ' + total + ' Kacheln');
|
||||
return cutLevel(source, levelWidth, levelHeight, level, quality, onTile);
|
||||
});
|
||||
})(z);
|
||||
}
|
||||
|
||||
return chain;
|
||||
}).then(function () {
|
||||
if (cancelled) return null;
|
||||
return flush(true).then(function () { return Promise.all(uploads); });
|
||||
}).then(function () {
|
||||
if (cancelled) return null;
|
||||
var finish = new FormData();
|
||||
finish.append('action', 'finish');
|
||||
finish.append('key', key);
|
||||
return postForm(finish);
|
||||
}).then(function (result) {
|
||||
if (cancelled) return;
|
||||
if (!result || result.status !== 'success') throw new Error((result && result.message) || 'Abschluss fehlgeschlagen.');
|
||||
setProgress(total, total, 'Fertig - Seite wird neu geladen …');
|
||||
setTimeout(function () {
|
||||
window.location.href = '/map.php?map=' + encodeURIComponent(key);
|
||||
}, 900);
|
||||
}).catch(function (err) {
|
||||
setInfo(err.message || 'Das Bauen ist fehlgeschlagen.', 'error');
|
||||
setProgress(0, total, '');
|
||||
abort(true);
|
||||
});
|
||||
}
|
||||
|
||||
function abort(silent) {
|
||||
cancelled = true;
|
||||
running = false;
|
||||
startBtn.disabled = false;
|
||||
abortBtn.hidden = true;
|
||||
panel.classList.remove('building');
|
||||
|
||||
var key = keyInput.value.trim().toLowerCase();
|
||||
if (!/^[a-z0-9][a-z0-9_-]{0,48}$/.test(key)) return;
|
||||
|
||||
var data = new FormData();
|
||||
data.append('action', 'abort');
|
||||
data.append('key', key);
|
||||
postForm(data).then(function (result) {
|
||||
if (!silent && result.status === 'success') setInfo(result.message);
|
||||
});
|
||||
}
|
||||
|
||||
startBtn.addEventListener('click', function () {
|
||||
if (!selectedFile || !selectedFile.image) {
|
||||
setInfo('Bitte zuerst ein Bild auswählen.', 'error');
|
||||
return;
|
||||
}
|
||||
build();
|
||||
});
|
||||
|
||||
abortBtn.addEventListener('click', function () { abort(false); });
|
||||
|
||||
// Beim Verlassen der Seite warnen, solange noch hochgeladen wird.
|
||||
window.addEventListener('beforeunload', function (e) {
|
||||
if (!running) return;
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
});
|
||||
})();
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
# Hochgeladene Kartenkacheln duerfen niemals als Skript ausgefuehrt werden -
|
||||
# der Ordner wird per FTP befuellt und enthaelt ausschliesslich Bilder/JSON.
|
||||
# Die Kartendateien duerfen niemals als Skript ausgefuehrt werden -
|
||||
# der Ordner enthaelt nur den statischen Viewer mit Bildern/JSON.
|
||||
<IfModule mod_php.c>
|
||||
php_flag engine off
|
||||
</IfModule>
|
||||
151
assets/map/README.md
Normal file
151
assets/map/README.md
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
# Aion 2 Interactive Map Viewer (SecondTry)
|
||||
|
||||
A modern, multi-map interactive viewer for Aion 2 maps from [interactivemap.app](https://interactivemap.app/aion2/maps).
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-map support**: View all available Aion 2 maps with easy map switching
|
||||
- **Tile-based rendering**: Efficient canvas rendering with tile caching and preloading
|
||||
- **Marker overlay**: Display thousands of markers with category filtering
|
||||
- **Zoom & pan**: Smooth navigation with mouse wheel, drag, and keyboard shortcuts
|
||||
- **Category filters**: Toggle visibility of marker categories by group or individually
|
||||
- **Tooltips**: Hover over markers to see details
|
||||
|
||||
## Architecture
|
||||
|
||||
This implementation follows MVC (Model-View-Controller) pattern:
|
||||
|
||||
```
|
||||
SecondTry/
|
||||
├── index.html # Main HTML page
|
||||
├── styles.css # Stylesheet with CSS variables
|
||||
├── app.js # Application entry point
|
||||
├── js/
|
||||
│ ├── config.js # Configuration constants
|
||||
│ ├── models/
|
||||
│ │ └── MapData.js # Data model for maps and markers
|
||||
│ ├── services/
|
||||
│ │ ├── TileService.js # Tile loading and caching
|
||||
│ │ └── MarkerService.js # Marker data management
|
||||
│ ├── views/
|
||||
│ │ └── MapView.js # Canvas rendering
|
||||
│ └── controllers/
|
||||
│ └── MapController.js # Main application controller
|
||||
├── scripts/
|
||||
│ ├── download_all_maps.py # Download tiles for all maps
|
||||
│ ├── download_marker_icons.py # Download marker icon graphics
|
||||
│ └── extract_all_markers.py # Extract markers for all maps
|
||||
└── data/
|
||||
├── maps.json # List of all available maps (generated by download script)
|
||||
├── icons/ # Marker icon graphics (downloaded)
|
||||
│ ├── icon-poi.png
|
||||
│ ├── aldelle-village.png
|
||||
│ └── ...
|
||||
├── tiles/ # Per-map tile directories
|
||||
│ ├── verteron/
|
||||
│ ├── elysea/
|
||||
│ └── ...
|
||||
└── markers/ # Per-map marker JSON files
|
||||
├── verteron_markers.json
|
||||
├── elysea_markers.json
|
||||
└── ...
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
### 1. Download Map Data
|
||||
|
||||
Run the Python scripts to download tiles and extract markers:
|
||||
|
||||
```bash
|
||||
# Download all map tiles (zoom levels 2-6)
|
||||
python scripts/download_all_maps.py
|
||||
|
||||
# Extract markers for all maps
|
||||
python scripts/extract_all_markers.py
|
||||
|
||||
# Download marker icon graphics
|
||||
python scripts/download_marker_icons.py
|
||||
|
||||
# Or for a specific map only
|
||||
python scripts/download_all_maps.py --map verteron
|
||||
python scripts/extract_all_markers.py --map verteron
|
||||
```
|
||||
|
||||
The download script automatically generates `data/maps.json` which lists all available maps. This local file is used by the viewer instead of calling the remote API directly (avoids CORS issues).
|
||||
|
||||
### 2. Serve the Viewer
|
||||
|
||||
The viewer requires a local web server due to CORS restrictions on fetch requests:
|
||||
|
||||
```bash
|
||||
# Using Python's built-in HTTP server
|
||||
cd SecondTry
|
||||
python -m http.server 8080
|
||||
|
||||
# Or using Node.js
|
||||
npx serve . -p 8080
|
||||
```
|
||||
|
||||
Then open `http://localhost:8080` in your browser.
|
||||
|
||||
## Controls
|
||||
|
||||
| Action | Control |
|
||||
|--------|---------|
|
||||
| Zoom In | Mouse wheel up, `+` key, or + button |
|
||||
| Zoom Out | Mouse wheel down, `-` key, or − button |
|
||||
| Pan | Click and drag |
|
||||
| Reset View | `0` key or ⟲ button |
|
||||
| Switch Map | Use the dropdown selector at top |
|
||||
| Filter Categories | Checkboxes in bottom-left panel |
|
||||
|
||||
## Data Format
|
||||
|
||||
### Tile Manifest (`tile_manifest.json`)
|
||||
```json
|
||||
{
|
||||
"tiles": ["2_0_0", "2_0_1", "3_1_2", ...]
|
||||
}
|
||||
```
|
||||
|
||||
### Marker Data (`<slug>_markers.json`)
|
||||
```json
|
||||
{
|
||||
"source": "https://interactivemap.app/aion2/maps/verteron",
|
||||
"extracted_at_utc": "2026-09-20T12:12:39Z",
|
||||
"map": {
|
||||
"id": "1",
|
||||
"name": "Verteron",
|
||||
"slug": "verteron"
|
||||
},
|
||||
"marker_count": 14729,
|
||||
"markers": [
|
||||
{
|
||||
"id": "34739",
|
||||
"name": "Point of Interest",
|
||||
"group_name": "Community",
|
||||
"category_name": "Point of Interest",
|
||||
"coordinates": [1505.46, 1585.43],
|
||||
"properties": { ... }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Improvements Over FirstTry
|
||||
|
||||
- **Multi-map support**: Not limited to a single map (Verteron/Elysea)
|
||||
- **MVC architecture**: Clean separation of concerns with proper OOP classes
|
||||
- **Service layer**: Dedicated services for tile and marker management
|
||||
- **Local maps list**: Generates `data/maps.json` to avoid CORS issues when loading from localhost
|
||||
- **Real icon graphics**: Downloads and displays actual marker icons instead of emoji symbols
|
||||
- **Better error handling**: Graceful fallbacks when data is missing
|
||||
- **Loading states**: Visual feedback during map loading
|
||||
- **Modular CSS**: Uses CSS variables for easy theming
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Python 3 (standard library only) for download scripts
|
||||
- Modern web browser with ES6+ support
|
||||
- No external JavaScript libraries required
|
||||
8
assets/map/app.js
Normal file
8
assets/map/app.js
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/**
|
||||
* Aion 2 Map Viewer - Application Entry Point
|
||||
*/
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const controller = new MapController();
|
||||
controller.init();
|
||||
});
|
||||
67
assets/map/index.html
Normal file
67
assets/map/index.html
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Aion 2 - Interactive Map Viewer</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<!-- Main map container -->
|
||||
<div id="map-container">
|
||||
<canvas id="map-canvas"></canvas>
|
||||
|
||||
<!-- Loading overlay -->
|
||||
<div id="loading-overlay" class="hidden">
|
||||
<div class="spinner"></div>
|
||||
<p>Loading map data...</p>
|
||||
</div>
|
||||
|
||||
<!-- UI Overlay -->
|
||||
<div id="ui-overlay">
|
||||
<!-- Title bar with map selector -->
|
||||
<header id="title-bar" class="panel">
|
||||
<h1>Aion 2</h1>
|
||||
<div class="map-selector-container">
|
||||
<select id="map-select" aria-label="Select map">
|
||||
<option value="">Loading maps...</option>
|
||||
</select>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Zoom controls -->
|
||||
<aside id="zoom-controls" class="panel">
|
||||
<button id="btn-zoom-in" title="Zoom In (+)">+</button>
|
||||
<button id="btn-zoom-out" title="Zoom Out (-)">−</button>
|
||||
<button id="btn-reset-view" title="Reset View (0)">⟲</button>
|
||||
</aside>
|
||||
|
||||
<!-- Category filter panel -->
|
||||
<aside id="category-panel" class="panel">
|
||||
<h3>Categories</h3>
|
||||
<div id="categories-list"></div>
|
||||
</aside>
|
||||
|
||||
<!-- Zoom level indicator -->
|
||||
<footer id="zoom-indicator" class="panel">
|
||||
Zoom: <span id="zoom-level">2</span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<!-- Tooltip for marker hover -->
|
||||
<div id="tooltip" class="hidden">
|
||||
<div class="name"></div>
|
||||
<div class="category"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Application scripts -->
|
||||
<script src="js/config.js"></script>
|
||||
<script src="js/models/MapData.js"></script>
|
||||
<script src="js/services/TileService.js"></script>
|
||||
<script src="js/services/MarkerService.js"></script>
|
||||
<script src="js/views/MapView.js"></script>
|
||||
<script src="js/controllers/MapController.js"></script>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
99
assets/map/js/config.js
Normal file
99
assets/map/js/config.js
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
/**
|
||||
* Aion 2 Map Viewer - Configuration
|
||||
*/
|
||||
|
||||
const CONFIG = {
|
||||
// Tile settings
|
||||
TILE_SIZE: 256,
|
||||
MIN_ZOOM: 2,
|
||||
MAX_ZOOM: 6,
|
||||
|
||||
// World coordinate system (fixed for all maps)
|
||||
WORLD_MIN_X: 0,
|
||||
WORLD_MAX_X: 4096,
|
||||
WORLD_MIN_Y: 0,
|
||||
WORLD_MAX_Y: 4096,
|
||||
|
||||
// Data paths
|
||||
TILES_DIR: 'data/tiles',
|
||||
MARKERS_DIR: 'data/markers',
|
||||
ICONS_DIR: 'data/icons',
|
||||
|
||||
// Local maps list (generated by download scripts to avoid CORS)
|
||||
MAPS_LIST: 'data/maps.json',
|
||||
|
||||
// Category symbols (emoji)
|
||||
CATEGORY_SYMBOLS: {
|
||||
'Settlement': '🏘️',
|
||||
'Stronghold': '🏰',
|
||||
'Dungeon': '🕳️',
|
||||
'Sealed Dungeon': '🔒',
|
||||
'Region': '🗺️',
|
||||
'Updraft': '💨',
|
||||
'Rift': '⚡',
|
||||
'Kibelisk': '🐉',
|
||||
'Verteron Monolith': '🗿',
|
||||
|
||||
'Intellect': '🧠',
|
||||
'Wild Monsters': '🐺',
|
||||
'Feral': '🦁',
|
||||
'Nature': '🌿',
|
||||
'Special': '✨',
|
||||
'Named Bosses': '💀',
|
||||
|
||||
'Citizens': '👤',
|
||||
'NPC': '🗣️',
|
||||
'General Goods Merchant': '🛒',
|
||||
'Events': '🎉',
|
||||
'Instance Entries': '🚪',
|
||||
'Storage Manager': '📦',
|
||||
'Alchemy Table': '⚗️',
|
||||
'Armorsmithing Table': '🛡️',
|
||||
'Blacksmithing Table': '⚒️',
|
||||
'Cooking Table': '🍳',
|
||||
'Handicrafting': '✂️',
|
||||
'Morph Merchant': '🔄',
|
||||
|
||||
'Odyle': '💎',
|
||||
'Orihalum Ore': '⛏️',
|
||||
'Sapphire Gemstone': '💠',
|
||||
'Diamond Gemstone': '💎',
|
||||
'Ruby Gemstone': '❤️',
|
||||
'Aria': '🌸',
|
||||
'Yggdrasil Log': '🪵',
|
||||
'Targena': '🍄',
|
||||
'Kukuru': '🥜',
|
||||
'Cypri': '🫐',
|
||||
'Inina': '🌺',
|
||||
'Coriolus': '🍂',
|
||||
'Mela': '🍇',
|
||||
|
||||
'Empyrean Trace': '🔮',
|
||||
'Hidden Cube': '📦',
|
||||
'Boss': '👑',
|
||||
|
||||
'Fera': '🐾',
|
||||
'Natura': '🌱',
|
||||
'Cogni': '🤖',
|
||||
'Varian': '🎭',
|
||||
|
||||
'Story Quests': '📜',
|
||||
'Regional Quest': '🏴',
|
||||
|
||||
'Spawn Location': '🥚',
|
||||
'Point of Interest': '⭐'
|
||||
},
|
||||
|
||||
// Category colors by group
|
||||
CATEGORY_COLORS: {
|
||||
'Locations': '#3388FF',
|
||||
'Monsters': '#FF4444',
|
||||
'NPC': '#44AA44',
|
||||
'Resources': '#FFAA00',
|
||||
'Collectibles': '#AA44FF',
|
||||
'Pets': '#FF66CC',
|
||||
'Quests': '#FFFF44',
|
||||
'Spawns': '#44AAAA',
|
||||
'Community': '#FFFFFF'
|
||||
}
|
||||
};
|
||||
402
assets/map/js/controllers/MapController.js
Normal file
402
assets/map/js/controllers/MapController.js
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
/**
|
||||
* MapController - Main controller for the map viewer application
|
||||
*/
|
||||
|
||||
class MapController {
|
||||
constructor() {
|
||||
this.mapData = new MapData();
|
||||
this.tileService = new TileService();
|
||||
this.markerService = new MarkerService();
|
||||
|
||||
// DOM elements
|
||||
this.canvas = document.getElementById('map-canvas');
|
||||
this.mapSelect = document.getElementById('map-select');
|
||||
this.categoriesList = document.getElementById('categories-list');
|
||||
this.zoomLevelEl = document.getElementById('zoom-level');
|
||||
this.loadingOverlay = document.getElementById('loading-overlay');
|
||||
this.tooltip = document.getElementById('tooltip');
|
||||
|
||||
// Initialize view
|
||||
this.view = new MapView(this.canvas);
|
||||
this.view.resize();
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
this.view.resize();
|
||||
this.render();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the application
|
||||
*/
|
||||
async init() {
|
||||
this.showLoading(true);
|
||||
|
||||
try {
|
||||
// Discover available maps
|
||||
await this.discoverMaps();
|
||||
|
||||
// Load first map by default
|
||||
if (this.mapData.maps.length > 0) {
|
||||
const firstMap = this.mapData.maps[0];
|
||||
this.mapSelect.value = firstMap.slug;
|
||||
await this.loadMap(firstMap.slug);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to initialize:', e);
|
||||
} finally {
|
||||
this.showLoading(false);
|
||||
}
|
||||
|
||||
// Setup event listeners
|
||||
this.setupEventListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover available maps from local maps.json file
|
||||
*/
|
||||
async discoverMaps() {
|
||||
try {
|
||||
const response = await fetch(CONFIG.MAPS_LIST);
|
||||
if (!response.ok) throw new Error('maps.json not found');
|
||||
|
||||
const data = await response.json();
|
||||
const maps = data.maps || [];
|
||||
|
||||
for (const mapEntry of maps) {
|
||||
this.mapData.addMap({
|
||||
id: mapEntry.id,
|
||||
slug: mapEntry.slug,
|
||||
name: mapEntry.name,
|
||||
zone: mapEntry.zone
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Failed to load maps list:', e);
|
||||
}
|
||||
|
||||
// Populate map selector dropdown
|
||||
this.populateMapSelector();
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate the map selection dropdown
|
||||
*/
|
||||
populateMapSelector() {
|
||||
const maps = this.mapData.maps;
|
||||
|
||||
if (maps.length === 0) {
|
||||
this.mapSelect.innerHTML = '<option value="">No maps available</option>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Group by zone
|
||||
let html = '';
|
||||
const zones = {};
|
||||
|
||||
for (const map of maps) {
|
||||
if (!zones[map.zone]) {
|
||||
zones[map.zone] = [];
|
||||
}
|
||||
zones[map.zone].push(map);
|
||||
}
|
||||
|
||||
for (const [zoneName, zoneMaps] of Object.entries(zones)) {
|
||||
html += `<optgroup label="${zoneName}">`;
|
||||
for (const map of zoneMaps) {
|
||||
html += `<option value="${map.slug}">${map.name}</option>`;
|
||||
}
|
||||
html += '</optgroup>';
|
||||
}
|
||||
|
||||
this.mapSelect.innerHTML = html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a specific map by slug
|
||||
*/
|
||||
async loadMap(slug) {
|
||||
this.showLoading(true);
|
||||
|
||||
try {
|
||||
// Set current map in model
|
||||
const mapInfo = this.mapData.setCurrentMap(slug);
|
||||
|
||||
if (!mapInfo) throw new Error(`Map ${slug} not found`);
|
||||
|
||||
// Load tile manifest
|
||||
await this.tileService.loadManifest(slug);
|
||||
|
||||
// Load markers
|
||||
try {
|
||||
const markerData = await this.markerService.loadMarkers(slug);
|
||||
this.mapData.loadMarkers(markerData);
|
||||
} catch (e) {
|
||||
console.warn(`No markers found for ${slug}`);
|
||||
}
|
||||
|
||||
// Reset view and render
|
||||
this.view.resetView();
|
||||
this.buildCategoryUI();
|
||||
this.render();
|
||||
|
||||
} catch (e) {
|
||||
console.error('Failed to load map:', e);
|
||||
} finally {
|
||||
this.showLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the category filter UI
|
||||
*/
|
||||
buildCategoryUI() {
|
||||
const categories = this.mapData.categories;
|
||||
|
||||
if (Object.keys(categories).length === 0) {
|
||||
this.categoriesList.innerHTML = '<p>No categories available</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Group by group_name
|
||||
const groups = {};
|
||||
Object.entries(categories).forEach(([key, cat]) => {
|
||||
if (!groups[cat.group]) {
|
||||
groups[cat.group] = [];
|
||||
}
|
||||
groups[cat.group].push({ key, ...cat });
|
||||
});
|
||||
|
||||
let html = '';
|
||||
|
||||
for (const [groupName, cats] of Object.entries(groups)) {
|
||||
html += `<div class="category-group">`;
|
||||
|
||||
// Group-level toggle checkbox
|
||||
const allVisible = this.mapData.isGroupFullyVisible(groupName);
|
||||
const someVisible = this.mapData.isGroupPartiallyVisible(groupName) && !allVisible;
|
||||
|
||||
html += `
|
||||
<div class="category-item group-toggle">
|
||||
<input type="checkbox" id="group-${groupName}"
|
||||
${allVisible ? 'checked' : ''} ${someVisible ? 'indeterminate' : ''}>
|
||||
<label for="group-${groupName}" style="font-weight:bold;">${groupName}</label>
|
||||
</div>
|
||||
`;
|
||||
|
||||
cats.forEach(cat => {
|
||||
// Use icon image if available, otherwise fallback to emoji
|
||||
let iconHtml = '';
|
||||
if (cat.iconImage) {
|
||||
const filename = cat.iconImage.split('/').pop();
|
||||
iconHtml = `<img src="${CONFIG.ICONS_DIR}/${filename}" class="category-icon" alt="">`;
|
||||
} else {
|
||||
const symbol = CONFIG.CATEGORY_SYMBOLS[cat.name] || '📍';
|
||||
iconHtml = `<span>${symbol}</span>`;
|
||||
}
|
||||
|
||||
html += `
|
||||
<div class="category-item">
|
||||
<input type="checkbox" id="cat-${cat.key}" checked>
|
||||
${iconHtml}
|
||||
<label for="cat-${cat.key}">${cat.name}</label>
|
||||
<span class="category-count">${cat.count}</span>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
html += `</div>`;
|
||||
}
|
||||
|
||||
this.categoriesList.innerHTML = html;
|
||||
|
||||
// Attach event listeners to checkboxes
|
||||
this.attachCategoryListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach event listeners to category checkboxes
|
||||
*/
|
||||
attachCategoryListeners() {
|
||||
// Group toggles
|
||||
document.querySelectorAll('.group-toggle input[type="checkbox"]').forEach(checkbox => {
|
||||
checkbox.addEventListener('change', (e) => {
|
||||
const groupName = e.target.id.replace('group-', '');
|
||||
this.mapData.toggleGroup(groupName, e.target.checked);
|
||||
|
||||
// Update individual checkboxes
|
||||
document.querySelectorAll(`.category-item:not(.group-toggle)`).forEach(item => {
|
||||
const catCheckbox = item.querySelector('input[type="checkbox"]');
|
||||
if (catCheckbox) {
|
||||
const key = catCheckbox.id.replace('cat-', '');
|
||||
const cat = this.mapData.categories[key];
|
||||
if (cat && cat.group === groupName) {
|
||||
catCheckbox.checked = e.target.checked;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.render();
|
||||
});
|
||||
});
|
||||
|
||||
// Individual category toggles
|
||||
document.querySelectorAll('.category-item:not(.group-toggle) input[type="checkbox"]').forEach(checkbox => {
|
||||
checkbox.addEventListener('change', (e) => {
|
||||
const key = e.target.id.replace('cat-', '');
|
||||
this.mapData.toggleCategory(key, e.target.checked);
|
||||
|
||||
// Update parent group checkbox state
|
||||
const cat = this.mapData.categories[key];
|
||||
if (cat) {
|
||||
this.updateGroupCheckboxState(cat.group);
|
||||
}
|
||||
|
||||
this.render();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update group checkbox state based on child categories
|
||||
*/
|
||||
updateGroupCheckboxState(groupName) {
|
||||
const allVisible = this.mapData.isGroupFullyVisible(groupName);
|
||||
const someVisible = this.mapData.isGroupPartiallyVisible(groupName) && !allVisible;
|
||||
|
||||
const groupCheckbox = document.getElementById(`group-${groupName}`);
|
||||
if (groupCheckbox) {
|
||||
groupCheckbox.checked = allVisible;
|
||||
groupCheckbox.indeterminate = someVisible;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the map
|
||||
*/
|
||||
render() {
|
||||
this.view.render(this.tileService, this.mapData).then(() => {
|
||||
// Update zoom indicator
|
||||
this.zoomLevelEl.textContent = this.view.zoom;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup all event listeners
|
||||
*/
|
||||
setupEventListeners() {
|
||||
// Map selection change
|
||||
this.mapSelect.addEventListener('change', (e) => {
|
||||
const slug = e.target.value;
|
||||
if (slug) {
|
||||
this.loadMap(slug);
|
||||
}
|
||||
});
|
||||
|
||||
// Zoom controls
|
||||
document.getElementById('btn-zoom-in').addEventListener('click', () => {
|
||||
if (this.view.zoomIn()) this.render();
|
||||
});
|
||||
|
||||
document.getElementById('btn-zoom-out').addEventListener('click', () => {
|
||||
if (this.view.zoomOut()) this.render();
|
||||
});
|
||||
|
||||
document.getElementById('btn-reset-view').addEventListener('click', () => {
|
||||
this.view.resetView();
|
||||
this.render();
|
||||
});
|
||||
|
||||
// Mouse wheel zoom
|
||||
this.canvas.addEventListener('wheel', (e) => {
|
||||
e.preventDefault();
|
||||
if (e.deltaY < 0) {
|
||||
if (this.view.zoomIn()) this.render();
|
||||
} else {
|
||||
if (this.view.zoomOut()) this.render();
|
||||
}
|
||||
});
|
||||
|
||||
// Pan with mouse drag
|
||||
this.canvas.addEventListener('mousedown', (e) => {
|
||||
this.view.isDragging = true;
|
||||
this.view.lastMouseX = e.clientX;
|
||||
this.view.lastMouseY = e.clientY;
|
||||
});
|
||||
|
||||
window.addEventListener('mousemove', (e) => {
|
||||
if (this.view.isDragging) {
|
||||
const dx = e.clientX - this.view.lastMouseX;
|
||||
const dy = e.clientY - this.view.lastMouseY;
|
||||
|
||||
this.view.panBy(dx, dy);
|
||||
|
||||
this.view.lastMouseX = e.clientX;
|
||||
this.view.lastMouseY = e.clientY;
|
||||
|
||||
this.view.requestRender(this.tileService, this.mapData);
|
||||
} else {
|
||||
// Hover detection for tooltips
|
||||
this.checkHover(e);
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('mouseup', () => {
|
||||
this.view.isDragging = false;
|
||||
});
|
||||
|
||||
// Keyboard shortcuts
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.key === '+' || e.key === '=') {
|
||||
if (this.view.zoomIn()) this.render();
|
||||
} else if (e.key === '-') {
|
||||
if (this.view.zoomOut()) this.render();
|
||||
} else if (e.key === '0') {
|
||||
this.view.resetView();
|
||||
this.render();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for marker hover and show tooltip
|
||||
*/
|
||||
checkHover(e) {
|
||||
const rect = this.canvas.getBoundingClientRect();
|
||||
const screenX = e.clientX - rect.left;
|
||||
const screenY = e.clientY - rect.top;
|
||||
|
||||
const nearest = this.view.findNearestMarker(this.mapData, screenX, screenY);
|
||||
|
||||
if (nearest) {
|
||||
this.tooltip.classList.remove('hidden');
|
||||
this.tooltip.querySelector('.name').textContent =
|
||||
nearest.iconText || nearest.nt || nearest.name;
|
||||
this.tooltip.querySelector('.category').textContent =
|
||||
`${nearest.group_name} / ${nearest.category_name}`;
|
||||
|
||||
// Position tooltip near cursor but not off-screen
|
||||
let tx = e.clientX + 15;
|
||||
let ty = e.clientY - 10;
|
||||
|
||||
if (tx + 300 > window.innerWidth) tx = e.clientX - 315;
|
||||
if (ty < 0) ty = 10;
|
||||
|
||||
this.tooltip.style.left = tx + 'px';
|
||||
this.tooltip.style.top = ty + 'px';
|
||||
} else {
|
||||
this.tooltip.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show/hide loading overlay
|
||||
*/
|
||||
showLoading(show) {
|
||||
if (show) {
|
||||
this.loadingOverlay.classList.remove('hidden');
|
||||
} else {
|
||||
this.loadingOverlay.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}
|
||||
131
assets/map/js/models/MapData.js
Normal file
131
assets/map/js/models/MapData.js
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
/**
|
||||
* MapData - Model for map information and markers
|
||||
*/
|
||||
|
||||
class MapData {
|
||||
constructor() {
|
||||
this.maps = []; // List of available maps
|
||||
this.currentMap = null; // Currently selected map info
|
||||
this.markers = []; // Markers for current map
|
||||
this.categories = {}; // Category metadata (group/name -> info)
|
||||
this.visibleCategories = new Set();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a map to the available maps list
|
||||
*/
|
||||
addMap(mapInfo) {
|
||||
this.maps.push({
|
||||
id: mapInfo.id,
|
||||
slug: mapInfo.slug,
|
||||
name: mapInfo.name,
|
||||
zone: mapInfo.zone || 'Unknown'
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current map and clear markers
|
||||
*/
|
||||
setCurrentMap(slug) {
|
||||
const map = this.maps.find(m => m.slug === slug);
|
||||
if (map) {
|
||||
this.currentMap = map;
|
||||
this.markers = [];
|
||||
this.categories = {};
|
||||
this.visibleCategories.clear();
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load markers for the current map from JSON data
|
||||
*/
|
||||
loadMarkers(jsonData) {
|
||||
if (!this.currentMap) return;
|
||||
|
||||
// Parse and normalize marker data
|
||||
const rawMarkers = jsonData.markers || [];
|
||||
|
||||
this.markers = rawMarkers.map(m => ({
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
description: m.description,
|
||||
group_name: m.group_name,
|
||||
category_name: m.category_name,
|
||||
worldX: m.coordinates ? m.coordinates[1] : 0,
|
||||
worldY: m.coordinates ? m.coordinates[0] : 0,
|
||||
color: m.properties?.primary_color || '#FFFFFF',
|
||||
iconText: m.properties?.icon_text || '',
|
||||
nt: m.properties?.nt || '',
|
||||
iconName: m.properties?.icon_name || '',
|
||||
iconImage: m.properties?.icon_image ? m.properties.icon_image.split('?')[0] : ''
|
||||
}));
|
||||
|
||||
// Build category metadata
|
||||
this.markers.forEach(m => {
|
||||
const key = `${m.group_name}/${m.category_name}`;
|
||||
if (!this.categories[key]) {
|
||||
this.categories[key] = {
|
||||
group: m.group_name,
|
||||
name: m.category_name,
|
||||
count: 0,
|
||||
color: CONFIG.CATEGORY_COLORS[m.group_name] || '#FFFFFF',
|
||||
iconImage: m.iconImage || ''
|
||||
};
|
||||
}
|
||||
this.categories[key].count++;
|
||||
});
|
||||
|
||||
// Show all categories by default
|
||||
Object.keys(this.categories).forEach(key => {
|
||||
this.visibleCategories.add(key);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle visibility of a category
|
||||
*/
|
||||
toggleCategory(key, visible) {
|
||||
if (visible) {
|
||||
this.visibleCategories.add(key);
|
||||
} else {
|
||||
this.visibleCategories.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle all categories in a group
|
||||
*/
|
||||
toggleGroup(groupName, visible) {
|
||||
Object.entries(this.categories).forEach(([key, cat]) => {
|
||||
if (cat.group === groupName) {
|
||||
this.toggleCategory(key, visible);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if all categories in a group are visible
|
||||
*/
|
||||
isGroupFullyVisible(groupName) {
|
||||
return Object.entries(this.categories)
|
||||
.filter(([key, cat]) => cat.group === groupName)
|
||||
.every(([key]) => this.visibleCategories.has(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if any category in a group is visible
|
||||
*/
|
||||
isGroupPartiallyVisible(groupName) {
|
||||
return Object.entries(this.categories)
|
||||
.filter(([key, cat]) => cat.group === groupName)
|
||||
.some(([key]) => this.visibleCategories.has(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get marker count for a category
|
||||
*/
|
||||
getCategoryCount(key) {
|
||||
return this.categories[key]?.count || 0;
|
||||
}
|
||||
}
|
||||
37
assets/map/js/services/MarkerService.js
Normal file
37
assets/map/js/services/MarkerService.js
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
/**
|
||||
* MarkerService - Handles marker data loading and management
|
||||
*/
|
||||
|
||||
class MarkerService {
|
||||
constructor() {
|
||||
this.loadedMarkers = {}; // slug -> markers array
|
||||
}
|
||||
|
||||
/**
|
||||
* Load markers for a map from JSON file
|
||||
*/
|
||||
async loadMarkers(slug) {
|
||||
if (this.loadedMarkers[slug]) {
|
||||
return this.loadedMarkers[slug];
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${CONFIG.MARKERS_DIR}/${slug}_markers.json`);
|
||||
if (!response.ok) throw new Error('Marker file not found');
|
||||
|
||||
const data = await response.json();
|
||||
this.loadedMarkers[slug] = data;
|
||||
return data;
|
||||
} catch (e) {
|
||||
console.error(`Failed to load markers for ${slug}:`, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get loaded markers for a map
|
||||
*/
|
||||
getMarkers(slug) {
|
||||
return this.loadedMarkers[slug];
|
||||
}
|
||||
}
|
||||
120
assets/map/js/services/TileService.js
Normal file
120
assets/map/js/services/TileService.js
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
/**
|
||||
* TileService - Handles tile loading, caching, and manifest management
|
||||
*/
|
||||
|
||||
class TileService {
|
||||
constructor() {
|
||||
this.tileCache = {};
|
||||
this.loadingTiles = new Set();
|
||||
this.manifests = {}; // slug -> Set of tile keys
|
||||
}
|
||||
|
||||
/**
|
||||
* Load tile manifest for a map
|
||||
*/
|
||||
async loadManifest(slug) {
|
||||
if (this.manifests[slug]) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${CONFIG.TILES_DIR}/${slug}/tile_manifest.json`);
|
||||
if (!response.ok) throw new Error('Manifest not found');
|
||||
|
||||
const data = await response.json();
|
||||
this.manifests[slug] = new Set(data.tiles || []);
|
||||
} catch (e) {
|
||||
console.warn(`Failed to load manifest for ${slug}:`, e);
|
||||
this.manifests[slug] = null; // No manifest, try all tiles
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a tile exists in the manifest
|
||||
*/
|
||||
hasTile(slug, zoom, x, y) {
|
||||
const key = `${zoom}_${x}_${y}`;
|
||||
const manifest = this.manifests[slug];
|
||||
|
||||
// If no manifest or null, assume tile might exist
|
||||
return !manifest || manifest.has(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a single tile image
|
||||
*/
|
||||
async loadTile(slug, zoom, x, y) {
|
||||
const key = `${slug}_${zoom}_${x}_${y}`;
|
||||
|
||||
if (this.tileCache[key]) {
|
||||
return this.tileCache[key];
|
||||
}
|
||||
|
||||
// Check manifest before attempting to load
|
||||
if (!this.hasTile(slug, zoom, x, y)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// If already loading, wait briefly and check again
|
||||
if (this.loadingTiles.has(key)) {
|
||||
await new Promise(r => setTimeout(r, 10));
|
||||
return this.tileCache[key] || null;
|
||||
}
|
||||
|
||||
this.loadingTiles.add(key);
|
||||
|
||||
try {
|
||||
const img = new Image();
|
||||
img.src = `${CONFIG.TILES_DIR}/${slug}/${zoom}_${x}_${y}.jpg`;
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
img.onload = resolve;
|
||||
img.onerror = () => reject(new Error('Load failed'));
|
||||
setTimeout(() => reject(new Error('Timeout')), 5000);
|
||||
});
|
||||
|
||||
this.tileCache[key] = img;
|
||||
} catch (e) {
|
||||
// Silently fail for missing tiles
|
||||
} finally {
|
||||
this.loadingTiles.delete(key);
|
||||
}
|
||||
|
||||
return this.tileCache[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Preload tiles at adjacent zoom levels in background
|
||||
*/
|
||||
async preloadAdjacentZoomLevels(slug, currentZoom, viewBounds) {
|
||||
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
|
||||
|
||||
for (let targetZoom of [currentZoom - 1, currentZoom + 1]) {
|
||||
if (targetZoom < CONFIG.MIN_ZOOM || targetZoom > CONFIG.MAX_ZOOM) continue;
|
||||
|
||||
const tilesPerSide = Math.pow(2, targetZoom);
|
||||
const tileWorldSize = worldWidth / tilesPerSide;
|
||||
|
||||
// Calculate which tiles overlap with viewport
|
||||
const startTX = Math.floor((viewBounds.minX - CONFIG.WORLD_MIN_X) / tileWorldSize);
|
||||
const endTX = Math.ceil((viewBounds.maxX - CONFIG.WORLD_MIN_X) / tileWorldSize);
|
||||
const startTY = Math.floor((viewBounds.minY - CONFIG.WORLD_MIN_Y) / tileWorldSize);
|
||||
const endTY = Math.ceil((viewBounds.maxY - CONFIG.WORLD_MIN_Y) / tileWorldSize);
|
||||
|
||||
// Load tiles in background (fire and forget)
|
||||
for (let tx = startTX; tx <= endTX; tx++) {
|
||||
for (let ty = startTY; ty <= endTY; ty++) {
|
||||
if (tx >= 0 && tx < tilesPerSide && ty >= 0 && ty < tilesPerSide) {
|
||||
this.loadTile(slug, targetZoom, tx, ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear cache for a specific map (when switching maps)
|
||||
*/
|
||||
clearCache() {
|
||||
this.tileCache = {};
|
||||
this.loadingTiles.clear();
|
||||
}
|
||||
}
|
||||
334
assets/map/js/views/MapView.js
Normal file
334
assets/map/js/views/MapView.js
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
/**
|
||||
* MapView - Handles all canvas rendering for the map viewer
|
||||
*/
|
||||
|
||||
class MapView {
|
||||
constructor(canvas) {
|
||||
this.canvas = canvas;
|
||||
this.ctx = canvas.getContext('2d');
|
||||
|
||||
// View state
|
||||
this.zoom = CONFIG.MIN_ZOOM + 1;
|
||||
this.centerWorldX = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2;
|
||||
this.centerWorldY = (CONFIG.WORLD_MIN_Y + CONFIG.WORLD_MAX_Y) / 2;
|
||||
|
||||
// Icon cache
|
||||
this.iconCache = {};
|
||||
this.loadingIcons = new Set();
|
||||
|
||||
// Interaction state
|
||||
this.isDragging = false;
|
||||
this.lastMouseX = 0;
|
||||
this.lastMouseY = 0;
|
||||
this.renderRequested = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize canvas to fill window
|
||||
*/
|
||||
resize() {
|
||||
this.canvas.width = window.innerWidth;
|
||||
this.canvas.height = window.innerHeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert world coordinates to screen coordinates
|
||||
*/
|
||||
worldToScreen(worldX, worldY) {
|
||||
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
|
||||
const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM);
|
||||
const visibleWidth = worldWidth / zoomScale;
|
||||
const scale = this.canvas.width / visibleWidth;
|
||||
|
||||
const camOffsetX = -this.centerWorldX * scale + this.canvas.width / 2;
|
||||
const camOffsetY = -this.centerWorldY * scale + this.canvas.height / 2;
|
||||
|
||||
return {
|
||||
x: worldX * scale + camOffsetX,
|
||||
y: worldY * scale + camOffsetY
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert screen coordinates to world coordinates
|
||||
*/
|
||||
screenToWorld(screenX, screenY) {
|
||||
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
|
||||
const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM);
|
||||
const visibleWidth = worldWidth / zoomScale;
|
||||
const scale = this.canvas.width / visibleWidth;
|
||||
|
||||
const camOffsetX = -this.centerWorldX * scale + this.canvas.width / 2;
|
||||
const camOffsetY = -this.centerWorldY * scale + this.canvas.height / 2;
|
||||
|
||||
return {
|
||||
x: (screenX - camOffsetX) / scale,
|
||||
y: (screenY - camOffsetY) / scale
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get viewport bounds in world coordinates
|
||||
*/
|
||||
getViewBounds() {
|
||||
const topLeft = this.screenToWorld(0, 0);
|
||||
const bottomRight = this.screenToWorld(this.canvas.width, this.canvas.height);
|
||||
|
||||
return {
|
||||
minX: Math.min(topLeft.x, bottomRight.x),
|
||||
maxX: Math.max(topLeft.x, bottomRight.x),
|
||||
minY: Math.min(topLeft.y, bottomRight.y),
|
||||
maxY: Math.max(topLeft.y, bottomRight.y)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the map with tiles and markers
|
||||
*/
|
||||
async render(tileService, mapData) {
|
||||
const ctx = this.ctx;
|
||||
const width = this.canvas.width;
|
||||
const height = this.canvas.height;
|
||||
|
||||
// Clear canvas
|
||||
ctx.fillStyle = '#0a0a1e';
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
|
||||
if (!mapData.currentMap) return;
|
||||
|
||||
const slug = mapData.currentMap.slug;
|
||||
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
|
||||
|
||||
// Calculate scale and camera offset
|
||||
const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM);
|
||||
const visibleWidth = worldWidth / zoomScale;
|
||||
const scale = width / visibleWidth;
|
||||
|
||||
const camOffsetX = -this.centerWorldX * scale + width / 2;
|
||||
const camOffsetY = -this.centerWorldY * scale + height / 2;
|
||||
|
||||
// Draw tiles at current zoom level
|
||||
const tilesPerSide = Math.pow(2, this.zoom);
|
||||
const tileWorldSize = worldWidth / tilesPerSide;
|
||||
const tileScreenSize = tileWorldSize * scale;
|
||||
|
||||
for (let tx = 0; tx < tilesPerSide; tx++) {
|
||||
for (let ty = 0; ty < tilesPerSide; ty++) {
|
||||
// World position of this tile's top-left corner
|
||||
const tileWorldX = CONFIG.WORLD_MIN_X + tx * tileWorldSize;
|
||||
const tileWorldY = CONFIG.WORLD_MIN_Y + ty * tileWorldSize;
|
||||
|
||||
// Screen position after camera transform
|
||||
const screenX = tileWorldX * scale + camOffsetX;
|
||||
const screenY = tileWorldY * scale + camOffsetY;
|
||||
|
||||
// Skip tiles completely outside viewport (with margin)
|
||||
if (screenX + tileScreenSize < -tileScreenSize ||
|
||||
screenX > width + tileScreenSize ||
|
||||
screenY + tileScreenSize < -tileScreenSize ||
|
||||
screenY > height + tileScreenSize) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const tileImg = await tileService.loadTile(slug, this.zoom, tx, ty);
|
||||
|
||||
if (tileImg) {
|
||||
ctx.drawImage(tileImg, screenX, screenY, tileScreenSize, tileScreenSize);
|
||||
} else {
|
||||
// Placeholder for missing/loading tiles
|
||||
ctx.fillStyle = '#1a1a3e';
|
||||
ctx.fillRect(screenX, screenY, tileScreenSize, tileScreenSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Draw markers
|
||||
this.drawMarkers(mapData);
|
||||
|
||||
// Preload adjacent zoom levels in background
|
||||
const viewBounds = this.getViewBounds();
|
||||
tileService.preloadAdjacentZoomLevels(slug, this.zoom, viewBounds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load an icon image from local data directory
|
||||
*/
|
||||
async loadIcon(iconPath) {
|
||||
if (!iconPath) return null;
|
||||
|
||||
// Extract filename from path
|
||||
const filename = iconPath.split('/').pop();
|
||||
if (this.iconCache[filename]) {
|
||||
return this.iconCache[filename];
|
||||
}
|
||||
|
||||
if (this.loadingIcons.has(filename)) {
|
||||
await new Promise(r => setTimeout(r, 10));
|
||||
return this.iconCache[filename] || null;
|
||||
}
|
||||
|
||||
this.loadingIcons.add(filename);
|
||||
|
||||
try {
|
||||
const img = new Image();
|
||||
img.src = `${CONFIG.ICONS_DIR}/${filename}`;
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
img.onload = resolve;
|
||||
img.onerror = () => reject(new Error('Load failed'));
|
||||
setTimeout(() => reject(new Error('Timeout')), 3000);
|
||||
});
|
||||
|
||||
this.iconCache[filename] = img;
|
||||
} catch (e) {
|
||||
// Silently fail for missing icons
|
||||
} finally {
|
||||
this.loadingIcons.delete(filename);
|
||||
}
|
||||
|
||||
return this.iconCache[filename] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw all visible markers using icon images
|
||||
*/
|
||||
async drawMarkers(mapData) {
|
||||
const ctx = this.ctx;
|
||||
|
||||
for (const marker of mapData.markers) {
|
||||
const catKey = `${marker.group_name}/${marker.category_name}`;
|
||||
if (!mapData.visibleCategories.has(catKey)) continue;
|
||||
|
||||
// Marker size based on zoom
|
||||
let iconSize = 12;
|
||||
if (this.zoom >= 4) iconSize = 16;
|
||||
if (this.zoom >= 5) iconSize = 20;
|
||||
if (this.zoom >= 6) iconSize = 24;
|
||||
|
||||
const screen = this.worldToScreen(marker.worldX, marker.worldY);
|
||||
|
||||
// Try to load and draw icon image
|
||||
let iconImg = null;
|
||||
if (marker.iconImage) {
|
||||
iconImg = await this.loadIcon(marker.iconImage);
|
||||
}
|
||||
|
||||
if (iconImg) {
|
||||
// Draw icon image centered at marker position
|
||||
ctx.drawImage(iconImg,
|
||||
screen.x - iconSize / 2,
|
||||
screen.y - iconSize / 2,
|
||||
iconSize,
|
||||
iconSize);
|
||||
} else {
|
||||
// Fallback to emoji if no icon available
|
||||
const symbol = CONFIG.CATEGORY_SYMBOLS[marker.category_name] || '📍';
|
||||
let fontSize = 8;
|
||||
if (this.zoom >= 5) fontSize = 12;
|
||||
if (this.zoom >= 6) fontSize = 16;
|
||||
|
||||
ctx.font = `${fontSize}px sans-serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(symbol, screen.x, screen.y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Zoom in
|
||||
*/
|
||||
zoomIn() {
|
||||
if (this.zoom < CONFIG.MAX_ZOOM) {
|
||||
this.zoom++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zoom out
|
||||
*/
|
||||
zoomOut() {
|
||||
if (this.zoom > CONFIG.MIN_ZOOM) {
|
||||
this.zoom--;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset view to default
|
||||
*/
|
||||
resetView() {
|
||||
this.zoom = CONFIG.MIN_ZOOM + 1;
|
||||
this.centerWorldX = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2;
|
||||
this.centerWorldY = (CONFIG.WORLD_MIN_Y + CONFIG.WORLD_MAX_Y) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pan by screen delta
|
||||
*/
|
||||
panBy(dx, dy) {
|
||||
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
|
||||
const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM);
|
||||
const visibleWidth = worldWidth / zoomScale;
|
||||
const scale = this.canvas.width / visibleWidth;
|
||||
|
||||
// Each screen pixel represents 1/scale world units
|
||||
const worldDx = -(dx / scale);
|
||||
const worldDy = -(dy / scale);
|
||||
|
||||
this.centerWorldX += worldDx;
|
||||
this.centerWorldY += worldDy;
|
||||
|
||||
// Clamp to world bounds
|
||||
const margin = 0.1;
|
||||
this.centerWorldX = Math.max(
|
||||
CONFIG.WORLD_MIN_X + worldWidth * margin,
|
||||
Math.min(CONFIG.WORLD_MAX_X - worldWidth * margin, this.centerWorldX)
|
||||
);
|
||||
this.centerWorldY = Math.max(
|
||||
CONFIG.WORLD_MIN_Y + (CONFIG.WORLD_MAX_Y - CONFIG.WORLD_MIN_Y) * margin,
|
||||
Math.min(CONFIG.WORLD_MAX_Y - (CONFIG.WORLD_MAX_Y - CONFIG.WORLD_MIN_Y) * margin, this.centerWorldY)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a render frame
|
||||
*/
|
||||
requestRender(tileService, mapData) {
|
||||
if (!this.renderRequested) {
|
||||
this.renderRequested = true;
|
||||
requestAnimationFrame(() => {
|
||||
this.render(tileService, mapData);
|
||||
this.renderRequested = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find nearest marker to screen position
|
||||
*/
|
||||
findNearestMarker(mapData, screenX, screenY, threshold = 20) {
|
||||
let nearest = null;
|
||||
let nearestDist = threshold;
|
||||
|
||||
for (const marker of mapData.markers) {
|
||||
const catKey = `${marker.group_name}/${marker.category_name}`;
|
||||
if (!mapData.visibleCategories.has(catKey)) continue;
|
||||
|
||||
const screen = this.worldToScreen(marker.worldX, marker.worldY);
|
||||
const dx = screenX - screen.x;
|
||||
const dy = screenY - screen.y;
|
||||
const dist = Math.sqrt(dx * dx + dy * dy);
|
||||
|
||||
if (dist < nearestDist) {
|
||||
nearestDist = dist;
|
||||
nearest = marker;
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
}
|
||||
239
assets/map/scripts/download_all_maps.py
Normal file
239
assets/map/scripts/download_all_maps.py
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Download all Aion 2 map tiles from interactivemap.app.
|
||||
|
||||
Discovers all available maps, downloads their tiles using the actual tile
|
||||
directory paths from the API (which may differ from map slugs). Generates
|
||||
tile manifests by attempting to download and tracking which tiles exist.
|
||||
Also generates a local maps.json for the viewer to use (avoids CORS issues).
|
||||
|
||||
Usage:
|
||||
python download_all_maps.py # Download all maps
|
||||
python download_all_maps.py --map verteron # Download specific map only
|
||||
python download_all_maps.py -o ./tiles # Custom output directory
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
API_BASE = "https://interactivemap.app/aion2/maps/imapp"
|
||||
TILES_BASE = "https://interactivemap.app/aion2/maps/imapp/uploads/tiles"
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) aion2-map-downloader/2.0"
|
||||
|
||||
|
||||
def http_get_json(url: str, retries: int = 3) -> object:
|
||||
"""GET a JSON endpoint with retry logic."""
|
||||
last_err = None
|
||||
for attempt in range(1, retries + 1):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
text = resp.read().decode("utf-8")
|
||||
if text.lstrip()[:1] == "<":
|
||||
raise ValueError("HTML fallback received instead of JSON")
|
||||
return json.loads(text)
|
||||
except (urllib.error.URLError, ValueError, TimeoutError) as exc:
|
||||
last_err = exc
|
||||
if attempt < retries:
|
||||
time.sleep(1.5 * attempt)
|
||||
raise RuntimeError(f"GET {url} failed after {retries} attempts: {last_err}")
|
||||
|
||||
|
||||
def discover_maps() -> list:
|
||||
"""Discover all available maps from the API."""
|
||||
print("Discovering available maps...")
|
||||
maps_data = http_get_json(f"{API_BASE}/api/getmaps")
|
||||
|
||||
# API returns a list of zones directly
|
||||
maps = []
|
||||
for zone in maps_data:
|
||||
zone_name = zone.get("name", "Unknown") or "General"
|
||||
for entry in zone.get("maps", []):
|
||||
# Extract actual tile directory from tiles_url field
|
||||
tiles_url = entry.get("tiles_url", "")
|
||||
# Format: uploads/tiles/{dir}/{z}_{x}_{y}.jpg or uploads/tiles/{dir}/{subdir}/{z}_{x}_{y}.jpg
|
||||
if tiles_url.startswith("uploads/tiles/"):
|
||||
path_parts = tiles_url[len("uploads/tiles/"):].split("/")
|
||||
tile_dir = "/".join(path_parts[:-1]) # Remove the {z}_{x}_{y}.jpg part
|
||||
else:
|
||||
tile_dir = entry.get("slug")
|
||||
|
||||
maps.append({
|
||||
"id": str(entry.get("id")),
|
||||
"slug": str(entry.get("slug")),
|
||||
"name": entry.get("name"),
|
||||
"zone": zone_name,
|
||||
"tile_dir": tile_dir,
|
||||
"min_zoom": int(entry.get("min_tiles_zoom", 0)),
|
||||
"max_zoom": int(entry.get("max_tiles_zoom", 7))
|
||||
})
|
||||
|
||||
print(f"Found {len(maps)} maps")
|
||||
for m in maps:
|
||||
print(f" {m['name']} (slug={m['slug']}, tiles={m['tile_dir']})")
|
||||
return maps
|
||||
|
||||
|
||||
def save_maps_list(maps, out_dir):
|
||||
"""Save the maps list to a local JSON file for the viewer."""
|
||||
# Save in both data root and scripts/../data for easy access
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
data_root = os.path.join(script_dir, "..", "data")
|
||||
|
||||
maps_json_path = os.path.join(data_root, "maps.json")
|
||||
with open(maps_json_path, "w") as f:
|
||||
json.dump({"maps": maps}, f, indent=2)
|
||||
|
||||
print(f"Saved maps list to {maps_json_path}")
|
||||
|
||||
|
||||
def enumerate_tiles(min_z: int, max_z: int):
|
||||
"""Yield (z, x, y) for every tile of zoom levels min_z..max_z."""
|
||||
for z in range(min_z, max_z + 1):
|
||||
n = 2 ** z
|
||||
for x in range(n):
|
||||
for y in range(n):
|
||||
yield z, x, y
|
||||
|
||||
|
||||
def fetch_tile(url: str, dest: str, retries: int) -> str:
|
||||
"""Download a single tile. Returns status string."""
|
||||
if os.path.exists(dest) and os.path.getsize(dest) > 0:
|
||||
return "exists"
|
||||
|
||||
tmp = dest + ".part"
|
||||
last_err = ""
|
||||
for attempt in range(1, retries + 1):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = resp.read()
|
||||
if not data:
|
||||
last_err = "empty response"
|
||||
else:
|
||||
with open(tmp, "wb") as fh:
|
||||
fh.write(data)
|
||||
os.replace(tmp, dest)
|
||||
return "ok"
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 404:
|
||||
last_err = ""
|
||||
return "missing"
|
||||
last_err = f"HTTP {e.code}"
|
||||
except Exception as e:
|
||||
last_err = repr(e)
|
||||
if attempt < retries:
|
||||
time.sleep(0.5 * attempt)
|
||||
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
return f"error:{last_err}"
|
||||
|
||||
|
||||
def download_map_tiles(map_info: dict, out_dir: str, workers: int = 16) -> None:
|
||||
"""Download all tiles for a single map."""
|
||||
slug = map_info["slug"]
|
||||
tile_dir_name = map_info["tile_dir"]
|
||||
min_z = max(2, map_info.get("min_zoom", 0))
|
||||
max_z = min(6, map_info.get("max_zoom", 7))
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"Downloading tiles for: {map_info['name']} ({slug})")
|
||||
print(f" Tile directory: {tile_dir_name}")
|
||||
print(f" Zoom range: {min_z}-{max_z}")
|
||||
print(f"{'='*60}")
|
||||
|
||||
map_out = os.path.join(out_dir, slug)
|
||||
os.makedirs(map_out, exist_ok=True)
|
||||
|
||||
# Enumerate all possible tiles in the zoom range
|
||||
tasks = list(enumerate_tiles(min_z, max_z))
|
||||
total = len(tasks)
|
||||
print(f" Total tile positions to check: {total}")
|
||||
|
||||
counts = {"ok": 0, "exists": 0, "missing": 0, "error": 0}
|
||||
existing_tiles = []
|
||||
done = 0
|
||||
t0 = time.time()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = {}
|
||||
for (z, x, y) in tasks:
|
||||
url = f"{TILES_BASE}/{tile_dir_name}/{z}_{x}_{y}.jpg"
|
||||
dest = os.path.join(map_out, f"{z}_{x}_{y}.jpg")
|
||||
futures[pool.submit(fetch_tile, url, dest, 3)] = (z, x, y)
|
||||
|
||||
for fut in as_completed(futures):
|
||||
z, x, y = futures[fut]
|
||||
status = fut.result()
|
||||
kind = status.split(":", 1)[0]
|
||||
counts[kind] += 1
|
||||
|
||||
if kind == "ok" or kind == "exists":
|
||||
existing_tiles.append(f"{z}_{x}_{y}")
|
||||
|
||||
done += 1
|
||||
|
||||
if done % max(1, total // 20) == 0 or done == total:
|
||||
rate = done / max(time.time() - t0, 1e-6)
|
||||
print(f" {done}/{total} ({rate:.1f}/s) "
|
||||
f"ok={counts['ok']} cached={counts['exists']} missing={counts['missing']} err={counts['error']}",
|
||||
flush=True)
|
||||
|
||||
# Generate manifest from successfully downloaded tiles
|
||||
manifest_path = os.path.join(map_out, "tile_manifest.json")
|
||||
with open(manifest_path, "w") as f:
|
||||
json.dump({"tiles": existing_tiles}, f)
|
||||
|
||||
elapsed = time.time() - t0
|
||||
print(f" Done in {elapsed:.0f}s: downloaded={counts['ok']} cached={counts['exists']} "
|
||||
f"missing={counts['missing']} failed={counts['error']}")
|
||||
print(f" Manifest saved with {len(existing_tiles)} existing tiles")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Download all Aion 2 map tiles")
|
||||
parser.add_argument("--map", type=str, default=None, help="Download specific map by slug only")
|
||||
parser.add_argument("-o", "--out-dir", default="../data/tiles", help="Output directory for tiles")
|
||||
parser.add_argument("-w", "--workers", type=int, default=16, help="Number of concurrent downloads")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Resolve output directory relative to script location
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
out_dir = os.path.join(script_dir, args.out_dir) if not os.path.isabs(args.out_dir) else args.out_dir
|
||||
|
||||
maps = discover_maps()
|
||||
|
||||
# Save the complete maps list for the viewer (always, even if downloading specific map)
|
||||
save_maps_list(maps, out_dir)
|
||||
|
||||
if args.map:
|
||||
# Filter to specific map
|
||||
target = [m for m in maps if m["slug"] == args.map]
|
||||
if not target:
|
||||
print(f"Error: Map '{args.map}' not found. Available slugs:")
|
||||
for m in maps:
|
||||
print(f" {m['slug']}")
|
||||
sys.exit(1)
|
||||
maps = target
|
||||
|
||||
t_start = time.time()
|
||||
|
||||
for map_info in maps:
|
||||
download_map_tiles(map_info, out_dir, args.workers)
|
||||
|
||||
elapsed = time.time() - t_start
|
||||
print(f"\n{'='*60}")
|
||||
print(f"All downloads complete in {elapsed:.0f}s")
|
||||
print(f"Output directory: {out_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
151
assets/map/scripts/download_marker_icons.py
Normal file
151
assets/map/scripts/download_marker_icons.py
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Download all unique marker icon graphics from interactivemap.app.
|
||||
|
||||
Scans all local marker JSON files to find unique icon image paths, then
|
||||
downloads each icon and saves it locally for the map viewer to use.
|
||||
|
||||
Usage:
|
||||
python download_marker_icons.py # Download all icons
|
||||
python download_marker_icons.py -o ./icons # Custom output directory
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
BASE_URL = "https://interactivemap.app"
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) aion2-icon-downloader/1.0"
|
||||
|
||||
|
||||
def collect_unique_icons(markers_dir):
|
||||
"""Scan all marker JSON files and collect unique icon image paths."""
|
||||
print(f"Scanning for icons in: {markers_dir}")
|
||||
|
||||
if not os.path.exists(markers_dir):
|
||||
print(f"Error: Markers directory not found: {markers_dir}")
|
||||
return set()
|
||||
|
||||
icons = set()
|
||||
json_files = [f for f in os.listdir(markers_dir) if f.endswith('_markers.json')]
|
||||
|
||||
print(f"Found {len(json_files)} marker files")
|
||||
|
||||
for filename in json_files:
|
||||
filepath = os.path.join(markers_dir, filename)
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
markers = data.get('markers', [])
|
||||
for marker in markers:
|
||||
props = marker.get('properties', {})
|
||||
icon_image = props.get('icon_image')
|
||||
if icon_image:
|
||||
# Remove query string (version parameter)
|
||||
clean_path = icon_image.split('?')[0]
|
||||
icons.add(clean_path)
|
||||
except Exception as e:
|
||||
print(f" Warning: Failed to read {filename}: {e}")
|
||||
|
||||
print(f"Found {len(icons)} unique icon paths")
|
||||
return icons
|
||||
|
||||
|
||||
def download_icon(icon_path, out_dir):
|
||||
"""Download a single icon. Returns status string."""
|
||||
# Extract filename from path
|
||||
filename = os.path.basename(icon_path)
|
||||
if not filename:
|
||||
return "error:no-filename", ""
|
||||
|
||||
dest = os.path.join(out_dir, filename)
|
||||
|
||||
if os.path.exists(dest) and os.path.getsize(dest) > 0:
|
||||
return "exists", filename
|
||||
|
||||
url = BASE_URL + icon_path
|
||||
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
data = resp.read()
|
||||
|
||||
if not data:
|
||||
return "empty", filename
|
||||
|
||||
tmp = dest + ".part"
|
||||
with open(tmp, "wb") as fh:
|
||||
fh.write(data)
|
||||
os.replace(tmp, dest)
|
||||
return "ok", filename
|
||||
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 404:
|
||||
return "missing", filename
|
||||
return f"error:{e.code}", filename
|
||||
except Exception as e:
|
||||
return f"error:{repr(e)}", filename
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Download all unique marker icon graphics")
|
||||
parser.add_argument("-m", "--markers-dir", default="../data/markers",
|
||||
help="Directory containing marker JSON files")
|
||||
parser.add_argument("-o", "--out-dir", default="../data/icons",
|
||||
help="Output directory for icons")
|
||||
parser.add_argument("-w", "--workers", type=int, default=16,
|
||||
help="Number of concurrent downloads")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Resolve directories relative to script location
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
markers_dir = os.path.join(script_dir, args.markers_dir) if not os.path.isabs(args.markers_dir) else args.markers_dir
|
||||
out_dir = os.path.join(script_dir, args.out_dir) if not os.path.isabs(args.out_dir) else args.out_dir
|
||||
|
||||
# Collect unique icons from all marker files
|
||||
icon_paths = collect_unique_icons(markers_dir)
|
||||
|
||||
if not icon_paths:
|
||||
print("No icons found. Run extract_all_markers.py first.")
|
||||
sys.exit(1)
|
||||
|
||||
# Create output directory
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
|
||||
# Download all icons
|
||||
print(f"\nDownloading {len(icon_paths)} icons to: {out_dir}")
|
||||
|
||||
counts = {"ok": 0, "exists": 0, "missing": 0, "error": 0}
|
||||
done = 0
|
||||
t0 = time.time()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.workers) as pool:
|
||||
futures = {}
|
||||
for icon_path in icon_paths:
|
||||
futures[pool.submit(download_icon, icon_path, out_dir)] = icon_path
|
||||
|
||||
for fut in as_completed(futures):
|
||||
status, filename = fut.result()
|
||||
kind = status.split(":", 1)[0]
|
||||
counts[kind] += 1
|
||||
done += 1
|
||||
|
||||
if done % max(1, len(icon_paths) // 10) == 0 or done == len(icon_paths):
|
||||
rate = done / max(time.time() - t0, 1e-6)
|
||||
print(f" {done}/{len(icon_paths)} ({rate:.1f}/s) "
|
||||
f"ok={counts['ok']} cached={counts['exists']} missing={counts['missing']} err={counts['error']}",
|
||||
flush=True)
|
||||
|
||||
elapsed = time.time() - t0
|
||||
print(f"\nDone in {elapsed:.0f}s: downloaded={counts['ok']} cached={counts['exists']} "
|
||||
f"missing={counts['missing']} failed={counts['error']}")
|
||||
print(f"Icons saved to: {out_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
230
assets/map/scripts/extract_all_markers.py
Normal file
230
assets/map/scripts/extract_all_markers.py
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Extract markers from all Aion 2 maps and export to JSON.
|
||||
|
||||
Discovers all available maps, fetches their marker data with anti-scraping
|
||||
token handling, de-poisons coordinates, and exports per-map JSON files.
|
||||
|
||||
Usage:
|
||||
python extract_all_markers.py # Extract all maps
|
||||
python extract_all_markers.py --map verteron # Specific map only
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
API_BASE = "https://interactivemap.app/aion2/maps/imapp"
|
||||
USER_AGENT = "Mozilla/5.0 (aion2-marker-extractor/2.0)"
|
||||
|
||||
|
||||
def http_get_json(url: str, retries: int = 4) -> object:
|
||||
"""GET a JSON endpoint with retry logic."""
|
||||
last_err = None
|
||||
for attempt in range(1, retries + 1):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
text = resp.read().decode("utf-8")
|
||||
if text.lstrip()[:1] == "<":
|
||||
raise ValueError("HTML fallback received instead of JSON")
|
||||
return json.loads(text)
|
||||
except (urllib.error.URLError, ValueError, TimeoutError) as exc:
|
||||
last_err = exc
|
||||
if attempt < retries:
|
||||
time.sleep(1.5 * attempt)
|
||||
raise RuntimeError(f"GET {url} failed after {retries} attempts: {last_err}")
|
||||
|
||||
|
||||
def http_get_text(url: str) -> str:
|
||||
"""GET a text endpoint."""
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return resp.read().decode("utf-8").strip()
|
||||
|
||||
|
||||
def fnv1a32(s: str) -> int:
|
||||
"""FNV-1a 32-bit hash over UTF-8 bytes."""
|
||||
h = 0x811C9DC5
|
||||
for b in s.encode("utf-8"):
|
||||
h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF
|
||||
return h
|
||||
|
||||
|
||||
def js_mod(v: float, m: int) -> float:
|
||||
"""JavaScript-style positive modulo."""
|
||||
return ((v % m) + m) % m
|
||||
|
||||
|
||||
def discover_maps() -> list:
|
||||
"""Discover all available maps from the API."""
|
||||
print("Discovering available maps...")
|
||||
maps_data = http_get_json(f"{API_BASE}/api/getmaps")
|
||||
|
||||
maps = []
|
||||
zones = maps_data if isinstance(maps_data, list) else maps_data.get("groups", [])
|
||||
for zone in zones:
|
||||
zone_name = zone.get("name", "Unknown")
|
||||
for entry in zone.get("maps", []):
|
||||
maps.append({
|
||||
"id": str(entry.get("id")),
|
||||
"slug": str(entry.get("slug")),
|
||||
"name": entry.get("name"),
|
||||
"zone": zone_name
|
||||
})
|
||||
|
||||
print(f"Found {len(maps)} maps")
|
||||
return maps
|
||||
|
||||
|
||||
def fetch_token() -> str:
|
||||
"""Fetch anti-scraping token."""
|
||||
token = http_get_text(f"{API_BASE}/api/mtoken/1?_={int(time.time() * 1000)}")
|
||||
if not token:
|
||||
raise RuntimeError("Empty anti-scraping token received")
|
||||
return token
|
||||
|
||||
|
||||
def fetch_map_markers(map_info: dict) -> tuple:
|
||||
"""Fetch and de-poison markers for a single map. Returns (token, data, marker_count)."""
|
||||
slug = map_info["slug"]
|
||||
map_id = map_info["id"]
|
||||
|
||||
print(f" Fetching markers for {map_info['name']} ({slug})...")
|
||||
|
||||
for attempt in (1, 2):
|
||||
token = fetch_token()
|
||||
url = f"{API_BASE}/api/{map_id}/options.json?t=" + urllib.parse.quote(token)
|
||||
data = http_get_json(url)
|
||||
|
||||
groups = data.get("groups") or []
|
||||
n_markers = sum(
|
||||
len(c.get("data") or [])
|
||||
for g in groups
|
||||
for c in (g.get("categories") or [])
|
||||
)
|
||||
|
||||
if n_markers > 0:
|
||||
return token, data, n_markers
|
||||
|
||||
print(f" Warning: attempt {attempt} returned no markers — retrying with fresh token", file=sys.stderr)
|
||||
|
||||
raise RuntimeError(f"Map '{slug}' (id {map_id}) returned zero markers")
|
||||
|
||||
|
||||
def de_poison_and_flatten(token: str, data: dict) -> list:
|
||||
"""Walk groups -> categories -> markers, undo coordinate offsets, flatten to records."""
|
||||
markers = []
|
||||
for group in data.get("groups") or []:
|
||||
g_id, g_name = group.get("id"), group.get("name")
|
||||
for cat in group.get("categories") or []:
|
||||
c_id, c_name = cat.get("id"), cat.get("name")
|
||||
for item in cat.get("data") or []:
|
||||
props = item.get("properties") or {}
|
||||
coords = item.get("coordinates")
|
||||
fixed = None
|
||||
|
||||
if isinstance(coords, list) and len(coords) >= 2:
|
||||
mid = str(props["id"]) if props.get("id") is not None else ""
|
||||
ox = fnv1a32(token + mid + "x") % 4096
|
||||
oy = fnv1a32(token + mid + "y") % 4096
|
||||
fixed = [
|
||||
js_mod(float(coords[0]) - ox, 4096),
|
||||
js_mod(float(coords[1]) - oy, 4096),
|
||||
]
|
||||
|
||||
rec = {
|
||||
"id": props.get("id"),
|
||||
"name": props.get("name"),
|
||||
"description": props.get("description"),
|
||||
"group_id": g_id,
|
||||
"group_name": g_name,
|
||||
"category_id": c_id,
|
||||
"category_name": c_name,
|
||||
"coordinates": fixed,
|
||||
"properties": props
|
||||
}
|
||||
markers.append(rec)
|
||||
|
||||
return markers
|
||||
|
||||
|
||||
def extract_map_markers(map_info: dict, out_dir: str) -> None:
|
||||
"""Extract and save markers for a single map."""
|
||||
slug = map_info["slug"]
|
||||
|
||||
try:
|
||||
token, data, n_markers = fetch_map_markers(map_info)
|
||||
|
||||
print(f" De-poisoning {n_markers} coordinates...")
|
||||
markers = de_poison_and_flatten(token, data)
|
||||
|
||||
export = {
|
||||
"source": f"https://interactivemap.app/aion2/maps/{slug}",
|
||||
"extracted_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"map": {
|
||||
"id": map_info["id"],
|
||||
"name": map_info["name"],
|
||||
"slug": slug,
|
||||
"zone": map_info.get("zone"),
|
||||
"last_update": data.get("last_update")
|
||||
},
|
||||
"marker_count": len(markers),
|
||||
"markers": markers
|
||||
}
|
||||
|
||||
out_path = os.path.join(out_dir, f"{slug}_markers.json")
|
||||
with open(out_path, "w", encoding="utf-8") as fh:
|
||||
json.dump(export, fh, ensure_ascii=False, indent=2)
|
||||
|
||||
# Print category breakdown
|
||||
by_cat = {}
|
||||
for m in markers:
|
||||
key = f"{m['group_name']}/{m['category_name']}"
|
||||
by_cat[key] = by_cat.get(key, 0) + 1
|
||||
|
||||
print(f" Saved {len(markers)} markers to {out_path}")
|
||||
|
||||
except Exception as e:
|
||||
print(f" Error extracting markers for {slug}: {e}", file=sys.stderr)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Extract markers from all Aion 2 maps")
|
||||
parser.add_argument("--map", type=str, default=None, help="Extract specific map by slug only")
|
||||
parser.add_argument("-o", "--out-dir", default="../data/markers", help="Output directory for marker JSON files")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Resolve output directory relative to script location
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
out_dir = os.path.join(script_dir, args.out_dir) if not os.path.isabs(args.out_dir) else args.out_dir
|
||||
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
|
||||
maps = discover_maps()
|
||||
|
||||
if args.map:
|
||||
target = [m for m in maps if m["slug"] == args.map]
|
||||
if not target:
|
||||
print(f"Error: Map '{args.map}' not found. Available slugs:")
|
||||
for m in maps:
|
||||
print(f" {m['slug']}")
|
||||
sys.exit(1)
|
||||
maps = target
|
||||
|
||||
t_start = time.time()
|
||||
|
||||
for map_info in maps:
|
||||
extract_map_markers(map_info, out_dir)
|
||||
|
||||
elapsed = time.time() - t_start
|
||||
print(f"\nAll marker extraction complete in {elapsed:.0f}s")
|
||||
print(f"Output directory: {out_dir}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
263
assets/map/styles.css
Normal file
263
assets/map/styles.css
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
/* Aion 2 Map Viewer - Styles */
|
||||
|
||||
:root {
|
||||
--bg-primary: #1a1a2e;
|
||||
--bg-secondary: rgba(20, 20, 40, 0.9);
|
||||
--border-color: rgba(100, 100, 150, 0.3);
|
||||
--text-primary: #e0e0e0;
|
||||
--text-secondary: #aaa;
|
||||
--accent-gold: #ffd700;
|
||||
--accent-blue: #3388FF;
|
||||
--panel-radius: 8px;
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Map container */
|
||||
#map-container {
|
||||
position: relative;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
canvas {
|
||||
display: block;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
canvas:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
/* Loading overlay */
|
||||
#loading-overlay {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
text-align: center;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 3px solid var(--border-color);
|
||||
border-top-color: var(--accent-gold);
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: 0 auto 16px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* UI overlay */
|
||||
#ui-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.panel {
|
||||
pointer-events: auto;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--panel-radius);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
/* Title bar */
|
||||
#title-bar {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
padding: 12px 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#title-bar h1 {
|
||||
font-size: 24px;
|
||||
color: var(--accent-gold);
|
||||
text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.map-selector-container select {
|
||||
background: rgba(30, 30, 60, 0.9);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-primary);
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
min-width: 250px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.map-selector-container select:hover {
|
||||
border-color: var(--accent-gold);
|
||||
}
|
||||
|
||||
/* Zoom controls */
|
||||
#zoom-controls {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
button {
|
||||
background: rgba(50, 50, 80, 0.8);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-primary);
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
transition: background 0.2s, border-color 0.2s;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: rgba(70, 70, 100, 0.8);
|
||||
border-color: var(--accent-gold);
|
||||
}
|
||||
|
||||
/* Category panel */
|
||||
#category-panel {
|
||||
position: absolute;
|
||||
bottom: 16px;
|
||||
left: 16px;
|
||||
padding: 12px;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
width: 300px;
|
||||
}
|
||||
|
||||
#category-panel h3 {
|
||||
font-size: 14px;
|
||||
color: var(--accent-gold);
|
||||
margin-bottom: 8px;
|
||||
border-bottom: 1px solid rgba(255, 215, 0, 0.3);
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.category-group {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.category-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 4px 0;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.category-item:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.category-item.group-toggle {
|
||||
margin-bottom: 6px;
|
||||
padding-bottom: 6px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.category-item input[type="checkbox"] {
|
||||
margin-right: 8px;
|
||||
accent-color: var(--accent-gold);
|
||||
}
|
||||
|
||||
.category-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin-right: 8px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.category-item label {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
flex: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.category-count {
|
||||
font-size: 10px;
|
||||
color: #888;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
/* Zoom indicator */
|
||||
#zoom-indicator {
|
||||
position: absolute;
|
||||
bottom: 16px;
|
||||
right: 16px;
|
||||
padding: 8px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* Tooltip */
|
||||
#tooltip {
|
||||
position: absolute;
|
||||
background: rgba(10, 10, 30, 0.95);
|
||||
border: 1px solid rgba(255, 215, 0, 0.5);
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
font-size: 12px;
|
||||
color: #fff;
|
||||
pointer-events: none;
|
||||
max-width: 300px;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
#tooltip .name {
|
||||
font-weight: bold;
|
||||
color: var(--accent-gold);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
#tooltip .category {
|
||||
font-size: 10px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* Utility classes */
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Scrollbar styling */
|
||||
#category-panel::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
#category-panel::-webkit-scrollbar-track {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
#category-panel::-webkit-scrollbar-thumb {
|
||||
background: rgba(100, 100, 150, 0.5);
|
||||
border-radius: 3px;
|
||||
}
|
||||
BIN
assets/vendor/leaflet/images/layers-2x.png
vendored
BIN
assets/vendor/leaflet/images/layers-2x.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 1.2 KiB |
BIN
assets/vendor/leaflet/images/layers.png
vendored
BIN
assets/vendor/leaflet/images/layers.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 696 B |
BIN
assets/vendor/leaflet/images/marker-icon-2x.png
vendored
BIN
assets/vendor/leaflet/images/marker-icon-2x.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 2.4 KiB |
BIN
assets/vendor/leaflet/images/marker-icon.png
vendored
BIN
assets/vendor/leaflet/images/marker-icon.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 1.4 KiB |
BIN
assets/vendor/leaflet/images/marker-shadow.png
vendored
BIN
assets/vendor/leaflet/images/marker-shadow.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 618 B |
661
assets/vendor/leaflet/leaflet.css
vendored
661
assets/vendor/leaflet/leaflet.css
vendored
|
|
@ -1,661 +0,0 @@
|
|||
/* required styles */
|
||||
|
||||
.leaflet-pane,
|
||||
.leaflet-tile,
|
||||
.leaflet-marker-icon,
|
||||
.leaflet-marker-shadow,
|
||||
.leaflet-tile-container,
|
||||
.leaflet-pane > svg,
|
||||
.leaflet-pane > canvas,
|
||||
.leaflet-zoom-box,
|
||||
.leaflet-image-layer,
|
||||
.leaflet-layer {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
}
|
||||
.leaflet-container {
|
||||
overflow: hidden;
|
||||
}
|
||||
.leaflet-tile,
|
||||
.leaflet-marker-icon,
|
||||
.leaflet-marker-shadow {
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
/* Prevents IE11 from highlighting tiles in blue */
|
||||
.leaflet-tile::selection {
|
||||
background: transparent;
|
||||
}
|
||||
/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
|
||||
.leaflet-safari .leaflet-tile {
|
||||
image-rendering: -webkit-optimize-contrast;
|
||||
}
|
||||
/* hack that prevents hw layers "stretching" when loading new tiles */
|
||||
.leaflet-safari .leaflet-tile-container {
|
||||
width: 1600px;
|
||||
height: 1600px;
|
||||
-webkit-transform-origin: 0 0;
|
||||
}
|
||||
.leaflet-marker-icon,
|
||||
.leaflet-marker-shadow {
|
||||
display: block;
|
||||
}
|
||||
/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
|
||||
/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
|
||||
.leaflet-container .leaflet-overlay-pane svg {
|
||||
max-width: none !important;
|
||||
max-height: none !important;
|
||||
}
|
||||
.leaflet-container .leaflet-marker-pane img,
|
||||
.leaflet-container .leaflet-shadow-pane img,
|
||||
.leaflet-container .leaflet-tile-pane img,
|
||||
.leaflet-container img.leaflet-image-layer,
|
||||
.leaflet-container .leaflet-tile {
|
||||
max-width: none !important;
|
||||
max-height: none !important;
|
||||
width: auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.leaflet-container img.leaflet-tile {
|
||||
/* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
|
||||
mix-blend-mode: plus-lighter;
|
||||
}
|
||||
|
||||
.leaflet-container.leaflet-touch-zoom {
|
||||
-ms-touch-action: pan-x pan-y;
|
||||
touch-action: pan-x pan-y;
|
||||
}
|
||||
.leaflet-container.leaflet-touch-drag {
|
||||
-ms-touch-action: pinch-zoom;
|
||||
/* Fallback for FF which doesn't support pinch-zoom */
|
||||
touch-action: none;
|
||||
touch-action: pinch-zoom;
|
||||
}
|
||||
.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
|
||||
-ms-touch-action: none;
|
||||
touch-action: none;
|
||||
}
|
||||
.leaflet-container {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
.leaflet-container a {
|
||||
-webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
|
||||
}
|
||||
.leaflet-tile {
|
||||
filter: inherit;
|
||||
visibility: hidden;
|
||||
}
|
||||
.leaflet-tile-loaded {
|
||||
visibility: inherit;
|
||||
}
|
||||
.leaflet-zoom-box {
|
||||
width: 0;
|
||||
height: 0;
|
||||
-moz-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
z-index: 800;
|
||||
}
|
||||
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
|
||||
.leaflet-overlay-pane svg {
|
||||
-moz-user-select: none;
|
||||
}
|
||||
|
||||
.leaflet-pane { z-index: 400; }
|
||||
|
||||
.leaflet-tile-pane { z-index: 200; }
|
||||
.leaflet-overlay-pane { z-index: 400; }
|
||||
.leaflet-shadow-pane { z-index: 500; }
|
||||
.leaflet-marker-pane { z-index: 600; }
|
||||
.leaflet-tooltip-pane { z-index: 650; }
|
||||
.leaflet-popup-pane { z-index: 700; }
|
||||
|
||||
.leaflet-map-pane canvas { z-index: 100; }
|
||||
.leaflet-map-pane svg { z-index: 200; }
|
||||
|
||||
.leaflet-vml-shape {
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
}
|
||||
.lvml {
|
||||
behavior: url(#default#VML);
|
||||
display: inline-block;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
|
||||
/* control positioning */
|
||||
|
||||
.leaflet-control {
|
||||
position: relative;
|
||||
z-index: 800;
|
||||
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
|
||||
pointer-events: auto;
|
||||
}
|
||||
.leaflet-top,
|
||||
.leaflet-bottom {
|
||||
position: absolute;
|
||||
z-index: 1000;
|
||||
pointer-events: none;
|
||||
}
|
||||
.leaflet-top {
|
||||
top: 0;
|
||||
}
|
||||
.leaflet-right {
|
||||
right: 0;
|
||||
}
|
||||
.leaflet-bottom {
|
||||
bottom: 0;
|
||||
}
|
||||
.leaflet-left {
|
||||
left: 0;
|
||||
}
|
||||
.leaflet-control {
|
||||
float: left;
|
||||
clear: both;
|
||||
}
|
||||
.leaflet-right .leaflet-control {
|
||||
float: right;
|
||||
}
|
||||
.leaflet-top .leaflet-control {
|
||||
margin-top: 10px;
|
||||
}
|
||||
.leaflet-bottom .leaflet-control {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.leaflet-left .leaflet-control {
|
||||
margin-left: 10px;
|
||||
}
|
||||
.leaflet-right .leaflet-control {
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
|
||||
/* zoom and fade animations */
|
||||
|
||||
.leaflet-fade-anim .leaflet-popup {
|
||||
opacity: 0;
|
||||
-webkit-transition: opacity 0.2s linear;
|
||||
-moz-transition: opacity 0.2s linear;
|
||||
transition: opacity 0.2s linear;
|
||||
}
|
||||
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
|
||||
opacity: 1;
|
||||
}
|
||||
.leaflet-zoom-animated {
|
||||
-webkit-transform-origin: 0 0;
|
||||
-ms-transform-origin: 0 0;
|
||||
transform-origin: 0 0;
|
||||
}
|
||||
svg.leaflet-zoom-animated {
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
.leaflet-zoom-anim .leaflet-zoom-animated {
|
||||
-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
|
||||
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
|
||||
transition: transform 0.25s cubic-bezier(0,0,0.25,1);
|
||||
}
|
||||
.leaflet-zoom-anim .leaflet-tile,
|
||||
.leaflet-pan-anim .leaflet-tile {
|
||||
-webkit-transition: none;
|
||||
-moz-transition: none;
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.leaflet-zoom-anim .leaflet-zoom-hide {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
|
||||
/* cursors */
|
||||
|
||||
.leaflet-interactive {
|
||||
cursor: pointer;
|
||||
}
|
||||
.leaflet-grab {
|
||||
cursor: -webkit-grab;
|
||||
cursor: -moz-grab;
|
||||
cursor: grab;
|
||||
}
|
||||
.leaflet-crosshair,
|
||||
.leaflet-crosshair .leaflet-interactive {
|
||||
cursor: crosshair;
|
||||
}
|
||||
.leaflet-popup-pane,
|
||||
.leaflet-control {
|
||||
cursor: auto;
|
||||
}
|
||||
.leaflet-dragging .leaflet-grab,
|
||||
.leaflet-dragging .leaflet-grab .leaflet-interactive,
|
||||
.leaflet-dragging .leaflet-marker-draggable {
|
||||
cursor: move;
|
||||
cursor: -webkit-grabbing;
|
||||
cursor: -moz-grabbing;
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
/* marker & overlays interactivity */
|
||||
.leaflet-marker-icon,
|
||||
.leaflet-marker-shadow,
|
||||
.leaflet-image-layer,
|
||||
.leaflet-pane > svg path,
|
||||
.leaflet-tile-container {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.leaflet-marker-icon.leaflet-interactive,
|
||||
.leaflet-image-layer.leaflet-interactive,
|
||||
.leaflet-pane > svg path.leaflet-interactive,
|
||||
svg.leaflet-image-layer.leaflet-interactive path {
|
||||
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
/* visual tweaks */
|
||||
|
||||
.leaflet-container {
|
||||
background: #ddd;
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.leaflet-container a {
|
||||
color: #0078A8;
|
||||
}
|
||||
.leaflet-zoom-box {
|
||||
border: 2px dotted #38f;
|
||||
background: rgba(255,255,255,0.5);
|
||||
}
|
||||
|
||||
|
||||
/* general typography */
|
||||
.leaflet-container {
|
||||
font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
|
||||
font-size: 12px;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
|
||||
/* general toolbar styles */
|
||||
|
||||
.leaflet-bar {
|
||||
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.leaflet-bar a {
|
||||
background-color: #fff;
|
||||
border-bottom: 1px solid #ccc;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
line-height: 26px;
|
||||
display: block;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
color: black;
|
||||
}
|
||||
.leaflet-bar a,
|
||||
.leaflet-control-layers-toggle {
|
||||
background-position: 50% 50%;
|
||||
background-repeat: no-repeat;
|
||||
display: block;
|
||||
}
|
||||
.leaflet-bar a:hover,
|
||||
.leaflet-bar a:focus {
|
||||
background-color: #f4f4f4;
|
||||
}
|
||||
.leaflet-bar a:first-child {
|
||||
border-top-left-radius: 4px;
|
||||
border-top-right-radius: 4px;
|
||||
}
|
||||
.leaflet-bar a:last-child {
|
||||
border-bottom-left-radius: 4px;
|
||||
border-bottom-right-radius: 4px;
|
||||
border-bottom: none;
|
||||
}
|
||||
.leaflet-bar a.leaflet-disabled {
|
||||
cursor: default;
|
||||
background-color: #f4f4f4;
|
||||
color: #bbb;
|
||||
}
|
||||
|
||||
.leaflet-touch .leaflet-bar a {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
line-height: 30px;
|
||||
}
|
||||
.leaflet-touch .leaflet-bar a:first-child {
|
||||
border-top-left-radius: 2px;
|
||||
border-top-right-radius: 2px;
|
||||
}
|
||||
.leaflet-touch .leaflet-bar a:last-child {
|
||||
border-bottom-left-radius: 2px;
|
||||
border-bottom-right-radius: 2px;
|
||||
}
|
||||
|
||||
/* zoom control */
|
||||
|
||||
.leaflet-control-zoom-in,
|
||||
.leaflet-control-zoom-out {
|
||||
font: bold 18px 'Lucida Console', Monaco, monospace;
|
||||
text-indent: 1px;
|
||||
}
|
||||
|
||||
.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
|
||||
/* layers control */
|
||||
|
||||
.leaflet-control-layers {
|
||||
box-shadow: 0 1px 5px rgba(0,0,0,0.4);
|
||||
background: #fff;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.leaflet-control-layers-toggle {
|
||||
background-image: url(images/layers.png);
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
.leaflet-retina .leaflet-control-layers-toggle {
|
||||
background-image: url(images/layers-2x.png);
|
||||
background-size: 26px 26px;
|
||||
}
|
||||
.leaflet-touch .leaflet-control-layers-toggle {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
}
|
||||
.leaflet-control-layers .leaflet-control-layers-list,
|
||||
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
|
||||
display: none;
|
||||
}
|
||||
.leaflet-control-layers-expanded .leaflet-control-layers-list {
|
||||
display: block;
|
||||
position: relative;
|
||||
}
|
||||
.leaflet-control-layers-expanded {
|
||||
padding: 6px 10px 6px 6px;
|
||||
color: #333;
|
||||
background: #fff;
|
||||
}
|
||||
.leaflet-control-layers-scrollbar {
|
||||
overflow-y: scroll;
|
||||
overflow-x: hidden;
|
||||
padding-right: 5px;
|
||||
}
|
||||
.leaflet-control-layers-selector {
|
||||
margin-top: 2px;
|
||||
position: relative;
|
||||
top: 1px;
|
||||
}
|
||||
.leaflet-control-layers label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-size: 1.08333em;
|
||||
}
|
||||
.leaflet-control-layers-separator {
|
||||
height: 0;
|
||||
border-top: 1px solid #ddd;
|
||||
margin: 5px -10px 5px -6px;
|
||||
}
|
||||
|
||||
/* Default icon URLs */
|
||||
.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
|
||||
background-image: url(images/marker-icon.png);
|
||||
}
|
||||
|
||||
|
||||
/* attribution and scale controls */
|
||||
|
||||
.leaflet-container .leaflet-control-attribution {
|
||||
background: #fff;
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
margin: 0;
|
||||
}
|
||||
.leaflet-control-attribution,
|
||||
.leaflet-control-scale-line {
|
||||
padding: 0 5px;
|
||||
color: #333;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.leaflet-control-attribution a {
|
||||
text-decoration: none;
|
||||
}
|
||||
.leaflet-control-attribution a:hover,
|
||||
.leaflet-control-attribution a:focus {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.leaflet-attribution-flag {
|
||||
display: inline !important;
|
||||
vertical-align: baseline !important;
|
||||
width: 1em;
|
||||
height: 0.6669em;
|
||||
}
|
||||
.leaflet-left .leaflet-control-scale {
|
||||
margin-left: 5px;
|
||||
}
|
||||
.leaflet-bottom .leaflet-control-scale {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.leaflet-control-scale-line {
|
||||
border: 2px solid #777;
|
||||
border-top: none;
|
||||
line-height: 1.1;
|
||||
padding: 2px 5px 1px;
|
||||
white-space: nowrap;
|
||||
-moz-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
text-shadow: 1px 1px #fff;
|
||||
}
|
||||
.leaflet-control-scale-line:not(:first-child) {
|
||||
border-top: 2px solid #777;
|
||||
border-bottom: none;
|
||||
margin-top: -2px;
|
||||
}
|
||||
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
|
||||
border-bottom: 2px solid #777;
|
||||
}
|
||||
|
||||
.leaflet-touch .leaflet-control-attribution,
|
||||
.leaflet-touch .leaflet-control-layers,
|
||||
.leaflet-touch .leaflet-bar {
|
||||
box-shadow: none;
|
||||
}
|
||||
.leaflet-touch .leaflet-control-layers,
|
||||
.leaflet-touch .leaflet-bar {
|
||||
border: 2px solid rgba(0,0,0,0.2);
|
||||
background-clip: padding-box;
|
||||
}
|
||||
|
||||
|
||||
/* popup */
|
||||
|
||||
.leaflet-popup {
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.leaflet-popup-content-wrapper {
|
||||
padding: 1px;
|
||||
text-align: left;
|
||||
border-radius: 12px;
|
||||
}
|
||||
.leaflet-popup-content {
|
||||
margin: 13px 24px 13px 20px;
|
||||
line-height: 1.3;
|
||||
font-size: 13px;
|
||||
font-size: 1.08333em;
|
||||
min-height: 1px;
|
||||
}
|
||||
.leaflet-popup-content p {
|
||||
margin: 17px 0;
|
||||
margin: 1.3em 0;
|
||||
}
|
||||
.leaflet-popup-tip-container {
|
||||
width: 40px;
|
||||
height: 20px;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
margin-top: -1px;
|
||||
margin-left: -20px;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
.leaflet-popup-tip {
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
padding: 1px;
|
||||
|
||||
margin: -10px auto 0;
|
||||
pointer-events: auto;
|
||||
|
||||
-webkit-transform: rotate(45deg);
|
||||
-moz-transform: rotate(45deg);
|
||||
-ms-transform: rotate(45deg);
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
.leaflet-popup-content-wrapper,
|
||||
.leaflet-popup-tip {
|
||||
background: white;
|
||||
color: #333;
|
||||
box-shadow: 0 3px 14px rgba(0,0,0,0.4);
|
||||
}
|
||||
.leaflet-container a.leaflet-popup-close-button {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
border: none;
|
||||
text-align: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
font: 16px/24px Tahoma, Verdana, sans-serif;
|
||||
color: #757575;
|
||||
text-decoration: none;
|
||||
background: transparent;
|
||||
}
|
||||
.leaflet-container a.leaflet-popup-close-button:hover,
|
||||
.leaflet-container a.leaflet-popup-close-button:focus {
|
||||
color: #585858;
|
||||
}
|
||||
.leaflet-popup-scrolled {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.leaflet-oldie .leaflet-popup-content-wrapper {
|
||||
-ms-zoom: 1;
|
||||
}
|
||||
.leaflet-oldie .leaflet-popup-tip {
|
||||
width: 24px;
|
||||
margin: 0 auto;
|
||||
|
||||
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
|
||||
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
|
||||
}
|
||||
|
||||
.leaflet-oldie .leaflet-control-zoom,
|
||||
.leaflet-oldie .leaflet-control-layers,
|
||||
.leaflet-oldie .leaflet-popup-content-wrapper,
|
||||
.leaflet-oldie .leaflet-popup-tip {
|
||||
border: 1px solid #999;
|
||||
}
|
||||
|
||||
|
||||
/* div icon */
|
||||
|
||||
.leaflet-div-icon {
|
||||
background: #fff;
|
||||
border: 1px solid #666;
|
||||
}
|
||||
|
||||
|
||||
/* Tooltip */
|
||||
/* Base styles for the element that has a tooltip */
|
||||
.leaflet-tooltip {
|
||||
position: absolute;
|
||||
padding: 6px;
|
||||
background-color: #fff;
|
||||
border: 1px solid #fff;
|
||||
border-radius: 3px;
|
||||
color: #222;
|
||||
white-space: nowrap;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
|
||||
}
|
||||
.leaflet-tooltip.leaflet-interactive {
|
||||
cursor: pointer;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.leaflet-tooltip-top:before,
|
||||
.leaflet-tooltip-bottom:before,
|
||||
.leaflet-tooltip-left:before,
|
||||
.leaflet-tooltip-right:before {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
border: 6px solid transparent;
|
||||
background: transparent;
|
||||
content: "";
|
||||
}
|
||||
|
||||
/* Directions */
|
||||
|
||||
.leaflet-tooltip-bottom {
|
||||
margin-top: 6px;
|
||||
}
|
||||
.leaflet-tooltip-top {
|
||||
margin-top: -6px;
|
||||
}
|
||||
.leaflet-tooltip-bottom:before,
|
||||
.leaflet-tooltip-top:before {
|
||||
left: 50%;
|
||||
margin-left: -6px;
|
||||
}
|
||||
.leaflet-tooltip-top:before {
|
||||
bottom: 0;
|
||||
margin-bottom: -12px;
|
||||
border-top-color: #fff;
|
||||
}
|
||||
.leaflet-tooltip-bottom:before {
|
||||
top: 0;
|
||||
margin-top: -12px;
|
||||
margin-left: -6px;
|
||||
border-bottom-color: #fff;
|
||||
}
|
||||
.leaflet-tooltip-left {
|
||||
margin-left: -6px;
|
||||
}
|
||||
.leaflet-tooltip-right {
|
||||
margin-left: 6px;
|
||||
}
|
||||
.leaflet-tooltip-left:before,
|
||||
.leaflet-tooltip-right:before {
|
||||
top: 50%;
|
||||
margin-top: -6px;
|
||||
}
|
||||
.leaflet-tooltip-left:before {
|
||||
right: 0;
|
||||
margin-right: -12px;
|
||||
border-left-color: #fff;
|
||||
}
|
||||
.leaflet-tooltip-right:before {
|
||||
left: 0;
|
||||
margin-left: -12px;
|
||||
border-right-color: #fff;
|
||||
}
|
||||
|
||||
/* Printing */
|
||||
|
||||
@media print {
|
||||
/* Prevent printers from removing background-images of controls. */
|
||||
.leaflet-control {
|
||||
-webkit-print-color-adjust: exact;
|
||||
print-color-adjust: exact;
|
||||
}
|
||||
}
|
||||
6
assets/vendor/leaflet/leaflet.js
vendored
6
assets/vendor/leaflet/leaflet.js
vendored
File diff suppressed because one or more lines are too long
|
|
@ -61,11 +61,6 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($
|
|||
<link rel="icon" type="image/png" sizes="32x32" href="/assets/images/favicon-32.png">
|
||||
<link rel="icon" type="image/png" sizes="48x48" href="/assets/images/favicon-48.png">
|
||||
<link rel="apple-touch-icon" href="/assets/images/apple-touch-icon.png">
|
||||
<?php if ($currentScript === 'map.php'): ?>
|
||||
<!-- Vor style.css, damit die eigenen Anpassungen an Leaflet-Elementen (Popups,
|
||||
Zoom-Buttons) bei gleicher Spezifitaet gewinnen. -->
|
||||
<link rel="stylesheet" href="/assets/vendor/leaflet/leaflet.css">
|
||||
<?php endif; ?>
|
||||
<link rel="stylesheet" href="/assets/css/style.css">
|
||||
</head>
|
||||
<body<?= $currentUser ? '' : ' class="guest-bg"' ?>>
|
||||
|
|
|
|||
365
includes/map.php
365
includes/map.php
|
|
@ -1,365 +0,0 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Datenschicht der Taktikkarte. Anders als Raids/Premades/Reports/Events haengt die Karte
|
||||
* nicht am Discord-Bot, sondern liegt komplett in der Website-Datenbank - der Bot kennt
|
||||
* weder Kartenkacheln noch Marker.
|
||||
*/
|
||||
|
||||
// Verzeichnis, in dem die gekachelten Karten liegen (je Karte ein Unterordner mit
|
||||
// tiles.json + Zoomstufen-Ordnern, erzeugt von tools/make_map_tiles.php).
|
||||
const MAP_TILES_DIR = __DIR__ . '/../assets/uploads/maps';
|
||||
const MAP_TILES_URL = '/assets/uploads/maps';
|
||||
|
||||
/**
|
||||
* Die Tabellen, die diese Seite braucht - in Anlegereihenfolge (Fremdschluessel!).
|
||||
*/
|
||||
const MAP_TABLES = ['map_categories', 'map_markers', 'map_tactics', 'map_tactic_shapes'];
|
||||
|
||||
/**
|
||||
* Welche der Kartentabellen fehlen noch? Bei einer Installation, die es schon vor dem
|
||||
* Karten-Update gab, sind das alle vier - ohne diese Pruefung wuerde die erste Abfrage
|
||||
* mit einer PDOException und damit HTTP 500 aussteigen.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
function map_missing_tables(): array
|
||||
{
|
||||
$placeholders = implode(',', array_fill(0, count(MAP_TABLES), '?'));
|
||||
$stmt = db()->prepare(
|
||||
"SELECT table_name FROM information_schema.tables
|
||||
WHERE table_schema = DATABASE() AND table_name IN ($placeholders)"
|
||||
);
|
||||
$stmt->execute(MAP_TABLES);
|
||||
|
||||
$existing = array_map('strtolower', $stmt->fetchAll(PDO::FETCH_COLUMN));
|
||||
|
||||
return array_values(array_filter(
|
||||
MAP_TABLES,
|
||||
static fn (string $table): bool => !in_array(strtolower($table), $existing, true)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Zieht die CREATE-TABLE-Befehle der Kartentabellen aus sql/schema.sql. Damit gibt es
|
||||
* genau eine Quelle fuer die Struktur - das Schema kann nicht von dem abweichen, was
|
||||
* hier angelegt wird.
|
||||
*
|
||||
* @return array<string, string> Tabellenname => SQL-Befehl
|
||||
*/
|
||||
function map_schema_statements(): array
|
||||
{
|
||||
$path = __DIR__ . '/../sql/schema.sql';
|
||||
if (!is_file($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$schema = (string) file_get_contents($path);
|
||||
$statements = [];
|
||||
foreach (MAP_TABLES as $table) {
|
||||
$pattern = '/CREATE TABLE IF NOT EXISTS\s+' . preg_quote($table, '/') . '\s*\(.*?\)\s*ENGINE[^;]*;/s';
|
||||
if (preg_match($pattern, $schema, $match) === 1) {
|
||||
$statements[$table] = $match[0];
|
||||
}
|
||||
}
|
||||
|
||||
return $statements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt die fehlenden Kartentabellen an. Die Befehle sind alle "IF NOT EXISTS", ein
|
||||
* zweiter Aufruf richtet also keinen Schaden an.
|
||||
*
|
||||
* @return int Anzahl ausgefuehrter Befehle
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
function map_create_tables(): int
|
||||
{
|
||||
$statements = map_schema_statements();
|
||||
if (count($statements) !== count(MAP_TABLES)) {
|
||||
throw new RuntimeException(
|
||||
'sql/schema.sql wurde nicht gefunden oder enthält nicht alle Kartentabellen - '
|
||||
. 'bitte den Abschnitt "Taktikkarte" aus sql/schema.sql von Hand ausführen.'
|
||||
);
|
||||
}
|
||||
|
||||
$pdo = db();
|
||||
foreach ($statements as $sql) {
|
||||
$pdo->exec($sql);
|
||||
}
|
||||
|
||||
return count($statements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liest die verfuegbaren Karten aus dem Kachel-Verzeichnis. Jede Karte beschreibt sich
|
||||
* ueber ihre eigene tiles.json selbst, dadurch kommt eine neue Region dazu, ohne dass
|
||||
* Code oder Datenbank angefasst werden muessen.
|
||||
*
|
||||
* @return array<string, array<string, mixed>> Kartenschluessel => Manifest
|
||||
*/
|
||||
function map_available(): array
|
||||
{
|
||||
if (!is_dir(MAP_TILES_DIR)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$maps = [];
|
||||
foreach (scandir(MAP_TILES_DIR) ?: [] as $entry) {
|
||||
if ($entry === '.' || $entry === '..') {
|
||||
continue;
|
||||
}
|
||||
$manifestPath = MAP_TILES_DIR . '/' . $entry . '/tiles.json';
|
||||
if (!is_file($manifestPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$manifest = json_decode((string) file_get_contents($manifestPath), true);
|
||||
if (!is_array($manifest) || empty($manifest['width']) || empty($manifest['height'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$manifest['key'] = $entry;
|
||||
$manifest['name'] = (string) ($manifest['name'] ?? ucfirst($entry));
|
||||
$manifest['url_template'] = MAP_TILES_URL . '/' . rawurlencode($entry) . '/{z}/{x}_{y}.'
|
||||
. (string) ($manifest['extension'] ?? 'jpg');
|
||||
$maps[$entry] = $manifest;
|
||||
}
|
||||
|
||||
ksort($maps);
|
||||
return $maps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kategorien als zweistufige Struktur (Gruppen mit ihren Kategorien), inklusive der
|
||||
* Marker-Anzahl je Kategorie - genau die Zahlen, die in der Sidebar hinter den Namen
|
||||
* stehen.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
function map_category_tree(string $mapKey): array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT c.id, c.parent_id, c.name, c.icon, c.color, c.sort_order,
|
||||
(SELECT COUNT(*) FROM map_markers m WHERE m.category_id = c.id AND m.map_key = ?) AS marker_count
|
||||
FROM map_categories c
|
||||
ORDER BY c.sort_order ASC, c.name ASC'
|
||||
);
|
||||
$stmt->execute([$mapKey]);
|
||||
$rows = $stmt->fetchAll();
|
||||
|
||||
$groups = [];
|
||||
$children = [];
|
||||
foreach ($rows as $row) {
|
||||
if ($row['parent_id'] === null) {
|
||||
$row['children'] = [];
|
||||
$row['total_count'] = 0;
|
||||
$groups[(int) $row['id']] = $row;
|
||||
} else {
|
||||
$children[(int) $row['parent_id']][] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($groups as $id => $group) {
|
||||
$groupChildren = $children[$id] ?? [];
|
||||
$groups[$id]['children'] = $groupChildren;
|
||||
$groups[$id]['total_count'] = array_sum(array_map(
|
||||
fn (array $child): int => (int) $child['marker_count'],
|
||||
$groupChildren
|
||||
));
|
||||
}
|
||||
|
||||
// Kategorien, deren Gruppe geloescht wurde, waeren sonst unsichtbar.
|
||||
$orphans = [];
|
||||
foreach ($children as $parentId => $list) {
|
||||
if (!isset($groups[$parentId])) {
|
||||
$orphans = array_merge($orphans, $list);
|
||||
}
|
||||
}
|
||||
if (!empty($orphans)) {
|
||||
$groups[0] = [
|
||||
'id' => 0,
|
||||
'parent_id' => null,
|
||||
'name' => 'Ohne Gruppe',
|
||||
'icon' => '',
|
||||
'color' => '#a0a0a0',
|
||||
'sort_order' => 9999,
|
||||
'children' => $orphans,
|
||||
'total_count' => array_sum(array_map(fn (array $c): int => (int) $c['marker_count'], $orphans)),
|
||||
];
|
||||
}
|
||||
|
||||
return array_values($groups);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Marker einer Karte, fertig fuer die Uebergabe an das Frontend.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
function map_markers(string $mapKey): array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT m.id, m.category_id, m.name, m.description, m.pos_x, m.pos_y,
|
||||
u.display_name, u.username
|
||||
FROM map_markers m
|
||||
LEFT JOIN users u ON u.id = m.created_by
|
||||
WHERE m.map_key = ?
|
||||
ORDER BY m.id ASC'
|
||||
);
|
||||
$stmt->execute([$mapKey]);
|
||||
|
||||
return array_map(static function (array $row): array {
|
||||
$author = trim((string) ($row['display_name'] ?? '')) !== ''
|
||||
? (string) $row['display_name']
|
||||
: (string) ($row['username'] ?? '');
|
||||
|
||||
return [
|
||||
'id' => (int) $row['id'],
|
||||
'category_id' => (int) $row['category_id'],
|
||||
'name' => (string) $row['name'],
|
||||
'description' => (string) ($row['description'] ?? ''),
|
||||
'x' => (float) $row['pos_x'],
|
||||
'y' => (float) $row['pos_y'],
|
||||
'author' => $author,
|
||||
];
|
||||
}, $stmt->fetchAll());
|
||||
}
|
||||
|
||||
/**
|
||||
* Taktiken einer Karte samt ihrer Zeichenobjekte.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
function map_tactics(string $mapKey): array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT t.id, t.name, t.description, t.updated_at, t.created_at, u.display_name, u.username
|
||||
FROM map_tactics t
|
||||
LEFT JOIN users u ON u.id = t.created_by
|
||||
WHERE t.map_key = ?
|
||||
ORDER BY t.name ASC'
|
||||
);
|
||||
$stmt->execute([$mapKey]);
|
||||
$tactics = $stmt->fetchAll();
|
||||
|
||||
if (empty($tactics)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$ids = array_map(fn (array $t): int => (int) $t['id'], $tactics);
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
$shapeStmt = db()->prepare(
|
||||
"SELECT id, tactic_id, shape_type, label, color, points, sort_order
|
||||
FROM map_tactic_shapes WHERE tactic_id IN ($placeholders)
|
||||
ORDER BY sort_order ASC, id ASC"
|
||||
);
|
||||
$shapeStmt->execute($ids);
|
||||
|
||||
$shapesByTactic = [];
|
||||
foreach ($shapeStmt->fetchAll() as $shape) {
|
||||
$points = json_decode((string) $shape['points'], true);
|
||||
$shapesByTactic[(int) $shape['tactic_id']][] = [
|
||||
'id' => (int) $shape['id'],
|
||||
'type' => (string) $shape['shape_type'],
|
||||
'label' => (string) $shape['label'],
|
||||
'color' => (string) $shape['color'],
|
||||
'points' => is_array($points) ? $points : [],
|
||||
];
|
||||
}
|
||||
|
||||
return array_map(static function (array $tactic) use ($shapesByTactic): array {
|
||||
$author = trim((string) ($tactic['display_name'] ?? '')) !== ''
|
||||
? (string) $tactic['display_name']
|
||||
: (string) ($tactic['username'] ?? '');
|
||||
|
||||
return [
|
||||
'id' => (int) $tactic['id'],
|
||||
'name' => (string) $tactic['name'],
|
||||
'description' => (string) ($tactic['description'] ?? ''),
|
||||
'author' => $author,
|
||||
'updated_at' => (string) ($tactic['updated_at'] ?? $tactic['created_at'] ?? ''),
|
||||
'shapes' => $shapesByTactic[(int) $tactic['id']] ?? [],
|
||||
];
|
||||
}, $tactics);
|
||||
}
|
||||
|
||||
/**
|
||||
* Startbestueckung der Kategorien, angelehnt an die Gliederung gaengiger Aion-Karten.
|
||||
* Wird nur angeboten, solange ueberhaupt keine Kategorie existiert - danach pflegt ihr
|
||||
* die Liste selbst.
|
||||
*
|
||||
* @return array<int, array{name: string, icon: string, color: string, children: array<int, array{0: string, 1: string}>}>
|
||||
*/
|
||||
function map_default_categories(): array
|
||||
{
|
||||
return [
|
||||
['name' => 'Orte', 'icon' => '🏰', 'color' => '#c9a227', 'children' => [
|
||||
['Siedlung', '🏘'], ['Region', '🚩'], ['Festung', '🛡'], ['Dungeon', '🕳'], ['Rift', '🌀'],
|
||||
]],
|
||||
['name' => 'Sammelbares', 'icon' => '💠', 'color' => '#4fc3f7', 'children' => [
|
||||
['Empyreische Spur', '✨'], ['Versteckter Würfel', '🎁'], ['Boss', '💀'],
|
||||
]],
|
||||
['name' => 'NPCs', 'icon' => '🧝', 'color' => '#81c784', 'children' => [
|
||||
['Händler', '💰'], ['Handwerksstation', '⚒'], ['Lagerverwalter', '📦'], ['Instanz-Eingang', '🚪'],
|
||||
]],
|
||||
['name' => 'Quests', 'icon' => '📜', 'color' => '#ffb74d', 'children' => [
|
||||
['Regionsquest', '❗'], ['Story-Quest', '📖'],
|
||||
]],
|
||||
['name' => 'Ressourcen', 'icon' => '⛏', 'color' => '#a1887f', 'children' => [
|
||||
['Erz', '⛏'], ['Edelstein', '💎'], ['Holz', '🪵'], ['Kraut', '🌿'],
|
||||
]],
|
||||
['name' => 'Monster', 'icon' => '🐉', 'color' => '#e57373', 'children' => [
|
||||
['Namhafter Boss', '👑'], ['Elite', '⚔'], ['Normal', '🐾'],
|
||||
]],
|
||||
['name' => 'Gilde', 'icon' => '⚜', 'color' => '#ba68c8', 'children' => [
|
||||
['Sammelpunkt', '📍'], ['Eigene Notiz', '📝'],
|
||||
]],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt die Standard-Kategorien an. Gibt die Anzahl der erzeugten Kategorien zurueck.
|
||||
*/
|
||||
function map_seed_default_categories(): int
|
||||
{
|
||||
$pdo = db();
|
||||
$created = 0;
|
||||
$sort = 0;
|
||||
|
||||
foreach (map_default_categories() as $group) {
|
||||
$sort += 10;
|
||||
$stmt = $pdo->prepare('INSERT INTO map_categories (parent_id, name, icon, color, sort_order) VALUES (NULL, ?, ?, ?, ?)');
|
||||
$stmt->execute([$group['name'], $group['icon'], $group['color'], $sort]);
|
||||
$groupId = (int) $pdo->lastInsertId();
|
||||
$created++;
|
||||
|
||||
$childSort = 0;
|
||||
foreach ($group['children'] as $child) {
|
||||
$childSort += 10;
|
||||
$childStmt = $pdo->prepare('INSERT INTO map_categories (parent_id, name, icon, color, sort_order) VALUES (?, ?, ?, ?, ?)');
|
||||
$childStmt->execute([$groupId, $child[0], $child[1], $group['color'], $childSort]);
|
||||
$created++;
|
||||
}
|
||||
}
|
||||
|
||||
return $created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prueft eine normierte Koordinate (0..1). Alles ausserhalb waere ausserhalb des
|
||||
* Kartenbildes und damit unerreichbar.
|
||||
*/
|
||||
function map_valid_coordinate($value): bool
|
||||
{
|
||||
return is_numeric($value) && (float) $value >= 0.0 && (float) $value <= 1.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prueft eine Farbangabe im Format #rrggbb.
|
||||
*/
|
||||
function map_valid_color(string $color): bool
|
||||
{
|
||||
return preg_match('/^#[0-9a-fA-F]{6}$/', $color) === 1;
|
||||
}
|
||||
|
|
@ -1,274 +0,0 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__ . '/map.php';
|
||||
|
||||
/**
|
||||
* Serverseite des Karten-Bauens.
|
||||
*
|
||||
* Geschnitten werden die Kacheln im Browser (siehe assets/js/map_build.js) - hier kommen
|
||||
* nur noch fertige 256er-JPEGs an, die geprueft und abgelegt werden. Das ist Absicht:
|
||||
* ein grosses Kartenbild serverseitig zu zerlegen scheitert auf typischem Webspace an
|
||||
* memory_limit, max_execution_time, fehlendem GD oder upload_max_filesize. So braucht
|
||||
* der Server nichts davon.
|
||||
*
|
||||
* Gebaut wird immer in einen Nebenordner "<schluessel>__build"; erst wenn alle Kacheln
|
||||
* oben sind, tritt er an die Stelle der alten Karte. Bricht der Vorgang ab, bleibt die
|
||||
* bisherige Karte unangetastet.
|
||||
*/
|
||||
|
||||
const MAP_BUILD_SUFFIX = '__build';
|
||||
|
||||
/** Obergrenze je hochgeladener Kachel - 256x256 JPEG liegt weit darunter. */
|
||||
const MAP_BUILD_MAX_TILE_BYTES = 512 * 1024;
|
||||
|
||||
/** Schutz vor absurden Angaben; 12 Stufen waeren ein 1-Million-Pixel-Quadrat. */
|
||||
const MAP_BUILD_MAX_ZOOM = 12;
|
||||
|
||||
/**
|
||||
* Prueft einen Kartenschluessel. Er wird zu einem Ordnernamen, darf also nichts
|
||||
* enthalten, was aus dem Kartenverzeichnis herausfuehren koennte.
|
||||
*/
|
||||
function map_build_valid_key(string $key): bool
|
||||
{
|
||||
return preg_match('/^[a-z0-9][a-z0-9_-]{0,48}$/', $key) === 1;
|
||||
}
|
||||
|
||||
function map_build_dir(string $key): string
|
||||
{
|
||||
return MAP_TILES_DIR . '/' . $key . MAP_BUILD_SUFFIX;
|
||||
}
|
||||
|
||||
function map_build_state_path(string $key): string
|
||||
{
|
||||
return map_build_dir($key) . '/build.json';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
function map_build_state(string $key): ?array
|
||||
{
|
||||
$path = map_build_state_path($key);
|
||||
if (!is_file($path)) {
|
||||
return null;
|
||||
}
|
||||
$state = json_decode((string) file_get_contents($path), true);
|
||||
|
||||
return is_array($state) ? $state : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt den Bauordner an (ein eventuell vorhandener Rest wird verworfen) und merkt sich,
|
||||
* was am Ende in die tiles.json gehoert.
|
||||
*
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
function map_build_begin(string $key, string $name, int $width, int $height, int $tileSize, int $maxZoom): void
|
||||
{
|
||||
if (!map_build_valid_key($key)) {
|
||||
throw new RuntimeException('Ungültiger Kartenschlüssel (erlaubt: a-z, 0-9, - und _).');
|
||||
}
|
||||
if ($width < 1 || $height < 1 || $width > 200000 || $height > 200000) {
|
||||
throw new RuntimeException('Unplausible Bildgröße.');
|
||||
}
|
||||
if ($tileSize < 64 || $tileSize > 1024) {
|
||||
throw new RuntimeException('Ungültige Kachelgröße.');
|
||||
}
|
||||
if ($maxZoom < 0 || $maxZoom > MAP_BUILD_MAX_ZOOM) {
|
||||
throw new RuntimeException('Ungültige Anzahl Zoomstufen.');
|
||||
}
|
||||
|
||||
$dir = map_build_dir($key);
|
||||
if (is_dir($dir)) {
|
||||
map_build_remove_dir($dir);
|
||||
}
|
||||
if (!mkdir($dir, 0775, true) && !is_dir($dir)) {
|
||||
throw new RuntimeException('Der Ordner für die Karte konnte nicht angelegt werden. '
|
||||
. 'Ist assets/uploads/maps/ für den Webserver beschreibbar?');
|
||||
}
|
||||
|
||||
$state = [
|
||||
'key' => $key,
|
||||
'name' => $name !== '' ? $name : ucfirst($key),
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'tile_size' => $tileSize,
|
||||
'min_zoom' => 0,
|
||||
'max_zoom' => $maxZoom,
|
||||
'extension' => 'jpg',
|
||||
'tiles_written' => 0,
|
||||
'started_at' => date('c'),
|
||||
];
|
||||
|
||||
file_put_contents(map_build_state_path($key), json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* Nimmt eine hochgeladene Kachel entgegen.
|
||||
*
|
||||
* @param array<string, mixed> $file Ein Eintrag aus $_FILES
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
function map_build_store_tile(array $state, array $file, int $z, int $x, int $y): void
|
||||
{
|
||||
$key = (string) $state['key'];
|
||||
$maxZoom = (int) $state['max_zoom'];
|
||||
|
||||
if ($z < 0 || $z > $maxZoom) {
|
||||
throw new RuntimeException("Zoomstufe $z liegt außerhalb der Karte.");
|
||||
}
|
||||
// Auf jeder Stufe gibt es hoechstens 2^z Kacheln je Achse - alles darueber waere
|
||||
// ein Versuch, irgendwohin sonst zu schreiben.
|
||||
$limit = 1 << $z;
|
||||
if ($x < 0 || $y < 0 || $x >= $limit || $y >= $limit) {
|
||||
throw new RuntimeException("Kachel $z/$x/$y liegt außerhalb der Karte.");
|
||||
}
|
||||
|
||||
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
|
||||
throw new RuntimeException("Kachel $z/$x/$y wurde nicht vollständig übertragen.");
|
||||
}
|
||||
if (($file['size'] ?? 0) > MAP_BUILD_MAX_TILE_BYTES) {
|
||||
throw new RuntimeException("Kachel $z/$x/$y ist zu groß.");
|
||||
}
|
||||
|
||||
$tmp = (string) ($file['tmp_name'] ?? '');
|
||||
if (!is_uploaded_file($tmp)) {
|
||||
throw new RuntimeException('Ungültiger Upload.');
|
||||
}
|
||||
|
||||
// Nicht dem Dateinamen oder dem gemeldeten Typ trauen, sondern den Inhalt ansehen.
|
||||
$info = @getimagesize($tmp);
|
||||
if ($info === false || $info[2] !== IMAGETYPE_JPEG) {
|
||||
throw new RuntimeException("Kachel $z/$x/$y ist kein JPEG.");
|
||||
}
|
||||
if ($info[0] > 1024 || $info[1] > 1024) {
|
||||
throw new RuntimeException("Kachel $z/$x/$y hat unerwartete Maße.");
|
||||
}
|
||||
|
||||
$zoomDir = map_build_dir($key) . '/' . $z;
|
||||
if (!is_dir($zoomDir) && !mkdir($zoomDir, 0775, true) && !is_dir($zoomDir)) {
|
||||
throw new RuntimeException("Ordner für Zoomstufe $z konnte nicht angelegt werden.");
|
||||
}
|
||||
|
||||
if (!move_uploaded_file($tmp, $zoomDir . '/' . $x . '_' . $y . '.jpg')) {
|
||||
throw new RuntimeException("Kachel $z/$x/$y konnte nicht gespeichert werden.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Zaehlt die abgelegten Kacheln im Bauordner mit. */
|
||||
function map_build_count(string $key, int $written): void
|
||||
{
|
||||
$state = map_build_state($key);
|
||||
if ($state === null) {
|
||||
return;
|
||||
}
|
||||
$state['tiles_written'] = (int) ($state['tiles_written'] ?? 0) + $written;
|
||||
file_put_contents(map_build_state_path($key), json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* Schliesst den Bau ab: tiles.json schreiben und den Bauordner an die Stelle der alten
|
||||
* Karte setzen. Erst hier wird die bisherige Karte ersetzt.
|
||||
*
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
function map_build_finish(string $key): int
|
||||
{
|
||||
$state = map_build_state($key);
|
||||
if ($state === null) {
|
||||
throw new RuntimeException('Zu dieser Karte läuft kein Bauvorgang.');
|
||||
}
|
||||
|
||||
$manifest = [
|
||||
'name' => $state['name'],
|
||||
'width' => (int) $state['width'],
|
||||
'height' => (int) $state['height'],
|
||||
'tile_size' => (int) $state['tile_size'],
|
||||
'min_zoom' => (int) $state['min_zoom'],
|
||||
'max_zoom' => (int) $state['max_zoom'],
|
||||
'extension' => 'jpg',
|
||||
'generated_at' => date('c'),
|
||||
];
|
||||
|
||||
$buildDir = map_build_dir($key);
|
||||
file_put_contents(
|
||||
$buildDir . '/tiles.json',
|
||||
json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
||||
);
|
||||
@unlink(map_build_state_path($key));
|
||||
|
||||
$target = MAP_TILES_DIR . '/' . $key;
|
||||
if (is_dir($target)) {
|
||||
// Erst zur Seite schieben, damit bei einem Fehler beim Umbenennen nicht beide
|
||||
// Stände weg sind.
|
||||
$retired = $target . '__old_' . bin2hex(random_bytes(4));
|
||||
if (!rename($target, $retired)) {
|
||||
throw new RuntimeException('Die bisherige Karte konnte nicht ersetzt werden (Schreibrechte?).');
|
||||
}
|
||||
if (!rename($buildDir, $target)) {
|
||||
rename($retired, $target);
|
||||
throw new RuntimeException('Die neue Karte konnte nicht aktiviert werden (Schreibrechte?).');
|
||||
}
|
||||
map_build_remove_dir($retired);
|
||||
} elseif (!rename($buildDir, $target)) {
|
||||
throw new RuntimeException('Die neue Karte konnte nicht aktiviert werden (Schreibrechte?).');
|
||||
}
|
||||
|
||||
return (int) ($state['tiles_written'] ?? 0);
|
||||
}
|
||||
|
||||
/** Bricht einen Bauvorgang ab und raeumt den Nebenordner weg. */
|
||||
function map_build_abort(string $key): void
|
||||
{
|
||||
if (!map_build_valid_key($key)) {
|
||||
return;
|
||||
}
|
||||
$dir = map_build_dir($key);
|
||||
if (is_dir($dir)) {
|
||||
map_build_remove_dir($dir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loescht ein Verzeichnis samt Inhalt. Bewusst eng gehalten: nur innerhalb des
|
||||
* Kartenverzeichnisses, keine Symlinks.
|
||||
*/
|
||||
function map_build_remove_dir(string $dir): void
|
||||
{
|
||||
$base = realpath(MAP_TILES_DIR);
|
||||
$real = realpath($dir);
|
||||
if ($base === false || $real === false || !str_starts_with($real, $base . DIRECTORY_SEPARATOR)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($real, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
foreach ($items as $item) {
|
||||
if ($item->isDir() && !$item->isLink()) {
|
||||
@rmdir($item->getPathname());
|
||||
} else {
|
||||
@unlink($item->getPathname());
|
||||
}
|
||||
}
|
||||
@rmdir($real);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie viele Kacheln ein Bild ergibt - fuer die Fortschrittsanzeige und um dem Nutzer
|
||||
* vorab zu sagen, worauf er sich einlaesst.
|
||||
*/
|
||||
function map_build_tile_count(int $width, int $height, int $tileSize, int $maxZoom): int
|
||||
{
|
||||
$total = 0;
|
||||
for ($z = 0; $z <= $maxZoom; $z++) {
|
||||
$scale = 2 ** ($z - $maxZoom);
|
||||
$levelWidth = max(1, (int) round($width * $scale));
|
||||
$levelHeight = max(1, (int) round($height * $scale));
|
||||
$total += (int) (ceil($levelWidth / $tileSize) * ceil($levelHeight / $tileSize));
|
||||
}
|
||||
|
||||
return $total;
|
||||
}
|
||||
|
|
@ -18,9 +18,7 @@ const CORE_PERMISSIONS = [
|
|||
['key' => 'premades.manage', 'description' => 'Alle Premade-Gruppen verwalten (nicht nur die eigene)'],
|
||||
['key' => 'events.view', 'description' => 'Geplante Event-Erinnerungen einsehen'],
|
||||
['key' => 'events.manage', 'description' => 'Event-Erinnerungen planen, bearbeiten und löschen'],
|
||||
['key' => 'map.view', 'description' => 'Taktikkarte ansehen'],
|
||||
['key' => 'map.manage', 'description' => 'Marker und Kategorien der Karte verwalten'],
|
||||
['key' => 'map.tactics', 'description' => 'Taktiken auf der Karte anlegen und bearbeiten'],
|
||||
['key' => 'map.view', 'description' => 'Interaktive Karte ansehen'],
|
||||
['key' => 'members.view', 'description' => 'Mitgliederliste einsehen'],
|
||||
['key' => 'reports.view', 'description' => 'Eingegangene Reports einsehen'],
|
||||
['key' => 'reports.manage', 'description' => 'Reports löschen/archivieren und die Punkte-Gewichtung verwalten'],
|
||||
|
|
|
|||
470
map.php
470
map.php
|
|
@ -1,475 +1,13 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/includes/bootstrap.php';
|
||||
require_once __DIR__ . '/includes/map_build.php';
|
||||
require_permission('map.view');
|
||||
|
||||
$canManageMap = user_has_permission('map.manage');
|
||||
$canEditTactics = user_has_permission('map.tactics');
|
||||
|
||||
/**
|
||||
* Panel zum Bauen einer Karte aus einem Bild. Das Schneiden passiert im Browser
|
||||
* (assets/js/map_build.js) - hochgeladen werden nur die fertigen Kacheln, damit weder
|
||||
* upload_max_filesize noch memory_limit oder max_execution_time im Weg stehen.
|
||||
*/
|
||||
function render_map_build_panel(?string $existingKey = null): void
|
||||
{
|
||||
?>
|
||||
<div class="map-build" id="map-build">
|
||||
<h2><?= $existingKey === null ? 'Karte aus einem Bild bauen' : 'Karte neu bauen' ?></h2>
|
||||
<p class="text-muted">
|
||||
Bild auswählen, Knopf drücken - der Rest passiert von allein: die Zoomstufen
|
||||
werden im Browser geschnitten und einzeln hochgeladen. Kein FTP, kein
|
||||
Kommandozeilen-Werkzeug nötig.
|
||||
<?php if ($existingKey !== null): ?>
|
||||
Die bisherige Karte bleibt unverändert, bis die neue vollständig oben ist.
|
||||
<?php endif; ?>
|
||||
</p>
|
||||
|
||||
<label class="map-build-drop" id="map-build-drop" for="map-build-file">
|
||||
<input type="file" id="map-build-file" accept="image/png,image/jpeg,image/webp" hidden>
|
||||
<span class="map-build-drop-text">Bild hierher ziehen oder klicken zum Auswählen</span>
|
||||
<span class="text-muted">PNG, JPEG oder WebP</span>
|
||||
</label>
|
||||
|
||||
<p class="map-build-info text-muted" id="map-build-info"></p>
|
||||
|
||||
<div class="map-build-fields">
|
||||
<div>
|
||||
<label>Kartenschlüssel</label>
|
||||
<input type="text" id="map-build-key" maxlength="49" placeholder="verteron"
|
||||
value="<?= e((string) $existingKey) ?>" <?= $existingKey !== null ? 'readonly' : '' ?>>
|
||||
<p class="text-muted map-build-hint">Ordnername, nur a-z, 0-9, - und _</p>
|
||||
</div>
|
||||
<div>
|
||||
<label>Anzeigename</label>
|
||||
<input type="text" id="map-build-name" maxlength="60" placeholder="Verteron">
|
||||
</div>
|
||||
<div>
|
||||
<label>JPEG-Qualität</label>
|
||||
<input type="text" id="map-build-quality" value="88">
|
||||
<p class="text-muted map-build-hint">40-100, höher = schärfer und größer</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="map-build-progress">
|
||||
<div class="map-build-track"><div class="map-build-bar" id="map-build-bar"></div></div>
|
||||
<span class="text-muted" id="map-build-progress"></span>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
<button type="button" id="map-build-start" disabled>Karte bauen</button>
|
||||
<button type="button" class="button-secondary" id="map-build-abort" hidden>Abbrechen</button>
|
||||
</div>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
// Bestehende Installationen kennen die Kartentabellen noch nicht. Ohne diese Pruefung
|
||||
// wuerde die erste Abfrage mit einer PDOException aussteigen - also lieber eine
|
||||
// verstaendliche Seite mit dem noetigen Schritt zeigen.
|
||||
$missingTables = map_missing_tables();
|
||||
if (!empty($missingTables)) {
|
||||
$pageTitle = 'Karte';
|
||||
include __DIR__ . '/includes/header.php';
|
||||
?>
|
||||
<div class="panel">
|
||||
<h1>Karte einrichten</h1>
|
||||
<p class="text-muted">
|
||||
Der Datenbank fehlen noch die Tabellen für die Karte
|
||||
(<?= e(implode(', ', $missingTables)) ?>). Das ist bei jeder Installation so,
|
||||
die es schon vor dem Karten-Update gab - einmalig anlegen, dann ist die Seite
|
||||
einsatzbereit. Vorhandene Daten sind davon nicht betroffen.
|
||||
</p>
|
||||
<?php if (user_has_permission('roles.manage')): ?>
|
||||
<form method="post" action="/map_install_action.php">
|
||||
<?= csrf_field() ?>
|
||||
<button type="submit">Tabellen jetzt anlegen</button>
|
||||
</form>
|
||||
<p class="text-muted map-hint">
|
||||
Führt genau die <code>CREATE TABLE IF NOT EXISTS</code>-Befehle aus dem
|
||||
Abschnitt „Taktikkarte" in <code>sql/schema.sql</code> aus.
|
||||
</p>
|
||||
<?php else: ?>
|
||||
<p class="text-muted">Dafür fehlt dir die Berechtigung <code>roles.manage</code> - bitte einen Administrator.</p>
|
||||
<?php endif; ?>
|
||||
<h2>Oder von Hand</h2>
|
||||
<p class="text-muted">
|
||||
Den Abschnitt „Taktikkarte“ am Ende von <code>sql/schema.sql</code> in phpMyAdmin
|
||||
ausführen - er enthält genau diese vier <code>CREATE TABLE</code>-Befehle.
|
||||
</p>
|
||||
</div>
|
||||
<?php
|
||||
include __DIR__ . '/includes/footer.php';
|
||||
exit;
|
||||
}
|
||||
|
||||
$maps = map_available();
|
||||
$mapKey = (string) ($_GET['map'] ?? '');
|
||||
if ($mapKey === '' || !isset($maps[$mapKey])) {
|
||||
$mapKey = (string) array_key_first($maps);
|
||||
}
|
||||
|
||||
$manifest = $maps[$mapKey] ?? null;
|
||||
$categoryTree = $manifest ? map_category_tree($mapKey) : [];
|
||||
$markers = $manifest ? map_markers($mapKey) : [];
|
||||
$tactics = $manifest ? map_tactics($mapKey) : [];
|
||||
|
||||
// Flache Kategorienliste fuer die Auswahlfelder im Marker-Formular.
|
||||
$flatCategories = [];
|
||||
foreach ($categoryTree as $group) {
|
||||
foreach ($group['children'] as $child) {
|
||||
$flatCategories[] = [
|
||||
'id' => (int) $child['id'],
|
||||
'name' => (string) $child['name'],
|
||||
'group' => (string) $group['name'],
|
||||
'icon' => (string) $child['icon'],
|
||||
'color' => (string) $child['color'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$totalMarkers = count($markers);
|
||||
|
||||
// Die Karte ist ein eigenstaendiger Viewer (assets/map/) mit eigenem Stylesheet, das
|
||||
// global auf body/button/* greift. Im iframe bleibt er vom Seitenlayout getrennt und
|
||||
// laeuft unveraendert so, wie er geliefert wurde.
|
||||
$pageTitle = 'Karte';
|
||||
$containerWide = true;
|
||||
include __DIR__ . '/includes/header.php';
|
||||
?>
|
||||
<?php if (!$manifest): ?>
|
||||
<div class="panel">
|
||||
<h1>Taktikkarte</h1>
|
||||
<p class="text-muted">
|
||||
Es ist noch keine Karte hinterlegt. Die Karte wird als Kachel-Pyramide ausgeliefert
|
||||
(mehrere Zoomstufen), damit sie auch nah herangezoomt scharf bleibt.
|
||||
</p>
|
||||
<h2>Alternativ: über die Kommandozeile</h2>
|
||||
<ol class="map-setup-steps">
|
||||
<li>Die Ingame-Karte in Bahnen abfotografieren - im Spiel maximal hineinzoomen, mit
|
||||
ca. 30% Überlappung. Je mehr Pixel dabei zusammenkommen, desto weiter lässt sich
|
||||
später scharf hineinzoomen.</li>
|
||||
<li>Die Screenshots lokal zu einem Bild zusammensetzen:<br>
|
||||
<code>python tools/stitch_map_screenshots.py shots/ -o verteron.png</code><br>
|
||||
<span class="text-muted">Feste UI-Ränder (Chat, Minimap) bei Bedarf mit
|
||||
<code>--crop=links,oben,rechts,unten</code> abschneiden - die Werte an den
|
||||
eigenen Screenshots abmessen, nicht raten.</span></li>
|
||||
<li>Daraus die Kacheln erzeugen (braucht die PHP-Erweiterung GD):<br>
|
||||
<code>php tools/make_map_tiles.php verteron verteron.png --name="Verteron"</code></li>
|
||||
<li>Den erzeugten Ordner <code>assets/uploads/maps/verteron/</code> per FTP hochladen.</li>
|
||||
</ol>
|
||||
<p class="text-muted">
|
||||
Danach erscheint die Karte hier automatisch - mehrere Regionen nebeneinander funktionieren
|
||||
genauso, jeder Unterordner mit einer <code>tiles.json</code> wird zu einer eigenen Karte.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<?php if ($canManageMap): ?>
|
||||
<div class="panel">
|
||||
<?php render_map_build_panel(); ?>
|
||||
</div>
|
||||
<script src="/assets/js/map_build.js"></script>
|
||||
<?php endif; ?>
|
||||
<?php else: ?>
|
||||
<div class="map-page"
|
||||
data-map-key="<?= e($mapKey) ?>"
|
||||
data-can-manage="<?= $canManageMap ? '1' : '0' ?>"
|
||||
data-can-tactics="<?= $canEditTactics ? '1' : '0' ?>">
|
||||
|
||||
<div class="map-sidebar">
|
||||
<div class="map-sidebar-head">
|
||||
<?php if (count($maps) > 1): ?>
|
||||
<select class="map-select" id="map-select">
|
||||
<?php foreach ($maps as $key => $available): ?>
|
||||
<option value="<?= e($key) ?>" <?= $key === $mapKey ? 'selected' : '' ?>><?= e((string) $available['name']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<?php else: ?>
|
||||
<h1><?= e((string) $manifest['name']) ?></h1>
|
||||
<?php endif; ?>
|
||||
<input type="text" id="map-search" placeholder="Suchen …" autocomplete="off">
|
||||
<div class="map-bulk-actions">
|
||||
<button type="button" class="button-secondary" id="map-show-all">Alle einblenden</button>
|
||||
<button type="button" class="button-secondary" id="map-hide-all">Alle ausblenden</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="map-tabs">
|
||||
<button type="button" class="map-tab active" data-panel="markers">Marker <span class="map-tab-count"><?= $totalMarkers ?></span></button>
|
||||
<button type="button" class="map-tab" data-panel="tactics">Taktiken <span class="map-tab-count"><?= count($tactics) ?></span></button>
|
||||
</div>
|
||||
|
||||
<div class="map-panel" data-panel="markers">
|
||||
<?php if (empty($categoryTree)): ?>
|
||||
<div class="map-empty">
|
||||
<p class="text-muted">Noch keine Kategorien angelegt.</p>
|
||||
<?php if ($canManageMap): ?>
|
||||
<button type="button" class="button-success" id="map-seed-categories">Standard-Kategorien anlegen</button>
|
||||
<p class="text-muted map-hint">Legt eine Gliederung nach Orten, Ressourcen, NPCs, Quests und Monstern an, die ihr danach frei anpassen könnt.</p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="map-category-tree" id="map-category-tree">
|
||||
<?php foreach ($categoryTree as $group): ?>
|
||||
<div class="map-group" data-group-id="<?= (int) $group['id'] ?>">
|
||||
<div class="map-group-head">
|
||||
<button type="button" class="map-group-toggle" aria-expanded="true">
|
||||
<?= icon('chevron-down') ?>
|
||||
</button>
|
||||
<label class="map-group-label">
|
||||
<input type="checkbox" class="map-group-checkbox" checked>
|
||||
<span class="map-group-icon"><?= e((string) $group['icon']) ?></span>
|
||||
<span class="map-group-name"><?= e((string) $group['name']) ?></span>
|
||||
</label>
|
||||
<span class="map-count"><?= (int) $group['total_count'] ?></span>
|
||||
<?php if ($canManageMap && (int) $group['id'] > 0): ?>
|
||||
<button type="button" class="icon-button map-category-edit"
|
||||
data-category-id="<?= (int) $group['id'] ?>"
|
||||
data-parent-id="0"
|
||||
data-name="<?= e((string) $group['name']) ?>"
|
||||
data-icon="<?= e((string) $group['icon']) ?>"
|
||||
data-color="<?= e((string) $group['color']) ?>"
|
||||
title="Gruppe bearbeiten"><?= icon('edit') ?></button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="map-group-children">
|
||||
<?php foreach ($group['children'] as $child): ?>
|
||||
<div class="map-category" data-category-id="<?= (int) $child['id'] ?>" data-name="<?= e((string) $child['name']) ?>">
|
||||
<label class="map-category-label">
|
||||
<input type="checkbox" class="map-category-checkbox" value="<?= (int) $child['id'] ?>" checked>
|
||||
<span class="map-category-icon" style="background: <?= e((string) $child['color']) ?>;"><?= e((string) $child['icon']) ?></span>
|
||||
<span class="map-category-name"><?= e((string) $child['name']) ?></span>
|
||||
</label>
|
||||
<span class="map-count"><?= (int) $child['marker_count'] ?></span>
|
||||
<?php if ($canManageMap): ?>
|
||||
<button type="button" class="icon-button map-category-edit"
|
||||
data-category-id="<?= (int) $child['id'] ?>"
|
||||
data-parent-id="<?= (int) $group['id'] ?>"
|
||||
data-name="<?= e((string) $child['name']) ?>"
|
||||
data-icon="<?= e((string) $child['icon']) ?>"
|
||||
data-color="<?= e((string) $child['color']) ?>"
|
||||
title="Kategorie bearbeiten"><?= icon('edit') ?></button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php if ($canManageMap): ?>
|
||||
<button type="button" class="button-secondary map-add-category" id="map-add-category">+ Kategorie</button>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="map-panel" data-panel="tactics" hidden>
|
||||
<?php if (empty($tactics)): ?>
|
||||
<p class="text-muted" id="map-tactics-empty">Noch keine Taktiken angelegt.</p>
|
||||
<?php endif; ?>
|
||||
<div class="map-tactic-list" id="map-tactic-list">
|
||||
<?php foreach ($tactics as $tactic): ?>
|
||||
<div class="map-tactic" data-tactic-id="<?= (int) $tactic['id'] ?>">
|
||||
<label class="map-tactic-label">
|
||||
<input type="checkbox" class="map-tactic-checkbox" value="<?= (int) $tactic['id'] ?>">
|
||||
<span class="map-tactic-name"><?= e($tactic['name']) ?></span>
|
||||
</label>
|
||||
<span class="map-count"><?= count($tactic['shapes']) ?></span>
|
||||
<?php if ($canEditTactics): ?>
|
||||
<button type="button" class="icon-button map-tactic-edit" title="Taktik bearbeiten"><?= icon('edit') ?></button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php if ($canEditTactics): ?>
|
||||
<button type="button" class="button-secondary map-add-tactic" id="map-add-tactic">+ Neue Taktik</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="map-stage">
|
||||
<div class="map-toolbar">
|
||||
<?php if ($canManageMap): ?>
|
||||
<button type="button" class="map-tool" id="map-tool-marker" title="Marker setzen: Werkzeug aktivieren und auf die Karte klicken">
|
||||
<?= icon('map-pin') ?><span>Marker setzen</span>
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
<?php if ($canEditTactics): ?>
|
||||
<div class="map-tool-group" id="map-tactic-tools" hidden>
|
||||
<span class="map-tool-group-label" id="map-tactic-active-name"></span>
|
||||
<button type="button" class="map-tool" data-shape="point" title="Punkt/Sammelpunkt setzen"><?= icon('map-pin') ?><span>Punkt</span></button>
|
||||
<button type="button" class="map-tool" data-shape="route" title="Route zeichnen: klicken für Punkte, Doppelklick beendet"><?= icon('route') ?><span>Route</span></button>
|
||||
<button type="button" class="map-tool" data-shape="area" title="Fläche zeichnen: klicken für Eckpunkte, Doppelklick beendet"><?= icon('area') ?><span>Fläche</span></button>
|
||||
<button type="button" class="map-tool" data-shape="text" title="Textnotiz setzen"><?= icon('edit') ?><span>Notiz</span></button>
|
||||
<input type="color" id="map-shape-color" value="#c9a227" title="Farbe für neue Objekte">
|
||||
<button type="button" class="map-tool map-tool-finish" id="map-shape-finish" hidden
|
||||
title="Route/Fläche abschließen (geht auch per Doppelklick oder Enter)">
|
||||
<?= icon('check') ?><span>Abschließen</span>
|
||||
</button>
|
||||
<button type="button" class="map-tool map-tool-done" id="map-tactic-close" title="Taktik-Bearbeitung beenden"><?= icon('x') ?><span>Fertig</span></button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div class="map-toolbar-spacer"></div>
|
||||
<span class="map-coords" id="map-coords" title="Position des Mauszeigers"></span>
|
||||
<button type="button" class="map-tool" id="map-reset-view" title="Ansicht zurücksetzen"><?= icon('restore') ?><span>Ansicht</span></button>
|
||||
</div>
|
||||
<div id="map-canvas" class="map-canvas"></div>
|
||||
<p class="map-status text-muted" id="map-status"></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Marker anlegen/bearbeiten -->
|
||||
<div class="modal-overlay" id="map-marker-modal" hidden>
|
||||
<div class="modal">
|
||||
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
|
||||
<h2 id="map-marker-modal-title">Marker anlegen</h2>
|
||||
<form id="map-marker-form">
|
||||
<input type="hidden" name="marker_id" value="">
|
||||
<input type="hidden" name="x" value="">
|
||||
<input type="hidden" name="y" value="">
|
||||
<div>
|
||||
<label>Name</label>
|
||||
<input type="text" name="name" maxlength="120" placeholder="z. B. Orihalum-Ader">
|
||||
</div>
|
||||
<div>
|
||||
<label>Kategorie</label>
|
||||
<select name="category_id">
|
||||
<?php
|
||||
$lastGroup = null;
|
||||
foreach ($flatCategories as $category):
|
||||
if ($category['group'] !== $lastGroup):
|
||||
if ($lastGroup !== null): ?></optgroup><?php endif; ?>
|
||||
<optgroup label="<?= e($category['group']) ?>">
|
||||
<?php $lastGroup = $category['group'];
|
||||
endif; ?>
|
||||
<option value="<?= (int) $category['id'] ?>"><?= e($category['icon'] . ' ' . $category['name']) ?></option>
|
||||
<?php endforeach;
|
||||
if ($lastGroup !== null): ?></optgroup><?php endif; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label>Beschreibung <span class="text-muted">(optional)</span></label>
|
||||
<textarea name="description" rows="3" placeholder="z. B. Respawn ca. 5 Min., 3er-Gruppe empfohlen"></textarea>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="submit">Speichern</button>
|
||||
<button type="button" class="button-secondary" id="map-marker-cancel">Abbrechen</button>
|
||||
<button type="button" class="icon-button icon-button-danger" id="map-marker-delete" title="Marker löschen" hidden><?= icon('trash') ?></button>
|
||||
<span class="map-feedback text-muted"></span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Kategorie anlegen/bearbeiten -->
|
||||
<div class="modal-overlay" id="map-category-modal" hidden>
|
||||
<div class="modal">
|
||||
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
|
||||
<h2 id="map-category-modal-title">Kategorie anlegen</h2>
|
||||
<form id="map-category-form">
|
||||
<input type="hidden" name="category_id" value="">
|
||||
<div>
|
||||
<label>Gruppe</label>
|
||||
<select name="parent_id">
|
||||
<option value="0">– Eigene Gruppe (Überschrift) –</option>
|
||||
<?php foreach ($categoryTree as $group): ?>
|
||||
<?php if ((int) $group['id'] > 0): ?>
|
||||
<option value="<?= (int) $group['id'] ?>"><?= e((string) $group['name']) ?></option>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label>Name</label>
|
||||
<input type="text" name="name" maxlength="80" placeholder="z. B. Orihalum-Erz">
|
||||
</div>
|
||||
<div class="map-category-form-row">
|
||||
<div>
|
||||
<label>Symbol</label>
|
||||
<input type="text" name="icon" maxlength="4" placeholder="⛏">
|
||||
</div>
|
||||
<div>
|
||||
<label>Farbe</label>
|
||||
<input type="color" name="color" value="#c9a227">
|
||||
</div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="submit">Speichern</button>
|
||||
<button type="button" class="button-secondary" id="map-category-cancel">Abbrechen</button>
|
||||
<button type="button" class="icon-button icon-button-danger" id="map-category-delete" title="Kategorie mitsamt ihren Markern löschen" hidden><?= icon('trash') ?></button>
|
||||
<span class="map-feedback text-muted"></span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Beschriftung fuer ein neu gezeichnetes Taktik-Objekt -->
|
||||
<div class="modal-overlay" id="map-shape-modal" hidden>
|
||||
<div class="modal">
|
||||
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
|
||||
<h2 id="map-shape-modal-title">Objekt beschriften</h2>
|
||||
<form id="map-shape-form">
|
||||
<div>
|
||||
<label>Beschriftung <span class="text-muted" id="map-shape-label-hint">(optional)</span></label>
|
||||
<input type="text" name="label" maxlength="120" placeholder="z. B. Sammelpunkt">
|
||||
</div>
|
||||
<div>
|
||||
<label>Farbe</label>
|
||||
<input type="color" name="color" value="#c9a227">
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="submit">Übernehmen</button>
|
||||
<button type="button" class="button-secondary" id="map-shape-cancel">Abbrechen</button>
|
||||
<span class="map-feedback text-muted"></span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Taktik anlegen/bearbeiten -->
|
||||
<div class="modal-overlay" id="map-tactic-modal" hidden>
|
||||
<div class="modal">
|
||||
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
|
||||
<h2 id="map-tactic-modal-title">Taktik anlegen</h2>
|
||||
<form id="map-tactic-form">
|
||||
<input type="hidden" name="tactic_id" value="">
|
||||
<div>
|
||||
<label>Name</label>
|
||||
<input type="text" name="name" maxlength="120" placeholder="z. B. Festung Verteron - Angriff Süd">
|
||||
</div>
|
||||
<div>
|
||||
<label>Beschreibung <span class="text-muted">(optional)</span></label>
|
||||
<textarea name="description" rows="3" placeholder="Ablauf, Rollenverteilung, Timings …"></textarea>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="submit">Speichern & bearbeiten</button>
|
||||
<button type="button" class="button-secondary" id="map-tactic-cancel">Abbrechen</button>
|
||||
<button type="button" class="icon-button icon-button-danger" id="map-tactic-delete" title="Taktik löschen" hidden><?= icon('trash') ?></button>
|
||||
<span class="map-feedback text-muted"></span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script id="map-data" type="application/json"><?= json_encode([
|
||||
'manifest' => [
|
||||
'width' => (int) $manifest['width'],
|
||||
'height' => (int) $manifest['height'],
|
||||
'tile_size' => (int) ($manifest['tile_size'] ?? 256),
|
||||
'min_zoom' => (int) ($manifest['min_zoom'] ?? 0),
|
||||
'max_zoom' => (int) ($manifest['max_zoom'] ?? 0),
|
||||
'url_template' => (string) $manifest['url_template'],
|
||||
'name' => (string) $manifest['name'],
|
||||
],
|
||||
'categories' => $flatCategories,
|
||||
'markers' => $markers,
|
||||
'tactics' => $tactics,
|
||||
], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?></script>
|
||||
<script src="/assets/vendor/leaflet/leaflet.js"></script>
|
||||
<?php if ($canManageMap): ?>
|
||||
<details class="panel map-build-panel">
|
||||
<summary>Karte neu bauen</summary>
|
||||
<?php render_map_build_panel($mapKey); ?>
|
||||
</details>
|
||||
<script src="/assets/js/map_build.js"></script>
|
||||
<?php endif; ?>
|
||||
|
||||
<script src="/assets/js/map.js"></script>
|
||||
<?php endif; ?>
|
||||
<iframe class="map-frame" src="/assets/map/index.html" title="Interaktive Karte"></iframe>
|
||||
<?php include __DIR__ . '/includes/footer.php'; ?>
|
||||
|
|
|
|||
294
map_action.php
294
map_action.php
|
|
@ -1,294 +0,0 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/includes/bootstrap.php';
|
||||
require_once __DIR__ . '/includes/map.php';
|
||||
require_permission('map.view');
|
||||
|
||||
$input = read_json_body();
|
||||
verify_csrf_token($input['csrf_token'] ?? '');
|
||||
|
||||
$action = (string) ($input['action'] ?? '');
|
||||
$user = current_user();
|
||||
$userId = (int) $user['id'];
|
||||
|
||||
$canManage = user_has_permission('map.manage');
|
||||
$canTactics = user_has_permission('map.tactics');
|
||||
|
||||
$mapKey = trim((string) ($input['map_key'] ?? ''));
|
||||
if ($mapKey === '' || !array_key_exists($mapKey, map_available())) {
|
||||
json_response(false, 'Unbekannte Karte.');
|
||||
}
|
||||
|
||||
/** Bricht mit einer Fehlermeldung ab, wenn die noetige Berechtigung fehlt. */
|
||||
function map_require(bool $allowed, string $message): void
|
||||
{
|
||||
if (!$allowed) {
|
||||
json_response(false, $message);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
switch ($action) {
|
||||
// ---- Marker ----
|
||||
case 'marker_save':
|
||||
map_require($canManage, 'Du darfst keine Marker verwalten.');
|
||||
|
||||
$markerId = (int) ($input['marker_id'] ?? 0);
|
||||
$categoryId = (int) ($input['category_id'] ?? 0);
|
||||
$name = trim((string) ($input['name'] ?? ''));
|
||||
$description = trim((string) ($input['description'] ?? ''));
|
||||
$x = $input['x'] ?? null;
|
||||
$y = $input['y'] ?? null;
|
||||
|
||||
if ($name === '') {
|
||||
json_response(false, 'Bitte einen Namen für den Marker angeben.');
|
||||
}
|
||||
if (mb_strlen($name) > 120) {
|
||||
json_response(false, 'Der Name darf höchstens 120 Zeichen lang sein.');
|
||||
}
|
||||
if (!map_valid_coordinate($x) || !map_valid_coordinate($y)) {
|
||||
json_response(false, 'Die Position liegt außerhalb der Karte.');
|
||||
}
|
||||
|
||||
// Nur Kategorien der zweiten Ebene koennen Marker tragen - eine Gruppe
|
||||
// ("Ressourcen") ist nur eine Ueberschrift in der Sidebar.
|
||||
$catStmt = db()->prepare('SELECT parent_id FROM map_categories WHERE id = ?');
|
||||
$catStmt->execute([$categoryId]);
|
||||
$category = $catStmt->fetch();
|
||||
if (!$category) {
|
||||
json_response(false, 'Bitte eine Kategorie auswählen.');
|
||||
}
|
||||
if ($category['parent_id'] === null) {
|
||||
json_response(false, 'Bitte eine Unterkategorie auswählen, keine Gruppe.');
|
||||
}
|
||||
|
||||
if ($markerId > 0) {
|
||||
$stmt = db()->prepare(
|
||||
'UPDATE map_markers SET category_id = ?, name = ?, description = ?, pos_x = ?, pos_y = ?, updated_at = NOW()
|
||||
WHERE id = ? AND map_key = ?'
|
||||
);
|
||||
$stmt->execute([$categoryId, $name, $description, (float) $x, (float) $y, $markerId, $mapKey]);
|
||||
json_response(true, 'Marker gespeichert.', ['marker_id' => $markerId]);
|
||||
}
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO map_markers (map_key, category_id, name, description, pos_x, pos_y, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([$mapKey, $categoryId, $name, $description, (float) $x, (float) $y, $userId]);
|
||||
json_response(true, 'Marker angelegt.', ['marker_id' => (int) db()->lastInsertId()]);
|
||||
|
||||
// no break - json_response() beendet den Request
|
||||
|
||||
case 'marker_move':
|
||||
map_require($canManage, 'Du darfst keine Marker verwalten.');
|
||||
|
||||
$markerId = (int) ($input['marker_id'] ?? 0);
|
||||
$x = $input['x'] ?? null;
|
||||
$y = $input['y'] ?? null;
|
||||
if ($markerId <= 0 || !map_valid_coordinate($x) || !map_valid_coordinate($y)) {
|
||||
json_response(false, 'Ungültige Position.');
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('UPDATE map_markers SET pos_x = ?, pos_y = ?, updated_at = NOW() WHERE id = ? AND map_key = ?');
|
||||
$stmt->execute([(float) $x, (float) $y, $markerId, $mapKey]);
|
||||
json_response(true, 'Marker verschoben.');
|
||||
|
||||
case 'marker_delete':
|
||||
map_require($canManage, 'Du darfst keine Marker verwalten.');
|
||||
|
||||
$markerId = (int) ($input['marker_id'] ?? 0);
|
||||
if ($markerId <= 0) {
|
||||
json_response(false, 'Ungültiger Marker.');
|
||||
}
|
||||
$stmt = db()->prepare('DELETE FROM map_markers WHERE id = ? AND map_key = ?');
|
||||
$stmt->execute([$markerId, $mapKey]);
|
||||
json_response(true, 'Marker gelöscht.');
|
||||
|
||||
// ---- Kategorien ----
|
||||
case 'category_save':
|
||||
map_require($canManage, 'Du darfst keine Kategorien verwalten.');
|
||||
|
||||
$categoryId = (int) ($input['category_id'] ?? 0);
|
||||
$parentId = (int) ($input['parent_id'] ?? 0);
|
||||
$name = trim((string) ($input['name'] ?? ''));
|
||||
$icon = trim((string) ($input['icon'] ?? ''));
|
||||
$color = trim((string) ($input['color'] ?? '#c9a227'));
|
||||
|
||||
if ($name === '' || mb_strlen($name) > 80) {
|
||||
json_response(false, 'Bitte einen Namen mit höchstens 80 Zeichen angeben.');
|
||||
}
|
||||
if (mb_strlen($icon) > 4) {
|
||||
json_response(false, 'Das Symbol darf höchstens 4 Zeichen lang sein (z.B. ein Emoji).');
|
||||
}
|
||||
if (!map_valid_color($color)) {
|
||||
json_response(false, 'Ungültige Farbe.');
|
||||
}
|
||||
|
||||
// Nur zwei Ebenen: eine Gruppe darf keine Gruppe als Elternteil haben.
|
||||
if ($parentId > 0) {
|
||||
$parentStmt = db()->prepare('SELECT parent_id FROM map_categories WHERE id = ?');
|
||||
$parentStmt->execute([$parentId]);
|
||||
$parent = $parentStmt->fetch();
|
||||
if (!$parent || $parent['parent_id'] !== null) {
|
||||
json_response(false, 'Ungültige Gruppe ausgewählt.');
|
||||
}
|
||||
}
|
||||
|
||||
if ($categoryId > 0) {
|
||||
$stmt = db()->prepare('UPDATE map_categories SET parent_id = ?, name = ?, icon = ?, color = ? WHERE id = ?');
|
||||
$stmt->execute([$parentId > 0 ? $parentId : null, $name, $icon, $color, $categoryId]);
|
||||
json_response(true, 'Kategorie gespeichert.');
|
||||
}
|
||||
|
||||
$sortStmt = db()->prepare('SELECT COALESCE(MAX(sort_order), 0) + 10 FROM map_categories WHERE parent_id <=> ?');
|
||||
$sortStmt->execute([$parentId > 0 ? $parentId : null]);
|
||||
$sortOrder = (int) $sortStmt->fetchColumn();
|
||||
|
||||
$stmt = db()->prepare('INSERT INTO map_categories (parent_id, name, icon, color, sort_order) VALUES (?, ?, ?, ?, ?)');
|
||||
$stmt->execute([$parentId > 0 ? $parentId : null, $name, $icon, $color, $sortOrder]);
|
||||
json_response(true, 'Kategorie angelegt.', ['category_id' => (int) db()->lastInsertId()]);
|
||||
|
||||
case 'category_delete':
|
||||
map_require($canManage, 'Du darfst keine Kategorien verwalten.');
|
||||
|
||||
$categoryId = (int) ($input['category_id'] ?? 0);
|
||||
if ($categoryId <= 0) {
|
||||
json_response(false, 'Ungültige Kategorie.');
|
||||
}
|
||||
// Loescht per ON DELETE CASCADE auch Unterkategorien und deren Marker.
|
||||
$stmt = db()->prepare('DELETE FROM map_categories WHERE id = ?');
|
||||
$stmt->execute([$categoryId]);
|
||||
json_response(true, 'Kategorie gelöscht.');
|
||||
|
||||
case 'category_seed':
|
||||
map_require($canManage, 'Du darfst keine Kategorien verwalten.');
|
||||
|
||||
$existing = (int) db()->query('SELECT COUNT(*) FROM map_categories')->fetchColumn();
|
||||
if ($existing > 0) {
|
||||
json_response(false, 'Es gibt bereits Kategorien - die Startbestückung ist nur für eine leere Liste gedacht.');
|
||||
}
|
||||
$created = map_seed_default_categories();
|
||||
json_response(true, $created . ' Kategorien wurden angelegt.');
|
||||
|
||||
// ---- Taktiken ----
|
||||
case 'tactic_save':
|
||||
map_require($canTactics, 'Du darfst keine Taktiken verwalten.');
|
||||
|
||||
$tacticId = (int) ($input['tactic_id'] ?? 0);
|
||||
$name = trim((string) ($input['name'] ?? ''));
|
||||
$description = trim((string) ($input['description'] ?? ''));
|
||||
|
||||
if ($name === '' || mb_strlen($name) > 120) {
|
||||
json_response(false, 'Bitte einen Namen mit höchstens 120 Zeichen angeben.');
|
||||
}
|
||||
|
||||
if ($tacticId > 0) {
|
||||
$stmt = db()->prepare('UPDATE map_tactics SET name = ?, description = ?, updated_at = NOW() WHERE id = ? AND map_key = ?');
|
||||
$stmt->execute([$name, $description, $tacticId, $mapKey]);
|
||||
json_response(true, 'Taktik gespeichert.', ['tactic_id' => $tacticId]);
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('INSERT INTO map_tactics (map_key, name, description, created_by) VALUES (?, ?, ?, ?)');
|
||||
$stmt->execute([$mapKey, $name, $description, $userId]);
|
||||
json_response(true, 'Taktik angelegt.', ['tactic_id' => (int) db()->lastInsertId()]);
|
||||
|
||||
case 'tactic_delete':
|
||||
map_require($canTactics, 'Du darfst keine Taktiken verwalten.');
|
||||
|
||||
$tacticId = (int) ($input['tactic_id'] ?? 0);
|
||||
if ($tacticId <= 0) {
|
||||
json_response(false, 'Ungültige Taktik.');
|
||||
}
|
||||
$stmt = db()->prepare('DELETE FROM map_tactics WHERE id = ? AND map_key = ?');
|
||||
$stmt->execute([$tacticId, $mapKey]);
|
||||
json_response(true, 'Taktik gelöscht.');
|
||||
|
||||
case 'shape_save':
|
||||
map_require($canTactics, 'Du darfst keine Taktiken verwalten.');
|
||||
|
||||
$tacticId = (int) ($input['tactic_id'] ?? 0);
|
||||
$shapeId = (int) ($input['shape_id'] ?? 0);
|
||||
$type = (string) ($input['type'] ?? '');
|
||||
$label = trim((string) ($input['label'] ?? ''));
|
||||
$color = trim((string) ($input['color'] ?? '#c9a227'));
|
||||
$points = $input['points'] ?? null;
|
||||
|
||||
if (!in_array($type, ['point', 'route', 'area', 'text'], true)) {
|
||||
json_response(false, 'Unbekannter Objekttyp.');
|
||||
}
|
||||
if (!map_valid_color($color)) {
|
||||
json_response(false, 'Ungültige Farbe.');
|
||||
}
|
||||
if (mb_strlen($label) > 120) {
|
||||
json_response(false, 'Die Beschriftung darf höchstens 120 Zeichen lang sein.');
|
||||
}
|
||||
if (!is_array($points) || empty($points)) {
|
||||
json_response(false, 'Dem Objekt fehlen Punkte.');
|
||||
}
|
||||
// Routen/Flaechen brauchen mehrere Stuetzpunkte, Punkte/Texte genau einen.
|
||||
$minPoints = in_array($type, ['route', 'area'], true) ? 2 : 1;
|
||||
if (count($points) < $minPoints) {
|
||||
json_response(false, 'Bitte mindestens ' . $minPoints . ' Punkte setzen.');
|
||||
}
|
||||
|
||||
$clean = [];
|
||||
foreach ($points as $point) {
|
||||
if (!is_array($point) || count($point) !== 2
|
||||
|| !map_valid_coordinate($point[0]) || !map_valid_coordinate($point[1])) {
|
||||
json_response(false, 'Ein Punkt liegt außerhalb der Karte.');
|
||||
}
|
||||
$clean[] = [round((float) $point[0], 6), round((float) $point[1], 6)];
|
||||
}
|
||||
|
||||
$ownerStmt = db()->prepare('SELECT id FROM map_tactics WHERE id = ? AND map_key = ?');
|
||||
$ownerStmt->execute([$tacticId, $mapKey]);
|
||||
if (!$ownerStmt->fetch()) {
|
||||
json_response(false, 'Die Taktik wurde nicht gefunden.');
|
||||
}
|
||||
|
||||
$encoded = json_encode($clean, JSON_UNESCAPED_UNICODE);
|
||||
|
||||
if ($shapeId > 0) {
|
||||
$stmt = db()->prepare(
|
||||
'UPDATE map_tactic_shapes SET shape_type = ?, label = ?, color = ?, points = ?
|
||||
WHERE id = ? AND tactic_id = ?'
|
||||
);
|
||||
$stmt->execute([$type, $label, $color, $encoded, $shapeId, $tacticId]);
|
||||
} else {
|
||||
$sortStmt = db()->prepare('SELECT COALESCE(MAX(sort_order), 0) + 10 FROM map_tactic_shapes WHERE tactic_id = ?');
|
||||
$sortStmt->execute([$tacticId]);
|
||||
$sortOrder = (int) $sortStmt->fetchColumn();
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO map_tactic_shapes (tactic_id, shape_type, label, color, points, sort_order)
|
||||
VALUES (?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([$tacticId, $type, $label, $color, $encoded, $sortOrder]);
|
||||
$shapeId = (int) db()->lastInsertId();
|
||||
}
|
||||
|
||||
db()->prepare('UPDATE map_tactics SET updated_at = NOW() WHERE id = ?')->execute([$tacticId]);
|
||||
json_response(true, 'Objekt gespeichert.', ['shape_id' => $shapeId]);
|
||||
|
||||
case 'shape_delete':
|
||||
map_require($canTactics, 'Du darfst keine Taktiken verwalten.');
|
||||
|
||||
$shapeId = (int) ($input['shape_id'] ?? 0);
|
||||
if ($shapeId <= 0) {
|
||||
json_response(false, 'Ungültiges Objekt.');
|
||||
}
|
||||
// Ueber den Join sicherstellen, dass das Objekt wirklich zu dieser Karte gehoert.
|
||||
$stmt = db()->prepare(
|
||||
'DELETE s FROM map_tactic_shapes s
|
||||
JOIN map_tactics t ON t.id = s.tactic_id
|
||||
WHERE s.id = ? AND t.map_key = ?'
|
||||
);
|
||||
$stmt->execute([$shapeId, $mapKey]);
|
||||
json_response(true, 'Objekt gelöscht.');
|
||||
|
||||
default:
|
||||
json_response(false, 'Unbekannte Aktion.');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
json_response(false, 'Aktion fehlgeschlagen: ' . $e->getMessage());
|
||||
}
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/includes/bootstrap.php';
|
||||
require_once __DIR__ . '/includes/map_build.php';
|
||||
require_permission('map.manage');
|
||||
|
||||
// Anders als die uebrigen JSON-Endpunkte kommt hier multipart/form-data an (die Kacheln
|
||||
// als Dateien), deshalb $_POST statt read_json_body().
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
json_response(false, 'Nur POST.');
|
||||
}
|
||||
verify_csrf();
|
||||
|
||||
$action = (string) ($_POST['action'] ?? '');
|
||||
$key = strtolower(trim((string) ($_POST['key'] ?? '')));
|
||||
|
||||
if (!map_build_valid_key($key)) {
|
||||
json_response(false, 'Ungültiger Kartenschlüssel (erlaubt: a-z, 0-9, - und _).');
|
||||
}
|
||||
|
||||
try {
|
||||
switch ($action) {
|
||||
case 'begin':
|
||||
$width = (int) ($_POST['width'] ?? 0);
|
||||
$height = (int) ($_POST['height'] ?? 0);
|
||||
$tileSize = (int) ($_POST['tile_size'] ?? 256);
|
||||
$maxZoom = (int) ($_POST['max_zoom'] ?? 0);
|
||||
$name = trim((string) ($_POST['name'] ?? ''));
|
||||
|
||||
if (mb_strlen($name) > 60) {
|
||||
json_response(false, 'Der Name darf höchstens 60 Zeichen lang sein.');
|
||||
}
|
||||
|
||||
map_build_begin($key, $name, $width, $height, $tileSize, $maxZoom);
|
||||
|
||||
json_response(true, 'Bauvorgang gestartet.', [
|
||||
'expected_tiles' => map_build_tile_count($width, $height, $tileSize, $maxZoom),
|
||||
]);
|
||||
|
||||
case 'tiles':
|
||||
$state = map_build_state($key);
|
||||
if ($state === null) {
|
||||
json_response(false, 'Zu dieser Karte läuft kein Bauvorgang. Bitte neu starten.');
|
||||
}
|
||||
|
||||
// Die Kacheln kommen als tile[] mit einem parallelen Feld coords[] im
|
||||
// Format "z_x_y" - so bleibt die Zuordnung eindeutig, auch wenn PHP die
|
||||
// Reihenfolge der Dateien anders sortieren wuerde.
|
||||
$coords = is_array($_POST['coords'] ?? null) ? $_POST['coords'] : [];
|
||||
$files = $_FILES['tile'] ?? null;
|
||||
if (!is_array($files) || !is_array($files['tmp_name'] ?? null)) {
|
||||
json_response(false, 'Es wurden keine Kacheln übertragen.');
|
||||
}
|
||||
|
||||
$count = count($files['tmp_name']);
|
||||
if ($count !== count($coords)) {
|
||||
json_response(false, 'Kacheln und Koordinaten passen nicht zusammen.');
|
||||
}
|
||||
|
||||
$written = 0;
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
if (preg_match('/^(\d+)_(\d+)_(\d+)$/', (string) $coords[$i], $m) !== 1) {
|
||||
json_response(false, 'Ungültige Kachelkoordinate.');
|
||||
}
|
||||
|
||||
map_build_store_tile($state, [
|
||||
'error' => $files['error'][$i],
|
||||
'size' => $files['size'][$i],
|
||||
'tmp_name' => $files['tmp_name'][$i],
|
||||
], (int) $m[1], (int) $m[2], (int) $m[3]);
|
||||
$written++;
|
||||
}
|
||||
|
||||
map_build_count($key, $written);
|
||||
json_response(true, '', ['written' => $written]);
|
||||
|
||||
case 'finish':
|
||||
$written = map_build_finish($key);
|
||||
json_response(true, 'Karte fertig gebaut (' . $written . ' Kacheln).', ['tiles' => $written]);
|
||||
|
||||
case 'abort':
|
||||
map_build_abort($key);
|
||||
json_response(true, 'Bauvorgang abgebrochen, die bisherige Karte bleibt unverändert.');
|
||||
|
||||
default:
|
||||
json_response(false, 'Unbekannte Aktion.');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
json_response(false, $e->getMessage());
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
<?php
|
||||
require_once __DIR__ . '/includes/bootstrap.php';
|
||||
require_once __DIR__ . '/includes/map.php';
|
||||
|
||||
// Struktur der Datenbank zu aendern ist eine Administratoren-Aufgabe - deshalb nicht an
|
||||
// map.manage haengen, sondern an dieselbe Berechtigung wie die Rechteverwaltung.
|
||||
require_permission('roles.manage');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
redirect('/map.php');
|
||||
}
|
||||
verify_csrf();
|
||||
|
||||
$missing = map_missing_tables();
|
||||
if (empty($missing)) {
|
||||
set_flash('success', 'Die Kartentabellen sind bereits vorhanden.');
|
||||
redirect('/map.php');
|
||||
}
|
||||
|
||||
try {
|
||||
map_create_tables();
|
||||
|
||||
$stillMissing = map_missing_tables();
|
||||
if (!empty($stillMissing)) {
|
||||
set_flash('error', 'Diese Tabellen konnten nicht angelegt werden: ' . implode(', ', $stillMissing));
|
||||
} else {
|
||||
set_flash('success', 'Die Kartentabellen wurden angelegt. Die Karte ist jetzt einsatzbereit.');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
set_flash('error', 'Anlegen fehlgeschlagen: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
redirect('/map.php');
|
||||
|
|
@ -55,69 +55,3 @@ CREATE TABLE IF NOT EXISTS user_roles (
|
|||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- --------------------------------------------------------------------------
|
||||
-- Taktikkarte
|
||||
-- --------------------------------------------------------------------------
|
||||
|
||||
-- Kategorien sind zweistufig: Zeilen ohne parent_id sind Gruppen ("Ressourcen"),
|
||||
-- Zeilen mit parent_id die eigentlichen Marker-Kategorien ("Orihalum-Erz").
|
||||
CREATE TABLE IF NOT EXISTS map_categories (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
parent_id INT UNSIGNED NULL,
|
||||
name VARCHAR(80) NOT NULL,
|
||||
-- Kurzes Zeichen (Emoji) fuer die Marker-Nadel, z.B. "⛏" oder "🐉".
|
||||
icon VARCHAR(16) NOT NULL DEFAULT '',
|
||||
color VARCHAR(7) NOT NULL DEFAULT '#c9a227',
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (parent_id) REFERENCES map_categories(id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- pos_x/pos_y sind auf 0..1 normiert (Anteil der Kartenbreite/-hoehe), damit die
|
||||
-- Marker unabhaengig von Zoomstufe, Kachelgroesse und Bildaufloesung sitzen und ein
|
||||
-- spaeter neu gekacheltes Kartenbild sie nicht verschiebt.
|
||||
CREATE TABLE IF NOT EXISTS map_markers (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
map_key VARCHAR(50) NOT NULL DEFAULT 'verteron',
|
||||
category_id INT UNSIGNED NOT NULL,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
description TEXT NULL,
|
||||
pos_x DECIMAL(9,6) NOT NULL,
|
||||
pos_y DECIMAL(9,6) NOT NULL,
|
||||
created_by INT UNSIGNED NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NULL,
|
||||
FOREIGN KEY (category_id) REFERENCES map_categories(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
|
||||
INDEX idx_map_markers_map (map_key),
|
||||
INDEX idx_map_markers_category (category_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Eine Taktik ist eine eigene Zeichenebene ueber der Karte (Sammelpunkte, Routen,
|
||||
-- Zonen, Notizen), die sich ein- und ausblenden laesst.
|
||||
CREATE TABLE IF NOT EXISTS map_tactics (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
map_key VARCHAR(50) NOT NULL DEFAULT 'verteron',
|
||||
name VARCHAR(120) NOT NULL,
|
||||
description TEXT NULL,
|
||||
created_by INT UNSIGNED NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NULL,
|
||||
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
|
||||
INDEX idx_map_tactics_map (map_key)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- points enthaelt die Stuetzpunkte als JSON-Array [[x,y], ...] mit denselben
|
||||
-- normierten Koordinaten wie map_markers (TEXT statt JSON, damit auch aeltere
|
||||
-- MySQL-/MariaDB-Versionen ohne JSON-Typ funktionieren).
|
||||
CREATE TABLE IF NOT EXISTS map_tactic_shapes (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
tactic_id INT UNSIGNED NOT NULL,
|
||||
shape_type ENUM('point', 'route', 'area', 'text') NOT NULL,
|
||||
label VARCHAR(120) NOT NULL DEFAULT '',
|
||||
color VARCHAR(7) NOT NULL DEFAULT '#c9a227',
|
||||
points TEXT NOT NULL,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (tactic_id) REFERENCES map_tactics(id) ON DELETE CASCADE,
|
||||
INDEX idx_map_shapes_tactic (tactic_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
|
|
|||
|
|
@ -1,226 +0,0 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Zerlegt ein grosses Kartenbild in eine Kachel-Pyramide fuer die Taktikkarte (map.php).
|
||||
*
|
||||
* Aufruf (lokal, nicht auf dem Webspace noetig):
|
||||
*
|
||||
* php tools/make_map_tiles.php <kartenschluessel> <bilddatei> [--name="Anzeigename"]
|
||||
* [--tile-size=256] [--quality=88] [--out=<zielordner>]
|
||||
*
|
||||
* Beispiel:
|
||||
*
|
||||
* php -d memory_limit=2G tools/make_map_tiles.php verteron "C:\Bilder\verteron.png" --name="Verteron"
|
||||
*
|
||||
* Ergebnis landet in assets/uploads/maps/<kartenschluessel>/ und besteht aus einem Ordner
|
||||
* je Zoomstufe plus einer tiles.json, ueber die sich die Karte selbst beschreibt. Diesen
|
||||
* Ordner danach einfach per FTP hochladen - map.php findet ihn von allein.
|
||||
*
|
||||
* Die oberste Zoomstufe zeigt das Bild in Originalaufloesung, jede Stufe darunter ist halb
|
||||
* so gross, bis die ganze Karte in eine einzige Kachel passt. Randkacheln werden auf die
|
||||
* volle Kachelgroesse aufgefuellt (mit der Hintergrundfarbe der Website), damit Leaflet sie
|
||||
* nicht verzerrt.
|
||||
*/
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
fwrite(STDERR, "Dieses Script laeuft nur auf der Kommandozeile.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (!extension_loaded('gd')) {
|
||||
// Haeufigster Fall auf einer frischen Windows-/scoop-Installation: PHP findet gar keine
|
||||
// php.ini und laedt deshalb ueberhaupt keine Erweiterung. Deshalb hier nicht nur melden,
|
||||
// was fehlt, sondern auch gleich wo es einzutragen waere.
|
||||
$loadedIni = php_ini_loaded_file();
|
||||
$expectedIni = $loadedIni !== false ? $loadedIni : dirname(PHP_BINARY) . DIRECTORY_SEPARATOR . 'php.ini';
|
||||
$extensionDir = (string) ini_get('extension_dir');
|
||||
$extensionHint = $extensionDir === ''
|
||||
? '(leer)'
|
||||
: $extensionDir . (is_dir($extensionDir) ? '' : ' <- existiert nicht');
|
||||
|
||||
$quoted = array_map(
|
||||
static fn (string $arg): string => str_contains($arg, ' ') ? '"' . $arg . '"' : $arg,
|
||||
$argv
|
||||
);
|
||||
|
||||
fwrite(STDERR, "Die PHP-Erweiterung GD wird benoetigt, ist aber nicht geladen.\n\n");
|
||||
fwrite(STDERR, ' PHP: ' . PHP_BINARY . ' (' . PHP_VERSION . ")\n");
|
||||
fwrite(STDERR, ' php.ini: ' . ($loadedIni !== false ? $loadedIni : 'KEINE geladen') . "\n");
|
||||
fwrite(STDERR, ' extension_dir: ' . $extensionHint . "\n\n");
|
||||
fwrite(STDERR, "So beheben - in\n\n " . $expectedIni . "\n\ndiese beiden Zeilen eintragen"
|
||||
. ($loadedIni !== false ? '' : ' (Datei dafuer neu anlegen)') . ":\n\n");
|
||||
fwrite(STDERR, " extension_dir = \"ext\"\n extension=gd\n\n");
|
||||
fwrite(STDERR, "Danach mit 'php -m' pruefen, ob 'gd' in der Liste steht.\n\n");
|
||||
fwrite(STDERR, "Einmalig ohne Konfigurationsdatei geht es auch direkt:\n\n php -d extension_dir=\""
|
||||
. dirname(PHP_BINARY) . DIRECTORY_SEPARATOR . "ext\" -d extension=gd " . implode(' ', $quoted) . "\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$args = array_slice($argv, 1);
|
||||
$positional = [];
|
||||
$options = ['name' => null, 'tile-size' => 256, 'quality' => 88, 'out' => null];
|
||||
|
||||
foreach ($args as $arg) {
|
||||
if (str_starts_with($arg, '--')) {
|
||||
[$key, $value] = array_pad(explode('=', substr($arg, 2), 2), 2, '');
|
||||
if (!array_key_exists($key, $options)) {
|
||||
fwrite(STDERR, "Unbekannte Option: --$key\n");
|
||||
exit(1);
|
||||
}
|
||||
$options[$key] = $value;
|
||||
} else {
|
||||
$positional[] = $arg;
|
||||
}
|
||||
}
|
||||
|
||||
if (count($positional) < 2) {
|
||||
fwrite(STDERR, "Aufruf: php tools/make_map_tiles.php <kartenschluessel> <bilddatei> [--name=\"Anzeigename\"]\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
[$mapKey, $sourcePath] = $positional;
|
||||
|
||||
if (preg_match('/^[a-z0-9_-]+$/', $mapKey) !== 1) {
|
||||
fwrite(STDERR, "Der Kartenschluessel darf nur Kleinbuchstaben, Ziffern, - und _ enthalten (z.B. 'verteron').\n");
|
||||
exit(1);
|
||||
}
|
||||
if (!is_file($sourcePath)) {
|
||||
fwrite(STDERR, "Bilddatei nicht gefunden: $sourcePath\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$tileSize = max(64, (int) $options['tile-size']);
|
||||
$quality = min(100, max(40, (int) $options['quality']));
|
||||
$displayName = $options['name'] !== null && $options['name'] !== '' ? (string) $options['name'] : ucfirst($mapKey);
|
||||
$outputRoot = $options['out'] !== null && $options['out'] !== ''
|
||||
? rtrim((string) $options['out'], '/\\')
|
||||
: __DIR__ . '/../assets/uploads/maps/' . $mapKey;
|
||||
|
||||
echo "Lade Bild …\n";
|
||||
$source = load_image($sourcePath);
|
||||
$width = imagesx($source);
|
||||
$height = imagesy($source);
|
||||
echo "Quellbild: {$width} x {$height} Pixel\n";
|
||||
|
||||
// Hoechste Zoomstufe = Originalgroesse. Kleinste Stufe = das ganze Bild passt in eine Kachel.
|
||||
$maxZoom = (int) max(0, ceil(log(max($width, $height) / $tileSize, 2)));
|
||||
$minZoom = 0;
|
||||
|
||||
echo "Zoomstufen: {$minZoom} bis {$maxZoom} (Kachelgroesse {$tileSize}px)\n";
|
||||
|
||||
// Wie weit sich die Karte spaeter scharf heranzoomen laesst, haengt einzig an der
|
||||
// Aufloesung dieser Vorlage - bei einem einzelnen Vollbild-Screenshot ist das zu wenig.
|
||||
if (max($width, $height) < 4000) {
|
||||
fwrite(STDERR, "\nHINWEIS: " . max($width, $height) . " Pixel Kantenlaenge sind wenig. Die Karte laesst\n"
|
||||
. "sich damit nur bis Zoomstufe {$maxZoom} scharf anzeigen und wirkt naeher herangezoomt unscharf.\n"
|
||||
. "Mehr Pixel bekommst du, indem du die Ingame-Karte maximal herangezoomt in Bahnen\n"
|
||||
. "abfotografierst und die Screenshots mit tools/stitch_map_screenshots.py verbindest.\n\n");
|
||||
}
|
||||
|
||||
if (!is_dir($outputRoot) && !mkdir($outputRoot, 0775, true) && !is_dir($outputRoot)) {
|
||||
fwrite(STDERR, "Zielordner konnte nicht angelegt werden: $outputRoot\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$totalTiles = 0;
|
||||
|
||||
for ($zoom = $maxZoom; $zoom >= $minZoom; $zoom--) {
|
||||
$scale = 2 ** ($zoom - $maxZoom);
|
||||
$levelWidth = max(1, (int) round($width * $scale));
|
||||
$levelHeight = max(1, (int) round($height * $scale));
|
||||
|
||||
echo "Zoom {$zoom}: {$levelWidth} x {$levelHeight} … ";
|
||||
|
||||
$level = $zoom === $maxZoom ? $source : resize_image($source, $levelWidth, $levelHeight);
|
||||
|
||||
$cols = (int) ceil($levelWidth / $tileSize);
|
||||
$rows = (int) ceil($levelHeight / $tileSize);
|
||||
|
||||
$zoomDir = $outputRoot . '/' . $zoom;
|
||||
if (!is_dir($zoomDir) && !mkdir($zoomDir, 0775, true) && !is_dir($zoomDir)) {
|
||||
fwrite(STDERR, "\nOrdner konnte nicht angelegt werden: $zoomDir\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Kein imagedestroy() noetig: GD-Bilder raeumt PHP seit 8.0 selbst auf, und seit 8.5
|
||||
// ist die Funktion als deprecated markiert.
|
||||
for ($x = 0; $x < $cols; $x++) {
|
||||
for ($y = 0; $y < $rows; $y++) {
|
||||
$tile = imagecreatetruecolor($tileSize, $tileSize);
|
||||
// Randkacheln auf volle Groesse auffuellen - in der Hintergrundfarbe der
|
||||
// Website, damit der Uebergang am Kartenrand nicht auffaellt.
|
||||
imagefill($tile, 0, 0, imagecolorallocate($tile, 0x14, 0x16, 0x1a));
|
||||
|
||||
$srcX = $x * $tileSize;
|
||||
$srcY = $y * $tileSize;
|
||||
$copyWidth = min($tileSize, $levelWidth - $srcX);
|
||||
$copyHeight = min($tileSize, $levelHeight - $srcY);
|
||||
|
||||
imagecopy($tile, $level, 0, 0, $srcX, $srcY, $copyWidth, $copyHeight);
|
||||
imagejpeg($tile, $zoomDir . '/' . $x . '_' . $y . '.jpg', $quality);
|
||||
$totalTiles++;
|
||||
}
|
||||
}
|
||||
|
||||
echo $cols * $rows . " Kacheln\n";
|
||||
}
|
||||
|
||||
$manifest = [
|
||||
'name' => $displayName,
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'tile_size' => $tileSize,
|
||||
'min_zoom' => $minZoom,
|
||||
'max_zoom' => $maxZoom,
|
||||
'extension' => 'jpg',
|
||||
'generated_at' => date('c'),
|
||||
];
|
||||
|
||||
file_put_contents(
|
||||
$outputRoot . '/tiles.json',
|
||||
json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
||||
);
|
||||
|
||||
echo "\nFertig: {$totalTiles} Kacheln in {$outputRoot}\n";
|
||||
echo "Diesen Ordner nach assets/uploads/maps/{$mapKey}/ auf den Webspace hochladen.\n";
|
||||
|
||||
/**
|
||||
* Laedt JPEG, PNG oder WebP als GD-Bild.
|
||||
*
|
||||
* @return GdImage
|
||||
*/
|
||||
function load_image(string $path)
|
||||
{
|
||||
$info = @getimagesize($path);
|
||||
if ($info === false) {
|
||||
fwrite(STDERR, "Datei ist kein unterstuetztes Bild: $path\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$image = match ($info[2]) {
|
||||
IMAGETYPE_JPEG => @imagecreatefromjpeg($path),
|
||||
IMAGETYPE_PNG => @imagecreatefrompng($path),
|
||||
IMAGETYPE_WEBP => @imagecreatefromwebp($path),
|
||||
default => false,
|
||||
};
|
||||
|
||||
if ($image === false) {
|
||||
fwrite(STDERR, "Bild konnte nicht geladen werden (JPEG, PNG und WebP werden unterstuetzt).\n");
|
||||
fwrite(STDERR, "Bei sehr grossen Bildern hilft ein hoeheres Speicherlimit: php -d memory_limit=2G ...\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
return $image;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param GdImage $source
|
||||
* @return GdImage
|
||||
*/
|
||||
function resize_image($source, int $width, int $height)
|
||||
{
|
||||
$resized = imagecreatetruecolor($width, $height);
|
||||
imagecopyresampled($resized, $source, 0, 0, 0, 0, $width, $height, imagesx($source), imagesy($source));
|
||||
return $resized;
|
||||
}
|
||||
|
|
@ -1,356 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Setzt ueberlappende Screenshots der Ingame-Karte zu einem grossen Bild zusammen.
|
||||
|
||||
Gedacht als Vorstufe zu tools/make_map_tiles.php: je mehr Pixel das zusammengesetzte
|
||||
Bild hat, desto weiter laesst sich die Karte auf der Website scharf heranzoomen. Statt
|
||||
die ganze Karte auf einen Screenshot zu quetschen, zoomst du im Spiel also maximal
|
||||
hinein und faehrst die Karte in einem Raster ab - dieses Script findet die Ueberlappungen
|
||||
von allein und baut daraus ein Bild.
|
||||
|
||||
Aufruf:
|
||||
|
||||
python tools/stitch_map_screenshots.py <screenshot-ordner> -o verteron.png
|
||||
|
||||
python tools/stitch_map_screenshots.py shots/ -o verteron.png --crop=0,60,0,120
|
||||
|
||||
Optionen:
|
||||
|
||||
-o, --output Zieldatei (PNG empfohlen, verlustfrei). Standard: stitched.png
|
||||
--crop Raender wegschneiden, die auf jedem Screenshot gleich sind
|
||||
(Chat, Minimap, Kartenrahmen) als links,oben,rechts,unten in Pixeln.
|
||||
Wichtig: UI-Elemente ueber der Karte verwirren die Zuordnung.
|
||||
--min-score Ab welcher Uebereinstimmung ein Bild akzeptiert wird (0..1,
|
||||
Standard 0.55). Niedriger = toleranter, aber fehleranfaelliger.
|
||||
--scale Vorab-Verkleinerung nur fuer die Suche (Standard 0.5). Kleiner =
|
||||
schneller, groesser = genauer bei wenig Struktur.
|
||||
--dry-run Nur die gefundene Anordnung ausgeben, nichts schreiben.
|
||||
|
||||
Voraussetzungen: Python 3.8+, numpy und Pillow (pip install numpy pillow).
|
||||
|
||||
Aufnahme-Hinweise:
|
||||
|
||||
* Immer dieselbe Zoomstufe im Spiel - das Script verschiebt Bilder nur, es dreht
|
||||
und skaliert sie nicht.
|
||||
* Mindestens ~30% Ueberlappung zwischen benachbarten Screenshots.
|
||||
* In Bahnen abfahren (eine Reihe komplett, dann die naechste), das ist am robustesten.
|
||||
* Fenstermodus ohne Rahmen, damit alle Screenshots exakt gleich gross sind.
|
||||
* --crop lieber ein paar Pixel zu grosszuegig setzen als zu knapp: mitten im Bild
|
||||
ueberdeckt ein Nachbar-Screenshot einen stehen gebliebenen UI-Streifen zwar wieder,
|
||||
am aeusseren Kartenrand gibt es diesen Nachbarn aber nicht.
|
||||
* Je mehr Pixel am Ende herauskommen, desto weiter laesst sich auf der Website scharf
|
||||
hineinzoomen. Mehr Pixel bekommst du ueber mehr Screenshots (im Spiel weiter
|
||||
hineinzoomen) und ueber eine hoehere Renderaufloesung (NVIDIA DSR / AMD VSR).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
sys.exit("numpy und Pillow werden benoetigt: pip install numpy pillow")
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = None # sehr grosse Ergebnisbilder sind hier gewollt
|
||||
|
||||
IMAGE_SUFFIXES = ('.png', '.jpg', '.jpeg', '.bmp', '.webp')
|
||||
|
||||
|
||||
def load_images(folder, crop):
|
||||
"""Laedt alle Bilder eines Ordners (alphabetisch) und schneidet die Raender ab."""
|
||||
names = sorted(n for n in os.listdir(folder) if n.lower().endswith(IMAGE_SUFFIXES))
|
||||
if not names:
|
||||
sys.exit(f"Keine Bilder in {folder} gefunden ({', '.join(IMAGE_SUFFIXES)}).")
|
||||
|
||||
images = []
|
||||
size = None
|
||||
for name in names:
|
||||
image = Image.open(os.path.join(folder, name)).convert('RGB')
|
||||
if crop:
|
||||
left, top, right, bottom = crop
|
||||
box = (left, top, image.width - right, image.height - bottom)
|
||||
if box[2] <= box[0] or box[3] <= box[1]:
|
||||
sys.exit(f"--crop schneidet {name} komplett weg.")
|
||||
image = image.crop(box)
|
||||
|
||||
if size is None:
|
||||
size = image.size
|
||||
elif image.size != size:
|
||||
sys.exit(f"{name} ist {image.size[0]}x{image.size[1]}, erwartet {size[0]}x{size[1]}. "
|
||||
"Alle Screenshots muessen gleich gross sein (Fenstermodus ohne Rahmen).")
|
||||
|
||||
images.append((name, np.asarray(image, dtype=np.float32)))
|
||||
|
||||
return images
|
||||
|
||||
|
||||
def to_gray(rgb):
|
||||
return rgb[:, :, 0] * 0.299 + rgb[:, :, 1] * 0.587 + rgb[:, :, 2] * 0.114
|
||||
|
||||
|
||||
def correlation_surface(a, b):
|
||||
"""Phasenkorrelation zweier gleich grosser Graustufenbilder.
|
||||
|
||||
Ueber die FFT, dadurch unempfindlich gegen Helligkeitsunterschiede und genau auf
|
||||
reine Verschiebungen zugeschnitten - das ist unser Fall, die Ingame-Karte wird nur
|
||||
verschoben, nicht gedreht oder skaliert. Zurueck kommt die komplette
|
||||
Korrelationsflaeche; welche Spitze darin die richtige ist, entscheidet erst
|
||||
overlap_score().
|
||||
"""
|
||||
fa = np.fft.rfft2(a - a.mean())
|
||||
fb = np.fft.rfft2(b - b.mean())
|
||||
|
||||
cross = fa * np.conj(fb)
|
||||
magnitude = np.abs(cross)
|
||||
magnitude[magnitude == 0] = 1e-9
|
||||
|
||||
return np.fft.irfft2(cross / magnitude, s=a.shape)
|
||||
|
||||
|
||||
def candidate_shifts(surface, count):
|
||||
"""Die staerksten Spitzen der Korrelationsflaeche als Verschiebungs-Kandidaten.
|
||||
|
||||
Die FFT rechnet zyklisch: eine Spitze bei x kann eine Verschiebung um x nach rechts
|
||||
ODER um x-Breite nach links bedeuten. Bei Panorama-Aufnahmen sind Verschiebungen
|
||||
groesser als die halbe Bildbreite der Normalfall (bei 35% Ueberlappung sind es 65%
|
||||
der Breite), deshalb werden beide Lesarten je Achse als Kandidat ausgegeben und
|
||||
spaeter an der tatsaechlichen Ueberlappung geprueft.
|
||||
"""
|
||||
height, width = surface.shape
|
||||
flat = surface.ravel()
|
||||
count = min(count, flat.size)
|
||||
|
||||
top = np.argpartition(flat, -count)[-count:]
|
||||
top = top[np.argsort(flat[top])[::-1]]
|
||||
|
||||
shifts = []
|
||||
for index in top:
|
||||
y, x = divmod(int(index), width)
|
||||
for dy in {y, y - height}:
|
||||
for dx in {x, x - width}:
|
||||
shifts.append((dy, dx))
|
||||
|
||||
return shifts
|
||||
|
||||
|
||||
def overlap_score(a, b, dy, dx):
|
||||
"""Bewertet eine Verschiebung an der tatsaechlichen Ueberlappung.
|
||||
|
||||
Die Spitze der Phasenkorrelation allein sagt wenig - erst der normierte
|
||||
Korrelationskoeffizient im ueberlappenden Bereich zeigt, ob dort wirklich dasselbe
|
||||
zu sehen ist. Ergebnis zwischen -1 und 1.
|
||||
"""
|
||||
height, width = a.shape
|
||||
ay0, by0 = max(0, dy), max(0, -dy)
|
||||
ax0, bx0 = max(0, dx), max(0, -dx)
|
||||
h = min(height - ay0, height - by0)
|
||||
w = min(width - ax0, width - bx0)
|
||||
|
||||
# Zu kleine Ueberlappungen sind statistisch wertlos.
|
||||
if h < height * 0.12 or w < width * 0.12:
|
||||
return -1.0
|
||||
|
||||
pa = a[ay0:ay0 + h, ax0:ax0 + w].ravel()
|
||||
pb = b[by0:by0 + h, bx0:bx0 + w].ravel()
|
||||
|
||||
pa = pa - pa.mean()
|
||||
pb = pb - pb.mean()
|
||||
denominator = float(np.sqrt((pa * pa).sum() * (pb * pb).sum()))
|
||||
if denominator < 1e-9:
|
||||
return -1.0
|
||||
|
||||
return float((pa * pb).sum() / denominator)
|
||||
|
||||
|
||||
def find_offset(gray_a, gray_b, small_a, small_b, scale):
|
||||
"""Verschiebung von b gegenueber a, in Pixeln des Originalbildes.
|
||||
|
||||
Dreistufig: Kandidaten aus der Korrelationsflaeche des verkleinerten Bildes, grobe
|
||||
Vorauswahl ebenfalls im Kleinen (schnell), dann Feinsuche auf Pixelgenauigkeit im
|
||||
Original.
|
||||
"""
|
||||
candidates = candidate_shifts(correlation_surface(small_a, small_b), 8)
|
||||
|
||||
scored = [(overlap_score(small_a, small_b, dy, dx), dy, dx) for dy, dx in candidates]
|
||||
scored.sort(reverse=True)
|
||||
|
||||
best = (0, 0, -1.0)
|
||||
for _, dy, dx in scored[:3]:
|
||||
fy, fx = int(round(dy / scale)), int(round(dx / scale))
|
||||
score = overlap_score(gray_a, gray_b, fy, fx)
|
||||
if score > best[2]:
|
||||
best = (fy, fx, score)
|
||||
|
||||
# Die Verkleinerung kostet Genauigkeit - im Original nachjustieren.
|
||||
radius = max(2, int(round(1 / scale)) + 1)
|
||||
dy, dx = best[0], best[1]
|
||||
for oy in range(-radius, radius + 1):
|
||||
for ox in range(-radius, radius + 1):
|
||||
score = overlap_score(gray_a, gray_b, dy + oy, dx + ox)
|
||||
if score > best[2]:
|
||||
best = (dy + oy, dx + ox, score)
|
||||
|
||||
return best
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Setzt ueberlappende Karten-Screenshots zu einem grossen Bild zusammen.')
|
||||
parser.add_argument('folder', help='Ordner mit den Screenshots')
|
||||
parser.add_argument('-o', '--output', default='stitched.png', help='Zieldatei (Standard: stitched.png)')
|
||||
parser.add_argument('--crop', default=None, help='Raender abschneiden: links,oben,rechts,unten')
|
||||
parser.add_argument('--min-score', type=float, default=0.55, help='Mindest-Uebereinstimmung 0..1 (Standard 0.55)')
|
||||
parser.add_argument('--scale', type=float, default=0.5, help='Verkleinerung fuer die Suche (Standard 0.5)')
|
||||
parser.add_argument('--dry-run', action='store_true', help='Nur die Anordnung zeigen, nichts schreiben')
|
||||
args = parser.parse_args()
|
||||
|
||||
crop = None
|
||||
if args.crop:
|
||||
try:
|
||||
crop = tuple(int(v) for v in args.crop.split(','))
|
||||
if len(crop) != 4 or any(v < 0 for v in crop):
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
sys.exit('--crop erwartet vier nicht-negative Zahlen: links,oben,rechts,unten')
|
||||
|
||||
scale = min(1.0, max(0.1, args.scale))
|
||||
|
||||
images = load_images(args.folder, crop)
|
||||
height, width = images[0][1].shape[:2]
|
||||
print(f'{len(images)} Screenshots, je {width}x{height} Pixel')
|
||||
|
||||
# Der haeufigste Fehler ist ein zu grosszuegiges --crop, das Teile der Karte selbst
|
||||
# abschneidet - das faellt sonst erst auf der fertigen Website auf.
|
||||
if crop and any(crop):
|
||||
print(f' --crop schneidet weg: links {crop[0]}, oben {crop[1]}, '
|
||||
f'rechts {crop[2]}, unten {crop[3]} Pixel')
|
||||
print(' (Das sind DEINE Werte - pruefe am Ergebnis, dass davon nichts zur Karte gehoerte.)')
|
||||
|
||||
if len(images) == 1:
|
||||
print('', file=sys.stderr)
|
||||
print('ACHTUNG: In dem Ordner liegt nur ein einziges Bild, es gibt also nichts', file=sys.stderr)
|
||||
print('zusammenzusetzen. Dieses Script verbindet VIELE ueberlappende Screenshots', file=sys.stderr)
|
||||
print('zu einem grossen Bild. Ein einzelner Vollbild-Screenshot hat zu wenig Pixel,', file=sys.stderr)
|
||||
print('um auf der Website scharf zu bleiben: im Spiel maximal hineinzoomen und die', file=sys.stderr)
|
||||
print('Karte in Bahnen abfahren, mit rund 30% Ueberlappung.', file=sys.stderr)
|
||||
print('', file=sys.stderr)
|
||||
|
||||
grays = [to_gray(rgb) for _, rgb in images]
|
||||
smalls = []
|
||||
for gray in grays:
|
||||
if scale < 1.0:
|
||||
small = np.asarray(
|
||||
Image.fromarray(gray).resize(
|
||||
(max(8, int(gray.shape[1] * scale)), max(8, int(gray.shape[0] * scale))),
|
||||
Image.BILINEAR),
|
||||
dtype=np.float32)
|
||||
else:
|
||||
small = gray
|
||||
smalls.append(small)
|
||||
|
||||
# Das erste Bild legt den Nullpunkt fest, alle weiteren werden relativ dazu
|
||||
# eingeordnet. Ein Bild wird nur gesetzt, wenn es zu einem bereits gesetzten
|
||||
# Bild sicher genug passt - der Rest kommt in der naechsten Runde dran.
|
||||
placed = {0: (0, 0)}
|
||||
print(f' [1/{len(images)}] {images[0][0]} -> Nullpunkt')
|
||||
|
||||
pending = set(range(1, len(images)))
|
||||
while pending:
|
||||
progress = False
|
||||
for index in sorted(pending):
|
||||
best = None
|
||||
for anchor in placed:
|
||||
dy, dx, score = find_offset(grays[anchor], grays[index],
|
||||
smalls[anchor], smalls[index], scale)
|
||||
if best is None or score > best[2]:
|
||||
best = (dy, dx, score, anchor)
|
||||
|
||||
dy, dx, score, anchor = best
|
||||
if score < args.min_score:
|
||||
continue
|
||||
|
||||
ay, ax = placed[anchor]
|
||||
placed[index] = (ay + dy, ax + dx)
|
||||
pending.discard(index)
|
||||
progress = True
|
||||
print(f' [{len(placed)}/{len(images)}] {images[index][0]} -> '
|
||||
f'an {images[anchor][0]}, Versatz y{ay + dy:+d} x{ax + dx:+d}, '
|
||||
f'Uebereinstimmung {score:.2f}')
|
||||
|
||||
if not progress:
|
||||
break
|
||||
|
||||
if pending:
|
||||
print('\nNicht zugeordnet (zu wenig Ueberlappung oder zu wenig Struktur im Bild):',
|
||||
file=sys.stderr)
|
||||
for index in sorted(pending):
|
||||
print(f' - {images[index][0]}', file=sys.stderr)
|
||||
print('Hilft meistens: mehr Ueberlappung aufnehmen, --crop fuer feste UI-Elemente '
|
||||
'setzen oder --min-score senken.', file=sys.stderr)
|
||||
|
||||
offsets = [placed[i] for i in sorted(placed)]
|
||||
min_y = min(y for y, _ in offsets)
|
||||
min_x = min(x for _, x in offsets)
|
||||
max_y = max(y for y, _ in offsets) + height
|
||||
max_x = max(x for _, x in offsets) + width
|
||||
|
||||
canvas_height, canvas_width = max_y - min_y, max_x - min_x
|
||||
print(f'\nErgebnis: {canvas_width} x {canvas_height} Pixel '
|
||||
f'({canvas_width * canvas_height / 1_000_000:.1f} Megapixel)')
|
||||
|
||||
if args.dry_run:
|
||||
return
|
||||
|
||||
canvas = np.zeros((canvas_height, canvas_width, 3), dtype=np.float32)
|
||||
# Fuer jedes Zielpixel gewinnt der Screenshot, dessen Mitte am naechsten liegt.
|
||||
# Das haelt die Naht weg von den Bildraendern (wo Vignettierung/UI-Reste sitzen)
|
||||
# und bleibt dabei pixelscharf - anders als weiches Ueberblenden.
|
||||
best_distance = np.full((canvas_height, canvas_width), np.inf, dtype=np.float32)
|
||||
|
||||
yy = np.abs(np.arange(height, dtype=np.float32) - (height - 1) / 2)[:, None]
|
||||
xx = np.abs(np.arange(width, dtype=np.float32) - (width - 1) / 2)[None, :]
|
||||
center_distance = np.maximum(yy / height, xx / width)
|
||||
|
||||
for index in sorted(placed):
|
||||
y, x = placed[index]
|
||||
y -= min_y
|
||||
x -= min_x
|
||||
region = best_distance[y:y + height, x:x + width]
|
||||
mask = center_distance < region
|
||||
region[mask] = center_distance[mask]
|
||||
canvas[y:y + height, x:x + width][mask] = images[index][1][mask]
|
||||
|
||||
result = Image.fromarray(np.clip(canvas, 0, 255).astype(np.uint8))
|
||||
|
||||
# Nicht abgedeckte Raender abschneiden (entstehen bei versetzten Bahnen).
|
||||
covered = np.isfinite(best_distance)
|
||||
rows = np.where(covered.any(axis=1))[0]
|
||||
cols = np.where(covered.any(axis=0))[0]
|
||||
if len(rows) and len(cols):
|
||||
result = result.crop((int(cols[0]), int(rows[0]), int(cols[-1]) + 1, int(rows[-1]) + 1))
|
||||
|
||||
result.save(args.output)
|
||||
print(f'Gespeichert: {args.output} ({result.width} x {result.height})')
|
||||
|
||||
# Aus der Kantenlaenge folgt direkt, wie weit sich die Karte spaeter scharf
|
||||
# heranzoomen laesst - darauf hier hinweisen statt es hinterher raten zu lassen.
|
||||
longest = max(result.width, result.height)
|
||||
levels = max(0, math.ceil(math.log2(longest / 256)))
|
||||
print(f'Daraus entstehen die Zoomstufen 0 bis {levels}.')
|
||||
|
||||
if longest < 4000:
|
||||
print('', file=sys.stderr)
|
||||
print(f'HINWEIS: {longest} Pixel Kantenlaenge sind wenig. Damit die Karte auch nah', file=sys.stderr)
|
||||
print('herangezoomt scharf bleibt, sollten es mindestens 4000 sein, gerne mehr.', file=sys.stderr)
|
||||
print('Mehr Pixel gibt es ueber mehr Screenshots (im Spiel weiter hineinzoomen)', file=sys.stderr)
|
||||
print('und eine hoehere Renderaufloesung (NVIDIA DSR / AMD VSR).', file=sys.stderr)
|
||||
|
||||
key = os.path.splitext(os.path.basename(args.output))[0].lower()
|
||||
print('\nWeiter mit:')
|
||||
print(f' php -d memory_limit=4G tools/make_map_tiles.php {key} "{args.output}" --name="{key.capitalize()}"')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -1,760 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
|
||||
<title>Kachel-Viewer</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0e1013;
|
||||
--gap: #1b2029;
|
||||
--panel: rgba(18, 20, 25, 0.86);
|
||||
--border: #333a45;
|
||||
--text: #e6e8ec;
|
||||
--muted: #8d95a3;
|
||||
--accent: #c9a227;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: "Segoe UI", Roboto, Arial, sans-serif;
|
||||
}
|
||||
|
||||
/* touch-action: none, damit Pointer-Events das Pannen/Zoomen selbst steuern und
|
||||
der Browser nicht dazwischenfunkt (Scrollen, Pull-to-refresh, Doppeltipp-Zoom). */
|
||||
#map {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
touch-action: none;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
#map.dragging { cursor: grabbing; }
|
||||
|
||||
#hud {
|
||||
position: fixed;
|
||||
top: 12px;
|
||||
left: 12px;
|
||||
padding: 10px 12px;
|
||||
background: var(--panel);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
color: var(--muted);
|
||||
pointer-events: none;
|
||||
min-width: 210px;
|
||||
}
|
||||
|
||||
#hud b { color: var(--text); font-weight: 600; }
|
||||
#hud .row { display: flex; justify-content: space-between; gap: 14px; }
|
||||
#hud .sep { height: 1px; background: var(--border); margin: 7px 0; }
|
||||
|
||||
#hud .buttons {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
#hud button {
|
||||
flex: 1;
|
||||
font: inherit;
|
||||
padding: 4px 8px;
|
||||
color: var(--text);
|
||||
background: #202632;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#hud button:hover { border-color: var(--accent); color: var(--accent); }
|
||||
|
||||
#help {
|
||||
position: fixed;
|
||||
left: 12px;
|
||||
bottom: 12px;
|
||||
padding: 7px 10px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
pointer-events: none;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="map"></canvas>
|
||||
|
||||
<div id="hud">
|
||||
<div class="row"><span>Maßstab</span><b id="hud-scale">–</b></div>
|
||||
<div class="row"><span>Ebene z</span><b id="hud-level">–</b></div>
|
||||
<div class="row"><span>Kachel</span><b id="hud-tile">–</b></div>
|
||||
<div class="row"><span>Welt</span><b id="hud-world">–</b></div>
|
||||
<div class="sep"></div>
|
||||
<div class="row"><span>geladen</span><b id="hud-loaded">0</b></div>
|
||||
<div class="row"><span>fehlend</span><b id="hud-absent">0</b></div>
|
||||
<div class="row"><span>Lücken/Bild</span><b id="hud-gaps">0</b></div>
|
||||
<div class="row"><span>Cache</span><b id="hud-cache">0</b></div>
|
||||
<div class="buttons">
|
||||
<button id="btn-reset" type="button" title="Ansicht zurücksetzen (R)">Reset</button>
|
||||
<button id="btn-png" type="button" title="Aktuelle Ansicht als PNG speichern">PNG</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="help">Ziehen = verschieben · Rad/Pinch = zoomen · Pfeile · +/− · R</div>
|
||||
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Konfiguration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Alles Wesentliche laesst sich ueber die Adresszeile einstellen, damit dieselbe Datei
|
||||
* fuer verschiedene Kartensaetze taugt:
|
||||
*
|
||||
* ?tiles=<muster> URL-Muster der Kacheln mit den Platzhaltern {z}, {x}, {y}
|
||||
* ?zmin=&zmax= vorhandene Zoomstufen
|
||||
* ?x=&y= Startpunkt in Weltpixeln
|
||||
*
|
||||
* Voreingestellt ist das Ablageschema von tools/make_map_tiles.php aus dem
|
||||
* Website-Projekt (<schluessel>/<z>/<x>_<y>.jpg). Ein flacher Ordner mit
|
||||
* {z}_{x}_{y}.jpg wird so angesprochen:
|
||||
*
|
||||
* index.html?tiles=elysea_tiles/{z}_{x}_{y}.jpg&zmin=2&zmax=6
|
||||
*/
|
||||
const params = new URLSearchParams(location.search);
|
||||
|
||||
function param(name, fallback) {
|
||||
const value = params.get(name);
|
||||
return value === null || value === '' ? fallback : value;
|
||||
}
|
||||
|
||||
function numParam(name, fallback) {
|
||||
const value = Number(params.get(name));
|
||||
return Number.isFinite(value) && params.get(name) !== null ? value : fallback;
|
||||
}
|
||||
|
||||
/** URL-Muster der Kacheln. {z}, {x}, {y} werden ersetzt. */
|
||||
const TILE_URL = param('tiles', 'tiles/{z}/{x}_{y}.jpg');
|
||||
|
||||
const ZMIN = numParam('zmin', 2);
|
||||
const ZMAX = numParam('zmax', 6);
|
||||
const TILE_PX = numParam('tilesize', 256);
|
||||
|
||||
/**
|
||||
* Feste "Welt" auf der hoechsten Ebene: Weltkoordinaten sind schlichte Pixel in
|
||||
* [0, WORLD)^2. Jede Ebene ist damit dieselbe Pyramide - vier (z+1)-Kacheln decken
|
||||
* exakt eine z-Kachel ab.
|
||||
*/
|
||||
const WORLD = TILE_PX * (1 << ZMAX); // 16384
|
||||
|
||||
/** Startansicht in Weltpixeln. Ohne Angabe die Mitte der Karte. */
|
||||
const START_X = numParam('x', WORLD / 2);
|
||||
const START_Y = numParam('y', WORLD / 2);
|
||||
|
||||
/** Fuellfarbe, wenn zu einem Bereich auf keiner Ebene Material existiert. */
|
||||
const GAP_COLOR = '#1b2029';
|
||||
|
||||
const MAX_INFLIGHT = 8; // gleichzeitige Netzwerk-Anfragen
|
||||
const CACHE_LIMIT = 512; // dekodierte Bitmaps im LRU-Cache
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Kachel-Geometrie
|
||||
//
|
||||
// Diese beiden Funktionen sind die EINZIGE Quelle fuer "welche Kachel deckt welchen
|
||||
// Weltbereich ab". Renderer und HUD benutzen beide - dadurch koennen Anzeige und
|
||||
// Daten nicht auseinanderlaufen.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Weltgroesse einer Kachel auf Ebene z (Kantenlaenge in Weltpixeln). */
|
||||
function tileSpan(z) {
|
||||
return TILE_PX * (1 << (ZMAX - z));
|
||||
}
|
||||
|
||||
/** Weltrechteck der Kachel (z, x, y). */
|
||||
function tileWorldRect(z, x, y) {
|
||||
const size = tileSpan(z);
|
||||
return { x: x * size, y: y * size, size: size };
|
||||
}
|
||||
|
||||
/** Kachelkoordinate, die den Weltpunkt (wx, wy) auf Ebene z enthaelt. */
|
||||
function tileAtWorld(z, wx, wy) {
|
||||
const size = tileSpan(z);
|
||||
return { x: Math.floor(wx / size), y: Math.floor(wy / size) };
|
||||
}
|
||||
|
||||
/** Anzahl Kacheln je Achse auf Ebene z. */
|
||||
function tileCount(z) {
|
||||
return 1 << z;
|
||||
}
|
||||
|
||||
function tileKey(z, x, y) {
|
||||
return z + '_' + x + '_' + y;
|
||||
}
|
||||
|
||||
function tileUrl(z, x, y) {
|
||||
return TILE_URL.replace('{z}', z).replace('{x}', x).replace('{y}', y);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Kamera
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const canvas = document.getElementById('map');
|
||||
const ctx = canvas.getContext('2d', { alpha: false });
|
||||
|
||||
let viewW = 0, viewH = 0, dpr = 1;
|
||||
let camX = START_X, camY = START_Y;
|
||||
let k = 1; // Bildschirmpixel je Weltpixel
|
||||
|
||||
function worldToScreenX(wx) { return (wx - camX) * k + viewW / 2; }
|
||||
function worldToScreenY(wy) { return (wy - camY) * k + viewH / 2; }
|
||||
function screenToWorldX(sx) { return (sx - viewW / 2) / k + camX; }
|
||||
function screenToWorldY(sy) { return (sy - viewH / 2) / k + camY; }
|
||||
|
||||
/**
|
||||
* Grenzen fuer k.
|
||||
*
|
||||
* Nativ ist eine Ebene, wenn ein Kachel-Bildpixel genau einem Geraetepixel entspricht.
|
||||
* Auf Ebene z deckt ein Bildpixel 2^(ZMAX-z) Weltpixel ab, nativ gilt also
|
||||
* k * dpr * 2^(ZMAX-z) = 1. Fuer die hoechste Ebene (z = ZMAX) heisst das k = 1/dpr.
|
||||
*
|
||||
* Nach oben sind zwei Ebenen ueber nativ erlaubt (vierfache Vergroesserung), nach unten
|
||||
* eine Halbierung unter "ganze Welt passt ins Fenster". Zwei statt einer Ebene deshalb,
|
||||
* weil flache Pyramiden sonst kaum Spielraum lassen: eine 1024er-Karte hat nur die
|
||||
* Stufen 0 bis 2, da waere die Startansicht schon fast am Anschlag.
|
||||
*/
|
||||
function scaleBounds() {
|
||||
const fit = Math.min(viewW, viewH) / WORLD;
|
||||
return { min: fit / 2, max: 4 / dpr };
|
||||
}
|
||||
|
||||
function clampScale(value) {
|
||||
const b = scaleBounds();
|
||||
return Math.min(b.max, Math.max(b.min, value));
|
||||
}
|
||||
|
||||
/** Kameramittelpunkt innerhalb der Welt halten. */
|
||||
function clampCamera() {
|
||||
camX = Math.min(WORLD, Math.max(0, camX));
|
||||
camY = Math.min(WORLD, Math.max(0, camY));
|
||||
}
|
||||
|
||||
/**
|
||||
* Aktive Kachelebene: diejenige, deren Darstellung der nativen Aufloesung am naechsten
|
||||
* kommt. Aus k * dpr * 2^(ZMAX-z) = 1 folgt z = ZMAX + log2(k * dpr).
|
||||
*/
|
||||
function activeLevel() {
|
||||
const z = Math.round(ZMAX + Math.log2(k * dpr));
|
||||
return Math.min(ZMAX, Math.max(ZMIN, z));
|
||||
}
|
||||
|
||||
function resetView() {
|
||||
camX = START_X;
|
||||
camY = START_Y;
|
||||
// Startmassstab: rund vier Level-6-Kacheln fuellen die Fensterbreite.
|
||||
k = clampScale(viewW / (4 * TILE_PX));
|
||||
requestRender();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Kachel-Speicher: LRU-Cache, Ladewarteschlange, Fehlliste
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Map haelt die Einfuegereihenfolge - der aelteste Eintrag ist der erste. */
|
||||
const cache = new Map();
|
||||
const absent = new Set(); // dauerhaft nicht vorhanden (404 o.ae.)
|
||||
const pending = new Set(); // laeuft gerade
|
||||
const queue = []; // wartet auf einen freien Slot
|
||||
let inflight = 0;
|
||||
let loadedCount = 0;
|
||||
|
||||
const stats = { gaps: 0 };
|
||||
|
||||
function cacheGet(key) {
|
||||
const bitmap = cache.get(key);
|
||||
if (bitmap === undefined) return null;
|
||||
// Zugriff macht den Eintrag wieder jung: loeschen und hinten neu einfuegen.
|
||||
cache.delete(key);
|
||||
cache.set(key, bitmap);
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
function cachePut(key, bitmap) {
|
||||
cache.set(key, bitmap);
|
||||
while (cache.size > CACHE_LIMIT) {
|
||||
const oldestKey = cache.keys().next().value;
|
||||
const oldest = cache.get(oldestKey);
|
||||
cache.delete(oldestKey);
|
||||
// ImageBitmap haelt Speicher ausserhalb des JS-Heaps - explizit freigeben.
|
||||
if (oldest && typeof oldest.close === 'function') oldest.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stellt eine Kachel in die Warteschlange. Pro Koordinate wird genau ein Versuch
|
||||
* unternommen - kein Wiederholen, keine Schleife.
|
||||
*/
|
||||
function request(z, x, y, priority) {
|
||||
if (z < ZMIN || z > ZMAX) return;
|
||||
const count = tileCount(z);
|
||||
if (x < 0 || y < 0 || x >= count || y >= count) return;
|
||||
|
||||
const key = tileKey(z, x, y);
|
||||
if (cache.has(key) || absent.has(key) || pending.has(key)) return;
|
||||
|
||||
pending.add(key);
|
||||
if (priority) queue.unshift({ key, z, x, y });
|
||||
else queue.push({ key, z, x, y });
|
||||
pump();
|
||||
}
|
||||
|
||||
function pump() {
|
||||
while (inflight < MAX_INFLIGHT && queue.length > 0) {
|
||||
const job = queue.shift();
|
||||
inflight++;
|
||||
loadTile(job).finally(() => {
|
||||
inflight--;
|
||||
pending.delete(job.key);
|
||||
pump();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTile(job) {
|
||||
try {
|
||||
const response = await fetch(tileUrl(job.z, job.x, job.y), { cache: 'force-cache' });
|
||||
if (!response.ok) throw new Error('HTTP ' + response.status);
|
||||
|
||||
const blob = await response.blob();
|
||||
let bitmap;
|
||||
if (typeof createImageBitmap === 'function') {
|
||||
bitmap = await createImageBitmap(blob);
|
||||
} else {
|
||||
bitmap = await blobToImage(blob);
|
||||
}
|
||||
|
||||
cachePut(job.key, bitmap);
|
||||
loadedCount++;
|
||||
} catch (err) {
|
||||
// Fehlende Kacheln sind erwartbar (Raster ragt ueber das Kartengebiet hinaus).
|
||||
absent.add(job.key);
|
||||
}
|
||||
requestRender();
|
||||
}
|
||||
|
||||
/** Rueckfallweg fuer Browser ohne createImageBitmap. */
|
||||
function blobToImage(blob) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const img = new Image();
|
||||
img.onload = () => { URL.revokeObjectURL(url); resolve(img); };
|
||||
img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('decode')); };
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Zeichnen
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let renderPending = false;
|
||||
|
||||
function requestRender() {
|
||||
if (renderPending) return;
|
||||
renderPending = true;
|
||||
requestAnimationFrame(render);
|
||||
}
|
||||
|
||||
function resize() {
|
||||
dpr = Math.min(3, window.devicePixelRatio || 1);
|
||||
viewW = canvas.clientWidth;
|
||||
viewH = canvas.clientHeight;
|
||||
canvas.width = Math.max(1, Math.round(viewW * dpr));
|
||||
canvas.height = Math.max(1, Math.round(viewH * dpr));
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeichnet den Weltbereich rect aus dem Bild der Kachel (iz, ix, iy).
|
||||
*
|
||||
* Die Bildschirmkanten werden einzeln gerundet und die Breite daraus abgeleitet
|
||||
* (rechts minus links). Dadurch benutzt eine Nachbarkachel fuer ihre linke Kante
|
||||
* exakt denselben gerundeten Wert - es entstehen weder Luecken noch Ueberlappungen,
|
||||
* auch nicht beim Uebergang zwischen Ebenen.
|
||||
*/
|
||||
function blit(image, iz, ix, iy, rect) {
|
||||
const tile = tileWorldRect(iz, ix, iy);
|
||||
const imgPerWorld = TILE_PX / tile.size;
|
||||
|
||||
const sx = (rect.x - tile.x) * imgPerWorld;
|
||||
const sy = (rect.y - tile.y) * imgPerWorld;
|
||||
const sw = rect.size * imgPerWorld;
|
||||
|
||||
const left = Math.round(worldToScreenX(rect.x) * dpr);
|
||||
const top = Math.round(worldToScreenY(rect.y) * dpr);
|
||||
const right = Math.round(worldToScreenX(rect.x + rect.size) * dpr);
|
||||
const bottom = Math.round(worldToScreenY(rect.y + rect.size) * dpr);
|
||||
|
||||
const dw = right - left;
|
||||
const dh = bottom - top;
|
||||
if (dw <= 0 || dh <= 0) return;
|
||||
|
||||
// Glaetten nur beim Hochskalieren; bei 1:1 oder Verkleinerung bleiben Kanten scharf.
|
||||
ctx.imageSmoothingEnabled = dw > sw + 0.5;
|
||||
ctx.drawImage(image, sx, sy, sw, sw, left, top, dw, dh);
|
||||
}
|
||||
|
||||
function fillGap(rect) {
|
||||
const left = Math.round(worldToScreenX(rect.x) * dpr);
|
||||
const top = Math.round(worldToScreenY(rect.y) * dpr);
|
||||
const right = Math.round(worldToScreenX(rect.x + rect.size) * dpr);
|
||||
const bottom = Math.round(worldToScreenY(rect.y + rect.size) * dpr);
|
||||
ctx.fillStyle = GAP_COLOR;
|
||||
ctx.fillRect(left, top, right - left, bottom - top);
|
||||
}
|
||||
|
||||
/**
|
||||
* Malt die Kachel (z, x, y) - notfalls aus Ersatzmaterial.
|
||||
*
|
||||
* Reihenfolge laut Vorgabe: erst das Original, dann mehr Detail (alle vier Kinder auf
|
||||
* z+1, aber nur wenn alle vier da sind), dann grobere Elternkacheln nach oben bis ZMIN,
|
||||
* zuletzt eine neutrale Fuellfarbe.
|
||||
*/
|
||||
function paintTile(z, x, y) {
|
||||
const rect = tileWorldRect(z, x, y);
|
||||
const key = tileKey(z, x, y);
|
||||
|
||||
const image = cacheGet(key);
|
||||
if (image) {
|
||||
blit(image, z, x, y, rect);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!absent.has(key)) {
|
||||
request(z, x, y, true);
|
||||
// Das Elternteil gleich mitbestellen: es ist der Ersatz, falls diese Kachel
|
||||
// fehlt oder noch laedt - ohne das waere die Rueckfallregel unten wirkungslos,
|
||||
// weil auf der aktiven Ebene nur diese eine Ebene im Cache liegt.
|
||||
if (z > ZMIN) request(z - 1, x >> 1, y >> 1, false);
|
||||
}
|
||||
|
||||
// 1) Mehr Detail: vier Kinder, aber nur vollstaendig (sonst entstuenden Loecher).
|
||||
if (z < ZMAX) {
|
||||
const cz = z + 1;
|
||||
const kids = [[2 * x, 2 * y], [2 * x + 1, 2 * y], [2 * x, 2 * y + 1], [2 * x + 1, 2 * y + 1]];
|
||||
const images = kids.map(([kx, ky]) => cacheGet(tileKey(cz, kx, ky)));
|
||||
if (images.every(Boolean)) {
|
||||
kids.forEach(([kx, ky], i) => blit(images[i], cz, kx, ky, tileWorldRect(cz, kx, ky)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Weniger Detail: naechstbeste Elternkachel, hochskaliert.
|
||||
for (let pz = z - 1; pz >= ZMIN; pz--) {
|
||||
const shift = z - pz;
|
||||
const px = x >> shift;
|
||||
const py = y >> shift;
|
||||
const parent = cacheGet(tileKey(pz, px, py));
|
||||
if (parent) {
|
||||
blit(parent, pz, px, py, rect);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 3) Nichts vorhanden.
|
||||
fillGap(rect);
|
||||
stats.gaps++;
|
||||
}
|
||||
|
||||
/** Laedt den Ring um den sichtbaren Bereich vor (aktuelle und naechsthoehere Ebene). */
|
||||
function prefetch(z, tx0, ty0, tx1, ty1) {
|
||||
const pad = Math.max(1, Math.ceil((tx1 - tx0 + 1) / 2));
|
||||
for (let x = tx0 - pad; x <= tx1 + pad; x++) {
|
||||
for (let y = ty0 - pad; y <= ty1 + pad; y++) {
|
||||
if (x >= tx0 && x <= tx1 && y >= ty0 && y <= ty1) continue; // sichtbar, laeuft schon
|
||||
request(z, x, y, false);
|
||||
}
|
||||
}
|
||||
if (z < ZMAX) {
|
||||
for (let x = 2 * tx0; x <= 2 * tx1 + 1; x++) {
|
||||
for (let y = 2 * ty0; y <= 2 * ty1 + 1; y++) {
|
||||
request(z + 1, x, y, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
renderPending = false;
|
||||
resize();
|
||||
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.fillStyle = '#0e1013';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
const z = activeLevel();
|
||||
const span = tileSpan(z);
|
||||
const count = tileCount(z);
|
||||
|
||||
const topLeft = tileAtWorld(z, screenToWorldX(0), screenToWorldY(0));
|
||||
const bottomRight = tileAtWorld(z, screenToWorldX(viewW), screenToWorldY(viewH));
|
||||
|
||||
const tx0 = Math.max(0, topLeft.x);
|
||||
const ty0 = Math.max(0, topLeft.y);
|
||||
const tx1 = Math.min(count - 1, bottomRight.x);
|
||||
const ty1 = Math.min(count - 1, bottomRight.y);
|
||||
|
||||
stats.gaps = 0;
|
||||
for (let x = tx0; x <= tx1; x++) {
|
||||
for (let y = ty0; y <= ty1; y++) {
|
||||
paintTile(z, x, y);
|
||||
}
|
||||
}
|
||||
|
||||
prefetch(z, tx0, ty0, tx1, ty1);
|
||||
updateHud(z, span);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HUD
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const hud = {
|
||||
scale: document.getElementById('hud-scale'),
|
||||
level: document.getElementById('hud-level'),
|
||||
tile: document.getElementById('hud-tile'),
|
||||
world: document.getElementById('hud-world'),
|
||||
loaded: document.getElementById('hud-loaded'),
|
||||
ab: document.getElementById('hud-absent'),
|
||||
gaps: document.getElementById('hud-gaps'),
|
||||
cache: document.getElementById('hud-cache'),
|
||||
};
|
||||
|
||||
let pointerScreenX = null, pointerScreenY = null;
|
||||
|
||||
function updateHud(z) {
|
||||
hud.scale.textContent = k.toFixed(3) + ' px/wp';
|
||||
hud.level.textContent = z;
|
||||
hud.loaded.textContent = loadedCount;
|
||||
hud.ab.textContent = absent.size;
|
||||
hud.gaps.textContent = stats.gaps;
|
||||
hud.cache.textContent = cache.size + '/' + CACHE_LIMIT;
|
||||
|
||||
if (pointerScreenX === null) {
|
||||
hud.tile.textContent = '–';
|
||||
hud.world.textContent = '–';
|
||||
return;
|
||||
}
|
||||
|
||||
const wx = screenToWorldX(pointerScreenX);
|
||||
const wy = screenToWorldY(pointerScreenY);
|
||||
// Dieselbe Funktion wie im Renderer - Anzeige und Daten koennen nicht abweichen.
|
||||
const t = tileAtWorld(z, wx, wy);
|
||||
hud.tile.textContent = z + '_' + t.x + '_' + t.y;
|
||||
hud.world.textContent = Math.round(wx) + ', ' + Math.round(wy);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bedienung
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Zoomt so, dass der Weltpunkt unter (sx, sy) genau dort stehen bleibt. */
|
||||
function zoomAt(sx, sy, factor) {
|
||||
const before = clampScale(k);
|
||||
const after = clampScale(before * factor);
|
||||
if (after === before) return;
|
||||
|
||||
const wx = screenToWorldX(sx);
|
||||
const wy = screenToWorldY(sy);
|
||||
|
||||
k = after;
|
||||
// Kamera so nachziehen, dass (wx, wy) wieder auf (sx, sy) landet.
|
||||
camX = wx - (sx - viewW / 2) / k;
|
||||
camY = wy - (sy - viewH / 2) / k;
|
||||
|
||||
clampCamera();
|
||||
requestRender();
|
||||
}
|
||||
|
||||
const activePointers = new Map();
|
||||
let dragLast = null;
|
||||
let pinchStart = null;
|
||||
|
||||
canvas.addEventListener('pointerdown', (e) => {
|
||||
canvas.setPointerCapture(e.pointerId);
|
||||
activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
|
||||
if (activePointers.size === 1) {
|
||||
dragLast = { x: e.clientX, y: e.clientY };
|
||||
canvas.classList.add('dragging');
|
||||
} else if (activePointers.size === 2) {
|
||||
const [a, b] = [...activePointers.values()];
|
||||
pinchStart = { distance: Math.hypot(a.x - b.x, a.y - b.y), k: k };
|
||||
dragLast = null;
|
||||
}
|
||||
});
|
||||
|
||||
canvas.addEventListener('pointermove', (e) => {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
pointerScreenX = e.clientX - rect.left;
|
||||
pointerScreenY = e.clientY - rect.top;
|
||||
|
||||
if (activePointers.has(e.pointerId)) {
|
||||
activePointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
}
|
||||
|
||||
if (activePointers.size === 2 && pinchStart) {
|
||||
const [a, b] = [...activePointers.values()];
|
||||
const distance = Math.hypot(a.x - b.x, a.y - b.y);
|
||||
if (distance > 0 && pinchStart.distance > 0) {
|
||||
const midX = (a.x + b.x) / 2 - rect.left;
|
||||
const midY = (a.y + b.y) / 2 - rect.top;
|
||||
const target = clampScale(pinchStart.k * (distance / pinchStart.distance));
|
||||
zoomAt(midX, midY, target / k);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (dragLast && activePointers.size === 1) {
|
||||
camX -= (e.clientX - dragLast.x) / k;
|
||||
camY -= (e.clientY - dragLast.y) / k;
|
||||
dragLast = { x: e.clientX, y: e.clientY };
|
||||
clampCamera();
|
||||
}
|
||||
|
||||
requestRender();
|
||||
});
|
||||
|
||||
function endPointer(e) {
|
||||
activePointers.delete(e.pointerId);
|
||||
if (activePointers.size < 2) pinchStart = null;
|
||||
if (activePointers.size === 0) {
|
||||
dragLast = null;
|
||||
canvas.classList.remove('dragging');
|
||||
} else {
|
||||
const first = [...activePointers.values()][0];
|
||||
dragLast = { x: first.x, y: first.y };
|
||||
}
|
||||
}
|
||||
|
||||
canvas.addEventListener('pointerup', endPointer);
|
||||
canvas.addEventListener('pointercancel', endPointer);
|
||||
canvas.addEventListener('pointerleave', () => {
|
||||
pointerScreenX = pointerScreenY = null;
|
||||
requestRender();
|
||||
});
|
||||
|
||||
canvas.addEventListener('wheel', (e) => {
|
||||
e.preventDefault();
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
// deltaMode 1 = Zeilen, 2 = Seiten - auf Pixel normieren, sonst zoomt Firefox anders.
|
||||
const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? viewH : 1;
|
||||
const factor = Math.exp(-e.deltaY * unit * 0.0015);
|
||||
zoomAt(e.clientX - rect.left, e.clientY - rect.top, factor);
|
||||
}, { passive: false });
|
||||
|
||||
window.addEventListener('keydown', (e) => {
|
||||
const step = 80 / k;
|
||||
switch (e.key) {
|
||||
case 'ArrowLeft': camX -= step; break;
|
||||
case 'ArrowRight': camX += step; break;
|
||||
case 'ArrowUp': camY -= step; break;
|
||||
case 'ArrowDown': camY += step; break;
|
||||
case '+': case '=': zoomAt(viewW / 2, viewH / 2, 2); return;
|
||||
case '-': case '_': zoomAt(viewW / 2, viewH / 2, 0.5); return;
|
||||
case 'r': case 'R': resetView(); return;
|
||||
default: return;
|
||||
}
|
||||
e.preventDefault();
|
||||
clampCamera();
|
||||
requestRender();
|
||||
});
|
||||
|
||||
/**
|
||||
* Einziger Weg, auf Groessenaenderungen zu reagieren - auch auf die allererste.
|
||||
*
|
||||
* Beim Parsen kann das Canvas noch 0x0 gross sein; wuerde die Startansicht dann schon
|
||||
* berechnet, kaeme k = 0 heraus und die Ansicht bliebe dauerhaft leer. Deshalb wird die
|
||||
* Startansicht erst gesetzt, sobald echte Masse vorliegen.
|
||||
*/
|
||||
let viewInitialised = false;
|
||||
|
||||
function handleViewportChange() {
|
||||
resize();
|
||||
if (viewW === 0 || viewH === 0) return;
|
||||
|
||||
if (!viewInitialised) {
|
||||
viewInitialised = true;
|
||||
resetView();
|
||||
// Das allererste Bild direkt zeichnen statt ueber requestAnimationFrame: in einem
|
||||
// Hintergrund-Tab wird rAF gedrosselt, dann bliebe die Seite leer und es wuerde
|
||||
// auch keine Kachel angefordert (die Anforderungen entstehen beim Zeichnen).
|
||||
render();
|
||||
return;
|
||||
}
|
||||
|
||||
k = clampScale(k);
|
||||
clampCamera();
|
||||
requestRender();
|
||||
}
|
||||
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
new ResizeObserver(handleViewportChange).observe(canvas);
|
||||
}
|
||||
window.addEventListener('resize', handleViewportChange);
|
||||
|
||||
document.getElementById('btn-reset').addEventListener('click', resetView);
|
||||
|
||||
document.getElementById('btn-png').addEventListener('click', () => {
|
||||
// Die Kacheln kommen per fetch von derselben Herkunft, das Canvas ist also nicht
|
||||
// "tainted" und laesst sich exportieren.
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) return;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'elysea_' + Math.round(camX) + '_' + Math.round(camY) + '_z' + activeLevel() + '.png';
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 5000);
|
||||
}, 'image/png');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Start
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Die beiden groebsten Ebenen einmalig komplett laden (16 + 64 Kacheln, fast alle nur
|
||||
* wenige hundert Byte). Damit existiert immer eine Grundschicht, auf die die
|
||||
* Rueckfallregel ausweichen kann - sichtbare Luecken gibt es dadurch praktisch nie,
|
||||
* auch nicht waehrend des Nachladens.
|
||||
*/
|
||||
function primeCoarseLevels() {
|
||||
for (let z = ZMIN; z <= Math.min(ZMIN + 1, ZMAX); z++) {
|
||||
const count = tileCount(z);
|
||||
for (let x = 0; x < count; x++) {
|
||||
for (let y = 0; y < count; y++) request(z, x, y, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleViewportChange();
|
||||
primeCoarseLevels();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Loading…
Reference in a new issue