@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.
@@ -0,0 +1,63 @@
1
+ import { BLOCK_TYPES } from './mapConfig.js';
2
+ import { generateParcelRooms } from './genera_casa/generadorCasa.js';
3
+
4
+
5
+ // Genera el contenido de una parcela individual dentro de una cuadra.
6
+ // Recibe las coordenadas de esquina inferior izquierda de la parcela y sus
7
+ // dimensiones, junto con referencias a los mapas y estructuras donde debe
8
+ // escribir. `orientation` es una letra N/S/E/O que indica el frente.
9
+ function generateParcel(plotX0, plotZ0, plotWidth, plotDepth,
10
+ mapWidth, mapDepth, baseY,
11
+ surfaceTypeMap, structures,
12
+ orientation,
13
+ roomHeight) {
14
+ // fijar todo el suelo de la parcela a pasto primero
15
+ for (let x = plotX0; x < plotX0 + plotWidth; x++) {
16
+ for (let z = plotZ0; z < plotZ0 + plotDepth; z++) {
17
+ if (x >= 0 && x < mapWidth && z >= 0 && z < mapDepth) {
18
+ surfaceTypeMap[x][z] = BLOCK_TYPES.GREEN;
19
+ }
20
+ }
21
+ }
22
+
23
+ // líneas horizontales (bordes superior e inferior) en ladrillo
24
+ for (let i = 0; i < plotWidth; i++) {
25
+ const x = plotX0 + i;
26
+ const zTop = plotZ0;
27
+ const zBottom = plotZ0 + plotDepth - 1;
28
+ if (x >= 0 && x < mapWidth) {
29
+ if (zTop >= 0 && zTop < mapDepth) {
30
+ if (surfaceTypeMap[x][zTop] !== BLOCK_TYPES.ASPHALT) surfaceTypeMap[x][zTop] = BLOCK_TYPES.BRICK;
31
+ }
32
+ if (zBottom >= 0 && zBottom < mapDepth) {
33
+ if (surfaceTypeMap[x][zBottom] !== BLOCK_TYPES.ASPHALT) surfaceTypeMap[x][zBottom] = BLOCK_TYPES.BRICK;
34
+ }
35
+ }
36
+ }
37
+
38
+ // líneas verticales (bordes izquierdo y derecho) en ladrillo
39
+ for (let j = 0; j < plotDepth; j++) {
40
+ const z = plotZ0 + j;
41
+ const xLeft = plotX0;
42
+ const xRight = plotX0 + plotWidth - 1;
43
+ if (z >= 0 && z < mapDepth) {
44
+ if (xLeft >= 0 && xLeft < mapWidth) {
45
+ if (surfaceTypeMap[xLeft][z] !== BLOCK_TYPES.ASPHALT) surfaceTypeMap[xLeft][z] = BLOCK_TYPES.BRICK;
46
+ }
47
+ if (xRight >= 0 && xRight < mapWidth) {
48
+ if (surfaceTypeMap[xRight][z] !== BLOCK_TYPES.ASPHALT) surfaceTypeMap[xRight][z] = BLOCK_TYPES.BRICK;
49
+ }
50
+ }
51
+ }
52
+
53
+ // generar conjunto de dormitorios según las reglas probabilísticas
54
+ // generate a simple identifier for this parcel so that structures
55
+ // spawned here can be distinguished from those in neighbouring lots.
56
+ const pid = `${plotX0}_${plotZ0}`;
57
+ generateParcelRooms(plotX0, plotZ0, plotWidth, plotDepth,
58
+ mapWidth, mapDepth, baseY, structures,
59
+ orientation, pid);
60
+ }
61
+
62
+
63
+ export { generateParcel };
@@ -0,0 +1,299 @@
1
+ // Utility helpers extracted from mapType3.js for reuse and cleaner code.
2
+ // These functions are intentionally kept "dumb" and receive all necessary
3
+ // parameters so they can be tested independently.
4
+
5
+ import { BLOCK_TYPES } from './mapConfig.js';
6
+
7
+ // pequeño helper usado en varias partes del módulo para saber si dos intervalos
8
+ // sobre un eje se solapan.
9
+ export function rangesOverlap(a0, a1, b0, b1) {
10
+ return a0 < b1 && b0 < a1;
11
+ }
12
+
13
+
14
+ /**
15
+ * ¿Dos estructuras están en la misma planta? Las casas de dos pisos repiten la
16
+ * misma huella en altura, así que todas las comprobaciones de adyacencia (que
17
+ * sólo miran X/Z) tienen que descartar antes las salas de otro nivel: dos
18
+ * cuartos superpuestos en el plano no comparten ninguna pared.
19
+ */
20
+ export function sameLevel(a, b) {
21
+ return a.y === b.y;
22
+ }
23
+
24
+ /**
25
+ * Devuelve el intervalo que una escalera prohíbe sobre el eje de una puerta, o
26
+ * null si esa pared no toca la escalera. `axis` es el eje a lo largo del cual
27
+ * corre la puerta ('x' para las paredes norte/sur, 'z' para este/oeste) y
28
+ * `wallCoord` la coordenada de la pared sobre el otro eje.
29
+ */
30
+ export function stairKeepOutRange(struct, axis, wallCoord) {
31
+ const ko = struct && struct.stairKeepOut;
32
+ if (!ko) return null;
33
+ if (axis === 'x') {
34
+ if (wallCoord < ko.z0 - 1 || wallCoord > ko.z1) return null;
35
+ return { start: ko.x0, end: ko.x1 };
36
+ }
37
+ if (wallCoord < ko.x0 - 1 || wallCoord > ko.x1) return null;
38
+ return { start: ko.z0, end: ko.z1 };
39
+ }
40
+
41
+ /**
42
+ * Calcula el tramo de puerta dentro del solape [o0,o1) de dos salas: deja un
43
+ * bloque de margen en cada extremo, descarta los intervalos de `keepOuts`
44
+ * (el hueco que ocupa una escalera) y centra la puerta en el trozo libre más
45
+ * ancho que queda. Devuelve {start,width} o null si no queda sitio.
46
+ *
47
+ * Sin keepOuts el resultado es el mismo que el cálculo que había repetido en
48
+ * cada función de conexión: doorWidth = min(4, solape - 2), centrado.
49
+ */
50
+ export function computeDoorSpan(o0, o1, keepOuts = [], maxWidth = 4) {
51
+ let segments = [{ start: o0 + 1, end: o1 - 1 }];
52
+ for (const ko of keepOuts) {
53
+ if (!ko) continue;
54
+ const rest = [];
55
+ for (const seg of segments) {
56
+ if (ko.end <= seg.start || ko.start >= seg.end) {
57
+ rest.push(seg);
58
+ continue;
59
+ }
60
+ if (ko.start > seg.start) rest.push({ start: seg.start, end: ko.start });
61
+ if (ko.end < seg.end) rest.push({ start: ko.end, end: seg.end });
62
+ }
63
+ segments = rest;
64
+ }
65
+ let best = null;
66
+ for (const seg of segments) {
67
+ if (seg.end - seg.start <= 0) continue;
68
+ if (!best || (seg.end - seg.start) > (best.end - best.start)) best = seg;
69
+ }
70
+ if (!best) return null;
71
+ const len = best.end - best.start;
72
+ const width = Math.min(maxWidth, len);
73
+ return { start: best.start + Math.floor((len - width) / 2), width };
74
+ }
75
+
76
+ /**
77
+ * Filter out structures that lie outside the terrain bounds.
78
+ */
79
+ export function filterStructuresInBounds(structures, width, depth) {
80
+ return structures.filter(s => {
81
+ if (s == null) return false;
82
+ const sx = s.x || 0;
83
+ const sz = s.z || 0;
84
+ const sw = s.width || 0;
85
+ const sd = s.depth || 0;
86
+ return sx >= 0 && sz >= 0 && sx + sw <= width && sz + sd <= depth;
87
+ });
88
+ }
89
+
90
+ /**
91
+ * Remove any window ranges that point to structures in other parcels.
92
+ */
93
+ export function cleanWindows(structures) {
94
+ structures.forEach(s => {
95
+ ['North','South','West','East'].forEach(dir => {
96
+ const rangeKey = 'window' + dir + 'Range';
97
+ if (!s[rangeKey]) return;
98
+ const hx = s.x, hz = s.z, hw = s.width, hd = s.depth;
99
+ const neighbor = structures.find(t => {
100
+ if (t === s) return false;
101
+ if (t.parcelId === s.parcelId) return false;
102
+ if (!sameLevel(s, t)) return false;
103
+ if (dir === 'North') return t.z + t.depth === hz && rangesOverlap(s.x, s.x + hw, t.x, t.x + t.width);
104
+ if (dir === 'South') return s.z + hd === t.z && rangesOverlap(s.x, s.x + hw, t.x, t.x + t.width);
105
+ if (dir === 'West') return t.x + t.width === hx && rangesOverlap(s.z, s.z + hd, t.z, t.z + t.depth);
106
+ if (dir === 'East') return s.x + hw === t.x && rangesOverlap(s.z, s.z + hd, t.z, t.z + t.depth);
107
+ });
108
+ if (neighbor) delete s[rangeKey];
109
+ });
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Carve doors/air rectangles between adjacent structures and ensure
115
+ * floor texture is painted across the entire opening.
116
+ */
117
+ export function carveInteriorConnections(volume, structures, width, depth, volumeHeight, enableInteriorConnections) {
118
+ const needInteriorCarving = enableInteriorConnections ||
119
+ structures.some(s => s.openNorth || s.openSouth || s.openEast || s.openWest);
120
+ if (!needInteriorCarving) return;
121
+
122
+ const carveRect = (startX, endX, startZ, endZ, hy, s, t) => {
123
+ const doorHeightStart = hy + 1;
124
+ const doorHeightEnd = hy + 6;
125
+ for (let y = doorHeightStart; y < doorHeightEnd; y++) {
126
+ for (let xx = startX; xx < endX; xx++) {
127
+ for (let zz = startZ; zz < endZ; zz++) {
128
+ if (xx < 0 || xx >= width || y < 0 || y >= volumeHeight || zz < 0 || zz >= depth) continue;
129
+ volume.set(xx, y, zz, BLOCK_TYPES.AIR);
130
+ }
131
+ }
132
+ }
133
+ for (let xx = startX; xx < endX; xx++) {
134
+ for (let zz = startZ; zz < endZ; zz++) {
135
+ if (xx < 0 || xx >= width || hy < 0 || hy >= volumeHeight || zz < 0 || zz >= depth) continue;
136
+ const sFloor = (s.floorTexture !== undefined) ? s.floorTexture : BLOCK_TYPES.GRAY;
137
+ const tFloor = (t.floorTexture !== undefined) ? t.floorTexture : BLOCK_TYPES.GRAY;
138
+ const otherFloor = (s.y <= t.y) ? sFloor : tFloor;
139
+ volume.set(xx, hy, zz, otherFloor);
140
+ }
141
+ }
142
+ };
143
+
144
+ const hasDoorBetween = (a, b) => {
145
+ if (a.parcelId && b.parcelId && a.parcelId !== b.parcelId) return false;
146
+ if (!sameLevel(a, b)) return false;
147
+ if (a.openNorth && b.openSouth) return true;
148
+ if (a.openSouth && b.openNorth) return true;
149
+ if (a.openEast && b.openWest) return true;
150
+ if (a.openWest && b.openEast) return true;
151
+ return false;
152
+ };
153
+
154
+ for (let i = 0; i < structures.length; i++) {
155
+ const s = structures[i];
156
+ if (s.type === 'spawn') continue;
157
+ for (let j = i + 1; j < structures.length; j++) {
158
+ const t = structures[j];
159
+ if (t.type === 'spawn') continue;
160
+
161
+ const tryCarve = () => {
162
+ const sx0 = s.x, sx1 = s.x + s.width;
163
+ const sz0 = s.z, sz1 = s.z + s.depth;
164
+ const tx0 = t.x, tx1 = t.x + t.width;
165
+ const tz0 = t.z, tz1 = t.z + t.depth;
166
+ const hy = Math.min(s.y, t.y);
167
+
168
+ // vertical wall
169
+ if (sx1 === tx0 || tx1 === sx0) {
170
+ const overlapZ0 = Math.max(sz0, tz0);
171
+ const overlapZ1 = Math.min(sz1, tz1);
172
+ const door = computeDoorSpan(overlapZ0, overlapZ1, [
173
+ stairKeepOutRange(s, 'z', (sx1 === tx0) ? sx1 - 1 : sx0),
174
+ stairKeepOutRange(t, 'z', (sx1 === tx0) ? tx0 : tx1 - 1)
175
+ ]);
176
+ if (door) {
177
+ const doorWidth = door.width;
178
+ const doorZStart = door.start;
179
+ const wallX1 = (sx1 === tx0) ? sx1 - 1 : tx1 - 1;
180
+ const wallX2 = (sx1 === tx0) ? tx0 : sx0;
181
+ const startX = Math.min(wallX1, wallX2);
182
+ const endX = Math.max(wallX1, wallX2) + 1;
183
+ carveRect(startX, endX, doorZStart, doorZStart + doorWidth, hy, s, t);
184
+ if (sx1 === tx0) {
185
+ s.openEast = true;
186
+ s.openEastRange = { start: doorZStart, end: doorZStart + doorWidth };
187
+ t.openWest = true;
188
+ t.openWestRange = { start: doorZStart, end: doorZStart + doorWidth };
189
+ } else {
190
+ t.openEast = true;
191
+ t.openEastRange = { start: doorZStart, end: doorZStart + doorWidth };
192
+ s.openWest = true;
193
+ s.openWestRange = { start: doorZStart, end: doorZStart + doorWidth };
194
+ }
195
+ }
196
+ }
197
+ // horizontal wall
198
+ if (sz1 === tz0 || tz1 === sz0) {
199
+ const overlapX0 = Math.max(sx0, tx0);
200
+ const overlapX1 = Math.min(sx1, tx1);
201
+ const door = computeDoorSpan(overlapX0, overlapX1, [
202
+ stairKeepOutRange(s, 'x', (sz1 === tz0) ? sz1 - 1 : sz0),
203
+ stairKeepOutRange(t, 'x', (sz1 === tz0) ? tz0 : tz1 - 1)
204
+ ]);
205
+ if (door) {
206
+ const doorWidth = door.width;
207
+ const doorXStart = door.start;
208
+ const wallZ1 = (sz1 === tz0) ? sz1 - 1 : tz1 - 1;
209
+ const wallZ2 = (sz1 === tz0) ? tz0 : sz0;
210
+ const startZ = Math.min(wallZ1, wallZ2);
211
+ const endZ = Math.max(wallZ1, wallZ2) + 1;
212
+ carveRect(doorXStart, doorXStart + doorWidth, startZ, endZ, hy, s, t);
213
+ if (sz1 === tz0) {
214
+ s.openSouth = true;
215
+ s.openSouthRange = { start: doorXStart, end: doorXStart + doorWidth };
216
+ t.openNorth = true;
217
+ t.openNorthRange = { start: doorXStart, end: doorXStart + doorWidth };
218
+ } else {
219
+ t.openSouth = true;
220
+ t.openSouthRange = { start: doorXStart, end: doorXStart + doorWidth };
221
+ s.openNorth = true;
222
+ s.openNorthRange = { start: doorXStart, end: doorXStart + doorWidth };
223
+ }
224
+ }
225
+ }
226
+ };
227
+
228
+ if (s.type === 'hallway' || t.type === 'hallway') {
229
+ if (hasDoorBetween(s, t)) tryCarve();
230
+ continue;
231
+ }
232
+ if (!sameLevel(s, t)) continue;
233
+ const combo = [s.type, t.type].sort().join('|');
234
+ if (combo === 'cocina|comedor' || combo === 'comedor|living' || combo === 'cocina|living') {
235
+ tryCarve();
236
+ }
237
+ }
238
+ }
239
+ }
240
+
241
+ /**
242
+ * After structures are drawn, perform final surface and floor adjustments
243
+ * (hallway floors and house footprints).
244
+ */
245
+ export function finalizeVolume(volume, surfaceTypeMap, structures, width, depth, volumeHeight) {
246
+ for (const s of structures) {
247
+ if (s.type === 'hallway') {
248
+ for (let x = s.x; x < s.x + s.width; x++) {
249
+ for (let z = s.z; z < s.z + s.depth; z++) {
250
+ if (x >= 0 && x < width && z >= 0 && z < depth) {
251
+ if (surfaceTypeMap[x] && surfaceTypeMap[x][z] !== BLOCK_TYPES.ASPHALT) {
252
+ surfaceTypeMap[x][z] = BLOCK_TYPES.WHITE;
253
+ }
254
+ }
255
+ }
256
+ }
257
+ }
258
+ }
259
+ const houseFootprints = {};
260
+ structures.forEach(s => {
261
+ if (s.houseOriginX === undefined) return;
262
+ const key = `${s.houseOriginX},${s.houseOriginZ}`;
263
+ if (!houseFootprints[key]) {
264
+ houseFootprints[key] = {minX: Infinity, maxX: -Infinity, minZ: Infinity, maxZ: -Infinity, y: s.houseY || 0};
265
+ }
266
+ const fb = houseFootprints[key];
267
+ fb.minX = Math.min(fb.minX, s.x);
268
+ fb.maxX = Math.max(fb.maxX, s.x + s.width);
269
+ fb.minZ = Math.min(fb.minZ, s.z);
270
+ fb.maxZ = Math.max(fb.maxZ, s.z + s.depth);
271
+ if (s.houseY !== undefined) fb.y = s.houseY;
272
+ });
273
+ Object.values(houseFootprints).forEach(fb => {
274
+ fb.x = fb.minX;
275
+ fb.z = fb.minZ;
276
+ fb.width = Math.max(0, fb.maxX - fb.minX);
277
+ fb.depth = Math.max(0, fb.maxZ - fb.minZ);
278
+ });
279
+ for (const h of Object.values(houseFootprints)) {
280
+ const floorY = h.y;
281
+ for (let x = h.x; x < h.x + h.width; x++) {
282
+ for (let z = h.z; z < h.z + h.depth; z++) {
283
+ if (x < 0 || x >= width || z < 0 || z >= depth) continue;
284
+ if (floorY < 0 || floorY >= volumeHeight) continue;
285
+ let floorCell = volume.get(x, floorY, z);
286
+ const isAir = (floorCell === BLOCK_TYPES.AIR) || (floorCell && typeof floorCell === 'object' && floorCell.type === BLOCK_TYPES.AIR);
287
+ if (isAir) {
288
+ volume.set(x, floorY, z, BLOCK_TYPES.GRAY);
289
+ }
290
+ if (surfaceTypeMap[x] && surfaceTypeMap[x][z] === BLOCK_TYPES.GREEN) {
291
+ surfaceTypeMap[x][z] = BLOCK_TYPES.GRAY;
292
+ }
293
+ }
294
+ }
295
+ }
296
+ }
297
+
298
+
299
+ // generateMapType3 removed; implementation lives in mapType3.js now
@@ -0,0 +1,210 @@
1
+ /**
2
+ * VolumeBuffer — almacenamiento eficiente de volumen 3D de bloques.
3
+ *
4
+ * Internamente usa UNA sola asignación plana (no un array denso de
5
+ * width*height*depth, ni un objeto por columna) repartida por columna (x,z)
6
+ * según `colHeights`: la altura que esa columna necesita en la práctica
7
+ * (suelo + el edificio más alto que la cubra), calculada de antemano por
8
+ * quien genera el mapa a partir de `heightMap`/`structures` (ver
9
+ * `computeColumnHeights` más abajo y su uso en mapType3.js).
10
+ *
11
+ * La mayoría de las columnas son calle/vereda y sólo necesitan una fracción
12
+ * de `height` (volumeHeight); sólo las que tienen un edificio encima reservan
13
+ * hasta su altura real. Como es UN array (con offsets precalculados, estilo
14
+ * CSR) y no uno por columna, no paga el overhead por objeto de tener
15
+ * millones de TypedArrays sueltos.
16
+ *
17
+ * Si algún escritor pide una celda por encima de lo previsto (un caso no
18
+ * cubierto por `computeColumnHeights`), no se pierde ni se corta: cae a un
19
+ * `Map` de desborde disperso, así que el peor caso es "un poco menos
20
+ * compacto", nunca datos perdidos o corrompidos.
21
+ *
22
+ * - Un Map disperso para tintes (solo almacena celdas que los tienen), con
23
+ * las combinaciones de color en una paleta compartida (ver `paleta`).
24
+ *
25
+ * BLOCK_TYPES.AIR = 0: una celda sin escribir (dentro o fuera del rango
26
+ * reservado) se lee como aire.
27
+ */
28
+ export class VolumeBuffer {
29
+ /**
30
+ * @param {Uint16Array|number[]} colHeights - alto a reservar por columna
31
+ * (x*depth+z), calculado por `computeColumnHeights`.
32
+ */
33
+ constructor(width, height, depth, colHeights) {
34
+ this.width = width;
35
+ this.height = height; // volumeHeight: tope teórico, no lo que reserva cada columna
36
+ this.depth = depth;
37
+
38
+ const numCols = width * depth;
39
+ this.colHeights = colHeights || new Uint16Array(numCols).fill(height);
40
+
41
+ // offsets estilo CSR: colOffset[ci] = inicio de la columna ci en `data`.
42
+ this.colOffset = new Uint32Array(numCols + 1);
43
+ let total = 0;
44
+ for (let ci = 0; ci < numCols; ci++) {
45
+ this.colOffset[ci] = total;
46
+ total += this.colHeights[ci];
47
+ }
48
+ this.colOffset[numCols] = total;
49
+ this.data = new Uint8Array(total);
50
+
51
+ // Red de seguridad: celdas con y >= colHeights[ci] que alguna parte
52
+ // del generador necesite escribir igual (no debería pasar si
53
+ // `computeColumnHeights` está bien calculado, pero así no se pierden).
54
+ this.overflow = new Map(); // Map<flatIndex, type>
55
+
56
+ // Tintes: Map<flatIndex, id de paleta>. Antes cada celda tintada
57
+ // guardaba su propio objeto `{ tintMinimap: {...}, tintRender: {...} }`
58
+ // (3 objetos de heap por celda, y un mapa tiene ~550 mil): como las
59
+ // combinaciones distintas son unas pocas decenas, se guarda una sola
60
+ // vez cada una en `paleta` y la celda sólo lleva su número.
61
+ this.tints = new Map();
62
+ this.paleta = [null]; // id -> { tintMinimap?, tintRender? } (inmutable)
63
+ this._idPorClave = new Map(); // "color|opacidad|color|opacidad" -> id
64
+ }
65
+
66
+ /** Id de paleta de la combinación (minimapa, render); la crea si no existe. */
67
+ _idTinte(tintMinimap, tintRender) {
68
+ const clave = (tintMinimap ? tintMinimap.color + '|' + tintMinimap.opacity : '|') + '|' +
69
+ (tintRender ? tintRender.color + '|' + tintRender.opacity : '|');
70
+ let id = this._idPorClave.get(clave);
71
+ if (id === undefined) {
72
+ const entrada = {};
73
+ if (tintMinimap) entrada.tintMinimap = { color: tintMinimap.color, opacity: tintMinimap.opacity };
74
+ if (tintRender) entrada.tintRender = { color: tintRender.color, opacity: tintRender.opacity };
75
+ id = this.paleta.length;
76
+ this.paleta.push(entrada);
77
+ this._idPorClave.set(clave, id);
78
+ }
79
+ return id;
80
+ }
81
+
82
+ /** Índice de columna para (x, z). */
83
+ _colIdx(x, z) {
84
+ return x * this.depth + z;
85
+ }
86
+
87
+ /** Índice plano "lógico" para la posición (x, y, z) — clave de `tints`/`overflow`. */
88
+ _idx(x, y, z) {
89
+ return x * this.height * this.depth + y * this.depth + z;
90
+ }
91
+
92
+ get(x, y, z) {
93
+ const type = this.getType(x, y, z);
94
+ const id = this.tints.get(this._idx(x, y, z));
95
+ return id ? { type, ...this.paleta[id] } : type;
96
+ }
97
+
98
+ /** Devuelve solo el tipo numérico (más rápido que get cuando no se necesita el tinte). */
99
+ getType(x, y, z) {
100
+ const ci = this._colIdx(x, z);
101
+ if (y < this.colHeights[ci]) {
102
+ return this.data[this.colOffset[ci] + y];
103
+ }
104
+ if (this.overflow.size === 0) return 0;
105
+ const v = this.overflow.get(this._idx(x, y, z));
106
+ return v == null ? 0 : v;
107
+ }
108
+
109
+ /**
110
+ * Almacena un valor de celda.
111
+ * - Si val es un número: guarda el tipo, borra cualquier tinte existente.
112
+ * - Si val es un objeto {type, tintMinimap?, tintRender?, tint?}: separa
113
+ * el tipo y los tintes; el campo legacy `tint` se trata como tintMinimap.
114
+ * - null/undefined → AIR (0).
115
+ */
116
+ set(x, y, z, val) {
117
+ let type, idTinte = 0;
118
+ if (val && typeof val === 'object') {
119
+ type = val.type || 0;
120
+ const tintMinimap = val.tintMinimap || val.tint || null; // `tint`: campo legacy
121
+ const tintRender = val.tintRender || null;
122
+ if (tintMinimap || tintRender) idTinte = this._idTinte(tintMinimap, tintRender);
123
+ } else {
124
+ type = (val == null ? 0 : val);
125
+ }
126
+
127
+ const idx = this._idx(x, y, z);
128
+ const ci = this._colIdx(x, z);
129
+
130
+ if (y < this.colHeights[ci]) {
131
+ this.data[this.colOffset[ci] + y] = type;
132
+ } else {
133
+ // fuera del rango previsto para esta columna: red de seguridad.
134
+ if (type === 0) this.overflow.delete(idx);
135
+ else this.overflow.set(idx, type);
136
+ }
137
+
138
+ if (idTinte) this.tints.set(idx, idTinte);
139
+ else this.tints.delete(idx);
140
+ }
141
+
142
+ /** Añade o actualiza el tinte de minimapa de una celda sin tocar el tipo. */
143
+ setTintMinimap(x, y, z, color, opacity) {
144
+ const idx = this._idx(x, y, z);
145
+ const previo = this.paleta[this.tints.get(idx) || 0];
146
+ this.tints.set(idx, this._idTinte({ color, opacity }, previo ? previo.tintRender : null));
147
+ }
148
+
149
+ /** Añade o actualiza el tinte de render de una celda sin tocar el tipo. */
150
+ setTintRender(x, y, z, color, opacity) {
151
+ const idx = this._idx(x, y, z);
152
+ const previo = this.paleta[this.tints.get(idx) || 0];
153
+ this.tints.set(idx, this._idTinte(previo ? previo.tintMinimap : null, { color, opacity }));
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Calcula, para cada columna (x,z), la altura real que necesita reservar:
159
+ * el nivel de suelo (heightMap) más la del edificio más alto (si hay alguno)
160
+ * que la cubra, con un margen chico para antepechos de techo (ver
161
+ * `buildRoofParapets` en generadorCasaPisos.js, que escribe un bloque por
162
+ * encima de `s.y + s.height`).
163
+ *
164
+ * No hace falta que sea exacto: cualquier escritura que se escape de este
165
+ * cálculo cae al `overflow` de VolumeBuffer en vez de perderse.
166
+ */
167
+ export function computeColumnHeights(width, depth, volumeHeight, heightMap, room, structures) {
168
+ const colHeights = new Uint16Array(width * depth);
169
+
170
+ for (let x = 0; x < width; x++) {
171
+ const row = heightMap[x];
172
+ if (!row) continue;
173
+ const base = x * depth;
174
+ for (let z = 0; z < depth; z++) {
175
+ const h = row[z];
176
+ if (typeof h === 'number' && h > colHeights[base + z]) colHeights[base + z] = h;
177
+ }
178
+ }
179
+
180
+ const ROOF_MARGIN = 9; // antepecho, casilla de escalera o tanque de agua (ver buildRoofExtras) + margen
181
+
182
+ const markBox = (hx, hz, hw, hd, topY) => {
183
+ const top = Math.min(volumeHeight, topY);
184
+ const x0 = Math.max(0, hx), x1 = Math.min(width, hx + hw);
185
+ const z0 = Math.max(0, hz), z1 = Math.min(depth, hz + hd);
186
+ for (let x = x0; x < x1; x++) {
187
+ const base = x * depth;
188
+ for (let z = z0; z < z1; z++) {
189
+ if (top > colHeights[base + z]) colHeights[base + z] = top;
190
+ }
191
+ }
192
+ };
193
+
194
+ if (room) {
195
+ markBox(room.x, room.z, room.width, room.depth, room.y + room.height + ROOF_MARGIN);
196
+ }
197
+
198
+ if (structures && structures.length) {
199
+ for (const s of structures) {
200
+ if (!s || s.type === 'spawn' || s.width == null || s.height == null || s.depth == null) continue;
201
+ markBox(s.x, s.z, s.width, s.depth, s.y + s.height + ROOF_MARGIN);
202
+ }
203
+ }
204
+
205
+ for (let i = 0; i < colHeights.length; i++) {
206
+ if (colHeights[i] > volumeHeight) colHeights[i] = volumeHeight;
207
+ }
208
+
209
+ return colHeights;
210
+ }
package/src/index.js ADDED
@@ -0,0 +1,23 @@
1
+ // index.js - API pública de @greenborn/mapa-voxel-back.
2
+ //
3
+ // Uso típico (en el worker o en el hilo principal del servidor):
4
+ //
5
+ // import { configurarMundo, registrarPlugins, construirMapa, buffersTransferibles }
6
+ // from '@greenborn/mapa-voxel-back';
7
+ //
8
+ // configurarMundo({ factorSuperficie: 1, directorioMinimapas: './maps' });
9
+ // registrarPlugins({ arboles: {...}, autos: {...}, /* ...ESQUEMA_PLUGINS */ });
10
+ // const mapa = construirMapa({ modo: 'zombies' });
11
+ //
12
+ // Los tipos de bloque y las constantes del mundo son parte del paquete;
13
+ // los datos de juego entran por plugins.
14
+
15
+ export { construirMapa, buffersTransferibles } from './generador/construirMapa.js';
16
+ export { configurarMundo, getFactorSuperficie, WORLD_CONFIG, TERRAIN_CONFIG, CONFIG_GENERATION,
17
+ BLOCK_TYPES, BLOCK_PROPERTIES, isTintableMinimap, isTintableRender, isTransparent,
18
+ tintBlock, tintBlockMinimap, tintBlockRender } from './generador/mapConfig.js';
19
+ export { registrarPlugins, pluginsFaltantes, pluginsRegistrados } from './plugins/registro.js';
20
+ export { ESQUEMA_PLUGINS } from './plugins/datos.js';
21
+ export { VolumeBuffer, computeColumnHeights } from './generador/volumeBuffer.js';
22
+ export { generateMapType3, generateVolumeType3 } from './generador/mapType3.js';
23
+ export * as chunkCompacto from './formato/chunk_compacto.js';