wip faster texture loading
This commit is contained in:
58
assets.js
58
assets.js
@@ -53,28 +53,18 @@ export class TextureAtlas {
|
||||
this.ctx.imageSmoothingEnabled = false;
|
||||
|
||||
this.map = new Map();
|
||||
this.promises = new Map(); // Track loading promises separately!
|
||||
|
||||
this.cellSize = 16;
|
||||
this.padding = 2; // Add empty space between textures
|
||||
this.padding = 1;
|
||||
this.x = 0;
|
||||
this.y = 0;
|
||||
this.rowHeight = 0;
|
||||
}
|
||||
|
||||
async load(id) {
|
||||
if (this.map.has(id)) return this.map.get(id);
|
||||
|
||||
async fill(id, currentX, currentY) {
|
||||
const url = resolveResourceLocation(id, 'textures', 'png');
|
||||
|
||||
// Include padding in the wrap calculation
|
||||
if (this.x + this.cellSize > this.canvas.width) {
|
||||
this.x = 0;
|
||||
this.y += this.rowHeight + this.padding;
|
||||
this.rowHeight = 0;
|
||||
}
|
||||
|
||||
const currentX = this.x;
|
||||
const currentY = this.y;
|
||||
|
||||
try {
|
||||
const img = await new Promise((resolve, reject) => {
|
||||
const i = new Image();
|
||||
@@ -90,21 +80,39 @@ export class TextureAtlas {
|
||||
this.ctx.fillStyle = '#ff00ff';
|
||||
this.ctx.fillRect(currentX, currentY, this.cellSize, this.cellSize);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean UV mapping (padding protects the edges natively)
|
||||
const uvData = {
|
||||
u: currentX / this.canvas.width,
|
||||
v: currentY / this.canvas.height,
|
||||
du: this.cellSize / this.canvas.width,
|
||||
dv: this.cellSize / this.canvas.height
|
||||
};
|
||||
load(id) {
|
||||
// If already loading/loaded, just return the tracking promise
|
||||
if (this.promises.has(id)) return this.promises.get(id);
|
||||
|
||||
this.map.set(id, uvData);
|
||||
if (this.x + this.cellSize > this.canvas.width) {
|
||||
this.x = 0;
|
||||
this.y += this.rowHeight + this.padding;
|
||||
this.rowHeight = 0;
|
||||
}
|
||||
|
||||
const currentX = this.x;
|
||||
const currentY = this.y;
|
||||
|
||||
// Advance X by cell size AND padding
|
||||
this.x += this.cellSize + this.padding;
|
||||
this.rowHeight = Math.max(this.rowHeight, this.cellSize);
|
||||
const epsX = 0.1 / this.canvas.width;
|
||||
const epsY = 0.1 / this.canvas.height;
|
||||
|
||||
return uvData;
|
||||
// 1. SYNCHRONOUSLY allocate the UV coordinates for buildGeometry
|
||||
const uvData = {
|
||||
u: currentX / this.canvas.width + epsX,
|
||||
v: currentY / this.canvas.height + epsY,
|
||||
du: this.cellSize / this.canvas.width - 2 * epsX,
|
||||
dv: this.cellSize / this.canvas.height - 2 * epsY,
|
||||
};
|
||||
this.map.set(id, uvData);
|
||||
|
||||
// 2. ASYNCHRONOUSLY kick off the image fetch
|
||||
const loadTask = this.fill(id, currentX, currentY);
|
||||
this.promises.set(id, loadTask);
|
||||
|
||||
return loadTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user