nanogl-gltf
Version:
69 lines (68 loc) • 2.88 kB
JavaScript
import GltfTypes from '../types/GltfTypes';
import Texture2D from 'nanogl/texture-2d';
import Deferred from '../lib/Deferred';
/**
* The Texture element contains the image data and sampler used to sample the texture.
* It also contains the nanogl Texture2D object, used to render the texture in a WebGL context.
*/
export default class Texture {
constructor() {
this.gltftype = GltfTypes.TEXTURE;
/**
* Deferred object used to wait for the glTexture to be created
*/
this._glTextureDeferred = new Deferred();
}
/**
* Promise that resolves when the glTexture is created, useful for classes that need to wait for the texture to be ready.
*/
get glTexturePromise() {
return this._glTextureDeferred.promise;
}
/**
* Parse the Texture data, create the Sampler and Image elements
*
* Is async as it needs to wait for the Sampler and Image to be created.
* @param gltfLoader GLTFLoader to use
* @param data Data to parse
*/
async parse(gltfLoader, data) {
if (data.sampler !== undefined) {
this.sampler = await gltfLoader.getElement(GltfTypes.SAMPLER, data.sampler);
}
if (data.source !== undefined) {
this.source = await gltfLoader.getElement(GltfTypes.IMAGE, data.source);
}
this._defaultTextureFilter = gltfLoader.defaultTextureFilter;
}
/**
* Setup the gl.TEXTURE_2D with minFilter, magFilter, wrapS and wrapT, depending on the sampler's options.
* This allocates the texture memory and uploads the image data to the GPU so it can be used in a shader.
* @param gl GL context
*/
async allocateGl(gl) {
var _a, _b;
let glFormat = gl.RGB;
if (this.source.hasAlpha)
glFormat = gl.RGBA;
let minFilter = this._defaultTextureFilter;
let magFilter = gl.LINEAR;
let wrapS = gl.REPEAT;
let wrapT = gl.REPEAT;
if (this.sampler) {
minFilter = (_a = this.sampler.minFilter) !== null && _a !== void 0 ? _a : minFilter;
magFilter = (_b = this.sampler.magFilter) !== null && _b !== void 0 ? _b : gl.LINEAR;
wrapS = this.sampler.wrapS;
wrapT = this.sampler.wrapT;
}
this.glTexture = new Texture2D(gl, glFormat, gl.UNSIGNED_BYTE);
await this.source.setupTexture(this.glTexture, wrapS, wrapT, minFilter, magFilter);
this.glTexture.bind();
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
gl.bindTexture(gl.TEXTURE_2D, null);
this._glTextureDeferred.resolve(this.glTexture);
}
}