diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index faae431..77ba754 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,7 @@ jobs: - run: python -m playwright install --with-deps chromium - run: npm run assets:export && npm run assets:review - run: python tests/browser.py + - run: python tests/city_life_browser.py - run: python tests/districts_browser.py - run: npm run build:lab - run: python tests/lab_browser.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f1e6aec..0e6518b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # 0.6.0 — Ouverture équitable et essais locaux +## Ville réactive — suite de 0.6.1 + +- Continuité de circulation lors des investissements, agents locaux bornés et bus aux abribus. +- Grues articulées sans duplication, effets annulés lorsque leur cause disparaît. +- Fiche accessible « La ville réagit » et cadrage caméra du terrain. +- 13 régressions Node et recette graphique dédiée ; règles, protocole et casino inchangés. +- Voir `docs/CITY_RESPONSE.md` pour les preuves et limites ; aucune fusion automatique. + - Six départs versionnés dans le lab ; classique et comp-60 facultatif dans le jeu. Défaut classique conservé, protocole/sauvegarde v5. - Choix préenregistré, confirmation sur graines indépendantes, négociation automatique et sensibilités ; 19 800 trajectoires. Résultat à deux joueurs défavorable, autres scénarios non concluants conservés. - Politique de propositions réciproques, indicateurs de transactions, sans accès aux futurs dés. diff --git a/README.md b/README.md index 99e6523..f760075 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,10 @@ npm run preview Les deux HTML autonomes s'ouvrent directement dans un navigateur de bureau. Le lab inclut son Worker et ne touche pas aux sauvegardes du jeu. Le jeu autonome permet le mode local ; le multijoueur nécessite une signalisation. Le lab est exclu du build ordinaire et de CrazyGames. +## Suite de la ville vivante + +Circulation et passants à identités stables, virages arrondis, bus marquant leurs arrêts, grues articulées et fiche **La ville réagit**, avec inspection caméra. L’économie et les crédits du casino restent inchangés. [Périmètre, budgets et validation](docs/CITY_RESPONSE.md). + ## 0.6.1 : correctifs de fiabilité Exports d’essais limités à la partie enregistrée, résultats conservés après resynchronisation, envois réseau en file bornée plutôt qu’abandonnés en cas de congestion, handshake relancé, suspension propagée aux autres pairs et snapshots anciens refusés. **118 tests Node**, dont 21 nouveaux contrôles ciblés. Les montants, dés et options de départ ne changent pas. [Détails de l’audit](docs/BUGFIX_AUDIT_0_6_1.md) et [preuve de validation](docs/VALIDATION.md). diff --git a/docs/CITY_RESPONSE.md b/docs/CITY_RESPONSE.md new file mode 100644 index 0000000..b42267b --- /dev/null +++ b/docs/CITY_RESPONSE.md @@ -0,0 +1,38 @@ +# Ville réactive — continuité des habitants et lecture du quartier + +## Base préservée + +Cette tranche part du `main` **b5f547c97ce8387f1c31b25bef3a29952d0a94a7**, après la fusion artistique #9. Elle ne réimporte pas l'ancienne 0.4, ne fusionne pas `feat/engagement-rhythm-0-7`, ne modifie aucun kit artistique et n'annonce pas la phase 4 terminée. Livraison sur `feat/city-response-continuity`, sans fusion automatique dans `main`. + +Moteur, protocole v5, dés, négociations, laboratoire, prix, casino et sauvegardes sont inchangés. La version du paquet reste 0.6.1 : ce n'est pas une nouvelle version des règles. + +## Ce qui change + +`src/scene/city-life.js` garde des identités et des positions locales stables pour les voitures et les piétons. Avant, recalculer les poids de circulation et diviser les positions par un nouveau nombre d'agents pouvait téléporter des véhicules lors d'un investissement. Maintenant, l'économie change leurs objectifs de densité et de vitesse, pas leur position courante. Les arrivées et départs visuels sont progressifs. Les virages ont une tangente continue. Les bus marquent une pause de 2,5 secondes aux deux abribus existants. + +Les passants sont répartis entre les parcelles actives, davantage sur les terrains développés. Leur identité ne change pas quand un autre terrain est acheté. Une hypothèque fait progressivement disparaître le passage local. De brèves pauses près des commerces rythment les déplacements ; ce n'est pas un calcul de clientèle, de revenus ni une navigation évitant tous les obstacles. + +Les grues ont un mât fixe, une flèche orientable et un câble de levage. Leur hauteur suit le niveau concerné. Plusieurs investissements rapides dans le même terrain renouvellent une seule grue, pas une pile de grues. Vente, hypothèque ou perte du quartier annulent les effets devenus obsolètes. **Le bâtiment économique est toujours mis à jour immédiatement** : pas d'assemblage étage par étage dans cette tranche. + +La fiche **La ville réagit** décrit le terrain sélectionné : ouverture des commerces, activité accrue, quartier réuni ou mise en veille. Sa jauge 0–8 représente uniquement l'intensité de la projection visuelle, pas un nombre réel d'habitants ni un multiplicateur économique. Le bouton **Voir en ville** cadre le terrain sans déplacer de pion ni interrompre la table. Le retour caméra est disponible. La fiche reste consultable sans WebGL ; seul le bouton caméra est désactivé. Sur mobile, elle occupe toute la largeur et le bouton mesure au moins 44 px de haut. + +## Budgets et isolation + +18 voitures et 48 piétons visibles au maximum en qualité élevée ; 6 et 12 en légère, plus deux bus. Les slots locaux sont bornés à 18 voitures et 128 piétons potentiels (8 par parcelle), dont au plus 48 sont affichés. Le changement de qualité peut retirer immédiatement du détail mais ne déplace pas les agents conservés. + +Le temps est local, plafonné à 0,1 seconde par pas ; il ne rattrape pas une absence d'onglet ou une pause. Aucun accès au générateur aléatoire du jeu, réseau ou stockage. Les mouvements réduits et la ville figée désactivent ces animations. Les maillages sont réutilisés, y compris ceux des pièces de grue. La limite de soumission existante de 30 images/s est conservée ; elle ne garantit pas 30 FPS sur téléphone. + +Casino : uniquement les crédits fictifs de la partie ; aucune nouvelle monnaie, recharge publicitaire, conversion, retrait ou XP. Les gains/pertes restent bien ceux du capital de la partie. L'aléatoire P2P demeure public et prédictible, pas un dispositif anti-triche. + +## Validation + +Localement : **223 tests Node réussis**, dont 13 nouvelles régressions ; 83 fichiers JavaScript contrôlés ; construction statique et HTML autonome réussie. Les tests ajoutés caractérisent notamment l'ancien saut de position, la continuité des routes, les quotas, les pauses, les bus, le cache GPU simulé, les effets périmés et l'absence de mutation économique. + +Le navigateur local refuse la navigation sur localhost (`ERR_BLOCKED_BY_ADMINISTRATOR`). Aucun contournement : la recette réelle est exécutée par GitHub Actions. `tests/city_life_browser.py` ajoute les captures de terrain disponible, construction, quartier développé de nuit, hypothèque et mobile émulé, ainsi que les contrôles caméra, mode sans WebGL, HTML autonome et arrêt des dessins. La CI ordinaire garde tous ses contrôles et ajoute ce script ; aucune assertion d'origine n'est supprimée. + +Vérifier la conclusion du run et `test-results/city-response/report.json`, pas la seule présence d'un artefact. Les fixtures graphiques sont contrôlées ; ce ne sont pas des participants humains ni des benchmarks sur appareil réel. La CI habituelle conserve les parcours WebRTC et les sessions complètes Classique / comp-60. Les performances GPU matériel, Safari/iOS, téléphones physiques et TURN restent à valider. Aucun déploiement de production ou publication CrazyGames. + +Références techniques consultées : +- https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame +- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-reduced-motion +- https://docs.crazygames.com/requirements/technical/ diff --git a/docs/validation/CITY_RESPONSE_2026-09-07.md b/docs/validation/CITY_RESPONSE_2026-09-07.md new file mode 100644 index 0000000..7f04e14 --- /dev/null +++ b/docs/validation/CITY_RESPONSE_2026-09-07.md @@ -0,0 +1,48 @@ +# Recette de la ville réactive — 7 septembre 2026 + +## Sources et publication + +Base conservée : `b5f547c97ce8387f1c31b25bef3a29952d0a94a7` sur main. +Code livré : `b2b1d805981b2b7f54291fcca8b60050be099850` sur `feat/city-response-continuity`. +Arbre exact testé : `78b8ec7b9f1e5aea747bcfa2460ecb32f678a80e`. + +Le [run de recette 34165090921](https://github.com/mc-datanalytics/dicestrict/actions/runs/34165090921) a réussi **toutes ses étapes de test**, mais sa conclusion globale est **failure** : l'étape finale de push a été refusée parce que le jeton du runner ne possède pas la permission de modifier les workflows. Ce n'est pas un échec fonctionnel, et ce run ne doit pas être présenté comme entièrement vert. + +La publication de ce même commit a ensuite été effectuée par le connecteur GitHub autorisé, en avance rapide et sans force. Aucune permission n'a été élargie. Le `source.tar` récupéré dans l'artefact a été indexé localement : son `git write-tree` correspond exactement à l'arbre testé et publié ci-dessus. Les fichiers temporaires de livraison et leur workflow ont été retirés du résultat. Main et les autres branches n'ont pas été modifiés. + +## Résultats exécutés + +| Suite | Résultat | +| --- | --- | +| `npm run check` | 83 fichiers JavaScript, syntaxe et imports valides | +| `npm test` | 223 tests réussis, 0 échec, 0 ignoré | +| `npm run build` | Client ESM statique et HTML autonome construits ; HTML : 323 002 octets | +| `assets:export` / `assets:review` | Exports et revue des modèles réussis | +| `tests/browser.py` | 28 contrôles réussis ; `pageErrors: []` | +| `tests/city_life_browser.py` | 9 contrôles réussis ; `pageErrors: []` | +| `tests/districts_browser.py` | 7 contrôles réussis ; aucune erreur remontée | +| `build:lab` / `tests/lab_browser.py` | Construction et 7 contrôles réussis ; `pageErrors: []` | + +Les nouveaux parcours passent par de vrais boutons d'achat, de construction équilibrée, de revente et d'hypothèque. Ils vérifient la stabilité des positions lors de l'achat, les grues articulées, le cadrage caméra, une image WebGL2 non uniforme sans erreur GL, les plafonds de population, la réutilisation des maillages pendant 600 pas d'animation et l'arrêt des dessins en mode figé. Ils couvrent aussi le viewport tactile émulé de 390 px, l'accès sans WebGL et le fichier autonome en `file://`. + +La suite existante a notamment revérifié les négociations et le casino entre deux contextes Chromium reliés par de vrais DataChannels WebRTC. Le pari débite/crédite le même capital de partie sur les deux pairs, sans modifier le générateur des dés du plateau. Aucune monnaie de compte, aucun achat de crédits, aucun retrait ni XP n'a été ajouté. + +## Preuves récupérées et inspectées + +[Artefact 10034119092 — sources, builds et rapports](https://github.com/mc-datanalytics/dicestrict/actions/runs/34165090921/artifacts/10034119092), rétention 14 jours. +SHA-256 de l'archive téléchargée : `ddaeca0f8971999540ceca7ca91616caa4625be2ade8c8604682221cb98ae7f9`. + +- `test-results/city-response/report.json` : résultats et diagnostics GPU. +- `test-results/city-response/01-terrain-disponible.png` à `05-mobile-emule.png` : captures du client exécuté, pas des maquettes générées. +- `test-results/browser-report.json`, `test-results/districts/report.json`, `test-results/lab-browser-report.json` : suites conservées. +- `delivery-logs/` : contrôle statique, tests Node et construction. + +Les captures de construction, de quartier développé la nuit et de mobile ont été ouvertes et inspectées. Le style reste celui du jeu low-poly existant ; ce n'est pas le rendu cinématique des maquettes conceptuelles. + +## Limites de cette preuve + +Environnement : runner GitHub Linux, Node 22, Playwright 1.57 et Chromium 143.0.7499.4, WebGL2 via SwiftShader. Les tests réseau utilisent deux contextes isolés sur une même machine, pas deux réseaux distants. Les états initiaux sont des fixtures contrôlées, pas des parties humaines observées. + +Les sessions WebRTC complètes Classique / comp-60 restent dans la CI habituelle et n'ont pas été exécutées par ce workflow de livraison. Leur résultat appartient au run de PR correspondant, pas à la présente preuve. Aucun test existant n'a été supprimé ou affaibli. + +Pas de mesure de FPS sur GPU matériel ou téléphone réel, ni validation Safari/iOS ou TURN. Les bâtiments changent encore de niveau immédiatement : les grues ne constituent pas une construction étage par étage. Pas de navigation complète évitant les obstacles. L'interface mobile conserve des limites de cadrage et de densité malgré l'absence de débordement horizontal. Aucun déploiement de production, arbitrage serveur de récompenses ou publication CrazyGames. diff --git a/src/scene/board-scene.js b/src/scene/board-scene.js index 50230a8..012f7b3 100644 --- a/src/scene/board-scene.js +++ b/src/scene/board-scene.js @@ -46,7 +46,7 @@ class BoardScene { this.canvas=canvas;this.onSelect=onSelect;this.reduced=matchMedia('(prefers-reduced-motion: reduce)').matches; this.renderer=new Renderer(canvas,atlas());this.staticMesh=this.renderer.mesh(cityGeometry());this.tokens=COLORS.map(c=>this.renderer.mesh(token(c)));this.diceMesh=this.renderer.mesh(dice()); this.city=new LivingCity(this.renderer);this.ambientTime=0;this.lastAmbientFrame=null;this.living=true;this.dayMode='auto';this.weather=true; - this.angle=.50;this.pitch=.85;this.zoom=1;this.time=0;this.selected=1;this.paths=[];this.lastRoll=-99999;this.state=null;this.dirty=true; + this.viewTarget=[0,.3,0];this.angle=.50;this.pitch=.85;this.zoom=1;this.time=0;this.selected=1;this.paths=[];this.lastRoll=-99999;this.state=null;this.dirty=true; this.abort=new AbortController();const opts={signal:this.abort.signal}; canvas.addEventListener('webglcontextlost',e=>{e.preventDefault();this.lost=true;cancelAnimationFrame(this.raf);onError('Le contexte graphique est interrompu. Restauration en attente ; la partie reste accessible.');},opts); canvas.addEventListener('webglcontextrestored',()=>{ @@ -74,11 +74,15 @@ class BoardScene { if(living!==undefined)this.living=living;if(dayMode)this.dayMode=dayMode;if(weather!==undefined)this.weather=weather; this.city.configure(settings);this.dirty=true; } - view(mode){if(mode==='top'){this.pitch=1.42;this.angle=0;this.zoom=1.1;}else if(mode==='reset'){this.pitch=.85;this.angle=.50;this.zoom=1;}else this.zoom=clamp(this.zoom*(mode==='in'?1.12:.89),.72,1.5);this.dirty=true;} + view(mode){if(mode==='reset'||mode==='top')this.viewTarget=[0,.3,0];if(mode==='top'){this.pitch=1.42;this.angle=0;this.zoom=1.1;}else if(mode==='reset'){this.pitch=.85;this.angle=.50;this.zoom=1;}else this.zoom=clamp(this.zoom*(mode==='in'?1.12:.89),.72,1.5);this.dirty=true;} + focusParcel(id){ + const p=this.city.city?.parcels.find(p=>p.id===id);if(!p)return false; + this.viewTarget=[p.x,.65,p.z];this.zoom=1.5;this.pitch=.85;this.dirty=true;return true; + } setSelected(id){this.selected=id;this.updateOwnership();this.dirty=true;} setState(s){ const now=performance.now(); - const sameMatch=this.state?.id===s.id; + const sameMatch=this.state?.id===s.id;if(!sameMatch)this.viewTarget=[0,.3,0]; if(this.state&&s.revision!==this.state.revision&&s.dice&&(s.players.some((p,i)=>p.position!==this.state.players[i]?.position))){this.lastRoll=now;} this.paths=s.players.map((p,i)=>{ if(sameMatch && p.position===this.state.players[i]?.position && this.paths[i])return this.paths[i]; @@ -122,7 +126,7 @@ class BoardScene { const rect=this.canvas.getBoundingClientRect(),aspect=rect.width/Math.max(rect.height,1); this.renderer.resize(rect.width,rect.height,Math.min(devicePixelRatio||1,this.renderer.shadows?1.7:1.0)); const extent=(aspect<1.15?10.1/aspect:9.0)/this.zoom; - const target=this.captureTarget??[0,.3,0]; + const target=this.captureTarget??this.viewTarget; const eye=[target[0]+Math.sin(this.angle)*24*Math.cos(this.pitch),target[1]-.3+Math.sin(this.pitch)*24,target[2]+Math.cos(this.angle)*24*Math.cos(this.pitch)]; this.renderer.camera=eye;this.city.marina.selectDetail(rect.height/(2*extent));this.city.districts.selectDetail(rect.height/(2*extent));this.city.civic.selectDetail(rect.height/(2*extent));this.city.harmony.selectDetail(rect.height/(2*extent)); this.vp=multiply(ortho(-extent*aspect,extent*aspect,-extent,extent,.1,80),lookAt(eye,target)); diff --git a/src/scene/city-life.js b/src/scene/city-life.js new file mode 100644 index 0000000..6e9d1bf --- /dev/null +++ b/src/scene/city-life.js @@ -0,0 +1,131 @@ +/** Local visual simulation. Never reads the game RNG, writes a save, or sends a packet. */ +import { cityBudget } from './city-state.js'; + +const CAR_LIMIT = 18, WALKER_LIMIT = 48, WALKERS_PER_PARCEL = 8; +const mod = (n, d) => ((n % d) + d) % d; +const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n)); +const approach = (value, target, delta) => value < target ? Math.min(target, value + delta) : Math.max(target, value - delta); + +/** Distance in world units, with continuous position AND tangent through rounded corners. */ +function roundedRoute(distance, radius = 4.48, corner = .34) { + if (!Number.isFinite(distance) || !Number.isFinite(radius) || !Number.isFinite(corner) || radius <= 0 || corner <= 0 || corner >= radius) throw Error('Invalid city route'); + const straight = 2 * (radius - corner), arc = Math.PI * corner / 2, segment = straight + arc; + const d = mod(distance, 4 * segment), side = Math.floor(d / segment), u = d - side * segment; + let x, z, dx, dz; + if (u < straight) { x = radius - corner - u; z = radius; dx = -1; dz = 0; } + else { + const angle = Math.PI / 2 + (u - straight) / corner; + x = -radius + corner + corner * Math.cos(angle); z = radius - corner + corner * Math.sin(angle); + dx = -Math.sin(angle); dz = Math.cos(angle); + } + const c = Math.cos(side * Math.PI / 2), s = Math.sin(side * Math.PI / 2); + return { x: c * x - s * z, z: s * x + c * z, yaw: Math.atan2(c * dx - s * dz, s * dx + c * dz) }; +} +function routeLength(radius = 4.48, corner = .34) { return 8 * (radius - corner) + 2 * Math.PI * corner; } + +/** Weighted fair allocation, with stable per-parcel identities and a fixed global cap. */ +function pedestrianAllocation(city, limit) { + const counts = new Map(city.parcels.map(p => [p.id, 0])); + const active = city.parcels.filter(p => p.activity > 0).slice().sort((a, b) => a.id - b.id); + for (let n = 0; n < Math.min(WALKER_LIMIT, Math.max(0, limit)); n++) { + let best = null, score = -1; + for (const p of active) { + const count = counts.get(p.id), priority = p.activity / (count + 1); + if (count < WALKERS_PER_PARCEL && priority > score) { best = p; score = priority; } + } + if (!best) break; + counts.set(best.id, counts.get(best.id) + 1); + } + return counts; +} + +/** Stable slots keep existing vehicles/people in place when ownership or budgets change. */ +class CityLife { + constructor() { + this.quality = 'high'; this.reduced = false; this.living = true; this.running = true; this.lastTime = null; this.elapsed = 0; + this.cars = []; this.walkers = []; this.buses = []; this.city = null; + } + configure({ quality = this.quality, reduced = this.reduced, living = this.living } = {}) { + const running = living && !reduced; + if (running !== this.running) this.lastTime = null; // Never catch up time spent paused. + this.running = running; this.quality = quality; this.reduced = reduced; this.living = living; + if (this.city) this.retarget(); + } + setCity(city, reset = false) { + this.city = city; + if (reset || !this.cars.length) { + this.lastTime = null; this.elapsed = 0; + this.cars = Array.from({ length: CAR_LIMIT }, (_, i) => ({ id: `car-${i}`, slot: i, distance: mod(i * .61803398875, 1) * routeLength(), speed: .7, scale: 0, target: false })); + this.walkers = city.parcels.flatMap(p => Array.from({ length: WALKERS_PER_PARCEL }, (_, j) => ({ id: `walker-${p.id}-${j}`, parcelId: p.id, slot: j, distance: mod(p.id * .37 + j * .61803398875, 1) * routeLength(.55, .12), scale: 0, target: false }))); + this.buses = [0, 1].map(i => ({ id: `bus-${i}`, distance: i * routeLength(6.98, .34) / 2, wait: 0 })); + } + this.retarget(); + if (reset) { for (const a of [...this.cars, ...this.walkers]) a.scale = a.target ? 1 : 0; } + } + retarget() { + const budget = cityBudget(this.city, this.quality); // Simulation population, not account data. + this.carCap = this.quality === 'low' ? 6 : CAR_LIMIT; + this.walkerCap = this.quality === 'low' ? 12 : WALKER_LIMIT; + this.parcels = new Map(this.city.parcels.map(p => [p.id, p])); + const counts = pedestrianAllocation(this.city, budget.pedestrians); + for (const a of this.cars) { a.target = a.slot < budget.cars; if (a.slot >= this.carCap) a.scale = 0; } + for (const a of this.walkers) a.target = a.slot < counts.get(a.parcelId); + // Lowering quality may remove detail immediately, but never repositions survivors. + const visible = this.walkers.filter(a => a.scale > 0).sort((a, b) => Number(b.target) - Number(a.target)); + for (const a of visible.slice(this.walkerCap)) a.scale = 0; + } + updatePopulation(agents, cap, dt) { + for (const a of agents) if (!a.target) a.scale = approach(a.scale, 0, dt * 1.5); + let occupied = agents.filter(a => a.scale > 0).length; + for (const a of agents) if (a.target) { + if (a.scale === 0) { if (occupied >= cap) continue; occupied++; } + a.scale = approach(a.scale, 1, dt * 1.5); + } + } + localActivity(position) { + let activity = 0; + // Soft distance weighting avoids an abrupt speed change at parcel boundaries. + for (const p of this.city.parcels) { + const dx = position.x - p.x * (4.48 / 3.64), dz = position.z - p.z * (4.48 / 3.64); + activity = Math.max(activity, p.activity / (1 + (dx * dx + dz * dz) * 2)); + } + return activity; + } + step(seconds) { + if (!Number.isFinite(seconds)) throw Error('Invalid city animation time'); + if (!this.city || !this.running) { this.lastTime = null; return { cars: [], pedestrians: [], buses: [] }; } + const dt = this.lastTime === null ? 0 : clamp(seconds - this.lastTime, 0, .1); + this.lastTime = seconds; this.elapsed += dt; + this.updatePopulation(this.cars, this.carCap, dt); + this.updatePopulation(this.walkers, this.walkerCap, dt); + const cars = [], pedestrians = [], buses = []; + for (const a of this.cars) if (a.scale > 0) { + const target = .85 / (1 + .15 * this.localActivity(roundedRoute(a.distance))); + a.speed += (target - a.speed) * (1 - Math.exp(-dt * 3)); + a.distance = mod(a.distance + a.speed * dt, routeLength()); + cars.push({ id: a.id, slot: a.slot, scale: a.scale, speed: a.speed, ...roundedRoute(a.distance) }); + } + for (const a of this.walkers) if (a.scale > 0) { + const p = this.parcels.get(a.parcelId); + // A brief café pause on developed parcels. Local decor only; no extra income. + const visiting = p.active && p.level > 0 && mod(this.elapsed + a.slot * 3.7 + p.id, 19) < 2.3; + a.distance = mod(a.distance + (visiting ? 0 : .105 + (a.slot % 3) * .012) * dt, routeLength(.55, .12)); + const q = roundedRoute(a.distance, .55, .12); + pedestrians.push({ id: a.id, parcelId: p.id, slot: a.slot, scale: a.scale, visiting, x: p.x + q.x, z: p.z + q.z, yaw: q.yaw }); + } + const r = 6.98, segment = routeLength(r) / 4; + const stops = [segment + r - .34 - 1.2, 3 * segment + r - .34 + 1.2]; + for (const a of this.buses) { + if (a.wait > 0) a.wait = Math.max(0, a.wait - dt); + else { + const travel = .95 * dt, length = routeLength(r); + const ahead = stops.map(stop => ({ stop, gap: mod(stop - a.distance, length) })).filter(p => p.gap > 1e-7 && p.gap <= travel).sort((a, b) => a.gap - b.gap)[0]; + if (ahead) { a.distance = ahead.stop; a.wait = 2.5; } + else a.distance = mod(a.distance + travel, length); + } + buses.push({ id: a.id, waiting: a.wait > 0, ...roundedRoute(a.distance, r) }); + } + return { cars, pedestrians, buses }; + } +} +export { CityLife, roundedRoute, routeLength, pedestrianAllocation, CAR_LIMIT, WALKER_LIMIT }; diff --git a/src/scene/living-city.js b/src/scene/living-city.js index 1cb4577..b29f59c 100644 --- a/src/scene/living-city.js +++ b/src/scene/living-city.js @@ -1,10 +1,11 @@ +import { CityLife } from './city-life.js'; import { Harmony, HARMONY_LOTS } from './harmony.js'; import { CivicCenter } from './civic.js'; import { Districts, DISTRICT_LOTS } from './districts.js'; import { Marina, MARINA_LOTS } from './marina.js'; import { Geometry } from './geometry.js'; import { model } from './math.js'; -import { deriveCity, cityTransitions, squareRoute, trafficPosition, cityBudget } from './city-state.js'; +import { deriveCity, cityTransitions, squareRoute, cityBudget } from './city-state.js'; const stone='#f3e7cc', ink='#315e55', gold='#e7be66', glass='#8bc4c3'; function tree(g,x,z,s=.8) { @@ -123,37 +124,44 @@ function person(color) { g.block([-.019,.021,0],[.018,.05,.026],ink);g.block([.019,.021,0],[.018,.05,.026],ink);return g; } function crane() { - const g=new Geometry();g.block([0,.60,0],[.07,1.2,.07],gold); - for(let y=.1;y<1.2;y+=.18){g.block([0,y,0],[.13,.025,.13],stone);} - g.block([.21,1.21,0],[.94,.065,.08],gold); - g.block([.63,.93,0],[.012,.55,.012],ink); - g.block([.63,.63,0],[.08,.025,.035],gold); - g.block([-.24,1.16,0],[.16,.16,.16],ink);return g; + const g=new Geometry();g.block([0,.6,0],[.055,1.2,.055],gold); + for(let y=.08;y<1.2;y+=.16)g.block([0,y,0],[.105,.023,.105],stone); + g.block([0,.04,0],[.22,.08,.22],ink);return g; } +function craneJib() { + const g=new Geometry();g.block([.18,0,0],[.96,.055,.075],gold); + g.block([-.25,-.06,0],[.16,.15,.15],ink); + g.block([.06,-.055,0],[.12,.10,.11],glass);return g; +} +function craneCable() { + const g=new Geometry();g.block([0,-.5,0],[.009,1,.009],ink); + g.block([0,-1,0],[.065,.025,.03],gold);return g; +} +function verticalModel(x,y,z,yaw,height) {const m=model(x,y,z,0,yaw);for(let i=4;i<8;i++)m[i]*=height;return m;} class LivingCity { constructor(renderer) { - this.renderer=renderer;this.city=null;this.elapsed=0;this.cranes=[];this.celebrations=[];this.quality='high';this.reduced=false;this.living=true; + this.renderer=renderer;this.life=new CityLife();this.city=null;this.elapsed=0;this.cranes=[];this.celebrations=[];this.quality='high';this.reduced=false;this.living=true; this.staticMesh=renderer.mesh(infrastructure());this.marina=new Marina(renderer);this.districts=new Districts(renderer);this.civic=new CivicCenter(renderer);this.harmony=new Harmony(renderer); this.cars=['#db947e','#e0c477','#79b2bb','#e6e3d5'].map(c=>renderer.mesh(vehicle(c))); this.bus=renderer.mesh(vehicle('#dcb875','bus'));this.ambulance=renderer.mesh(vehicle('#f1f1df')); this.people=['#567d77','#de917b','#b5a2ce','#d9b16b'].map(c=>renderer.mesh(person(c))); - this.crane=renderer.mesh(crane()); + this.crane=renderer.mesh(crane());this.jib=renderer.mesh(craneJib());this.cable=renderer.mesh(craneCable()); const droplet=new Geometry();droplet.block([0,0,0],[.008,.11,.008],'#abced6');this.drop=renderer.mesh(droplet); const spark=new Geometry();spark.block([0,0,0],[.035,.035,.035],gold);spark.material=0;this.spark=renderer.mesh(spark); const water=new Geometry();water.sphere([0,0,0],.028,'#c2e6dc',6,4);this.water=renderer.mesh(water); const siren=new Geometry();siren.material=3;siren.block([0,0,0],[.12,.04,.06],'#88cfe5');this.siren=renderer.mesh(siren); } - configure(settings) { this.harmony.configure(settings);this.civic.configure(settings);this.marina.configure(settings);this.districts.configure(settings);Object.assign(this,{quality:settings.quality??this.quality,reduced:settings.reduced??this.reduced,living:settings.living??this.living});if(this.reduced||!this.living){this.cranes=[];this.celebrations=[];} } + configure(settings) { this.harmony.configure(settings);this.civic.configure(settings);this.marina.configure(settings);this.districts.configure(settings);Object.assign(this,{quality:settings.quality??this.quality,reduced:settings.reduced??this.reduced,living:settings.living??this.living});this.life.configure({quality:this.quality,reduced:this.reduced,living:this.living});if(this.reduced||!this.living){this.cranes=[];this.celebrations=[];} } setState(s) { const next=deriveCity(s),reset=this.gameId!==s.id; if(!reset&&this.city?.signature===next.signature)return; const changes=cityTransitions(reset?null:this.city,next); - this.gameId=s.id;this.city=next;this.marina.setCity(next);this.districts.setCity(next);this.harmony.setCity(next); + this.gameId=s.id;this.city=next;this.life.setCity(next,reset);this.marina.setCity(next);this.districts.setCity(next);this.harmony.setCity(next); if(reset){this.cranes=[];this.celebrations=[];} if(!this.reduced&&this.living) { - for(const p of changes.construction)this.cranes.push({id:p.id,x:p.x,z:p.z,until:this.elapsed+6}); - for(const d of changes.celebrations)this.celebrations.push({group:d.id,until:this.elapsed+4}); - this.cranes=this.cranes.slice(-16);this.celebrations=this.celebrations.slice(-8); + for(const p of changes.construction){this.cranes=this.cranes.filter(c=>c.id!==p.id);this.cranes.push({id:p.id,owner:p.owner,tier:p.tier,x:p.x,z:p.z,until:this.elapsed+6});} + for(const d of changes.celebrations)this.celebrations.push({group:d.id,owner:d.owner,until:this.elapsed+4}); + this.cranes=this.cranes.filter(c=>{const p=next.parcels.find(p=>p.id===c.id);return p.active&&p.owner===c.owner&&p.tier>=c.tier;}).slice(-16);this.celebrations=this.celebrations.filter(c=>next.districts[c.group].owner===c.owner).slice(-8); } this.renderer.drop(this.parcelMesh);this.parcelMesh=this.renderer.mesh(parcelGeometry(next)); } @@ -163,21 +171,12 @@ class LivingCity { if(!this.city)return out; const running=this.living&&!this.reduced,t=running?seconds:0,budget=cityBudget(this.city,this.quality,this.reduced,this.living); this.stats={...budget,owned:this.city.owned,development:this.city.development}; - for(let i=0;ib.waiting).length; + for(const p of life.cars)out.push({mesh:this.cars[p.slot%4],model:model(p.x,.414,p.z,0,p.yaw,0,p.scale),noShadow:true}); + for(const p of life.buses)out.push({mesh:this.bus,model:model(p.x,.414,p.z,0,p.yaw),noShadow:true}); + for(const p of life.pedestrians)out.push({mesh:this.people[p.slot%4],model:model(p.x,.49+(p.visiting?0:Math.abs(Math.sin(t*7+p.slot))*.007),p.z,0,p.yaw,0,p.scale),noShadow:true}); if(running) { // Short surface metro trip between the two portals; local ambient clock only. const progress=(t%28)/28; @@ -194,7 +193,12 @@ class LivingCity { } } this.cranes=this.cranes.filter(c=>c.until>t); - for(const c of this.cranes)out.push({mesh:this.crane,model:model(c.x+.38,.48,c.z-.38,0,Math.sin(t*.4)*.35),noShadow:true}); + for(const c of this.cranes) { + const height=1.15+c.tier*.43,yaw=Math.sin(t*.4)*.4,x=c.x+.53,z=c.z-.53,rope=.28+(Math.sin(t*1.3)+1)*.22; + out.push({mesh:this.crane,model:verticalModel(x,.48,z,0,height/1.2),noShadow:true}, + {mesh:this.jib,model:model(x,.48+height,z,0,yaw),noShadow:true}, + {mesh:this.cable,model:verticalModel(x+Math.cos(yaw)*.6,.48+height,z-Math.sin(yaw)*.6,0,rope),noShadow:true}); + } this.celebrations=this.celebrations.filter(c=>c.until>t); for(const c of this.celebrations)for(const p of this.city.parcels.filter(p=>p.group===c.group))for(let i=0;i<6;i++) { const a=i*Math.PI/3+t*.8; diff --git a/src/ui/app.js b/src/ui/app.js index e7ed535..08f99bd 100644 --- a/src/ui/app.js +++ b/src/ui/app.js @@ -1,3 +1,4 @@ +import { renderCityInsight } from './city-view.js'; import { OPENINGS, validOpening, openingDescription } from '../game/opening.js'; import { PlaytestRecorder } from '../game/playtest.js'; import { botProposeDeal } from '../game/negotiator.js'; @@ -34,11 +35,11 @@ class App {
LA COLLECTION AURORA

