Compare commits

...
3 Commits
Author SHA1 Message Date
koka 8deba7cfb4 Deliver beta.161 playtest fixes and shared server metrics
Build Sanctuary / build (push) Waiting to run
2026-09-24 00:20:06 +02:00
koka c1d2278674 beta.160: opt-in shaders and lightweight local duo test lab
Build Sanctuary / build (push) Waiting to run
2026-09-23 22:27:49 +02:00
koka bdaad0c940 Add community search, responsive gallery and followed notice map markers
Build Sanctuary / build (push) Waiting to run
2026-09-23 01:20:17 +02:00
44 changed files with 1390 additions and 63 deletions
+21
View File
@@ -1,5 +1,26 @@
# Sanctuary
## beta.161 — correctifs de séance et site vivant
Liste des joueurs sur U, suivi des demandes expliqué, intendance compacte et
compteurs réels partagés avec le site. Site public en lecture seule, Gazette
en accordéon avec aperçus compacts.
[Contrat et vérifications](docs/session-fixes-beta161.md).
## beta.160 — laboratoire de test en duo
Shader désactivé sur une configuration neuve, serveur local léger, personnages
de test optionnels et séances de captures horodatées.
[Mode d’emploi et vérifications](docs/duo-lab-beta160.md) ·
[Récap Discord 130–160](docs/discord-beta130-160.md).
## beta.159 — recherche communautaire et galerie adaptable (pack local)
Recherche par joueur, titre ou texte, historique Serveur en lecture seule,
année dans les dates et galerie adaptée au GUI avec grand aperçu.
Repères « ! » et infobulles sur la carte pour les demandes suivies géolocalisées.
[Résultat et vérifications](docs/community-search-beta159.md).
## beta.158 — cartes communautaires et demandes suivies (pack local)
Grilles à deux colonnes, articles photo/texte, annonces colorées avec visages,
+39
View File
@@ -199,3 +199,42 @@ Les anciens boutons de liaison et d'historique public de l'intendance disparaiss
En mode fichier, le panneau d’intendance en jeu s’ouvre avec
`/sanctuary community admin` ; le serveur exige les permissions opérateur.
## Évolution beta.159 — recherche et lecture de l’intendance
Le schéma reste **v3** : aucune migration de données. Cette évolution remplace
la restriction de lecture publique de beta.158 : les onglets Gazette, Tableau
et Serveur permettent de lire leurs historiques. La publication et la gestion
de l’intendance restent dans l’administration, sans réponse ni abonnement.
`list` et `cards` acceptent une recherche facultative dans `Request.body` (120
caractères maximum, vide par défaut). Le site utilise le paramètre GET `q`,
conservé dans la pagination. Recherche littérale de sous-chaîne dans le nom de
l’auteur, le titre **ou** le corps, sans distinction de casse, avant pagination.
Les accents restent significatifs et `%` / `_` sont des caractères ordinaires.
Le filtre reste limité au serveur et à la rubrique sélectionnés ; les contenus
masqués restent exclus. Les épingles gardent leur priorité. Le client attend
300 ms après la frappe et ignore les réponses correspondant à un ancien filtre.
Les pages restent bornées à 10 publications ; aucune recherche dans les réponses.
Les dates des publications affichent l’année (UTC). Le menu pause affiche la date
complète dans la langue et le fuseau local du joueur. La galerie utilise la
surface disponible du GUI, adapte ses colonnes et conserve ses pages de 24
captures défilantes. Le clic ouvre un aperçu dans cette surface, en conservant
les proportions et les boutons Retour / Assigner. Le formulaire conserve son
aperçu compact. Les PNG sources ne sont pas modifiés.
Les demandes suivies ouvertes qui ont une position affichent un `!` sur la carte
de pause et le grand atlas, dans la dimension correspondante. Elles ne révèlent
pas le terrain et ne chargent aucun chunk. L’infobulle montre titre, auteur,
résumé, coordonnées, matériaux et récompense ; les listes longues sont abrégées
pour rester dans le GUI. Le clic ouvre l’annonce. « Voir sur la carte » centre
l’atlas sur son lieu dans la dimension courante, sans téléportation. Les repères
suivent tous les abonnements, indépendamment des trois suivis visibles dans le
HUD ; ils disparaissent au désabonnement, à la clôture ou au masquage. Un
rafraîchissement des suivis reste actif lorsque la carte ou la pause est ouverte
(période de cinq secondes, différée si une autre requête est en cours).
Le message réseau `following` ajoute `summary`, extrait littéral du corps limité
à 240 caractères Unicode plus une ellipse. Le texte intégral et les photos ne
sont pas diffusés dans ce message. Aucun champ persistant supplémentaire.
+81
View File
@@ -0,0 +1,81 @@
# beta.159 — recherche communautaire et galerie adaptable
Branche `codex/community-search-gallery-beta159`, socle beta.158.
## Résultat
Une barre de recherche filtre les publications par auteur, titre ou texte côté
serveur, avant pagination. Le filtre accompagne les pages suivantes, conserve
les épingles et se réinitialise en effaçant le champ. Les réponses aux anciennes
recherches sont ignorées et le focus de saisie est conservé.
Les trois onglets Gazette / Tableau / Serveur donnent accès aux publications de
chaque rubrique. L’en-tête d’intendance de la pause ouvre aussi son historique.
La lecture est publique ; la publication et la gestion des messages du serveur
restent réservées au panneau administrateur, même pour un opérateur visitant
l’écran public. Les messages du serveur n’acceptent ni réponses ni abonnements.
L’année figure dans la date de pause et les métadonnées des publications. La
galerie utilise l’espace disponible aux différentes échelles de GUI et tailles
de fenêtre. Les captures restent paginées par 24 avec défilement. Cliquer une
capture ouvre un grand aperçu avec les commandes de retour et d’assignation.
La photo assignée reste compacte dans le formulaire et les brouillons sont
conservés lors du retour. Aucune modification des PNG originaux.
Les annonces suivies géolocalisées portent un « ! » sur les deux cartes.
L’infobulle fournit titre, auteur, résumé, coordonnées, matériaux et récompense
sans ouvrir la discussion ; le clic reste disponible. Un bouton dans l’annonce
centre le grand atlas sur sa position, dans la dimension courante. Aucune
téléportation ni révélation du terrain : seules les coordonnées publiées sont
projetées. Les annonces fermées, masquées, sans lieu ou non suivies ne portent
pas de repère. Les longues infobulles sont abrégées pour tenir dans le GUI.
Le site suit le même contrat de recherche et de lecture. Schéma v3 inchangé,
aucune migration de sauvegarde ni de base. Libellés français et anglais.
## Vérifications
- Stockage fichier et MariaDB : recherche par auteur et corps, casse et accents,
filtre avant pagination, épingles conservées, caractères `%` / `_` littéraux,
rubrique et serveur isolés, contenus masqués exclus, borne de 120 caractères.
- Client natif Minecraft 26.3 / Java 25 / Vulkan : galerie et aperçu en FR/EN,
GUI 2/3/4 et fenêtres 1280×960 / 1920×1080 ; retour au brouillon, assignation,
publication, listes défilantes et chargement des pages suivantes.
- Recherche en jeu au-delà de la première page, filtre par joueur, effacement,
conservation du focus et rejet d’une réponse correspondant à l’ancien filtre.
- Lecture des messages serveur par un joueur ordinaire, aucun contrôle d’écriture
dans les pages publiques, y compris pour l’opérateur ; administration inchangée.
- Carte : projection dans la dimension correspondante, titre/auteur/résumé,
matériaux et récompense au survol ; ouverture de la demande par clic sur les
deux cartes ; retrait immédiat du repère après désabonnement.
- Date avec année en FR/EN, GUI 2/3/4, sans chevauchement de l’intendance.
- Site : 24 tests / 157 assertions sur SQLite puis MariaDB de développement,
formatage Pint réussi. Commit local `e70e78d`, branche `codex/community-search`.
La commande complète `./gradlew :sanctuary:runClientGameTest check build assemblePack`
avec les propriétés client Cards158, QuickTests et Vulkan a exécuté 252 GameTests :
229 réussites et les mêmes 23 échecs que beta.158. Aucun test serveur supprimé
ou modifié. La comparaison est conservée dans `build/search159-server-failures.json`
et le journal dans `build/beta159-check-build.log`.
Les contrôles restants, la compilation et `assemblePack` passent avec la suite
serveur déjà exécutée exclue (`-x :sanctuary:runGameTest`) : 133 tâches, journal
`build/beta159-release.log`. Le parcours client final passe en mode MariaDB,
puis en mode fichier (`build/beta159-file-client.log`). Les repères ont été
vérifiés avec et sans terrain d’atlas débloqué ; les infobulles restent dans la
fenêtre aux GUI 2/3/4. Captures représentatives inspectées :
`build/search159-file-screens/` et `build/search159-database-screens/`.
L’export packwiz est vérifié : intégrité ZIP, version beta.159, JAR embarqué
identique au JAR de livraison. Les 29 ressources de shaders sont identiques à
beta.158, qui conserve le socle beta.151. Les anciens JAR et MRpack beta.154 à
beta.158 restent présents. Aucun monde personnel, déploiement de serveur, canal
packwiz ou instance Prism n’est modifié.
## Artefacts locaux
- `mods/sanctuary/build/libs/sanctuary-beta.159.jar` — SHA-256 `c30d57a5f37e0a5c9dbb387ca831ce9e5c15a1dfe4cb55af0af20a376e862576`.
- `build/Sanctuary-beta.159.mrpack` — SHA-256 `868932d88bc241bfb526a7c5e4054009e247658bd0784b7141d82017edcc2823`.
+60
View File
@@ -0,0 +1,60 @@
# Récap Discord — beta.130 à beta.160
Brouillon à relire avant publication. Les captures sont des scènes de test,
pas des photos d'un serveur public. Aucune annonce envoyée automatiquement.
## Message 1 — l'image et la lumière
**Sanctuary — retour sur les beta.130 à 160**
On a d'abord beaucoup travaillé l'ambiance : bloom, minerais lumineux, rebonds
de couleur, relief des matériaux, reflets, rayons du soleil et lumières portées.
L'eau a reçu ses propres réglages, puis plusieurs passes de correction ont
amélioré les transitions, les distances et les matières.
La version du shader conservée est celle du socle beta.151. Elle reste gourmande,
mais on garde ce travail ! En beta.160, le shader devient **désactivé par défaut
sur une nouvelle configuration**, et peut être réactivé dans les options.
Images : `01-minerais-bloom-beta130.png`, `02-eau-beta144.png`.
## Message 2 — la vie du serveur
Le chantier suivant rapproche Minecraft et le site Sanctuary : **Gazette,
tableau d'affichage et intendance** partagent un contrat de publications.
Le mod fonctionne avec des fichiers par défaut ; une base MariaDB permet de
partager les données avec le site.
Le menu pause a été réorganisé autour des systèmes Sanctuary, de la carte et
des publications. La Gazette accepte les articles avec une capture obligatoire,
les réponses, les épingles et la recherche par joueur ou contenu.
Le tableau distingue les types d'annonces par couleur. Les demandes peuvent
indiquer un lieu, des matériaux, une récompense et des participants. Ce sont
des descriptions pour organiser les échanges entre joueurs : aucun coffre de
dépôt ni paiement automatique. Une demande suivie apparaît avec un **! sur la
carte**, et son résumé se lit au survol.
Images : `03-menu-et-quete-beta159.png`, `04-materiaux-beta158.png`.
## Message 3 — tester ensemble
Avec la beta.160, on prépare nos séances de test en binôme sur Mac : un petit
serveur local, un seul Minecraft à l'écran et des personnages de laboratoire.
Le but : vérifier les échanges côté technique pendant que les vrais essais en
jeu nous montrent ce qu'il faut simplifier dans l'interface.
Des scènes courtes et des captures horodatées permettront de reprendre les
moments où l'on hésite, cherche un bouton ou perd le fil. Le prochain chantier
est l'ergonomie, dans le jeu comme sur le site.
## Sources et pièces jointes
Les images originales et leurs empreintes sont rassemblées dans
`build/discord-beta130-160/` (ignoré par Git), avec `images.json` pour la provenance.
Les captures anciennes illustrent leur version d'origine, sans revendiquer une
nouvelle validation graphique. Les sondages restent une idée, pas une fonction livrée.
Références : `shader-beta130.md` à `nether-pbr-beta151.md`,
`community-beta154.md`, `pause-redesign-beta155.md`, `gazette-photos-beta157.md`,
`community-cards-beta158.md`, `community-search-beta159.md`, `duo-lab-beta160.md`.
+155
View File
@@ -0,0 +1,155 @@
# DUO-160 — laboratoire Mac et tests en binôme
Branche `codex/duo-lab-beta160`, base `beta.159`. Minecraft 26.3, Java 25,
Fabric 0.19.5 ; mêmes dépendances. Validation graphique Vulkan uniquement.
## Contrat
Le shader natif est OFF quand sa préférence est absente. Un choix sauvegardé
ON ou OFF reste respecté, ainsi que ses intensités. Aucun shader supprimé :
les ressources beta.151 restent identiques. Le client du laboratoire reçoit
explicitement `enabled:false`, indépendamment de l'installation personnelle.
Tout le laboratoire réside dans `build/duo/`, ignoré par Git. Le monde plat
`duo-flat-160`, graine 160, sert aux interfaces et aux échanges ; il ne valide
pas le terrain Sanctuary. Aucun monde personnel ouvert ou modifié.
Le module `sanctuary-test` fournit les personnages uniquement avec
`-Dsanctuary.duo=true`. Il ne fait pas partie du pack normal.
## Préparer et lancer
```sh
export JAVA_HOME=$(/usr/libexec/java_home -v 25)
./gradlew :sanctuary-test:exportDuoLaunch --max-workers=1 -Dorg.gradle.jvmargs=-Xmx1G
python3 scripts/duo_lab.py prepare
python3 scripts/duo_lab.py server
# Dans un autre terminal :
python3 scripts/duo_lab.py client
```
L'export permet ensuite de lancer Java directement, sans conserver un processus
Gradle pendant la séance. Préparer à nouveau ne remplace aucun fichier existant.
Le client rejoint automatiquement `127.0.0.1:25575`. Au premier accès,
choisir la couleur et le familier dans HELLO_WORLD puis entrer dans Sanctuary.
Depuis la console serveur : `op KokaLab` donne les commandes au client de test.
Le serveur écoute seulement sur loopback et utilise des identités hors ligne
pour ce laboratoire. Ce profil ne doit pas être exposé sur le réseau. La liaison
authentifiée d'un compte web exige toujours un vrai serveur en mode en ligne ;
elle n'est pas contournée par les outils du laboratoire.
Réglages de départ : serveur 256–768 Mio de heap, vue 4 chunks, simulation 3 ;
client 512–2048 Mio, vue 6, simulation 4, 30 FPS, fenêtre 1280×720. La mémoire
native, graphique et macOS s'ajoute au heap. Aucun engagement de tenir dans
une consommation totale de 2,75 Gio. Ne pas exécuter la compilation en même
temps qu'une séance. Augmenter seulement après mesure :
```sh
python3 scripts/duo_lab.py server --memory 1024
python3 scripts/duo_lab.py client --memory 2560
```
Le mode fichier reste le défaut. Pour une préparation neuve avec le site local :
```sh
python3 scripts/duo_lab.py prepare --storage database --server-id UUID_DU_SERVEUR \
--jdbc jdbc:mariadb://127.0.0.1:33077/BASE_DE_TEST
SANCTUARY_COMMUNITY_DB_PASSWORD='' python3 scripts/duo_lab.py server
```
La base doit déjà avoir le schéma communautaire v3. Le site doit utiliser le
même identifiant de serveur. Aucun schéma ni sauvegarde n'est migré ici.
## Personnages et séances
```text
/duo spawn Alice
/duo spawn Bob
/duo list
/duo remove Alice
/duo trace start
/duo trace stop
```
Les personnages portent le préfixe `Lab_`, sont créatifs et apparaissent près
de la source de commande. Limite de quatre, noms uniques de 1–12 caractères
ASCII alphanumériques ou `_`. Ce sont des ServerPlayer sans transport réseau
ni rendu, pas des IA et pas des clients réseau supplémentaires. On peut les
cibler avec les commandes natives, par exemple `tp Lab_Bob ~2 ~ ~`.
Ils ne valident pas seuls le protocole d'un deuxième client réel.
La trace consigne noms de test, dimension, positions et angles toutes les deux
secondes dans `build/duo/server/duo-sessions/`. Activation explicite, arrêt au
bout de cinq minutes maximum ou à la fermeture du serveur. Pas de frappe clavier,
mot de passe, navigateur ou audio enregistré.
Pour la relecture visuelle, identifier la fenêtre Minecraft puis lancer :
```sh
python3 scripts/duo_lab.py windows
python3 scripts/duo_lab.py record --window ID_FENETRE_MINECRAFT --seconds 120
```
Une séquence PNG horodatée toutes les deux secondes, un index HTML et une fiche
de notes sont écrits dans `build/duo/sessions/`. Ctrl-C termine la capture ; limite
de cinq minutes. macOS peut demander l'autorisation de capture. Cette version
ne produit pas une vidéo continue et peut manquer une interaction très courte.
On ne démarre une capture qu'au début d'une scène annoncée.
## Trois premières scènes
1. Ouvrir la Gazette, retrouver un auteur, lire un article et répondre. Vérifier
que l'autre interface retrouve la réponse, puis noter les hésitations.
2. Créer une demande avec lieu et matériaux, la suivre, lire son infobulle sur
la carte, ouvrir la discussion puis arrêter le suivi.
3. Afficher deux figurants, tester les interactions de proximité et comparer
la fluidité à un seul joueur. Garder un véritable second client pour une
vérification réseau ultérieure si nécessaire.
Le récap Discord se trouve dans `discord-beta130-160.md` ; les originaux des
quatre illustrations sont copiés avec provenance dans `build/discord-beta130-160/`.
## Vérifications
- `./gradlew check build assemblePack` : 252 GameTests, 229 réussites et les
mêmes 23 échecs que beta.159. Aucun échec ajouté ; comparaison dans
`build/duo160-server-failures.json`, log `build/beta160-check-build.log`.
- Contrôles restants, compilation, pack et client natif Vulkan réussis avec la
suite serveur déjà exécutée exclue (`-x :sanctuary:runGameTest`) : 137 tâches,
`build/beta160-release.log`. Le test `ShaderDefaults160ClientChecks` vérifie
préférence absente, objet vide, ON explicite, OFF enregistré et réactivation,
avec intensité personnelle conservée. Marqueur `SHADER160_DEFAULTS_PASS`.
- Module de test reconstruit après ajustement du transport sans réseau : build
réussi. L'export de lancement inclut les arguments fournis par Loom et élimine
son argfile imbriqué, que Java ne peut pas réinterpréter depuis un autre argfile.
- Serveur réel à 768 Mio : démarrage sur loopback, monde plat neuf ; création de
quatre acteurs, doublon et cinquième refusés, retrait et acteur absent vérifiés.
Le journal produit 56 observations JSON valides puis s'arrête sur commande.
- Client réel séparé, Vulkan, 2048 Mio, shader OFF : connexion jusqu'à l'écran
HELLO_WORLD vérifiée visuellement. La création du profil et le parcours en jeu
avec le joueur restent à faire ensemble ; aucune session ergonomique humaine
terminée ni validation d'un deuxième client réseau revendiquée.
- Mesure ponctuelle avant l'entrée du joueur : serveur ~313 Mio de heap utilisé,
client au menu ~289 Mio. Ce ne sont ni des pics ni une mesure de RAM système
totale. Les figurants ne possèdent ni sockets ni fenêtre graphique.
- Capture ciblée macOS essayée sur quatre secondes : séquence PNG, manifeste,
index HTML et fiche de notes créés. Aucun enregistrement continu ou micro.
- Export MRpack : intégrité ZIP, version et JAR embarqué vérifiés. Les 29 ressources
de shaders sont inchangées depuis beta.159. JAR et packs beta.154–159 conservés.
- Skill personnel `sanctuary-session-notes` installé et validé séparément dans
`~/.codex/skills/` pour classer les dictées en Markdown. Il ne change pas le
modèle du tour courant ; Luna/low peut être choisi dans une tâche dédiée.
Le serveur local utilise la base de développement du site, schéma v3 déjà présent,
sous le même scope. Aucune validation de liaison de comptes hors ligne : cette
opération reste réservée au mode authentifié. Aucun déploiement public, canal
packwiz, serveur personnel ou instance Prism modifié.
## Artefacts locaux
- `mods/sanctuary/build/libs/sanctuary-beta.160.jar` — SHA-256
`4c19e620e989050488c9a96aaddaf897a74115a9fb4c5099e5518ae32db5b2e8`.
- `build/Sanctuary-beta.160.mrpack` — SHA-256
`272e3460f35c8d9a4de689d30e4d952c3121923ba5fe30a23c83b3e76bd23bac`.
- `build/duo/Jouer.command` et `Serveur.command` : raccourcis locaux de séance.
+78
View File
@@ -0,0 +1,78 @@
# beta.161 — correctifs de la séance du 23 septembre
Ticket : R002–R009 du carnet de séance. Branches `codex/session-fixes-beta161`.
## Contrat de données et migration additive
Aucun monde ni chunk n’est régénéré, aucun format existant n’est modifié.
Le nouveau fichier `data/sanctuary-server-metrics.json` version 1 conserve le temps
réel cumulé depuis l’activation du compteur, les morts connues par UUID et les
UUID des figurants exclus. Au premier démarrage, les morts sont importées des
statistiques Minecraft déjà présentes ; le temps antérieur n’est pas inventé.
Les valeurs vivantes sont relevées côté serveur, sauvegardées toutes les 30 secondes
et à l’arrêt. Les arrêts ne comptent pas dans la durée. Un crash peut perdre au
plus la période depuis le dernier relevé enregistré. Un fichier corrompu ou
modifié extérieurement arrête la collecte sans le remplacer.
En mode base, appliquer la migration Web additive `create_sanctuary_server_metrics_table`
avant de lancer le mod. Elle crée une table indépendante, une ligne par server_id ;
le schéma communautaire v3 et ses données restent inchangés. Le serveur publie un
instantané toutes les 30 secondes et un état arrêté à l’arrêt propre. En cas de
panne SQL le compteur local continue ; le site marque la dernière mesure périmée
après 90 secondes. Une table absente ne bloque pas les publications communautaires.
La suppression de cette nouvelle table au rollback perd uniquement les instantanés,
recréés depuis le fichier local à la prochaine publication. Ne pas supprimer le fichier
local pour revenir en arrière ; les anciennes versions l’ignorent.
Un seul serveur actif par server_id, comme pour les publications. Les morts de tous
les joueurs ayant des statistiques sont cumulées, y compris les joueurs déconnectés.
Les figurants du laboratoire sont exclus des morts et des joueurs en ligne.
## Résultat livré
Liste des joueurs sur U (migration unique de Tab ; autres choix conservés), suivi
et place unique expliqués dans les demandes. Site : retour au dessin d’origine,
intendance limitée au titre, page officielle avec retour, pas de navbar de rubriques
ni de sélecteur de langue ni d’incitation à se connecter dans les publications.
Gazette en accordéon exclusif : le dernier article visible est ouvert au chargement,
ouvrir un autre referme le précédent. Photo entière à gauche, extrait court à droite,
visage/pseudo/date et lien de lecture alignés en bas. Calendrier jour/mois encadré,
message officiel à droite, sans heure ; année dans le footer.
Les pages publiques du site sont en lecture seule, y compris leurs anciennes
routes d’écriture pour les comptes connectés et le staff. L’administration
Intendance réservée au staff reste disponible. Les joueurs publient, répondent
et suivent les demandes dans Minecraft. Compteurs réels et état périmé explicite.
## Vérifications
| Vérification | Résultat |
| --- | --- |
| `./gradlew check build assemblePack` | 252 GameTests : 229 réussis, les mêmes 23 échecs que beta.160, aucun nouvel échec dans cette passe. Comparaison dans `build/session161-server-failures.json`. |
| Contrôles JVM et persistance fichier/SQL | Réussis, dont `SERVER_METRICS161_PASS` et `COMMUNITY154_SQL_PASS` dans `build/beta161-release.log`. |
| Démarrage et raccourci U | `SESSION161_KEYS_PASS` : défaut U, migration unique depuis Tab, choix personnalisé conservé. |
| Parcours natif communautaire | `SEARCH159_CLIENT_PASS mode=file` : photos/galerie, FR/EN, GUI 2/3/4, recherche, bulletin en lecture seule, suivi et infobulle du repère. Captures dans `mods/sanctuary/build/run/clientGameTest/screenshots/`. |
| Web SQLite et MariaDB isolée | 29 tests, 252 assertions réussies ; lecture seule visiteurs/joueurs/staff, contrats de persistance, statistiques absentes/périmées/arrêtées. Pint et `git diff --check` réussis. |
| Navigateur | Accordéon exclusif, lien vers l’article, calendrier sans heure, visage/auteur/date et lecture en bas ; vérification desktop et 390 × 844. |
| Assemblage final | `./gradlew build assemblePack :sanctuary-test:exportDuoLaunch -x :sanctuary:check` réussi, après les vérifications ci-dessus. Exclusion ponctuelle des tests connus en échec, pas de suppression d’assertion. |
| Laboratoire réel | Monde existant `duo-flat-160` relancé, serveur 768 MiB/client 2048 MiB, shaders désactivés. KokaLab non OP, 26 niveaux conservés. Deux figurants, compteur SQL et Web : 1 humain. Journal de durée persisté et exclusions vérifiées. |
Le premier démarrage de test a révélé une mauvaise déclaration du nouveau mixin :
`PlayerListKeyMixin` au lieu de `client.PlayerListKeyMixin`. Elle est corrigée ;
la classe et sa déclaration sont présentes dans le JAR final. Le test natif a
ensuite réussi. L’assemblage avait redéclenché une seconde passe de GameTests
serveur ; cette répétition a été interrompue, la première passe complète faisant
foi. Logs distincts : `beta161-check-build.log`, `beta161-release.log`,
`beta161-client.log`, `beta161-assembly.log`, sous `build/`.
Livraison locale uniquement : `mods/sanctuary/build/libs/sanctuary-beta.161.jar`
et pack assemblé dans `build/packwiz`. SHA-256 du JAR :
`c6e0424bf091c41827730bc260dad3b95b7c949fb0dcc41811f0ae3d94bce79c`.
Les 29 ressources shader sont identiques à beta.160. Les anciens JAR beta.154–160
sont conservés. Aucun canal public ni instance Prism personnelle n’a été modifié.
Le téléchargement public du site reste l’ancien lien beta.151, hors de cette
livraison locale. Les 23 échecs préexistants restent ouverts.
Le compteur de jours débute à l’activation de cette version : le fonctionnement
antérieur n’était pas mesuré. Le site reçoit les nouveaux compteurs au rechargement
de la page. La mesure d’une mort réelle supplémentaire n’a pas été provoquée sur
le personnage de la séance ; l’import et l’incrément sont couverts par le test du
journal et les tests de lecture Web.
+2 -2
View File
@@ -9,8 +9,8 @@ loom_version=1.17.20
fabric_api_version=0.160.5+26.3
# Release counter: beta.001, .002, .003, ... (see docs/versioning.md).
mod_version=beta.158
pack_version=beta.158
mod_version=beta.161
pack_version=beta.161
resource_pack_version=beta.121
maven_group=fr.koka.sanctuary
jei_version=30.32.0-sanctuary.3
+34
View File
@@ -16,5 +16,39 @@ processResources {
filesMatching('fabric.mod.json') { expand(values) }
}
loom { runs { client { runDir 'run/quick-test' } } }
loom {
runs {
duoServer {
server()
name 'Sanctuary duo lab'
runDir '../../build/duo/server'
vmArg '-Xms256m'
vmArg '-Xmx768m'
vmArg '-Dsanctuary.duo=true'
}
duoClient {
client()
name 'Sanctuary duo client'
runDir '../../build/duo/client'
vmArg '-Xms512m'
vmArg '-Xmx2G'
programArgs '--graphicsBackend', 'vulkan', '--username', 'KokaLab', '--width', '1280', '--height', '720'
}
}
}
// Export the Loom launcher so play sessions do not retain a Gradle JVM.
tasks.register('exportDuoLaunch') {
dependsOn tasks.named('runDuoServer').get().taskDependencies.getDependencies(tasks.named('runDuoServer').get())
dependsOn tasks.named('runDuoClient').get().taskDependencies.getDependencies(tasks.named('runDuoClient').get())
doLast {
['server': 'runDuoServer', 'client': 'runDuoClient'].each { kind, taskName ->
def launch = tasks.named(taskName).get()
def destination = rootProject.layout.buildDirectory.file("duo/${kind}.args").get().asFile
destination.parentFile.mkdirs()
def arguments = launch.allJvmArgs.findAll { !it.toString().startsWith('@') } + ['-classpath', launch.classpath.asPath, launch.mainClass.get()] + launch.args + launch.argumentProviders.collectMany { it.asArguments().toList() }
destination.text = arguments.collect { '"' + it.toString().replace('\\', '\\\\').replace('"', '\\"') + '"' }.join('\n') + '\n'
}
}
}
tasks.named('test') { failOnNoDiscoveredTests=false }
tasks.named('jar') { from(rootProject.file('LICENSE')) { rename { 'LICENSE_sanctuary_test' } } }
@@ -0,0 +1,136 @@
package fr.koka.sanctuarytest;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.arguments.StringArgumentType;
import fr.koka.sanctuary.operator.OperatorService;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ClientInformation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.CommonListenerCookie;
import net.minecraft.world.level.GameType;
/** Optional development module only. No sockets, renderer or additional JVM per actor. */
final class DuoLab {
private static final Map<String, ServerPlayer> ACTORS = new LinkedHashMap<>();
private static java.io.BufferedWriter trace;
private static int ticks;
private static long traceStarted;
private DuoLab() { }
static void register() {
// An explicit JVM opt-in keeps the ordinary quick-test pack unchanged.
if (!Boolean.getBoolean("sanctuary.duo")) return;
CommandRegistrationCallback.EVENT.register((dispatcher, registries, environment) ->
dispatcher.register(Commands.literal("duo").requires(OperatorService::canCommand)
.then(Commands.literal("trace")
.then(Commands.literal("start").executes(c -> trace(c.getSource(), true)))
.then(Commands.literal("stop").executes(c -> trace(c.getSource(), false))))
.then(Commands.literal("spawn").then(Commands.argument("name", StringArgumentType.word())
.executes(c -> spawn(c.getSource(), StringArgumentType.getString(c, "name")))))
.then(Commands.literal("remove").then(Commands.argument("name", StringArgumentType.word())
.executes(c -> remove(c.getSource(), StringArgumentType.getString(c, "name")))))
.then(Commands.literal("list").executes(c -> {
c.getSource().sendSuccess(() -> Component.translatable("sanctuary_test.duo.list", String.join(", ", ACTORS.keySet())), false);
return ACTORS.size();
}))));
ServerTickEvents.END_SERVER_TICK.register(server -> {
if (trace != null && System.nanoTime() - traceStarted >= 300_000_000_000L) closeTrace();
if (trace == null || ++ticks % 40 != 0) return;
try {
for (var player : server.getPlayerList().getPlayers()) {
var row = new com.google.gson.JsonObject();
row.addProperty("time", java.time.Instant.now().toString());
row.addProperty("player", player.getGameProfile().name());
row.addProperty("actor", ACTORS.containsValue(player));
row.addProperty("dimension", player.level().dimension().identifier().toString());
row.addProperty("x", player.getX()); row.addProperty("y", player.getY()); row.addProperty("z", player.getZ());
row.addProperty("yaw", player.getYRot()); row.addProperty("pitch", player.getXRot());
trace.write(row.toString()); trace.newLine();
}
trace.flush();
} catch (java.io.IOException error) {
org.slf4j.LoggerFactory.getLogger("sanctuary-duo").error("Trace stopped: cannot write session", error);
closeTrace();
}
});
ServerLifecycleEvents.SERVER_STOPPED.register(server -> { ACTORS.clear(); closeTrace(); });
}
private static int trace(CommandSourceStack source, boolean start) {
closeTrace();
if (start) try {
var folder = java.nio.file.Path.of("duo-sessions");
java.nio.file.Files.createDirectories(folder);
var path = folder.resolve("positions-" + System.currentTimeMillis() + ".jsonl");
trace = java.nio.file.Files.newBufferedWriter(path, StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.CREATE_NEW);
traceStarted = System.nanoTime(); ticks = 0;
} catch (java.io.IOException error) {
source.sendFailure(Component.translatable("sanctuary_test.duo.trace_failed")); return 0;
}
source.sendSuccess(() -> Component.translatable("sanctuary_test.duo.trace_" + (start ? "started" : "stopped")), false);
return 1;
}
private static void closeTrace() {
if (trace != null) try { trace.close(); } catch (java.io.IOException ignored) { }
trace = null;
}
private static int spawn(CommandSourceStack source, String name) {
if (!name.matches("[A-Za-z0-9_]{1,12}") || ACTORS.size() >= 4
|| source.getServer().getPlayerList().getPlayerByName("Lab_" + name) != null) {
source.sendFailure(Component.translatable("sanctuary_test.duo.invalid"));
return 0;
}
String fullName = "Lab_" + name;
var profile = new GameProfile(UUID.nameUUIDFromBytes(("SanctuaryDuo:" + fullName).getBytes(StandardCharsets.UTF_8)), fullName);
var player = new ServerPlayer(source.getServer(), source.getLevel(), profile, ClientInformation.createDefault());
source.getServer().getPlayerList().placeNewPlayer(new SinkConnection(), player, CommonListenerCookie.createInitial(profile, false));
var position = source.getPosition();
player.teleportTo(source.getLevel(), position.x + 2, position.y, position.z, java.util.Set.of(), 0, 0, false);
player.setGameMode(GameType.CREATIVE);
ACTORS.put(name, player);
source.sendSuccess(() -> Component.translatable("sanctuary_test.duo.spawned", fullName), false);
return 1;
}
private static int remove(CommandSourceStack source, String name) {
var player = ACTORS.remove(name);
if (player == null) {
source.sendFailure(Component.translatable("sanctuary_test.duo.missing", name));
return 0;
}
source.getServer().getPlayerList().remove(player);
source.sendSuccess(() -> Component.translatable("sanctuary_test.duo.removed", name), false);
return 1;
}
private static final class SinkConnection extends Connection {
private net.minecraft.network.PacketListener listener;
SinkConnection() { super(PacketFlow.SERVERBOUND); }
@Override public <T extends net.minecraft.network.PacketListener> void setupInboundProtocol(net.minecraft.network.ProtocolInfo<T> protocol, T listener) { this.listener = listener; }
@Override public net.minecraft.network.PacketListener getPacketListener() { return listener; }
@Override public void flushChannel() { }
@Override public void send(Packet<?> packet) { }
@Override public void send(Packet<?> packet, io.netty.channel.ChannelFutureListener listener) { }
@Override public void send(Packet<?> packet, io.netty.channel.ChannelFutureListener listener, boolean flush) { }
@Override public boolean isConnected() { return true; }
@Override public boolean isConnecting() { return false; }
@Override public boolean isMemoryConnection() { return true; }
@Override public SocketAddress getRemoteAddress() { return new InetSocketAddress("127.0.0.1", 0); }
}
}
@@ -16,6 +16,7 @@ public final class QuickTestMod implements ModInitializer {
}
public void onInitialize(){
QuickTestWorld.enable();
DuoLab.register();
PayloadTypeRegistry.clientboundConfiguration().register(Mode.TYPE,Mode.CODEC);
ServerConfigurationConnectionEvents.CONFIGURE.register((handler,server)->{
if(ServerConfigurationNetworking.canSend(handler,Mode.TYPE))
@@ -1,3 +1,11 @@
{
"generator.sanctuary_test.flat": "Sanctuary — Quick Test"
"generator.sanctuary_test.flat": "Sanctuary — Quick Test",
"sanctuary_test.duo.list": "Lab actors: %s",
"sanctuary_test.duo.invalid": "Name: 1–12 letters/digits/_; up to 4 actors, unique names.",
"sanctuary_test.duo.spawned": "%s spawned nearby (test actor).",
"sanctuary_test.duo.missing": "Lab actor not found: %s",
"sanctuary_test.duo.removed": "Lab actor removed: %s",
"sanctuary_test.duo.trace_failed": "Cannot write session log.",
"sanctuary_test.duo.trace_started": "Position log started (one sample every 2 seconds).",
"sanctuary_test.duo.trace_stopped": "Position log stopped."
}
@@ -1,3 +1,11 @@
{
"generator.sanctuary_test.flat": "Sanctuary — Test rapide"
"generator.sanctuary_test.flat": "Sanctuary — Test rapide",
"sanctuary_test.duo.list": "Personnages labo : %s",
"sanctuary_test.duo.invalid": "Nom : 1–12 lettres/chiffres/_ ; 4 personnages maximum, noms uniques.",
"sanctuary_test.duo.spawned": "%s créé à proximité (personnage de test).",
"sanctuary_test.duo.missing": "Personnage labo introuvable : %s",
"sanctuary_test.duo.removed": "Personnage labo retiré : %s",
"sanctuary_test.duo.trace_failed": "Impossible d’écrire le journal de séance.",
"sanctuary_test.duo.trace_started": "Journal des positions démarré (une mesure toutes les 2 secondes).",
"sanctuary_test.duo.trace_stopped": "Journal des positions arrêté."
}
+14
View File
@@ -128,6 +128,12 @@ tasks.named('processGametestResources') {
def sunshaft137Client = providers.gradleProperty('sanctuarySunshaft137ClientTests').map { it.toBoolean() }.getOrElse(false)
inputs.property('sanctuarySunshaft137ClientTests', sunshaft137Client)
if (sunshaft137Client) filter { line -> line.replace('fr.koka.sanctuary.gametest.SanctuaryClientRenderTests', 'fr.koka.sanctuary.client.shader.Sunshafts137ClientChecks') }
def defaults160 = providers.gradleProperty('sanctuaryDefaults160ClientTests').map { it.toBoolean() }.getOrElse(false)
inputs.property('defaults160', defaults160)
if (defaults160) filter { line -> line.replace('fr.koka.sanctuary.gametest.SanctuaryClientRenderTests', 'fr.koka.sanctuary.client.shader.ShaderDefaults160ClientChecks') }
def session161 = providers.gradleProperty('sanctuarySession161ClientTests').map { it.toBoolean() }.getOrElse(false)
inputs.property('sanctuarySession161ClientTests', session161)
if (session161) filter { line -> line.replace('fr.koka.sanctuary.gametest.SanctuaryClientRenderTests', 'fr.koka.sanctuary.client.Session161ClientChecks') }
def bloom130Client = providers.gradleProperty('sanctuaryBloom130ClientTests').map { it.toBoolean() }.getOrElse(false)
inputs.property('sanctuaryBloom130ClientTests', bloom130Client)
if (bloom130Client) filter { line -> line.replace('fr.koka.sanctuary.gametest.SanctuaryClientRenderTests', 'fr.koka.sanctuary.client.shader.Bloom130ClientChecks') }
@@ -1241,3 +1247,11 @@ tasks.register('community154Interop', JavaExec) {
mainClass = 'fr.koka.sanctuary.community.CommunityInterop'
args(providers.gradleProperty('communityInteropPhase').getOrElse('seed'))
}
tasks.register('serverMetrics161Smoke', JavaExec) {
group = 'verification'
dependsOn('testClasses')
classpath = sourceSets.test.runtimeClasspath
mainClass = 'fr.koka.sanctuary.community.ServerMetricsSmoke'
}
tasks.named('check') { dependsOn('serverMetrics161Smoke') }
@@ -43,17 +43,26 @@ public final class Community158ClientChecks implements FabricClientGameTest {
var config=CommunityConfig.load(net.fabricmc.loader.api.FabricLoader.getInstance().getConfigDir().resolve("sanctuary-community.json"));
CommunityStore store=database?new SqlCommunityStore(config.jdbcUrl(),config.user(),"",config.serverId()):new FileCommunityStore(server.getWorldPath(net.minecraft.world.level.storage.LevelResource.ROOT).resolve("data/sanctuary-community.json"),config.serverId());
var author=new Community.Actor(UUID.randomUUID().toString(),"Voisin",true);
store.change(author,new Community.Change("create",UUID.randomUUID().toString(),"","bulletin","info","Annonce officielle159","Le serveur vous souhaite la bienvenue.",0));
for(int i=0;i<13;i++) {
store.change(author,new Community.Change("create",UUID.randomUUID().toString(),"","article","info","Gazette "+i,"Le village raconte. ".repeat(90),0,testPhoto()));
store.change(author,new Community.Change("create",i==0?noticeId:UUID.randomUUID().toString(),"","notice",List.of("info","event","work","need").get(i%4),"Demande "+i,"Rendez-vous au village. ".repeat(40),0,null,CommunityTask.EMPTY));
store.change(author,new Community.Change("create",UUID.randomUUID().toString(),"","article","info","Gazette "+i,"Le village raconte. ".repeat(90)+(i==0?" Unique159":""),0,testPhoto()));
store.change(author,new Community.Change("create",i==0?noticeId:UUID.randomUUID().toString(),"","notice",List.of("info","event","work","need").get(i%4),"Demande "+i,"Rendez-vous au village. ".repeat(40),0,null,i==0?new CommunityTask(new CommunityTask.Location("minecraft:overworld",0,64,0),List.of(new CommunityTask.Material("minecraft:oak_log",128)),"shared","custom",List.of(),"Un repas au village"):CommunityTask.EMPTY));
}
}catch(Exception error){throw new AssertionError(error);}});
try(var world=c.worldBuilder().adjustSettings(s->{s.setName("Cards158 "+UUID.randomUUID());s.setSeed("157");s.setAllowCommands(false);s.setGameMode(WorldCreationUiState.SelectedGameMode.SURVIVAL);s.setWorldType(s.getNormalPresetList().stream().filter(e->e.preset()!=null&&e.preset().getRegisteredName().equals("sanctuary_test:flat")).findFirst().orElseThrow());}).create()) {
c.waitFor(m->ProgressionClient.active()&&m.player!=null&&m.gui.screen()==null&&!IntroSpawnFlash.active(),1200);
world.getServer().runOnServer(s->s.getPlayerList().getPlayers().getFirst().getAbilities().invulnerable=true);
for(String locale:List.of("fr_fr","en_us"))for(int scale:List.of(2,3,4)) {
world.getServer().runOnServer(s->{
var player=s.getPlayerList().getPlayers().getFirst();player.getAbilities().invulnerable=true;player.setExperienceLevels(20);
check(fr.koka.sanctuary.progression.ProgressionService.purchase(player,"atlas",fr.koka.sanctuary.progression.ProgressEffects.get(player).revision()),"Atlas unlocked through progression");
fr.koka.sanctuary.progression.ProgressionService.send(player,"");
for(int z=-2;z<=2;z++)for(int x=-2;x<=2;x++) {
var tile=fr.koka.sanctuary.atlas.AtlasSampler.sample(player.level(),player.chunkPosition().x()+x,player.chunkPosition().z()+z);
if(tile!=null)fr.koka.sanctuary.atlas.AtlasService.observations(player).observe(tile);
}
});
for(String locale:List.of("fr_fr","en_us"))for(int scale:List.of(2,3,4))for(int windowWidth:List.of(1280,1920)) {
c.runOnClient(m->{
m.getWindow().setWindowed(1280,960);m.options.guiScale().set(scale);m.resizeGui();m.getLanguageManager().setSelected(locale);m.getLanguageManager().onResourceManagerReload(m.getResourceManager());
m.getWindow().setWindowed(windowWidth,windowWidth==1280?960:1080);m.options.guiScale().set(scale);m.resizeGui();m.getLanguageManager().setSelected(locale);m.getLanguageManager().onResourceManagerReload(m.getResourceManager());
CommunityClient.open(new PauseScreen(true),"article","",true);
check(!button(m.gui.screen(),"publish").active,"Photo is mandatory in the composer");
edit(m.gui.screen()).setValue("Une journée au village");body(m.gui.screen()).setValue("La photo rejoint la Gazette.");
@@ -63,23 +72,29 @@ public final class Community158ClientChecks implements FabricClientGameTest {
c.runOnClient(m->{
var s=m.gui.screen();check(s instanceof CommunityScreenshotsScreen,"Dedicated screenshot view");
var a=widgets(s).filter(AbstractScrollArea.class::isInstance).map(AbstractScrollArea.class::cast).findFirst().orElseThrow();
check(a.maxScrollAmount()>0,"Gallery scrolls");s.mouseScrolled(a.getX()+5,a.getY()+5,0,-4);check(a.scrollAmount()>0,"Wheel moves screenshots");a.setScrollAmount(0);
if(a.maxScrollAmount()>0){s.mouseScrolled(a.getX()+5,a.getY()+5,0,-4);check(a.scrollAmount()>0,"Wheel moves screenshots");a.setScrollAmount(0);}
var photos=widgets(s).filter(CommunityPhotoWidget.class::isInstance).map(CommunityPhotoWidget.class::cast).toList();
check(photos.stream().mapToInt(AbstractWidget::getRight).max().orElseThrow()>s.width*0.8,"Gallery uses GUI width");
for(var child:s.children())if(child instanceof AbstractWidget w)check(w.getX()>=0&&w.getRight()<=s.width&&w.getY()>=0&&w.getBottom()<=s.height,"Gallery bounds "+w.getMessage());
});
c.takeScreenshot("cards158-gallery-"+locale+"-"+scale+(database?"-database":"-file"));
c.takeScreenshot("search159-gallery-"+locale+"-"+scale+"-"+windowWidth+(database?"-database":"-file"));
c.runOnClient(m->widgets(m.gui.screen()).filter(CommunityPhotoWidget.class::isInstance).map(CommunityPhotoWidget.class::cast).findFirst().orElseThrow().onPress(enter()));
c.runOnClient(m->{var s=m.gui.screen();var image=widgets(s).filter(CommunityPhotoWidget.class::isInstance).map(CommunityPhotoWidget.class::cast).findFirst().orElseThrow();check(image.getWidth()>s.width*0.8&&image.getHeight()>s.height*0.5,"Preview fills available GUI");check(button(s,"photo_assign").getBottom()<s.height-30,"Preview controls remain visible");});
c.takeScreenshot("search159-preview-"+locale+"-"+scale+"-"+windowWidth);
c.runOnClient(m->press(m.gui.screen(),"sanctuary.community.screenshots_back"));
c.runOnClient(m->m.gui.screen().onClose());
c.runOnClient(m->{check(edit(m.gui.screen()).getValue().equals("Une journée au village"),"Cancel retains text");check(!button(m.gui.screen(),"publish").active,"Cancel leaves photo unassigned");});
}
c.runOnClient(m->{m.options.guiScale().set(2);m.resizeGui();m.getLanguageManager().setSelected("fr_fr");m.getLanguageManager().onResourceManagerReload(m.getResourceManager());press(m.gui.screen(),"sanctuary.community.photo_choose");});
c.runOnClient(m->{m.getWindow().setWindowed(1280,960);m.options.guiScale().set(2);m.resizeGui();m.getLanguageManager().setSelected("fr_fr");m.getLanguageManager().onResourceManagerReload(m.getResourceManager());press(m.gui.screen(),"sanctuary.community.photo_choose");});
c.waitFor(m->widgets(m.gui.screen()).anyMatch(CommunityPhotoWidget.class::isInstance),500);
c.runOnClient(m->press(m.gui.screen(),"sanctuary.community.next"));
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityPhotoWidget.class::isInstance).count()>0&&!button(m.gui.screen(),"next").active,500);
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityPhotoWidget.class::isInstance).count()>0&&button(m.gui.screen(),"previous").active,500);
c.runOnClient(m->widgets(m.gui.screen()).filter(CommunityPhotoWidget.class::isInstance).map(CommunityPhotoWidget.class::cast).findFirst().orElseThrow().onPress(enter()));
c.takeScreenshot("cards158-preview");
c.runOnClient(m->press(m.gui.screen(),"sanctuary.community.photo_assign"));
c.runOnClient(m->{check(button(m.gui.screen(),"publish").active,"Photo enables publishing");check(edit(m.gui.screen()).getValue().equals("Une journée au village"),"Selection retains draft");press(m.gui.screen(),"sanctuary.community.publish");});
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.reply")&&!CommunityClient.pending(),600);
c.runOnClient(m->{var article=widgets(m.gui.screen()).filter(CommunityArticle.class::isInstance).map(CommunityArticle.class::cast).findFirst().orElseThrow();var face=widgets(m.gui.screen()).filter(PlayerFaceWidget.class::isInstance).map(PlayerFaceWidget.class::cast).findFirst().orElseThrow();check(face.getY()>=article.getBottom(),"Author metadata below the article");check(button(m.gui.screen(),"actions").getY()==face.getY(),"Author metadata next to ellipsis");});
c.runOnClient(m->{var article=widgets(m.gui.screen()).filter(CommunityArticle.class::isInstance).map(CommunityArticle.class::cast).findFirst().orElseThrow();var face=widgets(m.gui.screen()).filter(PlayerFaceWidget.class::isInstance).map(PlayerFaceWidget.class::cast).findFirst().orElseThrow();check(face.getY()>=article.getBottom(),"Author metadata below the article");check(button(m.gui.screen(),"actions").getY()==face.getY(),"Author metadata next to ellipsis");check(widgets(m.gui.screen()).anyMatch(w->w instanceof AbstractWidget widget && widget.getMessage().getString().contains("/"+java.time.Year.now()+" ")),"Article date includes year");});
c.takeScreenshot("cards158-article"+(database?"-database":"-file"));
world.getServer().runOnServer(s->{try {
var config=CommunityConfig.load(net.fabricmc.loader.api.FabricLoader.getInstance().getConfigDir().resolve("sanctuary-community.json"));
@@ -92,7 +107,7 @@ public final class Community158ClientChecks implements FabricClientGameTest {
c.runOnClient(m->{var screen=m.gui.screen();var cards=widgets(screen).filter(CommunityCard.class::isInstance).map(CommunityCard.class::cast).toList();
check(cards.get(0).getY()==cards.get(1).getY()&&cards.get(0).getRight()<cards.get(1).getX(),"Two-column grid");
check(cards.get(2).getY()>cards.get(0).getY(),"Rows continue vertically");
check(!has(screen,"sanctuary.community.link")&&!has(screen,"sanctuary.community.bulletin"),"Public navigation excludes linking and bulletin");
check(!has(screen,"sanctuary.community.link")&&has(screen,"sanctuary.community.server_tab"),"Public navigation restores read-only server history");
check(widgets(screen).filter(AbstractScrollArea.class::isInstance).map(AbstractScrollArea.class::cast).anyMatch(a->a.maxScrollAmount()>0),"Grid scrolls");
});
c.takeScreenshot("cards158-grid-"+kind+"-"+locale+"-"+scale+(database?"-database":"-file"));
@@ -100,6 +115,24 @@ public final class Community158ClientChecks implements FabricClientGameTest {
c.runOnClient(m->{var a=widgets(m.gui.screen()).filter(AbstractScrollArea.class::isInstance).map(AbstractScrollArea.class::cast).findFirst().orElseThrow();a.setScrollAmount(a.maxScrollAmount());press(m.gui.screen(),"sanctuary.community.more");});
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).count()==13&&!CommunityClient.pending(),300);
c.runOnClient(m->check(widgets(m.gui.screen()).filter(AbstractScrollArea.class::isInstance).map(AbstractScrollArea.class::cast).anyMatch(a->a.scrollAmount()>0),"Appending cards retains scroll"));
c.runOnClient(m->{CommunityClient.open(new PauseScreen(true),"article","",false);edit(m.gui.screen()).setValue("unique159");});
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).count()==1&&!CommunityClient.pending(),300);
c.runOnClient(m->{check(text(m.gui.screen(),"Gazette 0"),"Search finds body beyond first page");edit(m.gui.screen()).setValue("VoISin");});
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).count()==10&&!CommunityClient.pending(),300);
c.runOnClient(m->press(m.gui.screen(),"sanctuary.community.more"));
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).count()==13&&!CommunityClient.pending(),300);
c.runOnClient(m->{edit(m.gui.screen()).setValue("absent159");m.gui.screen().setFocused(edit(m.gui.screen()));for(int tick=0;tick<12;tick++)m.gui.screen().tick();check(CommunityClient.pending(),"Old search is in flight");edit(m.gui.screen()).setValue("Gazette 12");});
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).count()==1&&!CommunityClient.pending(),300);
c.runOnClient(m->{check(text(m.gui.screen(),"Gazette 12"),"Latest search wins over prior pending request");check(edit(m.gui.screen()).isFocused(),"Search retains keyboard focus");});
c.takeScreenshot("search159-filtered");
c.runOnClient(m->edit(m.gui.screen()).setValue(""));
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).count()==10&&!CommunityClient.pending(),300);
c.runOnClient(m->press(m.gui.screen(),"sanctuary.community.server_tab"));
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).count()==1&&!CommunityClient.pending(),300);
c.runOnClient(m->{check(!has(m.gui.screen(),"sanctuary.community.publish"),"Public server listing is read only");widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).map(CommunityCard.class::cast).findFirst().orElseThrow().onPress(enter());});
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.back")&&!CommunityClient.pending(),300);
c.runOnClient(m->{check(!has(m.gui.screen(),"sanctuary.community.actions")&&!has(m.gui.screen(),"sanctuary.community.reply"),"Public bulletin has no write actions");check(text(m.gui.screen(),"Annonce officielle159"),"Server bulletin readable by ordinary player");});
c.takeScreenshot("search159-server-readonly");
world.getServer().runOnServer(server->{var inventory=server.getPlayerList().getPlayers().getFirst().getInventory();inventory.setItem(6,new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.OAK_LOG,17));inventory.setItem(7,new net.minecraft.world.item.ItemStack(net.minecraft.world.item.Items.DIAMOND,3));});
c.runOnClient(m->{m.options.guiScale().set(2);m.resizeGui();CommunityClient.open(new PauseScreen(true),"notice","",true);edit(m.gui.screen()).setValue("Le coffre descriptif");body(m.gui.screen()).setValue("Du bois pour le pont");press(m.gui.screen(),"sanctuary.community.task_configure");press(m.gui.screen(),"sanctuary.community.location_current");press(m.gui.screen(),"sanctuary.community.materials");edit(m.gui.screen()).setValue("minecraft:oak_log");});
c.waitTicks(3);
@@ -115,6 +148,33 @@ public final class Community158ClientChecks implements FabricClientGameTest {
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.unfollow")&&!CommunityClient.pending(),300);
c.runOnClient(m->check(NotificationClient.tracked().stream().anyMatch(t->t.title().getString().equals("Demande 0")),"Server-backed quest appears in HUD"));
c.runOnClient(m->m.gui.setScreen(null));c.waitTicks(5);c.takeScreenshot("cards158-follow-hud");
c.runOnClient(m->{CommunityClient.open(new PauseScreen(true),"notice",noticeId,false);});
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.map_show")&&!CommunityClient.pending(),300);
c.runOnClient(m->press(m.gui.screen(),"sanctuary.community.map_show"));
c.waitFor(m->m.gui.screen() instanceof SanctuaryAtlasScreen a&&!a.questPins().isEmpty(),200);
c.runOnClient(m->{var a=(SanctuaryAtlasScreen)m.gui.screen();var pin=a.questPins().getFirst();check(pin.marker().id().equals(noticeId),"Followed location appears on atlas");check(CommunityMapMarkers.project("minecraft:the_nether",x->100,z->100,0,0,300,300).isEmpty(),"Other dimension has no pin");
var tooltip=new StringBuilder();for(var line:CommunityMapMarkers.tooltip(pin.marker())){line.accept((index,style,point)->{tooltip.appendCodePoint(point);return true;});tooltip.append(' ');}
check(tooltip.toString().contains("Voisin")&&tooltip.toString().contains("128")&&tooltip.toString().contains("Un repas")&&tooltip.toString().contains("Rendez-vous"),"Hover includes author, summary, materials and reward");
hover(m,pin.x(),pin.y());
});
c.waitTicks(3);c.takeScreenshot("search159-map-hover"+(database?"-database":"-file"));
for(int scale:List.of(3,4)) {
c.runOnClient(m->{m.options.guiScale().set(scale);m.resizeGui();var pin=((SanctuaryAtlasScreen)m.gui.screen()).questPins().getFirst();hover(m,pin.x(),pin.y());});
c.waitTicks(3);c.takeScreenshot("search159-map-hover-gui"+scale);
}
c.runOnClient(m->{m.options.guiScale().set(2);m.resizeGui();});
c.runOnClient(m->{var a=(SanctuaryAtlasScreen)m.gui.screen();var pin=a.questPins().getFirst();check(a.mouseClicked(new net.minecraft.client.input.MouseButtonEvent(pin.x(),pin.y(),new net.minecraft.client.input.MouseButtonInfo(com.mojang.blaze3d.platform.InputConstants.MOUSE_BUTTON_LEFT,0)),false),"Quest marker click handled");});
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.unfollow")&&!CommunityClient.pending(),300);
world.getServer().runOnServer(server->server.getPlayerList().getPlayers().getFirst().teleportTo(20.5,65,20.5));
c.waitTicks(5);c.runOnClient(m->m.gui.setScreen(new PauseScreen(true)));c.waitTicks(20);
c.runOnClient(m->{var map=((PauseAtlasAccess)m.gui.screen()).sanctuary$pauseMap();var pin=map.questPins().getFirst();check(pin.marker().id().equals(noticeId),"Pause map includes followed location");hover(m,pin.x(),pin.y());});
c.waitTicks(3);c.takeScreenshot("search159-pause-map-hover"+(database?"-database":"-file"));
c.runOnClient(m->{var map=((PauseAtlasAccess)m.gui.screen()).sanctuary$pauseMap();var pin=map.questPins().getFirst();map.mouseClicked(new net.minecraft.client.input.MouseButtonEvent(pin.x(),pin.y(),new net.minecraft.client.input.MouseButtonInfo(com.mojang.blaze3d.platform.InputConstants.MOUSE_BUTTON_LEFT,0)),false);});
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.unfollow")&&!CommunityClient.pending(),300);c.waitTicks(25);
c.runOnClient(m->press(m.gui.screen(),"sanctuary.community.unfollow"));
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.follow")&&!CommunityClient.pending(),300);
c.runOnClient(m->check(CommunityMapMarkers.project("minecraft:overworld",x->100,z->100,0,0,300,300).isEmpty(),"Unfollowing removes the map marker immediately"));
c.runOnClient(m->m.gui.setScreen(null));
c.runOnClient(m->m.getConnection().sendCommand("sanctuary community admin"));c.waitTicks(5);
c.runOnClient(m->check(m.gui.screen()==null,"Non-operator cannot open administration"));
@@ -124,9 +184,29 @@ public final class Community158ClientChecks implements FabricClientGameTest {
c.waitFor(m->m.gui.screen() instanceof CommunityScreen&&has(m.gui.screen(),"sanctuary.community.publish")&&!CommunityClient.pending(),200);
c.runOnClient(m->{press(m.gui.screen(),"sanctuary.community.publish");edit(m.gui.screen()).setValue("Message officiel");body(m.gui.screen()).setValue("Bienvenue !");press(m.gui.screen(),"sanctuary.community.publish");});
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.back")&&!CommunityClient.pending(),250);
c.runOnClient(m->{check(!has(m.gui.screen(),"sanctuary.community.follow")&&!has(m.gui.screen(),"sanctuary.community.reply"),"Administrative bulletin has no quest or replies");m.gui.setScreen(null);});
System.out.println("CARDS158_CLIENT_PASS mode="+(database?"database":"file"));
c.runOnClient(m->{check(!has(m.gui.screen(),"sanctuary.community.follow")&&!has(m.gui.screen(),"sanctuary.community.reply"),"Administrative bulletin has no quest or replies");CommunityClient.open(null,"bulletin","",false);});
c.waitFor(m->widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).count()==2&&!CommunityClient.pending(),250);
c.runOnClient(m->{check(!has(m.gui.screen(),"sanctuary.community.publish"),"Public bulletin remains read only for operators");widgets(m.gui.screen()).filter(CommunityCard.class::isInstance).map(CommunityCard.class::cast).findFirst().orElseThrow().onPress(enter());});
c.waitFor(m->has(m.gui.screen(),"sanctuary.community.back")&&!CommunityClient.pending(),250);
c.runOnClient(m->{check(!has(m.gui.screen(),"sanctuary.community.actions"),"Operator uses administration to edit official messages");m.gui.setScreen(new PauseScreen(true));});
c.waitFor(m->CommunityClient.overview.has("bulletins")&&!CommunityClient.pending(),200);
for(String locale:List.of("fr_fr","en_us"))for(int scale:List.of(2,3,4)) {
c.runOnClient(m->{m.options.guiScale().set(scale);m.resizeGui();m.getLanguageManager().setSelected(locale);m.getLanguageManager().onResourceManagerReload(m.getResourceManager());m.gui.setScreen(new PauseScreen(true));});
c.waitTicks(20);
c.runOnClient(m->{
var date=widgets(m.gui.screen()).filter(StringWidget.class::isInstance).map(StringWidget.class::cast).filter(w->w.getMessage().getString().endsWith(java.time.Year.now().toString())).findFirst().orElseThrow();
var official=widgets(m.gui.screen()).filter(PauseTextButton.class::isInstance).map(PauseTextButton.class::cast).filter(w->w.getMessage().getString().contains("Message officiel")).findFirst().orElseThrow();
check(date.getRight()<official.getX(),"Full date and server message do not overlap");
});
c.takeScreenshot("search159-pause-year-"+locale+"-"+scale);
}
c.runOnClient(m->m.gui.setScreen(null));
System.out.println("SEARCH159_CLIENT_PASS mode="+(database?"database":"file"));
} finally {intro.set(false);}
}
private static void hover(net.minecraft.client.Minecraft m,double x,double y) {
var w=m.getWindow();double sx=(double)w.getScreenWidth()/w.getGuiScaledWidth(),sy=(double)w.getScreenHeight()/w.getGuiScaledHeight();
m.mouseHandler.onMove(w.handle(),x*sx,y*sy,(x-m.mouseHandler.getScaledXPos(w))*sx,(y-m.mouseHandler.getScaledYPos(w))*sy);m.mouseHandler.handleAccumulatedMovement();
}
private static AbstractButton button(Screen screen,String key) {return widgets(screen).filter(AbstractButton.class::isInstance).map(AbstractButton.class::cast).filter(b->b.getMessage().getContents() instanceof net.minecraft.network.chat.contents.TranslatableContents t&&t.getKey().equals("sanctuary.community."+key)).findFirst().orElseThrow();}
}
@@ -0,0 +1,39 @@
package fr.koka.sanctuary.client;
import com.mojang.blaze3d.platform.InputConstants;
import java.nio.file.*;
import net.fabricmc.fabric.api.client.gametest.v1.FabricClientGameTest;
import net.fabricmc.fabric.api.client.gametest.v1.context.ClientGameTestContext;
import net.fabricmc.loader.api.FabricLoader;
public final class Session161ClientChecks implements FabricClientGameTest {
public void runTest(ClientGameTestContext c) {
c.runOnClient(m->{
var marker=FabricLoader.getInstance().getConfigDir().resolve("sanctuary-player-list-key-v1.txt");
var saved=m.options.keyPlayerList.saveString();
try {
byte[] previous=Files.exists(marker)?Files.readAllBytes(marker):null;
try {
check(m.options.keyPlayerList.getDefaultKey().getValue()==InputConstants.KEY_U,"U is reset-to-default player list key");
Files.deleteIfExists(marker);
m.options.keyPlayerList.setKey(InputConstants.Type.KEYBOARD.getOrCreate(InputConstants.KEY_TAB));
HotbarClient.migratePlayerListKey(m);
check(m.options.keyPlayerList.matches(InputConstants.Type.KEYBOARD.getOrCreate(InputConstants.KEY_U)),"Saved Tab migrates to U");
Files.delete(marker);
m.options.keyPlayerList.setKey(InputConstants.Type.KEYBOARD.getOrCreate(InputConstants.KEY_F8));
HotbarClient.migratePlayerListKey(m);
check(m.options.keyPlayerList.matches(InputConstants.Type.KEYBOARD.getOrCreate(InputConstants.KEY_F8)),"Custom binding retained");
m.options.keyPlayerList.setKey(InputConstants.Type.KEYBOARD.getOrCreate(InputConstants.KEY_TAB));
HotbarClient.migratePlayerListKey(m);
check(m.options.keyPlayerList.matches(InputConstants.Type.KEYBOARD.getOrCreate(InputConstants.KEY_TAB)),"Migration happens once");
System.out.println("SESSION161_KEYS_PASS");
} finally {
if(previous==null)Files.deleteIfExists(marker);else Files.write(marker,previous);
m.options.keyPlayerList.setKey(InputConstants.getKey(saved));net.minecraft.client.KeyMapping.resetMapping();m.options.save();
}
}catch(Exception error){throw new AssertionError(error);}
});
new Community158ClientChecks().runTest(c);
}
private static void check(boolean value,String message){if(!value)throw new AssertionError(message);}
}
@@ -0,0 +1,40 @@
package fr.koka.sanctuary.client.shader;
import java.nio.file.Files;
import net.fabricmc.fabric.api.client.gametest.v1.FabricClientGameTest;
import net.fabricmc.fabric.api.client.gametest.v1.context.ClientGameTestContext;
import net.fabricmc.loader.api.FabricLoader;
/** Exercise the real preference loader in the isolated native client. */
public final class ShaderDefaults160ClientChecks implements FabricClientGameTest {
public void runTest(ClientGameTestContext context) {
context.runOnClient(client -> {
var path = FabricLoader.getInstance().getConfigDir().resolve("sanctuary-shaders.json");
try {
byte[] previous = Files.exists(path) ? Files.readAllBytes(path) : null;
var cache = VanillaLight.class.getDeclaredField("preferences");
cache.setAccessible(true);
try {
Files.deleteIfExists(path);
cache.set(null, null);
check(!VanillaLight.enabled(), "Fresh install disables shaders");
Files.createDirectories(path.getParent());
Files.writeString(path, "{}"); cache.set(null, null);
check(!VanillaLight.enabled(), "Missing setting uses OFF");
Files.writeString(path, "{\"enabled\":true,\"pbrIntensity\":73}"); cache.set(null, null);
check(VanillaLight.enabled() && VanillaLight.pbrIntensity() == 73, "Explicit ON and tuning retained");
VanillaLight.setEnabled(false); cache.set(null, null);
check(!VanillaLight.enabled() && VanillaLight.pbrIntensity() == 73, "OFF persists without losing tuning");
VanillaLight.setEnabled(true); cache.set(null, null);
check(VanillaLight.enabled(), "Manual reactivation persists");
System.out.println("SHADER160_DEFAULTS_PASS");
} finally {
if (previous == null) Files.deleteIfExists(path); else Files.write(path, previous);
cache.set(null, null);
}
} catch (Exception error) { throw new AssertionError(error); }
});
context.takeScreenshot("shader160-native-client");
}
private static void check(boolean value, String message) { if (!value) throw new AssertionError(message); }
}
@@ -44,6 +44,7 @@ public final class SanctuaryMod implements ModInitializer {
@Override
public void onInitialize() {
fr.koka.sanctuary.community.CommunityNetwork.register();
fr.koka.sanctuary.community.ServerMetrics.register();
fr.koka.sanctuary.building.ColoredBricks.register();
fr.koka.sanctuary.gems.Gems.register();
fr.koka.sanctuary.sky.VortexClouds.register();
@@ -23,7 +23,7 @@ final class CommunityCard extends AbstractButton implements AutoCloseable {
CommunityCard(int width,JsonObject entry,boolean compact,Runnable action) {
super(0,0,width,compact?44:90,Component.literal(str(entry,"title")));this.entry=entry;this.compact=compact;this.action=action;article=str(entry,"kind").equals("article");
face=new PlayerFaceWidget(compact?20:24,ResolvableProfile.createUnresolved(UUID.fromString(str(entry,"authorId"))));
setTooltip(Tooltip.create(getMessage().copy().append("\n").append(str(entry,"authorName"))));
setTooltip(Tooltip.create(getMessage().copy().append("\n").append(str(entry,"authorName")).append("\n").append(CommunityScreen.date(entry))));
if(article&&!compact) {
height=width*9/16+78;
try {
@@ -51,7 +51,7 @@ final class CommunityCard extends AbstractButton implements AutoCloseable {
if(compact)g.text(font,font.plainSubstrByWidth(text("category."+str(entry,"category")).append(" · ").append(text(str(entry,"status"))).getString(),width-14),x+7,y+31,accent,false);
else {
g.text(font,font.plainSubstrByWidth(str(entry,"authorName"),width-14),x+7,top+30,0xffd6d4c9,false);
g.text(font,CommunityScreen.date(entry),x+7,top+42,0xffa2aaa4,false);
g.text(font,font.plainSubstrByWidth(CommunityScreen.date(entry),width-14),x+7,top+42,0xffa2aaa4,false);
if(!article)g.text(font,font.plainSubstrByWidth(text("category."+str(entry,"category")).append(" · ").append(text(str(entry,"status"))).getString(),width-14),x+7,top+59,accent,false);
}
}
@@ -32,13 +32,13 @@ public final class CommunityClient {
}));
ClientPlayConnectionEvents.DISCONNECT.register((h,c) -> { pending = 0; owner = null; callback = null; overview = new JsonObject(); stale = true; overviewError = ""; DRAFTS.clear(); });
ClientTickEvents.END_CLIENT_TICK.register(client -> {
if(++followTicks%100==0 && pending==0 && client.player!=null && client.gui.screen()==null && available())request(null,"following","","","notice","info","","",0,0,r->{});
if(++followTicks%100==0 && pending==0 && client.player!=null && (client.gui.screen()==null || client.gui.screen() instanceof SanctuaryAtlasScreen || client.gui.screen() instanceof PauseAtlasAccess) && available())request(null,"following","","","notice","info","","",0,0,r->{});
if (pending != 0 && ++ticks > 200) { var result = new JsonObject(); result.addProperty("error","unavailable"); finish(result); }
});
}
private static void finish(JsonObject result) {
pending = 0;
if(result.has("following"))NotificationClient.community(result.getAsJsonArray("following"));
if(result.has("following")){NotificationClient.community(result.getAsJsonArray("following"));CommunityMapMarkers.accept(result.getAsJsonArray("following"));}
if (overviewRequest) {
if (!result.has("error")) { overview = result; stale = false; overviewError = ""; }
else { stale = true; overviewError = str(result,"error"); }
@@ -0,0 +1,84 @@
package fr.koka.sanctuary.client;
import com.google.gson.JsonArray;
import fr.koka.sanctuary.community.CommunityTask;
import java.util.*;
import java.util.function.DoubleToIntFunction;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.network.chat.Component;
/** Locations deliberately shared by followed notices; these never reveal terrain or generate chunks. */
final class CommunityMapMarkers {
record Marker(String id,String title,String author,String summary,CommunityTask task,int color) { }
record Pin(Marker marker,int x,int y) {
boolean contains(double mx,double my){return Math.abs(mx-x)<=7 && Math.abs(my-y)<=8;}
}
private static List<Marker> markers=List.of();
private CommunityMapMarkers() { }
static void clear(){markers=List.of();}
static void accept(JsonArray entries) {
var next=new ArrayList<Marker>();
for(var value:entries) {
var e=value.getAsJsonObject();
if(!CommunityClient.str(e,"status").equals("open") || !e.has("task") || e.get("task").isJsonNull())continue;
var task=new com.google.gson.Gson().fromJson(e.get("task"),CommunityTask.class);
if(task.location()!=null)next.add(new Marker(CommunityClient.str(e,"id"),CommunityClient.str(e,"title"),CommunityClient.str(e,"authorName"),CommunityClient.str(e,"summary"),task,CommunityCard.color(CommunityClient.str(e,"category"))));
}
markers=List.copyOf(next);
}
static List<Pin> project(String dimension,DoubleToIntFunction screenX,DoubleToIntFunction screenZ,int left,int top,int right,int bottom) {
var pins=new ArrayList<Pin>();
for(var marker:markers) {
var location=marker.task().location();if(!location.dimension().equals(dimension))continue;
int x=screenX.applyAsInt(location.x()+.5),y=screenZ.applyAsInt(location.z()+.5);
if(x>=left+7 && x<right-7 && y>=top+8 && y<bottom-8)pins.add(new Pin(marker,x,y));
}
return List.copyOf(pins);
}
static Pin at(List<Pin> pins,double x,double y){return pins.stream().filter(p->p.contains(x,y)).findFirst().orElse(null);}
static boolean render(GuiGraphicsExtractor g,List<Pin> pins,int mouseX,int mouseY) {
var font=Minecraft.getInstance().font;
for(var pin:pins) {
int x=pin.x(),y=pin.y();
g.fill(x-7,y-8,x+8,y+9,pin.contains(mouseX,mouseY)?0xfff4e7b4:pin.marker().color());
g.fill(x-6,y-7,x+7,y+8,0xff20251e);
g.fill(x-1,y-5,x+2,y+2,0xffffd35a);
g.fill(x-1,y+4,x+2,y+6,0xffffd35a);
}
var hovered=at(pins,mouseX,mouseY);
if(hovered==null)return false;
g.setTooltipForNextFrame(font,tooltip(hovered.marker()),mouseX,mouseY);
return true;
}
static List<net.minecraft.util.FormattedCharSequence> tooltip(Marker marker) {
var client=Minecraft.getInstance();var font=client.font;var task=marker.task();var location=task.location();
int width=Math.min(230,client.getWindow().getGuiScaledWidth()-28);
var lines=new ArrayList<net.minecraft.util.FormattedCharSequence>();
lines.addAll(font.split(Component.literal(marker.title()).withStyle(net.minecraft.ChatFormatting.BOLD),width).stream().limit(2).toList());
lines.add(Component.literal(font.plainSubstrByWidth(marker.author(),width)).getVisualOrderText());
lines.addAll(font.split(Component.literal(marker.summary()),width).stream().limit(3).toList());
lines.addAll(font.split(Component.literal("X "+location.x()+" Y "+location.y()+" Z "+location.z()),width));
if(!task.materials().isEmpty()) {
lines.add(CommunityClient.text("materials").getVisualOrderText());
itemLines(lines,task.materials(),width,2);
}
lines.addAll(font.split(CommunityClient.text("reward."+task.reward()),width));
if(task.reward().equals("items"))itemLines(lines,task.rewards(),width,2);
if(task.reward().equals("custom"))lines.addAll(font.split(Component.literal(task.customReward()),width).stream().limit(2).toList());
lines.addAll(font.split(CommunityClient.text("audience."+task.audience()),width));
int limit=Math.max(5,(client.getWindow().getGuiScaledHeight()-34)/font.lineHeight-2);
if(lines.size()>limit){lines=new ArrayList<>(lines.subList(0,limit-1));lines.add(Component.literal("…").getVisualOrderText());}
lines.addAll(font.split(CommunityClient.text("map_followed"),width));
return List.copyOf(lines);
}
private static void itemLines(List<net.minecraft.util.FormattedCharSequence> lines,List<CommunityTask.Material> items,int width,int limit) {
var font=Minecraft.getInstance().font;
for(var item:items.stream().limit(limit).toList()) {
var name=net.minecraft.core.registries.BuiltInRegistries.ITEM.getOptional(net.minecraft.resources.Identifier.parse(item.item()))
.map(i->i.getDefaultInstance().getHoverName()).orElse(Component.literal(item.item()));
lines.addAll(font.split(Component.literal(item.count()+" × ").append(name),width));
}
if(items.size()>limit)lines.addAll(font.split(CommunityClient.text("map_more_materials",items.size()-limit),width));
}
}
@@ -31,7 +31,7 @@ public final class CommunityPausePanels implements AutoCloseable {
clock=new StringWidget(rightX,8,right,20,Component.empty(),font);
add.accept(date);add.accept(clock);
int headerSide=Math.max(84,screen.width/5);
bulletin=new PauseTextButton(headerSide,3,screen.width-2*headerSide,32,text("bulletin"),()->{});
bulletin=new PauseTextButton(headerSide,3,screen.width-2*headerSide,32,text("bulletin"),()->open(screen,"bulletin",items("bulletins").isEmpty()?"":str(items("bulletins").get(0).getAsJsonObject(),"id"),false));
add.accept(bulletin);
String[] sections={"blocks","history","progress","identity"};
int optionsTop=screen.height-76;
@@ -64,15 +64,18 @@ public final class CommunityPausePanels implements AutoCloseable {
private void updateHeader() {
var locale=Locale.forLanguageTag(Minecraft.getInstance().getLanguageManager().getSelected().replace('_','-'));
var now=ZonedDateTime.now();
date.setMessage(Component.literal(DateTimeFormatter.ofPattern("d MMMM",locale).format(now)));
date.setMessage(Component.literal(DateTimeFormatter.ofPattern("d MMMM yyyy",locale).format(now)));
clock.setMessage(Component.literal(DateTimeFormatter.ofPattern("HH:mm",locale).format(now)));
clock.setX(screen.width-8-Minecraft.getInstance().font.width(clock.getMessage()));clock.setWidth(Minecraft.getInstance().font.width(clock.getMessage()));
var list=items("bulletins");
Component message=list.isEmpty()?text("bulletin_empty"):Component.literal(str(list.get(0).getAsJsonObject(),"title")+" · "+str(list.get(0).getAsJsonObject(),"body"));
Component message=list.isEmpty()?text("bulletin_empty"):Component.literal(str(list.get(0).getAsJsonObject(),"title"));
if(!overviewError.isEmpty())message=text(overviewError);
bulletin.setMessage(message);
bulletin.setTooltip(Tooltip.create(text("bulletin").append("\n").append(list.isEmpty()?message:Component.literal(str(list.get(0).getAsJsonObject(),"body")))));
bulletin.active=false;
date.setWidth(Minecraft.getInstance().font.width(date.getMessage()));
int left=Math.max(date.getRight()+8,screen.width/5),right=screen.width-Math.max(56,screen.width/5);
bulletin.setRectangle(Math.max(24,right-left),32,left,3);
bulletin.active=available();
}
public void tick() {
if(closed)return;
@@ -12,6 +12,11 @@ import static fr.koka.sanctuary.client.CommunityClient.*;
/** Native community pages: user content is always a literal Minecraft component. */
public final class CommunityScreen extends BlocodexFrame {
private final String kind;
private final boolean admin;
private String search="";
private int searchAfter;
private boolean rebuildSearch;
private EditBox searchBox;
private String id, editingId = "", message = "", expandedId = "";
private int page, revision;
private boolean composing, needsLoad = true, moderator;
@@ -36,12 +41,19 @@ public final class CommunityScreen extends BlocodexFrame {
}
static CommunityScreen admin(Screen parent){return new CommunityScreen(parent,"bulletin","",false,true);}
private CommunityScreen(Screen parent,String kind,String id,boolean compose,boolean admin) {
super(parent); this.kind = kind.equals("bulletin")&&!admin?"article":kind; this.id = id; this.composing = compose;
super(parent); this.kind = kind; this.admin=admin; this.id = id; this.composing = compose && (!kind.equals("bulletin") || admin);
moderator = flag(overview,"moderator");
if (compose) useDraft("new:" + kind);
}
private void useDraft(String key) { draft = DRAFTS.computeIfAbsent(key, unused -> new Draft()); }
@Override protected void rebuildWidgets() {
boolean restoreFocus=searchBox!=null && searchBox.isFocused() && !composing && id.isEmpty();
int cursor=restoreFocus?searchBox.getCursorPosition():0;
super.rebuildWidgets();
if(restoreFocus && searchBox!=null){setInitialFocus(searchBox);searchBox.moveCursorTo(cursor,false);}
}
@Override protected void init() {
searchBox=null;
closePhotos();initFrame("history",text(kind)); contentX=(width-contentWidth)/2; int w = contentWidth - 28;
var layout = LinearLayout.vertical().spacing(8);
if (!message.isEmpty()) line(layout,w,text(message));
@@ -55,9 +67,12 @@ public final class CommunityScreen extends BlocodexFrame {
}
private void listing(LinearLayout layout,int w) {
var tabs=layout.addChild(LinearLayout.horizontal().spacing(6));
if(!kind.equals("bulletin"))for(String target:new String[]{"article","notice"})tabs.addChild(Button.builder(text(target),b->open(parent,target,"",false)).width((w-6)/2).build());
if(!admin)for(String target:new String[]{"article","notice","bulletin"})tabs.addChild(Button.builder(text(target.equals("bulletin")?"server_tab":target.equals("notice")?"notice_tab":target),b->open(parent,target,"",false)).width((w-12)/3).build());
searchBox=layout.addChild(new EditBox(font,w,20,text("search")));
searchBox.setMaxLength(120);searchBox.setHint(text("search"));searchBox.setValue(search);
searchBox.setResponder(value->{search=value;page=0;more=false;entries.clear();restoreScroll=0;needsLoad=true;searchAfter=ticks+6;rebuildSearch=true;});
var toolbar=layout.addChild(LinearLayout.horizontal().spacing(6));
button(toolbar,(w-6)/2,"publish",()->{composing=true;useDraft("new:"+kind);rebuildWidgets();});
if(!kind.equals("bulletin") || admin)button(toolbar,(w-6)/2,"publish",()->{composing=true;useDraft("new:"+kind);rebuildWidgets();});
button(toolbar,(w-6)/2,"refresh",()->{page=0;needsLoad=true;});
if(entries.isEmpty())line(layout,w,text(needsLoad?"loading":"empty"));
int cardWidth=(w-8)/2;
@@ -122,11 +137,12 @@ public final class CommunityScreen extends BlocodexFrame {
}).size(20,18).tooltip(Tooltip.create(text("actions_for",str(entry,"authorName")))).build());
}
private void message(LinearLayout layout,int w,JsonObject entry) {
author(layout,w,entry,true);
author(layout,w,entry,!kind.equals("bulletin") || admin);
layout.addChild(new CommunityBubble(w,str(entry,"body"),own(entry)));
if(expandedId.equals(str(entry,"id"))) controls(layout,w,entry);
}
private void controls(LinearLayout layout,int w,JsonObject entry) {
if(kind.equals("bulletin") && !admin)return;
boolean own = own(entry);
var row=layout.addChild(LinearLayout.horizontal().spacing(4)); int size=Math.min(100,(w-12)/4);
if (own) button(row,size,"edit",() -> {
@@ -193,7 +209,12 @@ public final class CommunityScreen extends BlocodexFrame {
}
private void taskDetails(LinearLayout layout,int w,JsonObject entry) {
var task=readTask(entry);
if(task.location()!=null)line(layout,w,text("location_value",task.location().dimension(),task.location().x(),task.location().y(),task.location().z()));
if(task.location()!=null) {
line(layout,w,text("location_value",task.location().dimension(),task.location().x(),task.location().y(),task.location().z()));
var map=layout.addChild(Button.builder(text("map_show"),b->minecraft.gui.setScreen(new SanctuaryAtlasScreen(this,task.location()))).width(Math.min(w,220)).build());
map.active=minecraft.level!=null && task.location().dimension().equals(minecraft.level.dimension().identifier().toString());
if(!map.active)map.setTooltip(Tooltip.create(text("map_other_dimension")));
}
if(!task.materials().isEmpty()) {line(layout,w,text("materials"));CommunityMaterialsScreen.showItems(layout,w,task.materials());}
line(layout,w,text("audience."+task.audience()));line(layout,w,text("reward."+task.reward()));
if(task.reward().equals("items"))CommunityMaterialsScreen.showItems(layout,w,task.rewards());
@@ -203,6 +224,8 @@ public final class CommunityScreen extends BlocodexFrame {
line(layout,w,text("followers",count));
if(data.has("members"))for(var member:data.getAsJsonArray("members"))line(layout,w,Component.literal("• "+str(member.getAsJsonObject(),"playerName")));
boolean subscribed=flag(data,"subscribed");
if(str(entry,"status").equals("open"))line(layout,w,text(subscribed?"follow_map_active":"follow_map_help"));
if(!subscribed && str(entry,"status").equals("open") && task.audience().equals("single") && count>0)line(layout,w,text("notice_full_help"));
var follow=layout.addChild(Button.builder(text(subscribed?"unfollow":"follow"),b->request(this,subscribed?"unfollow":"follow",id,"","notice","info","","",0,0,result->{
message=result.has("error")?str(result,"error"):"saved";needsLoad=true;stale=true;
if(!result.has("error")&&!subscribed)NotificationClient.communitySubscribed(Component.literal(str(entry,"title")));
@@ -229,9 +252,10 @@ public final class CommunityScreen extends BlocodexFrame {
private void button(LinearLayout layout,int w,String key,Runnable action) {
layout.addChild(Button.builder(text(key),b -> { if (!publishing) action.run(); }).width(w).build());
}
static String date(JsonObject e) { return DateTimeFormatter.ofPattern("dd/MM HH:mm 'UTC'").withZone(ZoneOffset.UTC).format(Instant.ofEpochMilli(e.get("createdAt").getAsLong())); }
static String date(JsonObject e) { return DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm 'UTC'").withZone(ZoneOffset.UTC).format(Instant.ofEpochMilli(e.get("createdAt").getAsLong())); }
@Override public void tick() {
super.tick(); ticks++;
if(rebuildSearch){rebuildSearch=false;rebuildWidgets();}
if(publishing && !pending() && ticks>=sendAfter) {
if(!taskSent) {
request(this,"task",editingId.isEmpty()?draft.operation:editingId,"","notice","info","",new GsonBuilder().disableHtmlEscaping().create().toJson(draft.task),0,0,result->{
@@ -248,7 +272,9 @@ public final class CommunityScreen extends BlocodexFrame {
});
} else if(commit!=null) {var actionToRun=commit;commit=null;actionToRun.run();}
}
if (!composing && needsLoad && ticks%4==0 && request(this,id.isEmpty()?(kind.equals("bulletin")?"list":"cards"):"thread",id,"",kind,"info","","",0,page,result -> {
String requestedSearch=search,requestedId=id;int requestedPage=page;
if (!composing && needsLoad && ticks>=searchAfter && ticks%4==0 && request(this,id.isEmpty()?(kind.equals("bulletin")?"list":"cards"):"thread",id,"",kind,"info","",id.isEmpty()?search:"",0,page,result -> {
if(!search.equals(requestedSearch) || !id.equals(requestedId) || page!=requestedPage || composing)return;
if (result.has("error")) message=str(result,"error");
else {data=result;moderator=flag(result,"moderator");
if(id.isEmpty()&&result.has("page")) {
@@ -61,7 +61,7 @@ public final class CommunityScreenshotsScreen extends BlocodexFrame {
}
@Override protected void init() {
closeTextures();initFrame("history",text("screenshots"));
contentWidth=Math.min(420,contentWidth);contentX=(width-contentWidth)/2;
contentWidth=Math.max(240,width-24);contentX=(width-contentWidth)/2;
if(!loaded)load(true);
if(selected!=null) {preview();return;}
int w=contentWidth-24;
@@ -70,12 +70,12 @@ public final class CommunityScreenshotsScreen extends BlocodexFrame {
controls.addChild(new StringWidget(Math.max(30,w-228),20,text("page",page+1),font));
controls.addChild(Button.builder(text("next"),b->{page++;load(false);rebuildWidgets();}).width(72).build()).active=(page+1)*PAGE_SIZE<paths.size() && loading==null;
controls.addChild(Button.builder(text("refresh"),b->{page=0;load(true);rebuildWidgets();}).width(76).build()).active=loading==null;
controls.setPosition(contentX+8,contentTop+Math.max(24,Math.min(180,contentBottom-contentTop-28))+8);controls.arrangeElements();controls.visitWidgets(this::addRenderableWidget);
controls.setPosition(contentX+8,contentTop+Math.max(24,contentBottom-contentTop-28)+8);controls.arrangeElements();controls.visitWidgets(this::addRenderableWidget);
var layout=LinearLayout.vertical().spacing(8);
if(loading!=null)layout.addChild(new StringWidget(text("loading"),font));
else if(!error.isEmpty() || shots.isEmpty())layout.addChild(new MultiLineTextWidget(text(error.isEmpty()?"screenshots_empty":error),font).setMaxWidth(w));
else {
int columns=w>=360?4:3,cell=(w-(columns-1)*8)/columns;
int columns=Math.max(2,w/112),cell=(w-(columns-1)*8)/columns;
for(int i=0;i<shots.size();i+=columns) {
var row=layout.addChild(LinearLayout.horizontal().spacing(8));
for(int j=i;j<Math.min(i+columns,shots.size());j++) {
@@ -85,11 +85,11 @@ public final class CommunityScreenshotsScreen extends BlocodexFrame {
}
}
}
var scroll=new ScrollableLayout(minecraft,layout,Math.max(24,Math.min(180,contentBottom-contentTop-28)),ScrollableLayout.ReserveStrategy.RIGHT);
var scroll=new ScrollableLayout(minecraft,layout,Math.max(24,contentBottom-contentTop-28),ScrollableLayout.ReserveStrategy.RIGHT);
scroll.setPosition(contentX+8,contentTop);scroll.arrangeElements();scroll.visitWidgets(this::addRenderableWidget);
}
private void preview() {
int w=Math.min(260,contentWidth-16),h=Math.max(24,Math.min(146,contentBottom-contentTop-34));
int w=contentWidth-16,h=Math.max(24,contentBottom-contentTop-34);
int left=(width-w)/2;
try {
var image=CommunityPhoto.decode(Base64.getDecoder().decode(selected.photo()),CommunityPhoto.WIDTH,CommunityPhoto.HEIGHT);
@@ -21,7 +21,20 @@ public final class HotbarClient {
private static boolean held;
private static boolean worldHeld;
private HotbarClient() {}
static void migratePlayerListKey(net.minecraft.client.Minecraft client) {
var marker=net.fabricmc.loader.api.FabricLoader.getInstance().getConfigDir().resolve("sanctuary-player-list-key-v1.txt");
if(java.nio.file.Files.exists(marker))return;
try {
if(client.options.keyPlayerList.matches(InputConstants.Type.KEYBOARD.getOrCreate(InputConstants.KEY_TAB))) {
client.options.keyPlayerList.setKey(InputConstants.Type.KEYBOARD.getOrCreate(InputConstants.KEY_U));
KeyMapping.resetMapping();client.options.save();
}
java.nio.file.Files.createDirectories(marker.getParent());
java.nio.file.Files.writeString(marker,"beta.161\n",java.nio.file.StandardOpenOption.CREATE_NEW);
} catch(java.io.IOException error) {fr.koka.sanctuary.SanctuaryMod.LOGGER.warn("Cannot record player list key migration",error);}
}
public static void register(KeyMapping.Category category) {
net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents.CLIENT_STARTED.register(HotbarClient::migratePlayerListKey);
key=KeyMappingHelper.registerKeyMapping(new KeyMapping("screen.sanctuary.inventory.rotate_key",InputConstants.Type.KEYBOARD,InputConstants.KEY_TAB,category));
ClientConfigurationNetworking.registerGlobalReceiver(HotbarPayloads.Capability.TYPE,(p,c) -> {});
ClientPlayNetworking.registerGlobalReceiver(HotbarPayloads.State.TYPE,(p,c) -> c.client().execute(() -> {
@@ -41,7 +41,7 @@ public final class NotificationClient {
ClientPlayConnectionEvents.DISCONNECT.register((h,m)->reset());
ClientTickEvents.END_CLIENT_TICK.register(NotificationClient::tick);
}
public static void reset(){communityTracks=List.of();FEED.clear();OBJECTIVES.reset();inhabitant=null;trackingScope=null;hasRoom=true;recipes=null;blocks=totalBlocks=totalItems=totalRecipes=ticks=0;lastClock=0;animatedBlocks=animatedItems=animatedRecipes=0;}
public static void reset(){CommunityMapMarkers.clear();communityTracks=List.of();FEED.clear();OBJECTIVES.reset();inhabitant=null;trackingScope=null;hasRoom=true;recipes=null;blocks=totalBlocks=totalItems=totalRecipes=ticks=0;lastClock=0;animatedBlocks=animatedItems=animatedRecipes=0;}
public static void clearFeed(){FEED.clear();}
public static List<NotificationFeed.Entry<Message>> messages(){return FEED.entries();}
public static List<Track> tracked(){var tracks=new ArrayList<>(OBJECTIVES.shown(options().pinnedAdvancements,options().advancements));if(options().pinnedAdvancements)tracks.addAll(communityTracks);return tracks.stream().distinct().limit(6).toList();}
@@ -69,6 +69,16 @@ public final class PauseAtlasWidget extends AbstractButton implements AutoClosea
if(--refresh<=0)request();
}
public int knownPixels() {return pixels;}
private double zoom(){return Math.max(.75,Math.max(width,height)/992.);}
java.util.List<CommunityMapMarkers.Pin> questPins() {
return CommunityMapMarkers.project(dimension,wx->getX()+width/2+(int)Math.round((wx-centerX)*zoom()),
wz->getY()+height/2+(int)Math.round((wz-centerZ)*zoom()),getX(),getY()+20,getRight(),getBottom()-20);
}
@Override public boolean mouseClicked(net.minecraft.client.input.MouseButtonEvent event,boolean doubleClick) {
var pin=CommunityMapMarkers.at(questPins(),event.x(),event.y());
if(event.button()==com.mojang.blaze3d.platform.InputConstants.MOUSE_BUTTON_LEFT && pin!=null){CommunityClient.open(owner,"notice",pin.marker().id(),false);return true;}
return super.mouseClicked(event,doubleClick);
}
@Override public void onPress(InputWithModifiers input) {ProgressionClient.open(owner,"history");}
@Override protected void extractContents(GuiGraphicsExtractor g,int mx,int my,float delta) {
if(texture==null)return;
@@ -77,7 +87,7 @@ public final class PauseAtlasWidget extends AbstractButton implements AutoClosea
g.fill(x,y,getRight(),getBottom(),0x90151B19);
g.enableScissor(x,y,getRight(),getBottom());
if(readable) {
double zoom=Math.max(.75,Math.max(width,height)/992.);
double zoom=zoom();
int left=x+width/2+(int)((originX-centerX)*zoom),top=y+height/2+(int)((originZ-centerZ)*zoom);
g.blit(RenderPipelines.GUI_TEXTURED,TEXTURE,left,top,0,0,(int)(SIZE*zoom),(int)(SIZE*zoom),SIZE,SIZE,SIZE,SIZE);
int px=x+width/2,pz=y+height/2;
@@ -89,6 +99,8 @@ public final class PauseAtlasWidget extends AbstractButton implements AutoClosea
int color=ProgressionClient.identity==null?0xFFFFFFFF:0xFF000000|ProgressionClient.identity.color();
g.fill(px-3,pz-3,px+4,pz+4,0xFF141818);g.fill(px-2,pz-2,px+3,pz+3,color);
}
boolean questHovered=CommunityMapMarkers.render(g,questPins(),mx,my);
setTooltip(questHovered?null:Tooltip.create(Component.translatable("sanctuary.pause.map_hint")));
g.text(font,"N ↑",x+7,y+7,0xFFFFFFFF);
if(pixels==0)g.textWithWordWrap(font,SanctuaryAtlasScreen.label(readable?"empty":status),x+8,y+height/2+12,width-16,0xFFCCCCCC);
g.text(font,font.plainSubstrByWidth(getMessage().getString(),width-14),x+7,getBottom()-16,0xFFF0EEE6);
@@ -38,7 +38,9 @@ public final class SanctuaryAtlasScreen extends BlocodexFrame {
private String status="loading";
private String dimension="";
public SanctuaryAtlasScreen(Screen parent) {super(parent);}
private final fr.koka.sanctuary.community.CommunityTask.Location initialTarget;
public SanctuaryAtlasScreen(Screen parent) {this(parent,null);}
SanctuaryAtlasScreen(Screen parent,fr.koka.sanctuary.community.CommunityTask.Location target) {super(parent);initialTarget=target;}
public static Component label(String key,Object... args) {return Component.translatable("sanctuary.atlas."+key,args);}
@Override protected void init() {
dragging=false;
@@ -75,7 +77,10 @@ public final class SanctuaryAtlasScreen extends BlocodexFrame {
minecraft.getTextureManager().register(TEXTURE,texture);
footprintTexture=new DynamicTexture("Sanctuary atlas footprints",SIZE,SIZE,false);
minecraft.getTextureManager().register(FOOTPRINT_TEXTURE,footprintTexture);
clear();recenter();
clear();
if(initialTarget!=null && minecraft.level!=null && initialTarget.dimension().equals(minecraft.level.dimension().identifier().toString())) {
centerX=initialTarget.x()+.5;centerZ=initialTarget.z()+.5;request();
} else recenter();
}
}
private void clear() {
@@ -193,6 +198,8 @@ public final class SanctuaryAtlasScreen extends BlocodexFrame {
@Override public boolean mouseClicked(MouseButtonEvent event,boolean doubleClick) {
// Disabled buttons also own their hit area; clicking one must never start a map gesture.
if (overControl(event.x(),event.y())) return super.mouseClicked(event,doubleClick);
var quest=CommunityMapMarkers.at(questPins(),event.x(),event.y());
if(event.button()==InputConstants.MOUSE_BUTTON_LEFT && quest!=null){CommunityClient.open(this,"notice",quest.marker().id(),false);return true;}
if (event.button()==InputConstants.MOUSE_BUTTON_LEFT && inside(event.x(),event.y()) && readable()) {
setFocused(null);setDragging(false);dragging=true;return true;
}
@@ -267,13 +274,18 @@ public final class SanctuaryAtlasScreen extends BlocodexFrame {
graphics.textWithWordWrap(font,message,x,y,textWidth,0xFFE0E6EE);
}
renderCoordinates(graphics,mouseX,mouseY);
if (!renderMarkerHint(graphics,mouseX,mouseY)) renderFootprintHint(graphics,mouseX,mouseY);
boolean questHint=CommunityMapMarkers.render(graphics,questPins(),mouseX,mouseY);
if (!questHint && !renderMarkerHint(graphics,mouseX,mouseY)) renderFootprintHint(graphics,mouseX,mouseY);
}
public void accept(fr.koka.sanctuary.atlas.AtlasMarkerPayload payload) {
if (payload.token()!=token || !readable() || minecraft.level==null
|| !dimension.equals(minecraft.level.dimension().identifier().toString())) return;
markers=payload.markers();
}
java.util.List<CommunityMapMarkers.Pin> questPins() {
return CommunityMapMarkers.project(dimension,this::screenX,this::screenZ,0,contentTop,width,height-62).stream()
.filter(pin->!overControl(pin.x(),pin.y())).toList();
}
private Component markerName(fr.koka.sanctuary.atlas.AtlasMarker marker) {
return marker.name().isBlank() ? label("marker_"+marker.kind()) : Component.literal(marker.name());
}
@@ -15,7 +15,8 @@ public final class VanillaLight {
private static Preferences preferences;
private VanillaLight() { }
private static final class Preferences {
boolean enabled=true;
// Opt-in on fresh installations; explicit saved choices remain authoritative.
boolean enabled=false;
Boolean naturalWater; // Legacy OFF is an explicit opt-out in both world types.
Boolean sanctuaryNaturalWater;
Boolean ordinaryNaturalWater;
@@ -44,6 +44,12 @@ public final class Community {
public Refused(String code) { super(code); this.code = code; }
}
public static void fail(String code) { throw new Refused(code); }
public static String search(String value) {
if(value==null || value.codePointCount(0,value.length())>120)fail("invalid");
value=value.strip();
if(!value.isEmpty())text(value,120);
return value.toLowerCase(Locale.ROOT);
}
public static String uuid(String value) {
if (value == null || !value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) fail("invalid");
return value;
@@ -79,17 +79,17 @@ public final class CommunityNetwork {
if (System.nanoTime() - now > 10_000_000_000L) fail("busy");
var store = runtime.store(); result = new JsonObject(); result.addProperty("moderator",actor.moderator());
result.addProperty("serverTime",System.currentTimeMillis()); result.addProperty("mode",runtime.config.mode());
if(request.kind().equals("bulletin") && !Set.of("overview","following").contains(request.action()) && !actor.moderator())fail("forbidden");
if(request.kind().equals("bulletin") && !Set.of("overview","following","list","cards","thread").contains(request.action()) && !actor.moderator())fail("forbidden");
switch (request.action()) {
case "overview" -> {
result.add("articles", JSON.toJsonTree(store.list("article","",0).entries().stream().limit(3).toList()));
result.add("notices", JSON.toJsonTree(store.list("notice","",0).entries().stream().limit(3).toList()));
result.add("bulletins", JSON.toJsonTree(store.list("bulletin","",0).entries().stream().limit(1).toList()));
}
case "list" -> result.add("page",JSON.toJsonTree(store.list(request.kind(),"",request.page())));
case "list" -> result.add("page",JSON.toJsonTree(store.list(request.kind(),"",request.page(),request.body())));
case "cards" -> {
if(!Set.of("article","notice").contains(request.kind()))fail("invalid");
var page=store.list(request.kind(),"",request.page());var cards=JSON.toJsonTree(page).getAsJsonObject();
var page=store.list(request.kind(),"",request.page(),request.body());var cards=JSON.toJsonTree(page).getAsJsonObject();
for(var value:cards.getAsJsonArray("entries")) {
var entry=value.getAsJsonObject();String photo=entry.has("photo")?entry.get("photo").getAsString():"";
if(!photo.isEmpty())entry.addProperty("thumbnail",runtime.thumbnail(entry.get("id").getAsString()+":"+entry.get("revision").getAsInt(),photo));
@@ -99,7 +99,6 @@ public final class CommunityNetwork {
}
case "thread" -> {
var thread=store.thread(request.id(),request.page());
if(thread.entry().kind().equals("bulletin")&&!actor.moderator())fail("forbidden");
result.add("thread",JSON.toJsonTree(thread));
if(thread.entry().kind().equals("notice")) {
var members=store.members(request.id());result.add("members",JSON.toJsonTree(members));
@@ -154,7 +153,11 @@ public final class CommunityNetwork {
}
private static JsonElement following(CommunityStore store,Actor actor) throws Exception {
var result=JSON.toJsonTree(store.following(actor));omitPhotos(result);
result.getAsJsonArray().forEach(e->e.getAsJsonObject().remove("body"));return result;
result.getAsJsonArray().forEach(e->{
var entry=e.getAsJsonObject();String body=entry.remove("body").getAsString();
int count=body.codePointCount(0,body.length());
entry.addProperty("summary",count>240?body.substring(0,body.offsetByCodePoints(0,240))+"…":body);
});return result;
}
private static void omitTasks(JsonElement value) {
if(value.isJsonArray())value.getAsJsonArray().forEach(CommunityNetwork::omitTasks);
@@ -9,7 +9,8 @@ public interface CommunityStore extends AutoCloseable {
void save(Entry entry, boolean insert) throws Exception;
int followers(String id) throws Exception;
}
Page list(String kind, String parent, int page) throws Exception;
default Page list(String kind, String parent, int page) throws Exception { return list(kind,parent,page,""); }
Page list(String kind, String parent, int page, String search) throws Exception;
ThreadView thread(String id, int page) throws Exception;
Entry change(Actor actor, Change change) throws Exception;
java.util.List<CommunityTask.Follow> members(String id) throws Exception;
@@ -40,20 +40,22 @@ public final class FileCommunityStore implements CommunityStore {
}
}
}
@Override public synchronized Page list(String kind, String parent, int page) {
@Override public synchronized Page list(String kind, String parent, int page, String search) {
String needle=Community.search(search);
page(page); if (!KINDS.contains(kind)) fail("invalid");
if (!parent.isEmpty()) visible(entries.get(parent));
Comparator<Entry> order = Comparator.comparingLong(Entry::createdAt).thenComparing(Entry::id);
if (kind.equals("bulletin")) order = order.reversed();
else if (!kind.equals("reply")) order = Comparator.comparing(Entry::pinned).reversed().thenComparing(order.reversed());
var found = entries.values().stream().filter(e -> e.kind().equals(kind) && e.parentId().equals(parent)
&& !e.status().equals("hidden")).sorted(order).skip((long) page * PAGE_SIZE).limit(PAGE_SIZE + 1).toList();
&& !e.status().equals("hidden") && (needle.isEmpty() || e.authorName().toLowerCase(Locale.ROOT).contains(needle)
|| e.title().toLowerCase(Locale.ROOT).contains(needle) || e.body().toLowerCase(Locale.ROOT).contains(needle))).sorted(order).skip((long) page * PAGE_SIZE).limit(PAGE_SIZE + 1).toList();
return new Page(found.subList(0, Math.min(PAGE_SIZE, found.size())), page, found.size() > PAGE_SIZE);
}
@Override public synchronized ThreadView thread(String id, int page) {
Entry entry = visible(entries.get(uuid(id)));
if (entry.kind().equals("reply")) fail("missing");
return new ThreadView(entry, list("reply", id, page));
return new ThreadView(entry, list("reply", id, page, ""));
}
@Override public synchronized Entry change(Actor actor, Change change) throws Exception {
var candidate = new LinkedHashMap<>(entries);
@@ -0,0 +1,79 @@
package fr.koka.sanctuary.community;
import fr.koka.sanctuary.SanctuaryMod;
import java.nio.charset.StandardCharsets;
import java.sql.DriverManager;
import java.util.*;
import java.util.concurrent.*;
import net.fabricmc.fabric.api.event.lifecycle.v1.*;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.stats.Stats;
import net.minecraft.world.level.storage.LevelResource;
/** Server-thread observations, bounded asynchronous persistence; no web requests touch the game thread. */
public final class ServerMetrics {
private static final Map<MinecraftServer,Session> SESSIONS=new HashMap<>();
private ServerMetrics() { }
public static void register() {
ServerLifecycleEvents.SERVER_STARTED.register(server -> {if(!server.isSingleplayer()) {var s=new Session(server);SESSIONS.put(server,s);s.capture(true);}});
ServerTickEvents.END_SERVER_TICK.register(server -> {var s=SESSIONS.get(server);if(s!=null && System.nanoTime()-s.lastCapture>=30_000_000_000L)s.capture(true);});
ServerPlayConnectionEvents.DISCONNECT.register((handler,server)->{var s=SESSIONS.get(server);if(s!=null)s.observe(handler.player);});
ServerLifecycleEvents.SERVER_STOPPING.register(server -> {var s=SESSIONS.remove(server);if(s!=null)s.stop();});
}
private static boolean actor(ServerPlayer player) {
String name=player.getGameProfile().name();
return name.startsWith("Lab_") && player.getUUID().equals(UUID.nameUUIDFromBytes(("SanctuaryDuo:"+name).getBytes(StandardCharsets.UTF_8)));
}
private static final class Session {
final MinecraftServer server;
final ThreadPoolExecutor worker=new ThreadPoolExecutor(1,1,0L,TimeUnit.SECONDS,new ArrayBlockingQueue<>(2),r->{var t=new Thread(r,"sanctuary-metrics");t.setDaemon(true);return t;});
final Map<String,Long> latest=new HashMap<>();
final Set<String> actors=new HashSet<>();
final long started=System.nanoTime()/1_000_000;
ServerMetricsLedger ledger;
CommunityConfig config;
boolean broken;
long lastCapture,lastSqlWarning;
Session(MinecraftServer server){this.server=server;}
void observe(ServerPlayer player) {
if(actor(player))actors.add(player.getStringUUID());
else latest.put(player.getStringUUID(),(long)player.getStats().getValue(Stats.CUSTOM.get(Stats.DEATHS)));
}
void capture(boolean running) {
lastCapture=System.nanoTime();
int online=0;
for(var player:server.getPlayerList().getPlayers()) {observe(player);if(!actor(player))online++;}
var values=Map.copyOf(latest);var excluded=Set.copyOf(actors);
long monotonic=lastCapture/1_000_000,wall=System.currentTimeMillis();int count=running?online:0;
try {worker.execute(()->persist(monotonic,wall,values,excluded,count,running));}
catch(RejectedExecutionException error){SanctuaryMod.LOGGER.warn("Server metrics worker busy; next sample will include elapsed time");}
}
void persist(long monotonic,long wall,Map<String,Long> values,Set<String> excluded,int online,boolean running) {
if(broken)return;
ServerMetricsLedger.Snapshot snapshot;
try {
if(ledger==null)ledger=new ServerMetricsLedger(server.getWorldPath(LevelResource.ROOT),started);
snapshot=ledger.sample(monotonic,wall,values,excluded,online,running);
} catch(Exception error) {broken=true;SanctuaryMod.LOGGER.error("Server metrics stopped; existing local data preserved ({})",error.getClass().getSimpleName());return;}
try {
if(config==null)config=CommunityConfig.load(FabricLoader.getInstance().getConfigDir().resolve("sanctuary-community.json"));
if(!config.mode().equals("database"))return;
String password=System.getenv(config.passwordEnv());if(password==null)throw new IllegalStateException("Missing metrics database credential");
var props=new Properties();props.setProperty("user",config.user());props.setProperty("password",password);props.setProperty("connectTimeout","2000");props.setProperty("socketTimeout","3000");
try(var c=DriverManager.getConnection(config.jdbcUrl(),props);var stmt=c.prepareStatement("INSERT INTO sanctuary_server_metrics (server_id,uptime_millis,deaths,online_players,updated_at,running) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE uptime_millis=VALUES(uptime_millis),deaths=VALUES(deaths),online_players=VALUES(online_players),updated_at=VALUES(updated_at),running=VALUES(running)")) {
stmt.setQueryTimeout(3);stmt.setString(1,config.serverId());stmt.setLong(2,snapshot.uptimeMillis());stmt.setLong(3,snapshot.deaths());stmt.setInt(4,snapshot.onlinePlayers());stmt.setLong(5,snapshot.updatedAt());stmt.setBoolean(6,snapshot.running());stmt.executeUpdate();
}
} catch(Exception error) {
if(lastSqlWarning==0 || wall-lastSqlWarning>=300_000){lastSqlWarning=wall;SanctuaryMod.LOGGER.warn("Server metrics publication unavailable; local measurements retained ({})",error.getClass().getSimpleName());}
}
}
void stop() {
capture(false);worker.shutdown();
try {if(!worker.awaitTermination(8,TimeUnit.SECONDS))worker.shutdownNow();}
catch(InterruptedException error){worker.shutdownNow();Thread.currentThread().interrupt();}
}
}
}
@@ -0,0 +1,56 @@
package fr.koka.sanctuary.community;
import com.google.gson.*;
import fr.koka.sanctuary.progression.AtomicJson;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
/** Additive ledger: elapsed process time, vanilla deaths, and explicitly excluded lab actors. */
public final class ServerMetricsLedger {
private static final Gson JSON = new Gson();
private final Path path;
private byte[] previous;
private long uptimeMillis;
private final Map<String,Long> deaths = new HashMap<>();
private final Set<String> excluded = new HashSet<>();
private long sampledAt;
public record Snapshot(long uptimeMillis, long deaths, int onlinePlayers, long updatedAt, boolean running) { }
public ServerMetricsLedger(Path root, long monotonicMillis) throws Exception {
path=root.resolve("data/sanctuary-server-metrics.json");
sampledAt=monotonicMillis;
previous=AtomicJson.read(path,4*1024*1024);
if(previous!=null) {
var data=AtomicJson.parse(new String(previous,StandardCharsets.UTF_8));
AtomicJson.fields(data,"version","uptimeMillis","deaths","excluded");
var o=data.getAsJsonObject();
if(o.get("version").getAsInt()!=1 || (uptimeMillis=o.get("uptimeMillis").getAsLong())<0)throw new IllegalArgumentException("Metrics version or uptime");
for(var e:o.getAsJsonObject("deaths").entrySet()) {Community.uuid(e.getKey());long value=e.getValue().getAsLong();if(value<0)throw new IllegalArgumentException("Deaths");deaths.put(e.getKey(),value);}
for(var e:o.getAsJsonArray("excluded"))excluded.add(Community.uuid(e.getAsString()));
}
var stats=root.resolve("stats");
if(Files.isDirectory(stats))try(var files=Files.list(stats)) {
for(var file:files.filter(f->f.getFileName().toString().matches("[0-9a-f-]{36}\\.json")).toList()) {
String id=Community.uuid(file.getFileName().toString().substring(0,36));
byte[] bytes=AtomicJson.read(file,8*1024*1024);
var o=AtomicJson.parse(new String(bytes,StandardCharsets.UTF_8)).getAsJsonObject();
var all=o.getAsJsonObject("stats");var custom=all==null?null:all.getAsJsonObject("minecraft:custom");
if(custom!=null && custom.has("minecraft:deaths")) {
long value=custom.get("minecraft:deaths").getAsLong();if(value<0)throw new IllegalArgumentException("Deaths");
deaths.merge(id,value,Math::max);
}
}
}
}
public Snapshot sample(long monotonicMillis,long wallMillis,Map<String,Long> currentDeaths,Set<String> actors,int online,boolean running) throws Exception {
if(monotonicMillis<sampledAt || wallMillis<0 || online<0)throw new IllegalArgumentException("Metrics clock");
uptimeMillis=Math.addExact(uptimeMillis,monotonicMillis-sampledAt);sampledAt=monotonicMillis;
excluded.addAll(actors);
for(var e:currentDeaths.entrySet()) {Community.uuid(e.getKey());if(e.getValue()<0)throw new IllegalArgumentException("Deaths");deaths.merge(e.getKey(),e.getValue(),Math::max);}
excluded.forEach(deaths::remove);
var o=new JsonObject();o.addProperty("version",1);o.addProperty("uptimeMillis",uptimeMillis);o.add("deaths",JSON.toJsonTree(deaths));o.add("excluded",JSON.toJsonTree(excluded));
previous=AtomicJson.write(path,previous,JSON.toJson(o),4*1024*1024);
long total=0;for(long value:deaths.values())total=Math.addExact(total,value);
return new Snapshot(uptimeMillis,total,online,wallMillis,running);
}
}
@@ -42,27 +42,30 @@ public final class SqlCommunityStore implements CommunityStore {
try (var s = query(c, "SELECT * FROM sanctuary_community_entries WHERE server_id=? AND id=?" + (lock ? " FOR UPDATE" : ""), serverId, id);
var r = s.executeQuery()) { return r.next() ? row(r) : null; }
}
private Page list(Connection c, String kind, String parent, int page) throws Exception {
private Page list(Connection c, String kind, String parent, int page, String search) throws Exception {
String needle=Community.search(search);
page(page); if (!KINDS.contains(kind)) fail("invalid");
if (!parent.isEmpty()) visible(get(c, uuid(parent), false));
String parentSql = parent.isEmpty() ? "parent_id IS NULL" : "parent_id=?";
String order = kind.equals("reply") ? "created_at ASC,id ASC" : kind.equals("bulletin") ? "created_at DESC,id DESC" : "pinned DESC,created_at DESC,id DESC";
var values = new ArrayList<Object>(List.of(serverId, kind)); if (!parent.isEmpty()) values.add(parent);
String filter=needle.isEmpty()?"":" AND (LOCATE(?,BINARY LOWER(author_name))>0 OR LOCATE(?,BINARY LOWER(title))>0 OR LOCATE(?,BINARY LOWER(body))>0)";
if(!needle.isEmpty())values.addAll(List.of(needle,needle,needle));
values.add(PAGE_SIZE + 1); values.add(page * PAGE_SIZE);
try (var s = query(c, "SELECT * FROM sanctuary_community_entries WHERE server_id=? AND kind=? AND " + parentSql
+ " AND status<>'hidden' ORDER BY " + order + " LIMIT ? OFFSET ?", values.toArray()); var r = s.executeQuery()) {
+ " AND status<>'hidden'" + filter + " ORDER BY " + order + " LIMIT ? OFFSET ?", values.toArray()); var r = s.executeQuery()) {
var entries = new ArrayList<Entry>(); while (r.next()) entries.add(row(r));
return new Page(List.copyOf(entries.subList(0, Math.min(PAGE_SIZE, entries.size()))), page, entries.size() > PAGE_SIZE);
}
}
@Override public Page list(String kind, String parent, int page) throws Exception {
try (var c = connect()) { c.setAutoCommit(false); var result = list(c, kind, parent, page); c.commit(); return result; }
@Override public Page list(String kind, String parent, int page, String search) throws Exception {
try (var c = connect()) { c.setAutoCommit(false); var result = list(c, kind, parent, page, search); c.commit(); return result; }
}
@Override public ThreadView thread(String id, int page) throws Exception {
try (var c = connect()) {
c.setAutoCommit(false); Entry entry = visible(get(c, uuid(id), false));
if (entry.kind().equals("reply")) fail("missing");
var result = new ThreadView(entry, list(c, "reply", id, page)); c.commit(); return result;
var result = new ThreadView(entry, list(c, "reply", id, page, "")); c.commit(); return result;
}
}
@Override public Entry change(Actor actor, Change change) throws Exception {
@@ -0,0 +1,16 @@
package fr.koka.sanctuary.mixin.client;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.Options;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyArgs;
import org.spongepowered.asm.mixin.injection.invoke.arg.Args;
@Mixin(Options.class)
public abstract class PlayerListKeyMixin {
@ModifyArgs(method = "<init>", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/KeyMapping;<init>(Ljava/lang/String;ILnet/minecraft/client/KeyMapping$Category;)V"))
private void sanctuary$playerListDefault(Args args) {
if ("key.playerlist".equals(args.get(0))) args.set(1, InputConstants.KEY_U);
}
}
@@ -2341,6 +2341,13 @@
"sanctuary.shaders.ssr_distance_help": "Independent SSR range: 16, 32, 64, 128 or 256 blocks. Default: 64 blocks. Limited to visible terrain and mesh budget.",
"sanctuary.community.article": "Gazette",
"sanctuary.community.notice": "Notice board",
"sanctuary.community.notice_tab": "Notice board",
"sanctuary.community.map_followed": "Followed request · click for discussion",
"sanctuary.community.map_more_materials": "+ %s more materials",
"sanctuary.community.map_show": "Show on map",
"sanctuary.community.map_other_dimension": "Visit this dimension to open its map.",
"sanctuary.community.search": "Search: player, title or text…",
"sanctuary.community.server_tab": "Server",
"sanctuary.community.bulletin": "Server notices",
"sanctuary.community.publish": "Publish",
"sanctuary.community.reply": "Reply",
@@ -2432,5 +2439,8 @@
"sanctuary.community.task_expired": "Request expired. Please publish again.",
"sanctuary.community.own_notice": "You cannot follow your own request.",
"sanctuary.community.follow_limit": "You already follow 16 requests.",
"sanctuary.community.notice_full": "This request has no available places."
"sanctuary.community.notice_full": "This request has no available places.",
"sanctuary.community.follow_map_active": "Following: a map marker appears when a location is provided.",
"sanctuary.community.follow_map_help": "Replying does not subscribe you. Follow this request to display its map marker.",
"sanctuary.community.notice_full_help": "The single place is taken. You can reply, but cannot follow this request."
}
@@ -2341,6 +2341,13 @@
"sanctuary.shaders.ssr_distance_help": "Portée indépendante du SSR : 16, 32, 64, 128 ou 256 blocs. Défaut : 64 blocs. Limitée au terrain visible et au budget de maillage.",
"sanctuary.community.article": "Gazette",
"sanctuary.community.notice": "Tableau",
"sanctuary.community.notice_tab": "Tableau",
"sanctuary.community.map_followed": "Demande suivie · cliquer pour la discussion",
"sanctuary.community.map_more_materials": "+ %s autres matériaux",
"sanctuary.community.map_show": "Voir sur la carte",
"sanctuary.community.map_other_dimension": "Rejoignez cette dimension pour ouvrir sa carte.",
"sanctuary.community.search": "Rechercher : joueur, titre ou texte…",
"sanctuary.community.server_tab": "Serveur",
"sanctuary.community.bulletin": "Intendance",
"sanctuary.community.publish": "Publier",
"sanctuary.community.reply": "Répondre",
@@ -2432,5 +2439,8 @@
"sanctuary.community.task_expired": "La demande a expiré. Réessayez de publier.",
"sanctuary.community.own_notice": "Vous ne pouvez pas suivre votre propre demande.",
"sanctuary.community.follow_limit": "Vous suivez déjà 16 demandes.",
"sanctuary.community.notice_full": "Cette demande n’a plus de place disponible."
"sanctuary.community.notice_full": "Cette demande n’a plus de place disponible.",
"sanctuary.community.follow_map_active": "Demande suivie : son repère apparaît sur la carte si un lieu est indiqué.",
"sanctuary.community.follow_map_help": "Répondre ne vous abonne pas. Suivez la demande pour afficher son repère sur la carte.",
"sanctuary.community.notice_full_help": "La place unique est occupée. Vous pouvez répondre, mais pas suivre cette demande."
}
@@ -289,7 +289,8 @@
"client.NaturalWaterFogColorMixin",
"client.NaturalWaterSectionCopyAccess",
"client.PauseAtlasServerMixin",
"client.CommunityPauseMixin"
"client.CommunityPauseMixin",
"client.PlayerListKeyMixin"
],
"injectors": {
"defaultRequire": 1
@@ -50,6 +50,28 @@ public final class CommunitySmoke {
check(new com.google.gson.GsonBuilder().disableHtmlEscaping().create().toJson(task).length()<8000,"Task fits request envelope");
System.out.println("COMMUNITY158_TASKS_PASS "+store.getClass().getSimpleName());return limited;
}
static void search(CommunityStore store) throws Exception {
var author=new Actor(UUID.randomUUID().toString(),"Chercheur_159",false);
Entry first=null;
for(int i=0;i<13;i++) {
var e=store.change(author,create(UUID.randomUUID().toString(),"","notice","Recherche159 "+i,i==0?"Épingle 50%_exact":"Description159"));
if(i==0)first=e;
}
var pinned=store.change(moderator,action("pin",first));
check(store.list("notice","",0," CHERCHEUR_159 ").entries().getFirst().id().equals(pinned.id()),"Search author and retain pins");
check(store.list("notice","",0,"recherche159").more()&&store.list("notice","",1,"recherche159").entries().size()==3,"Search before pagination");
check(store.list("notice","",0,"50%_exact").entries().size()==1,"Literal SQL wildcard characters");
check(store.list("notice","",0,"ÉPINGLE").entries().size()==1,"Accented case-insensitive body search");
check(store.list("notice","",0,"%").entries().size()==1,"Percent is literal");
check(store.list("article","",0,"Chercheur_159").entries().isEmpty(),"Search stays within selected section");
store.change(moderator,action("hide",pinned));
check(store.list("notice","",0,"50%_exact").entries().isEmpty(),"Hidden search result excluded");
refuse("invalid",()->store.list("notice","",0,"x".repeat(121)));
var official=store.change(moderator,create(UUID.randomUUID().toString(),"","bulletin","Serveur159","Message officiel"));
check(store.list("bulletin","",0,"serveur159").entries().size()==1 && store.thread(official.id(),0).entry().equals(official),"Read server history");
refuse("forbidden",()->store.change(owner,action("hide",official)));
System.out.println("COMMUNITY159_SEARCH_PASS "+store.getClass().getSimpleName());
}
static Entry scenario(CommunityStore store) throws Exception {
var request=create(UUID.randomUUID().toString(),"","notice","Un pont","Du bois et des bras 🌳");
var post=store.change(owner,request);
@@ -92,7 +114,7 @@ public final class CommunitySmoke {
Path dir=Files.createTempDirectory("sanctuary-community-check-");
String server=UUID.randomUUID().toString();Path file=dir.resolve("community.json");
var store=new FileCommunityStore(file,server);var article=scenario(store);
var follower=tasks(store);
var follower=tasks(store);search(store);
var reopened=new FileCommunityStore(file,server);
check(reopened.following(follower).equals(store.following(follower)) && reopened.following(follower).size()==16,"Follow state survives restart");
check(reopened.thread(article.id(),0).entry().equals(article),"Durable restart");
@@ -102,7 +124,7 @@ public final class CommunitySmoke {
String url=System.getenv("SANCTUARY_COMMUNITY_TEST_JDBC");
if(url!=null){
var sql=new SqlCommunityStore(url,"root","",server);
var value=scenario(sql);tasks(sql);
var value=scenario(sql);tasks(sql);search(sql);
check(new SqlCommunityStore(url,"root","",server).thread(value.id(),0).entry().equals(value),"Database restart");
var isolated=new SqlCommunityStore(url,"root","",UUID.randomUUID().toString());
check(isolated.list("notice","",0).entries().isEmpty(),"Different server isolated");
@@ -0,0 +1,28 @@
package fr.koka.sanctuary.community;
import java.nio.file.*;
import java.util.*;
public final class ServerMetricsSmoke {
public static void main(String[] args) throws Exception {
Path root=Files.createTempDirectory("sanctuary-metrics-test");
String player="11111111-1111-4111-8111-111111111111",bot="22222222-2222-4222-8222-222222222222";
Files.createDirectories(root.resolve("stats"));
Files.writeString(root.resolve("stats/"+player+".json"),"{\"stats\":{\"minecraft:custom\":{\"minecraft:deaths\":12}}}");
var ledger=new ServerMetricsLedger(root,100);
var first=ledger.sample(3100,10000,Map.of(player,13L,bot,9L),Set.of(bot),1,true);
check(first.uptimeMillis()==3000 && first.deaths()==13 && first.onlinePlayers()==1,"imports offline deaths, counts current deaths, excludes actors");
ledger.sample(4100,11000,Map.of(),Set.of(),0,false);
var restarted=new ServerMetricsLedger(root,900000);
var next=restarted.sample(901000,9000000,Map.of(player,13L),Set.of(),1,true);
check(next.uptimeMillis()==5000 && next.deaths()==13,"downtime excluded and deaths not counted twice");
var death=restarted.sample(902000,9001000,Map.of(player,14L),Set.of(),1,true);
check(death.deaths()==14,"new death increments cumulative total");
Path file=root.resolve("data/sanctuary-server-metrics.json");Files.writeString(file,"corrupt");
try{restarted.sample(903000,9002000,Map.of(),Set.of(),0,false);throw new AssertionError("overwrite");}catch(java.io.IOException expected){}
check(Files.readString(file).equals("corrupt"),"external edit preserved");
try{new ServerMetricsLedger(root,0);throw new AssertionError("reset");}catch(IllegalArgumentException expected){}
System.out.println("SERVER_METRICS161_PASS");
}
private static void check(boolean ok,String message){if(!ok)throw new AssertionError(message);}
}
+1 -1
View File
@@ -1,6 +1,6 @@
name = "Sanctuary"
author = "KOKA99CAB"
version = "beta.158"
version = "beta.161"
pack-format = "packwiz:1.1.0"
[index]
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Local, isolated duo lab. No personal saves, accounts or launcher settings touched."""
import argparse
import datetime as dt
import json
import os
from pathlib import Path
import subprocess
import time
import uuid
import html
ROOT = Path(__file__).resolve().parents[1]
LAB = ROOT / "build" / "duo"
def create(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
path.write_text(text)
def prepare(args):
server = LAB / "server"
create(server / "server.properties", """server-ip=127.0.0.1
server-port=25575
online-mode=false
white-list=false
enforce-secure-profile=false
enable-query=false
enable-rcon=false
level-name=duo-flat-160
level-type=sanctuary_test:flat
level-seed=160
gamemode=creative
difficulty=peaceful
max-players=6
view-distance=4
simulation-distance=3
pause-when-empty-seconds=30
spawn-protection=0
motd=Sanctuary DUO — local test lab
""")
create(server / "eula.txt", "eula=true\n")
config = {"mode": args.storage, "serverId": args.server_id or str(uuid.uuid4()),
"jdbcUrl": args.jdbc, "user": "root", "passwordEnv": "SANCTUARY_COMMUNITY_DB_PASSWORD"}
create(server / "config/sanctuary-community.json", json.dumps(config, indent=2) + "\n")
create(LAB / "client/config/sanctuary-shaders.json", '{"enabled":false}\n')
create(LAB / "client/options.txt", "renderDistance:6\nsimulationDistance:4\nmaxFps:30\nenableVsync:true\nguiScale:2\nlang:fr_fr\npauseOnLostFocus:false\n")
print("Prepared", LAB, "— existing files preserved. Server: 127.0.0.1:25575")
def launch(args):
java_home = os.environ.get("JAVA_HOME")
if not java_home:
java_home = subprocess.check_output(["/usr/libexec/java_home", "-v", "25"], text=True).strip()
java = str(Path(java_home) / "bin/java")
argfile = LAB / (args.command + ".args")
if not argfile.is_file():
raise SystemExit("Run ./gradlew :sanctuary-test:exportDuoLaunch first.")
if not 512 <= args.memory <= (2048 if args.command == "server" else 3072):
raise SystemExit("Memory must be 512–2048 MiB (server) or 512–3072 MiB (client).")
# JVM overrides must precede the main class, therefore rewrite a temporary argfile.
lines = argfile.read_text().splitlines()
lines = [f'"-Xmx{args.memory}m"' if line.startswith('"-Xmx') else line for line in lines]
if args.command == "client":
lines += ['"--quickPlayMultiplayer"', '"127.0.0.1:25575"']
runtime = LAB / (args.command + "-runtime.args")
runtime.write_text("\n".join(lines) + "\n")
os.chdir(LAB / args.command)
print(f"Starting {args.command}: heap cap {args.memory} MiB; native/GPU memory is additional.", flush=True)
os.execv(java, [java, "@" + str(runtime)])
def record(args):
if not 1 <= args.seconds <= 300:
raise SystemExit("Sessions are limited to 1–300 seconds.")
windows = json.loads(subprocess.check_output(["swift", str(ROOT / "scripts/minecraft_windows.swift")], text=True))
if args.window not in [window["id"] for window in windows]:
raise SystemExit("This ID is not a visible Minecraft window. Run the windows command first.")
# Explicit window ID prevents accidentally recording another screen or app.
session = LAB / "sessions" / dt.datetime.now().strftime("%Y%m%d-%H%M%S")
session.mkdir(parents=True)
create(session / "notes.md", "# Séance duo\n\nScène :\nAttendu :\nObservations ergonomiques :\nVérifications fonctionnelles :\nDécisions :\n")
(session / "manifest.json").write_text(json.dumps({"window": args.window, "duration": args.seconds,
"interval": 2, "audio": False, "format": "timestamped PNG sequence", "started": dt.datetime.now().astimezone().isoformat()}, indent=2))
print("Recording selected Minecraft window only, no audio:", session, flush=True)
started = time.monotonic()
try:
while time.monotonic() - started < args.seconds:
elapsed = time.monotonic() - started
output = session / f"{elapsed:07.2f}.png"
subprocess.run(["/usr/sbin/screencapture", "-x", "-o", "-l", str(args.window), str(output)], check=True)
time.sleep(2)
except KeyboardInterrupt:
pass
frames = sorted(session.glob("*.png"))
rows = "\n".join(f'<figure><figcaption>{html.escape(frame.stem)} s</figcaption><a href="{frame.name}"><img loading="lazy" src="{frame.name}"></a></figure>' for frame in frames)
(session / "index.html").write_text('<!doctype html><meta charset="utf-8"><title>Séance Sanctuary</title>'
'<style>body{background:#171c1a;color:#f2f2e7;font:16px system-ui;margin:24px}main{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:20px}figure{margin:0}img{width:100%}</style>'
'<h1>Séance Sanctuary</h1><p>Une capture toutes les deux secondes. Cliquer pour voir en grand.</p><main>' + rows + '</main>')
print("Session saved:", session)
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
setup = sub.add_parser("prepare")
setup.add_argument("--storage", choices=["file", "database"], default="file")
setup.add_argument("--server-id")
setup.add_argument("--jdbc", default="jdbc:mariadb://127.0.0.1:33077/sanctuary_community_tasks158_interop")
sub.add_parser("windows", help="List only visible Minecraft window IDs")
for command, memory in [("server", 768), ("client", 2048)]:
item = sub.add_parser(command)
item.add_argument("--memory", type=int, default=memory)
capture = sub.add_parser("record")
capture.add_argument("--window", type=int, required=True, help="Verified Minecraft window ID; never the desktop")
capture.add_argument("--seconds", type=int, default=120)
args = parser.parse_args()
if args.command == "prepare":
prepare(args)
elif args.command == "windows":
subprocess.run(["swift", str(ROOT / "scripts/minecraft_windows.swift")], check=True)
elif args.command == "record":
record(args)
else:
launch(args)
if __name__ == "__main__":
main()
+13
View File
@@ -0,0 +1,13 @@
import CoreGraphics
import Foundation
// Only list Minecraft/Java game windows, never titles from other applications.
let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []
let matches = windows.compactMap { window -> [String: Any]? in
let owner = window[kCGWindowOwnerName as String] as? String ?? ""
let title = window[kCGWindowName as String] as? String ?? ""
guard ["java", "Minecraft"].contains(owner), title.hasPrefix("Sanctuary - ") || title.hasPrefix("Minecraft") else { return nil }
return ["id": window[kCGWindowNumber as String] ?? 0, "pid": window[kCGWindowOwnerPID as String] ?? 0, "title": title]
}
let data = try JSONSerialization.data(withJSONObject: matches, options: [.prettyPrinted, .sortedKeys])
print(String(data: data, encoding: .utf8)!)