70 lines
1.8 KiB
TypeScript
70 lines
1.8 KiB
TypeScript
import { to1D } from '../convert';
|
|
import { WorldChunk } from './WorldChunk';
|
|
import { WorldLoader } from './WorldLoader';
|
|
|
|
export class WorldManager {
|
|
protected _chunks!: WorldChunk[];
|
|
|
|
constructor(
|
|
public loader: WorldLoader,
|
|
public worldWidth = 1,
|
|
public worldHeight = 1,
|
|
public worldChunkSize = 256,
|
|
) {
|
|
this._chunks = new Array(this.worldWidth * this.worldHeight);
|
|
}
|
|
|
|
async loadHeightData(chunkX: number, chunkY: number) {
|
|
const heightData = await this.loader.loadHeightMap(chunkX, chunkY);
|
|
this._chunks[to1D(chunkX, chunkY, this.worldWidth)] = new WorldChunk(
|
|
heightData,
|
|
chunkX, chunkY,
|
|
this.worldChunkSize,
|
|
);
|
|
}
|
|
|
|
async loadWorld() {
|
|
for (let x = 0; x < this.worldWidth; x++) {
|
|
for (let y = 0; y < this.worldHeight; y++) {
|
|
await this.loadHeightData(x, y);
|
|
}
|
|
}
|
|
}
|
|
|
|
getHeight(x: number, y: number): number {
|
|
const chunkX = Math.floor(x / this.worldChunkSize);
|
|
const chunkY = Math.floor(y / this.worldChunkSize);
|
|
if (
|
|
chunkX >= this.worldWidth ||
|
|
chunkY >= this.worldHeight ||
|
|
x < 0 ||
|
|
y < 0
|
|
) {
|
|
return 0;
|
|
}
|
|
|
|
return this._chunks[to1D(chunkX, chunkY, this.worldWidth)].getPoint(
|
|
x - chunkX * this.worldChunkSize,
|
|
y - chunkY * this.worldChunkSize,
|
|
);
|
|
}
|
|
|
|
getInterpolatedHeight(x: number, y: number): number {
|
|
const chunkX = Math.floor(x / this.worldChunkSize);
|
|
const chunkY = Math.floor(y / this.worldChunkSize);
|
|
if (
|
|
chunkX >= this.worldWidth ||
|
|
chunkY >= this.worldHeight ||
|
|
x < 0 ||
|
|
y < 0
|
|
) {
|
|
return 0;
|
|
}
|
|
|
|
return this._chunks[to1D(chunkX, chunkY, this.worldWidth)].getInterpolatedPoint(
|
|
x - chunkX * this.worldChunkSize,
|
|
y - chunkY * this.worldChunkSize,
|
|
);
|
|
}
|
|
}
|