diff --git a/src/loader/GLTFLoader.ts b/src/loader/GLTFLoader.ts index 9a020c4..671a65c 100644 --- a/src/loader/GLTFLoader.ts +++ b/src/loader/GLTFLoader.ts @@ -334,7 +334,7 @@ export class GLTF { weights = accessor.getArray(); } const geo = new Geometry({ type: "pbrGeomtry" }); - if (indices) geo.setIndice(Array.from(indices)); + if (indices) geo.setIndice(indices); if (positions) geo.setAttribute(new Float32Attribute("position", Array.from(positions), 3)); if (normals) geo.setAttribute(new Float32Attribute("normal", Array.from(normals), 3)); if (colors) geo.setAttribute(new Float32Attribute("color", Array.from(colors), colorSize)); diff --git a/src/render/IndexBuffer.ts b/src/render/IndexBuffer.ts index c08edab..1fc2e0b 100644 --- a/src/render/IndexBuffer.ts +++ b/src/render/IndexBuffer.ts @@ -1,19 +1,21 @@ import { IndexFormat } from "../core/WebGPUConstant"; import Buffer from "./Buffer"; +import {TypedArray} from "../utils/gltfUtils"; export default class IndexBuffer { buffer: Buffer; - indices: Array; + indices: TypedArray; indexFormat: GPUIndexFormat; dirty: boolean; private label: string; - constructor(label: string, indices?: Array) { + constructor(label: string, indices?: TypedArray) { this.label = label; this.indices = indices; - this.indexFormat = IndexFormat.Uint16; + this.indexFormat = indices instanceof Uint32Array ? IndexFormat.Uint32 : IndexFormat.Uint16; this.dirty = true; } setIndices(indices) { this.indices = indices; + this.indexFormat = indices instanceof Uint32Array ? IndexFormat.Uint32 : IndexFormat.Uint16; this.dirty = true; } bind(device: GPUDevice, passEncoder: GPURenderPassEncoder) { @@ -22,8 +24,9 @@ export default class IndexBuffer { this.buffer = Buffer.createIndexBuffer( this.label, device, - this.indexFormat == IndexFormat.Uint16 ? new Uint16Array(this.indices) : new Uint32Array(this.indices) - ); + this.indices instanceof Array ? + (IndexFormat.Uint16 ? new Uint16Array(this.indices) : new Uint32Array(this.indices)): + this.indices); } passEncoder.setIndexBuffer(this.buffer.gpuBuffer, this.indexFormat); } diff --git a/src/utils/gltfUtils.ts b/src/utils/gltfUtils.ts index 00be75f..6f36eaf 100644 --- a/src/utils/gltfUtils.ts +++ b/src/utils/gltfUtils.ts @@ -45,7 +45,15 @@ export function toIndices(array: TypedArray): Uint16Array | Uint32Array { if (array instanceof Float32Array) { toArray = new Uint32Array(array.length); } else { - toArray = new Uint16Array(array.length); + let max = 0; + for (let i = 0; i < array.length; i++) { + max = max < array[i] ? array[i] : max; + } + if (max < 65536) { + toArray = new Uint16Array(array.length); + } else { + toArray = new Uint32Array(array.length); + } } array.forEach((element, index) => { toArray[index] = element;