dracoCompression.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import { Tools } from "../../Misc/tools";
  2. import { WorkerPool } from '../../Misc/workerPool';
  3. import { Nullable } from "../../types";
  4. import { IDisposable } from "../../scene";
  5. import { VertexData } from "../../Meshes/mesh.vertexData";
  6. declare var DracoDecoderModule: any;
  7. declare var WebAssembly: any;
  8. // WorkerGlobalScope
  9. declare function importScripts(...urls: string[]): void;
  10. declare function postMessage(message: any, transfer?: any[]): void;
  11. function createDecoderAsync(wasmBinary?: ArrayBuffer): Promise<any> {
  12. return new Promise((resolve) => {
  13. DracoDecoderModule({ wasmBinary: wasmBinary }).then((module: any) => {
  14. resolve({ module: module });
  15. });
  16. });
  17. }
  18. function decodeMesh(decoderModule: any, dataView: ArrayBufferView, attributes: { [kind: string]: number } | undefined, onIndicesData: (data: Uint32Array) => void, onAttributeData: (kind: string, data: Float32Array) => void): void {
  19. const buffer = new decoderModule.DecoderBuffer();
  20. buffer.Init(dataView, dataView.byteLength);
  21. const decoder = new decoderModule.Decoder();
  22. let geometry: any;
  23. let status: any;
  24. try {
  25. const type = decoder.GetEncodedGeometryType(buffer);
  26. switch (type) {
  27. case decoderModule.TRIANGULAR_MESH:
  28. geometry = new decoderModule.Mesh();
  29. status = decoder.DecodeBufferToMesh(buffer, geometry);
  30. break;
  31. case decoderModule.POINT_CLOUD:
  32. geometry = new decoderModule.PointCloud();
  33. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  34. break;
  35. default:
  36. throw new Error(`Invalid geometry type ${type}`);
  37. }
  38. if (!status.ok() || !geometry.ptr) {
  39. throw new Error(status.error_msg());
  40. }
  41. const numPoints = geometry.num_points();
  42. if (type === decoderModule.TRIANGULAR_MESH) {
  43. const numFaces = geometry.num_faces();
  44. const faceIndices = new decoderModule.DracoInt32Array();
  45. try {
  46. const indices = new Uint32Array(numFaces * 3);
  47. for (let i = 0; i < numFaces; i++) {
  48. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  49. const offset = i * 3;
  50. indices[offset + 0] = faceIndices.GetValue(0);
  51. indices[offset + 1] = faceIndices.GetValue(1);
  52. indices[offset + 2] = faceIndices.GetValue(2);
  53. }
  54. onIndicesData(indices);
  55. }
  56. finally {
  57. decoderModule.destroy(faceIndices);
  58. }
  59. }
  60. const processAttribute = (kind: string, attribute: any) => {
  61. const dracoData = new decoderModule.DracoFloat32Array();
  62. try {
  63. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64. const numComponents = attribute.num_components();
  65. if (kind === "color" && numComponents === 3) {
  66. const babylonData = new Float32Array(numPoints * 4);
  67. for (let i = 0, j = 0; i < babylonData.length; i += 4, j += numComponents) {
  68. babylonData[i + 0] = dracoData.GetValue(j + 0);
  69. babylonData[i + 1] = dracoData.GetValue(j + 1);
  70. babylonData[i + 2] = dracoData.GetValue(j + 2);
  71. babylonData[i + 3] = 1;
  72. }
  73. onAttributeData(kind, babylonData);
  74. }
  75. else {
  76. const babylonData = new Float32Array(numPoints * numComponents);
  77. for (let i = 0; i < babylonData.length; i++) {
  78. babylonData[i] = dracoData.GetValue(i);
  79. }
  80. onAttributeData(kind, babylonData);
  81. }
  82. }
  83. finally {
  84. decoderModule.destroy(dracoData);
  85. }
  86. };
  87. if (attributes) {
  88. for (const kind in attributes) {
  89. const id = attributes[kind];
  90. const attribute = decoder.GetAttributeByUniqueId(geometry, id);
  91. processAttribute(kind, attribute);
  92. }
  93. }
  94. else {
  95. const nativeAttributeTypes: { [kind: string]: string } = {
  96. "position": "POSITION",
  97. "normal": "NORMAL",
  98. "color": "COLOR",
  99. "uv": "TEX_COORD"
  100. };
  101. for (const kind in nativeAttributeTypes) {
  102. const id = decoder.GetAttributeId(geometry, decoderModule[nativeAttributeTypes[kind]]);
  103. if (id !== -1) {
  104. const attribute = decoder.GetAttribute(geometry, id);
  105. processAttribute(kind, attribute);
  106. }
  107. }
  108. }
  109. }
  110. finally {
  111. if (geometry) {
  112. decoderModule.destroy(geometry);
  113. }
  114. decoderModule.destroy(decoder);
  115. decoderModule.destroy(buffer);
  116. }
  117. }
  118. /**
  119. * The worker function that gets converted to a blob url to pass into a worker.
  120. */
  121. function worker(): void {
  122. let decoderPromise: Promise<any> | undefined;
  123. onmessage = (event) => {
  124. const data = event.data;
  125. switch (data.id) {
  126. case "init": {
  127. const decoder = data.decoder;
  128. if (decoder.url) {
  129. importScripts(decoder.url);
  130. decoderPromise = createDecoderAsync(decoder.wasmBinary);
  131. }
  132. postMessage("done");
  133. break;
  134. }
  135. case "decodeMesh": {
  136. if (!decoderPromise) {
  137. throw new Error("Draco decoder module is not available");
  138. }
  139. decoderPromise.then((decoder) => {
  140. decodeMesh(decoder.module, data.dataView, data.attributes, (indices) => {
  141. postMessage({ id: "indices", value: indices }, [indices.buffer]);
  142. }, (kind, data) => {
  143. postMessage({ id: kind, value: data }, [data.buffer]);
  144. });
  145. postMessage("done");
  146. });
  147. break;
  148. }
  149. }
  150. };
  151. }
  152. function getAbsoluteUrl<T>(url: T): T | string {
  153. if (typeof document !== "object" || typeof url !== "string") {
  154. return url;
  155. }
  156. return Tools.GetAbsoluteUrl(url);
  157. }
  158. /**
  159. * Configuration for Draco compression
  160. */
  161. export interface IDracoCompressionConfiguration {
  162. /**
  163. * Configuration for the decoder.
  164. */
  165. decoder: {
  166. /**
  167. * The url to the WebAssembly module.
  168. */
  169. wasmUrl?: string;
  170. /**
  171. * The url to the WebAssembly binary.
  172. */
  173. wasmBinaryUrl?: string;
  174. /**
  175. * The url to the fallback JavaScript module.
  176. */
  177. fallbackUrl?: string;
  178. };
  179. }
  180. /**
  181. * Draco compression (https://google.github.io/draco/)
  182. *
  183. * This class wraps the Draco module.
  184. *
  185. * **Encoder**
  186. *
  187. * The encoder is not currently implemented.
  188. *
  189. * **Decoder**
  190. *
  191. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  192. *
  193. * To update the configuration, use the following code:
  194. * ```javascript
  195. * DracoCompression.Configuration = {
  196. * decoder: {
  197. * wasmUrl: "<url to the WebAssembly library>",
  198. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  199. * fallbackUrl: "<url to the fallback JavaScript library>",
  200. * }
  201. * };
  202. * ```
  203. *
  204. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  205. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  206. * Use `DracoCompression.DecoderAvailable` to determine if the decoder configuration is available for the current context.
  207. *
  208. * To decode Draco compressed data, get the default DracoCompression object and call decodeMeshAsync:
  209. * ```javascript
  210. * var vertexData = await DracoCompression.Default.decodeMeshAsync(data);
  211. * ```
  212. *
  213. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  214. */
  215. export class DracoCompression implements IDisposable {
  216. private _workerPoolPromise?: Promise<WorkerPool>;
  217. private _decoderModulePromise?: Promise<any>;
  218. /**
  219. * The configuration. Defaults to the following urls:
  220. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  221. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  222. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  223. */
  224. public static Configuration: IDracoCompressionConfiguration = {
  225. decoder: {
  226. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  227. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  228. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  229. }
  230. };
  231. /**
  232. * Returns true if the decoder configuration is available.
  233. */
  234. public static get DecoderAvailable(): boolean {
  235. const decoder = DracoCompression.Configuration.decoder;
  236. return !!((decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") || decoder.fallbackUrl);
  237. }
  238. /**
  239. * Default number of workers to create when creating the draco compression object.
  240. */
  241. public static DefaultNumWorkers = DracoCompression.GetDefaultNumWorkers();
  242. private static GetDefaultNumWorkers(): number {
  243. if (typeof navigator !== "object" || !navigator.hardwareConcurrency) {
  244. return 1;
  245. }
  246. // Use 50% of the available logical processors but capped at 4.
  247. return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);
  248. }
  249. private static _Default: Nullable<DracoCompression> = null;
  250. /**
  251. * Default instance for the draco compression object.
  252. */
  253. public static get Default(): DracoCompression {
  254. if (!DracoCompression._Default) {
  255. DracoCompression._Default = new DracoCompression();
  256. }
  257. return DracoCompression._Default;
  258. }
  259. /**
  260. * Constructor
  261. * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.
  262. */
  263. constructor(numWorkers = DracoCompression.DefaultNumWorkers) {
  264. const decoder = DracoCompression.Configuration.decoder;
  265. const decoderInfo: { url: string | undefined, wasmBinaryPromise: Promise<ArrayBuffer | string | undefined> } =
  266. (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") ? {
  267. url: decoder.wasmUrl,
  268. wasmBinaryPromise: Tools.LoadFileAsync(getAbsoluteUrl(decoder.wasmBinaryUrl))
  269. } : {
  270. url: decoder.fallbackUrl,
  271. wasmBinaryPromise: Promise.resolve(undefined)
  272. };
  273. if (numWorkers && typeof Worker === "function") {
  274. this._workerPoolPromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => {
  275. const workerContent = `${createDecoderAsync}${decodeMesh}(${worker})()`;
  276. const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" }));
  277. const workerPromises = new Array<Promise<Worker>>(numWorkers);
  278. for (let i = 0; i < workerPromises.length; i++) {
  279. workerPromises[i] = new Promise((resolve, reject) => {
  280. const worker = new Worker(workerBlobUrl);
  281. const onError = (error: ErrorEvent) => {
  282. worker.removeEventListener("error", onError);
  283. worker.removeEventListener("message", onMessage);
  284. reject(error);
  285. };
  286. const onMessage = (message: MessageEvent) => {
  287. if (message.data === "done") {
  288. worker.removeEventListener("error", onError);
  289. worker.removeEventListener("message", onMessage);
  290. resolve(worker);
  291. }
  292. };
  293. worker.addEventListener("error", onError);
  294. worker.addEventListener("message", onMessage);
  295. worker.postMessage({
  296. id: "init",
  297. decoder: {
  298. url: getAbsoluteUrl(decoderInfo.url),
  299. wasmBinary: decoderWasmBinary,
  300. }
  301. });
  302. });
  303. }
  304. return Promise.all(workerPromises).then((workers) => {
  305. return new WorkerPool(workers);
  306. });
  307. });
  308. }
  309. else {
  310. this._decoderModulePromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => {
  311. if (!decoderInfo.url) {
  312. throw new Error("Draco decoder module is not available");
  313. }
  314. return Tools.LoadScriptAsync(decoderInfo.url).then(() => {
  315. return createDecoderAsync(decoderWasmBinary as ArrayBuffer);
  316. });
  317. });
  318. }
  319. }
  320. /**
  321. * Stop all async operations and release resources.
  322. */
  323. public dispose(): void {
  324. if (this._workerPoolPromise) {
  325. this._workerPoolPromise.then((workerPool) => {
  326. workerPool.dispose();
  327. });
  328. }
  329. delete this._workerPoolPromise;
  330. delete this._decoderModulePromise;
  331. }
  332. /**
  333. * Returns a promise that resolves when ready. Call this manually to ensure draco compression is ready before use.
  334. * @returns a promise that resolves when ready
  335. */
  336. public whenReadyAsync(): Promise<void> {
  337. if (this._workerPoolPromise) {
  338. return this._workerPoolPromise.then(() => { });
  339. }
  340. if (this._decoderModulePromise) {
  341. return this._decoderModulePromise.then(() => { });
  342. }
  343. return Promise.resolve();
  344. }
  345. /**
  346. * Decode Draco compressed mesh data to vertex data.
  347. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  348. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  349. * @returns A promise that resolves with the decoded vertex data
  350. */
  351. public decodeMeshAsync(data: ArrayBuffer | ArrayBufferView, attributes?: { [kind: string]: number }): Promise<VertexData> {
  352. const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  353. if (this._workerPoolPromise) {
  354. return this._workerPoolPromise.then((workerPool) => {
  355. return new Promise<VertexData>((resolve, reject) => {
  356. workerPool.push((worker, onComplete) => {
  357. const vertexData = new VertexData();
  358. const onError = (error: ErrorEvent) => {
  359. worker.removeEventListener("error", onError);
  360. worker.removeEventListener("message", onMessage);
  361. reject(error);
  362. onComplete();
  363. };
  364. const onMessage = (message: MessageEvent) => {
  365. if (message.data === "done") {
  366. worker.removeEventListener("error", onError);
  367. worker.removeEventListener("message", onMessage);
  368. resolve(vertexData);
  369. onComplete();
  370. }
  371. else if (message.data.id === "indices") {
  372. vertexData.indices = message.data.value;
  373. }
  374. else {
  375. vertexData.set(message.data.value, message.data.id);
  376. }
  377. };
  378. worker.addEventListener("error", onError);
  379. worker.addEventListener("message", onMessage);
  380. const dataViewCopy = new Uint8Array(dataView.byteLength);
  381. dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength));
  382. worker.postMessage({ id: "decodeMesh", dataView: dataViewCopy, attributes: attributes }, [dataViewCopy.buffer]);
  383. });
  384. });
  385. });
  386. }
  387. if (this._decoderModulePromise) {
  388. return this._decoderModulePromise.then((decoder) => {
  389. const vertexData = new VertexData();
  390. decodeMesh(decoder.module, dataView, attributes, (indices) => {
  391. vertexData.indices = indices;
  392. }, (kind, data) => {
  393. vertexData.set(data, kind);
  394. });
  395. return vertexData;
  396. });
  397. }
  398. throw new Error("Draco decoder module is not available");
  399. }
  400. }