Une ville.
Votre empire.

De grandes ambitions. Un lancer à la fois.

${icon('clock',20)}
MANCHE EN COURS01 / 12
${icon('globe',12)} Glissez pour explorer
- + ${casinoMarkup()}`; } - async initScene(){try{const {BoardScene}=await import("../scene/board-scene.js");this.scene=new BoardScene($('#board'),id=>this.select(id),message=>this.sceneError(message));this.scene.configure(this.settings);this.scene.setState(this.state);this.scene.setSelected(this.selected);$('.scene-loading')?.remove();}catch(e){this.sceneError(e.message);}} + async initScene(){try{const {BoardScene}=await import("../scene/board-scene.js");this.scene=new BoardScene($('#board'),id=>this.select(id),message=>this.sceneError(message));this.scene.configure(this.settings);this.scene.setState(this.state);this.scene.setSelected(this.selected);$('.scene-loading')?.remove();renderCityInsight(this);}catch(e){this.sceneError(e.message);}} sceneError(message){$('.scene-loading')?.remove();let fallback=$('.scene-error');if(!fallback){fallback=document.createElement('div');fallback.className='scene-error';$('.stage').append(fallback);}fallback.innerHTML=`${icon('globe',30)}

${esc(message)}

Le mode accessible permet de continuer à jouer.

