@greenborn/mapa-voxel-back 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +107 -2
- package/package.json +36 -4
- package/src/formato/chunk_compacto.js +263 -0
- package/src/generador/cartel_tienda.js +118 -0
- package/src/generador/construirMapa.js +447 -0
- package/src/generador/excavar_refugios.js +32 -0
- package/src/generador/genera_casa/bathroom_impl.js +87 -0
- package/src/generador/genera_casa/bathrooms_insert.js +104 -0
- package/src/generador/genera_casa/generadorCasa.js +470 -0
- package/src/generador/genera_casa/generadorCasaConexiones.js +299 -0
- package/src/generador/genera_casa/generadorCasaPisos.js +816 -0
- package/src/generador/genera_casa/generadorCasaVentanas.js +361 -0
- package/src/generador/genera_casa/ubicacionSalaCasa.js +486 -0
- package/src/generador/genera_nidos.js +74 -0
- package/src/generador/genera_refugios.js +301 -0
- package/src/generador/genera_tiendas.js +200 -0
- package/src/generador/mapConfig.js +549 -0
- package/src/generador/mapType3.js +635 -0
- package/src/generador/mapType3Block.js +476 -0
- package/src/generador/mapType3Center.js +137 -0
- package/src/generador/mapType3Parcel.js +63 -0
- package/src/generador/mapType3Utils.js +299 -0
- package/src/generador/volumeBuffer.js +210 -0
- package/src/index.js +23 -0
- package/src/plugins/datos.js +111 -0
- package/src/plugins/registro.js +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 2012lucho
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,108 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @greenborn/mapa-voxel-back
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Generador de mapas voxel del lado del servidor: terreno, edificios (casas de
|
|
4
|
+
varios pisos, escaleras, ventanas, baños, armarios), vehículos, árboles y
|
|
5
|
+
postes, refugios subterráneos, nidos, tiendas, bases por modo de juego,
|
|
6
|
+
partición en chunks, luces e índice de salas.
|
|
7
|
+
|
|
8
|
+
Módulo puro: no depende de three.js ni del DOM, así que corre en Node y en un
|
|
9
|
+
`worker_thread` o Web Worker. Sólo usa `pngjs` (planos PNG, opcionales).
|
|
10
|
+
|
|
11
|
+
## Qué trae el paquete y qué aporta el consumidor
|
|
12
|
+
|
|
13
|
+
- **Del paquete**: los tipos de bloque (`BLOCK_TYPES`, `BLOCK_PROPERTIES`), las
|
|
14
|
+
constantes del mundo (`WORLD_CONFIG`, `TERRAIN_CONFIG`, `CONFIG_GENERATION`),
|
|
15
|
+
el generador completo y el formato de chunks compacto.
|
|
16
|
+
- **Plugins de datos (del consumidor)**: el contenido de juego que el
|
|
17
|
+
generador necesita, registrado con `registrarPlugins`. Son los nombres de
|
|
18
|
+
`ESQUEMA_PLUGINS` (`src/plugins/datos.js`):
|
|
19
|
+
|
|
20
|
+
| Plugin | Nombres que aporta |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `arboles` | `elegirArbol(x, z)` |
|
|
23
|
+
| `autos` | `AUTOS`, `ORDEN_AUTOS`, `idEntidadAuto`, `PROPORCION_MOTOS` |
|
|
24
|
+
| `postes` | `ID_POSTE` |
|
|
25
|
+
| `lucesInteriores` | `ID_LUZ_INTERIOR` |
|
|
26
|
+
| `refugios` | `PROB_REFUGIO_PARCELA`, `MIN_REFUGIOS`, `INTENTOS_REFUGIO`, `REFUGIO`, `PROFUNDIDAD_REFUGIO`, `ejesRefugio`, `rotYHacia` |
|
|
27
|
+
| `armarios` | `ARMARIO` |
|
|
28
|
+
| `necesidades` | `sortearArmario`, `sortearCantidades` |
|
|
29
|
+
| `tiendas` | `TIENDAS_POR_MAPA`, `ROT_PUERTA`, `ALTO_GONDOLA` |
|
|
30
|
+
| `hordas` | `PROB_NIDO_PARCELA`, `INTENTOS_NIDO`, `RADIO_NIDO`, `DIST_MIN_BASE_NIDO`, `DIST_MIN_ENTRE_NIDOS`, `ESCALA_SUPERFICIE` |
|
|
31
|
+
| `equipos` | `COLORES_EQUIPO` |
|
|
32
|
+
| `configuracion` | `CONFIG` (p. ej. `lighting.point.distance`) |
|
|
33
|
+
|
|
34
|
+
Todos los plugins son obligatorios para `construirMapa`: si falta alguno lanza
|
|
35
|
+
un error que lista lo que falta (`pluginsFaltantes()`).
|
|
36
|
+
|
|
37
|
+
## Uso
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
import {
|
|
41
|
+
configurarMundo, registrarPlugins, construirMapa, buffersTransferibles,
|
|
42
|
+
} from '@greenborn/mapa-voxel-back';
|
|
43
|
+
|
|
44
|
+
configurarMundo({ factorSuperficie: 1, directorioMinimapas: './maps' });
|
|
45
|
+
registrarPlugins({
|
|
46
|
+
arboles: { elegirArbol },
|
|
47
|
+
autos: { AUTOS, ORDEN_AUTOS, idEntidadAuto, PROPORCION_MOTOS },
|
|
48
|
+
// ...resto de plugins de la tabla
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const mapa = construirMapa({ modo: 'zombies' }); // 'zombies' | 'equipos' | null
|
|
52
|
+
// Para enviar desde un worker sin copiar los buffers grandes:
|
|
53
|
+
// parentPort.postMessage({ mapa }, buffersTransferibles(mapa));
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### `configurarMundo({ factorSuperficie, directorioMinimapas })`
|
|
57
|
+
|
|
58
|
+
- `factorSuperficie` (por defecto `1`): fracción de la superficie base. El lado
|
|
59
|
+
del mapa se escala con su raíz cuadrada. Debe ser mayor que 0.
|
|
60
|
+
- `directorioMinimapas` (por defecto `null`): carpeta donde se escriben los PNG
|
|
61
|
+
de los planos. Con `null` no se escribe ningún archivo.
|
|
62
|
+
|
|
63
|
+
Pensado para un worker por sala: cada `worker_thread` tiene su propia copia de
|
|
64
|
+
los módulos, así que el estado de configuración no se comparte entre salas.
|
|
65
|
+
|
|
66
|
+
### `construirMapa(opciones)`
|
|
67
|
+
|
|
68
|
+
Devuelve sólo datos clonables (sin funciones ni instancias de clase):
|
|
69
|
+
`heightMap`, `maxHeightMap`, `structures`, `startPosition`, `lights`, `chunks`,
|
|
70
|
+
`roomIndex`, `autos`, `minimapFile`, `zonasEspeciales`, `zonas`, `nidos`,
|
|
71
|
+
`refugios`, `tiendas` y `modo`.
|
|
72
|
+
|
|
73
|
+
- `modo`: `'zombies'` y `'equipos'` eligen bases por bando (casas ya generadas,
|
|
74
|
+
nunca construcciones nuevas). Otro valor no agrega bases especiales.
|
|
75
|
+
|
|
76
|
+
## Determinismo
|
|
77
|
+
|
|
78
|
+
El generador usa `Math.random`. Para reproducir un mapa, sembrar
|
|
79
|
+
`Math.random` antes de llamar a `construirMapa` con un generador determinista.
|
|
80
|
+
|
|
81
|
+
## Tests
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
npm install
|
|
85
|
+
npm test
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Los tests usan plugins falsos de `fixtures/plugins_falsos.js`: validan la API,
|
|
89
|
+
la configuración del mundo y que la generación sea determinista con la misma
|
|
90
|
+
semilla. No validan el contenido de juego real.
|
|
91
|
+
|
|
92
|
+
## Origen y pendientes
|
|
93
|
+
|
|
94
|
+
- Extraído de `server/generador_mapa/` del proyecto
|
|
95
|
+
`Lab/test_3d_html5_multiplayer`. Con los mismos datos de juego y la misma
|
|
96
|
+
semilla de `Math.random`, el mapa generado por el paquete es idéntico al de
|
|
97
|
+
Lab (mismo hash de chunks, estructuras y entidades).
|
|
98
|
+
- Quedaron fuera del paquete, porque mantienen estado de partida o usan
|
|
99
|
+
`workerData`: `mapGenerator.js`, `preparador_mapa.js`, `mapaWorker.js` y
|
|
100
|
+
`zonasControl.js`. Son el glue de runtime que queda en Lab.
|
|
101
|
+
- `chunk_compacto.js` también lo usa el cliente del navegador. El paquete tiene
|
|
102
|
+
su copia en `src/formato/`; el cliente mantiene la suya.
|
|
103
|
+
- Lab todavía no consume este paquete: sigue con su copia de
|
|
104
|
+
`server/generador_mapa/`.
|
|
105
|
+
|
|
106
|
+
## Licencia
|
|
107
|
+
|
|
108
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@greenborn/mapa-voxel-back",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Generador de mapas voxel del lado del servidor (terreno, edificios, chunks, luces e índice de salas) con plugins de datos de juego. Módulo para correr en Node o en un Web Worker/worker_thread.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"src",
|
|
8
|
+
"README.md",
|
|
9
|
+
"LICENSE"
|
|
10
|
+
],
|
|
11
|
+
"main": "./src/index.js",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.js"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"voxel",
|
|
20
|
+
"mapa",
|
|
21
|
+
"procedural",
|
|
22
|
+
"servidor",
|
|
23
|
+
"greenborn"
|
|
24
|
+
],
|
|
25
|
+
"license": "MIT",
|
|
26
|
+
"author": {
|
|
27
|
+
"name": "2012lucho"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=18"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"pngjs": "^7.0.0"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// chunk_compacto.js - Formato compacto de los datos crudos de un chunk.
|
|
2
|
+
//
|
|
3
|
+
// Lo comparten el servidor (construirMapa.js, multijugador.js), el hilo
|
|
4
|
+
// principal del cliente (manejo_chunks.js) y el worker de mallado
|
|
5
|
+
// (world_voxel.js): por eso no importa nada ni toca three.js/DOM.
|
|
6
|
+
//
|
|
7
|
+
// Un mapa son ~38 millones de celdas y ~550 mil tintes, y cada copia viva de
|
|
8
|
+
// esos datos (mapa vigente del servidor, mapa de la ronda siguiente, mensaje
|
|
9
|
+
// a cada cliente, `chunkData`, caché de cada worker) pagaba el formato
|
|
10
|
+
// ingenuo entero. Acá se guarda sólo lo que no se puede deducir:
|
|
11
|
+
//
|
|
12
|
+
// VOXELS
|
|
13
|
+
// Todas las columnas de un chunk son iguales por debajo de cierta altura
|
|
14
|
+
// (subsuelo macizo) y aire por encima del edificio más alto. Sólo se
|
|
15
|
+
// guardan las capas [yBase, yBase + capas):
|
|
16
|
+
// - y < yBase => `relleno` (tipo implícito del subsuelo)
|
|
17
|
+
// - y >= yBase + capas => aire
|
|
18
|
+
// `types` sigue empaquetado a 4 bits/celda, con el mismo orden de siempre
|
|
19
|
+
// pero relativo a yBase: idx = (lx * capas + (y - yBase)) * D + lz
|
|
20
|
+
// `volumeHeight` conserva su significado: el alto LÓGICO del mundo.
|
|
21
|
+
// Si alguien escribe fuera del rango guardado (un cráter que baja al
|
|
22
|
+
// subsuelo), el rango crece solo (ver `escribirVoxel`).
|
|
23
|
+
//
|
|
24
|
+
// TINTES
|
|
25
|
+
// En vez de un objeto `{ idx, tintMinimap: {...}, tintRender: {...} }` por
|
|
26
|
+
// celda (3 objetos de heap, y JSON al viajar), tres piezas:
|
|
27
|
+
// - `tintClaves` Uint32Array ordenado: clave de celda (ver `claveTinte`)
|
|
28
|
+
// - `tintIds` Uint16Array paralelo: índice en `tintPaleta` (0 = sin tinte)
|
|
29
|
+
// - `tintPaleta` [null, { tintMinimap?, tintRender? }, ...] combinaciones únicas
|
|
30
|
+
// `tintN` es la cantidad de entradas usadas (los arrays pueden tener holgura).
|
|
31
|
+
// La clave no depende de yBase/capas, así que crecer el rango no la mueve.
|
|
32
|
+
//
|
|
33
|
+
// MAPAS DE ALTURA
|
|
34
|
+
// `heightMap`/`maxHeightMap` eran arrays de arrays de números (8 bytes por
|
|
35
|
+
// celda en Node, y JSON de ~1.5 MB c/u hacia cada cliente). Viajan y se
|
|
36
|
+
// guardan como un Uint8Array plano; `filasMapaAlturas` arma vistas por fila
|
|
37
|
+
// para que el código que hace `mapa[x][z]` siga funcionando sin copiar.
|
|
38
|
+
|
|
39
|
+
/** Capas extra que se reservan al crecer, para no realojar en cada voxel. */
|
|
40
|
+
const MARGEN_CRECER = 6;
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
// Voxels
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Tipo de bloque en coordenadas LOCALES del chunk. No valida lx/lz (el que
|
|
48
|
+
* llama ya sabe que caen dentro); `y` puede ser cualquiera.
|
|
49
|
+
*/
|
|
50
|
+
export function leerVoxel(c, lx, y, lz) {
|
|
51
|
+
const yl = y - c.yBase;
|
|
52
|
+
if (yl < 0) return y < 0 ? 0 : c.relleno;
|
|
53
|
+
if (yl >= c.capas) return 0;
|
|
54
|
+
const idx = (lx * c.capas + yl) * c.volumeDepth + lz;
|
|
55
|
+
return (c.types[idx >> 1] >> ((idx & 1) << 2)) & 0x0F;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Realoja `types` para que cubra las capas [y0, y1). Conserva el contenido. */
|
|
59
|
+
function cambiarRango(c, y0, y1) {
|
|
60
|
+
const W = c.volumeWidth, D = c.volumeDepth;
|
|
61
|
+
const capasNuevas = y1 - y0;
|
|
62
|
+
const nuevo = new Uint8Array(Math.ceil((W * capasNuevas * D) / 2));
|
|
63
|
+
for (let lx = 0; lx < W; lx++) {
|
|
64
|
+
for (let yl = 0; yl < capasNuevas; yl++) {
|
|
65
|
+
const y = y0 + yl;
|
|
66
|
+
const fila = (lx * capasNuevas + yl) * D;
|
|
67
|
+
for (let lz = 0; lz < D; lz++) {
|
|
68
|
+
const t = leerVoxel(c, lx, y, lz);
|
|
69
|
+
if (t === 0) continue;
|
|
70
|
+
const idx = fila + lz;
|
|
71
|
+
nuevo[idx >> 1] |= t << ((idx & 1) << 2);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
c.types = nuevo;
|
|
76
|
+
c.yBase = y0;
|
|
77
|
+
c.capas = capasNuevas;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Cambia el tipo de un voxel (coordenadas locales). Devuelve false si cae
|
|
82
|
+
* fuera del mundo. Si la celda queda fuera del rango guardado, lo agranda.
|
|
83
|
+
*/
|
|
84
|
+
export function escribirVoxel(c, lx, y, lz, tipo) {
|
|
85
|
+
if (y < 0 || y >= c.volumeHeight) return false;
|
|
86
|
+
if (lx < 0 || lx >= c.volumeWidth || lz < 0 || lz >= c.volumeDepth) return false;
|
|
87
|
+
tipo &= 0x0F;
|
|
88
|
+
if (y < c.yBase) {
|
|
89
|
+
if (tipo === c.relleno) return true; // ya vale eso
|
|
90
|
+
cambiarRango(c, Math.max(0, y - MARGEN_CRECER), c.yBase + c.capas);
|
|
91
|
+
} else if (y >= c.yBase + c.capas) {
|
|
92
|
+
if (tipo === 0) return true; // ya es aire
|
|
93
|
+
cambiarRango(c, c.yBase, Math.min(c.volumeHeight, y + 1 + MARGEN_CRECER));
|
|
94
|
+
}
|
|
95
|
+
const idx = (lx * c.capas + (y - c.yBase)) * c.volumeDepth + lz;
|
|
96
|
+
const byteIdx = idx >> 1;
|
|
97
|
+
const shift = (idx & 1) << 2;
|
|
98
|
+
c.types[byteIdx] = (c.types[byteIdx] & (0xF0 >> shift)) | (tipo << shift);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
// Tintes
|
|
104
|
+
// ---------------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
/** Clave de celda para los tintes: columna (lx,lz) en los bits altos, `y` en los 8 bajos. */
|
|
107
|
+
export function claveTinte(c, lx, y, lz) {
|
|
108
|
+
return ((lx * c.volumeDepth + lz) << 8) | y;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Posición de `clave` en `tintClaves`, o -1 si la celda no tiene entrada. */
|
|
112
|
+
function buscarTinte(c, clave) {
|
|
113
|
+
const claves = c.tintClaves;
|
|
114
|
+
let lo = 0, hi = (c.tintN | 0) - 1;
|
|
115
|
+
while (lo <= hi) {
|
|
116
|
+
const mid = (lo + hi) >> 1;
|
|
117
|
+
const v = claves[mid];
|
|
118
|
+
if (v === clave) return mid;
|
|
119
|
+
if (v < clave) lo = mid + 1; else hi = mid - 1;
|
|
120
|
+
}
|
|
121
|
+
return -(lo + 1); // negativo: -(punto de inserción + 1)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function mismoTinte(a, b) {
|
|
125
|
+
if (!a || !b) return !a && !b;
|
|
126
|
+
return a.color === b.color && a.opacity === b.opacity;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Índice en `tintPaleta` de la combinación (minimapa, render); la agrega si falta. */
|
|
130
|
+
export function idPaleta(c, tintMinimap, tintRender) {
|
|
131
|
+
if (!tintMinimap && !tintRender) return 0;
|
|
132
|
+
const paleta = c.tintPaleta || (c.tintPaleta = [null]);
|
|
133
|
+
for (let i = 1; i < paleta.length; i++) {
|
|
134
|
+
const p = paleta[i];
|
|
135
|
+
if (mismoTinte(p.tintMinimap, tintMinimap) && mismoTinte(p.tintRender, tintRender)) return i;
|
|
136
|
+
}
|
|
137
|
+
if (paleta.length >= 65535) return 0; // no entra en Uint16: se queda sin tinte
|
|
138
|
+
const entrada = {};
|
|
139
|
+
if (tintMinimap) entrada.tintMinimap = { color: tintMinimap.color, opacity: tintMinimap.opacity };
|
|
140
|
+
if (tintRender) entrada.tintRender = { color: tintRender.color, opacity: tintRender.opacity };
|
|
141
|
+
paleta.push(entrada);
|
|
142
|
+
return paleta.length - 1;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Combinación `{ tintMinimap?, tintRender? }` de una celda, o null. */
|
|
146
|
+
export function tinteDe(c, lx, y, lz) {
|
|
147
|
+
if (!c.tintN) return null;
|
|
148
|
+
const pos = buscarTinte(c, claveTinte(c, lx, y, lz));
|
|
149
|
+
if (pos < 0) return null;
|
|
150
|
+
return c.tintPaleta[c.tintIds[pos]] || null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Aplica (o reemplaza) el tinte de render de una celda, conservando el de minimapa. */
|
|
154
|
+
export function ponerTinteRender(c, lx, y, lz, color, opacity) {
|
|
155
|
+
if (y < 0 || y >= c.volumeHeight) return false;
|
|
156
|
+
if (lx < 0 || lx >= c.volumeWidth || lz < 0 || lz >= c.volumeDepth) return false;
|
|
157
|
+
const clave = claveTinte(c, lx, y, lz);
|
|
158
|
+
const n = c.tintN | 0;
|
|
159
|
+
let pos = n > 0 ? buscarTinte(c, clave) : -1;
|
|
160
|
+
if (pos >= 0) {
|
|
161
|
+
const previo = c.tintPaleta[c.tintIds[pos]] || null;
|
|
162
|
+
c.tintIds[pos] = idPaleta(c, previo && previo.tintMinimap, { color, opacity });
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
const id = idPaleta(c, null, { color, opacity });
|
|
166
|
+
if (id === 0) return false;
|
|
167
|
+
pos = -pos - 1;
|
|
168
|
+
if (!c.tintClaves || n >= c.tintClaves.length) {
|
|
169
|
+
const cap = n + Math.max(64, n >> 3);
|
|
170
|
+
const claves = new Uint32Array(cap);
|
|
171
|
+
const ids = new Uint16Array(cap);
|
|
172
|
+
if (n > 0) { claves.set(c.tintClaves.subarray(0, n)); ids.set(c.tintIds.subarray(0, n)); }
|
|
173
|
+
c.tintClaves = claves;
|
|
174
|
+
c.tintIds = ids;
|
|
175
|
+
}
|
|
176
|
+
c.tintClaves.copyWithin(pos + 1, pos, n);
|
|
177
|
+
c.tintIds.copyWithin(pos + 1, pos, n);
|
|
178
|
+
c.tintClaves[pos] = clave;
|
|
179
|
+
c.tintIds[pos] = id;
|
|
180
|
+
c.tintN = n + 1;
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Quita cualquier tinte de la celda (el bloque ya no existe). */
|
|
185
|
+
export function quitarTinte(c, lx, y, lz) {
|
|
186
|
+
if (!c.tintN) return;
|
|
187
|
+
const pos = buscarTinte(c, claveTinte(c, lx, y, lz));
|
|
188
|
+
if (pos >= 0) c.tintIds[pos] = 0;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
// Transporte
|
|
193
|
+
// ---------------------------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
function comoTipado(valor, Ctor) {
|
|
196
|
+
if (!valor || valor instanceof Ctor) return valor;
|
|
197
|
+
// socket.io entrega los binarios como ArrayBuffer en el navegador (y como
|
|
198
|
+
// Buffer en Node): se vuelve a envolver con el tipo original.
|
|
199
|
+
if (valor instanceof ArrayBuffer) return new Ctor(valor);
|
|
200
|
+
if (ArrayBuffer.isView(valor)) {
|
|
201
|
+
const bytes = Ctor.BYTES_PER_ELEMENT;
|
|
202
|
+
if (valor.byteOffset % bytes === 0) {
|
|
203
|
+
return new Ctor(valor.buffer, valor.byteOffset, Math.floor(valor.byteLength / bytes));
|
|
204
|
+
}
|
|
205
|
+
return new Ctor(valor.buffer.slice(valor.byteOffset, valor.byteOffset + valor.byteLength));
|
|
206
|
+
}
|
|
207
|
+
return new Ctor(valor);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Deja listo para usar un chunk recién llegado por la red: los TypedArray
|
|
212
|
+
* pierden su tipo en el camino (ver `comoTipado`). Idempotente.
|
|
213
|
+
*/
|
|
214
|
+
export function revivirChunk(c) {
|
|
215
|
+
if (!c) return c;
|
|
216
|
+
if (c.types) c.types = comoTipado(c.types, Uint8Array);
|
|
217
|
+
if (c.tintClaves) c.tintClaves = comoTipado(c.tintClaves, Uint32Array);
|
|
218
|
+
if (c.tintIds) c.tintIds = comoTipado(c.tintIds, Uint16Array);
|
|
219
|
+
return c;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ---------------------------------------------------------------------------
|
|
223
|
+
// Mapas de altura
|
|
224
|
+
// ---------------------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Pasa un mapa de alturas `mapa[x][z]` a `{ ancho, profundo, datos }` con un
|
|
228
|
+
* byte por celda (datos[x * profundo + z]). Devuelve null si algún valor no
|
|
229
|
+
* entra en un byte: en ese caso se sigue usando el array anidado.
|
|
230
|
+
*/
|
|
231
|
+
export function compactarMapaAlturas(mapa) {
|
|
232
|
+
if (!Array.isArray(mapa) || mapa.length === 0 || !mapa[0]) return null;
|
|
233
|
+
const ancho = mapa.length;
|
|
234
|
+
const profundo = mapa[0].length;
|
|
235
|
+
const datos = new Uint8Array(ancho * profundo);
|
|
236
|
+
for (let x = 0; x < ancho; x++) {
|
|
237
|
+
const fila = mapa[x];
|
|
238
|
+
if (!fila || fila.length !== profundo) return null;
|
|
239
|
+
const base = x * profundo;
|
|
240
|
+
for (let z = 0; z < profundo; z++) {
|
|
241
|
+
const v = fila[z];
|
|
242
|
+
if (!Number.isInteger(v) || v < 0 || v > 255) return null;
|
|
243
|
+
datos[base + z] = v;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { ancho, profundo, datos };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Inverso de `compactarMapaAlturas` para leer: un array de vistas por fila
|
|
251
|
+
* sobre el mismo buffer, así `filas[x][z]` funciona sin copiar los datos.
|
|
252
|
+
* Si ya recibe un array anidado (formato viejo), lo devuelve tal cual.
|
|
253
|
+
*/
|
|
254
|
+
export function filasMapaAlturas(mapa) {
|
|
255
|
+
if (!mapa || Array.isArray(mapa)) return mapa || null;
|
|
256
|
+
const datos = comoTipado(mapa.datos, Uint8Array);
|
|
257
|
+
const { ancho, profundo } = mapa;
|
|
258
|
+
const filas = new Array(ancho);
|
|
259
|
+
for (let x = 0; x < ancho; x++) {
|
|
260
|
+
filas[x] = datos.subarray(x * profundo, (x + 1) * profundo);
|
|
261
|
+
}
|
|
262
|
+
return filas;
|
|
263
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// cartel_tienda.js - Cartel de cada tienda, armado con bloques del mapa.
|
|
2
|
+
//
|
|
3
|
+
// Va sobre la fachada que da a la calle, justo encima de la puerta. El tablero
|
|
4
|
+
// queda en el plano exterior de la pared (un bloque hacia la calle), así que
|
|
5
|
+
// se apoya en la fachada. Las letras van en blanco sobre un tablero de asfalto.
|
|
6
|
+
// Sólo se escriben celdas de aire: si una celda ya tiene algo (otra casa, la
|
|
7
|
+
// calle, un techo), se deja tal cual.
|
|
8
|
+
//
|
|
9
|
+
// Lo llama generateVolumeType3 después de tallar puertas y ventanas; las
|
|
10
|
+
// tiendas ya están marcadas (`s.tienda`, `s.tiendaLado`) por elegirTiendas.
|
|
11
|
+
|
|
12
|
+
import { BLOCK_TYPES } from './mapConfig.js';
|
|
13
|
+
|
|
14
|
+
const TEXTO = 'TIENDA';
|
|
15
|
+
/** Fuente de 3x5: cada fila es una cadena de 0/1 (1 = bloque de letra). */
|
|
16
|
+
const FUENTE = {
|
|
17
|
+
T: ['111', '010', '010', '010', '010'],
|
|
18
|
+
I: ['111', '010', '010', '010', '111'],
|
|
19
|
+
E: ['111', '100', '110', '100', '111'],
|
|
20
|
+
N: ['101', '111', '111', '111', '101'],
|
|
21
|
+
D: ['110', '101', '101', '101', '110'],
|
|
22
|
+
A: ['010', '101', '111', '101', '101']
|
|
23
|
+
};
|
|
24
|
+
const ANCHO_LETRA = 3, ALTO_LETRA = 5, ESPACIO = 1;
|
|
25
|
+
const MARGEN = 1; // borde del tablero alrededor de las letras
|
|
26
|
+
/** Altura del cartel sobre el suelo de la sala: a la altura del techo (hy+8 en salas de 9) y hacia arriba. */
|
|
27
|
+
const DESDE_PISO = 8;
|
|
28
|
+
const COLOR_TABLERO = BLOCK_TYPES.ASPHALT;
|
|
29
|
+
const COLOR_LETRA = BLOCK_TYPES.WHITE;
|
|
30
|
+
|
|
31
|
+
/** Máscara del texto: matriz de filas (arriba→abajo) con true donde hay letra. */
|
|
32
|
+
function mascaraTexto(texto) {
|
|
33
|
+
const filas = Array.from({ length: ALTO_LETRA }, () => []);
|
|
34
|
+
for (const ch of texto) {
|
|
35
|
+
const g = FUENTE[ch];
|
|
36
|
+
for (let f = 0; f < ALTO_LETRA; f++) {
|
|
37
|
+
for (let c = 0; c < ANCHO_LETRA; c++) filas[f].push(g ? g[f][c] === '1' : false);
|
|
38
|
+
for (let e = 0; e < ESPACIO; e++) filas[f].push(false);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
for (const fila of filas) fila.length -= ESPACIO; // sin espacio al final
|
|
42
|
+
return filas;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Pinta el cartel de una tienda. `s` es la sala (x, y, z, width, depth, height)
|
|
47
|
+
* y `lado` la fachada de calle ('N','S','E','O'), igual que en genera_tiendas.js.
|
|
48
|
+
*/
|
|
49
|
+
export function pintarCartelTienda(volume, s, lado, width, depth, volumeHeight) {
|
|
50
|
+
const mascara = mascaraTexto(TEXTO);
|
|
51
|
+
const anchoLetras = mascara[0].length;
|
|
52
|
+
const anchoTablero = anchoLetras + 2 * MARGEN;
|
|
53
|
+
const altoTablero = ALTO_LETRA + 2 * MARGEN;
|
|
54
|
+
|
|
55
|
+
const alongZ = lado === 'N' || lado === 'S'; // la fachada corre a lo largo de x
|
|
56
|
+
const ancho = alongZ ? s.width : s.depth; // largo de la fachada
|
|
57
|
+
const inicioLat = alongZ ? s.x : s.z; // coordenada lateral del primer borde
|
|
58
|
+
// plano exterior de la pared (un bloque hacia la calle)
|
|
59
|
+
let plano;
|
|
60
|
+
if (lado === 'N') plano = s.z - 1;
|
|
61
|
+
else if (lado === 'S') plano = s.z + s.depth;
|
|
62
|
+
else if (lado === 'O') plano = s.x - 1;
|
|
63
|
+
else plano = s.x + s.width;
|
|
64
|
+
|
|
65
|
+
// centrado sobre la puerta (la puerta está en el centro de la fachada)
|
|
66
|
+
const lat0 = inicioLat + Math.floor((ancho - anchoTablero) / 2);
|
|
67
|
+
const y0 = s.y + DESDE_PISO;
|
|
68
|
+
|
|
69
|
+
const cell = (lat, y) => {
|
|
70
|
+
const x = alongZ ? lat : plano;
|
|
71
|
+
const z = alongZ ? plano : lat;
|
|
72
|
+
return { x, y, z };
|
|
73
|
+
};
|
|
74
|
+
const dentro = ({ x, y, z }) => x >= 0 && x < width && z >= 0 && z < depth && y >= 0 && y < volumeHeight;
|
|
75
|
+
// tablero: sólo sobre aire. Letras: sobre el tablero que acabamos de poner.
|
|
76
|
+
const pintar = (lat, y, tipo) => {
|
|
77
|
+
const p = cell(lat, y);
|
|
78
|
+
if (!dentro(p)) return;
|
|
79
|
+
if (volume.getType(p.x, p.y, p.z) !== BLOCK_TYPES.AIR) return;
|
|
80
|
+
volume.set(p.x, p.y, p.z, tipo);
|
|
81
|
+
};
|
|
82
|
+
const pintarLetra = (lat, y) => {
|
|
83
|
+
const p = cell(lat, y);
|
|
84
|
+
if (!dentro(p)) return;
|
|
85
|
+
volume.set(p.x, p.y, p.z, COLOR_LETRA);
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// Sentido de lectura: el observador está en la calle, mirando hacia la fachada.
|
|
89
|
+
// Con su derecha = forward × up, en 'N' (mira +z) la derecha es −x, y en 'E'
|
|
90
|
+
// (mira −x) la derecha es −z. Ahí el eje lateral crece hacia la izquierda del
|
|
91
|
+
// observador, así que las columnas se invierten para que el texto no salga espejado.
|
|
92
|
+
const invertirLectura = lado === 'N' || lado === 'E';
|
|
93
|
+
|
|
94
|
+
// tablero completo y después las letras encima
|
|
95
|
+
for (let f = 0; f < altoTablero; f++) {
|
|
96
|
+
for (let c = 0; c < anchoTablero; c++) pintar(lat0 + c, y0 + f, COLOR_TABLERO);
|
|
97
|
+
}
|
|
98
|
+
for (let f = 0; f < ALTO_LETRA; f++) {
|
|
99
|
+
// la fila 0 de la máscara es la de arriba: va en la fila superior del tablero
|
|
100
|
+
const yFila = y0 + MARGEN + (ALTO_LETRA - 1 - f);
|
|
101
|
+
for (let c = 0; c < anchoLetras; c++) {
|
|
102
|
+
if (!mascara[f][c]) continue;
|
|
103
|
+
const col = invertirLectura ? (anchoLetras - 1 - c) : c;
|
|
104
|
+
pintarLetra(lat0 + MARGEN + col, yFila);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Pinta el cartel de todas las tiendas del mapa. Las salas tienda tienen
|
|
111
|
+
* `tienda === true` y `tiendaLado` (lo pone elegirTiendas).
|
|
112
|
+
*/
|
|
113
|
+
export function pintarCarteles(volume, structures, width, depth, volumeHeight) {
|
|
114
|
+
for (const s of structures || []) {
|
|
115
|
+
if (!s || !s.tienda || !s.tiendaLado) continue;
|
|
116
|
+
pintarCartelTienda(volume, s, s.tiendaLado, width, depth, volumeHeight);
|
|
117
|
+
}
|
|
118
|
+
}
|