/** * Implementación de ZoneContext del kit de mundo. Ver la documentación de uso en src/world/index.ts. */ import * as THREE from 'three'; import type { Game } from '../../core/game'; import { Entity } from '../../core/entity'; import { overlaps } from '../../physics/world'; import { emojiMesh, emojiSprite } from '../../render/emoji'; import type { Area, Collider, DecorOpts, GroundOpts, PlatformOpts, Props, ZoneContext, ZoneDef, } from '../../core/types'; import { anim } from './anim'; import { buildBackdrop } from './backdrop'; import { buildProp, ensureGlobals, glowCrystalMat, swayVariant, type BuiltProp } from './props'; import { STYLES, buildPlatform, buildSlab, roundRect, styleOf } from './terrain'; import { softSoilTexture } from './textures'; import { GeoBatch, P, extrude, kitMat, mergeGeometries, paint, rng, seedOf, solid } from './util'; import { waterMesh, waterfallMesh } from './water'; /** Profundidades estándar del terreno. */ export const Z = { groundFront: 1.4, groundBack: -6, blockFront: 1.4, blockBack: -1.6, waterFront: 1.46 }; interface Sink { add(mat: THREE.Material, g: THREE.BufferGeometry, cast?: boolean): void } class OffsetSink implements Sink { constructor(private to: GeoBatch, private x: number, private y: number) {} add(mat: THREE.Material, g: THREE.BufferGeometry, cast = true): void { g.translate(this.x, this.y, 0); this.to.add(mat, g, cast); } } /** Plataforma móvil senoidal (mueve el colisionador y mantiene vx/vy). */ class Mover extends Entity { private t: number; private prevX: number; private prevY: number; constructor(private c: Collider, private mesh: THREE.Object3D, private ox: number, private oy: number, private mv: NonNullable, private topOff: number, private bobAmp: number) { super(); this.t = (mv.phase ?? 0) * mv.period; this.prevX = c.x; this.prevY = c.y; this.tags.add('platform'); } update(dt: number): void { this.prevX = this.c.x; this.prevY = this.c.y; this.t += dt; const w = (Math.PI * 2) / this.mv.period; const s = Math.sin(this.t * w) * 0.5; const nx = this.ox + (this.mv.dx ?? 0) * s; const ny = this.oy + (this.mv.dy ?? 0) * s; this.c.vx = (nx - this.c.x) / dt; this.c.vy = (ny - this.c.y) / dt; this.c.x = nx; this.c.y = ny; } render(alpha: number): void { const x = this.prevX + (this.c.x - this.prevX) * alpha; const y = this.prevY + (this.c.y - this.prevY) * alpha; const bob = this.bobAmp ? Math.sin(anim.time.value * 1.3 + this.ox) * this.bobAmp : 0; this.mesh.position.set(x, y + this.topOff + bob, 0); } } /** Salida de zona (al tocar, o con interact/arriba si es puerta). */ class Exit extends Entity { private prompt: THREE.Object3D | null = null; private arrow: THREE.Object3D | null = null; private inside = false; private arrowBase = 0; constructor(private box: { x: number; y: number; hw: number; hh: number }, private to: string, private spawnName: string, private door: boolean, private opts: Props) { super(); } bounds() { return this.box; } /** Boca de túnel: arco de roca natural, armazón de mina y túnel oscuro con profundidad 3D. */ private buildCaveMouth(): void { const w = Math.max(3.0, this.box.hw * 2); const h = Math.max(3.6, this.box.hh * 2); const z = typeof this.opts.z === 'number' ? this.opts.z : -0.1; const rock = 0x60566e; const rockDark = 0x443c52; const rockRim = 0x726882; // 1. Arco exterior de roca modelada const arch = new THREE.Shape(); const ow = w * 0.58; const oh = h * 0.95; arch.moveTo(-ow - 0.45, 0); arch.lineTo(ow + 0.45, 0); arch.lineTo(ow + 0.45, oh * 0.55); arch.absarc(0, oh * 0.55, ow + 0.45, 0, Math.PI, false); arch.lineTo(-ow - 0.45, 0); const hole = new THREE.Path(); const iw = w * 0.42; const ih = h * 0.82; hole.moveTo(-iw, 0); hole.lineTo(iw, 0); hole.lineTo(iw, ih * 0.52); hole.absarc(0, ih * 0.52, iw, 0, Math.PI, false); hole.lineTo(-iw, 0); arch.holes.push(hole); const rockMat = solid(rock, 0.22); const rimMat = solid(rockRim, 0.28); const shell = new THREE.Mesh(extrude(arch, z - 1.2, z + 0.35, 0.16, 18, 2), rockMat); shell.castShadow = true; shell.receiveShadow = true; this.view.add(shell); // Borde biselado frontal del arco de roca const rimShape = new THREE.Shape(); rimShape.moveTo(-ow - 0.15, 0); rimShape.lineTo(ow + 0.15, 0); rimShape.lineTo(ow + 0.15, oh * 0.52); rimShape.absarc(0, oh * 0.52, ow + 0.15, 0, Math.PI, false); rimShape.lineTo(-ow - 0.15, 0); const rimHole = new THREE.Path(); rimHole.moveTo(-iw + 0.05, 0); rimHole.lineTo(iw - 0.05, 0); rimHole.lineTo(iw - 0.05, ih * 0.54); rimHole.absarc(0, ih * 0.54, iw - 0.05, 0, Math.PI, false); rimHole.lineTo(-iw + 0.05, 0); rimShape.holes.push(rimHole); const rimMesh = new THREE.Mesh(extrude(rimShape, z + 0.15, z + 0.42, 0.08, 16, 2), rimMat); rimMesh.castShadow = true; this.view.add(rimMesh); // 2. Interior oscuro del túnel con profundidad 3D const voidShape = new THREE.Shape(); voidShape.moveTo(-iw, 0); voidShape.lineTo(iw, 0); voidShape.lineTo(iw, ih * 0.52); voidShape.absarc(0, ih * 0.52, iw, 0, Math.PI, false); voidShape.lineTo(-iw, 0); const voidMat = kitMat('caveVoid', { color: 0x0c0816, gloss: 0.02, emissive: 0x160f24, emissiveIntensity: 0.3, }); const darkness = new THREE.Mesh(extrude(voidShape, z - 3.8, z - 0.8, 0.02, 16, 1), voidMat); darkness.castShadow = false; this.view.add(darkness); // Fondo del túnel (plano abisal) const backMat = kitMat('caveBack', { color: 0x05030a, gloss: 0 }); const backPlane = new THREE.Mesh(new THREE.PlaneGeometry(iw * 2.2, ih * 1.2), backMat); backPlane.position.set(0, ih * 0.5, z - 3.82); this.view.add(backPlane); // 3. Vigas de soporte de madera estilo mina (Timber framing) const woodMat = solid(0x764a27, 0.32); const woodDark = solid(0x5a371c, 0.3); const ironMat = solid(0x2d2b35, 0.75); const postH = ih * 0.92; const postL = new THREE.Mesh(P.rbox(), woodMat); postL.scale.set(0.24, postH, 0.26); postL.position.set(-iw + 0.12, postH * 0.5, z - 0.25); postL.rotation.z = -0.04; postL.castShadow = true; this.view.add(postL); const postR = new THREE.Mesh(P.rbox(), woodMat); postR.scale.set(0.24, postH, 0.26); postR.position.set(iw - 0.12, postH * 0.5, z - 0.25); postR.rotation.z = 0.04; postR.castShadow = true; this.view.add(postR); const beamW = iw * 2 + 0.35; const beamTop = new THREE.Mesh(P.rbox(), woodMat); beamTop.scale.set(beamW, 0.28, 0.3); beamTop.position.set(0, postH + 0.02, z - 0.22); beamTop.castShadow = true; this.view.add(beamTop); const braceL = new THREE.Mesh(P.rbox(), woodDark); braceL.scale.set(0.18, 0.72, 0.18); braceL.position.set(-iw + 0.38, postH - 0.25, z - 0.22); braceL.rotation.z = Math.PI / 4; this.view.add(braceL); const braceR = new THREE.Mesh(P.rbox(), woodDark); braceR.scale.set(0.18, 0.72, 0.18); braceR.position.set(iw - 0.38, postH - 0.25, z - 0.22); braceR.rotation.z = -Math.PI / 4; this.view.add(braceR); for (const [bx, by] of [[-iw + 0.12, postH + 0.02], [iw - 0.12, postH + 0.02]]) { const bolt = new THREE.Mesh(P.sphereLo(), ironMat); bolt.scale.setScalar(0.07); bolt.position.set(bx, by, z - 0.06); this.view.add(bolt); } // 4. Rocas naturales redondeadas a los lados y en la coronación const bL = new THREE.Mesh(P.rock(0), solid(rockDark, 0.22)); bL.scale.set(1.2, 0.95, 1.1); bL.position.set(-ow - 0.25, 0.45, z + 0.15); bL.castShadow = true; this.view.add(bL); const bR = new THREE.Mesh(P.rock(1), solid(rock, 0.22)); bR.scale.set(1.3, 1.1, 1.15); bR.position.set(ow + 0.3, 0.55, z + 0.2); bR.castShadow = true; this.view.add(bR); const bTop = new THREE.Mesh(P.rock(2), solid(rockDark, 0.22)); bTop.scale.set(1.5, 0.75, 1.0); bTop.position.set(-0.25, oh + 0.25, z + 0.15); bTop.castShadow = true; this.view.add(bTop); const moss = new THREE.Mesh(P.sphereLo(), solid(0x3e7436, 0.15)); moss.scale.set(0.85, 0.22, 0.45); moss.position.set(0.35, oh + 0.35, z + 0.22); this.view.add(moss); // 5. Estalactitas goteando del techo de la cueva const dripMat = solid(0x8a809b, 0.35); const drips = [ { x: -0.65, y: ih * 0.98, s: 0.38, r: 0.14 }, { x: -0.22, y: ih * 1.04, s: 0.58, r: 0.18 }, { x: 0.32, y: ih * 1.02, s: 0.46, r: 0.15 }, { x: 0.72, y: ih * 0.96, s: 0.52, r: 0.16 }, ]; for (const d of drips) { const cone = new THREE.Mesh(P.cone(), dripMat); cone.scale.set(d.r, d.s, d.r); cone.position.set(d.x, d.y - d.s * 0.5, z + 0.08); cone.rotation.x = Math.PI; cone.castShadow = true; this.view.add(cone); } const smL = new THREE.Mesh(P.cone(), dripMat); smL.scale.set(0.18, 0.42, 0.18); smL.position.set(-iw + 0.22, 0.21, z + 0.22); smL.castShadow = true; this.view.add(smL); const smR = new THREE.Mesh(P.cone(), dripMat); smR.scale.set(0.16, 0.36, 0.16); smR.position.set(iw - 0.22, 0.18, z + 0.25); smR.castShadow = true; this.view.add(smR); // 6. Cristales brillantes luminosos (Cueva Cristal 💎) const crysCyan = new THREE.Mesh(P.octa(), glowCrystalMat(0x5eeaff)); crysCyan.scale.set(0.19, 0.44, 0.19); crysCyan.position.set(-ow - 0.05, 0.85, z + 0.35); crysCyan.rotation.set(0.25, 0.3, 0.4); this.view.add(crysCyan); const crysPurple = new THREE.Mesh(P.octa(), glowCrystalMat(0xc469ff)); crysPurple.scale.set(0.17, 0.38, 0.17); crysPurple.position.set(ow + 0.08, 0.95, z + 0.38); crysPurple.rotation.set(-0.3, 0.4, -0.3); this.view.add(crysPurple); const crysGold = new THREE.Mesh(P.octa(), glowCrystalMat(0xffd54f)); crysGold.scale.set(0.13, 0.28, 0.13); crysGold.position.set(-iw + 0.4, postH + 0.12, z + 0.1); crysGold.rotation.set(0.1, 0.2, 0.4); this.view.add(crysGold); // 7. Prompt interactivo (⬆️) const p = emojiSprite('⬆️', 0.65); p.position.set(0, postH + 0.85, 0.6); p.visible = false; this.prompt = p; this.view.add(p); this.arrowBase = postH + 0.85; if (this.opts.emoji) { const e = emojiMesh(this.opts.emoji, 0.65); e.position.set(0, postH + 0.42, z + 0.2); this.view.add(e); } } onAdded(): void { this.setPos(this.box.x, this.box.y - this.box.hh); const h = this.box.hh * 2; if (this.door && this.opts.doorVisual === 'cave') { this.buildCaveMouth(); } else if (this.door && this.opts.doorVisual !== false) { const dw = Math.min(1.5, this.box.hw * 2); const dh = Math.min(2.3, h); const z = this.opts.z ?? -0.75; const frame = extrude(roundRect(-dw / 2 - 0.2, 0, dw / 2 + 0.2, dh + 0.2, dw / 2 + 0.2, 0, 0.06), z - 0.3, z + 0.12, 0.06, 10, 2); const fm = new THREE.Mesh(frame, solid(this.opts.frameColor ?? 0xa9a2c8, 0.3)); const panel = extrude(roundRect(-dw / 2, 0, dw / 2, dh, dw / 2, 0, 0.05), z - 0.2, z + 0.2, 0.05, 10, 2); const pm = new THREE.Mesh(panel, kitMat('doorWood', { color: this.opts.color ?? 0xb8783f, gloss: 0.3, map: null })); for (const m of [fm, pm]) { m.castShadow = true; m.receiveShadow = true; this.view.add(m); } for (let i = 1; i < 4; i++) { const plank = new THREE.Mesh(P.rbox(), solid(0x93592c, 0.3)); plank.scale.set(0.05, dh * 0.8, 0.04); plank.position.set(-dw / 2 + (dw * i) / 4, dh * 0.42, z + 0.21); this.view.add(plank); } const knob = new THREE.Mesh(P.sphereLo(), solid(0xffc928, 0.9)); knob.scale.setScalar(0.08); knob.position.set(dw * 0.3, dh * 0.45, z + 0.25); this.view.add(knob); if (this.opts.emoji) { const e = emojiMesh(this.opts.emoji, 0.6); e.position.set(0, dh + 0.55, z + 0.15); this.view.add(e); } const p = emojiSprite('⬆️', 0.6); p.position.set(0, dh + (this.opts.emoji ? 1.3 : 0.6), 0.6); p.visible = false; this.prompt = p; this.view.add(p); } if (this.opts.arrow) { const dir = typeof this.opts.arrow === 'string' ? this.opts.arrow : this.door ? 'up' : this.box.x > (this.game.zone?.spawns.default?.x ?? 0) ? 'right' : 'left'; const em = ({ up: '⬆️', down: '⬇️', left: '⬅️', right: '➡️' } as Record)[dir] ?? '➡️'; const a = emojiSprite(em, 0.7, { glow: 0.3 }); this.arrowBase = Math.max(this.arrowBase, Math.min(h, 2.4) + 0.7); a.position.set(0, this.arrowBase, 0.5); this.arrow = a; this.view.add(a); } } update(): void { const h = this.game.hero; this.inside = !!h && h.alive && overlaps(this.box, h.body, 0); if (!this.inside) return; if (this.door && !this.game.input.pressed('interact') && !this.game.input.pressed('up')) return; if (this.door) { if (this.opts.doorVisual === 'cave') this.game.audio.sfx('whoosh'); else this.game.audio.sfx('door'); } void this.game.loadZone(this.to, this.spawnName); } render(alpha: number, dt: number): void { super.render(alpha, dt); const t = anim.time.value; if (this.prompt) { this.prompt.visible = this.inside; const s = 0.6 * (1 + Math.sin(t * 6) * 0.06); this.prompt.scale.set(s, s, 1); } if (this.arrow) this.arrow.position.y = this.arrowBase + Math.abs(Math.sin(t * 3)) * 0.25; } } interface GroundRec { x0: number; x1: number; top: number; bottom: number; style: string; zBack: number; zFront: number; plain: boolean } /** * Caché de lo más caro de construir una zona (losas de terreno y decorados fusionados): al volver a una zona * ya visitada se reutilizan las geometrías en vez de recalcularlas (antes ~0,5-1 s por zona en PC, varios * segundos en móvil, con la estrella de la transición tapando la pantalla). */ interface MeshSnap { geo: THREE.BufferGeometry; mat: THREE.Material | THREE.Material[]; name: string; cast: boolean; recv: boolean; order: number; frustum: boolean } const buildCache = new Map(); function snapMeshes(list: THREE.Object3D[]): MeshSnap[] { const out: MeshSnap[] = []; for (const o of list) { const m = o as THREE.Mesh; if (!m.isMesh || m.children.length || (m as THREE.InstancedMesh).isInstancedMesh) return []; m.geometry.userData.shared = true; for (const mt of Array.isArray(m.material) ? m.material : [m.material]) mt.userData.shared = true; out.push({ geo: m.geometry, mat: m.material, name: m.name, cast: m.castShadow, recv: m.receiveShadow, order: m.renderOrder, frustum: m.frustumCulled }); } return out; } function restoreMeshes(group: THREE.Group, snaps: MeshSnap[]): void { for (const s of snaps) { const m = new THREE.Mesh(s.geo, s.mat); m.name = s.name; m.castShadow = s.cast; m.receiveShadow = s.recv; m.renderOrder = s.order; m.frustumCulled = s.frustum; group.add(m); } } export class KitZoneContext implements ZoneContext { private batch = new GeoBatch(); private grounds: GroundRec[] = []; private staticProps: BuiltProp[] = []; private finished = false; private nSeed = 0; constructor(readonly game: Game, readonly def: ZoneDef, readonly group: THREE.Group) { anim.reset(); ensureGlobals(); } private seed(...n: number[]): number { return seedOf(...n, this.nSeed++); } private physMat(style: string | undefined, material?: string): string { return material ?? (style && STYLES[style] ? STYLES[style].material : style) ?? 'grass'; } private flushIfFinished(): void { if (this.finished) this.batch.flush(this.group); } // ───────────── Terreno ───────────── ground(x0: number, x1: number, top: number, opts: GroundOpts = {}): Collider { const o = opts as GroundOpts & { zBack?: number; zFront?: number; plain?: boolean }; const bottom = opts.bottom ?? this.def.bounds.minY - 6; const style = opts.style ?? 'grass'; this.grounds.push({ x0, x1, top, bottom, style, zBack: o.zBack ?? Z.groundBack, zFront: o.zFront ?? Z.groundFront, plain: !!o.plain }); if (this.finished) this.buildGrounds(); const w = x1 - x0; const h = top - bottom; return this.game.physics.box(x0 + w / 2, bottom + h / 2, w, h, { material: this.physMat(style, opts.material) }); } block(x: number, y: number, w: number, h: number, opts: GroundOpts = {}): Collider { const o = opts as GroundOpts & { zBack?: number; zFront?: number; plain?: boolean }; const style = opts.style ?? 'stone'; buildSlab(this.batch, x - w / 2, x + w / 2, y + h / 2, y - h / 2, { style, zBack: o.zBack ?? Z.blockBack, zFront: o.zFront ?? Z.blockFront, seed: this.seed(x, y, w, h), kind: 'block', plain: o.plain ?? h < 1.5, }); this.flushIfFinished(); return this.game.physics.box(x, y, w, h, { material: this.physMat(style, opts.material) }); } platform(x: number, y: number, w: number, opts: PlatformOpts = {}): Collider { const o = opts as PlatformOpts & { float?: boolean }; const t = opts.thickness ?? 0.5; const style = opts.style ?? 'wood'; const cy = y - t / 2; const c = this.game.physics.box(x, cy, w, t, { oneWay: opts.oneWay ?? true, material: this.physMat(style, opts.material) }); const floaty = o.float ?? !(style === 'wood' || style === 'metal'); const seed = this.seed(x, y, w); if (opts.move || floaty) { const g = new THREE.Group(); g.name = 'platform'; const pkey = `pf|${style}|${w.toFixed(2)}|${t.toFixed(2)}|${seed}`; const hit = buildCache.get(pkey); if (hit) restoreMeshes(g, hit); else { const local = new GeoBatch(); buildPlatform(local, w, t, style, seed); local.flush(g, 'platform'); const snaps = snapMeshes(g.children); if (snaps.length) buildCache.set(pkey, snaps); } g.position.set(x, y, 0); this.group.add(g); if (opts.move) this.game.add(new Mover(c, g, x, cy, opts.move, t / 2, floaty ? 0.03 : 0)); else anim.bob(g, 0.035, 1.1); } else { buildPlatform(new OffsetSink(this.batch, x, y), w, t, style, seed); this.flushIfFinished(); } return c; } private buildGrounds(): void { const list = this.grounds.splice(0).sort((a, b) => a.x0 - b.x0); const merged: GroundRec[] = []; for (const g of list) { const last = merged[merged.length - 1]; if (last && last.style === g.style && Math.abs(last.top - g.top) < 1e-3 && Math.abs(last.bottom - g.bottom) < 1e-3 && g.x0 <= last.x1 + 0.01 && last.zBack === g.zBack && last.zFront === g.zFront && last.plain === g.plain) { last.x1 = Math.max(last.x1, g.x1); } else { merged.push({ ...g }); } } const key = 'g|' + this.def.id + '|' + JSON.stringify(merged); const hit = buildCache.get(key); if (hit) { restoreMeshes(this.group, hit); return; } // lo que ya hubiera en el lote (plataformas fijas, bloques) se vuelca antes: la caché guarda solo el terreno this.batch.flush(this.group); for (const g of merged) { buildSlab(this.batch, g.x0, g.x1, g.top, g.bottom, { style: g.style, zBack: g.zBack, zFront: g.zFront, seed: seedOf(g.x0, g.top), kind: 'ground', plain: g.plain, }); } const before = this.group.children.length; this.batch.flush(this.group); const snaps = snapMeshes(this.group.children.slice(before)); if (snaps.length) buildCache.set(key, snaps); } // ───────────── Agua ───────────── water(x0: number, x1: number, surface: number, depth: number, opts: Props = {}): Area { const lava = !!opts.lava; const m = waterMesh(x0, x1, surface, depth, { lava, zFront: opts.zFront ?? Z.waterFront, zBack: opts.zBack ?? Z.groundBack, shallow: opts.color ?? opts.shallow, deep: opts.deep, foam: opts.foam, top: opts.top, wave: opts.wave, shoreL: opts.shoreL, shoreR: opts.shoreR, }); this.group.add(m); const w = x1 - x0; return this.game.physics.addArea({ kind: lava ? 'lava' : 'water', x: x0 + w / 2, y: surface - depth / 2, hw: w / 2, hh: depth / 2, data: { ...opts, view: m }, }); } /** Cascada decorativa (opts: z, lava, width). No crea Area. */ waterfall(x: number, top: number, bottom: number, opts: Props = {}): THREE.Object3D { const w = opts.width ?? 1.6; const m = waterfallMesh(x - w / 2, x + w / 2, top, bottom, opts.z ?? Z.groundFront + 0.05, !!opts.lava); this.group.add(m); return m; } area(kind: string, x: number, y: number, w: number, h: number, data: Props = {}): Area { const a = this.game.physics.addArea({ kind, x, y, hw: w / 2, hh: h / 2, data }); if (data.visual === false) return a; let view: THREE.Object3D | null = null; if (kind === 'soft') view = this.softPatch(x, y, w, h); else if (kind === 'hazard' && data.visual === 'spikes') view = this.spikes(x, y - h / 2, w); if (view) { data.view = view; anim.tick(() => { view!.visible = a.enabled !== false; }); } return a; } private softPatch(x: number, y: number, w: number, h: number): THREE.Object3D { const tex = softSoilTexture(); const mat = kitMat('softSoil', { color: 0xffffff, map: tex, vertexColors: true, gloss: 0.15, rim: 0.2 }); tex.repeat.set(0.5, 0.5); const g = new THREE.Group(); g.name = 'soft'; const geo = extrude(roundRect(x - w / 2 - 0.05, y - h / 2, x + w / 2 + 0.05, y + h / 2 + 0.06, 0.25, 0.15, 0.08), Z.blockBack, Z.groundFront + 0.06, 0.08, 5, 2); paint(geo, (p, n, out) => { const k = 0.75 + 0.3 * ((p.y - (y - h / 2)) / Math.max(0.1, h)); out.setScalar(n.y > 0.5 ? 1.1 : k); }); const body = new THREE.Mesh(geo, mat); body.receiveShadow = true; g.add(body); // montoncitos de tierra suelta encima const r = rng(seedOf(x, y)); const crumbs = solid(0x9a6438, 0.15); const geos: THREE.BufferGeometry[] = []; for (let i = 0; i < Math.max(2, Math.round(w * 2.2)); i++) { const s = 0.12 + r() * 0.16; const sg = P.sphereLo().clone(); sg.scale(s * 1.4, s * 0.7, s); sg.translate(x - w / 2 + 0.2 + r() * (w - 0.4), y + h / 2 + 0.04, -1 + r() * 2.2); geos.push(sg); } const mg = mergeGeometries(geos); for (const gg of geos) gg.dispose(); if (mg) { const cm = new THREE.Mesh(mg, crumbs); cm.castShadow = true; g.add(cm); } // borde punteado claro para que se reconozca como excavable const dots: THREE.BufferGeometry[] = []; const per = 2 * (w + h); const n = Math.max(6, Math.round(per / 0.45)); for (let i = 0; i < n; i++) { let d = (i / n) * per; let px: number, py: number; if (d < w) { px = x - w / 2 + d; py = y + h / 2 - 0.12; } else if ((d -= w) < h) { px = x + w / 2 - 0.12; py = y + h / 2 - d; } else if ((d -= h) < w) { px = x + w / 2 - d; py = y - h / 2 + 0.12; } else { d -= w; px = x - w / 2 + 0.12; py = y - h / 2 + d; } const dg = P.sphereLo().clone(); dg.scale(0.07, 0.07, 0.03); dg.translate(px, py, Z.groundFront + 0.07); dots.push(dg); } const dm = mergeGeometries(dots); for (const gg of dots) gg.dispose(); if (dm) g.add(new THREE.Mesh(dm, solid(0xe8c08a, 0.2))); this.group.add(g); return g; } private spikes(x: number, base: number, w: number): THREE.Object3D { const n = Math.max(1, Math.round(w / 0.5)); const geos: THREE.BufferGeometry[] = []; for (let i = 0; i < n; i++) { for (const z of [-0.5, 0.4]) { const g = P.cone().clone(); g.scale(0.2, 0.55, 0.2); g.translate(x - w / 2 + (w * (i + 0.5)) / n, base + 0.27, z); geos.push(g); } } const mg = mergeGeometries(geos)!; for (const g of geos) g.dispose(); const m = new THREE.Mesh(mg, solid(0xd0d6e6, 0.85)); m.castShadow = true; this.group.add(m); return m; } // ───────────── Decorado ───────────── decor(emoji: string, x: number, y: number, opts: DecorOpts = {}): THREE.Object3D { const s = opts.scale ?? 1; const m = emojiMesh(emoji, s, { glow: opts.glow }); m.position.y = s * 0.46; if (opts.flipX) m.scale.x *= -1; const g = new THREE.Group(); g.name = `decor:${emoji}`; g.add(m); g.position.set(x, y, opts.z ?? -0.5); if (opts.rotation) g.rotation.z = opts.rotation; this.group.add(g); if (opts.sway) anim.sway(g, 0.05 + 0.03 / Math.max(0.5, s), 1.4 + Math.random() * 0.6); return g; } prop(kind: string, x: number, y: number, opts: Props = {}): THREE.Object3D { const bp = buildProp(kind, x, y, opts); if (!bp) { console.warn(`[world] prop desconocido: ${kind}`); return this.decor('❓', x, y, { scale: 1, z: opts.z ?? -1 }); } this.group.add(bp.group); const dynamic = !!opts.dynamic || !!bp.info.dynamic || this.finished; if (dynamic) { if (bp.swayer) anim.sway(bp.group, 0.08, 1.7); if (bp.kind === 'cloud') anim.bob(bp.group, 0.15, 0.5); if (bp.kind === 'lilypad') anim.bob(bp.group, 0.03, 1.4, 0.04); } else { this.staticProps.push(bp); } if (opts.solid) { bp.group.updateMatrixWorld(true); const box = new THREE.Box3().setFromObject(bp.group); if (bp.kind === 'bridge') { const w = (opts.width ?? 6) * (opts.scale ?? 1); this.game.physics.box(x, y - 0.1, w, 0.2, { oneWay: true, material: 'wood' }); } else { this.game.physics.box((box.min.x + box.max.x) / 2, (box.min.y + box.max.y) / 2, box.max.x - box.min.x, box.max.y - box.min.y, { material: opts.material ?? (bp.kind === 'rock' ? 'stone' : 'wood') }); } } return bp.group; } /** Reparte `count` props `kind` entre x0 y x1. y: número o 'ground' (busca el suelo bajo cada x). */ scatter(kind: string, x0: number, x1: number, y: number | 'ground', count: number, opts: Props = {}): THREE.Object3D[] { const r = rng(seedOf(x0, x1, count, kind.length)); const out: THREE.Object3D[] = []; for (let i = 0; i < count; i++) { const x = x0 + ((i + 0.2 + r() * 0.6) / count) * (x1 - x0); const gy = y === 'ground' ? this.game.physics.groundBelow(x, this.def.bounds.maxY + 50, 200) : y; if (gy === null) continue; const sc = (opts.scale ?? 1) * (0.8 + r() * 0.4); const z = opts.z !== undefined ? opts.z + (r() - 0.5) * (opts.zJitter ?? 0.6) : undefined; out.push(this.prop(kind, x, gy, { ...opts, scale: sc, z, seed: i * 31 + x })); } return out; } spawn(type: string, x: number, y: number, props: Props = {}) { return this.game.spawn(type, x, y, props); } exit(x: number, y: number, w: number, h: number, toZone: string, toSpawn = 'default', opts: Props = {}): void { this.game.add(new Exit({ x, y, hw: w / 2, hh: h / 2 }, toZone, toSpawn, !!opts.door, opts)); } backdrop(preset: string, opts: Props = {}): void { buildBackdrop(this.game, this.def, this.group, preset, opts); } // ───────────── Cierre ───────────── /** Fusiona terreno y props estáticos en pocas mallas. Lo llama el núcleo tras build(). */ finish(): void { if (this.finished) return; this.buildGrounds(); this.batch.flush(this.group); this.mergeProps(); this.finished = true; } private mergeProps(): void { if (!this.staticProps.length) return; this.group.updateMatrixWorld(true); // Clave: zona + posición/escala de cada decorado (si cambia el guion de la zona, cambia la clave). // (las posiciones de algunos decorados son aleatorias en cada visita: no entran en la clave) let sig = this.def.id + '|' + this.staticProps.length; for (const p of this.staticProps) sig += '|' + p.group.children.length; const pkey = 'p|' + sig; const cached = buildCache.get(pkey); if (cached) { for (const p of this.staticProps) { const meshes: THREE.Mesh[] = []; p.group.traverse((o) => { if ((o as THREE.Mesh).isMesh) meshes.push(o as THREE.Mesh); }); for (const m of meshes) { const mat = m.material; if (Array.isArray(mat) || m.userData.noMerge || (mat as THREE.MeshStandardMaterial).map) continue; m.removeFromParent(); } if (!p.group.children.length) p.group.removeFromParent(); } restoreMeshes(this.group, cached); this.staticProps.length = 0; return; } const created: THREE.Mesh[] = []; const lists = new Map(); const inv = new THREE.Matrix4(); const rel = new THREE.Matrix4(); const v = new THREE.Vector3(); const groupInv = new THREE.Matrix4().copy(this.group.matrixWorld).invert(); for (const p of this.staticProps) { inv.copy(p.group.matrixWorld).invert(); const meshes: THREE.Mesh[] = []; p.group.traverse((o) => { if ((o as THREE.Mesh).isMesh) meshes.push(o as THREE.Mesh); }); const scale = p.group.scale.x; for (const m of meshes) { const mat = m.material; if (Array.isArray(mat) || m.userData.noMerge || (mat as THREE.MeshStandardMaterial).map) continue; const src = m.geometry; // se conserva el índice (toNonIndexed triplicaba los vértices y hacía lenta la fusión) let g = src.clone(); g.userData = {}; for (const k of Object.keys(g.attributes)) if (k !== 'position' && k !== 'normal') g.deleteAttribute(k); const sw = (m.userData.sway ?? 0) as number; if (sw > 0) { rel.multiplyMatrices(inv, m.matrixWorld); const pos = g.attributes.position as THREE.BufferAttribute; const arr = new Float32Array(pos.count); for (let i = 0; i < pos.count; i++) { v.fromBufferAttribute(pos, i).applyMatrix4(rel); arr[i] = sw * Math.min(1.4, Math.max(0, v.y / p.info.h)) * Math.max(0.6, scale); } g.setAttribute('aSway', new THREE.BufferAttribute(arr, 1)); } g.applyMatrix4(rel.multiplyMatrices(groupInv, m.matrixWorld)); const ks = mat.userData.kitSolid as { hex: number; gloss: number } | undefined; let useMat = mat; if (ks) { useMat = kitMat(`propVC:${ks.gloss}`, { color: 0xffffff, vertexColors: true, gloss: ks.gloss }); const col = new THREE.Color(ks.hex); const n = g.attributes.position.count; const ca = new Float32Array(n * 3); for (let i = 0; i < n; i++) { ca[i * 3] = col.r; ca[i * 3 + 1] = col.g; ca[i * 3 + 2] = col.b; } g.setAttribute('color', new THREE.BufferAttribute(ca, 3)); } const key = useMat.uuid + (sw > 0 ? ':s' : ''); let l = lists.get(key); if (!l) { l = { mat: useMat, sway: sw > 0, geos: [] }; lists.set(key, l); } l.geos.push(g); m.removeFromParent(); } if (!p.group.children.length) p.group.removeFromParent(); } for (const { mat, sway, geos } of lists.values()) { const allIdx = geos.every((x) => !!x.index); const list = allIdx ? geos : geos.map((x) => (x.index ? x.toNonIndexed() : x)); const merged = list.length === 1 ? list[0] : mergeGeometries(list, false); if (list.length > 1) for (const g of list) g.dispose(); if (!allIdx) for (const g of geos) if (g.index) g.dispose(); if (!merged) continue; merged.computeBoundingSphere(); const mesh = new THREE.Mesh(merged, sway ? swayVariant(mat) : mat); mesh.name = 'props'; mesh.castShadow = true; mesh.receiveShadow = true; this.group.add(mesh); created.push(mesh); } const snaps = snapMeshes(created); if (snaps.length) buildCache.set(pkey, snaps); this.staticProps.length = 0; } } export { styleOf };