${BOARD.map(t=>``).join('')}
`;} async initPlatform(){ const platform=await initializePlatform({onSettings:settings=>{this.platformMuted=Boolean(settings.muteAudio);if(this.platformMuted)this.audio?.suspend();},onInvite:code=>this.joinInvite(code)});this.platform=platform; @@ -71,6 +72,7 @@ class App { else if(action==='new-game')this.confirmNew();else if(action==='confirm-new'){this.startSolo();this.closeModal();} else if(action==='view'){this.topView=!this.topView;this.scene?.view(this.topView?'top':'reset');$('.view-button').innerHTML=`${icon('layers',14)}${this.topView?'Vue du dessus':'Vue 3D'}`;} else if(action==='zoom-in')this.scene?.view('in');else if(action==='zoom-out')this.scene?.view('out');else if(action==='reset-view'){this.topView=false;this.scene?.view('reset');$('.view-button').innerHTML=`${icon('layers',14)}Vue 3D`;} + else if(action==='focus-city'){if(this.scene?.focusParcel(this.selected)){this.topView=false;$('.view-button').innerHTML=`${icon('layers',14)}Vue 3D`;$('#board').scrollIntoView({block:'center',behavior:'auto'});$('#board').focus({preventScroll:true});}} else if(action==='players'||action==='assets'){this.tab=action;this.renderPlayers();} else if(action==='casino')openCasino(this);else if(action==='casino-close')closeCasino(); else if(action==='ambience'){this.settings.dayMode=({auto:'day',day:'night',night:'auto'})[this.settings.dayMode];this.scene?.configure(this.settings);safeWrite(SETTINGS,this.settings);this.showSettings();} @@ -107,6 +109,7 @@ class App { $('#players').innerHTML=s.players.map((p,i)=>`
${avatar(i,34)}
${esc(p.name)}${p.id===this.localId?'VOUS':p.bot?'IA':'JOUEUR'}${p.bankrupt?'Faillite':`${s.properties.filter(x=>x.owner===p.id).length} biens · ${money(netWorth(s,p.id))} de patrimoine`}
${money(p.cash)}₡
${currentPlayer(s).id===p.id&&s.phase!=='finished'?'':''}
`).join(''); } renderProperty(){ + renderCityInsight(this); const s=this.state,t=BOARD[this.selected],prop=s.properties[t.id],owner=s.players.find(p=>p.id===prop.owner),own=prop.owner===this.localId,canManage=currentPlayer(s).id===this.localId&&['roll','end'].includes(s.phase)&&!this.busy&&!this.session?.paused; const status=owner?(prop.mortgaged?'Hypothéqué':`À ${owner.id===this.localId?'vous':owner.name}`):t.kind==='lot'?'Disponible':'LA VIE À AURORA'; let actions='';if(own&&t.kind==='lot'){ diff --git a/src/ui/city-view.js b/src/ui/city-view.js new file mode 100644 index 0000000..b0a597e --- /dev/null +++ b/src/ui/city-view.js @@ -0,0 +1,38 @@ +/** Accessible, read-only explanation of what the selected parcel contributes visually. */ +import { deriveCity } from '../scene/city-state.js'; +import { BOARD } from '../game/board.js'; +import { icon } from './icons.js'; + +function parcelInsight(state, tileId) { + const city = deriveCity(state), p = city.parcels.find(p => p.id === tileId); + if (!p) return null; + const labels = ['Les commerces ouvrent', 'Les terrasses s’animent', 'Le quartier attire', 'Un pôle de vie']; + return { + id: p.id, name: BOARD[p.id].name, activity: p.activity, level: p.level, owner: p.owner, + title: !p.owner ? 'Un quartier à imaginer' : p.mortgaged ? 'L’activité est en veille' : labels[p.level], + detail: !p.owner ? 'L’achat ouvrira les commerces et fera arriver les premiers passants.' : p.mortgaged ? 'Les vitrines se ferment, le passage diminue. Le bâtiment reste en place.' : 'Les investissements attirent les passants et densifient la circulation locale.', + status: p.mortgaged ? 'Hypothéqué' : !p.owner ? 'Terrain disponible' : `Niveau ${p.level} / 3${p.complete ? ' · Quartier réuni' : ''}`, + ownerName: state.players.find(q => q.id === p.owner)?.name ?? '', + }; +} +function renderCityInsight(app) { + const root = app.root.querySelector('#city-insight'); + if (!root) return; + const p = parcelInsight(app.state, app.selected); + root.hidden = !p; + if (!p) { root.replaceChildren(); return; } + // Keep a focused control alive through a peer snapshot. No animation timer or aria-live spam. + if (!root.firstElementChild) root.innerHTML = `
LA VILLE RÉAGIT

