@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,470 @@
1
+ import { BLOCK_TYPES, WORLD_CONFIG, isTintableRender } from '../mapConfig.js';
2
+ import { placeRooms } from './ubicacionSalaCasa.js';
3
+ import { addWindows } from './generadorCasaVentanas.js';
4
+ import {
5
+ connectRooms,
6
+ connectSpecialRoomsToHallways,
7
+ connectBathrooms,
8
+ connectBedrooms,
9
+ connectBackyardDoor
10
+ } from './generadorCasaConexiones.js';
11
+ import {
12
+ pickFloorCount,
13
+ maxFloorsFitting,
14
+ floorRise,
15
+ stairWidth,
16
+ planStairs,
17
+ planStairwell,
18
+ applyStairPlan,
19
+ clearStairPlan,
20
+ hasDoor,
21
+ buildUpperFloor,
22
+ removeFloor,
23
+ planRoofExtras,
24
+ pickLootRooms,
25
+ pickLootSpot,
26
+ pickArmario
27
+ } from './generadorCasaPisos.js';
28
+
29
+ // re-export moved helpers for external consumers
30
+ export {
31
+ connectRooms,
32
+ connectSpecialRoomsToHallways,
33
+ connectBathrooms,
34
+ connectBedrooms,
35
+ connectBackyardDoor
36
+ };
37
+
38
+ // definiciones base de cada tipo de habitación. El resto del código usa estos
39
+ // valores para conocer dimensiones y texturas.
40
+ // distribution of wall materials for houses.
41
+ // each element has a weight (fraction of total) and the corresponding block type.
42
+ // originally there were only two options (brick + white). a second brick
43
+ // variant ('brick_2') was added so that the server can reference it as a
44
+ // separate block type and make the client pick from an array of textures.
45
+ // the weights still sum to 1.0.
46
+ export const WALL_MATERIAL_DISTRIBUTION = [
47
+ { weight: 0.15, texture: BLOCK_TYPES.BRICK },
48
+ { weight: 0.15, texture: BLOCK_TYPES.BRICK_2 },
49
+ { weight: 0.15, texture: BLOCK_TYPES.BRICK_3 },
50
+ { weight: 0.55, texture: BLOCK_TYPES.WHITE }
51
+ ];
52
+
53
+ // distribución de texturas para el piso; por ahora alterna entre gris y
54
+ // madera clara. Las probabilidades pueden ajustarse más adelante a otra
55
+ // mezcla si se desea madera menos frecuente.
56
+ export const FLOOR_MATERIAL_DISTRIBUTION = [
57
+ { weight: 0.25, texture: BLOCK_TYPES.GRAY },
58
+ { weight: 0.25, texture: BLOCK_TYPES.WOOD_1 },
59
+ { weight: 0.25, texture: BLOCK_TYPES.BALDOSAS_1 },
60
+ { weight: 0.25, texture: BLOCK_TYPES.BALDOSAS_2 }
61
+ ];
62
+
63
+ // ten beige tint variants – each entry includes a probability weight and a
64
+ // 24‑bit color value. The weights should sum roughly to 1 but need not be
65
+ // exact; the selection function normalizes them internally.
66
+ export const BEIGE_TINT_DISTRIBUTION = [
67
+ { weight: 0.10, color: 0xFFFFFF },
68
+ { weight: 0.10, color: 0xFF0000 },
69
+ { weight: 0.10, color: 0x00FF00 },
70
+ { weight: 0.10, color: 0xFF00FF },
71
+ { weight: 0.10, color: 0xFFFF00 },
72
+ { weight: 0.10, color: 0x00FFFF },
73
+ { weight: 0.10, color: 0x0000FF }
74
+ ];
75
+
76
+ // pick a color from a weighted distribution array of {weight,color} objects
77
+ export function chooseBeigeColor(distribution) {
78
+ const r = Math.random();
79
+ let cum = 0;
80
+ for (const opt of distribution) {
81
+ cum += opt.weight;
82
+ if (r < cum) return opt.color;
83
+ }
84
+ return distribution[distribution.length - 1].color;
85
+ }
86
+
87
+ // pick a texture from a weighted distribution array of {weight,texture} objects
88
+ export function chooseWallTexture(distribution) {
89
+ const r = Math.random();
90
+ let cum = 0;
91
+ for (const opt of distribution) {
92
+ cum += opt.weight;
93
+ if (r < cum) return opt.texture;
94
+ }
95
+ // fallback to last entry in case of rounding issues
96
+ return distribution[distribution.length - 1].texture;
97
+ }
98
+
99
+ // for now floor selection uses the same logic as walls; kept as separate
100
+ // function in case behaviour diverges later
101
+ export const chooseFloorTexture = chooseWallTexture;
102
+
103
+ export const ROOM_CONFIGS = {
104
+ banio: {
105
+ type: 'banio', width: 10, depth: 15, height: 9,
106
+ floorTexture: BLOCK_TYPES.GRAY,
107
+ ceilingTexture: BLOCK_TYPES.WHITE,
108
+ wallTexture: BLOCK_TYPES.BRICK,
109
+ // this colour is only used on the minimap (and when N toggle is on)
110
+ tintMinimap: 0xADD8E6,
111
+ tintMinimapOpacity: 0.7
112
+ },
113
+ cocina: {
114
+ type: 'cocina', width: 10, depth: 15, height: 9,
115
+ floorTexture: BLOCK_TYPES.GRAY,
116
+ ceilingTexture: BLOCK_TYPES.WHITE,
117
+ wallTexture: BLOCK_TYPES.BRICK,
118
+ tintMinimap: 0xFFFF00,
119
+ tintMinimapOpacity: 0.7
120
+ },
121
+ comedor: {
122
+ type: 'comedor', width: 15, depth: 15, height: 9,
123
+ floorTexture: BLOCK_TYPES.GRAY,
124
+ ceilingTexture: BLOCK_TYPES.WHITE,
125
+ wallTexture: BLOCK_TYPES.BRICK,
126
+ tintMinimap: 0xFFA500,
127
+ tintMinimapOpacity: 0.7
128
+ },
129
+ dormitorio: {
130
+ type: 'dormitorio', width: 15, depth: 15, height: 9,
131
+ floorTexture: BLOCK_TYPES.GRAY,
132
+ ceilingTexture: BLOCK_TYPES.WHITE,
133
+ wallTexture: BLOCK_TYPES.BRICK,
134
+ tintMinimap: 0x00FF00,
135
+ tintMinimapOpacity: 0.7
136
+ },
137
+ living: {
138
+ type: 'living', width: 15, depth: 15, height: 9,
139
+ floorTexture: BLOCK_TYPES.GRAY,
140
+ ceilingTexture: BLOCK_TYPES.WHITE,
141
+ wallTexture: BLOCK_TYPES.BRICK,
142
+ tintMinimap: 0xEE82EE,
143
+ tintMinimapOpacity: 0.7
144
+ },
145
+ hallway: {
146
+ type: 'hallway', width: 6, depth: 6, height: 9,
147
+ floorTexture: BLOCK_TYPES.GRAY,
148
+ ceilingTexture: BLOCK_TYPES.WHITE,
149
+ wallTexture: BLOCK_TYPES.BRICK,
150
+ tintMinimap: 0xCCCCCC,
151
+ tintMinimapOpacity: 0.5
152
+ },
153
+ // caja de escalera: la llevan sólo las casas de dos o más plantas. Tiene
154
+ // que entrar un tramo (`rise` escalones más los dos descansos) a lo largo
155
+ // y los dos tramos de la ida y vuelta a lo ancho; ver planStairwell en
156
+ // generadorCasaPisos.js.
157
+ escalera: {
158
+ type: 'escalera', width: 14, depth: 10, height: 9,
159
+ floorTexture: BLOCK_TYPES.GRAY,
160
+ ceilingTexture: BLOCK_TYPES.WHITE,
161
+ wallTexture: BLOCK_TYPES.BRICK,
162
+ tintMinimap: 0x9370DB,
163
+ tintMinimapOpacity: 0.7
164
+ }
165
+ };
166
+
167
+ // helper que empaqueta una sala en el arreglo de estructuras.
168
+ export function createRoom(x0, y0, z0, cfg, structures) {
169
+ const {
170
+ type,
171
+ width,
172
+ depth,
173
+ height,
174
+ floorTexture,
175
+ ceilingTexture,
176
+ wallTexture,
177
+ frontNorth,
178
+ frontSouth,
179
+ frontEast,
180
+ frontWest,
181
+ hasFrontDoor,
182
+ // render tint (rarely used; leaves material colour as default if
183
+ // undefined)
184
+ tintRender,
185
+ tintOpacity,
186
+ // minimap-only tint
187
+ tintMinimap,
188
+ tintMinimapOpacity,
189
+ parcelId
190
+ } = cfg;
191
+ const roomStruct = {
192
+ type: type || 'room',
193
+ x: x0,
194
+ y: y0,
195
+ z: z0,
196
+ width,
197
+ depth,
198
+ height,
199
+ floorTexture,
200
+ ceilingTexture,
201
+ wallTexture,
202
+ // planta a la que pertenece la sala: 0 es la que se apoya en el
203
+ // terreno, 1 la que generadorCasaPisos levanta sobre su techo.
204
+ floor: cfg.floor || 0
205
+ };
206
+ if (frontNorth) roomStruct.frontNorth = true;
207
+ if (frontSouth) roomStruct.frontSouth = true;
208
+ if (frontEast) roomStruct.frontEast = true;
209
+ if (frontWest) roomStruct.frontWest = true;
210
+ if (hasFrontDoor) roomStruct.hasFrontDoor = true;
211
+ if (typeof tintRender !== 'undefined') roomStruct.tintRender = tintRender;
212
+ if (typeof tintOpacity !== 'undefined') roomStruct.tintOpacity = tintOpacity;
213
+ if (typeof tintMinimap !== 'undefined') roomStruct.tintMinimap = tintMinimap;
214
+ if (typeof tintMinimapOpacity !== 'undefined') roomStruct.tintMinimapOpacity = tintMinimapOpacity;
215
+ if (typeof parcelId !== 'undefined') roomStruct.parcelId = parcelId;
216
+ structures.push(roomStruct);
217
+ }
218
+
219
+ // -------------------------------------------------------------------------
220
+ // funciones exportadas solicitadas por el refactor
221
+ // -------------------------------------------------------------------------
222
+
223
+ /**
224
+ * Devuelve un arreglo (lista) de nombres de sala que compondrán la casa.
225
+ * La primera entrada está reservada para la sala que llevará la puerta.
226
+ *
227
+ * `withStairwell` agrega la caja de escalera, que llevan las casas de dos o
228
+ * más plantas. Va al final de la lista para que nunca sea la sala de entrada:
229
+ * el reordenamiento de abajo siempre pone adelante living, comedor o cocina.
230
+ */
231
+ export function chooseRoomTypes(withStairwell = false) {
232
+ const types = ['banio', 'cocina', 'dormitorio'];
233
+ if (Math.random() < 0.25) types.push('banio');
234
+ if (Math.random() < 0.5) types.push('living');
235
+ if (Math.random() < 0.5) types.push('dormitorio');
236
+ if (Math.random() < 0.25) types.push('dormitorio');
237
+ if (Math.random() < 0.55) types.push('comedor');
238
+
239
+ if (types.includes('cocina') && types.includes('comedor')) {
240
+ types.splice(types.indexOf('cocina'), 1);
241
+ types.splice(types.indexOf('comedor'), 1);
242
+ types.unshift('comedor', 'cocina');
243
+ }
244
+ if (types.includes('living') && types.includes('dormitorio')) {
245
+ const filtered = types.filter(t => t !== 'living' && t !== 'dormitorio');
246
+ types.length = 0;
247
+ types.push('living', 'dormitorio', ...filtered);
248
+ }
249
+ let entrance = null;
250
+ if (types.includes('living')) entrance = 'living';
251
+ else if (types.includes('comedor')) entrance = 'comedor';
252
+ else if (types.includes('cocina')) entrance = 'cocina';
253
+ if (entrance) {
254
+ const idx = types.indexOf(entrance);
255
+ if (idx > 0) {
256
+ types.splice(idx, 1);
257
+ types.unshift(entrance);
258
+ }
259
+ }
260
+ // la caja de escalera va al final: ya está resuelta la sala de entrada
261
+ if (withStairwell) types.push('escalera');
262
+ return types;
263
+ }
264
+
265
+ /**
266
+ * Calcula el frente principal de una parcela dado su índice (`px`,`pz`) y
267
+ * el número de parcelas en cada dirección (`plotsX`,`plotsZ`).
268
+ * Devuelve 'N','S','E' u 'O' o `null` si no toca ningún borde.
269
+ */
270
+ export function determineFront(px, pz, plotsX, plotsZ) {
271
+ const candidates = [];
272
+ if (pz === 0) candidates.push('N');
273
+ if (pz === plotsZ - 1) candidates.push('S');
274
+ if (px === 0) candidates.push('O');
275
+ if (px === plotsX - 1) candidates.push('E');
276
+ if (candidates.length === 0) return null;
277
+ return candidates[Math.floor(Math.random() * candidates.length)];
278
+ }
279
+
280
+ /**
281
+ * Tramo de escalera de una planta. Si la casa tiene caja de escalera el tramo
282
+ * va siempre en ella —uno por planta, apilados, como en un edificio—. Si no la
283
+ * tiene (no entró en la parcela) se busca sitio dentro de alguna sala, que es
284
+ * cómo se resolvía antes de haber caja.
285
+ */
286
+ function planFloorStairs(rooms, rise, stairW, level) {
287
+ const caja = rooms.find(r => r.type === 'escalera');
288
+ return (caja ? planStairwell(caja, rise, level) : null)
289
+ || planStairs(rooms, rise, stairW, level);
290
+ }
291
+
292
+ /**
293
+ * Toma una parcela y un frente ya resuelto y construye las salas dentro del
294
+ * terreno. Recibe el arreglo `structures` donde añadirá los objetos resultantes.
295
+ */
296
+ export function generateParcelRooms(plotX0, plotZ0, plotWidth, plotDepth,
297
+ mapWidth, mapDepth, baseY, structures,
298
+ orientation, parcelId) {
299
+ // log each house/parcel as it is added for server-side debugging
300
+ console.log(`Generando casa en parcela ${parcelId} (${plotX0},${plotZ0}) orientacion=${orientation}`);
301
+
302
+ // choose predominant wall texture using the distribution array
303
+ const houseWallTexture = chooseWallTexture(WALL_MATERIAL_DISTRIBUTION);
304
+ // choose floor texture (GRAY or WOOD_1 for now)
305
+ const houseFloorTexture = chooseFloorTexture(FLOOR_MATERIAL_DISTRIBUTION);
306
+
307
+ // log textures for debugging
308
+ console.log(` pared principal: ${houseWallTexture}`);
309
+ console.log(` piso seleccionado : ${houseFloorTexture}`);
310
+
311
+ // Si el tipo de pared seleccionado admite tintado en el render,
312
+ // escogemos un tono beige para toda la casa que aparecerá en el modo
313
+ // render por defecto. El minimapa seguirá tomando su color de
314
+ // ROOM_CONFIGS (como los azules de los baños).
315
+ let wallRenderTintColor;
316
+ let wallRenderTintOpacity;
317
+ if (isTintableRender(houseWallTexture)) {
318
+ wallRenderTintColor = chooseBeigeColor(BEIGE_TINT_DISTRIBUTION);
319
+ wallRenderTintOpacity = 0.5;
320
+ }
321
+
322
+ // create a shallow copy of ROOM_CONFIGS with the selected wall texture
323
+ const roomConfigsForHouse = {};
324
+ for (const key in ROOM_CONFIGS) {
325
+ // copy and override wall and floor textures; si hay render tint lo
326
+ // adjuntamos a cada configuración de sala.
327
+ roomConfigsForHouse[key] = Object.assign({}, ROOM_CONFIGS[key], {
328
+ wallTexture: houseWallTexture,
329
+ floorTexture: houseFloorTexture,
330
+ ...(wallRenderTintColor !== undefined ? { tintRender: wallRenderTintColor, tintOpacity: wallRenderTintOpacity } : {})
331
+ });
332
+ }
333
+
334
+ // ¿cuántas plantas? Se decide antes de colocar las salas porque una casa
335
+ // de dos o más plantas lleva una sala más: la caja de escalera. El alto
336
+ // del volumen es limitado, así que tampoco puede tener más plantas que las
337
+ // que dejen su techo —y los bloques que el jugador necesita encima para
338
+ // pararse en él— dentro del mundo.
339
+ const rise = floorRise(Object.values(ROOM_CONFIGS));
340
+ const floorCount = Math.min(pickFloorCount(),
341
+ maxFloorsFitting(baseY, rise, WORLD_CONFIG.volumeHeight));
342
+
343
+ const types = chooseRoomTypes(floorCount > 1);
344
+ placeRooms(types, plotX0, plotZ0, plotWidth, plotDepth,
345
+ baseY, structures, orientation, parcelId,
346
+ roomConfigsForHouse, createRoom);
347
+
348
+ // La escalera se resuelve ANTES de abrir las puertas: ocupa un tramo de la
349
+ // caja y lo deja reservado en `stairKeepOut`, de modo que las reglas de
350
+ // conexión abran cada puerta esquivándolo en lugar de quedar tapada por
351
+ // los escalones.
352
+ const groundRooms = structures.filter(s => s.parcelId === parcelId);
353
+ const stairW = stairWidth(groundRooms);
354
+ let stairPlan = null;
355
+ if (floorCount > 1) {
356
+ stairPlan = planFloorStairs(groundRooms, rise, stairW, 0);
357
+ applyStairPlan(stairPlan);
358
+ if (!stairPlan) {
359
+ console.log(' sin lugar para la escalera: la casa se queda de una planta');
360
+ }
361
+ }
362
+
363
+ // Durante la fase de colocación no se creaban conexiones internas entre
364
+ // salas. A partir de aquí ejecutamos un paso adicional que marca aperturas
365
+ // (4×6) en las paredes de las habitaciones que deben comunicarse.
366
+ // Por el momento sólo nos interesan los pasillos de una misma casa: si dos
367
+ // `hallway` contiguos llevan el mismo parcelId generamos los flags que
368
+ // `generateVolumeType3` utilizará más tarde para grabar la abertura.
369
+ connectRooms(structures);
370
+ // asegurarse también de que cocina, comedor y living estén abiertos hacia
371
+ // un pasillo siempre que queden adyacentes a él. esto aplica una política
372
+ // más estricta para los tres tipos principales que el cliente quiere
373
+ // garantizar.
374
+ connectSpecialRoomsToHallways(structures);
375
+ // los baños deben conectarse con un solo acceso siguiendo la prioridad
376
+ // pasillo > sala principal > otra sala. se aplica después de las otras
377
+ // reglas para no interferir con puertas ya creadas.
378
+ connectBathrooms(structures);
379
+ // dormitorios también pueden tener una única abertura; prioridad
380
+ // 1. pasillo 2. sala principal.
381
+ connectBedrooms(structures);
382
+
383
+ // generate a back‑yard opening in the farthest principal room
384
+ // (comedor > living > cocina) for the current parcel. This must run
385
+ // after all internal connections because it uses room positions but
386
+ // does not affect geometry.
387
+ connectBackyardDoor(structures, orientation, parcelId);
388
+
389
+ // tras todas las conexiones internas procedemos a generar ventanas.
390
+ // el algoritmo ahora espera recibir únicamente las salas que pertenecen
391
+ // a esta casa; filtramos por `parcelId` antes de llamar.
392
+ // no windows for bathrooms, so omit them from the list
393
+ const parcelRooms = structures.filter(s =>
394
+ s.parcelId === parcelId && s.type !== 'hallway' && s.type !== 'spawn' && s.type !== 'banio'
395
+ );
396
+ addWindows(parcelRooms, structures, plotX0, plotZ0, plotWidth, plotDepth);
397
+
398
+ // Ninguna regla de conexión garantiza una puerta: si la escalera quedó sin
399
+ // acceso no hay cómo subir, así que se la quita y la casa se queda de una
400
+ // planta en lugar de levantar plantas incomunicadas.
401
+ if (stairPlan && !hasDoor(stairPlan.room) && !stairPlan.room.hasFrontDoor) {
402
+ console.log(` la escalera quedó sin puerta (${stairPlan.room.type}): la casa se queda de una planta`);
403
+ clearStairPlan(stairPlan);
404
+ stairPlan = null;
405
+ }
406
+
407
+ // cada planta alta repite la de abajo un piso más arriba (mismas paredes,
408
+ // mismas puertas interiores) y recibe sus propias ventanas. Cada planta k
409
+ // lleva un tramo de escalera que sube a la k+1, y la planta de arriba del
410
+ // todo lleva el que sube al techo. Con caja de escalera todos los tramos
411
+ // van apilados en ella; sin caja se busca sitio sala por sala, después de
412
+ // clonar la planta, para poder esquivar sus puertas copiadas.
413
+ const levels = [groundRooms];
414
+ const stairFrom = [stairPlan];
415
+ let level = 0;
416
+ while (stairFrom[level] && level + 1 < floorCount) {
417
+ const upperRooms = buildUpperFloor(levels[level], structures, rise);
418
+ const upperWithWindows = upperRooms.filter(s =>
419
+ s.type !== 'hallway' && s.type !== 'spawn' && s.type !== 'banio'
420
+ );
421
+ addWindows(upperWithWindows, structures, plotX0, plotZ0, plotWidth, plotDepth);
422
+ levels.push(upperRooms);
423
+ level++;
424
+ stairFrom[level] = planFloorStairs(upperRooms, rise, stairW, level);
425
+ applyStairPlan(stairFrom[level]);
426
+ if (!stairFrom[level]) {
427
+ console.log(` sin lugar para la escalera de la planta ${level + 1}`);
428
+ }
429
+ }
430
+ // Si la última planta no tiene sitio para su tramo, se quita y la casa
431
+ // queda una planta más abajo. El tramo de la planta de abajo ya está
432
+ // puesto y las puertas ya lo esquivan, así que se deja como está: pasa a
433
+ // ser el que sube al techo, que está a la misma altura que estaba el piso
434
+ // de la planta quitada. Una casa de una planta no lleva escalera.
435
+ if (!stairFrom[level] && level > 0) {
436
+ console.log(` la planta ${level + 1} se quita: no hay sitio para su escalera`);
437
+ removeFloor(structures, parcelId, level);
438
+ levels.pop();
439
+ level--;
440
+ }
441
+
442
+ // Azotea: casilla sobre la escalera que sale al techo (si la hay) y, en
443
+ // la mitad de las casas, un tanque de agua. Después de clonar las plantas
444
+ // para que las anotaciones no se copien a ninguna otra.
445
+ planRoofExtras(levels[level], stairFrom[level] || null);
446
+
447
+ // Botín fijo de la casa: cada sala tiene 25% de probabilidad de llevar una
448
+ // caja. Se anota recién ahora, después de clonar las plantas y resolver sus
449
+ // escaleras, para que los clones no se lleven el punto de la planta baja.
450
+ for (let l = 0; l < levels.length; l++) {
451
+ for (const sala of pickLootRooms(levels[l], l)) {
452
+ const spot = pickLootSpot(sala);
453
+ if (spot) sala.lootSpot = spot;
454
+ }
455
+ // Armarios con comida/agua (supervivencia): decisión y contenido se
456
+ // sortean acá, una sola vez; el servidor los envía a los clientes.
457
+ for (const sala of levels[l]) {
458
+ const armario = pickArmario(sala);
459
+ if (armario) sala.armarios = [armario];
460
+ }
461
+ }
462
+
463
+ if (level > 0) {
464
+ const plan = stairFrom[level];
465
+ console.log(` casa de ${level + 1} plantas; escalera al techo en ${plan.room.type} (${plan.startX},${plan.startZ}) eje ${plan.axis} sentido ${plan.dir}`);
466
+ }
467
+ // ejemplos de usos futuros: addHallways, addBathroomConnections, etc.
468
+ }
469
+
470
+ // connection helpers moved to generadorCasaConexiones.js