-
Notifications
You must be signed in to change notification settings - Fork 3
/
chunk.ts
367 lines (321 loc) · 9.95 KB
/
chunk.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { WangTile } from './tile';
import { CoordMap } from './coord-map';
import { WangTileSet } from './tile-set';
import { RandomGenerator, WeightedArray } from './prng';
import { Edge } from './edge';
/**
* A chunk is a block of the dimension which can be used to
* observe part of a tile generated world.
*/
export class WangTileChunk<
D extends number[],
V extends WangTileSet<D> | WangTile<D> = WangTileSet<D> | WangTile<D>,
> {
public observed = false;
private readonly coordMap: CoordMap<D, V>;
private readonly center: D;
private readonly iter: number;
private active: D | null = null;
constructor(
private readonly tileset: Set<WangTile<D>>,
private readonly random: RandomGenerator,
chunkStart: D,
chunkEnd: D,
) {
this.coordMap = new CoordMap<D, V>().fill(
() => new Set(tileset) as V,
chunkStart,
chunkEnd,
);
this.center = chunkStart.map((start, index) => {
const end = chunkEnd[index];
const diff = end - start;
return start + Math.floor(diff / 2);
}) as D;
this.iter = this.center.reduce((memo, vec) => (memo *= vec), 1);
}
/**
* Observe the tiles until there are no unobserved tiles.
* @yields
*/
public *observe() {
const centerTile = this.coordMap.get(this.center);
// observe the center if still a set
if (centerTile instanceof Set) {
yield this.select(this.center);
// this.reduceAll();
}
// sort by size and observe the next smallest set.
let nextSet;
do {
nextSet = this.findSmallestSet();
if (nextSet != null) {
this.active = nextSet[0];
console.log(this.debug());
yield this.select(nextSet[0]);
}
} while (nextSet != null);
this.active = null;
console.log(this.debug());
// mark the chuck as observed and end iteration.
this.observed = true;
return;
}
/**
* Select an element via weighted random at the coordinates.
* @param coord - The coordinates to retrieve.
* @returns the coordinate/tile pair that was set.
*/
private select(coord: D): [D, WangTile<D>] {
const elem = this.reduce(coord);
if (elem instanceof WangTile) {
this.coordMap.set(coord, elem);
return [coord, elem];
}
const possibleElements: WeightedArray<WangTile<D>> = Array.from(elem).map(
(tile) => [tile.probability, tile],
);
const tile = this.random.weightedRandom(possibleElements);
this.coordMap.set(coord, tile as V);
return [coord, tile];
}
/**
* Find the smallest set in the coordinate map and return it, or null if no more sets exist.
* @returns A coord/tileset pair or null
*/
private findSmallestSet(): [D, WangTileSet<D>] | null {
const sets: [D, WangTileSet<D>][] = Array.from(this.coordMap).filter(
(coord) => coord[1] instanceof Set,
) as [D, WangTileSet<D>][];
if (sets.length < 1) {
return null;
}
if (sets.length == 1) {
return sets[0];
}
return sets.sort((a, b) => {
return (
this.getPossibilitiesCount(a[0]) - this.getPossibilitiesCount(b[0])
);
})[0];
}
/**
* Get the number for possibilities for a coordinate via count.
* @param coord - The coordinate to calculate.
* @returns the count of possibilities for a coordinate.
*/
private getPossibilitiesCount(coord: D): number {
const neighbors = this.coordMap.getNeighbors(coord);
let possibilities = 0;
for (let dimension = 0; dimension < coord.length; dimension++) {
const [[, beforeVal], [, afterVal]] = neighbors[dimension];
if (beforeVal instanceof WangTile) {
possibilities -= this.tileset.size;
} else if (beforeVal instanceof Set) {
possibilities += beforeVal.size;
} else if (beforeVal == null) {
possibilities += this.tileset.size * 2;
}
if (afterVal instanceof WangTile) {
possibilities -= this.tileset.size;
} else if (afterVal instanceof Set) {
possibilities += afterVal.size;
} else if (beforeVal == null) {
possibilities += this.tileset.size * 2;
}
}
return possibilities;
}
/**
* Reduce the possibilities of the entire chunk
*/
private reduceAll(): void {
for (let index = 0; index < this.iter; index++) {
for (const [coord] of this.coordMap) {
this.reduce(coord);
}
}
}
/**
* Reduce the possibilities to a single tile.
* @param coord - The coordinate to retrieve.
* @returns A single, randomly selected tile from the set.
*/
private reduce(coord: D): V {
const elem = this.coordMap.get(coord);
// Throw if coordinates are uninitialized.
if (elem == null) {
throw new Error('Coordinates are uninitialized or out of bounds.');
}
// Return if already observed.
if (elem instanceof WangTile) {
return elem;
}
// Throw if the set is empty.
if (elem.size <= 0) {
throw new Error('Tileset possibilities were empty.');
}
// Return if the set only has one possibility.
if (elem.size <= 1) {
return elem.values().next().value;
}
const neighbors = this.coordMap.getNeighbors(coord);
let availableTiles = new WangTileSet(elem);
for (let dimension = 0; dimension < coord.length; dimension++) {
const [[beforeCoord, beforeVal], [afterCoord, afterVal]] =
neighbors[dimension];
if (beforeVal instanceof WangTile) {
availableTiles = this.reduceByNeighborEdge(
beforeVal,
availableTiles,
coord.length,
dimension,
1,
);
} else if (beforeVal instanceof Set) {
availableTiles = this.reduceByNeighborEdges(
beforeVal,
availableTiles,
coord.length,
dimension,
1,
);
}
if (afterVal instanceof WangTile) {
availableTiles = this.reduceByNeighborEdge(
afterVal,
availableTiles,
coord.length,
dimension,
-1,
);
} else if (afterVal instanceof Set) {
availableTiles = this.reduceByNeighborEdges(
afterVal,
availableTiles,
coord.length,
dimension,
-1,
);
}
if (availableTiles.size < 1) {
throw new Error(
`The coordinate {${coord.join()}} could not be resolved due to it's neighbors constraints at {${beforeCoord.join()}}:${beforeVal} and {${afterCoord.join()}}:${afterVal}`,
);
}
}
if (availableTiles.size > 1) {
const newTileset = new WangTileSet(availableTiles) as V;
this.coordMap.set(coord, newTileset);
return newTileset;
} else {
const newTile = availableTiles.values().next().value as V;
this.coordMap.set(coord, newTile);
return newTile;
}
}
/**
* Reduce a tileset by a neighboring tile.
* @param tile - The neighboring tile
* @param availableTiles - The tileset to reduce
* @param dimensions - The number of dimensions
* @param dimension - The dimension of the edge
* @param offset - The offset from the position
* @returns - A new tileset reduced by the neighboring tile.
*/
private reduceByNeighborEdge(
tile: WangTile<D, unknown>,
availableTiles: WangTileSet<D, unknown>,
dimensions: number,
dimension: number,
offset: -1 | 1,
): WangTileSet<D, unknown> {
const oppositeOffset = (offset * -1) as 1 | -1;
const edge = tile.edges.getByOffset(dimensions, dimension, offset);
if (edge != null) {
availableTiles = availableTiles.reduceOffset(
edge,
dimensions,
dimension,
oppositeOffset,
);
}
return availableTiles;
}
/**
* Reduce a tileset by a neighboring tile.
* @param tiles - The neighboring tileset
* @param availableTiles - The tileset to reduce
* @param dimensions - The number of dimensions
* @param dimension - The dimension of the edge
* @param offset - The offset from the position
* @returns - A new tileset reduced by the neighboring tile.
*/
private reduceByNeighborEdges(
tiles: WangTileSet<D>,
availableTiles: WangTileSet<D, unknown>,
dimensions: number,
dimension: number,
offset: -1 | 1,
): WangTileSet<D, unknown> {
let beforeEdges: Edge[] | null = null;
for (const tile of tiles.values()) {
const beforeEdge = tile.edges.getByOffset(dimensions, dimension, offset);
if (beforeEdge != null) {
if (beforeEdges == null) {
beforeEdges = [];
}
beforeEdges.push(beforeEdge);
}
}
if (beforeEdges != null) {
return availableTiles.reduceOffset(
beforeEdges,
dimensions,
dimension,
-1,
);
}
return availableTiles;
}
/**
* Convert coordinate map to a simple object for storage and testing.
* @returns An object representing all coordinates in the map. Keys are comma delineated coordinates.
*/
toJSON(): Record<string, V> {
return this.coordMap.toJSON();
}
/**
* Convert coordinate map to an ascii representation.
* Only works for 2D chunks at the moment.
* @returns An ascii based representation of the map.
*/
debug(): string {
const asciiCoords = Array.from(this.coordMap)
.reduce((memo, [coord, val]) => {
if (memo[coord[1]] == null) {
memo[coord[1]] = [];
}
if (
this.active != null &&
coord[0] === this.active[0] &&
coord[1] === this.active[1]
) {
memo[coord[1]][coord[0]] = '█';
} else if (val instanceof Set) {
memo[coord[1]][coord[0]] = '░';
} else {
memo[coord[1]][coord[0]] = val.toString();
}
return memo;
}, [] as string[][])
.map((strings) => strings.join(''));
let blockDrawing = asciiCoords
.reverse()
.reduce((memo, string) => `${memo}\n${string}`, '');
if (this.active != null) {
blockDrawing += `\nActive: {${this.active[0]}, ${this.active[1]}}`;
}
return blockDrawing + '\n';
}
}