${Array.from({length:8},()=>'').join('')}
Activité visuelle
`; + root.dataset.tile = String(p.id); + root.querySelector('h3').textContent = p.title; + root.querySelector('.city-insight-detail').textContent = p.detail; + root.querySelector('.city-insight-meta strong').textContent = p.status; + const meter = root.querySelector('[role="meter"]'); + meter.setAttribute('aria-valuenow', String(p.activity)); + meter.setAttribute('aria-valuetext', `${p.name} : ${p.activity} sur 8, activité visuelle uniquement`); + [...meter.children].forEach((bar, i) => bar.classList.toggle('lit', i < p.activity)); + const button = root.querySelector('button'); + button.disabled = !app.scene || Boolean(app.scene.lost); + button.title = app.scene ? `Centrer la caméra sur ${p.name}` : 'La description du quartier reste disponible sans WebGL'; +} +export { parcelInsight, renderCityInsight }; diff --git a/src/ui/styles.css b/src/ui/styles.css index ac9c276..f6466ce 100644 --- a/src/ui/styles.css +++ b/src/ui/styles.css @@ -44,3 +44,16 @@ .casino-warning{font-size:12px;line-height:1.65}.casino-warning strong{display:block;margin-bottom:5px}#casino-status{font-size:12px;background:#eaf0e7;border-radius:10px;padding:11px;line-height:1.5}#casino-form{display:grid;gap:14px}#casino-form fieldset{border:1px solid #d6dfce;border-radius:12px;padding:13px;display:flex;gap:26px}#casino-form legend{font-size:12px;font-weight:650}#casino-form label{font-size:12px;line-height:1.5}#casino-form fieldset label{display:flex;align-items:center;gap:7px}#casino-form input{accent-color:#386956;flex:none}#casino-form .stake-label{font-weight:650}#casino-stake{display:block;width:100%;background:white;border:1px solid #d5ded5;border-radius:10px;padding:11px;color:#254e42;font:inherit;margin-top:7px}.casino-confirm{display:flex;align-items:flex-start;gap:8px}.casino-odds{font-size:11px;line-height:1.7;color:#617565}.roulette-red{background:#ba7568}.roulette-black{background:#34544c}.roulette-green{background:#689d70}i.roulette-red,i.roulette-black{width:11px;height:11px;display:inline-block;border-radius:50%}.casino-settlement{display:flex;align-items:center;gap:12px;border:1px solid #d5ddc8;border-radius:10px;padding:11px;margin-bottom:14px}.casino-settlement>b{border-radius:50%;color:white;font-size:18px;padding:9px}.casino-settlement strong,.casino-settlement small{display:block}.casino-settlement strong{font-size:13px}.casino-settlement small{font-size:10px;line-height:1.5;margin-top:4px} @media(max-width:1100px){.city-life{top:189px;left:24px;font-size:10px}.final-lap{top:251px}} @media(max-width:700px){#casino-entry{grid-column:1/-1}.casino-entry{margin-top:0}.city-life{top:113px;left:18px;padding:6px 9px;max-width:190px;font-size:8px}.city-life small{font-size:7px}.final-lap{top:162px}.casino-panel{top:12px;right:12px;bottom:12px;width:calc(100vw - 24px);padding:18px}.casino-panel .deal-head h2{font-size:23px}.casino-panel .eyebrow{font-size:7px}.roulette-art{gap:20px;padding:15px}} + +/* Read-only neighborhood feedback; no new currency, offer modal or animation timer. */ +#city-insight{margin-top:14px;min-width:0} +.city-insight-card{border:1px solid #d9e2d0;border-radius:16px;background:linear-gradient(130deg,#edf3e4,#fafbf4);padding:14px;color:#264b3f} +.city-insight-heading{display:flex;justify-content:space-between;align-items:center;gap:8px} +.city-insight-heading>span{font-size:8px;font-weight:700;letter-spacing:1px;color:#597254} +.city-insight-heading button{display:flex;align-items:center;justify-content:center;gap:5px;min-height:44px;padding:7px;border:1px solid #cddbc6;border-radius:10px;background:#fafcf5;color:#31573f;font-size:10px} +.city-insight-card h3{font-size:16px;line-height:1.25;letter-spacing:-.3px;margin:9px 0 7px} +.city-insight-detail{font-size:11px;line-height:1.6;margin:0;color:#526b56} +.city-insight-meter{display:flex;gap:4px;margin:13px 0 8px;height:5px} +.city-insight-meter i{flex:1;border-radius:3px;background:#dce5d5}.city-insight-meter i.lit{background:#58835c} +.city-insight-meta{display:flex;flex-wrap:wrap;justify-content:space-between;gap:5px;font-size:9px;line-height:1.5}.city-insight-meta strong{font-weight:600}.city-insight-meta span{color:#5f735f} +@media(max-width:850px){#city-insight{grid-column:1/-1;margin-top:0}.city-insight-heading button{font-size:12px;padding:9px 12px}.city-insight-card h3{font-size:17px}.city-insight-detail{font-size:12px}.city-insight-meta{font-size:11px}} diff --git a/tests/city-life.test.mjs b/tests/city-life.test.mjs new file mode 100644 index 0000000..8215240 --- /dev/null +++ b/tests/city-life.test.mjs @@ -0,0 +1,140 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createGame, applyAction, fingerprint } from '../src/game/engine.js'; +import { BOARD } from '../src/game/board.js'; +import { deriveCity, trafficPosition } from '../src/scene/city-state.js'; +import { CityLife, roundedRoute, routeLength, pedestrianAllocation } from '../src/scene/city-life.js'; +import { LivingCity } from '../src/scene/living-city.js'; +import { BoardScene } from '../src/scene/board-scene.js'; +import { parcelInsight } from '../src/ui/city-view.js'; + +const fresh=()=>createGame([{id:'host',name:'Michaël'},{id:'guest',name:'Invité'}],42,{id:'city-response',casino:true}); +function developed(s=fresh()) {for(const t of BOARD)if(t.kind==='lot'){s.properties[t.id].owner='host';s.properties[t.id].level=3;}return s;} +const start=s=>{const life=new CityLife();life.setCity(deriveCity(s),true);life.step(0);return life;}; +const distance=(a,b)=>Math.hypot(a.x-b.x,a.z-b.z); +const renderer=()=>{const meshes=new Set();return {meshes,mesh(g){const data=g.typed();assert.ok(data.every(Number.isFinite));const m={count:g.indices?.length??data.length/12,bytes:data.byteLength+(g.indices?.byteLength??0)};meshes.add(m);return m;},drop(m){meshes.delete(m);}};}; + +test('rounded routes are periodic, finite, on the road and have continuous corner tangents',()=>{ + for(const r of [4.48,6.98]){ + const length=routeLength(r); + assert.ok(distance(roundedRoute(0,r),roundedRoute(length,r))<1e-12); + for(let d=-2;d=r-.24); + assert.ok(distance(p,q)<=.000101);assert.ok(Math.cos(p.yaw-q.yaw)>.99999); + } + } + for(const n of [NaN,Infinity,-Infinity])assert.throws(()=>roundedRoute(n)); + assert.throws(()=>roundedRoute(0,0));assert.throws(()=>roundedRoute(0,2,3)); +}); +test('existing cars never teleport when activity weights or population targets change',()=>{ + const s=fresh(),old=deriveCity(s),life=start(s),before=life.step(.1); + s.properties[1].owner='host';s.properties[2].owner='host';s.properties[1].level=s.properties[2].level=3; + const next=deriveCity(s); + // Characterize the old positional remapping: identical phase changed world position. + assert.ok(distance(trafficPosition(.2,old),trafficPosition(.2,next))>.1); + life.setCity(next);const now=life.step(.1); + assert.deepEqual(now.cars,before.cars); + for(let frame=2;frame<35;frame++){ + const previous=life.step((frame-1)*.1),current=life.step(frame*.1); + for(const car of previous.cars){const after=current.cars.find(c=>c.id===car.id);assert.ok(distance(car,after)<=.086);} + } + assert.ok(life.step(3.5).cars.length>before.cars.length); +}); +test('economic contraction retires slots; survivors keep identity and route position',()=>{ + const s=developed(),life=start(s);life.step(.1);const before=life.step(.2); + for(const p of s.properties){p.owner=null;p.level=0;p.mortgaged=false;} + life.setCity(deriveCity(s));assert.deepEqual(life.step(.2).cars,before.cars); + let after;for(let i=3;i<=15;i++)after=life.step(i*.1); + assert.equal(after.cars.length,3);assert.equal(after.pedestrians.length,0); + assert.deepEqual(after.cars.map(c=>c.id),['car-0','car-1','car-2']); +}); +test('weighted pedestrians favor active neighborhoods and never exceed allocation caps',()=>{ + const s=fresh();s.properties[1].owner='host';s.properties[4].owner='guest';s.properties[4].level=3; + const city=deriveCity(s),counts=pedestrianAllocation(city,12); + assert.ok(counts.get(4)>counts.get(1));assert.ok([...counts.values()].reduce((a,b)=>a+b,0)<=12); + assert.ok([...counts.values()].every(n=>n<=8));assert.equal(counts.get(2),0); + s.properties[4].level=0;s.properties[4].mortgaged=true; + assert.equal(pedestrianAllocation(deriveCity(s),12).get(4),0); +}); +test('pedestrian slots keep their position when a different parcel changes',()=>{ + const s=developed(),life=start(s);life.step(.1);const before=life.step(.2); + s.properties[8].level=2;s.properties[9].level=2;life.setCity(deriveCity(s));const after=life.step(.2); + for(const p of before.pedestrians){const q=after.pedestrians.find(x=>x.id===p.id);assert.ok(q);assert.equal(distance(p,q),0);} +}); +test('high/low/pause/resume preserve hard budgets and never catch up an absent interval',()=>{ + const life=start(developed());life.step(.1);life.configure({quality:'low'});const low=life.step(.2); + assert.ok(low.cars.length<=6);assert.ok(low.pedestrians.length<=12); + life.configure({living:false});assert.deepEqual(life.step(500),{cars:[],pedestrians:[],buses:[]}); + life.configure({quality:'high'});assert.equal(life.running,false); // A partial setting must not resume. + life.configure({living:true});const resumed=life.step(900); + for(const c of low.cars){assert.equal(distance(c,resumed.cars.find(p=>p.id===c.id)),0);} + const before=resumed.cars;const after=life.step(5000).cars; + for(const c of before)assert.ok(distance(c,after.find(p=>p.id===c.id))<=.086); + life.configure({reduced:true});assert.equal(life.step(6000).cars.length,0); + life.configure({reduced:false});const snapshot=life.step(7000);assert.deepEqual(life.step(7000),snapshot); + assert.throws(()=>life.step(NaN)); +}); +test('pedestrian reallocations and long visual sessions stay bounded with finite poses',()=>{ + const s=developed(),life=start(s);let maxCars=0,maxPeople=0,stops=0; + for(let i=1;i<=2200;i++){ + if(i%50===0){s.properties[1].level=s.properties[2].level=(i/50)%4;life.setCity(deriveCity(s));} + if(i%70===0)life.configure({quality:life.quality==='high'?'low':'high'}); + const frame=life.step(i*.1),low=life.quality==='low'; + assert.ok(frame.cars.length<=(low?6:18));assert.ok(frame.pedestrians.length<=(low?12:48)); + maxCars=Math.max(maxCars,frame.cars.length);maxPeople=Math.max(maxPeople,frame.pedestrians.length); + assert.equal(new Set(frame.pedestrians.map(p=>p.id)).size,frame.pedestrians.length); + for(const p of [...frame.cars,...frame.pedestrians,...frame.buses])assert.ok(Number.isFinite(p.x+p.z+p.yaw)); + stops+=frame.buses.filter(b=>b.waiting).length; + } + assert.equal(life.cars.length,18);assert.equal(life.walkers.length,128);assert.equal(maxCars,18);assert.equal(maxPeople,48);assert.ok(stops>30); +}); +test('both buses stop alongside the actual shelter coordinates and leave again',()=>{ + const life=start(developed()),stopped=new Map();let previous=null; + for(let i=1;i<1100;i++){ + const frame=life.step(i*.1); + for(const b of frame.buses)if(b.waiting){assert.ok(Math.abs(Math.abs(b.x)-6.98)<1e-8);assert.ok(Math.abs(b.z-1.2)<1e-8);stopped.set(b.id,b);} + if(previous)for(const b of frame.buses)assert.ok(distance(b,previous.buses.find(p=>p.id===b.id))<=.096); + previous=frame; + } + assert.equal(stopped.size,2); + for(const b of previous.buses)assert.ok(distance(b,stopped.get(b.id))>.1); +}); +test('new matches reset local actors; visuals never consume dice RNG or mutate the game',()=>{ + const s=developed(),before=fingerprint(s),life=start(s); + const random=Math.random;Math.random=()=>{throw Error('Visual code must not use a random source');}; + try{for(let i=1;i<200;i++)life.step(i*.1);life.setCity(deriveCity(s));}finally{Math.random=random;} + assert.equal(fingerprint(s),before); + life.setCity(deriveCity(fresh()),true);assert.equal(life.step(400).pedestrians.length,0);assert.equal(life.elapsed,0); + assert.equal(life.step(400).cars.length,3); +}); +test('cranes are deduplicated, animated without new buffers, and cancelled on closure',()=>{ + const r=renderer(),city=new LivingCity(r),s=fresh();city.setState(s);city.objects(0); + s.properties[1].owner='host';city.setState(s);s.properties[1].level=1;city.setState(s); + assert.equal(city.cranes.filter(c=>c.id===1).length,1); + const count=r.meshes.size,first=city.objects(.1),second=city.objects(.2); + assert.equal(r.meshes.size,count);assert.ok(first.some(o=>o.mesh===city.jib)); + assert.notDeepEqual(first.find(o=>o.mesh===city.cable).model,second.find(o=>o.mesh===city.cable).model); + s.properties[1].level=0;s.properties[1].mortgaged=true;city.setState(s);assert.equal(city.cranes.length,0); + city.setState({...s,id:'different'});assert.equal(city.cranes.length,0);assert.equal(city.celebrations.length,0); +}); +test('district celebrations stop if the district is no longer complete',()=>{ + const city=new LivingCity(renderer()),s=fresh();city.setState(s); + s.properties[1].owner=s.properties[2].owner='host';city.setState(s);assert.equal(city.celebrations.length,1); + s.properties[1].mortgaged=true;city.setState(s);assert.equal(city.celebrations.length,0); +}); +test('neighborhood feedback reflects real purchases, investments and mortgages, not cash rewards',()=>{ + let s=fresh();assert.equal(parcelInsight(s,1).activity,0);assert.equal(parcelInsight(s,0),null); + s.properties[1].owner=s.properties[2].owner='host'; + const initial=parcelInsight(s,1);assert.equal(initial.activity,2);assert.match(initial.status,/Quartier réuni/); + s=applyAction(s,'host',{type:'UPGRADE',tile:1});assert.equal(parcelInsight(s,1).activity,4);assert.equal(parcelInsight(s,1).level,1); + s=applyAction(s,'host',{type:'SELL_LEVEL',tile:1});s=applyAction(s,'host',{type:'MORTGAGE',tile:1}); + const before=fingerprint(s),closed=parcelInsight(s,1);assert.equal(closed.activity,0);assert.equal(closed.title,'L’activité est en veille');assert.equal(fingerprint(s),before); +}); +test('inspect camera is read-only and can be reset without affecting game or selection',()=>{ + const s=developed(),before=fingerprint(s),scene={city:{city:deriveCity(s)},selected:8}; + assert.equal(BoardScene.prototype.focusParcel.call(scene,8),true);assert.equal(scene.selected,8);assert.equal(scene.zoom,1.5);assert.equal(scene.dirty,true); + assert.equal(BoardScene.prototype.focusParcel.call(scene,0),false); + BoardScene.prototype.view.call(scene,'reset');assert.deepEqual(scene.viewTarget,[0,.3,0]);assert.equal(scene.zoom,1);assert.equal(fingerprint(s),before); +}); diff --git a/tests/city_life_browser.py b/tests/city_life_browser.py new file mode 100644 index 0000000..f3502aa --- /dev/null +++ b/tests/city_life_browser.py @@ -0,0 +1,166 @@ +"""City response in actual Chromium/WebGL2; controlled fixtures, not a human playtest.""" +import asyncio, json, pathlib, platform, subprocess, time, traceback, urllib.request +from playwright.async_api import async_playwright + +ROOT = pathlib.Path(__file__).resolve().parents[1] +OUT = ROOT / 'test-results' / 'city-response' +URL = 'http://127.0.0.1:4447' +OUT.mkdir(parents=True, exist_ok=True) + +FIXTURE = """async()=>{ + const {app}=await import('/src/main.js');window.cityApp=app; + const {createGame,assertState}=await import('/src/game/engine.js');const {BOARD}=await import('/src/game/board.js'); + clearTimeout(app.botTimer);clearTimeout(app.busyTimer);cancelAnimationFrame(app.scene?.raf); + const s=createGame([{id:'you',name:'Michaël'},{id:'friend',name:'Nova'}],42,{id:'city-response-browser',casino:true}); + s.players.forEach(p=>p.cash=5000); + for(const t of BOARD)if(t.kind==='lot'&&t.id!==1){s.properties[t.id].owner=t.id===2?'you':s.players[t.group%2].id;s.properties[t.id].level=t.id===2?0:t.group%4;} + s.players[0].position=1;s.phase='buy';s.pending=1;assertState(s); + app.settings.reduced=false;app.settings.living=true;app.settings.weather=false; + app.scene?.configure({reduced:false,living:true,quality:'high',dayMode:'day',weather:false}); + app.accept(s);app.select(1);cancelAnimationFrame(app.scene?.raf); + if(app.scene){app.scene.ambientTime=0;app.scene.lastAmbientFrame=null;app.scene.dirty=true;app.scene.render(performance.now()+100);} + return s.id; +}""" +DRAW = """async()=>{ + const a=cityApp,s=a.scene,r=s.renderer,gl=r.gl;const {fingerprint}=await import('/src/game/engine.js'); + const before=fingerprint(a.state);s.lastAmbientFrame=null;s.dirty=true;s.render(performance.now()+100); + const colors=new Set(),pixel=new Uint8Array(4); + for(let x=30;x{const s=cityApp.scene;for(let i=0;i8 and frame['unchanged'],frame + report['frames']['available']=frame + assert await page.locator('#city-insight [role="meter"]').get_attribute('aria-valuenow')=='0' + await page.screenshot(path=str(OUT/'01-terrain-disponible.png'),timeout=90000) + report['checks'].append('Real non-uniform WebGL2 frame, no GL error; unowned parcel has zero visual activity.') + + before=await page.evaluate('cityApp.scene.city.life.step(cityApp.scene.ambientTime).cars') + await page.locator('[data-game="BUY"]').click() + await page.wait_for_function('cityApp.state.properties[1].owner==="you"') + after=await page.evaluate('cityApp.scene.city.life.step(cityApp.scene.ambientTime).cars') + assert before==after,(before,after) + assert await page.locator('#city-insight [role="meter"]').get_attribute('aria-valuenow')=='2' + report['checks'].append('Legal purchase via UI reunites the district and updates activity; existing cars keep exactly the same poses.') + for _ in range(3): + for tile in [1,2]: + await page.evaluate('id=>cityApp.select(id)',tile) + await page.locator(f'[data-game="UPGRADE"][data-lot="{tile}"]').click() + await page.evaluate('cityApp.select(1)') + assert await page.evaluate('cityApp.state.properties[1].level===3&&cityApp.state.properties[2].level===3') + assert await page.locator('#city-insight [role="meter"]').get_attribute('aria-valuenow')=='8' + assert await page.evaluate('cityApp.scene.city.cranes.filter(c=>c.id===1).length===1') + frame=await advance(page) + assert frame['unchanged'] and frame['error']==0 and frame['life']['cars']<=18 and frame['life']['pedestrians']<=48 + report['frames']['construction']=frame + await page.screenshot(path=str(OUT/'02-quartier-en-construction.png'),timeout=90000) + report['checks'].append('Six real balanced upgrades through UI, maximum activity and two articulated construction cranes; no extra economy writes.') + + await page.locator('[data-ui="focus-city"]').click() + assert await page.evaluate('cityApp.scene.viewTarget[2]===cityApp.scene.city.city.parcels.find(p=>p.id===1).z') + assert await page.locator('#board').evaluate('(e)=>e===document.activeElement') + await advance(page,70) + await page.evaluate('cityApp.scene.configure({dayMode:"night"})') + night=await page.evaluate(DRAW);assert night['error']==0 and night['colors']>8 + assert await page.evaluate('cityApp.scene.city.cranes.length===0') + report['frames']['night']=night + await page.screenshot(path=str(OUT/'03-quartier-developpe-nuit.png'),timeout=90000) + await page.locator('[data-ui="reset-view"]').click() + assert await page.evaluate('JSON.stringify(cityApp.scene.viewTarget)==="[0,0.3,0]"') + report['checks'].append('Inspect button centers the selected property and focuses the canvas; reset restores the full board. Night frame and crane expiry verified.') + + # Sell balanced levels via ordinary rules, then mortgage the selected property. + for _ in range(3): + for tile in [1,2]: + await page.evaluate('id=>cityApp.select(id)',tile) + await page.locator(f'[data-game="SELL_LEVEL"][data-lot="{tile}"]').click() + await page.evaluate('cityApp.select(1)') + await page.locator('[data-game="MORTGAGE"][data-lot="1"]').click() + assert await page.locator('#city-insight [role="meter"]').get_attribute('aria-valuenow')=='0' + assert 'en veille' in await page.locator('#city-insight-title').inner_text() + await advance(page,15) + assert await page.evaluate('!cityApp.scene.city.life.step(cityApp.scene.ambientTime).pedestrians.some(p=>p.parcelId===1)') + await page.screenshot(path=str(OUT/'04-activite-en-veille.png'),timeout=90000) + report['checks'].append('Legal sales and mortgage close the storefront activity and retire that parcel’s pedestrians without destroying the building.') + + cache=await page.evaluate("""()=>{const s=cityApp.scene,r=s.renderer,before=r.meshes.size;for(let i=0;i<600;i++){s.ambientTime+=.1;s.city.objects(s.ambientTime,0);}return {before,after:r.meshes.size};}""") + assert cache['before']==cache['after'];report['meshStability']=cache + await page.evaluate('cityApp.scene.configure({quality:"low"})') + low=await advance(page);assert low['life']['cars']<=6 and low['life']['pedestrians']<=12 and low['renderer']['shadowDrawCalls']==0 + assert low['renderer']['textureBytes']['shadowDepth24StorageUpperBound']==0 + report['frames']['low']=low + idle=await page.evaluate("""()=>{const s=cityApp.scene;s.configure({living:false,reduced:true});s.dirty=true;s.render(performance.now()+1000);const before=s.frameCount;for(let i=0;i<30;i++)s.render(performance.now()+1100+i*50);return {before,after:s.frameCount};}""") + assert idle['before']==idle['after'];report['idle']=idle + report['checks'].append('600 local animation steps allocate no new meshes; low mode respects 6/12 caps and allocates no shadow map; frozen scene submits no further frames.') + + mobile_ctx=await browser.new_context(viewport={'width':390,'height':844},device_scale_factor=1,is_mobile=True,has_touch=True) + mobile=await mobile_ctx.new_page();mobile.on('pageerror',lambda e:report['pageErrors'].append(str(e))) + await mobile.goto(URL);await mobile.wait_for_function("!document.querySelector('.scene-loading')") + await mobile.evaluate(FIXTURE) + await mobile.evaluate('cityApp.scene.configure({quality:"low"})') + await mobile.evaluate(DRAW) + assert await mobile.evaluate('document.documentElement.scrollWidth<=window.innerWidth') + box=await mobile.locator('[data-ui="focus-city"]').bounding_box();assert box['height']>=44 + await mobile.locator('[data-ui="focus-city"]').click() + assert await mobile.locator('#board').evaluate('(e)=>e===document.activeElement') + await mobile.screenshot(path=str(OUT/'05-mobile-emule.png'),full_page=True,timeout=90000) + report['checks'].append('390 px touch emulation: no horizontal overflow, full-width feedback card, 44 px inspect target and canvas focus.') + + fallback=await browser.new_page(viewport={'width':1100,'height':900}) + fallback.on('pageerror',lambda e:report['pageErrors'].append(str(e))) + await fallback.add_init_script("const original=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(kind,...args){return /webgl/i.test(kind)?null:original.call(this,kind,...args);}") + await fallback.goto(URL);await fallback.locator('.scene-error').wait_for() + assert await fallback.locator('#city-insight [role="meter"]').count()==1 + assert await fallback.locator('[data-ui="focus-city"]').is_disabled() + await fallback.locator('.fallback-grid [data-tile="4"]').click() + assert await fallback.locator('#city-insight').get_attribute('data-tile')=='4' + report['checks'].append('Without WebGL, the parcel explanation and accessible selection remain usable; the camera-only action is disabled.') + + offline=await browser.new_page(viewport={'width':1280,'height':900}) + offline.on('pageerror',lambda e:report['pageErrors'].append(str(e))) + await offline.goto((ROOT/'dist/dicestrict-offline.html').as_uri()) + await offline.wait_for_function("!document.querySelector('.scene-loading')") + assert await offline.locator('.scene-error').count()==0 + assert await offline.locator('#city-insight [role="meter"]').count()==1 + assert await offline.locator('[data-ui="focus-city"]').is_enabled() + await offline.locator('[data-ui="focus-city"]').click() + assert await offline.evaluate('document.querySelector("#board").getContext("webgl2").getError()===0') + report['checks'].append('Standalone file:// build initializes WebGL2 and the new inspect interaction without external dependencies.') + assert not report['pageErrors'],report['pageErrors'] + await browser.close();browser=None + except Exception: + report['failure']=traceback.format_exc() + if browser: + for i,ctx in enumerate(browser.contexts): + for j,page in enumerate(ctx.pages): + try:await page.screenshot(path=str(OUT/f'failure-{i}-{j}.png'),full_page=True,timeout=15000) + except Exception:pass + raise + finally: + (OUT/'report.json').write_text(json.dumps(report,indent=2,ensure_ascii=False)) + if browser:await browser.close() + server.terminate();server.wait(timeout=5) + print(json.dumps(report['checks'],indent=2,ensure_ascii=False)) + +asyncio.run(main())