KHR_draco_mesh_compression.ts 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF2.Extensions {
  3. // https://github.com/KhronosGroup/glTF/pull/874
  4. const NAME = "KHR_draco_mesh_compression";
  5. interface IKHRDracoMeshCompression {
  6. bufferView: number;
  7. attributes: { [name: string]: number };
  8. }
  9. export class KHR_draco_mesh_compression extends GLTFLoaderExtension {
  10. public readonly name = NAME;
  11. protected _loadVertexDataAsync(context: string, primitive: ILoaderMeshPrimitive, babylonMesh: Mesh): Nullable<Promise<VertexData>> {
  12. return this._loadExtensionAsync<IKHRDracoMeshCompression, VertexData>(context, primitive, (extensionContext, extension) => {
  13. if (primitive.mode != undefined) {
  14. if (primitive.mode !== MeshPrimitiveMode.TRIANGLE_STRIP &&
  15. primitive.mode !== MeshPrimitiveMode.TRIANGLES) {
  16. throw new Error(`${context}: Unsupported mode ${primitive.mode}`);
  17. }
  18. // TODO: handle triangle strips
  19. if (primitive.mode === MeshPrimitiveMode.TRIANGLE_STRIP) {
  20. throw new Error(`${context}: Mode ${primitive.mode} is not currently supported`);
  21. }
  22. }
  23. const attributes: { [kind: string]: number } = {};
  24. const loadAttribute = (name: string, kind: string) => {
  25. const uniqueId = extension.attributes[name];
  26. if (uniqueId == undefined) {
  27. return;
  28. }
  29. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  30. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  31. babylonMesh._delayInfo.push(kind);
  32. }
  33. attributes[kind] = uniqueId;
  34. };
  35. loadAttribute("POSITION", VertexBuffer.PositionKind);
  36. loadAttribute("NORMAL", VertexBuffer.NormalKind);
  37. loadAttribute("TANGENT", VertexBuffer.TangentKind);
  38. loadAttribute("TEXCOORD_0", VertexBuffer.UVKind);
  39. loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind);
  40. loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind);
  41. loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind);
  42. loadAttribute("COLOR_0", VertexBuffer.ColorKind);
  43. var bufferView = GLTFLoader._GetProperty(extensionContext, this._loader._gltf.bufferViews, extension.bufferView);
  44. return this._loader._loadBufferViewAsync(`#/bufferViews/${bufferView._index}`, bufferView).then(data => {
  45. try {
  46. return DracoCompression.Decode(data, attributes);
  47. }
  48. catch (e) {
  49. throw new Error(`${context}: ${e.message}`);
  50. }
  51. });
  52. });
  53. }
  54. }
  55. if (DracoCompression.IsSupported) {
  56. GLTFLoader._Register(NAME, loader => new KHR_draco_mesh_compression(loader));
  57. }
  58. }