diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index faae431..711d694 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,7 +40,7 @@ jobs: assets/ retention-days: 14 - # Each complete opening gets a clean runner and the original bounded budget. + # Each complete opening gets a clean runner and a bounded software-render budget. # Both matrix entries are required; every shard also verifies the lab import. sessions: name: sessions (${{ matrix.opening }}) @@ -49,7 +49,7 @@ jobs: matrix: opening: [classic, comp-60] runs-on: ubuntu-latest - timeout-minutes: 25 + timeout-minutes: 28 steps: - uses: actions/checkout@v6 - uses: actions/setup-node@v6 @@ -62,7 +62,7 @@ jobs: - run: pip install playwright==1.57.0 - run: python -m playwright install --with-deps chromium - run: python -u tests/playtest_browser.py --opening "${{ matrix.opening }}" - timeout-minutes: 22 + timeout-minutes: 25 - name: Capture exact session sources if: always() run: | diff --git a/.github/workflows/visual-finish.yml b/.github/workflows/visual-finish.yml new file mode 100644 index 0000000..f17b142 --- /dev/null +++ b/.github/workflows/visual-finish.yml @@ -0,0 +1,49 @@ +name: Phase 4 visual finish +on: + push: + branches: [feat/phase4-visual-finish] + pull_request: + paths: ['src/scene/**', 'scripts/assets/**', 'tests/visual*', '.github/workflows/visual-finish.yml'] + workflow_dispatch: +permissions: + contents: read +jobs: + native: + name: native (${{ matrix.section }}) + strategy: + fail-fast: false + matrix: + section: [proof, measures] + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + with: {fetch-depth: 0} + - uses: actions/setup-node@v6 + with: {node-version: '22'} + - uses: actions/setup-python@v6 + with: {python-version: '3.12'} + - run: npm run check && npm test && npm run build + - run: npm run assets:export && node scripts/assets/export-civic.mjs && node scripts/assets/export-harmony.mjs && node scripts/assets/export-finish.mjs && npm run assets:review + - run: pip install playwright==1.57.0 && python -m playwright install --with-deps chromium + - name: Pinned actual main baseline + run: | + mkdir -p test-results/visual-baseline + git archive b5f547c97ce8387f1c31b25bef3a29952d0a94a7 | tar -x -C test-results/visual-baseline + - run: python -u tests/visual_finish_browser.py --section "${{ matrix.section }}" + timeout-minutes: 15 + - name: Exact source + if: always() + run: | + git rev-parse HEAD > test-results/visual-finish/commit.txt + git archive --format=tar -o source.tar HEAD + - uses: actions/upload-artifact@v4 + if: always() + with: + name: phase4-visual-${{ matrix.section }} + path: | + source.tar + dist/ + assets/ + test-results/visual-finish/ + retention-days: 14 diff --git a/.gitignore b/.gitignore index 1ed906f..603c966 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,6 @@ assets/districts/ assets/civic/ assets/waterfront/ + +assets/harmony/ +assets/finish/ diff --git a/docs/assets/PHASE4_VISUAL_FINISH.md b/docs/assets/PHASE4_VISUAL_FINISH.md new file mode 100644 index 0000000..af18fb4 --- /dev/null +++ b/docs/assets/PHASE4_VISUAL_FINISH.md @@ -0,0 +1,72 @@ +# Phase 4 — ville assemblée, matériaux et effets + +## Base et périmètre + +Base : `main b5f547c97ce8387f1c31b25bef3a29952d0a94a7`, fusion de la PR #9. Livraison sur `feat/phase4-visual-finish`, PR #10 en brouillon, sans nouvelle fusion. La branche d'équipe `feat/engagement-rhythm-0-7` reste indépendante. Les règles, le réseau, l'UI, le laboratoire, les 28 cases et les cinq workflows préexistants sont conservés. Les scripts et assertions des tests antérieurs ne sont pas remplacés. + +« AAA » désigne une ambition, pas une qualité certifiée. Même dans une scène développée, la référence illustrée possède une continuité urbaine, une densité et une étendue d'eau plus grandes. Cette passe ne prétend pas les avoir reproduites. Les vues de départ conservent les terrains vacants, sans argent ni bâtiments privés offerts pour embellir les captures. + +## Modèles et intégration + +Jardins 4–5 : maison à terrasses plantées et orangeraie vitrée à belvédère. Nova 18–19 : campus vertical à ailettes et observatoire à tambour/coupole. Solstice 25–26 : palazzo à portique et résidence à volumes décalés. Les variantes changent de silhouette et de volume, pas seulement de couleur. Chaque bien dispose de l'état vacant, des niveaux 0–3 et de deux LOD ; origine au centre, Y vers le haut, façade principale en +Z. La projection existante assure l'orientation, l'état hypothéqué, le fanion du propriétaire et l'activité. + +Roseraie 22–23 conserve son générateur et ses géométries. Les lots Marina, Rivage, Horizon et Ateliers sont réutilisés. Le casino conserve son architecture avec une frise intégrée plus lisible. La promenade et la fontaine ne sont pas refaites. + +Le pavillon municipal remplace l'ancien volume aux mêmes coordonnées : ouvertures profondes, portique, fronton, tambour vitré et coupole profilée. Les deux portails de métro possèdent marches, murets, garde-corps, verrières courbes et un petit M intégré. Leurs cheminements, plantations, bancs et lampes forment un maillage public partagé par LOD, sans empiéter sur les cases. + +## Matériaux et VFX + +`src/scene/finish/shader.js` fournit une réponse stylisée commune en espace linéaire, éclairage direct et hémisphérique, spéculaire GGX/Schlick pour les surfaces brillantes, réflexion de ciel analytique et courbe de sortie filmique. Il ne s'agit pas d'une chaîne PBR complète avec HDRI/GI. Les surfaces mates évitent le calcul d'un lobe spéculaire peu perceptible. Le bassin conserve son reflet planaire borné ; la nappe extérieure emploie des ondulations analytiques et un fondu spatial vers le fond. Aucun bloom ou flou plein écran n'est ajouté. + +Un atlas RGBA8 256² encode micro-normales et rugosité des huit surfaces existantes. Le mode bas ne l'échantillonne pas ; les textures restent partagées. Un autre atlas RGBA8 256² encode les contacts et les petites zones de lumière au sol. Ce champ se reconstruit lors des changements immobiliers, pas à chaque frame ou lancer de dés. Ce n'est pas du SSAO ni de la GI. Les quatre sources analytiques de proximité sont conservées ; les lampes supplémentaires ne créent pas de nouvelles shadow maps. + +Les transitions économiques existantes déclenchent un ruban de construction, une poussière légère et des gerbes teintées. Petits triangles regroupés, animation au vertex shader, âge en uniforme : aucun upload par particule ou par frame. Quatre constructions visibles maximum en haut, deux en bas ; poussière seulement en haut ; deux célébrations simultanées. Les effets disparaissent en mode mouvements réduits ou ville figée. Ils ne créent ni monnaie, ni commande réseau, ni récompense. L'état du mélange alpha et de l'écriture de profondeur est restauré après les effets. + +## Budgets des modèles effectivement générés + +| Modèle/famille | Maximum de triangles bas / haut | +|---|---:| +| Jardins, un bien | 2 748 / 4 644 | +| Nova, un bien | 2 908 / 4 912 | +| Roseraie conservée, un bien | 2 534 / 4 362 | +| Solstice, un bien | 3 024 / 5 188 | +| Pavillon municipal | 2 119 / 3 583 | +| Un portail de métro | 564 / 700 | +| Cheminements et mobilier nouveaux | 4 592 / 6 340 | + +Les silhouettes, toits et ouvertures visibles ont priorité sur les micro-objets. Un bien est un maillage indexé plus son fanion. Le lot public est un seul maillage par LOD. Le cache Harmony est limité à 16 maillages et 4 Mio, sans évincer un modèle visible. Les huit variantes actives au détail haut totalisent au maximum 3 616 392 octets ; les LOD inactifs les moins récents sont supprimés. Les autres lots gardent leurs caches bornés. + +Ressources GPU ajoutées : 349 525 octets pour le détail avec mipmaps, 262 144 pour le champ au sol, soit environ 597 Kio. Ce dernier possède une copie CPU de 256 Kio. Les buffers géométriques, leur copie CPU de restauration, l'atlas du plateau, les ombres, le reflet, le framebuffer et les allocations inconnues du pilote sont comptés séparément. Le mode bas libère la shadow map et la cible de reflet ; le changement de qualité et la restauration du contexte restent testés. + +Les GLB sont des exports d'échange des mêmes modèles natifs, pas des téléchargements obligatoires au démarrage. Les matériaux glTF de base sont exportés ; un lecteur générique ne reproduit pas les shaders natifs ou le champ de lumière. Le PNG RG-normal/B-rugosité est un format empaqueté pour ce moteur, pas une normal map glTF directement branchable. + +## Régénérer et vérifier + +```sh +npm run check +npm test +npm run build +npm run assets:export +node scripts/assets/export-civic.mjs +node scripts/assets/export-harmony.mjs +node scripts/assets/export-finish.mjs +npm run assets:review +``` + +Sources : `src/scene/harmony/extensions.js`, `src/scene/finish/`, `scripts/assets/`. Exports : `assets/harmony/`, `assets/finish/`, et kits précédents. Galerie : `assets/districts/review.html`. Les binaires reproductibles sont dans les artefacts CI et la livraison, pas dupliqués dans Git. + +Le workflow `visual-finish.yml` sépare preuve et mesures. L'avant est le vrai `main b5f547c9`, servi sur une autre origine, pas une fonction qui masque des objets. `civicFixtures()` et `waterfrontFixtures()` fournissent des historiques légaux déterministes. Dimensions 1600 × 1000, DPR 1, état, horloge et caméra identiques dans chaque paire. Caméra principale : angle 0,5, inclinaison 0,85, zoom 1, cible normale. Les vues obliques (inclinaison 0,63 / zoom 1,12) et le zoom 1,5 restent accessibles au joueur. Les vues studio servent seulement de complément. + +Le diagnostic ABBA bas/haut, figé/animé, conserve six mesures après deux chauffes par bloc. Une lecture synchrone d'un pixel mesure rendu logiciel et synchronisation, pas le seul GPU matériel. Les nouvelles ressources sont testées après perte de contexte, au repos et pendant les transitions. Les scénarios WebRTC complets Classique et comp-60 restent séparés, avec leurs assertions et délais de convergence d'origine. Seule la limite globale de l'étape CI passe de 22 à 25 minutes (job borné à 28 minutes), car le rendu logiciel simultané de quatre navigateurs a dépassé l'ancien budget de quelques secondes. + +## Défauts trouvés pendant la mise au point + +La première preuve native a montré une eau extérieure trop striée et un contraste insuffisant derrière le titre inchangé. Les ondulations et le fondu spatial ont été corrigés. La galerie a révélé un réexport non supporté par le bundler ESM minimal : import/export explicite et test syntaxique sur les bundles produits ajoutés. + +Le code `86108430` a mesuré un surcoût SwiftShader de 45–49 % par rapport au vrai main. Un premier allègement du shader n'a pas démontré de gain ; ne pas annoncer de non-régression temporelle ou de performances mobiles. La suite quartiers a également observé 18 949 206 octets de buffers après des zooms, dépassant la limite de 18 Mio. La borne en octets du cache corrige ce problème ; le seuil du test n'est pas relevé. Les résultats des anciennes exécutions échouées ne constituent pas une validation finale. Consulter le commit effectivement testé et ses rapports dans la PR #10. + +Les journaux du run `34158220245` montrent la progression continue de la session Classique, 147 commandes, trace vérifiée et import du laboratoire réussi, avant une conclusion CI timeout à 22 minutes. La session comp-60 a également exporté ses 147 commandes avant son interruption. Ces sorties ne sont pas présentées comme une CI réussie ; la nouvelle limite globale est bornée, les contrôles fonctionnels et leur ordre sont inchangés, et toute la recette est relancée. + +## Matériel restant à tester + +Aucun téléphone physique, Safari/iOS, réseau mobile/TURN, batterie ou essai humain n'est validé ici. Sur appareils réels, noter modèle, OS, navigateur, résolution/DPR, qualité, température et alimentation. Exécuter les mêmes états jour/crépuscule, trois passages de 60 secondes après chauffe, puis 10 minutes animées. Relever distributions des intervalles de frames, longues tâches, chargement, transitions, mémoire, arrière-plan et restauration. Utiliser un compteur GPU seulement s'il est disponible et non disjoint. Le protocole détaillé `PHASE3_DEVICE_PROTOCOL.md` reste applicable. L'émulation tactile valide uniquement l'affichage et les interactions. diff --git a/scripts/assets/export-finish.mjs b/scripts/assets/export-finish.mjs new file mode 100644 index 0000000..0ca9340 --- /dev/null +++ b/scripts/assets/export-finish.mjs @@ -0,0 +1,13 @@ +/** Exchange files for the implemented public models and generated shared textures. */ +import {mkdir,writeFile,readFile} from 'node:fs/promises'; +import {createHash} from 'node:crypto'; +import {createPublicAsset,PUBLIC_FACTORIES,PUBLIC_BUDGETS} from '../../src/scene/finish/public.js'; +import {detailAtlas} from '../../src/scene/finish/materials.js'; +import {cityField} from '../../src/scene/finish/field.js'; +import {encodeGLB,png} from './glb.mjs'; +const out=new URL('../../assets/finish/',import.meta.url);await mkdir(out,{recursive:true});const rows=[]; +for(const name of Object.keys(PUBLIC_FACTORIES))for(const lod of ['low','high']){const mesh=createPublicAsset(name,lod),{bytes,min,max}=encodeGLB(mesh);await writeFile(new URL(mesh.name+'.glb',out),bytes);rows.push({name,lod,triangles:mesh.indices.length/3,bytes:bytes.length,bounds:{min,max},sha256:createHash('sha256').update(bytes).digest('hex')});} +await writeFile(new URL('normal-roughness.png',out),png(detailAtlas()));await writeFile(new URL('public-contact-light.png',out),png(cityField())); +const sources={};for(const p of ['public.js','field.js','materials.js','shader.js','effects.js'])sources[p]=createHash('sha256').update(await readFile(new URL('../../src/scene/finish/'+p,import.meta.url))).digest('hex'); +await writeFile(new URL('manifest.json',out),JSON.stringify({schema:1,budgets:PUBLIC_BUDGETS,sources,models:rows,notes:'Native runtime meshes and shaders; GLB exchange roughness descriptors are supported. Packed normal/roughness PNG is for the native shader, not a glTF normal texture. Ground field is world-space contact/lighting, not real-time GI.'},null,2)); +console.table(rows); diff --git a/scripts/assets/export-harmony.mjs b/scripts/assets/export-harmony.mjs index cce31d5..9309778 100644 --- a/scripts/assets/export-harmony.mjs +++ b/scripts/assets/export-harmony.mjs @@ -13,7 +13,7 @@ for(const family of HARMONY_FAMILIES)for(let level=-1;level<4;level++)for(const const min=[Infinity,Infinity,Infinity],max=min.map(x=>-x);for(let j=0;j({name,triangles,gpuBytes,glbBytes}))); console.log(`Executed ${rows.length} GLB exports to assets/harmony`); diff --git a/src/scene/board-scene.js b/src/scene/board-scene.js index 50230a8..661cc96 100644 --- a/src/scene/board-scene.js +++ b/src/scene/board-scene.js @@ -23,11 +23,11 @@ function atlas(){ function uv(id){const x=id%8*256,y=Math.floor(id/8)*256;return [(x+2)/2048,1-(y+254)/1024,(x+254)/2048,1-(y+2)/1024];} function cityGeometry(){ const g=new Geometry(); - g.block([0,-.67,0],[150,.08,150],'#f4f2e9'); - g.box([0,-.14,0],[15.3,.78,15.3],'#9bb6a7',.25); - g.box([0,.13,0],[15.18,.32,15.18],'#e3e8d8',.18); - g.box([0,.32,0],[14.98,.08,14.98],'#c8d9c4',.12); - g.box([0,.37,0],[9.54,.10,9.54],'#a5c3ac',.12); + g.material=21;g.block([0,-.67,0],[150,.08,150],'#205d70');g.material=0; + g.box([0,-.14,0],[15.3,.78,15.3],'#6a7168',.25); + g.box([0,.13,0],[15.18,.32,15.18],'#b5a483',.18); + g.box([0,.32,0],[14.98,.08,14.98],'#c9ba99',.12); + g.box([0,.37,0],[9.54,.10,9.54],'#899979',.12); g.quad([.4,.525,2.6],2.20,.85,uv(28)); g.box([.1,.47,3.38],[2.45,.08,.95],'#d0ddc5',.1); for(const t of BOARD){const [x,z]=tilePosition(t.id);g.box([x,.40,z],[1.49,.21,1.49],'#fffff6',.09);g.quad([x,.509,z],1.37,1.37,uv(t.id));} @@ -124,7 +124,7 @@ class BoardScene { const extent=(aspect<1.15?10.1/aspect:9.0)/this.zoom; const target=this.captureTarget??[0,.3,0]; 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.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.city.publicRealm.selectDetail(rect.height/(2*extent)); this.vp=multiply(ortho(-extent*aspect,extent*aspect,-extent,extent,.1,80),lookAt(eye,target)); const objects=[{mesh:this.staticMesh,model:identity()},...this.city.objects(this.ambientTime,this.renderer.weather)];if(this.ownerMesh)objects.push({mesh:this.ownerMesh}); if(this.state)for(let i=0;ifont[c].forEach((r,y)=>[...r].forEach((v,x)=>{if(v==='1')g.box([-.254+i*.088+x*.022,.74-y*.016,.710],[.017,.012,.009],C.brass,M.metal);}))); + g.box([0,.708,.696],[.76,.124,.024],C.dark,M.paint); + [...'CASINO'].forEach((c,i)=>font[c].forEach((r,y)=>[...r].forEach((v,x)=>{if(v==='1')g.box([-.338+i*.118+x*.027,.754-y*.023,.710],[.022,.018,.012],C.brass,M.lamp);}))); for(const x of [-.60,.60]){ g.box([x,.37,.395],[.028,.19,.028],C.brass,M.metal); g.box([x,.47,.405],[.055,.072,.055],C.warm,M.lamp,.006); diff --git a/src/scene/districts/review.js b/src/scene/districts/review.js index 474d6cf..7cc6cce 100644 --- a/src/scene/districts/review.js +++ b/src/scene/districts/review.js @@ -1,3 +1,4 @@ +import {createPublicAsset,PUBLIC_FACTORIES} from '../finish/public.js'; import { createHarmonyAsset, HARMONY_FAMILIES } from '../harmony/kit.js'; import { createCivicAsset, CIVIC_FACTORIES } from '../civic/kit.js'; /** Isolated asset inspection with the SAME Renderer and geometry factories as the game. */ @@ -11,6 +12,7 @@ for(const family of FAMILIES)for(const level of [-1,0,1,2,3])for(const variant o for(const name of ['linden','bench','cafe-table','heritage-lamp','office-lamp','container','delivery-truck','gantry'])choices.set(name,lod=>createDistrictProp(name,lod)); for(const name of Object.keys(FACTORIES))choices.set(name,lod=>createAsset(name,lod)); for(const name of Object.keys(CIVIC_FACTORIES))choices.set(name,lod=>createCivicAsset(name,lod)); +for(const name of Object.keys(PUBLIC_FACTORIES))choices.set(name,lod=>createPublicAsset(name,lod)); const canvas=document.querySelector('canvas'),atlas=document.createElement('canvas');atlas.width=atlas.height=2; const ctx=atlas.getContext('2d');ctx.fillStyle='#ffffff';ctx.fillRect(0,0,2,2); const renderer=new Renderer(canvas,atlas);renderer.studio=true;renderer.shadows=false; diff --git a/src/scene/finish/effects.js b/src/scene/finish/effects.js new file mode 100644 index 0000000..ab5a486 --- /dev/null +++ b/src/scene/finish/effects.js @@ -0,0 +1,31 @@ +/** Shader-animated bursts/dust/ribbons. Every particle is a real tiny triangle, + * collected into one shared mesh; no per-frame vertex upload or timer per particle. */ +import {MeshBuilder} from '../marina/mesh-builder.js'; +export function effectMesh(kind,lod='low'){ + if(!['burst','dust','scan'].includes(kind)||!['low','high'].includes(lod))throw Error('Invalid effect mesh'); + const g=new MeshBuilder(),n=kind==='scan'?4:kind==='dust'?(lod==='high'?8:4):(lod==='high'?24:8); + for(let i=0;ig.vertex(p,[0,0,1],kind==='dust'?'#d7c5a3':i%3?'#eac578':'#bce1d4',23,[i/n,(i*.6180339)%1])); + g.indices.push(ids[0],ids[1],ids[2],ids[0],ids[2],ids[3]); + } + return g.build(`event-${kind}-${lod}`); +} +export const EFFECT_VERTEX=` +uniform float uEffectAge;uniform float uEffectKind;out float vEffectFade; +vec3 effectPosition(vec3 p){ + vEffectFade=1.;if(aTex<22.5)return p; + float t=max(uEffectAge,0.),a=aUv.x*6.283185,s=aUv.y; + if(uEffectKind>1.5){p.y+=.08+min(t/3.,1.)*1.6;vEffectFade=.38*(1.-smoothstep(1.8,3.0,t));} + else if(uEffectKind>.5){p*=1.+t*1.8;p+=vec3(cos(a)*(.40+t*.18),.10+t*(.16+s*.10),sin(a)*(.40+t*.18));vEffectFade=.22*(1.-smoothstep(.2,2.4,t));} + else {p*=1.-smoothstep(1.7,3.6,t);p+=vec3(cos(a)*(.26+s*.22)*t,.12+(1.+s*.8)*t-.49*t*t,sin(a)*(.26+s*.22)*t);vEffectFade=.95*(1.-smoothstep(1.5,3.6,t));} + return p; +} +`; diff --git a/src/scene/finish/field.js b/src/scene/finish/field.js new file mode 100644 index 0000000..0451e51 --- /dev/null +++ b/src/scene/finish/field.js @@ -0,0 +1,22 @@ +/** World-space contact/illumination field, 256² RGBA8. One CPU regeneration and + * one texture upload on economic changes; no camera, dice or network clock dependency. + * R=soft contact visibility; G=warm pools; B=cool transit pools. Not SSAO or GI. */ +import {STREET_LIGHTS} from './public.js'; +export const FIELD_SIZE=256; +export function cityField(city=null){ + const n=FIELD_SIZE,data=new Uint8Array(n*n*4);for(let i=0;i{ + const loX=Math.max(0,Math.floor((x-w-r+8)*n/16)),hiX=Math.min(n-1,Math.ceil((x+w+r+8)*n/16)); + const loZ=Math.max(0,Math.floor((z-d-r+8)*n/16)),hiZ=Math.min(n-1,Math.ceil((z+d+r+8)*n/16)); + for(let j=loZ;j<=hiZ;j++)for(let i=loX;i<=hiX;i++){ + const dx=Math.max(0,Math.abs((i+.5)*16/n-8-x)-w),dz=Math.max(0,Math.abs((j+.5)*16/n-8-z)-d),dist=Math.hypot(dx,dz); + if(dist>r)continue;const a=strength*Math.pow(1-dist/r,2),at=(j*n+i)*4+channel; + data[at]=channel===0?Math.round(data[at]*(1-a)):Math.min(255,data[at]+Math.round(255*a)); + } + }; + for(const p of city?.parcels??[])if(p.owner){splat(p.x,p.z,.29,.28,.31,.38,0);if(!p.mortgaged)splat(p.x,p.z+.32,.19,.05,.46,.11+p.level*.045,1);} + for(const p of [[-1.25,-.95,.88,.43],[1.3,-1.65,.48,.36],[-2.25,.355,.52,.36],[1.65,1.45,.31,.31]])splat(...p,.30,.42,0); + for(const [x,z] of STREET_LIGHTS)splat(x,z,0,0,.72,.72,1); + for(const x of [-2.25,2.3])splat(x,-2.24,.17,.03,.46,.60,2); + return {width:n,height:n,data}; +} diff --git a/src/scene/finish/materials.js b/src/scene/finish/materials.js new file mode 100644 index 0000000..08de2a3 --- /dev/null +++ b/src/scene/finish/materials.js @@ -0,0 +1,18 @@ +/** One shared, generated micro-normal/roughness atlas; matches the existing 8 tiles. + * RG = tangent normal, B = perceptual roughness, A = 1. All 64² tiles have mipmaps. + * No fetched textures, no extra textures per object. */ +import {surfaceTile} from '../marina/surfaces.js'; +export function detailAtlas(){ + const width=256,data=new Uint8Array(width*width*4);data.fill(255); + const roughness=[.62,.86,.35,.90,.88,.74,.92,.48]; + for(let id=0;id<8;id++){ + const tile=surfaceTile(id),ox=id%4*64,oy=Math.floor(id/4)*64; + const h=(x,y)=>tile.data[(((y+64)%64)*64+(x+64)%64)*4]/255; + for(let y=0;y<64;y++)for(let x=0;x<64;x++){ + const dx=(h(x-1,y)-h(x+1,y))*.48,dy=(h(x,y-1)-h(x,y+1))*.48; + const k=((y+oy)*256+x+ox)*4; + data.set([Math.round((dx*.5+.5)*255),Math.round((dy*.5+.5)*255),Math.round(255*Math.min(.98,roughness[id]+(h(x,y)-.85)*.15)),255],k); + } + } + return {width,height:width,data}; +} diff --git a/src/scene/finish/public.js b/src/scene/finish/public.js new file mode 100644 index 0000000..ca34190 --- /dev/null +++ b/src/scene/finish/public.js @@ -0,0 +1,93 @@ +/** Public infill only; keeps the original casino, promenade, fountain and marina. + * The pavilion and metro occupy their existing footprints. No selectable lot is used. */ +import {MeshBuilder} from '../marina/mesh-builder.js'; +import {MATERIALS as M} from '../marina/surfaces.js'; +import {createDistrictProp} from '../districts/kit.js'; +import {C,B,R,shell,hip,steps} from '../harmony/architecture.js'; +import {path} from '../civic/kit.js'; +export const PUBLIC_PLACEMENT=Object.freeze({pavilion:[1.3,.48,-1.65],metro:[[-2.25,.43,-2.55],[2.3,.43,-2.55]]}); +export const STREET_LIGHTS=Object.freeze([ + [-2.98,1.04],[-2.98,3.12],[-1.4,.59],[-.83,2.51],[-2.06,3.29], + [-1.98,-.12],[-.44,-.13],[.08,.74],[2.39,1.98], + [-3.04,-2.74],[-1.15,-3.07],[1.23,-3.07],[3.04,-2.72], + [3.02,-.26],[3.02,2.73],[.84,3.01],[-1.20,3.07], + [-3.07,-.69],[.71,-1.13],[1.89,-1.13], +]); +function pavilion(lod){ + const g=new MeshBuilder(),fine=lod==='high'; + B(g,[0,.03,0],[1.13,.06,.97],C.stone,M.stone,.025); + const h=shell(g,0,-.07,.95,.75,.075,2,fine,'#e7d0a6'); + hip(g,0,-.07,1.03,.83,h,.16,'#477967',M.roof,fine); + // Octagonal drum with glazing, a profiled copper dome, ridge bands and finial. + g.lathe([0,h+.12,-.07],[[.28,0],[.28,.045],[.24,.045],[.24,.23],[.27,.23],[.27,.27]],C.chalk,M.stone,8); + for(let i=0;i<8;i++){ + const a=i*Math.PI/4,x=Math.cos(a)*.244,z=-.07+Math.sin(a)*.244; + const panel=new MeshBuilder();B(panel,[0,0,0],[.115,.12,.013],C.glass,M.glass); + g.add(panel.build('drum-glazing'),[x,h+.263,z],Math.PI/2-a); + } + const profile=[[.29,0],[.29,.035],[.265,.10],[.22,.20],[.13,.29],[.057,.33],[.057,.38],[0,.40]]; + g.lathe([0,h+.39,-.07],profile,'#467f71',M.roof,fine?24:16); + R(g,[0,h+.765,-.07],[0,h+.95,-.07],.013,C.brass,M.metal,6); + for(const x of [-.30,-.10,.10,.30]){ + g.lathe([x,.08,.43],[[.046,0],[.046,.06],[.032,.09],[.032,.38],[.048,.415],[.048,.445]],C.chalk,M.stone,fine?10:8); + } + B(g,[0,.544,.405],[.77,.07,.30],C.chalk);B(g,[0,.589,.405],[.80,.023,.33],C.brass,M.metal); + g.polygon([[-.405,.605,.571],[.405,.605,.571],[0,.805,.571]],C.stone,M.stone,[0,0,1]); + for(const x of [-.29,.29]){B(g,[x,.34,.332],[.055,.10,.039],C.brass,M.metal);B(g,[x,.415,.344],[.075,.085,.065],'#f7ce82',M.lamp,.009);} + steps(g,0,.63,.68);return g.build(`municipal-pavilion-${lod}`); +} +function metro(lod){ + const g=new MeshBuilder(),fine=lod==='high'; + B(g,[0,.025,0],[.66,.05,.48],C.stone,M.stone,.013); + B(g,[0,.060,0],[.47,.025,.40],'#213e40',M.paint); + for(let i=0;i<5;i++)B(g,[0,.08+i*.016,.19-i*.060],[.43,.025,.060],i%2?C.stone:C.paving,M.stone); + for(const side of [-1,1]){ + B(g,[side*.29,.15,0],[.07,.25,.46],C.stone); + R(g,[side*.235,.25,.20],[side*.235,.32,-.15],.009,C.brass); + for(const z of [-.18,.18])R(g,[side*.27,.20,z],[side*.27,.61,z],.013,C.dark,M.metal,6); + } + // True curved glazed canopy, no fake billboard entrance. + const n=fine?10:6,pt=(i,z)=>[-.36+i/n*.72,.58+Math.sin(i/n*Math.PI)*.16,z]; + for(let i=0;i{if(!cache.has(name))cache.set(name,createDistrictProp(name,lod));g.add(cache.get(name),p,a,s);}; + // Narrow continuous inner walk, open at the sea access and dice plaza. + path(g,[[-3.09,-2.98],[2.95,-2.98],[2.95,2.91],[1.02,2.91]],.19,.494,C.paving,M.paving); + path(g,[[-3.07,-2.98],[-3.07,.49]],.19,.494,C.paving,M.paving); + path(g,[[.45,-1.10],[1.30,-1.10],[1.30,-1.02]],.31,.520,C.stone,M.paving); + for(const x of [-2.25,2.3])path(g,[[x,-2.30],[x,-2.13],[.45,-2.13]],.18,.514,C.paving,M.paving); + // The new lamps share one baked ground-light map, not twenty dynamic lights. + for(const [x,z] of STREET_LIGHTS.slice(9))prop('heritage-lamp',[x,.49,z],0,.94); + const trees=[[-2.81,-2.82,.75],[-.90,-2.83,.76],[.04,-2.82,.72],[2.76,-2.03,.79],[2.76,-.39,.82],[2.78,.42,.70],[2.78,2.58,.84],[.94,2.74,.70],[-2.76,-.58,.65],[-2.76,-1.82,.64]]; + for(const [x,z,s] of trees){B(g,[x,.496,z],[.28,.029,.26],'#887354',M.stone,.018);prop('linden',[x,.514,z],.36,s);} + for(const [x,z,a] of [[.67,-1.08,0],[1.90,-1.08,0],[2.77,.94,-Math.PI/2],[-2.81,-1.10,Math.PI/2]])prop('bench',[x,.52,z],a,.92); + // Low perennial beds make the pavilion approach less sterile, without masking paths. + for(const [x,z] of [[.70,-1.46],[1.95,-1.46],[2.51,2.48]]){ + B(g,[x,.505,z],[.23,.055,.34],C.stone,M.stone,.022); + for(let i=0;i<3;i++)g.lathe([x,.535,z+(i-1)*.083],[[0,0],[.080,.015],[.085,.09],[0,.15]],i%2?'#80a071':'#4f775d',M.foliage,6); + } + return g.build(`public-landscape-${lod}`); +} +export const PUBLIC_FACTORIES=Object.freeze({pavilion,metro,landscape}); +export const PUBLIC_BUDGETS=Object.freeze({pavilion:[4200,6500],metro:[800,1000],landscape:[5000,8500]}); +export function createPublicAsset(name,lod='low'){ + if(!PUBLIC_FACTORIES[name]||!['low','high'].includes(lod))throw Error('Invalid public asset'); + const g=PUBLIC_FACTORIES[name](lod);if(g.indices.length/3>PUBLIC_BUDGETS[name][lod==='high'?1:0])throw Error(`Public budget ${g.name}: ${g.indices.length/3}`);return g; +} +function publicBatch(lod){const g=new MeshBuilder();g.add(createPublicAsset('pavilion',lod),PUBLIC_PLACEMENT.pavilion);for(const p of PUBLIC_PLACEMENT.metro)g.add(createPublicAsset('metro',lod),p);g.add(createPublicAsset('landscape',lod));return g.build(`public-equipment-${lod}`);} +export class PublicRealm{ + constructor(renderer){this.renderer=renderer;this.quality='high';this.detail='low';this.cache=new Map();this.builds=0;this.ensure();} + ensure(){if(!this.cache.has(this.detail)){this.cache.set(this.detail,this.renderer.mesh(publicBatch(this.detail)));this.builds++;}this.mesh=this.cache.get(this.detail);} + configure(s={}){this.quality=s.quality??this.quality;if(this.quality==='low'&&this.detail!=='low'){this.detail='low';this.ensure();}} + selectDetail(p){const d=this.quality!=='low'&&p>(this.detail==='high'?55:65)?'high':'low';if(d!==this.detail){this.detail=d;this.ensure();}} + objects(){this.stats={builds:this.builds,cachedMeshes:this.cache.size,triangles:this.mesh.count/3,drawCalls:1};return [{mesh:this.mesh}];} + destroy(){for(const m of this.cache.values())this.renderer.drop(m);this.cache.clear();} +} diff --git a/src/scene/finish/shader.js b/src/scene/finish/shader.js new file mode 100644 index 0000000..b5f114b --- /dev/null +++ b/src/scene/finish/shader.js @@ -0,0 +1,93 @@ +/** Shared stylised linear-light surface response. Analytic sky, GGX/Schlick specular, + * generated detail normals, contact field, and retained bounded planar marina reflections. + * This is not a full image-based PBR pipeline or global illumination. No bloom or blur. */ +import {WATERFRONT_FRAGMENT} from '../marina/finish.js'; +export const FINISH_FRAGMENT=` +uniform sampler2D uSurface;uniform sampler2D uDetail;uniform sampler2D uGround; +uniform float uGroundReady;uniform float uFineLighting; +uniform vec3 uCamera;uniform vec3 uObjectTint;uniform float uClosed;uniform float uStudio; +uniform vec3 uHarborLights[4]; +${WATERFRONT_FRAGMENT} +vec3 displayColor(vec3 c){c=max(c,vec3(0.));c=(c*(2.51*c+.03))/(c*(2.43*c+.59)+.14);return pow(clamp(c,0.,1.),vec3(1./2.2));} +vec3 skyColor(vec3 dir){ + vec3 sky=mix(vec3(.18,.31,.40),vec3(.53,.77,.96),smoothstep(-.15,.85,dir.y)); + sky=mix(sky,vec3(.98,.47,.19),uDusk*pow(1.-max(dir.y,0.),2.)*.70); + return sky*mix(vec3(1.),vec3(.065,.13,.27),uNight); +} +vec3 microNormal(vec3 n,vec2 map){ + vec3 dp1=dFdx(vWorld),dp2=dFdy(vWorld);vec2 duv1=dFdx(vUv),duv2=dFdy(vUv); + vec3 p2=cross(dp2,n),p1=cross(n,dp1),t=p2*duv1.x+p1*duv2.x,b=p2*duv1.y+p1*duv2.y; + float inv=inversesqrt(max(max(dot(t,t),dot(b,b)),.0000001)); + return normalize(n+t*map.x*inv+b*map.y*inv); +} +vec3 seaShade(vec3 n,float shadow){ + float edge=max(abs(vWorld.x),abs(vWorld.z))-7.60; + vec3 haze=vec3(.955,.950,.924)-uNight*vec3(.19,.17,.12); + if(edge>=2.80)return haze; + vec3 v=normalize(uCamera-vWorld),l=normalize(vec3(-.5,.9,.55)); + float a=vWorld.x*14.7+vWorld.z*9.2+sin(vWorld.z*3.1)*1.6+uTime*.48,b=vWorld.x*7.2-vWorld.z*15.1+cos(vWorld.x*2.7)*1.4+uTime*.37; + float aa=1./(1.+fwidth(a)*1.8);n=normalize(vec3((sin(a)+sin(b)*.45)*.07*aa,1.,cos(b)*.055*aa)); + vec3 color=mix(vec3(.028,.13,.18),vec3(.05,.29,.33),exp(-max(edge,0.)*.72)); + color*=1.-shadow*.58;color*=mix(vec3(1.),vec3(.24,.40,.63),uNight); + color+=vec3(.08,.17,.19)*pow(max(dot(n,normalize(v+l)),0.),95.)*aa*(1.-uNight*.8); + color+=vec3(.003,.006,.007)*sin(a+b*.38)*aa; + return mix(pow(max(color,vec3(0.)),vec3(.85)),haze,smoothstep(.20,2.80,max(edge,0.))); +} +vec3 marinaShade(vec3 color,vec3 normal,float diffuse,float shadow){ + int m=int(vTex+.5);vec3 n=normal,v=normalize(uCamera-vWorld),l=normalize(vec3(-.5,.9,.55)); + if(m==21)return seaShade(n,shadow); + float rough=m==5?.19:m==10?.25:m==4?.33:m==8?.36:m==11?.24:.84; + float tile=m==6?0.:m==7?1.:m==8?2.:m==15?3.:m==17?4.:m==18?5.:m==19?6.:m==20?7.:-1.; + if(tile>=0.){ + vec2 uv=vec2(mod(tile,4.),floor(tile/4.))*.25+(fract(vUv)*60.+2.)/256.; + vec2 dx=dFdx(vUv)*60./256.,dy=dFdy(vUv)*60./256.; + vec3 tex=textureGrad(uSurface,uv,dx,dy).rgb; + color*=mix(vec3(1.),tex,m==15?.25:.62); + if(uFineLighting>.5&&uStudio<.5&&uReflectionPass<.5){vec3 detail=textureGrad(uDetail,uv,dx,dy).rgb;n=microNormal(n,(detail.rg*2.-1.)*.64);rough=detail.b;} + } + if(m==14)color*=uObjectTint; + if(uClosed>.5)color=mix(color,vec3(dot(color,vec3(.2126,.7152,.0722))),.72); + float lamps=max(uNight,uDusk*.70); + if(m==11||m==12)color=mix(vec3(.13,.25,.29),color,lamps*(1.-uClosed)*float(m==11)); + if(uStudio>.5)return color*(.34+.66*diffuse); + if(m==9){vec3 water=waterfrontFinish(color,normal,diffuse,shadow,m);return pow(max(water,vec3(0.)),vec3(.92));} + vec3 albedo=pow(max(color,vec3(.001)),vec3(2.2)); + float metallic=m==10?.82:m==8?.36:m==20?.24:0.; + float glass=float(m==5||m==11||m==12),NoL=max(dot(n,l),0.),NoV=max(dot(n,v),.001); + vec3 f0=mix(vec3(.04),albedo,metallic),spec=vec3(0.); + // Matte stone/soil/foliage do not pay for a barely visible specular lobe. + if(rough<.65){ + vec3 halfV=normalize(l+v);float NoH=max(dot(n,halfV),0.),VoH=max(dot(v,halfV),0.); + rough=max(rough,.17);float alpha=rough*rough,a2=alpha*alpha; + float denom=NoH*NoH*(a2-1.)+1.,D=a2/(3.14159*denom*denom+.0001),k=(rough+1.)*(rough+1.)*.125; + float G=NoV/(NoV*(1.-k)+k)*NoL/(NoL*(1.-k)+k); + vec3 F=f0+(1.-f0)*pow(1.-VoH,5.);spec=D*G*F/max(4.*NoV*max(NoL,.01),.01); + } + vec3 sun=mix(vec3(1.48,1.34,1.12),vec3(2.10,1.13,.47),uDusk*.75)*(1.-uNight*.95); + vec3 ambient=mix(vec3(.11,.16,.22),vec3(.35,.44,.52),n.y*.5+.5); + ambient*=mix(vec3(1.),vec3(.12,.22,.40),uNight); + vec3 ground=vec3(1.,0.,0.); + if(uGroundReady>.5&&vWorld.y<.86&&abs(vWorld.x)<7.8&&abs(vWorld.z)<7.8){ + vec3 field=texture(uGround,(vWorld.xz+8.)/16.).rgb;ground=mix(vec3(1.,0.,0.),field,1.-smoothstep(.55,.86,vWorld.y)); + } + float bounce=.78+.22*smoothstep(.49,1.12,vWorld.y); + vec3 radiance=albedo*(ambient*ground.r*bounce+sun*NoL*(1.-shadow*.87))*(1.-metallic*.73); + radiance+=spec*sun*NoL*(1.-shadow*.90); + if(rough<.65){ + vec3 sky=pow(max(skyColor(reflect(-v,n)),vec3(.001)),vec3(2.2)); + vec3 envF=f0+(1.-f0)*pow(1.-NoV,5.); + radiance+=sky*envF*(1.-rough*.65)*(1.+glass*2.4); + if(m==5)radiance=mix(radiance,sky*(.38+.40*pow(1.-NoV,3.))+albedo*.16,.64); + } + if(m==13){radiance+=albedo*vec3(.45,.65,.23)*pow(max(dot(-n,l),0.),2.)*(1.-uNight);radiance*=vec3(.83,1.02,.78);} + if(m==7&&uWaterfront>.5)radiance*=.76+.24*smoothstep(.432,.57,vWorld.y); + radiance+=albedo*(ground.g*vec3(2.9,1.45,.44)+ground.b*vec3(.29,1.25,1.70))*lamps; + if(m==11&&uClosed<.5){float room=.76+.24*step(.35,fract(sin(dot(floor(vWorld*9.),vec3(1.7,8.1,3.4)))*4357.));radiance+=vec3(1.8,.92,.24)*lamps*room;} + if(m==16)radiance+=vec3(2.2,1.13,.34)*(.12+lamps*1.30); + if(lamps>.01)for(int i=0;i<4;i++){ + vec3 d=uHarborLights[i]-vWorld;float ds=dot(d,d),nd=max(dot(n,normalize(d)),0.); + radiance+=albedo*vec3(1.,.52,.18)*nd*.15/(.08+ds)*lamps; + } + return mix(displayColor(radiance),vec3(.41,.51,.55),uWeather*.045); +} +`; diff --git a/src/scene/harmony.js b/src/scene/harmony.js index 6cc254d..e82f0ac 100644 --- a/src/scene/harmony.js +++ b/src/scene/harmony.js @@ -3,9 +3,10 @@ import {MeshBuilder,rgb} from './marina/mesh-builder.js'; import {MATERIALS as M} from './marina/surfaces.js'; import {createHarmonyAsset} from './harmony/kit.js'; import {model} from './math.js'; -const HARMONY_SPEC=Object.freeze({22:['roseraie',0],23:['roseraie',1]}); +const HARMONY_SPEC=Object.freeze({4:['jardins',0],5:['jardins',1],18:['nova',0],19:['nova',1],22:['roseraie',0],23:['roseraie',1],25:['solstice',0],26:['solstice',1]}); const HARMONY_LOTS=Object.freeze(Object.keys(HARMONY_SPEC).map(Number)); const HARMONY_CACHE_LIMIT=16; +const HARMONY_CACHE_BYTES=4*1024*1024; function pennant(){const g=new MeshBuilder();g.rod([0,0,0],[0,.25,0],.008,'#7b8e80',M.metal,5);g.box([.044,.206,0],[.090,.069,.012],'#ffffff',M.canvas);return g.build('neighbourhood-owner-pennant');} class Harmony { constructor(renderer){this.renderer=renderer;this.detail='low';this.quality='high';this.cache=new Map();this.entries=[];this.builds=0;this.clock=0;this.flag=renderer.mesh(pennant());} @@ -22,9 +23,16 @@ class Harmony { const yaw=p.id>=22?-Math.PI/2:p.id<7?Math.PI:0; return {id:p.id,key,level,owner:p.owner,closed:p.mortgaged?1:0,mesh:item.mesh,model:model(p.x,.48,p.z,0,yaw),flagModel:model(p.x+.39,.53,p.z+.38),tint:rgb(p.mortgaged?'#949b94':p.color)}; }); - const used=new Set(this.entries.map(e=>e.key));for(const [key,item] of [...this.cache].sort((a,b)=>a[1].used-b[1].used)){if(this.cache.size<=HARMONY_CACHE_LIMIT)break;if(!used.has(key)){this.renderer.drop(item.mesh);this.cache.delete(key);}} + // Retain current visible meshes; evict only least-recently-used inactive LODs. + // Eight active high-detail variants fit under 4 MiB; counts alone did not bound bytes. + const used=new Set(this.entries.map(e=>e.key)); + let bytes=[...this.cache.values()].reduce((n,item)=>n+(item.mesh.bytes??0),0); + for(const [key,item] of [...this.cache].sort((a,b)=>a[1].used-b[1].used)){ + if(this.cache.size<=HARMONY_CACHE_LIMIT&&bytes<=HARMONY_CACHE_BYTES)break; + if(!used.has(key)){bytes-=item.mesh.bytes??0;this.renderer.drop(item.mesh);this.cache.delete(key);} + } } objects(){const out=[];for(const e of this.entries){out.push({mesh:e.mesh,model:e.model,closed:e.closed});if(e.owner)out.push({mesh:this.flag,model:e.flagModel,tint:e.tint,closed:e.closed});}this.stats={detail:this.detail,builds:this.builds,cachedMeshes:this.cache.size,cachedGpuBytes:[...this.cache.values()].reduce((n,m)=>n+m.mesh.bytes,0),triangles:out.reduce((n,o)=>n+o.mesh.count/3,0),objects:out.length};return out;} destroy(){for(const {mesh} of this.cache.values())this.renderer.drop(mesh);this.cache.clear();this.renderer.drop(this.flag);} } -export {Harmony,HARMONY_SPEC,HARMONY_LOTS,HARMONY_CACHE_LIMIT}; +export {Harmony,HARMONY_SPEC,HARMONY_LOTS,HARMONY_CACHE_LIMIT,HARMONY_CACHE_BYTES}; diff --git a/src/scene/harmony/extensions.js b/src/scene/harmony/extensions.js new file mode 100644 index 0000000..6fa084d --- /dev/null +++ b/src/scene/harmony/extensions.js @@ -0,0 +1,97 @@ +/** Completion of the six real lots. All elevations/terraces are volumetric. + * Y-up, base at zero, +Z entrance. Geometry changes only with the legal level. + * The retained Roseraie factory is deliberately not duplicated here. */ +import {MATERIALS as M} from '../marina/surfaces.js'; +import {C,B,R,planter,cedar,rail,shell,hip,barrel,pergola,steps} from './architecture.js'; + +function roofGarden(g,x,z,w,d,y,fine){ + B(g,[x,y,z],[w,.045,d],C.stone,M.stone,.009); + B(g,[x,y+.029,z],[w-.05,.018,d-.05],'#6e9367',M.foliage); + for(const s of [-1,1])B(g,[x+s*(w/2-.017),y+.043,z],[.034,.080,d],C.chalk); + if(fine)for(const s of [-1,1])B(g,[x,y+.043,z+s*(d/2-.017)],[w,.080,.034],C.chalk); +} +function dome(g,x,z,y,r,fine,color=C.roof){ + g.lathe([x,y,z],[[r*1.08,0],[r*1.08,.034],[r,.034],[r,.095],[r*.95,.15],[r*.75,.235],[r*.40,.30],[0,.335]],color,M.roof,fine?16:10); + R(g,[x,y+.31,z],[x,y+.405,z],.011,C.brass,M.metal,6); +} +function jardins(g,level,v,fine){ + if(v===0){ + // Jardin Suspendu: stepped limestone maison, projecting planted terraces. + const floors=level===0?1:level===3?3:2; + const h=shell(g,-.105,-.13,.46,.43,.075,floors,fine,'#ead7b9'); + hip(g,-.105,-.13,.53,.50,h,.19,C.roof,M.slate,fine); + if(level>=2){const w=shell(g,.245,-.09,.23,.36,.075,level===3?2:1,fine,C.chalk,M.glass);roofGarden(g,.245,-.09,.27,.40,w+.016,fine);} + else {barrel(g,.245,-.09,.235,.34,.15,.26,fine);} + for(let f=0;f=2?2:1,fine,C.chalk,M.glass); + barrel(g,-.16,-.09,.41,.52,h,.18,fine); + const tower=shell(g,.245,-.16,.23,.27,.075,1+Math.min(level,2),fine,C.stone); + hip(g,.245,-.16,.28,.33,tower,.19,'#956c4f',M.slate,fine); + if(level===3){const wing=shell(g,.19,.21,.31,.20,.075,1,fine,C.chalk);roofGarden(g,.19,.21,.35,.24,wing,fine);rail(g,.19,wing+.04,.335,.30,fine);} + steps(g,-.16,.29,.28);cedar(g,-.36,.24,.52,fine);cedar(g,.36,.30,.56,fine); + if(level>=1)pergola(g,.14,.20,.22,.19,.34,fine); + } +} +function nova(g,level,v,fine){ + if(v===0){ + // Nova Square: rising tech campus, deep pale fins around blue glazing. + const h=shell(g,-.04,-.11,.58,.44,.075,1,fine,C.chalk,M.glass); + B(g,[-.04,h+.018,-.11],[.65,.048,.50],C.dark,M.metal,.01); + const floors=level+1,w=.38,d=.32,top=shell(g,-.02,-.13,w,d,h+.045,floors,fine,'#b3bec7',M.glass); + for(const x of [-.225,.185])B(g,[x,(h+top)/2,-.13],[.028,top-h+.09,.40],C.chalk,M.stone); + B(g,[-.02,top+.075,-.13],[.45,.12,.37],C.dark,M.metal,.014); + B(g,[-.02,top+.146,-.13],[.47,.027,.40],C.brass,M.metal,.006); + if(level>=2){const wing=shell(g,.25,.14,.22,.24,.075,2,fine,C.stone,M.glass);roofGarden(g,.25,.14,.26,.28,wing+.018,fine);} + if(level===3){R(g,[-.15,top+.15,-.21],[-.15,top+.42,-.21],.008,C.brass);} + B(g,[-.14,.39,.21],[.40,.035,.20],C.dark,M.metal,.007);steps(g,-.14,.34,.28); + planter(g,-.34,.29,.16,.13,fine);planter(g,.34,.30,.15,.12,fine); + }else{ + // Observatoire: distinct round drum/dome on a terraced research pavilion. + const h=shell(g,-.09,-.11,.49,.45,.075,1+Math.min(level,2),fine,C.chalk,M.glass); + B(g,[-.09,h+.018,-.11],[.55,.041,.51],C.brass,M.metal,.006); + g.lathe([-.09,h+.035,-.11],[[.19,0],[.19,.04],[.17,.04],[.17,.20],[.19,.20],[.19,.235]],C.stone,M.stone,fine?16:10); + dome(g,-.09,-.11,h+.267,.20,fine,'#547e93'); + for(const side of [-1,1])B(g,[-.09+side*.18,h+.14,-.11],[.016,.095,.075],C.glass,M.glass); + if(level>=1){const wing=shell(g,.25,.17,.25,.28,.075,1,fine,C.stone,M.glass);roofGarden(g,.25,.17,.29,.33,wing+.01,fine);} + if(level===3){const side=shell(g,.255,-.25,.20,.22,.075,2,fine,C.stone);hip(g,.255,-.25,.24,.27,side,.12,C.roof,M.roof,fine);} + planter(g,-.34,.29,.16,.12,fine);steps(g,-.10,.30,.28); + } +} +function solstice(g,level,v,fine){ + if(v===0){ + // Palais Solaire: warm resort palazzo, twin wings and copper/gold belvedere. + const floors=level+1,h=shell(g,-.065,-.115,.51,.45,.075,floors,fine,'#eed6ad'); + hip(g,-.065,-.115,.57,.51,h,.20,'#ab7453',M.slate,fine); + if(level>=1){const wing=shell(g,.28,.02,.22,.33,.075,Math.max(1,level-1),fine,C.chalk);hip(g,.28,.02,.27,.38,wing,.15,C.roof,M.roof,fine);} + for(let j=0;j=2){B(g,[.05,y+.08,-.16],[.22,.13,.22],C.glass,M.glass,.009);B(g,[.05,y+.16,-.16],[.29,.035,.29],C.brass,M.metal);} + B(g,[.14,.365,.22],[.37,.035,.20],C.dark,M.metal,.005);steps(g,-.045,.31,.28); + planter(g,-.34,.28,.15,.13,fine);planter(g,.34,.30,.15,.13,fine); + } +} +export {jardins,nova,solstice}; diff --git a/src/scene/harmony/kit.js b/src/scene/harmony/kit.js index 14fdd26..fefa072 100644 --- a/src/scene/harmony/kit.js +++ b/src/scene/harmony/kit.js @@ -2,8 +2,9 @@ import { MeshBuilder } from '../marina/mesh-builder.js'; import { MATERIALS as M } from '../marina/surfaces.js'; import {C,B,R,base,planter,cedar,rail,shell,hip,barrel,pergola,steps} from './architecture.js'; -const HARMONY_FAMILIES=Object.freeze(['roseraie']); -const HARMONY_BUDGETS=Object.freeze({roseraie:[3200,5200]}); +import {jardins,nova,solstice} from './extensions.js'; +const HARMONY_FAMILIES=Object.freeze(['jardins','nova','roseraie','solstice']); +const HARMONY_BUDGETS=Object.freeze({jardins:[3400,5600],nova:[3600,5800],roseraie:[3200,5200],solstice:[4400,7400]}); function roseraie(g,level,variant,fine){ if(variant===0){ // Villa Rosée: staggered hipped roofs, courtyard and timber loggia, never a pink tower. @@ -36,7 +37,7 @@ function roseraie(g,level,variant,fine){ function createHarmonyAsset(family,level=0,variant=0,lod='low'){ if(!HARMONY_FAMILIES.includes(family)||!Number.isInteger(level)||level< -1||level>3||![0,1].includes(variant)||!['low','high'].includes(lod))throw Error('Invalid harmony asset'); const g=new MeshBuilder();base(g,family,level); - if(level>=0)roseraie(g,level,variant,lod==='high'); + if(level>=0)({jardins,nova,roseraie,solstice})[family](g,level,variant,lod==='high'); const result=g.build(`${family}-${variant}-level-${level}-${lod}`); const budget=HARMONY_BUDGETS[family][lod==='high'?1:0];if(result.indices.length/3>budget)throw Error(`${result.name}: ${result.indices.length/3} exceeds ${budget} triangles`); return result; diff --git a/src/scene/living-city.js b/src/scene/living-city.js index 1cb4577..005e0b9 100644 --- a/src/scene/living-city.js +++ b/src/scene/living-city.js @@ -1,3 +1,6 @@ +import {effectMesh} from './finish/effects.js'; +import {rgb} from './marina/mesh-builder.js'; +import {PublicRealm} from './finish/public.js'; import { Harmony, HARMONY_LOTS } from './harmony.js'; import { CivicCenter } from './civic.js'; import { Districts, DISTRICT_LOTS } from './districts.js'; @@ -80,24 +83,15 @@ function infrastructure() { const g=new Geometry(); // Two closed roads. The outside bus lane never obscures the property labels. for(const radius of [4.48,6.98])for(const side of [-1,1]) { - g.block([0,.378,side*radius],[radius*2+.5,.04,.48],'#748c84'); - g.block([side*radius,.379,0],[.48,.04,radius*2+.5],'#748c84'); - for(let x=-radius+.5;xrenderer.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.fx={};for(const lod of ['low','high'])for(const kind of ['burst','dust','scan'])this.fx[`${kind}:${lod}`]=renderer.mesh(effectMesh(kind,lod)); 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.publicRealm.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=[];} } 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.marina.setCity(next);this.districts.setCity(next);this.harmony.setCity(next);this.renderer.setGroundCity?.(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}); @@ -159,7 +153,7 @@ class LivingCity { } objects(seconds,rain=0) { this.elapsed=seconds; - const out=[{mesh:this.staticMesh},...this.marina.objects(seconds),...this.districts.objects(),...this.civic.objects(),...this.harmony.objects()];if(this.parcelMesh)out.push({mesh:this.parcelMesh}); + const out=[{mesh:this.staticMesh},...this.marina.objects(seconds),...this.districts.objects(),...this.civic.objects(),...this.harmony.objects(),...this.publicRealm.objects()];if(this.parcelMesh)out.push({mesh:this.parcelMesh}); 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}; @@ -196,9 +190,15 @@ 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}); 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; - out.push({mesh:this.spark,model:model(p.x+Math.cos(a)*.55,1+((t+i*.1)%1)*1.4,p.z+Math.sin(a)*.55),noShadow:true}); + const fxLOD=this.quality==='low'?'low':'high'; + if(running){ + for(const c of this.cranes.slice(-(this.quality==='low'?2:4))){ + const age=t-(c.until-6);if(age<3){const p=this.city.parcels.find(p=>p.id===c.id);const common={model:model(c.x,.50,c.z),noShadow:true,effect:true,effectAge:age,tint:rgb(p?.color??gold)}; + out.push({...common,mesh:this.fx[`scan:${fxLOD}`],effectKind:2}); + if(age<2.4&&this.quality!=='low')out.push({...common,mesh:this.fx[`dust:${fxLOD}`],effectKind:1}); + } + } + for(const c of this.celebrations.slice(-2))for(const p of this.city.parcels.filter(p=>p.group===c.group))out.push({mesh:this.fx[`burst:${fxLOD}`],model:model(p.x,.60,p.z),tint:rgb(p.color),effect:true,effectKind:0,effectAge:t-(c.until-4),noShadow:true}); } if(running&&rain>.1)for(let i=0;i.5?0.:uNight;float dusk=uStudio>.5?0.:uDusk;float lamps=max(night,dusk*.58); - float tile=material==6?0.:material==7?1.:material==8?2.:material==15?3.:material==17?4.:material==18?5.:material==19?6.:material==20?7.:-1.; - if(tile>=0.) { - vec2 corner=vec2(mod(tile,4.),floor(tile/4.))*.25; - vec2 uv=corner+(fract(vUv)*60.+2.)/256.; - vec3 tex=textureGrad(uSurface,uv,dFdx(vUv)*60./256.,dFdy(vUv)*60./256.).rgb; - color*=mix(vec3(1.),tex,material==15?.35:.73); - } - if(material==14)color*=uObjectTint; - if(uClosed>.5)color=mix(color,vec3(dot(color,vec3(.2126,.7152,.0722))),.68); - if(material==11||material==12)color=mix(vec3(.15,.30,.33),color,lamps*(1.-uClosed)*float(material==11)); - if(uStudio>.5) { - if(material==5)color=mix(color,vec3(.22,.36,.40),.3); - return color*(.39+.61*diffuse*(1.-shadow*.70)); - } - if(uWaterfront>.5)return waterfrontFinish(color,normal,diffuse,shadow,material); - vec3 sun=normalize(vec3(-.5,.9,.55)); - if(material==9) { - float a=vWorld.x*33.+vWorld.z*23.+uTime*1.35,b=vWorld.x*16.-vWorld.z*27.+uTime*.94; - float attenuation=1./(1.+fwidth(a)*.8); - n=normalize(vec3((sin(a)*.080+sin(b)*.042)*attenuation,1.,cos(a*.73+b*.32)*.080*attenuation)); - float edge=min(min(abs(vWorld.x+2.966),abs(vWorld.x+1.01)),min(abs(vWorld.z-.914),abs(vWorld.z-3.165))); - color=mix(vec3(.035,.255,.296),vec3(.145,.405,.395),exp(-edge*7.)*.55); - color+=sin(a*.46+b*.62)*.012*attenuation; - diffuse=max(dot(n,sun),0.); - } - float fresnel=pow(1.-max(dot(n,v),0.),5.); - float light=.44+.56*diffuse*(1.-shadow*.73); - vec3 hemisphere=mix(vec3(.79,.86,.89),vec3(1.055,1.027,.94),n.y*.5+.5); - vec3 shaded=color*light*hemisphere*mix(vec3(1.),vec3(.40,.51,.64),night); - shaded*=mix(vec3(1.),vec3(1.09,.96,.81),dusk*.72); - float shiny=material==5?.65:material==9?.68:material==10?.62:material==4?.22:material==8?.13:.015; - if(material==5||material==9||material==10) { - vec3 r=reflect(-v,n);vec3 sky=mix(vec3(.37,.52,.53),vec3(.64,.81,.87),smoothstep(-.08,.85,r.y)); - sky=mix(sky,vec3(.82,.63,.47),dusk*(1.-smoothstep(.0,.6,r.y))*.45); - sky*=mix(vec3(1.),vec3(.16,.26,.44),night); - float amount=material==9?.15+fresnel*.55:material==5?.27+fresnel*.50:.18+fresnel*.28; - shaded=mix(shaded,sky,amount); - } - float spec=pow(max(dot(n,normalize(sun+v)),0.),material==9?100.:material==5?76.:material==4?55.:28.); - shaded+=vec3(1.,.96,.86)*spec*shiny*(1.-shadow*.8)*(1.-night*.86); - if(material==11&&uClosed<.5)shaded=mix(shaded,color*(.88+.035*sin(uTime*.15)),lamps*.94); - if(material==16)shaded=mix(color*light*.76,color*1.02,lamps); - if(lamps>.01)for(int i=0;i<4;i++) { - vec3 d=uHarborLights[i]-vWorld;float ds=dot(d,d);vec3 l=normalize(d); - float pool=max(dot(n,l),0.)*.043/(.045+ds); - float glint=pow(max(dot(n,normalize(l+v)),0.),material==9?62.:35.)*.10/(.02+ds); - shaded+=vec3(1.,.65,.30)*(pool+glint*shiny)*lamps; - } - return mix(shaded,vec3(.48,.59,.61),uWeather*.075); -} -`; -export { MARINA_FRAGMENT }; +import {FINISH_FRAGMENT} from '../finish/shader.js'; +const MARINA_FRAGMENT=FINISH_FRAGMENT; +export {MARINA_FRAGMENT}; diff --git a/src/scene/webgl.js b/src/scene/webgl.js index 21bf2a3..4f221c0 100644 --- a/src/scene/webgl.js +++ b/src/scene/webgl.js @@ -1,3 +1,6 @@ +import {cityField} from './finish/field.js'; +import {detailAtlas} from './finish/materials.js'; +import {EFFECT_VERTEX} from './finish/effects.js'; import { WaterfrontReflection } from './marina/reflection.js'; import { surfaceAtlas } from './marina/surfaces.js'; import { MARINA_FRAGMENT } from './marina/shader.js'; @@ -8,13 +11,14 @@ layout(location=0) in vec3 aPosition; layout(location=1) in vec3 aNormal; layout(location=2) in vec3 aColor; layout(location=3) in vec2 aUv; layout(location=4) in float aTex; uniform mat4 uModel; uniform mat4 uVP; uniform mat4 uLight; out vec3 vWorld;out vec3 vNormal;out vec3 vColor;out vec2 vUv;out float vTex;out vec4 vShadow; -void main(){vec4 world=uModel*vec4(aPosition,1.);vWorld=world.xyz;gl_Position=uVP*world;vNormal=normalize(mat3(uModel)*aNormal);vColor=aColor;vUv=aUv;vTex=aTex;vShadow=uLight*world;}`; +${EFFECT_VERTEX} +void main(){vec4 world=uModel*vec4(effectPosition(aPosition),1.);vWorld=world.xyz;gl_Position=uVP*world;vNormal=normalize(mat3(uModel)*aNormal);vColor=aColor;vUv=aUv;vTex=aTex;vShadow=uLight*world;}`; const FRAG=`#version 300 es precision highp float; -in vec3 vWorld;in vec3 vNormal;in vec3 vColor;in vec2 vUv;in float vTex;in vec4 vShadow; +in float vEffectFade;in vec3 vWorld;in vec3 vNormal;in vec3 vColor;in vec2 vUv;in float vTex;in vec4 vShadow; uniform float uNight;uniform float uDusk;uniform float uWeather;uniform float uTime;uniform sampler2D uAtlas;uniform sampler2D uShadow;uniform float uUseShadow;out vec4 frag; ${MARINA_FRAGMENT} -void main(){if(uReflectionPass>.5&&vWorld.y<.428)discard;vec3 base=vColor; if(vTex>.5&&vTex<1.5){vec4 t=texture(uAtlas,vUv);base=mix(base,t.rgb,t.a);} +void main(){if(vTex>22.5){if(vEffectFade<.008)discard;frag=vec4(vColor*mix(vec3(1.),uObjectTint,.42)*(1.+uNight*.3),vEffectFade);return;}if(uReflectionPass>.5&&vWorld.y<.428)discard;vec3 base=vColor; if(vTex>.5&&vTex<1.5){vec4 t=texture(uAtlas,vUv);base=mix(base,t.rgb,t.a);} vec3 n=normalize(vNormal);float diffuse=max(dot(n,normalize(vec3(-.5,.9,.55))),0.); vec3 p=vShadow.xyz/vShadow.w*.5+.5;float shadow=0.; if(uUseShadow>.5&&p.x>0.&&p.x<1.&&p.y>0.&&p.y<1.&&p.z<1.){ @@ -22,7 +26,7 @@ void main(){if(uReflectionPass>.5&&vWorld.y<.428)discard;vec3 base=vColor; if(vT for(int x=-1;x<=1;x++)for(int y=-1;y<=1;y++){float depth=texture(uShadow,p.xy+vec2(float(x),float(y))/2048.).r;shadow+=(p.z-bias>depth?1.:0.);} shadow/=9.; } - if(vTex>3.5){frag=vec4(marinaShade(base,n,diffuse,shadow),1.);return;} + if(vTex>3.5||vTex<.5){frag=vec4(marinaShade(base,n,diffuse,shadow),1.);return;} float light=.68+.32*diffuse*(1.-shadow*.78);float rim=pow(max(n.y,0.),3.)*.025; vec3 shaded=(base*light+rim)*mix(vec3(1.),vec3(.46,.57,.69),uNight); if(vTex>.5&&vTex<1.5)shaded=mix(base*light,shaded,.48); @@ -52,11 +56,11 @@ class Renderer { this.gl=gl;this.canvas=canvas;this.atlasSource=atlas;this.meshes=new Set();this.uniforms=new Map(); this._shadows=true;this.lost=false;this.meshUploads=0;this.meshDrops=0;this.restoreCount=0; this.light=multiply(ortho(-12,12,-12,12,.1,60),lookAt([-10,21,13],[0,0,0])); - this.reflections=new WaterfrontReflection(this);this.initializeGPU(); + this.groundSource=cityField();this.groundUploads=0;this.groundDirty=false;this.reflections=new WaterfrontReflection(this);this.initializeGPU(); this.abort=new AbortController();const opts={signal:this.abort.signal}; canvas.addEventListener('webglcontextlost',e=>{ e.preventDefault();this.lost=true;this.reflections.forget();this.reflections.memory();this.shadow=null;this.fb=null;this.shadowOK=false; - this.textureBytes.shadowDepth24StorageUpperBound=0; + this.textureBytes.shadowDepth24StorageUpperBound=0;this.ground=null;this.detail=null;this.textureBytes.groundFieldRGBA8=0;this.textureBytes.materialDetailMipmapped=0; this.stats={...this.stats,contextLost:true,gpuBufferBytes:0,drawCalls:0,shadowDrawCalls:0}; },opts); canvas.addEventListener('webglcontextrestored',()=>{ @@ -75,6 +79,15 @@ class Renderer { gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,surface.width,surface.height,0,gl.RGBA,gl.UNSIGNED_BYTE,surface.data);gl.generateMipmap(gl.TEXTURE_2D); gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR); this.textureBytes={boardAtlasMipmapped:Math.round(atlas.width*atlas.height*4*4/3),surfaceAtlasMipmapped:Math.round(surface.width*surface.height*4*4/3),shadowDepth24StorageUpperBound:0}; + const detail=detailAtlas();this.detail=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,this.detail); + gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,detail.width,detail.height,0,gl.RGBA,gl.UNSIGNED_BYTE,detail.data);gl.generateMipmap(gl.TEXTURE_2D); + gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR); + this.ground=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,this.ground);const field=this.groundSource; + gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,field.width,field.height,0,gl.RGBA,gl.UNSIGNED_BYTE,field.data); + gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE); + this.groundUploads++;this.groundDirty=false; + this.textureBytes.materialDetailMipmapped=Math.round(detail.data.byteLength*4/3);this.textureBytes.groundFieldRGBA8=field.data.byteLength; this.reflections.memory(); // No shadow allocation at construction or in low mode. A complete colour texture is // bound to the inactive depth sampler; no incomplete-texture warnings on mobile GL. @@ -82,6 +95,8 @@ class Renderer { gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.enable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE); this.defaultFramebufferConfig={depthBits:gl.getParameter(gl.DEPTH_BITS),samples:gl.getParameter(gl.SAMPLES),driverAllocationUnknown:true}; } + setGroundCity(city){if(this.groundSignature===city.signature)return;this.groundSignature=city.signature;this.groundSource=cityField(city);this.groundDirty=true;} + syncGround(){if(!this.groundDirty||this.lost)return;const g=this.gl,f=this.groundSource;g.activeTexture(g.TEXTURE4);g.bindTexture(g.TEXTURE_2D,this.ground);g.texSubImage2D(g.TEXTURE_2D,0,0,0,f.width,f.height,g.RGBA,g.UNSIGNED_BYTE,f.data);this.groundUploads++;this.groundDirty=false;} get shadows(){return this._shadows;} set shadows(value){this._shadows=Boolean(value);if(!this._shadows){this.releaseShadow();this.reflections?.release();}} releaseShadow(){ @@ -131,20 +146,24 @@ class Renderer { const camera=this.camera??[10,18,20];gl.uniform3fv(this.uniform(p,'uCamera'),reflection?[camera[0],.854-camera[1],camera[2]]:camera); gl.uniform1f(this.uniform(p,'uReflectionPass'),reflection?1:0);gl.uniform1f(this.uniform(p,'uUseReflection'),!reflection&&this.reflections.ready?1:0);gl.uniformMatrix4fv(this.uniform(p,'uReflectionProject'),false,this.reflections.project); gl.activeTexture(gl.TEXTURE3);gl.bindTexture(gl.TEXTURE_2D,reflection?this.atlas:(this.reflections.texture??this.atlas));gl.uniform1i(this.uniform(p,'uWaterReflection'),3);gl.uniform1f(this.uniform(p,'uStudio'),this.studio?1:0); - gl.uniform3fv(this.uniform(p,'uHarborLights[0]'),this.harborLights??new Float32Array(12));} + gl.uniform3fv(this.uniform(p,'uHarborLights[0]'),this.harborLights??new Float32Array(12)); + gl.activeTexture(gl.TEXTURE4);gl.bindTexture(gl.TEXTURE_2D,this.ground);gl.uniform1i(this.uniform(p,'uGround'),4);gl.uniform1f(this.uniform(p,'uGroundReady'),this.groundSignature&&!this.studio?1:0); + gl.activeTexture(gl.TEXTURE5);gl.bindTexture(gl.TEXTURE_2D,this.detail);gl.uniform1i(this.uniform(p,'uDetail'),5);gl.uniform1f(this.uniform(p,'uFineLighting'),this.shadows?1:0);} for(const o of objects){if(p===this.dp&&o.noShadow)continue;gl.uniformMatrix4fv(this.uniform(p,'uModel'),false,o.model??identity());gl.bindVertexArray(o.mesh.vao); - if(p===this.p){gl.uniform3fv(this.uniform(p,'uObjectTint'),o.tint??[1,1,1]);gl.uniform1f(this.uniform(p,'uClosed'),o.closed??0);gl.uniform1f(this.uniform(p,'uWaterfront'),o.waterfront?1:0);gl.uniform3fv(this.uniform(p,'uHarborLights[0]'),(o.waterfront?this.waterfrontLights:this.harborLights)??new Float32Array(12));} + if(p===this.p){gl.uniform1f(this.uniform(p,'uEffectAge'),o.effectAge??0);gl.uniform1f(this.uniform(p,'uEffectKind'),o.effectKind??0);gl.uniform3fv(this.uniform(p,'uObjectTint'),o.tint??[1,1,1]);gl.uniform1f(this.uniform(p,'uClosed'),o.closed??0);gl.uniform1f(this.uniform(p,'uWaterfront'),o.waterfront?1:0);gl.uniform3fv(this.uniform(p,'uHarborLights[0]'),(o.waterfront?this.waterfrontLights:this.harborLights)??new Float32Array(12));} + const fx=p===this.p&&o.effect===true;if(fx){gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);gl.depthMask(false);this.stats.effectDrawCalls++;} if(o.mesh.indexBuffer)gl.drawElements(gl.TRIANGLES,o.mesh.count,o.mesh.indexType,0);else gl.drawArrays(gl.TRIANGLES,0,o.mesh.count); + if(fx){gl.depthMask(true);gl.disable(gl.BLEND);} if(p===this.dp){this.stats.shadowDrawCalls++;this.stats.shadowTriangles+=o.mesh.count/3;}else if(reflection){this.stats.reflectionDrawCalls++;this.stats.reflectionTriangles+=o.mesh.count/3;}else{this.stats.drawCalls++;this.stats.triangles+=o.mesh.count/3;}} } - render(vp,objects){if(this.lost||this.gl.isContextLost())return;this.ensureShadow();const gl=this.gl,start=performance.now(); - this.stats={drawCalls:0,shadowDrawCalls:0,triangles:0,shadowTriangles:0,reflectionDrawCalls:0,reflectionTriangles:0,reflectionPasses:0,gpuBufferBytes:[...this.meshes].reduce((n,m)=>n+m.bytes,0),meshUploads:this.meshUploads,meshDrops:this.meshDrops,cpuRetainedGeometryBytes:[...this.meshes].reduce((n,m)=>n+m.bytes,0),restoreCount:this.restoreCount,textureBytes:{...this.textureBytes},defaultFramebuffer:{pixels:this.canvas.width*this.canvas.height,rgba8SingleSampleLowerBound:this.canvas.width*this.canvas.height*4,...this.defaultFramebufferConfig},meshes:this.meshes.size,width:this.canvas.width,height:this.canvas.height}; + render(vp,objects){if(this.lost||this.gl.isContextLost())return;this.syncGround();this.ensureShadow();const gl=this.gl,start=performance.now(); + this.stats={effectDrawCalls:0,groundUploads:this.groundUploads,cpuFieldBytes:this.groundSource.data.byteLength,drawCalls:0,shadowDrawCalls:0,triangles:0,shadowTriangles:0,reflectionDrawCalls:0,reflectionTriangles:0,reflectionPasses:0,gpuBufferBytes:[...this.meshes].reduce((n,m)=>n+m.bytes,0),meshUploads:this.meshUploads,meshDrops:this.meshDrops,cpuRetainedGeometryBytes:[...this.meshes].reduce((n,m)=>n+m.bytes,0),restoreCount:this.restoreCount,textureBytes:{...this.textureBytes},defaultFramebuffer:{pixels:this.canvas.width*this.canvas.height,rgba8SingleSampleLowerBound:this.canvas.width*this.canvas.height*4,...this.defaultFramebufferConfig},meshes:this.meshes.size,width:this.canvas.width,height:this.canvas.height}; if(this.shadows&&this.shadowOK){gl.bindFramebuffer(gl.FRAMEBUFFER,this.fb);gl.viewport(0,0,2048,2048);gl.clear(gl.DEPTH_BUFFER_BIT);gl.enable(gl.POLYGON_OFFSET_FILL);gl.polygonOffset(1,2);this.pass(this.dp,this.light,objects);gl.disable(gl.POLYGON_OFFSET_FILL);} this.reflections.render(vp,objects);this.stats.textureBytes={...this.textureBytes}; gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.viewport(0,0,this.canvas.width,this.canvas.height);const night=this.night??0;gl.clearColor(.955-night*.55,.95-night*.49,.924-night*.37,1);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);this.pass(this.p,vp,objects);this.stats.cpuSubmitMs=performance.now()-start; } resize(w,h,dpr=1){const width=Math.max(1,Math.round(w*dpr)),height=Math.max(1,Math.round(h*dpr));if(this.canvas.width!==width||this.canvas.height!==height){this.canvas.width=width;this.canvas.height=height;}} - destroy(){this.abort.abort();this.reflections.release();for(const mesh of [...this.meshes])this.drop(mesh);const gl=this.gl;gl.deleteProgram(this.p);gl.deleteProgram(this.dp);gl.deleteTexture(this.atlas);gl.deleteTexture(this.surface);gl.deleteTexture(this.shadow);gl.deleteFramebuffer(this.fb);} + destroy(){this.abort.abort();this.reflections.release();for(const mesh of [...this.meshes])this.drop(mesh);const gl=this.gl;gl.deleteProgram(this.p);gl.deleteProgram(this.dp);gl.deleteTexture(this.atlas);gl.deleteTexture(this.surface);gl.deleteTexture(this.detail);gl.deleteTexture(this.ground);this.groundSource=null;gl.deleteTexture(this.shadow);gl.deleteFramebuffer(this.fb);} } export { Renderer }; diff --git a/tests/visual-finish.test.mjs b/tests/visual-finish.test.mjs new file mode 100644 index 0000000..75020d7 --- /dev/null +++ b/tests/visual-finish.test.mjs @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createHash} from 'node:crypto'; +import {BOARD} from '../src/game/board.js'; +import {deriveCity} from '../src/scene/city-state.js'; +import {civicFixtures} from '../scripts/assets/civic-fixtures.mjs'; +import {HARMONY_SPEC,HARMONY_LOTS,HARMONY_CACHE_LIMIT,HARMONY_CACHE_BYTES,Harmony} from '../src/scene/harmony.js'; +import {createPublicAsset,PUBLIC_FACTORIES,PUBLIC_BUDGETS,PublicRealm} from '../src/scene/finish/public.js'; +import {cityField,FIELD_SIZE} from '../src/scene/finish/field.js'; +import {detailAtlas} from '../src/scene/finish/materials.js'; +import {effectMesh} from '../src/scene/finish/effects.js'; +const hash=d=>createHash('sha256').update(d).digest('hex'); +const fixture=civicFixtures(); +function fake(){const live=new Set();return {live,mesh(g){const m={count:g.indices.length,bytes:g.data.byteLength+g.indices.byteLength};live.add(m);return m;},drop(m){live.delete(m);}};} +test('all eight remaining property IDs map to their original families, no new economic lot',()=>{ + assert.deepEqual(HARMONY_LOTS,[4,5,18,19,22,23,25,26]);assert.equal(BOARD.length,28); + for(const id of HARMONY_LOTS){assert.equal(BOARD[id].kind,'lot');assert.equal(HARMONY_SPEC[id][0],['rivage','jardins','marina','ateliers','horizon','nova','roseraie','solstice'][BOARD[id].group]);} +}); +for(const name of Object.keys(PUBLIC_FACTORIES))for(const [k,lod] of ['low','high'].entries())test(`public ${name}/${lod}: bounded triangles, finite unit normals, reproducible`,()=>{ + const g=createPublicAsset(name,lod);assert.ok(g.indices.length/3<=PUBLIC_BUDGETS[name][k]);assert.equal(hash(new Uint8Array(g.data.buffer)),hash(new Uint8Array(createPublicAsset(name,lod).data.buffer))); + for(let i=0;ig.data.slice(g.indices[i+k]*12,g.indices[i+k]*12+3)),a=p[1].map((x,k)=>x-p[0][k]),b=p[2].map((x,k)=>x-p[0][k]);assert.ok(Math.hypot(a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0])>1e-10);} +}); +test('public equipment two-LOD batch, no reconstruction on time/settings, releases resources',()=>{ + const r=fake(),p=new PublicRealm(r);p.selectDetail(80);assert.equal(p.builds,2);for(let i=0;i<100;i++){p.configure({reduced:true,living:false});p.selectDetail(60);assert.equal(p.objects().length,1);}assert.equal(p.builds,2);p.configure({quality:'low'});p.selectDetail(200);assert.equal(p.detail,'low');p.destroy();assert.equal(r.live.size,0); +}); +test('harmony bounds its cache and updates mortgage/owner without changing gameplay',()=>{ + const r=fake(),h=new Harmony(r),s=structuredClone(fixture.checkpoints.late.state),initial=JSON.stringify(s);h.setCity(deriveCity(s));const n=h.builds; + for(let i=0;i<100;i++)h.setCity(deriveCity(structuredClone(s)));assert.equal(h.builds,n);assert.equal(JSON.stringify(s),initial); + for(let l=0;l<4;l++)for(const id of HARMONY_LOTS){s.properties[id].owner=s.players[0].id;s.properties[id].level=l;h.setCity(deriveCity(s));h.selectDetail(80);h.selectDetail(40);assert.ok(h.cache.size<=HARMONY_CACHE_LIMIT);assert.ok(h.objects()&&h.stats.cachedGpuBytes<=HARMONY_CACHE_BYTES);assert.ok(h.entries.every(e=>h.cache.has(e.key)));} + s.properties[22].mortgaged=true;h.setCity(deriveCity(s));assert.equal(h.entries.find(p=>p.id===22).closed,1);h.destroy();assert.equal(r.live.size,0); +}); +test('contact/light field is deterministic, small, reads actual vacant and mortgaged states',()=>{ + const start=deriveCity(fixture.checkpoints.start.state),late=deriveCity(fixture.checkpoints.late.state),before=JSON.stringify(late); + const a=cityField(start),b=cityField(late);assert.equal(a.width,FIELD_SIZE);assert.equal(a.data.byteLength,262144);assert.notEqual(hash(a.data),hash(b.data));assert.equal(hash(b.data),hash(cityField(late).data));assert.equal(JSON.stringify(late),before); + const closed=structuredClone(late);closed.parcels.forEach(p=>p.mortgaged=true);assert.notEqual(hash(b.data),hash(cityField(closed).data)); +}); +test('one shared normal/roughness atlas, bounded normal perturbations and deterministic mip source',()=>{ + const a=detailAtlas();assert.equal(a.width,256);assert.equal(a.data.byteLength,262144);assert.equal(hash(a.data),hash(detailAtlas().data));for(let i=0;i<128*256*4;i+=4){assert.ok(a.data[i]>=90&&a.data[i]<=166);assert.ok(a.data[i+1]>=90&&a.data[i+1]<=166);assert.ok(a.data[i+2]>=65);} +}); +test('effects have bounded reusable geometry, no random/time source, and low detail reduces burst count',()=>{ + for(const name of ['burst','dust','scan']){const a=effectMesh(name,'low'),b=effectMesh(name,'high');assert.ok(a.indices.length<=b.indices.length);assert.ok(b.indices.length/3<=48);assert.equal(hash(new Uint8Array(b.data.buffer)),hash(new Uint8Array(effectMesh(name,'high').data.buffer)));for(let i=0;ieffectMesh('missing')); +}); + +test('standalone game/gallery ESM subset bundles into valid JavaScript, not just source syntax',async()=>{ + const {bundle}=await import('../scripts/bundle.mjs');const {Script}=await import('node:vm');const {resolve}=await import('node:path'); + const root=resolve(import.meta.dirname,'..');for(const entry of ['src/main.js','src/scene/districts/review.js']){const source=await bundle(root,entry);assert.doesNotThrow(()=>new Script(source,{filename:entry}));} +}); diff --git a/tests/visual_finish_browser.py b/tests/visual_finish_browser.py new file mode 100644 index 0000000..628d100 --- /dev/null +++ b/tests/visual_finish_browser.py @@ -0,0 +1,111 @@ +"""Actual WebGL2 proof and ABBA software diagnostics. No screenshot-only renderer.""" +import argparse,asyncio,json,os,pathlib,platform,subprocess,time,traceback,urllib.request +from playwright.async_api import async_playwright +from waterfront_browser import LOAD,DRAW +ROOT=pathlib.Path(__file__).resolve().parents[1] +OUT=ROOT/'test-results/visual-finish';OUT.mkdir(parents=True,exist_ok=True) +BASE=pathlib.Path(os.getenv('VISUAL_BASELINE_DIR',ROOT/'test-results/visual-baseline')).resolve() +def node(expr):return json.loads(subprocess.check_output(['node','--input-type=module','-e',expr],cwd=ROOT,text=True)) +FIX=node("import{civicFixtures}from'./scripts/assets/civic-fixtures.mjs';console.log(JSON.stringify(civicFixtures()));") +PORT=node("import{waterfrontFixtures}from'./scripts/assets/waterfront-fixtures.mjs';console.log(JSON.stringify(waterfrontFixtures()));") +EP=node("import{civicFixtures}from'./scripts/assets/civic-fixtures.mjs';import{applyAction}from'./src/game/engine.js';import{deriveCity,cityTransitions}from'./src/scene/city-state.js';let s=civicFixtures().initial,out={};for(const c of civicFixtures().commands){const n=applyAction(s,c.actor,c.action);if(cityTransitions(deriveCity(s),deriveCity(n)).celebrations.length){out={before:s,after:n};break;}s=n;}console.log(JSON.stringify(out));") +async def draw(page): + r=await page.evaluate(DRAW) + assert r['glError']==0 and not r['lost'],r + return r +async def main(section): + report={'baseCommit':'b5f547c97ce8387f1c31b25bef3a29952d0a94a7','testedCommit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip(),'section':section,'environment':{'platform':platform.platform(),'cpu':subprocess.check_output(['bash','-lc','grep -m1 "model name" /proc/cpuinfo'],text=True).strip(),'device':'GitHub Actions Linux VM, Chromium/SwiftShader software. No physical phone.','viewport':{'width':1600,'height':1000},'dpr':1},'captures':{},'checks':[],'timings':{},'pageErrors':[]} + servers=[];browser=None + try: + for root,port in [(BASE,4468),(ROOT,4469)]: + assert (root/'src/main.js').exists(),root + servers.append(subprocess.Popen(['node','scripts/dev.mjs','--port',str(port)],cwd=root,stdout=subprocess.DEVNULL)) + for _ in range(80): + try:urllib.request.urlopen(f'http://127.0.0.1:{port}',timeout=.5);break + except Exception:time.sleep(.1) + async with async_playwright() as pw: + browser=await pw.chromium.launch(headless=True,args=['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader','--ignore-gpu-blocklist']) + report['environment']['chromium']=browser.version;pages={} + for label,port in [('before',4468),('after',4469)]: + page=await browser.new_page(viewport=report['environment']['viewport'],device_scale_factor=1);pages[label]=page + page.on('pageerror',lambda e:report['pageErrors'].append(str(e))) + await page.add_init_script("localStorage.setItem('dicestrict:settings:v1',JSON.stringify({reduced:true,living:false,weather:false,quality:'low'}))") + await page.goto(f'http://127.0.0.1:{port}');await page.wait_for_function("!document.querySelector('.scene-loading')") + assert await page.locator('.scene-error').count()==0,'Actual WebGL2 required' + await page.evaluate(LOAD,FIX['checkpoints']['start']['state']) + report['environment'][label+'Renderer']=await page.evaluate("()=>{const gl=portApp.scene.renderer.gl,e=gl.getExtension('WEBGL_debug_renderer_info');return e?gl.getParameter(e.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER);}") + if section=='proof': + for state,c in FIX['checkpoints'].items(): + for mood,clock in [('day',0),('dusk',65)]: + await page.evaluate(LOAD,c['state']);await page.evaluate("t=>{const s=portApp.scene;s.ambientTime=t;s.configure({dayMode:t?'auto':'day'});}",clock) + r=await draw(page);assert r['fingerprint']==c['fingerprint'];assert r['camera']=={'angle':.5,'pitch':.85,'zoom':1,'target':None} + name=f'{state}-{mood}-{label}.png';report['captures'][name]=r;await page.screenshot(path=str(OUT/name),full_page=True,timeout=90000) + print(name,flush=True) + for mood,clock in [('day',0),('dusk',65),('bluehour',85)]: + await page.evaluate(LOAD,PORT['checkpoints']['late']['state']);await page.evaluate("t=>{const s=portApp.scene;s.ambientTime=t;s.configure({dayMode:t?'auto':'day'});}",clock) + name=f'marina-developed-{mood}-{label}.png';report['captures'][name]=await draw(page);await page.screenshot(path=str(OUT/name),full_page=True,timeout=90000) + # Within the player's real pitch and zoom bounds, no recentered target. + await page.evaluate("()=>{const s=portApp.scene;s.pitch=.63;s.angle=.50;s.zoom=1.12;}") + name=f'player-oblique-{mood}-{label}.png';report['captures'][name]=await draw(page);await page.screenshot(path=str(OUT/name),full_page=True,timeout=90000) + print(name,flush=True) + await page.evaluate(LOAD,FIX['checkpoints']['late']['state']);await page.evaluate("()=>{const s=portApp.scene;for(let i=0;i<5;i++)s.view('in');s.ambientTime=65;s.configure({dayMode:'auto'});}") + name=f'player-close-dusk-{label}.png';report['captures'][name]=await draw(page);await page.screenshot(path=str(OUT/name),full_page=True,timeout=90000) + if section=='proof': + page=pages['after'] + for name,episode in [('construction',FIX['episodes']['upgrade']),('celebration',EP)]: + await page.evaluate(LOAD,episode['before']) + await page.evaluate("state=>{const a=portApp,s=a.scene;s.ambientTime=100;s.city.elapsed=100;s.configure({living:true,reduced:false});a.accept(structuredClone(state));clearTimeout(a.botTimer);clearTimeout(a.busyTimer);cancelAnimationFrame(s.raf);s.configure({living:true,reduced:false,dayMode:'auto'});s.ambientTime=100.85;s.lastAmbientFrame=null;}",episode['after']) + r=await draw(page);assert r['effectDrawCalls']>0,r + name=f'event-{name}.png';report['captures'][name]=r;await page.screenshot(path=str(OUT/name),full_page=True,timeout=90000) + await page.close();pages.pop('after') + page=await browser.new_page(viewport={'width':1100,'height':850});page.on('pageerror',lambda e:report['pageErrors'].append(str(e))) + await page.goto('file://'+str(ROOT/'assets/districts/review.html'));await page.wait_for_function('!!globalThis.assetReview') + for name in ['jardins-0-level-3','nova-1-level-3','solstice-1-level-3','pavilion','metro']: + for angle,label in [(.60,'front'),(3.70,'rear')]: + r=await page.evaluate("x=>{assetReview.select(x.name,'high');assetReview.setLight('studio');assetReview.setView(x.angle,.44);return assetReview.renderer.gl.getError();}",{'name':name,'angle':angle});assert r==0 + await page.screenshot(path=str(OUT/f'studio-{name}-{label}.png'),timeout=90000) + await page.close() + report['checks'].append('Two real pinned source versions, identical legal checkpoints, default player camera plus bounded oblique/close views; day/dusk and developed marina at blue hour. New models examined under studio illumination, no bloom/blur.') + else: + for quality in ['low','high']: + for animated in [False,True]: + case=quality+('-animated' if animated else '-frozen');report['timings'][case]={'before':[],'after':[]} + for label in ['before','after','after','before']: + page=pages[label];await page.evaluate(LOAD,PORT['checkpoints']['late']['state']) + await page.evaluate("x=>portApp.scene.configure({quality:x.quality,living:x.animated,reduced:false,dayMode:'auto'})",{'quality':quality,'animated':animated}) + for i in range(8): + await page.evaluate('t=>portApp.scene.ambientTime=t',65+i/30);r=await draw(page) + if i>=2:report['timings'][case][label].append(r) + await asyncio.sleep(.025) + print('timed',case,flush=True) + page=pages['after'];await page.evaluate(LOAD,FIX['checkpoints']['late']['state']);await draw(page) + stable=await page.evaluate("()=>{const s=portApp.scene,r=s.renderer,up=r.meshUploads,field=r.groundUploads;for(let i=0;i<100;i++)s.setState(structuredClone(portApp.state));s.dirty=true;s.render(performance.now()+100);return {meshes:r.meshUploads-up,field:r.groundUploads-field};}") + assert stable=={'meshes':0,'field':0},stable;report['stableSnapshots']=stable + await page.evaluate("()=>portApp.scene.configure({reduced:true,living:false})");await draw(page) + idle=await page.evaluate("()=>{const s=portApp.scene,n=s.frameCount;for(let i=0;i<20;i++)s.render(performance.now()+1000+i*40);return s.frameCount-n;}");assert idle==0;report['idleFrames']=idle + # Dedicated new-texture lifecycle; upstream shadow/reflection tests remain unchanged. + await page.evaluate("()=>{const r=portApp.scene.renderer;window.loss=r.gl.getExtension('WEBGL_lose_context');if(!loss)throw Error('Context-loss extension required');window.oldDetail=r.detail;window.oldGround=r.ground;loss.loseContext();}") + await page.wait_for_function('portApp.scene.lost&&portApp.scene.renderer.lost');await page.evaluate("()=>portApp.scene.configure({quality:'low'})");await page.evaluate('loss.restoreContext()') + await page.wait_for_function('!portApp.scene.lost&&!portApp.scene.renderer.lost',timeout=30000) + restored=await draw(page);assert restored['textureBytes']['shadowDepth24StorageUpperBound']==0 and restored['textureBytes']['waterReflectionRGBA8']==0 + assert await page.evaluate("()=>{const r=portApp.scene.renderer;return r.gl.isTexture(r.ground)&&r.gl.isTexture(r.detail)&&r.ground!==oldGround&&r.detail!==oldDetail;}") + report['restoredLow']=restored + # Shader/GL state is left usable after effects and all property transitions. + for name,e in FIX['episodes'].items(): + await page.evaluate(LOAD,e['before']);await page.evaluate("e=>{const a=portApp,s=a.scene;s.city.elapsed=20;s.configure({living:true,reduced:false});a.accept(e.after);clearTimeout(a.botTimer);clearTimeout(a.busyTimer);cancelAnimationFrame(s.raf);s.ambientTime=20.8;s.lastAmbientFrame=null;}",e) + r=await draw(page);assert r['glError']==0 + assert await page.evaluate("()=>{const g=portApp.scene.renderer.gl;return !g.isEnabled(g.BLEND)&&g.getParameter(g.DEPTH_WRITEMASK);}") + report['checks'].append('ABBA software timings: 2 warmup + 6 retained synchronous readback samples per block. Submission/readback, geometry, color/shadow/reflection calls and texture resources separate. No real phone validation.') + report['checks'].append('100 stable snapshots: no mesh or contact-field uploads. Frozen scene: zero submitted idle frames. New textures restore after context loss in low quality, no shadow/reflection allocation. Legal property transitions and GL blending/depth state verified.') + assert not report['pageErrors'],report['pageErrors'] + for page in pages.values():await page.close() + await browser.close();browser=None + except Exception:report['failure']=traceback.format_exc();raise + finally: + (OUT/f'{section}-report.json').write_text(json.dumps(report,indent=2)) + (OUT/'legal-history.json').write_text(json.dumps({'civic':FIX,'marina':PORT},indent=2)) + if browser:await browser.close() + for s in servers:s.terminate();s.wait(timeout=5) + print(json.dumps({'checks':report['checks'],'captures':len(report['captures'])},indent=2)) +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('--section',choices=['proof','measures'],required=True);asyncio.run(main(p.parse_args().section))