From 35222997db6d2c77ce65d766d24d7264f7981e17 Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Thu, 6 Jul 2023 11:44:40 -0400 Subject: [PATCH 01/10] Refactor workers to be ESM, remove RequireJS --- .eslintignore | 2 - .prettierignore | 3 - LICENSE.md | 12 - ThirdParty.extra.json | 6 - ThirdParty.json | 8 - build.js | 173 +- gulpfile.js | 36 +- package.json | 6 - packages/engine/.gitignore | 6 +- packages/engine/LICENSE.md | 12 - .../engine/Source/Core/FeatureDetection.js | 9 + packages/engine/Source/Core/KTX2Transcoder.js | 10 +- packages/engine/Source/Core/TaskProcessor.js | 283 +- packages/engine/Source/Core/buildModuleUrl.js | 11 +- packages/engine/Source/Scene/DracoLoader.js | 29 +- .../engine/Source/Scene/I3SDataProvider.js | 27 - packages/engine/Source/Scene/I3SDecoder.js | 127 + packages/engine/Source/Scene/I3SNode.js | 142 +- .../ThirdParty/Workers/basis_transcoder.js | 2 +- .../Workers/cesiumWorkerBootstrapper.js | 2290 ----------------- .../combineGeometry.js | 0 .../createBoxGeometry.js | 0 .../createBoxOutlineGeometry.js | 0 .../createCircleGeometry.js | 0 .../createCircleOutlineGeometry.js | 0 .../createCoplanarPolygonGeometry.js | 0 .../createCoplanarPolygonOutlineGeometry.js | 0 .../createCorridorGeometry.js | 0 .../createCorridorOutlineGeometry.js | 0 .../createCylinderGeometry.js | 0 .../createCylinderOutlineGeometry.js | 0 .../createEllipseGeometry.js | 0 .../createEllipseOutlineGeometry.js | 0 .../createEllipsoidGeometry.js | 0 .../createEllipsoidOutlineGeometry.js | 0 .../createFrustumGeometry.js | 0 .../createFrustumOutlineGeometry.js | 0 .../{WorkersES6 => Workers}/createGeometry.js | 23 +- .../createGroundPolylineGeometry.js | 0 .../createPlaneGeometry.js | 0 .../createPlaneOutlineGeometry.js | 0 .../createPolygonGeometry.js | 0 .../createPolygonOutlineGeometry.js | 0 .../createPolylineGeometry.js | 0 .../createPolylineVolumeGeometry.js | 0 .../createPolylineVolumeOutlineGeometry.js | 0 .../createRectangleGeometry.js | 0 .../createRectangleOutlineGeometry.js | 0 .../createSimplePolylineGeometry.js | 0 .../createSphereGeometry.js | 0 .../createSphereOutlineGeometry.js | 0 .../createTaskProcessorWorker.js | 100 +- .../createVectorTileClampedPolylines.js | 0 .../createVectorTileGeometries.js | 0 .../createVectorTilePoints.js | 0 .../createVectorTilePolygons.js | 0 .../createVectorTilePolylines.js | 0 ...VerticesFromGoogleEarthEnterpriseBuffer.js | 0 .../createVerticesFromHeightmap.js | 0 .../createVerticesFromQuantizedTerrainMesh.js | 0 .../createWallGeometry.js | 0 .../createWallOutlineGeometry.js | 0 .../{WorkersES6 => Workers}/decodeDraco.js | 44 +- .../decodeGoogleEarthEnterprisePacket.js | 0 .../{WorkersES6 => Workers}/decodeI3S.js | 50 +- packages/engine/Source/Workers/package.json | 1 - .../{WorkersES6 => Workers}/transcodeKTX2.js | 45 +- .../Source/Workers/transferTypedArrayTest.js | 6 - .../upsampleQuantizedTerrainMesh.js | 0 packages/engine/Specs/Scene/PrimitiveSpec.js | 1 - packages/engine/package.json | 1 + server.js | 65 +- 72 files changed, 542 insertions(+), 2988 deletions(-) create mode 100644 packages/engine/Source/Scene/I3SDecoder.js delete mode 100644 packages/engine/Source/Workers/cesiumWorkerBootstrapper.js rename packages/engine/Source/{WorkersES6 => Workers}/combineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createBoxGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createBoxOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createCircleGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createCircleOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createCoplanarPolygonGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createCoplanarPolygonOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createCorridorGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createCorridorOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createCylinderGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createCylinderOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createEllipseGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createEllipseOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createEllipsoidGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createEllipsoidOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createFrustumGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createFrustumOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createGeometry.js (69%) rename packages/engine/Source/{WorkersES6 => Workers}/createGroundPolylineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createPlaneGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createPlaneOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createPolygonGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createPolygonOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createPolylineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createPolylineVolumeGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createPolylineVolumeOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createRectangleGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createRectangleOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createSimplePolylineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createSphereGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createSphereOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createTaskProcessorWorker.js (54%) rename packages/engine/Source/{WorkersES6 => Workers}/createVectorTileClampedPolylines.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createVectorTileGeometries.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createVectorTilePoints.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createVectorTilePolygons.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createVectorTilePolylines.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createVerticesFromGoogleEarthEnterpriseBuffer.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createVerticesFromHeightmap.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createVerticesFromQuantizedTerrainMesh.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createWallGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/createWallOutlineGeometry.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/decodeDraco.js (92%) rename packages/engine/Source/{WorkersES6 => Workers}/decodeGoogleEarthEnterprisePacket.js (100%) rename packages/engine/Source/{WorkersES6 => Workers}/decodeI3S.js (96%) delete mode 100644 packages/engine/Source/Workers/package.json rename packages/engine/Source/{WorkersES6 => Workers}/transcodeKTX2.js (90%) rename packages/engine/Source/{WorkersES6 => Workers}/upsampleQuantizedTerrainMesh.js (100%) diff --git a/.eslintignore b/.eslintignore index e22333336662..cd0ca280ec42 100644 --- a/.eslintignore +++ b/.eslintignore @@ -17,8 +17,6 @@ packages/engine/Build/** packages/engine/Source/Scene/GltfPipeline/** packages/engine/Source/Shaders/** packages/engine/Source/ThirdParty/** -packages/engine/Source/Workers/** -!packages/engine/Source/Workers/transferTypedArrayTest.js # packages/widgets packages/widgets/Build/** diff --git a/.prettierignore b/.prettierignore index 6237c3b02b15..44c086520c7a 100644 --- a/.prettierignore +++ b/.prettierignore @@ -28,9 +28,6 @@ packages/engine/index.js packages/engine/Source/Scene/GltfPipeline/** packages/engine/Source/Shaders/**/*.js packages/engine/Source/ThirdParty/** -packages/engine/Source/Workers/**/* -!packages/engine/Source/Workers/cesiumWorkerBootstrapper.js -!packages/engine/Source/Workers/transferTypedArrayTest.js packages/widgets/Build/** packages/widgets/index.js diff --git a/LICENSE.md b/LICENSE.md index 2d512c93855c..8e5e9fa09fb2 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -270,18 +270,6 @@ https://github.com/sole/tween.js > > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -### RequireJS - -https://github.com/jrburke/requirejs - -> Copyright (c) 2010-2015, The Dojo Foundation -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ### Knockout http://knockoutjs.com/ diff --git a/ThirdParty.extra.json b/ThirdParty.extra.json index 2a78123a9050..48dbdc1cd905 100644 --- a/ThirdParty.extra.json +++ b/ThirdParty.extra.json @@ -69,12 +69,6 @@ { "name": "rbush" }, - { - "name": "requirejs", - "license": ["MIT"], - "version": "2.1.20", - "url": "https://www.npmjs.com/package/requirejs" - }, { "name": "topojson-client" }, diff --git a/ThirdParty.json b/ThirdParty.json index b24426296e44..8fdc881ed477 100644 --- a/ThirdParty.json +++ b/ThirdParty.json @@ -161,14 +161,6 @@ "version": "3.0.1", "url": "https://www.npmjs.com/package/rbush" }, - { - "name": "requirejs", - "license": [ - "MIT" - ], - "version": "2.1.20", - "url": "https://www.npmjs.com/package/requirejs" - }, { "name": "topojson-client", "license": [ diff --git a/build.js b/build.js index 91e7882900d2..aa7c608c0fdb 100644 --- a/build.js +++ b/build.js @@ -11,11 +11,6 @@ import { globby } from "globby"; import glslStripComments from "glsl-strip-comments"; import gulp from "gulp"; import { rimraf } from "rimraf"; -import { rollup } from "rollup"; -import rollupPluginStripPragma from "rollup-plugin-strip-pragma"; -import terser from "@rollup/plugin-terser"; -import rollupCommonjs from "@rollup/plugin-commonjs"; -import rollupResolve from "@rollup/plugin-node-resolve"; import streamToPromise from "stream-to-promise"; import { mkdirp } from "mkdirp"; @@ -105,10 +100,7 @@ function printBuildWarning({ location, text }) { // Ignore `eval` warnings in third-party code we don't have control over function handleBuildWarnings(result) { for (const warning of result.warnings) { - if ( - !warning.location.file.includes("protobufjs.js") && - !warning.location.file.includes("Build/Cesium") - ) { + if (!warning.location.file.includes("protobufjs.js")) { printBuildWarning(warning); } } @@ -204,6 +196,9 @@ export async function bundleCesiumJs(options) { format: "iife", globalName: "Cesium", outfile: path.join(options.path, "Cesium.js"), + logOverride: { + "empty-import-meta": "silent", + }, }); if (incremental) { @@ -218,6 +213,9 @@ export async function bundleCesiumJs(options) { ...buildConfig, format: "cjs", platform: "node", + logOverride: { + "empty-import-meta": "silent", + }, define: { // TransformStream is a browser-only implementation depended on by zip.js TransformStream: "null", @@ -244,9 +242,8 @@ const workspaceSourceFiles = { "packages/engine/Source/**/*.js", "!packages/engine/Source/*.js", "!packages/engine/Source/Workers/**", - "!packages/engine/Source/WorkersES6/**", - "packages/engine/Source/WorkersES6/createTaskProcessorWorker.js", - "!packages/engine/Source/ThirdParty/Workers/**", + "packages/engine/Source/Workers/createTaskProcessorWorker.js", + "!packages/engine/Source/ThirdParty/Workers/**.js", "!packages/engine/Source/ThirdParty/google-earth-dbroot-parser.js", "!packages/engine/Source/ThirdParty/_*", ], @@ -320,39 +317,20 @@ export async function createCombinedSpecList() { return contents; } -function rollupWarning(message) { - // Ignore eval warnings in third-party code we don't have control over - if (message.code === "EVAL" && /protobufjs/.test(message.loc.file)) { - return; - } - - console.log(message); -} - /** * @param {object} options + * @param {string} options.path output directory * @param {boolean} [options.minify=false] true if the worker output should be minified * @param {boolean} [options.removePragmas=false] true if debug pragma should be removed * @param {boolean} [options.sourcemap=false] true if an external sourcemap should be generated - * @param {string} options.path output directory + * @param {boolean} [options.incremental=false] true if build output should be cached for repeated builds + * @param {boolean} [options.write=true] true if build output should be written to disk. If false, the files that would have been written as in-memory buffers */ -export async function bundleCombinedWorkers(options) { - // Bundle non ES6 workers. - const workers = await globby(["packages/engine/Source/Workers/**"]); - const workerConfig = defaultESBuildOptions(); - workerConfig.bundle = false; - workerConfig.banner = { - js: combinedCopyrightHeader, - }; - workerConfig.entryPoints = workers; - workerConfig.outdir = options.path; - workerConfig.minify = options.minify; - workerConfig.outbase = "packages/engine/Source"; - await esbuild.build(workerConfig); - +export async function bundleWorkers(options) { // Copy ThirdParty workers const thirdPartyWorkers = await globby([ - "packages/engine/Source/ThirdParty/Workers/**", + "packages/engine/Source/ThirdParty/Workers/**.js", + "!packages/engine/Source/ThirdParty/Workers/basis_transcoder.js", ]); const thirdPartyWorkerConfig = defaultESBuildOptions(); @@ -363,96 +341,29 @@ export async function bundleCombinedWorkers(options) { thirdPartyWorkerConfig.outbase = "packages/engine/Source"; await esbuild.build(thirdPartyWorkerConfig); - // Bundle ES6 workers. - - const es6Workers = await globby([`packages/engine/Source/WorkersES6/*.js`]); - const plugins = [rollupResolve({ preferBuiltins: true }), rollupCommonjs()]; - - if (options.removePragmas) { - plugins.push( - rollupPluginStripPragma({ - pragmas: ["debug"], - }) - ); - } - - if (options.minify) { - plugins.push(terser()); - } - - const bundle = await rollup({ - input: es6Workers, - plugins: plugins, - onwarn: rollupWarning, - }); - - return bundle.write({ - dir: path.join(options.path, "Workers"), - format: "amd", - // Rollup cannot generate a sourcemap when pragmas are removed - sourcemap: options.sourcemap && !options.removePragmas, - // SAMTODO: Add copyrightBanner - }); -} - -/** - * Bundles the workers and outputs the result to the specified directory - * @param {object} options - * @param {boolean} [options.minify=false] true if the worker output should be minified - * @param {boolean} [options.removePragmas=false] true if debug pragma should be removed - * @param {boolean} [options.sourcemap=false] true if an external sourcemap should be generated - * @param {string[]} options.input The worker globs. - * @param {string[]} options.inputES6 The ES6 worker globs. - * @param {string} options.path output directory - * @param {string} options.copyrightHeader The copyright header to add to worker bundles - * @returns {Promise} - */ -export async function bundleWorkers(options) { - // Copy existing workers - const workers = await globby(options.input); - + // Bundle Cesium workers + const workers = await globby(["packages/engine/Source/Workers/**"]); const workerConfig = defaultESBuildOptions(); - workerConfig.bundle = false; + workerConfig.bundle = true; + workerConfig.format = "esm"; + workerConfig.splitting = true; workerConfig.banner = { js: combinedCopyrightHeader, }; + workerConfig.treeShaking = true; // Tree shaking must be turned on manually for ESM workerConfig.entryPoints = workers; - workerConfig.outdir = options.path; - workerConfig.outbase = `packages/engine/Source`; // Maintain existing file paths + workerConfig.outdir = path.join(options.path, "Workers"); workerConfig.minify = options.minify; - await esbuild.build(workerConfig); - - // Use rollup to build the workers: - // 1) They can be built as AMD style modules - // 2) They can be built using code-splitting, resulting in smaller modules - const files = await globby(options.inputES6); - const plugins = [rollupResolve({ preferBuiltins: true }), rollupCommonjs()]; - - if (options.removePragmas) { - plugins.push( - rollupPluginStripPragma({ - pragmas: ["debug"], - }) - ); - } + workerConfig.external = ["http", "https", "url", "zlib", "fs", "path"]; + workerConfig.write = options.write; - if (options.minify) { - plugins.push(terser()); + const incremental = options.incremental; + let build = esbuild.build; + if (incremental) { + build = esbuild.context; } - const bundle = await rollup({ - input: files, - plugins: plugins, - onwarn: rollupWarning, - }); - - return bundle.write({ - dir: path.join(options.path, "Workers"), - format: "amd", - // Rollup cannot generate a sourcemap when pragmas are removed - sourcemap: options.sourcemap && !options.removePragmas, - banner: options.copyrightHeader, - }); + return build(workerConfig); } const shaderFiles = [ @@ -754,7 +665,6 @@ export async function copyFiles(globs, destination, base) { export async function copyEngineAssets(destination) { const engineStaticAssets = [ "packages/engine/Source/**", - "!packages/engine/Source/Workers/package.json", "!packages/engine/Source/**/*.js", "!packages/engine/Source/**/*.glsl", "!packages/engine/Source/**/*.css", @@ -838,7 +748,6 @@ export function bundleCombinedSpecs(options) { bundle: true, format: "esm", sourcemap: true, - target: "es2020", outdir: path.join("Build", "Specs"), plugins: [externalResolvePlugin], external: [`http`, `https`, `url`, `zlib`], @@ -1013,8 +922,7 @@ export const buildEngine = async (options) => { // Build workers. await bundleWorkers({ - input: ["packages/engine/Source/Workers/**"], - inputES6: ["packages/engine/Source/WorkersES6/*.js"], + ...options, path: "packages/engine/Build", }); @@ -1145,16 +1053,16 @@ export async function buildCesium(options) { write: write, }); - await Promise.all([ - createJsHintOptions(), - bundleCombinedWorkers({ - minify: minify, - sourcemap: sourcemap, - path: outputDirectory, - removePragmas: removePragmas, - }), - createGalleryList(!development), - ]); + await Promise.all([createJsHintOptions(), createGalleryList(!development)]); + + const workersContext = await bundleWorkers({ + minify: minify, + sourcemap: sourcemap, + path: outputDirectory, + removePragmas: removePragmas, + incremental: incremental, + write: write, + }); // Generate Specs bundle. const specsContext = await bundleCombinedSpecs({ @@ -1204,5 +1112,6 @@ export async function buildCesium(options) { iife: contexts.iife, node: contexts.node, specs: specsContext, + workers: workersContext, }; } diff --git a/gulpfile.js b/gulpfile.js index a55506e6e6c9..a27334667878 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -47,7 +47,6 @@ import { createCombinedSpecList, createJsHintOptions, defaultESBuildOptions, - bundleCombinedWorkers, } from "./build.js"; // Determines the scope of the workspace packages. If the scope is set to cesium, the workspaces should be @cesium/engine. @@ -82,15 +81,11 @@ const sourceFiles = [ "packages/widgets/Source/**/*.js", "!packages/widgets/Source/*.js", "!packages/engine/Source/Shaders/**", - "!packages/engine/Source/Workers/**", - "!packages/engine/Source/WorkersES6/**", - "packages/engine/Source/WorkersES6/createTaskProcessorWorker.js", "!packages/engine/Source/ThirdParty/Workers/**", "!packages/engine/Source/ThirdParty/google-earth-dbroot-parser.js", "!packages/engine/Source/ThirdParty/_*", ]; -const workerSourceFiles = ["packages/engine/Source/WorkersES6/**"]; const watchedSpecFiles = [ "packages/engine/Specs/**/*Spec.js", "!packages/engine/Specs/SpecList.js", @@ -214,6 +209,13 @@ export const buildWatch = gulp.series(build, async function () { if (cjs) { await cjs.rebuild(); } + + await bundleWorkers({ + minify: minify, + path: outputDirectory, + removePragmas: removePragmas, + sourcemap: sourcemap, + }); } ); @@ -238,15 +240,6 @@ export const buildWatch = gulp.series(build, async function () { } ); - gulp.watch(workerSourceFiles, () => { - return bundleCombinedWorkers({ - minify: minify, - path: outputDirectory, - removePragmas: removePragmas, - sourcemap: sourcemap, - }); - }); - process.on("SIGINT", () => { // Free up resources esm.dispose(); @@ -308,10 +301,6 @@ export function buildApps() { const filesToClean = [ "Source/Cesium.js", "Source/Shaders/**/*.js", - "Source/Workers/**", - "!Source/Workers/cesiumWorkerBootstrapper.js", - "!Source/Workers/transferTypedArrayTest.js", - "!Source/Workers/package.json", "Source/ThirdParty/Shaders/*.js", "Source/**/*.d.ts", "Specs/SpecList.js", @@ -372,10 +361,6 @@ async function clocSource() { export async function prepare() { // Copy Draco3D files from node_modules into Source - copyFileSync( - "node_modules/draco3d/draco_decoder_nodejs.js", - "packages/engine/Source/ThirdParty/Workers/draco_decoder_nodejs.js" - ); copyFileSync( "node_modules/draco3d/draco_decoder.wasm", "packages/engine/Source/ThirdParty/draco_decoder.wasm" @@ -2253,11 +2238,8 @@ async function buildCesiumViewer() { }); await bundleWorkers({ - input: [ - "packages/engine/Source/Workers/**", - "packages/engine/Source/ThirdParty/Workers/**", - ], - inputES6: ["packages/engine/Source/WorkersES6/*.js"], + minify: true, + removePragmas: true, path: cesiumViewerOutputDirectory, }); diff --git a/package.json b/package.json index c9b69d2fb963..a729fee7b145 100644 --- a/package.json +++ b/package.json @@ -57,15 +57,11 @@ "devDependencies": { "@aws-sdk/client-s3": "^3.342.0", "@aws-sdk/lib-storage": "^3.342.0", - "@rollup/plugin-commonjs": "^25.0.0", - "@rollup/plugin-node-resolve": "^15.1.0", - "@rollup/plugin-terser": "^0.4.0", "chokidar": "^3.5.3", "cloc": "^2.8.0", "compression": "^1.7.4", "decompress": "^4.2.1", "download": "^8.0.0", - "draco3d": "^1.5.1", "esbuild": "^0.17.10", "eslint": "^8.41.0", "eslint-config-cesium": "^9.0.1", @@ -110,8 +106,6 @@ "prismjs": "^1.28.0", "request": "^2.79.0", "rimraf": "^5.0.0", - "rollup": "^3.23.0", - "rollup-plugin-strip-pragma": "^1.0.0", "stream-to-promise": "^3.0.0", "tsd-jsdoc": "^2.5.0", "typescript": "^5.0.2", diff --git a/packages/engine/.gitignore b/packages/engine/.gitignore index 58c6a285fcea..5eb1f9b8e9cc 100644 --- a/packages/engine/.gitignore +++ b/packages/engine/.gitignore @@ -9,8 +9,4 @@ Source/ThirdParty/draco_decoder.wasm Source/ThirdParty/Workers/draco_decoder_nodejs.js Source/ThirdParty/Workers/pako_inflate.min.js Source/ThirdParty/Workers/pako_deflate.min.js -Source/ThirdParty/Workers/z-worker-pako.js -Source/Workers/** -!Source/Workers/cesiumWorkerBootstrapper.js -!Source/Workers/transferTypedArrayTest.js -!Source/Workers/package.json \ No newline at end of file +Source/ThirdParty/Workers/z-worker-pako.js \ No newline at end of file diff --git a/packages/engine/LICENSE.md b/packages/engine/LICENSE.md index 7a9866455fb1..7c3383354f82 100644 --- a/packages/engine/LICENSE.md +++ b/packages/engine/LICENSE.md @@ -270,18 +270,6 @@ https://github.com/sole/tween.js > > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -### RequireJS - -https://github.com/jrburke/requirejs - -> Copyright (c) 2010-2015, The Dojo Foundation -> -> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ### topojson-client https://github.com/topojson/topojson-client diff --git a/packages/engine/Source/Core/FeatureDetection.js b/packages/engine/Source/Core/FeatureDetection.js index e7f41884fe42..795f79e34e4b 100644 --- a/packages/engine/Source/Core/FeatureDetection.js +++ b/packages/engine/Source/Core/FeatureDetection.js @@ -426,4 +426,13 @@ FeatureDetection.supportsWebgl2 = function (scene) { return scene.context.webgl2; }; +/** + * Detects whether the current browser supports ECMAScript modules in web workers. + * @returns {boolean} true if the browser supports ECMAScript modules in web workers. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Worker|Worker} + */ +FeatureDetection.supportsEsmWebWorkers = function () { + return !isFirefox() || parseInt(firefoxVersionResult) >= 114; +}; + export default FeatureDetection; diff --git a/packages/engine/Source/Core/KTX2Transcoder.js b/packages/engine/Source/Core/KTX2Transcoder.js index 1eb0a51c440b..638805d9e93b 100644 --- a/packages/engine/Source/Core/KTX2Transcoder.js +++ b/packages/engine/Source/Core/KTX2Transcoder.js @@ -1,6 +1,7 @@ import Check from "./Check.js"; import CompressedTextureBuffer from "./CompressedTextureBuffer.js"; import defined from "./defined.js"; +import RuntimeError from "./RuntimeError.js"; import TaskProcessor from "./TaskProcessor.js"; /** @@ -20,11 +21,14 @@ KTX2Transcoder._readyPromise = undefined; function makeReadyPromise() { const readyPromise = KTX2Transcoder._transcodeTaskProcessor .initWebAssemblyModule({ - modulePath: "ThirdParty/Workers/basis_transcoder.js", wasmBinaryFile: "ThirdParty/basis_transcoder.wasm", }) - .then(function () { - return KTX2Transcoder._transcodeTaskProcessor; + .then(function (message) { + if (message.result) { + return KTX2Transcoder._transcodeTaskProcessor; + } + + throw new RuntimeError("KTX2 transcoder could not be initialized."); }); KTX2Transcoder._readyPromise = readyPromise; } diff --git a/packages/engine/Source/Core/TaskProcessor.js b/packages/engine/Source/Core/TaskProcessor.js index 699aaa136537..4884834bde18 100644 --- a/packages/engine/Source/Core/TaskProcessor.js +++ b/packages/engine/Source/Core/TaskProcessor.js @@ -1,7 +1,6 @@ import Uri from "urijs"; import buildModuleUrl from "./buildModuleUrl.js"; import defaultValue from "./defaultValue.js"; -import defer from "./defer.js"; import defined from "./defined.js"; import destroyObject from "./destroyObject.js"; import DeveloperError from "./DeveloperError.js"; @@ -38,23 +37,21 @@ function canTransferArrayBuffer() { return TaskProcessor._canTransferArrayBuffer; } - const deferred = defer(); - - worker.onmessage = function (event) { - const array = event.data.array; - - // some versions of Firefox silently fail to transfer typed arrays. - // https://bugzilla.mozilla.org/show_bug.cgi?id=841904 - // Check to make sure the value round-trips successfully. - const result = defined(array) && array[0] === value; - deferred.resolve(result); + TaskProcessor._canTransferArrayBuffer = new Promise((resolve) => { + worker.onmessage = function (event) { + const array = event.data.array; - worker.terminate(); + // some versions of Firefox silently fail to transfer typed arrays. + // https://bugzilla.mozilla.org/show_bug.cgi?id=841904 + // Check to make sure the value round-trips successfully. + const result = defined(array) && array[0] === value; + resolve(result); - TaskProcessor._canTransferArrayBuffer = result; - }; + worker.terminate(); - TaskProcessor._canTransferArrayBuffer = deferred.promise; + TaskProcessor._canTransferArrayBuffer = result; + }; + }); } return TaskProcessor._canTransferArrayBuffer; @@ -62,37 +59,6 @@ function canTransferArrayBuffer() { const taskCompletedEvent = new Event(); -function completeTask(processor, data) { - --processor._activeTasks; - - const id = data.id; - if (!defined(id)) { - // This is not one of ours. - return; - } - - const deferreds = processor._deferreds; - const deferred = deferreds[id]; - - if (defined(data.error)) { - let error = data.error; - if (error.name === "RuntimeError") { - error = new RuntimeError(data.error.message); - error.stack = data.error.stack; - } else if (error.name === "DeveloperError") { - error = new DeveloperError(data.error.message); - error.stack = data.error.stack; - } - taskCompletedEvent.raiseEvent(error); - deferred.reject(error); - } else { - taskCompletedEvent.raiseEvent(); - deferred.resolve(data.result); - } - - delete deferreds[id]; -} - function getWorkerUrl(moduleID) { let url = buildModuleUrl(moduleID); @@ -123,40 +89,16 @@ function getWorkerUrl(moduleID) { return url; } -let bootstrapperUrlResult; -function getBootstrapperUrl() { - if (!defined(bootstrapperUrlResult)) { - bootstrapperUrlResult = getWorkerUrl("Workers/cesiumWorkerBootstrapper.js"); - } - return bootstrapperUrlResult; -} - function createWorker(processor) { - const worker = new Worker(getBootstrapperUrl()); - worker.postMessage = defaultValue( - worker.webkitPostMessage, - worker.postMessage - ); - - const bootstrapMessage = { - loaderConfig: { - paths: { - Workers: buildModuleUrl("Workers"), - }, - baseUrl: buildModuleUrl.getCesiumBaseUrl().url, - }, - workerModule: processor._workerPath, - }; - - worker.postMessage(bootstrapMessage); - worker.onmessage = function (event) { - completeTask(processor, event.data); - }; - - return worker; + if (!FeatureDetection.supportsEsmWebWorkers()) { + throw new RuntimeError( + "This browser is not supported. Please update your browser to continue." + ); + } + return new Worker(processor._workerPath, { type: "module" }); } -function getWebAssemblyLoaderConfig(processor, wasmOptions) { +async function getWebAssemblyLoaderConfig(processor, wasmOptions) { const config = { modulePath: undefined, wasmBinaryFile: undefined, @@ -172,18 +114,18 @@ function getWebAssemblyLoaderConfig(processor, wasmOptions) { } config.modulePath = buildModuleUrl(wasmOptions.fallbackModulePath); - return Promise.resolve(config); + return config; } config.modulePath = buildModuleUrl(wasmOptions.modulePath); config.wasmBinaryFile = buildModuleUrl(wasmOptions.wasmBinaryFile); - return Resource.fetchArrayBuffer({ + const arrayBuffer = await Resource.fetchArrayBuffer({ url: config.wasmBinaryFile, - }).then(function (arrayBuffer) { - config.wasmBinary = arrayBuffer; - return config; }); + + config.wasmBinary = arrayBuffer; + return config; } /** @@ -202,20 +144,88 @@ function getWebAssemblyLoaderConfig(processor, wasmOptions) { */ function TaskProcessor(workerPath, maximumActiveTasks) { const uri = new Uri(workerPath); - this._workerPath = - uri.scheme().length !== 0 && uri.fragment().length === 0 - ? workerPath - : TaskProcessor._workerModulePrefix + workerPath; + const isUri = uri.scheme().length !== 0 && uri.fragment().length === 0; + this._workerPath = isUri + ? workerPath + : getWorkerUrl(`${TaskProcessor._workerModulePrefix + workerPath}.js`); this._maximumActiveTasks = defaultValue( maximumActiveTasks, Number.POSITIVE_INFINITY ); this._activeTasks = 0; - this._deferreds = {}; this._nextID = 0; + this._webAssemblyPromise = undefined; } +const createOnmessageHandler = (worker, id, resolve, reject) => { + const listener = ({ data }) => { + if (data.id !== id) { + return; + } + + if (defined(data.error)) { + let error = data.error; + if (error.name === "RuntimeError") { + error = new RuntimeError(data.error.message); + error.stack = data.error.stack; + } else if (error.name === "DeveloperError") { + error = new DeveloperError(data.error.message); + error.stack = data.error.stack; + } + taskCompletedEvent.raiseEvent(error); + reject(error); + } else { + taskCompletedEvent.raiseEvent(); + resolve(data.result); + } + + worker.removeEventListener("message", listener); + }; + + return listener; +}; + const emptyTransferableObjectArray = []; +async function runTask(processor, parameters, transferableObjects) { + const canTransfer = await Promise.resolve(canTransferArrayBuffer()); + if (!defined(transferableObjects)) { + transferableObjects = emptyTransferableObjectArray; + } else if (!canTransfer) { + transferableObjects.length = 0; + } + + const id = processor._nextID++; + const promise = new Promise((resolve, reject) => { + processor._worker.addEventListener( + "message", + createOnmessageHandler(processor._worker, id, resolve, reject) + ); + }); + + processor._worker.postMessage( + { + id: id, + parameters: parameters, + canTransferArrayBuffer: canTransfer, + }, + transferableObjects + ); + + return promise; +} + +async function scheduleTask(processor, parameters, transferableObjects) { + ++processor._activeTasks; + + try { + const result = await runTask(processor, parameters, transferableObjects); + --processor._activeTasks; + return result; + } catch (error) { + --processor._activeTasks; + throw error; + } +} /** * Schedule a task to be processed by the web worker asynchronously. If there are currently more @@ -255,38 +265,12 @@ TaskProcessor.prototype.scheduleTask = function ( return undefined; } - ++this._activeTasks; - - const processor = this; - return Promise.resolve(canTransferArrayBuffer()).then(function ( - canTransferArrayBuffer - ) { - if (!defined(transferableObjects)) { - transferableObjects = emptyTransferableObjectArray; - } else if (!canTransferArrayBuffer) { - transferableObjects.length = 0; - } - - const id = processor._nextID++; - const deferred = defer(); - processor._deferreds[id] = deferred; - - processor._worker.postMessage( - { - id: id, - parameters: parameters, - canTransferArrayBuffer: canTransferArrayBuffer, - }, - transferableObjects - ); - - return deferred.promise; - }); + return scheduleTask(this, parameters, transferableObjects); }; /** * Posts a message to a web worker with configuration to initialize loading - * and compiling a web assembly module asychronously, as well as an optional + * and compiling a web assembly module asynchronously, as well as an optional * fallback JavaScript module to use if Web Assembly is not supported. * * @param {object} [webAssemblyOptions] An object with the following properties: @@ -294,43 +278,52 @@ TaskProcessor.prototype.scheduleTask = function ( * @param {string} [webAssemblyOptions.wasmBinaryFile] The path of the web assembly binary file. * @param {string} [webAssemblyOptions.fallbackModulePath] The path of the fallback JavaScript module to use if web assembly is not supported. * @returns {Promise} A promise that resolves to the result when the web worker has loaded and compiled the web assembly module and is ready to process tasks. + * + * @exception {RuntimeError} This browser does not support Web Assembly, and no backup module was provided */ -TaskProcessor.prototype.initWebAssemblyModule = function (webAssemblyOptions) { - if (!defined(this._worker)) { - this._worker = createWorker(this); +TaskProcessor.prototype.initWebAssemblyModule = async function ( + webAssemblyOptions +) { + if (defined(this._webAssemblyPromise)) { + return this._webAssemblyPromise; } - const deferred = defer(); - const processor = this; - const worker = this._worker; - getWebAssemblyLoaderConfig(this, webAssemblyOptions).then(function ( - wasmConfig - ) { - return Promise.resolve(canTransferArrayBuffer()).then(function ( - canTransferArrayBuffer - ) { - let transferableObjects; - const binary = wasmConfig.wasmBinary; - if (defined(binary) && canTransferArrayBuffer) { - transferableObjects = [binary]; - } - - worker.onmessage = function (event) { - worker.onmessage = function (event) { - completeTask(processor, event.data); - }; + const init = async () => { + const worker = (this._worker = createWorker(this)); + const wasmConfig = await getWebAssemblyLoaderConfig( + this, + webAssemblyOptions + ); + const canTransfer = await Promise.resolve(canTransferArrayBuffer()); + let transferableObjects; + const binary = wasmConfig.wasmBinary; + if (defined(binary) && canTransfer) { + transferableObjects = [binary]; + } - deferred.resolve(event.data); + const promise = new Promise((resolve, reject) => { + worker.onmessage = function ({ data }) { + if (data) { + resolve(data); + } else { + reject(new RuntimeError("Could not configure wasm module")); + } }; - - worker.postMessage( - { webAssemblyConfig: wasmConfig }, - transferableObjects - ); }); - }); - return deferred.promise; + worker.postMessage( + { + canTransferArrayBuffer: canTransfer, + parameters: { webAssemblyConfig: wasmConfig }, + }, + transferableObjects + ); + + return promise; + }; + + this._webAssemblyPromise = init(); + return this._webAssemblyPromise; }; /** diff --git a/packages/engine/Source/Core/buildModuleUrl.js b/packages/engine/Source/Core/buildModuleUrl.js index 90549e8323a5..b51aecff8942 100644 --- a/packages/engine/Source/Core/buildModuleUrl.js +++ b/packages/engine/Source/Core/buildModuleUrl.js @@ -21,7 +21,7 @@ function getBaseUrlFromCesiumScript() { let a; function tryMakeAbsolute(url) { if (typeof document === "undefined") { - //Node.js and Web Workers. In both cases, the URL will already be absolute. + // Node.js and Web Workers. In both cases, the URL will already be absolute. return url; } @@ -29,10 +29,6 @@ function tryMakeAbsolute(url) { a = document.createElement("a"); } a.href = url; - - // IE only absolutizes href on get, not set - // eslint-disable-next-line no-self-assign - a.href = a.href; return a.href; } @@ -45,17 +41,22 @@ function getCesiumBaseUrl() { let baseUrlString; if (typeof CESIUM_BASE_URL !== "undefined") { baseUrlString = CESIUM_BASE_URL; + } else if (defined(import.meta)) { + // ESM + baseUrlString = getAbsoluteUri(".", import.meta.url); } else if ( typeof define === "object" && defined(define.amd) && !define.amd.toUrlUndefined && defined(require.toUrl) ) { + // RequireJS baseUrlString = getAbsoluteUri( "..", buildModuleUrl("Core/buildModuleUrl.js") ); } else { + // IIFE baseUrlString = getBaseUrlFromCesiumScript(); } diff --git a/packages/engine/Source/Scene/DracoLoader.js b/packages/engine/Source/Scene/DracoLoader.js index 82901e159d7a..f6d034c11239 100644 --- a/packages/engine/Source/Scene/DracoLoader.js +++ b/packages/engine/Source/Scene/DracoLoader.js @@ -1,5 +1,6 @@ import defined from "../Core/defined.js"; import FeatureDetection from "../Core/FeatureDetection.js"; +import RuntimeError from "../Core/RuntimeError.js"; import TaskProcessor from "../Core/TaskProcessor.js"; /** @@ -16,6 +17,7 @@ DracoLoader._maxDecodingConcurrency = Math.max( // Exposed for testing purposes DracoLoader._decoderTaskProcessor = undefined; DracoLoader._taskProcessorReady = false; +DracoLoader._error = undefined; DracoLoader._getDecoderTaskProcessor = function () { if (!defined(DracoLoader._decoderTaskProcessor)) { const processor = new TaskProcessor( @@ -24,11 +26,19 @@ DracoLoader._getDecoderTaskProcessor = function () { ); processor .initWebAssemblyModule({ - modulePath: "ThirdParty/Workers/draco_decoder_nodejs.js", wasmBinaryFile: "ThirdParty/draco_decoder.wasm", }) - .then(function () { - DracoLoader._taskProcessorReady = true; + .then(function (message) { + if (message.result) { + DracoLoader._taskProcessorReady = true; + } else { + DracoLoader._error = new RuntimeError( + "Draco decoder could not be initialized." + ); + } + }) + .catch((error) => { + DracoLoader._error = error; }); DracoLoader._decoderTaskProcessor = processor; } @@ -39,9 +49,15 @@ DracoLoader._getDecoderTaskProcessor = function () { /** * Decodes a compressed point cloud. Returns undefined if the task cannot be scheduled. * @private + * + * @exception {RuntimeError} Draco decoder could not be initialized. */ DracoLoader.decodePointCloud = function (parameters) { const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor(); + if (defined(DracoLoader._error)) { + throw DracoLoader._error; + } + if (!DracoLoader._taskProcessorReady) { // The task processor is not ready to schedule tasks return; @@ -62,9 +78,16 @@ DracoLoader.decodePointCloud = function (parameters) { * * @returns {Promise} A promise that resolves to the decoded indices and attributes. * @private + * + * @exception {RuntimeError} Draco decoder could not be initialized. */ DracoLoader.decodeBufferView = function (options) { const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor(); + + if (defined(DracoLoader._error)) { + throw DracoLoader._error; + } + if (!DracoLoader._taskProcessorReady) { // The task processor is not ready to schedule tasks return; diff --git a/packages/engine/Source/Scene/I3SDataProvider.js b/packages/engine/Source/Scene/I3SDataProvider.js index 5b1d4527348d..6d4e7c2e297d 100644 --- a/packages/engine/Source/Scene/I3SDataProvider.js +++ b/packages/engine/Source/Scene/I3SDataProvider.js @@ -56,7 +56,6 @@ import destroyObject from "../Core/destroyObject.js"; import HeightmapEncoding from "../Core/HeightmapEncoding.js"; import Resource from "../Core/Resource.js"; import RuntimeError from "../Core/RuntimeError.js"; -import TaskProcessor from "../Core/TaskProcessor.js"; import WebMercatorProjection from "../Core/WebMercatorProjection.js"; import I3SLayer from "./I3SLayer.js"; import Lerc from "lerc"; @@ -583,32 +582,6 @@ I3SDataProvider.prototype._binarizeGltf = function (rawGltf) { return binaryGltfData; }; -/** - * @private - * @returns {Promise} - */ -I3SDataProvider.prototype.getDecoderTaskProcessor = function () { - if (defined(this._taskProcessorReadyPromise)) { - return this._taskProcessorReadyPromise; - } - - if (!defined(this._decoderTaskProcessor)) { - const processor = new TaskProcessor("decodeI3S"); - this._taskProcessorReadyPromise = processor - .initWebAssemblyModule({ - modulePath: "ThirdParty/Workers/draco_decoder_nodejs.js", - wasmBinaryFile: "ThirdParty/draco_decoder.wasm", - }) - .then(() => { - return processor; - }); - - this._decoderTaskProcessor = processor; - } - - return this._taskProcessorReadyPromise; -}; - function getCoveredTiles(terrainProvider, extent) { return getTiles(terrainProvider, extent); } diff --git a/packages/engine/Source/Scene/I3SDecoder.js b/packages/engine/Source/Scene/I3SDecoder.js new file mode 100644 index 000000000000..eeda42c43304 --- /dev/null +++ b/packages/engine/Source/Scene/I3SDecoder.js @@ -0,0 +1,127 @@ +import Cartographic from "../Core/Cartographic.js"; +import Check from "../Core/Check.js"; +import defined from "../Core/defined.js"; +import Ellipsoid from "../Core/Ellipsoid.js"; +import FeatureDetection from "../Core/FeatureDetection.js"; +import CesiumMath from "../Core/Math.js"; +import Matrix3 from "../Core/Matrix3.js"; +import RuntimeError from "../Core/RuntimeError.js"; +import TaskProcessor from "../Core/TaskProcessor.js"; + +/** + * Decode I3S using web workers. + * + * @private + */ +function I3SDecoder() {} + +// Maximum concurrency to use when decoding draco models +I3SDecoder._maxDecodingConcurrency = Math.max( + FeatureDetection.hardwareConcurrency - 1, + 1 +); + +I3SDecoder._decodeTaskProcessor = new TaskProcessor( + "decodeI3S", + I3SDecoder._maxDecodingConcurrency +); + +I3SDecoder._promise = undefined; + +async function initializeDecoder() { + const message = await I3SDecoder._decodeTaskProcessor.initWebAssemblyModule({ + wasmBinaryFile: "ThirdParty/draco_decoder.wasm", + }); + if (message.result) { + return I3SDecoder._decodeTaskProcessor; + } + + throw new RuntimeError("I3S decoder could not be initialized."); +} + +/** + * Transcodes I3S to glTF in a web worker + * @param {String} url custom attributes source URL + * @param {Object} defaultGeometrySchema Schema to use during decoding + * @param {Object} geometryData The draco encoded geometry data + * @param {Array} [featureData] The draco encoded feature data + * @returns Promise Returns a promise which resolves to the glTF result, or undefined if the task cannot be scheduled this frame. + * + * @exception {RuntimeError} I3S decoder could not be initialized. + */ +I3SDecoder.decode = async function ( + url, + defaultGeometrySchema, + geometryData, + featureData +) { + //>>includeStart('debug', pragmas.debug); + Check.typeOf.string("url", url); + Check.defined("defaultGeometrySchema", defaultGeometrySchema); + Check.defined("geometryData", geometryData); + //>>includeEnd('debug'); + + if (!defined(I3SDecoder._promise)) { + I3SDecoder._promise = initializeDecoder(); + } + + return I3SDecoder._promise.then(function (taskProcessor) { + // Prepare the data to send to the worker + const parentData = geometryData._parent._data; + const parentRotationInverseMatrix = + geometryData._parent._inverseRotationMatrix; + + let longitude = 0.0; + let latitude = 0.0; + let height = 0.0; + + if (defined(parentData.obb)) { + longitude = parentData.obb.center[0]; + latitude = parentData.obb.center[1]; + height = parentData.obb.center[2]; + } else if (defined(parentData.mbs)) { + longitude = parentData.mbs[0]; + latitude = parentData.mbs[1]; + height = parentData.mbs[2]; + } + + const axisFlipRotation = Matrix3.fromRotationX(-CesiumMath.PI_OVER_TWO); + const parentRotation = new Matrix3(); + + Matrix3.multiply( + axisFlipRotation, + parentRotationInverseMatrix, + parentRotation + ); + + const cartographicCenter = Cartographic.fromDegrees( + longitude, + latitude, + height + ); + + const cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian( + cartographicCenter + ); + + const payload = { + binaryData: geometryData._data, + featureData: + defined(featureData) && defined(featureData[0]) + ? featureData[0].data + : undefined, + schema: defaultGeometrySchema, + bufferInfo: geometryData._geometryBufferInfo, + ellipsoidRadiiSquare: Ellipsoid.WGS84.radiiSquared, + url: url, + geoidDataList: geometryData._dataProvider._geoidDataList, + cartographicCenter: cartographicCenter, + cartesianCenter: cartesianCenter, + parentRotation: parentRotation, + }; + + return taskProcessor.scheduleTask(payload); + }); +}; + +export default I3SDecoder; diff --git a/packages/engine/Source/Scene/I3SNode.js b/packages/engine/Source/Scene/I3SNode.js index 222f79ce7e59..9e09e569cb9a 100644 --- a/packages/engine/Source/Scene/I3SNode.js +++ b/packages/engine/Source/Scene/I3SNode.js @@ -3,7 +3,6 @@ import defaultValue from "../Core/defaultValue.js"; import defined from "../Core/defined.js"; import Ellipsoid from "../Core/Ellipsoid.js"; import HeadingPitchRoll from "../Core/HeadingPitchRoll.js"; -import CesiumMath from "../Core/Math.js"; import Matrix3 from "../Core/Matrix3.js"; import Matrix4 from "../Core/Matrix4.js"; import Resource from "../Core/Resource.js"; @@ -11,6 +10,7 @@ import Quaternion from "../Core/Quaternion.js"; import Transforms from "../Core/Transforms.js"; import Cesium3DTile from "./Cesium3DTile.js"; import I3SDataProvider from "./I3SDataProvider.js"; +import I3SDecoder from "./I3SDecoder.js"; import I3SFeature from "./I3SFeature.js"; import I3SField from "./I3SField.js"; import I3SGeometry from "./I3SGeometry.js"; @@ -608,71 +608,6 @@ I3SNode.prototype._create3DTileDefinition = function () { return inPlaceTileDefinition; }; -/** - * @private - */ -I3SNode.prototype._createI3SDecoderTask = async function ( - decodeI3STaskProcessor, - data -) { - // Prepare the data to send to the worker - const parentData = data.geometryData._parent._data; - const parentRotationInverseMatrix = - data.geometryData._parent._inverseRotationMatrix; - - let longitude = 0.0; - let latitude = 0.0; - let height = 0.0; - - if (defined(parentData.obb)) { - longitude = parentData.obb.center[0]; - latitude = parentData.obb.center[1]; - height = parentData.obb.center[2]; - } else if (defined(parentData.mbs)) { - longitude = parentData.mbs[0]; - latitude = parentData.mbs[1]; - height = parentData.mbs[2]; - } - - const axisFlipRotation = Matrix3.fromRotationX(-CesiumMath.PI_OVER_TWO); - const parentRotation = new Matrix3(); - - Matrix3.multiply( - axisFlipRotation, - parentRotationInverseMatrix, - parentRotation - ); - - const cartographicCenter = Cartographic.fromDegrees( - longitude, - latitude, - height - ); - - const cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian( - cartographicCenter - ); - - const payload = { - binaryData: data.geometryData._data, - featureData: - defined(data.featureData) && defined(data.featureData[0]) - ? data.featureData[0].data - : undefined, - schema: data.defaultGeometrySchema, - bufferInfo: data.geometryData._geometryBufferInfo, - ellipsoidRadiiSquare: Ellipsoid.WGS84.radiiSquared, - url: data.url, - geoidDataList: data.geometryData._dataProvider._geoidDataList, - cartographicCenter: cartographicCenter, - cartesianCenter: cartesianCenter, - parentRotation: parentRotation, - }; - - const transferrableObjects = []; - return decodeI3STaskProcessor.scheduleTask(payload, transferrableObjects); -}; - /** * @private */ @@ -702,59 +637,46 @@ I3SNode.prototype._createContentURL = async function () { }, }; - const decodeI3STaskProcessor = await this._dataProvider.getDecoderTaskProcessor(); - // Load the geometry data const dataPromises = [this._loadGeometryData()]; if (this._dataProvider.legacyVersion16) { dataPromises.push(this._loadFeatureData()); } - const that = this; - return Promise.all(dataPromises).then(function () { - // Binary glTF - let generateGltfPromise = Promise.resolve(); - if (defined(that._geometryData) && that._geometryData.length > 0) { - const parameters = { - geometryData: that._geometryData[0], - featureData: that._featureData, - defaultGeometrySchema: that._layer._data.store.defaultGeometrySchema, - url: that._geometryData[0].resource.url, - tile: that._tile, - }; - - const promise = that._createI3SDecoderTask( - decodeI3STaskProcessor, - parameters - ); - if (!defined(promise)) { - // Postponed - return; - } - - generateGltfPromise = promise.then(function (result) { - rawGltf = parameters.geometryData._generateGltf( - result.meshData.nodesInScene, - result.meshData.nodes, - result.meshData.meshes, - result.meshData.buffers, - result.meshData.bufferViews, - result.meshData.accessors - ); - - that._geometryData[0]._customAttributes = - result.meshData._customAttributes; - }); + await Promise.all(dataPromises); + // Binary glTF + if (defined(this._geometryData) && this._geometryData.length > 0) { + const url = this._geometryData[0].resource.url; + const geometrySchema = this._layer._data.store.defaultGeometrySchema; + const geometryData = this._geometryData[0]; + const result = await I3SDecoder.decode( + url, + geometrySchema, + geometryData, + this._featureData + ); + if (!defined(result)) { + // Postponed + return; } - return generateGltfPromise.then(function () { - const binaryGltfData = that._dataProvider._binarizeGltf(rawGltf); - const glbDataBlob = new Blob([binaryGltfData], { - type: "application/binary", - }); - return URL.createObjectURL(glbDataBlob); - }); + rawGltf = geometryData._generateGltf( + result.meshData.nodesInScene, + result.meshData.nodes, + result.meshData.meshes, + result.meshData.buffers, + result.meshData.bufferViews, + result.meshData.accessors + ); + + this._geometryData[0]._customAttributes = result.meshData._customAttributes; + } + + const binaryGltfData = this._dataProvider._binarizeGltf(rawGltf); + const glbDataBlob = new Blob([binaryGltfData], { + type: "application/binary", }); + return URL.createObjectURL(glbDataBlob); }; // Reimplement Cesium3DTile.prototype.requestContent so that diff --git a/packages/engine/Source/ThirdParty/Workers/basis_transcoder.js b/packages/engine/Source/ThirdParty/Workers/basis_transcoder.js index 7ad429d4a9a6..c81ab0778fcc 100644 --- a/packages/engine/Source/ThirdParty/Workers/basis_transcoder.js +++ b/packages/engine/Source/ThirdParty/Workers/basis_transcoder.js @@ -6,7 +6,7 @@ var BASIS = (function() { function(BASIS) { BASIS = BASIS || {}; -var Module=typeof BASIS!=="undefined"?BASIS:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseRejectza=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="basis_transcoder.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["K"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["O"];addOnInit(Module["asm"]["L"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){var result=WebAssembly.instantiate(binary,info);return result}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var structRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}else{return name}}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationGroup=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function attachFinalizer(handle){if("undefined"===typeof FinalizationGroup){attachFinalizer=function(handle){return handle};return handle}finalizationGroup=new FinalizationGroup(function(iter){for(var result=iter.next();!result.done;result=iter.next()){var $$=result.value;if(!$$.ptr){console.warn("object already deleted: "+$$.ptr)}else{releaseClassHandle($$)}}});attachFinalizer=function(handle){finalizationGroup.register(handle,handle.$$,handle.$$);return handle};detachFinalizer=function(handle){finalizationGroup.unregister(handle.$$)};return attachFinalizer(handle)}function ClassHandle_clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}}function ClassHandle_delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}}function ClassHandle_isDeleted(){return!this.$$.ptr}var delayFunction=undefined;var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}function ClassHandle_deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}var registeredPointers={};function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function exposePublicSymbol(name,value,numArguments){if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError("Cannot register public name '"+name+"' twice")}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError("Cannot register multiple overloads of a function with the same number of arguments ("+numArguments+")!")}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}function upcastPointer(ptr,ptrClass,desiredClass){while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError("Expected null or instance of "+desiredClass.name+", got an instance of "+ptrClass.name)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr}function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,__emval_register(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+handle.$$.ptrType.name+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function downcastPointer(ptr,ptrClass,desiredClass){if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)}function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function makeClassHandle(prototype,record){if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record}}))}function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["fromWireType"]=RegisteredPointer_fromWireType}function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}function dynCall(sig,ptr,args){if(sig.indexOf("j")!=-1){return dynCallLegacy(sig,ptr,args)}return wasmTable.get(ptr).apply(null,args)}function getDynCaller(sig,ptr){var argCache=[];return function(){argCache.length=arguments.length;for(var i=0;i>2)+i])}return array}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);var args=[rawConstructor];var destructors=[];whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName="constructor "+classType.name;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError("Cannot register multiple constructors with identical number of parameters ("+(argCount-1)+") for class '"+classType.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!")}classType.registeredClass.constructor_body[argCount-1]=function unboundTypeHandler(){throwUnboundTypeError("Cannot construct "+classType.name+" due to unbound types",rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){classType.registeredClass.constructor_body[argCount-1]=function constructor_body(){if(arguments.length!==argCount-1){throwBindingError(humanName+" called with "+arguments.length+" arguments, expected "+(argCount-1))}destructors.length=0;args.length=argCount;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i>1])};case 2:return function(pointer){var heap=signed?HEAP32:HEAPU32;return this["fromWireType"](heap[pointer>>2])};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_enum(rawType,name,size,isSigned){var shift=getShiftFromSize(size);name=readLatin1String(name);function ctor(){}ctor.values={};registerType(rawType,{name:name,constructor:ctor,"fromWireType":function(c){return this.constructor.values[c]},"toWireType":function(destructors,c){return c.value},"argPackAdvance":8,"readValueFromPointer":enumReadValueFromPointer(name,shift,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor)}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __embind_register_enum_value(rawEnumType,name,enumValue){var enumType=requireRegisteredType(rawEnumType,"enum");name=readLatin1String(name);var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(enumType.name+"_"+name,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value}function _embind_repr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function __embind_register_function(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn){var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=readLatin1String(name);rawInvoker=embind__requireFunction(signature,rawInvoker);exposePublicSymbol(name,function(){throwUnboundTypeError("Cannot call "+name+" due to unbound types",argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn),argCount-1);return[]})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=function(value){return value};if(minRange===0){var bitshift=32-8*size;fromWireType=function(value){return value<>>bitshift}}var isUnsignedType=name.indexOf("unsigned")!=-1;registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}if(valuemaxRange){throw new TypeError('Passing a number "'+_embind_repr(value)+'" from JS side to C/C++ side to an argument of type "'+name+'", which is outside the valid range ['+minRange+", "+maxRange+"]!")}return isUnsignedType?value>>>0:value|0},"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var str;if(stdStringIsUTF8){var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr+4,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+4+i]=charCode}}else{for(var i=0;i>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value==="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_object(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){structRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}}function __embind_register_value_object_field(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireHandle(handle){if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value}function __emval_as(handle,returnType,destructorsRef){handle=requireHandle(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=__emval_register(destructors);HEAP32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}else{return symbol}}var emval_methodCallers=[];function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=requireHandle(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function emval_get_global(){if(typeof globalThis==="object"){return globalThis}return function(){return Function}()("return this")()}function __emval_get_global(name){if(name===0){return __emval_register(emval_get_global())}else{name=getStringOrSymbol(name);return __emval_register(emval_get_global()[name])}}function __emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function __emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2)+i],"parameter "+i)}return a}function __emval_get_method_caller(argCount,argTypes){var types=__emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function craftEmvalAllocator(argCount){var argsList="";for(var i=0;i>> 2) + "+i+'], "parameter '+i+'");\n'+"var arg"+i+" = argType"+i+".readValueFromPointer(args);\n"+"args += argType"+i+"['argPackAdvance'];\n"}functionBody+="var obj = new constructor("+argsList+");\n"+"return __emval_register(obj);\n"+"}\n";return new Function("requireRegisteredType","Module","__emval_register",functionBody)(requireRegisteredType,Module,__emval_register)}var emval_newers={};function __emval_new(handle,argCount,argTypes,args){handle=requireHandle(handle);var newer=emval_newers[argCount];if(!newer){newer=craftEmvalAllocator(argCount);emval_newers[argCount]=newer}return newer(handle,argTypes,args)}function __emval_new_cstring(v){return __emval_register(getStringOrSymbol(v))}function __emval_run_destructors(handle){var destructors=emval_handle_array[handle].value;runDestructors(destructors);__emval_decref(handle)}function _abort(){abort()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j>2]=num;return 0}function _setTempRet0($i){setTempRet0($i|0)}InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_RegisteredPointer();init_embind();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();var asmLibraryArg={"t":__embind_finalize_value_object,"I":__embind_register_bool,"x":__embind_register_class,"w":__embind_register_class_constructor,"d":__embind_register_class_function,"k":__embind_register_constant,"H":__embind_register_emval,"n":__embind_register_enum,"a":__embind_register_enum_value,"A":__embind_register_float,"i":__embind_register_function,"j":__embind_register_integer,"h":__embind_register_memory_view,"B":__embind_register_std_string,"v":__embind_register_std_wstring,"u":__embind_register_value_object,"c":__embind_register_value_object_field,"J":__embind_register_void,"m":__emval_as,"s":__emval_call_void_method,"b":__emval_decref,"y":__emval_get_global,"p":__emval_get_method_caller,"r":__emval_get_module_property,"e":__emval_get_property,"g":__emval_incref,"q":__emval_new,"f":__emval_new_cstring,"l":__emval_run_destructors,"o":_abort,"E":_emscripten_memcpy_big,"F":_emscripten_resize_heap,"G":_fd_close,"C":_fd_seek,"z":_fd_write,"D":_setTempRet0};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["L"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["M"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["N"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["P"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["Q"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["R"]).apply(null,arguments)};var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run(); +var Module=typeof BASIS!=="undefined"?BASIS:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="basis_transcoder.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["K"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["O"];addOnInit(Module["asm"]["L"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){var result=WebAssembly.instantiate(binary,info);return result}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var structRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}else{return name}}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationGroup=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function attachFinalizer(handle){if("undefined"===typeof FinalizationGroup){attachFinalizer=function(handle){return handle};return handle}finalizationGroup=new FinalizationGroup(function(iter){for(var result=iter.next();!result.done;result=iter.next()){var $$=result.value;if(!$$.ptr){console.warn("object already deleted: "+$$.ptr)}else{releaseClassHandle($$)}}});attachFinalizer=function(handle){finalizationGroup.register(handle,handle.$$,handle.$$);return handle};detachFinalizer=function(handle){finalizationGroup.unregister(handle.$$)};return attachFinalizer(handle)}function ClassHandle_clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}}function ClassHandle_delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}}function ClassHandle_isDeleted(){return!this.$$.ptr}var delayFunction=undefined;var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}function ClassHandle_deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}var registeredPointers={};function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function exposePublicSymbol(name,value,numArguments){if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError("Cannot register public name '"+name+"' twice")}ensureOverloadTable(Module,name,name);if(Module.hasOwnProperty(numArguments)){throwBindingError("Cannot register multiple overloads of a function with the same number of arguments ("+numArguments+")!")}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}function upcastPointer(ptr,ptrClass,desiredClass){while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError("Expected null or instance of "+desiredClass.name+", got an instance of "+ptrClass.name)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr}function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError("Cannot convert argument of type "+(handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name)+" to parameter type "+this.name)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,__emval_register(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError("null is not a valid "+this.name)}return 0}if(!handle.$$){throwBindingError('Cannot pass "'+_embind_repr(handle)+'" as a '+this.name)}if(!handle.$$.ptr){throwBindingError("Cannot pass deleted object as a pointer of type "+this.name)}if(handle.$$.ptrType.isConst){throwBindingError("Cannot convert argument of type "+handle.$$.ptrType.name+" to parameter type "+this.name)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function downcastPointer(ptr,ptrClass,desiredClass){if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)}function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function makeClassHandle(prototype,record){if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record}}))}function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr:ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["fromWireType"]=RegisteredPointer_fromWireType}function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this["toWireType"]=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this["toWireType"]=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this["toWireType"]=genericPointerToWireType}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}function dynCall(sig,ptr,args){if(sig.indexOf("j")!=-1){return dynCallLegacy(sig,ptr,args)}return wasmTable.get(ptr).apply(null,args)}function getDynCaller(sig,ptr){var argCache=[];return function(){argCache.length=arguments.length;for(var i=0;i>2)+i])}return array}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);var args=[rawConstructor];var destructors=[];whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName="constructor "+classType.name;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError("Cannot register multiple constructors with identical number of parameters ("+(argCount-1)+") for class '"+classType.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!")}classType.registeredClass.constructor_body[argCount-1]=function unboundTypeHandler(){throwUnboundTypeError("Cannot construct "+classType.name+" due to unbound types",rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){classType.registeredClass.constructor_body[argCount-1]=function constructor_body(){if(arguments.length!==argCount-1){throwBindingError(humanName+" called with "+arguments.length+" arguments, expected "+(argCount-1))}destructors.length=0;args.length=argCount;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i>1])};case 2:return function(pointer){var heap=signed?HEAP32:HEAPU32;return this["fromWireType"](heap[pointer>>2])};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_enum(rawType,name,size,isSigned){var shift=getShiftFromSize(size);name=readLatin1String(name);function ctor(){}ctor.values={};registerType(rawType,{name:name,constructor:ctor,"fromWireType":function(c){return this.constructor.values[c]},"toWireType":function(destructors,c){return c.value},"argPackAdvance":8,"readValueFromPointer":enumReadValueFromPointer(name,shift,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor)}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __embind_register_enum_value(rawEnumType,name,enumValue){var enumType=requireRegisteredType(rawEnumType,"enum");name=readLatin1String(name);var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(enumType.name+"_"+name,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value}function _embind_repr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function __embind_register_function(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn){var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=readLatin1String(name);rawInvoker=embind__requireFunction(signature,rawInvoker);exposePublicSymbol(name,function(){throwUnboundTypeError("Cannot call "+name+" due to unbound types",argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn),argCount-1);return[]})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=function(value){return value};if(minRange===0){var bitshift=32-8*size;fromWireType=function(value){return value<>>bitshift}}var isUnsignedType=name.indexOf("unsigned")!=-1;registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}if(valuemaxRange){throw new TypeError('Passing a number "'+_embind_repr(value)+'" from JS side to C/C++ side to an argument of type "'+name+'", which is outside the valid range ['+minRange+", "+maxRange+"]!")}return isUnsignedType?value>>>0:value|0},"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var str;if(stdStringIsUTF8){var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr+4,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+4+i]=charCode}}else{for(var i=0;i>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value==="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_object(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){structRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}}function __embind_register_value_object_field(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireHandle(handle){if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value}function __emval_as(handle,returnType,destructorsRef){handle=requireHandle(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=__emval_register(destructors);HEAP32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}else{return symbol}}var emval_methodCallers=[];function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=requireHandle(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function emval_get_global(){if(typeof globalThis==="object"){return globalThis}return function(){return Function}()("return this")()}function __emval_get_global(name){if(name===0){return __emval_register(emval_get_global())}else{name=getStringOrSymbol(name);return __emval_register(emval_get_global()[name])}}function __emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function __emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2)+i],"parameter "+i)}return a}function __emval_get_method_caller(argCount,argTypes){var types=__emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function craftEmvalAllocator(argCount){var argsList="";for(var i=0;i>> 2) + "+i+'], "parameter '+i+'");\n'+"var arg"+i+" = argType"+i+".readValueFromPointer(args);\n"+"args += argType"+i+"['argPackAdvance'];\n"}functionBody+="var obj = new constructor("+argsList+");\n"+"return __emval_register(obj);\n"+"}\n";return new Function("requireRegisteredType","Module","__emval_register",functionBody)(requireRegisteredType,Module,__emval_register)}var emval_newers={};function __emval_new(handle,argCount,argTypes,args){handle=requireHandle(handle);var newer=emval_newers[argCount];if(!newer){newer=craftEmvalAllocator(argCount);emval_newers[argCount]=newer}return newer(handle,argTypes,args)}function __emval_new_cstring(v){return __emval_register(getStringOrSymbol(v))}function __emval_run_destructors(handle){var destructors=emval_handle_array[handle].value;runDestructors(destructors);__emval_decref(handle)}function _abort(){abort()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j>2]=num;return 0}function _setTempRet0($i){setTempRet0($i|0)}InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_RegisteredPointer();init_embind();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();var asmLibraryArg={"t":__embind_finalize_value_object,"I":__embind_register_bool,"x":__embind_register_class,"w":__embind_register_class_constructor,"d":__embind_register_class_function,"k":__embind_register_constant,"H":__embind_register_emval,"n":__embind_register_enum,"a":__embind_register_enum_value,"A":__embind_register_float,"i":__embind_register_function,"j":__embind_register_integer,"h":__embind_register_memory_view,"B":__embind_register_std_string,"v":__embind_register_std_wstring,"u":__embind_register_value_object,"c":__embind_register_value_object_field,"J":__embind_register_void,"m":__emval_as,"s":__emval_call_void_method,"b":__emval_decref,"y":__emval_get_global,"p":__emval_get_method_caller,"r":__emval_get_module_property,"e":__emval_get_property,"g":__emval_incref,"q":__emval_new,"f":__emval_new_cstring,"l":__emval_run_destructors,"o":_abort,"E":_emscripten_memcpy_big,"F":_emscripten_resize_heap,"G":_fd_close,"C":_fd_seek,"z":_fd_write,"D":_setTempRet0};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["L"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["M"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["N"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["P"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["Q"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["R"]).apply(null,arguments)};var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run(); return BASIS.ready diff --git a/packages/engine/Source/Workers/cesiumWorkerBootstrapper.js b/packages/engine/Source/Workers/cesiumWorkerBootstrapper.js deleted file mode 100644 index 505a4b99b033..000000000000 --- a/packages/engine/Source/Workers/cesiumWorkerBootstrapper.js +++ /dev/null @@ -1,2290 +0,0 @@ -if (typeof self === "undefined") { - self = {}; //define self so that the Dojo build can evaluate this file without crashing. -} - -self.onmessage = function (event) { - var data = event.data; - require(data.loaderConfig, [data.workerModule], function (workerModule) { - //replace onmessage with the required-in workerModule - self.onmessage = workerModule; - self.CESIUM_BASE_URL = data.loaderConfig.baseUrl; - }); -}; - -// replace setTimeout with a function that executes immediately synchronously, which -// will make the above require synchronous like it used to be, to ensure that we we -// have the real worker module loaded and installed before receiving any more messages. -function setTimeout(fn) { - fn(); -} - -//below is RequireJS, verbatim - -/** vim: et:ts=4:sw=4:sts=4 - * @license RequireJS 2.1.20 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved. - * Available via the MIT or new BSD license. - * see: http://github.com/jrburke/requirejs for details - */ -//Not using strict: uneven strict support in browsers, #392, and causes -//problems with requirejs.exec()/transpiler plugins that may not be strict. -/*jslint regexp: true, nomen: true, sloppy: true */ -/*global window, navigator, document, importScripts, setTimeout, opera */ - -var requirejs, require, define; -(function (global) { - var req, - s, - head, - baseElement, - dataMain, - src, - interactiveScript, - currentlyAddingScript, - mainScript, - subPath, - version = "2.1.20", - commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm, - cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, - jsSuffixRegExp = /\.js$/, - currDirRegExp = /^\.\//, - op = Object.prototype, - ostring = op.toString, - hasOwn = op.hasOwnProperty, - ap = Array.prototype, - isBrowser = !!( - typeof window !== "undefined" && - typeof navigator !== "undefined" && - window.document - ), - isWebWorker = !isBrowser && typeof importScripts !== "undefined", - //PS3 indicates loaded and complete, but need to wait for complete - //specifically. Sequence is 'loading', 'loaded', execution, - // then 'complete'. The UA check is unfortunate, but not sure how - //to feature test w/o causing perf issues. - readyRegExp = - isBrowser && navigator.platform === "PLAYSTATION 3" - ? /^complete$/ - : /^(complete|loaded)$/, - defContextName = "_", - //Oh the tragedy, detecting opera. See the usage of isOpera for reason. - isOpera = - typeof opera !== "undefined" && opera.toString() === "[object Opera]", - contexts = {}, - cfg = {}, - globalDefQueue = [], - useInteractive = false; - - function isFunction(it) { - return ostring.call(it) === "[object Function]"; - } - - function isArray(it) { - return ostring.call(it) === "[object Array]"; - } - - /** - * @private - * Helper function for iterating over an array. If the func returns - * a true value, it will break out of the loop. - */ - function each(ary, func) { - if (ary) { - var i; - for (i = 0; i < ary.length; i += 1) { - if (ary[i] && func(ary[i], i, ary)) { - break; - } - } - } - } - - /** - * @private - * Helper function for iterating over an array backwards. If the func - * returns a true value, it will break out of the loop. - */ - function eachReverse(ary, func) { - if (ary) { - var i; - for (i = ary.length - 1; i > -1; i -= 1) { - if (ary[i] && func(ary[i], i, ary)) { - break; - } - } - } - } - - function hasProp(obj, prop) { - return hasOwn.call(obj, prop); - } - - function getOwn(obj, prop) { - return hasProp(obj, prop) && obj[prop]; - } - - /** - * @private - * Cycles over properties in an object and calls a function for each - * property value. If the function returns a truthy value, then the - * iteration is stopped. - */ - function eachProp(obj, func) { - var prop; - for (prop in obj) { - if (hasProp(obj, prop)) { - if (func(obj[prop], prop)) { - break; - } - } - } - } - - /** - * @private - * Simple function to mix in properties from source into target, - * but only if target does not already have a property of the same name. - */ - function mixin(target, source, force, deepStringMixin) { - if (source) { - eachProp(source, function (value, prop) { - if (force || !hasProp(target, prop)) { - if ( - deepStringMixin && - typeof value === "object" && - value && - !isArray(value) && - !isFunction(value) && - !(value instanceof RegExp) - ) { - if (!target[prop]) { - target[prop] = {}; - } - mixin(target[prop], value, force, deepStringMixin); - } else { - target[prop] = value; - } - } - }); - } - return target; - } - - //Similar to Function.prototype.bind, but the 'this' object is specified - //first, since it is easier to read/figure out what 'this' will be. - function bind(obj, fn) { - return function () { - return fn.apply(obj, arguments); - }; - } - - function scripts() { - return document.getElementsByTagName("script"); - } - - function defaultOnError(err) { - throw err; - } - - //Allow getting a global that is expressed in - //dot notation, like 'a.b.c'. - function getGlobal(value) { - if (!value) { - return value; - } - var g = global; - each(value.split("."), function (part) { - g = g[part]; - }); - return g; - } - - /** - * Constructs an error with a pointer to an URL with more information. - * @param {string} id the error ID that maps to an ID on a web page. - * @param {string} msg human readable error. - * @param {Error} [err] the original error, if there is one. - * @param {RequireModules} requireModules The modules required but not found. - * @private - * @returns {Error} - */ - function makeError(id, msg, err, requireModules) { - var e = new Error(msg + "\nhttp://requirejs.org/docs/errors.html#" + id); - e.requireType = id; - e.requireModules = requireModules; - if (err) { - e.originalError = err; - } - return e; - } - - if (typeof define !== "undefined") { - //If a define is already in play via another AMD loader, - //do not overwrite. - return; - } - - if (typeof requirejs !== "undefined") { - if (isFunction(requirejs)) { - //Do not overwrite an existing requirejs instance. - return; - } - cfg = requirejs; - requirejs = undefined; - } - - //Allow for a require config object - if (typeof require !== "undefined" && !isFunction(require)) { - //assume it is a config object. - cfg = require; - require = undefined; - } - - function newContext(contextName) { - var inCheckLoaded, - Module, - context, - handlers, - checkLoadedTimeoutId, - config = { - //Defaults. Do not set a default for map - //config to speed up normalize(), which - //will run faster if there is no default. - waitSeconds: 7, - baseUrl: "./", - paths: {}, - bundles: {}, - pkgs: {}, - shim: {}, - config: {}, - }, - registry = {}, - //registry of just enabled modules, to speed - //cycle breaking code when lots of modules - //are registered, but not activated. - enabledRegistry = {}, - undefEvents = {}, - defQueue = [], - defined = {}, - urlFetched = {}, - bundlesMap = {}, - requireCounter = 1, - unnormalizedCounter = 1; - - /** - * @private - * Trims the . and .. from an array of path segments. - * It will keep a leading path segment if a .. will become - * the first path segment, to help with module name lookups, - * which act like paths, but can be remapped. But the end result, - * all paths that use this function should look normalized. - * NOTE: this method MODIFIES the input array. - * @param {Array} ary the array of path segments. - */ - function trimDots(ary) { - var i, part; - for (i = 0; i < ary.length; i++) { - part = ary[i]; - if (part === ".") { - ary.splice(i, 1); - i -= 1; - } else if (part === "..") { - // If at the start, or previous value is still .., - // keep them so that when converted to a path it may - // still work when converted to a path, even though - // as an ID it is less than ideal. In larger point - // releases, may be better to just kick out an error. - if (i === 0 || (i === 1 && ary[2] === "..") || ary[i - 1] === "..") { - continue; - } else if (i > 0) { - ary.splice(i - 1, 2); - i -= 2; - } - } - } - } - - /** - * @private - * Given a relative module name, like ./something, normalize it to - * a real name that can be mapped to a path. - * @param {string} name the relative name - * @param {string} baseName a real name that the name arg is relative - * to. - * @param {boolean} applyMap apply the map config to the value. Should - * only be done if this normalization is for a dependency ID. - * @returns {string} normalized name - */ - function normalize(name, baseName, applyMap) { - var pkgMain, - mapValue, - nameParts, - i, - j, - nameSegment, - lastIndex, - foundMap, - foundI, - foundStarMap, - starI, - normalizedBaseParts, - baseParts = baseName && baseName.split("/"), - map = config.map, - starMap = map && map["*"]; - - //Adjust any relative paths. - if (name) { - name = name.split("/"); - lastIndex = name.length - 1; - - // If wanting node ID compatibility, strip .js from end - // of IDs. Have to do this here, and not in nameToUrl - // because node allows either .js or non .js to map - // to same file. - if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { - name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ""); - } - - // Starts with a '.' so need the baseName - if (name[0].charAt(0) === "." && baseParts) { - //Convert baseName to array, and lop off the last part, - //so that . matches that 'directory' and not name of the baseName's - //module. For instance, baseName of 'one/two/three', maps to - //'one/two/three.js', but we want the directory, 'one/two' for - //this normalization. - normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); - name = normalizedBaseParts.concat(name); - } - - trimDots(name); - name = name.join("/"); - } - - //Apply map config if available. - if (applyMap && map && (baseParts || starMap)) { - nameParts = name.split("/"); - - outerLoop: for (i = nameParts.length; i > 0; i -= 1) { - nameSegment = nameParts.slice(0, i).join("/"); - - if (baseParts) { - //Find the longest baseName segment match in the config. - //So, do joins on the biggest to smallest lengths of baseParts. - for (j = baseParts.length; j > 0; j -= 1) { - mapValue = getOwn(map, baseParts.slice(0, j).join("/")); - - //baseName segment has config, find if it has one for - //this name. - if (mapValue) { - mapValue = getOwn(mapValue, nameSegment); - if (mapValue) { - //Match, update name to the new value. - foundMap = mapValue; - foundI = i; - break outerLoop; - } - } - } - } - - //Check for a star map match, but just hold on to it, - //if there is a shorter segment match later in a matching - //config, then favor over this star map. - if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { - foundStarMap = getOwn(starMap, nameSegment); - starI = i; - } - } - - if (!foundMap && foundStarMap) { - foundMap = foundStarMap; - foundI = starI; - } - - if (foundMap) { - nameParts.splice(0, foundI, foundMap); - name = nameParts.join("/"); - } - } - - // If the name points to a package's name, use - // the package main instead. - pkgMain = getOwn(config.pkgs, name); - - return pkgMain ? pkgMain : name; - } - - function removeScript(name) { - if (isBrowser) { - each(scripts(), function (scriptNode) { - if ( - scriptNode.getAttribute("data-requiremodule") === name && - scriptNode.getAttribute("data-requirecontext") === - context.contextName - ) { - scriptNode.parentNode.removeChild(scriptNode); - return true; - } - }); - } - } - - function hasPathFallback(id) { - var pathConfig = getOwn(config.paths, id); - if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { - //Pop off the first array value, since it failed, and - //retry - pathConfig.shift(); - context.require.undef(id); - - //Custom require that does not do map translation, since - //ID is "absolute", already mapped/resolved. - context.makeRequire(null, { - skipMap: true, - })([id]); - - return true; - } - } - - //Turns a plugin!resource to [plugin, resource] - //with the plugin being undefined if the name - //did not have a plugin prefix. - function splitPrefix(name) { - var prefix, - index = name ? name.indexOf("!") : -1; - if (index > -1) { - prefix = name.substring(0, index); - name = name.substring(index + 1, name.length); - } - return [prefix, name]; - } - - /** - * Creates a module mapping that includes plugin prefix, module - * name, and path. If parentModuleMap is provided it will - * also normalize the name via require.normalize() - * - * @param {string} name the module name - * @param {string} [parentModuleMap] parent module map - * for the module name, used to resolve relative names. - * @param {boolean} isNormalized: is the ID already normalized. - * This is true if this call is done for a define() module ID. - * @param {boolean} applyMap: apply the map config to the ID. - * Should only be true if this map is for a dependency. - * @private - * @returns {object} - */ - function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { - var url, - pluginModule, - suffix, - nameParts, - prefix = null, - parentName = parentModuleMap ? parentModuleMap.name : null, - originalName = name, - isDefine = true, - normalizedName = ""; - - //If no name, then it means it is a require call, generate an - //internal name. - if (!name) { - isDefine = false; - name = "_@r" + (requireCounter += 1); - } - - nameParts = splitPrefix(name); - prefix = nameParts[0]; - name = nameParts[1]; - - if (prefix) { - prefix = normalize(prefix, parentName, applyMap); - pluginModule = getOwn(defined, prefix); - } - - //Account for relative paths if there is a base name. - if (name) { - if (prefix) { - if (pluginModule && pluginModule.normalize) { - //Plugin is loaded, use its normalize method. - normalizedName = pluginModule.normalize(name, function (name) { - return normalize(name, parentName, applyMap); - }); - } else { - // If nested plugin references, then do not try to - // normalize, as it will not normalize correctly. This - // places a restriction on resourceIds, and the longer - // term solution is not to normalize until plugins are - // loaded and all normalizations to allow for async - // loading of a loader plugin. But for now, fixes the - // common uses. Details in #1131 - normalizedName = - name.indexOf("!") === -1 - ? normalize(name, parentName, applyMap) - : name; - } - } else { - //A regular module. - normalizedName = normalize(name, parentName, applyMap); - - //Normalized name may be a plugin ID due to map config - //application in normalize. The map config values must - //already be normalized, so do not need to redo that part. - nameParts = splitPrefix(normalizedName); - prefix = nameParts[0]; - normalizedName = nameParts[1]; - isNormalized = true; - - url = context.nameToUrl(normalizedName); - } - } - - //If the id is a plugin id that cannot be determined if it needs - //normalization, stamp it with a unique ID so two matching relative - //ids that may conflict can be separate. - suffix = - prefix && !pluginModule && !isNormalized - ? "_unnormalized" + (unnormalizedCounter += 1) - : ""; - - return { - prefix: prefix, - name: normalizedName, - parentMap: parentModuleMap, - unnormalized: !!suffix, - url: url, - originalName: originalName, - isDefine: isDefine, - id: (prefix ? prefix + "!" + normalizedName : normalizedName) + suffix, - }; - } - - function getModule(depMap) { - var id = depMap.id, - mod = getOwn(registry, id); - - if (!mod) { - mod = registry[id] = new context.Module(depMap); - } - - return mod; - } - - function on(depMap, name, fn) { - var id = depMap.id, - mod = getOwn(registry, id); - - if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { - if (name === "defined") { - fn(defined[id]); - } - } else { - mod = getModule(depMap); - if (mod.error && name === "error") { - fn(mod.error); - } else { - mod.on(name, fn); - } - } - } - - function onError(err, errback) { - var ids = err.requireModules, - notified = false; - - if (errback) { - errback(err); - } else { - each(ids, function (id) { - var mod = getOwn(registry, id); - if (mod) { - //Set error on module, so it skips timeout checks. - mod.error = err; - if (mod.events.error) { - notified = true; - mod.emit("error", err); - } - } - }); - - if (!notified) { - req.onError(err); - } - } - } - - /** - * @private - * Internal method to transfer globalQueue items to this context's - * defQueue. - */ - function takeGlobalQueue() { - //Push all the globalDefQueue items into the context's defQueue - if (globalDefQueue.length) { - each(globalDefQueue, function (queueItem) { - var id = queueItem[0]; - if (typeof id === "string") { - context.defQueueMap[id] = true; - } - defQueue.push(queueItem); - }); - globalDefQueue = []; - } - } - - handlers = { - require: function (mod) { - if (mod.require) { - return mod.require; - } else { - return (mod.require = context.makeRequire(mod.map)); - } - }, - exports: function (mod) { - mod.usingExports = true; - if (mod.map.isDefine) { - if (mod.exports) { - return (defined[mod.map.id] = mod.exports); - } else { - return (mod.exports = defined[mod.map.id] = {}); - } - } - }, - module: function (mod) { - if (mod.module) { - return mod.module; - } else { - return (mod.module = { - id: mod.map.id, - uri: mod.map.url, - config: function () { - return getOwn(config.config, mod.map.id) || {}; - }, - exports: mod.exports || (mod.exports = {}), - }); - } - }, - }; - - function cleanRegistry(id) { - //Clean up machinery used for waiting modules. - delete registry[id]; - delete enabledRegistry[id]; - } - - function breakCycle(mod, traced, processed) { - var id = mod.map.id; - - if (mod.error) { - mod.emit("error", mod.error); - } else { - traced[id] = true; - each(mod.depMaps, function (depMap, i) { - var depId = depMap.id, - dep = getOwn(registry, depId); - - //Only force things that have not completed - //being defined, so still in the registry, - //and only if it has not been matched up - //in the module already. - if (dep && !mod.depMatched[i] && !processed[depId]) { - if (getOwn(traced, depId)) { - mod.defineDep(i, defined[depId]); - mod.check(); //pass false? - } else { - breakCycle(dep, traced, processed); - } - } - }); - processed[id] = true; - } - } - - function checkLoaded() { - var err, - usingPathFallback, - waitInterval = config.waitSeconds * 1000, - //It is possible to disable the wait interval by using waitSeconds of 0. - expired = - waitInterval && - context.startTime + waitInterval < new Date().getTime(), - noLoads = [], - reqCalls = [], - stillLoading = false, - needCycleCheck = true; - - //Do not bother if this call was a result of a cycle break. - if (inCheckLoaded) { - return; - } - - inCheckLoaded = true; - - //Figure out the state of all the modules. - eachProp(enabledRegistry, function (mod) { - var map = mod.map, - modId = map.id; - - //Skip things that are not enabled or in error state. - if (!mod.enabled) { - return; - } - - if (!map.isDefine) { - reqCalls.push(mod); - } - - if (!mod.error) { - //If the module should be executed, and it has not - //been inited and time is up, remember it. - if (!mod.inited && expired) { - if (hasPathFallback(modId)) { - usingPathFallback = true; - stillLoading = true; - } else { - noLoads.push(modId); - removeScript(modId); - } - } else if (!mod.inited && mod.fetched && map.isDefine) { - stillLoading = true; - if (!map.prefix) { - //No reason to keep looking for unfinished - //loading. If the only stillLoading is a - //plugin resource though, keep going, - //because it may be that a plugin resource - //is waiting on a non-plugin cycle. - return (needCycleCheck = false); - } - } - } - }); - - if (expired && noLoads.length) { - //If wait time expired, throw error of unloaded modules. - err = makeError( - "timeout", - "Load timeout for modules: " + noLoads, - null, - noLoads - ); - err.contextName = context.contextName; - return onError(err); - } - - //Not expired, check for a cycle. - if (needCycleCheck) { - each(reqCalls, function (mod) { - breakCycle(mod, {}, {}); - }); - } - - //If still waiting on loads, and the waiting load is something - //other than a plugin resource, or there are still outstanding - //scripts, then just try back later. - if ((!expired || usingPathFallback) && stillLoading) { - //Something is still waiting to load. Wait for it, but only - //if a timeout is not already in effect. - if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { - checkLoadedTimeoutId = setTimeout(function () { - checkLoadedTimeoutId = 0; - checkLoaded(); - }, 50); - } - } - - inCheckLoaded = false; - } - - Module = function (map) { - this.events = getOwn(undefEvents, map.id) || {}; - this.map = map; - this.shim = getOwn(config.shim, map.id); - this.depExports = []; - this.depMaps = []; - this.depMatched = []; - this.pluginMaps = {}; - this.depCount = 0; - - /* this.exports this.factory - this.depMaps = [], - this.enabled, this.fetched - */ - }; - - Module.prototype = { - init: function (depMaps, factory, errback, options) { - options = options || {}; - - //Do not do more inits if already done. Can happen if there - //are multiple define calls for the same module. That is not - //a normal, common case, but it is also not unexpected. - if (this.inited) { - return; - } - - this.factory = factory; - - if (errback) { - //Register for errors on this module. - this.on("error", errback); - } else if (this.events.error) { - //If no errback already, but there are error listeners - //on this module, set up an errback to pass to the deps. - errback = bind(this, function (err) { - this.emit("error", err); - }); - } - - //Do a copy of the dependency array, so that - //source inputs are not modified. For example - //"shim" deps are passed in here directly, and - //doing a direct modification of the depMaps array - //would affect that config. - this.depMaps = depMaps && depMaps.slice(0); - - this.errback = errback; - - //Indicate this module has be initialized - this.inited = true; - - this.ignore = options.ignore; - - //Could have option to init this module in enabled mode, - //or could have been previously marked as enabled. However, - //the dependencies are not known until init is called. So - //if enabled previously, now trigger dependencies as enabled. - if (options.enabled || this.enabled) { - //Enable this module and dependencies. - //Will call this.check() - this.enable(); - } else { - this.check(); - } - }, - - defineDep: function (i, depExports) { - //Because of cycles, defined callback for a given - //export can be called more than once. - if (!this.depMatched[i]) { - this.depMatched[i] = true; - this.depCount -= 1; - this.depExports[i] = depExports; - } - }, - - fetch: function () { - if (this.fetched) { - return; - } - this.fetched = true; - - context.startTime = new Date().getTime(); - - var map = this.map; - - //If the manager is for a plugin managed resource, - //ask the plugin to load it now. - if (this.shim) { - context.makeRequire(this.map, { - enableBuildCallback: true, - })( - this.shim.deps || [], - bind(this, function () { - return map.prefix ? this.callPlugin() : this.load(); - }) - ); - } else { - //Regular dependency. - return map.prefix ? this.callPlugin() : this.load(); - } - }, - - load: function () { - var url = this.map.url; - - //Regular dependency. - if (!urlFetched[url]) { - urlFetched[url] = true; - context.load(this.map.id, url); - } - }, - - /** - * Checks if the module is ready to define itself, and if so, - * define it. - * @private - */ - check: function () { - if (!this.enabled || this.enabling) { - return; - } - - var err, - cjsModule, - id = this.map.id, - depExports = this.depExports, - exports = this.exports, - factory = this.factory; - - if (!this.inited) { - // Only fetch if not already in the defQueue. - if (!hasProp(context.defQueueMap, id)) { - this.fetch(); - } - } else if (this.error) { - this.emit("error", this.error); - } else if (!this.defining) { - //The factory could trigger another require call - //that would result in checking this module to - //define itself again. If already in the process - //of doing that, skip this work. - this.defining = true; - - if (this.depCount < 1 && !this.defined) { - if (isFunction(factory)) { - //If there is an error listener, favor passing - //to that instead of throwing an error. However, - //only do it for define()'d modules. require - //errbacks should not be called for failures in - //their callbacks (#699). However if a global - //onError is set, use that. - if ( - (this.events.error && this.map.isDefine) || - req.onError !== defaultOnError - ) { - try { - exports = context.execCb(id, factory, depExports, exports); - } catch (e) { - err = e; - } - } else { - exports = context.execCb(id, factory, depExports, exports); - } - - // Favor return value over exports. If node/cjs in play, - // then will not have a return value anyway. Favor - // module.exports assignment over exports object. - if (this.map.isDefine && exports === undefined) { - cjsModule = this.module; - if (cjsModule) { - exports = cjsModule.exports; - } else if (this.usingExports) { - //exports already set the defined value. - exports = this.exports; - } - } - - if (err) { - err.requireMap = this.map; - err.requireModules = this.map.isDefine ? [this.map.id] : null; - err.requireType = this.map.isDefine ? "define" : "require"; - return onError((this.error = err)); - } - } else { - //Just a literal value - exports = factory; - } - - this.exports = exports; - - if (this.map.isDefine && !this.ignore) { - defined[id] = exports; - - if (req.onResourceLoad) { - req.onResourceLoad(context, this.map, this.depMaps); - } - } - - //Clean up - cleanRegistry(id); - - this.defined = true; - } - - //Finished the define stage. Allow calling check again - //to allow define notifications below in the case of a - //cycle. - this.defining = false; - - if (this.defined && !this.defineEmitted) { - this.defineEmitted = true; - this.emit("defined", this.exports); - this.defineEmitComplete = true; - } - } - }, - - callPlugin: function () { - var map = this.map, - id = map.id, - //Map already normalized the prefix. - pluginMap = makeModuleMap(map.prefix); - - //Mark this as a dependency for this plugin, so it - //can be traced for cycles. - this.depMaps.push(pluginMap); - - on( - pluginMap, - "defined", - bind(this, function (plugin) { - var load, - normalizedMap, - normalizedMod, - bundleId = getOwn(bundlesMap, this.map.id), - name = this.map.name, - parentName = this.map.parentMap ? this.map.parentMap.name : null, - localRequire = context.makeRequire(map.parentMap, { - enableBuildCallback: true, - }); - - //If current map is not normalized, wait for that - //normalized name to load instead of continuing. - if (this.map.unnormalized) { - //Normalize the ID if the plugin allows it. - if (plugin.normalize) { - name = - plugin.normalize(name, function (name) { - return normalize(name, parentName, true); - }) || ""; - } - - //prefix and name should already be normalized, no need - //for applying map config again either. - normalizedMap = makeModuleMap( - map.prefix + "!" + name, - this.map.parentMap - ); - on( - normalizedMap, - "defined", - bind(this, function (value) { - this.init( - [], - function () { - return value; - }, - null, - { - enabled: true, - ignore: true, - } - ); - }) - ); - - normalizedMod = getOwn(registry, normalizedMap.id); - if (normalizedMod) { - //Mark this as a dependency for this plugin, so it - //can be traced for cycles. - this.depMaps.push(normalizedMap); - - if (this.events.error) { - normalizedMod.on( - "error", - bind(this, function (err) { - this.emit("error", err); - }) - ); - } - normalizedMod.enable(); - } - - return; - } - - //If a paths config, then just load that file instead to - //resolve the plugin, as it is built into that paths layer. - if (bundleId) { - this.map.url = context.nameToUrl(bundleId); - this.load(); - return; - } - - load = bind(this, function (value) { - this.init( - [], - function () { - return value; - }, - null, - { - enabled: true, - } - ); - }); - - load.error = bind(this, function (err) { - this.inited = true; - this.error = err; - err.requireModules = [id]; - - //Remove temp unnormalized modules for this module, - //since they will never be resolved otherwise now. - eachProp(registry, function (mod) { - if (mod.map.id.indexOf(id + "_unnormalized") === 0) { - cleanRegistry(mod.map.id); - } - }); - - onError(err); - }); - - //Allow plugins to load other code without having to know the - //context or how to 'complete' the load. - load.fromText = bind(this, function (text, textAlt) { - /*jslint evil: true */ - var moduleName = map.name, - moduleMap = makeModuleMap(moduleName), - hasInteractive = useInteractive; - - //As of 2.1.0, support just passing the text, to reinforce - //fromText only being called once per resource. Still - //support old style of passing moduleName but discard - //that moduleName in favor of the internal ref. - if (textAlt) { - text = textAlt; - } - - //Turn off interactive script matching for IE for any define - //calls in the text, then turn it back on at the end. - if (hasInteractive) { - useInteractive = false; - } - - //Prime the system by creating a module instance for - //it. - getModule(moduleMap); - - //Transfer any config to this other module. - if (hasProp(config.config, id)) { - config.config[moduleName] = config.config[id]; - } - - try { - req.exec(text); - } catch (e) { - return onError( - makeError( - "fromtexteval", - "fromText eval for " + id + " failed: " + e, - e, - [id] - ) - ); - } - - if (hasInteractive) { - useInteractive = true; - } - - //Mark this as a dependency for the plugin - //resource - this.depMaps.push(moduleMap); - - //Support anonymous modules. - context.completeLoad(moduleName); - - //Bind the value of that module to the value for this - //resource ID. - localRequire([moduleName], load); - }); - - //Use parentName here since the plugin's name is not reliable, - //could be some weird string with no path that actually wants to - //reference the parentName's path. - plugin.load(map.name, localRequire, load, config); - }) - ); - - context.enable(pluginMap, this); - this.pluginMaps[pluginMap.id] = pluginMap; - }, - - enable: function () { - enabledRegistry[this.map.id] = this; - this.enabled = true; - - //Set flag mentioning that the module is enabling, - //so that immediate calls to the defined callbacks - //for dependencies do not trigger inadvertent load - //with the depCount still being zero. - this.enabling = true; - - //Enable each dependency - each( - this.depMaps, - bind(this, function (depMap, i) { - var id, mod, handler; - - if (typeof depMap === "string") { - //Dependency needs to be converted to a depMap - //and wired up to this module. - depMap = makeModuleMap( - depMap, - this.map.isDefine ? this.map : this.map.parentMap, - false, - !this.skipMap - ); - this.depMaps[i] = depMap; - - handler = getOwn(handlers, depMap.id); - - if (handler) { - this.depExports[i] = handler(this); - return; - } - - this.depCount += 1; - - on( - depMap, - "defined", - bind(this, function (depExports) { - if (this.undefed) { - return; - } - this.defineDep(i, depExports); - this.check(); - }) - ); - - if (this.errback) { - on(depMap, "error", bind(this, this.errback)); - } else if (this.events.error) { - // No direct errback on this module, but something - // else is listening for errors, so be sure to - // propagate the error correctly. - on( - depMap, - "error", - bind(this, function (err) { - this.emit("error", err); - }) - ); - } - } - - id = depMap.id; - mod = registry[id]; - - //Skip special modules like 'require', 'exports', 'module' - //Also, don't call enable if it is already enabled, - //important in circular dependency cases. - if (!hasProp(handlers, id) && mod && !mod.enabled) { - context.enable(depMap, this); - } - }) - ); - - //Enable each plugin that is used in - //a dependency - eachProp( - this.pluginMaps, - bind(this, function (pluginMap) { - var mod = getOwn(registry, pluginMap.id); - if (mod && !mod.enabled) { - context.enable(pluginMap, this); - } - }) - ); - - this.enabling = false; - - this.check(); - }, - - on: function (name, cb) { - var cbs = this.events[name]; - if (!cbs) { - cbs = this.events[name] = []; - } - cbs.push(cb); - }, - - emit: function (name, evt) { - each(this.events[name], function (cb) { - cb(evt); - }); - if (name === "error") { - //Now that the error handler was triggered, remove - //the listeners, since this broken Module instance - //can stay around for a while in the registry. - delete this.events[name]; - } - }, - }; - - function callGetModule(args) { - //Skip modules already defined. - if (!hasProp(defined, args[0])) { - getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); - } - } - - function removeListener(node, func, name, ieName) { - //Favor detachEvent because of IE9 - //issue, see attachEvent/addEventListener comment elsewhere - //in this file. - if (node.detachEvent && !isOpera) { - //Probably IE. If not it will throw an error, which will be - //useful to know. - if (ieName) { - node.detachEvent(ieName, func); - } - } else { - node.removeEventListener(name, func, false); - } - } - - /** - * Given an event from a script node, get the requirejs info from it, - * and then removes the event listeners on the node. - * @param {Event} evt - * @private - * @returns {object} - */ - function getScriptData(evt) { - //Using currentTarget instead of target for Firefox 2.0's sake. Not - //all old browsers will be supported, but this one was easy enough - //to support and still makes sense. - var node = evt.currentTarget || evt.srcElement; - - //Remove the listeners once here. - removeListener(node, context.onScriptLoad, "load", "onreadystatechange"); - removeListener(node, context.onScriptError, "error"); - - return { - node: node, - id: node && node.getAttribute("data-requiremodule"), - }; - } - - function intakeDefines() { - var args; - - //Any defined modules in the global queue, intake them now. - takeGlobalQueue(); - - //Make sure any remaining defQueue items get properly processed. - while (defQueue.length) { - args = defQueue.shift(); - if (args[0] === null) { - return onError( - makeError( - "mismatch", - "Mismatched anonymous define() module: " + args[args.length - 1] - ) - ); - } else { - //args are id, deps, factory. Should be normalized by the - //define() function. - callGetModule(args); - } - } - context.defQueueMap = {}; - } - - context = { - config: config, - contextName: contextName, - registry: registry, - defined: defined, - urlFetched: urlFetched, - defQueue: defQueue, - defQueueMap: {}, - Module: Module, - makeModuleMap: makeModuleMap, - nextTick: req.nextTick, - onError: onError, - - /** - * @private - * Set a configuration for the context. - * @param {object} cfg config object to integrate. - */ - configure: function (cfg) { - //Make sure the baseUrl ends in a slash. - if (cfg.baseUrl) { - if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== "/") { - cfg.baseUrl += "/"; - } - } - - //Save off the paths since they require special processing, - //they are additive. - var shim = config.shim, - objs = { - paths: true, - bundles: true, - config: true, - map: true, - }; - - eachProp(cfg, function (value, prop) { - if (objs[prop]) { - if (!config[prop]) { - config[prop] = {}; - } - mixin(config[prop], value, true, true); - } else { - config[prop] = value; - } - }); - - //Reverse map the bundles - if (cfg.bundles) { - eachProp(cfg.bundles, function (value, prop) { - each(value, function (v) { - if (v !== prop) { - bundlesMap[v] = prop; - } - }); - }); - } - - //Merge shim - if (cfg.shim) { - eachProp(cfg.shim, function (value, id) { - //Normalize the structure - if (isArray(value)) { - value = { - deps: value, - }; - } - if ((value.exports || value.init) && !value.exportsFn) { - value.exportsFn = context.makeShimExports(value); - } - shim[id] = value; - }); - config.shim = shim; - } - - //Adjust packages if necessary. - if (cfg.packages) { - each(cfg.packages, function (pkgObj) { - var location, name; - - pkgObj = typeof pkgObj === "string" ? { name: pkgObj } : pkgObj; - - name = pkgObj.name; - location = pkgObj.location; - if (location) { - config.paths[name] = pkgObj.location; - } - - //Save pointer to main module ID for pkg name. - //Remove leading dot in main, so main paths are normalized, - //and remove any trailing .js, since different package - //envs have different conventions: some use a module name, - //some use a file name. - config.pkgs[name] = - pkgObj.name + - "/" + - (pkgObj.main || "main") - .replace(currDirRegExp, "") - .replace(jsSuffixRegExp, ""); - }); - } - - //If there are any "waiting to execute" modules in the registry, - //update the maps for them, since their info, like URLs to load, - //may have changed. - eachProp(registry, function (mod, id) { - //If module already has init called, since it is too - //late to modify them, and ignore unnormalized ones - //since they are transient. - if (!mod.inited && !mod.map.unnormalized) { - mod.map = makeModuleMap(id, null, true); - } - }); - - //If a deps array or a config callback is specified, then call - //require with those args. This is useful when require is defined as a - //config object before require.js is loaded. - if (cfg.deps || cfg.callback) { - context.require(cfg.deps || [], cfg.callback); - } - }, - - makeShimExports: function (value) { - function fn() { - var ret; - if (value.init) { - ret = value.init.apply(global, arguments); - } - return ret || (value.exports && getGlobal(value.exports)); - } - return fn; - }, - - makeRequire: function (relMap, options) { - options = options || {}; - - function localRequire(deps, callback, errback) { - var id, map, requireMod; - - if (options.enableBuildCallback && callback && isFunction(callback)) { - callback.__requireJsBuild = true; - } - - if (typeof deps === "string") { - if (isFunction(callback)) { - //Invalid call - return onError( - makeError("requireargs", "Invalid require call"), - errback - ); - } - - //If require|exports|module are requested, get the - //value for them from the special handlers. Caveat: - //this only works while module is being defined. - if (relMap && hasProp(handlers, deps)) { - return handlers[deps](registry[relMap.id]); - } - - //Synchronous access to one module. If require.get is - //available (as in the Node adapter), prefer that. - if (req.get) { - return req.get(context, deps, relMap, localRequire); - } - - //Normalize module name, if it contains . or .. - map = makeModuleMap(deps, relMap, false, true); - id = map.id; - - if (!hasProp(defined, id)) { - return onError( - makeError( - "notloaded", - 'Module name "' + - id + - '" has not been loaded yet for context: ' + - contextName + - (relMap ? "" : ". Use require([])") - ) - ); - } - return defined[id]; - } - - //Grab defines waiting in the global queue. - intakeDefines(); - - //Mark all the dependencies as needing to be loaded. - context.nextTick(function () { - //Some defines could have been added since the - //require call, collect them. - intakeDefines(); - - requireMod = getModule(makeModuleMap(null, relMap)); - - //Store if map config should be applied to this require - //call for dependencies. - requireMod.skipMap = options.skipMap; - - requireMod.init(deps, callback, errback, { - enabled: true, - }); - - checkLoaded(); - }); - - return localRequire; - } - - mixin(localRequire, { - isBrowser: isBrowser, - - /** - * Converts a module name + .extension into an URL path. - * *Requires* the use of a module name. It does not support using - * plain URLs like nameToUrl. - */ - toUrl: function (moduleNamePlusExt) { - var ext, - index = moduleNamePlusExt.lastIndexOf("."), - segment = moduleNamePlusExt.split("/")[0], - isRelative = segment === "." || segment === ".."; - - //Have a file extension alias, and it is not the - //dots from a relative path. - if (index !== -1 && (!isRelative || index > 1)) { - ext = moduleNamePlusExt.substring( - index, - moduleNamePlusExt.length - ); - moduleNamePlusExt = moduleNamePlusExt.substring(0, index); - } - - return context.nameToUrl( - normalize(moduleNamePlusExt, relMap && relMap.id, true), - ext, - true - ); - }, - - defined: function (id) { - return hasProp(defined, makeModuleMap(id, relMap, false, true).id); - }, - - specified: function (id) { - id = makeModuleMap(id, relMap, false, true).id; - return hasProp(defined, id) || hasProp(registry, id); - }, - }); - - //Only allow undef on top level require calls - if (!relMap) { - localRequire.undef = function (id) { - //Bind any waiting define() calls to this context, - //fix for #408 - takeGlobalQueue(); - - var map = makeModuleMap(id, relMap, true), - mod = getOwn(registry, id); - - mod.undefed = true; - removeScript(id); - - delete defined[id]; - delete urlFetched[map.url]; - delete undefEvents[id]; - - //Clean queued defines too. Go backwards - //in array so that the splices do not - //mess up the iteration. - eachReverse(defQueue, function (args, i) { - if (args[0] === id) { - defQueue.splice(i, 1); - } - }); - delete context.defQueueMap[id]; - - if (mod) { - //Hold on to listeners in case the - //module will be attempted to be reloaded - //using a different config. - if (mod.events.defined) { - undefEvents[id] = mod.events; - } - - cleanRegistry(id); - } - }; - } - - return localRequire; - }, - - /** - * @private - * Called to enable a module if it is still in the registry - * awaiting enablement. A second arg, parent, the parent module, - * is passed in for context, when this method is overridden by - * the optimizer. Not shown here to keep code compact. - */ - enable: function (depMap) { - var mod = getOwn(registry, depMap.id); - if (mod) { - getModule(depMap).enable(); - } - }, - - /** - * Internal method used by environment adapters to complete a load event. - * A load event could be a script load or just a load pass from a synchronous - * load call. - * @param {string} moduleName the name of the module to potentially complete. - * @private - */ - completeLoad: function (moduleName) { - var found, - args, - mod, - shim = getOwn(config.shim, moduleName) || {}, - shExports = shim.exports; - - takeGlobalQueue(); - - while (defQueue.length) { - args = defQueue.shift(); - if (args[0] === null) { - args[0] = moduleName; - //If already found an anonymous module and bound it - //to this name, then this is some other anon module - //waiting for its completeLoad to fire. - if (found) { - break; - } - found = true; - } else if (args[0] === moduleName) { - //Found matching define call for this script! - found = true; - } - - callGetModule(args); - } - context.defQueueMap = {}; - - //Do this after the cycle of callGetModule in case the result - //of those calls/init calls changes the registry. - mod = getOwn(registry, moduleName); - - if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { - if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { - if (hasPathFallback(moduleName)) { - return; - } else { - return onError( - makeError( - "nodefine", - "No define call for " + moduleName, - null, - [moduleName] - ) - ); - } - } else { - //A script that does not call define(), so just simulate - //the call for it. - callGetModule([moduleName, shim.deps || [], shim.exportsFn]); - } - } - - checkLoaded(); - }, - - /** - * @private - * Converts a module name to a file path. Supports cases where - * moduleName may actually be just an URL. - * Note that it **does not** call normalize on the moduleName, - * it is assumed to have already been normalized. This is an - * internal API, not a public one. Use toUrl for the public API. - */ - nameToUrl: function (moduleName, ext, skipExt) { - var paths, - syms, - i, - parentModule, - url, - parentPath, - bundleId, - pkgMain = getOwn(config.pkgs, moduleName); - - if (pkgMain) { - moduleName = pkgMain; - } - - bundleId = getOwn(bundlesMap, moduleName); - - if (bundleId) { - return context.nameToUrl(bundleId, ext, skipExt); - } - - //If a colon is in the URL, it indicates a protocol is used and it is just - //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) - //or ends with .js, then assume the user meant to use an url and not a module id. - //The slash is important for protocol-less URLs as well as full paths. - if (req.jsExtRegExp.test(moduleName)) { - //Just a plain path, not module name lookup, so just return it. - //Add extension if it is included. This is a bit wonky, only non-.js things pass - //an extension, this method probably needs to be reworked. - url = moduleName + (ext || ""); - } else { - //A module that needs to be converted to a path. - paths = config.paths; - - syms = moduleName.split("/"); - //For each module name segment, see if there is a path - //registered for it. Start with most specific name - //and work up from it. - for (i = syms.length; i > 0; i -= 1) { - parentModule = syms.slice(0, i).join("/"); - - parentPath = getOwn(paths, parentModule); - if (parentPath) { - //If an array, it means there are a few choices, - //Choose the one that is desired - if (isArray(parentPath)) { - parentPath = parentPath[0]; - } - syms.splice(0, i, parentPath); - break; - } - } - - //Join the path parts together, then figure out if baseUrl is needed. - url = syms.join("/"); - url += ext || (/^data\:|\?/.test(url) || skipExt ? "" : ".js"); - url = - (url.charAt(0) === "/" || url.match(/^[\w\+\.\-]+:/) - ? "" - : config.baseUrl) + url; - } - - return config.urlArgs - ? url + ((url.indexOf("?") === -1 ? "?" : "&") + config.urlArgs) - : url; - }, - - //Delegates to req.load. Broken out as a separate function to - //allow overriding in the optimizer. - load: function (id, url) { - req.load(context, id, url); - }, - - /** - * Executes a module callback function. Broken out as a separate function - * solely to allow the build system to sequence the files in the built - * layer in the right sequence. - * - * @private - */ - execCb: function (name, callback, args, exports) { - return callback.apply(exports, args); - }, - - /** - * callback for script loads, used to check status of loading. - * @private - * @param {Event} evt the event from the browser for the script - * that was loaded. - */ - onScriptLoad: function (evt) { - //Using currentTarget instead of target for Firefox 2.0's sake. Not - //all old browsers will be supported, but this one was easy enough - //to support and still makes sense. - if ( - evt.type === "load" || - readyRegExp.test((evt.currentTarget || evt.srcElement).readyState) - ) { - //Reset interactive script so a script node is not held onto for - //to long. - interactiveScript = null; - - //Pull out the name of the module and the context. - var data = getScriptData(evt); - context.completeLoad(data.id); - } - }, - - /** - * @private - * Callback for script errors. - */ - onScriptError: function (evt) { - var data = getScriptData(evt); - if (!hasPathFallback(data.id)) { - return onError( - makeError("scripterror", "Script error for: " + data.id, evt, [ - data.id, - ]) - ); - } - }, - }; - - context.require = context.makeRequire(); - return context; - } - - /** - * Main entry point. - * - * If the only argument to require is a string, then the module that - * is represented by that string is fetched for the appropriate context. - * - * If the first argument is an array, then it will be treated as an array - * of dependency string names to fetch. An optional function callback can - * be specified to execute when all of those dependencies are available. - * - * Make a local req variable to help Caja compliance (it assumes things - * on a require that are not standardized), and to give a short - * name for minification/local scope use. - * @namespace - */ - req = requirejs = function (deps, callback, errback, optional) { - //Find the right context, use default - var context, - config, - contextName = defContextName; - - // Determine if have config object in the call. - if (!isArray(deps) && typeof deps !== "string") { - // deps is a config object - config = deps; - if (isArray(callback)) { - // Adjust args if there are dependencies - deps = callback; - callback = errback; - errback = optional; - } else { - deps = []; - } - } - - if (config && config.context) { - contextName = config.context; - } - - context = getOwn(contexts, contextName); - if (!context) { - context = contexts[contextName] = req.s.newContext(contextName); - } - - if (config) { - context.configure(config); - } - - return context.require(deps, callback, errback); - }; - - /** - * Support require.config() to make it easier to cooperate with other - * AMD loaders on globally agreed names. - */ - req.config = function (config) { - return req(config); - }; - - /** - * Execute something after the current tick - * of the event loop. Override for other envs - * that have a better solution than setTimeout. - * @param {Function} fn function to execute later. - */ - req.nextTick = - typeof setTimeout !== "undefined" - ? function (fn) { - setTimeout(fn, 4); - } - : function (fn) { - fn(); - }; - - /** - * Export require as a global, but only if it does not already exist. - */ - if (!require) { - require = req; - } - - req.version = version; - - //Used to filter out dependencies that are already paths. - req.jsExtRegExp = /^\/|:|\?|\.js$/; - req.isBrowser = isBrowser; - s = req.s = { - contexts: contexts, - newContext: newContext, - }; - - //Create default context. - req({}); - - //Exports some context-sensitive methods on global require. - each(["toUrl", "undef", "defined", "specified"], function (prop) { - //Reference from contexts instead of early binding to default context, - //so that during builds, the latest instance of the default context - //with its config gets used. - req[prop] = function () { - var ctx = contexts[defContextName]; - return ctx.require[prop].apply(ctx, arguments); - }; - }); - - if (isBrowser) { - head = s.head = document.getElementsByTagName("head")[0]; - //If BASE tag is in play, using appendChild is a problem for IE6. - //When that browser dies, this can be removed. Details in this jQuery bug: - //http://dev.jquery.com/ticket/2709 - baseElement = document.getElementsByTagName("base")[0]; - if (baseElement) { - head = s.head = baseElement.parentNode; - } - } - - /** - * Any errors that require explicitly generates will be passed to this - * function. Intercept/override it if you want custom error handling. - * @param {Error} err the error object. - */ - req.onError = defaultOnError; - - /** - * Creates the node for the load command. Only used in browser envs. - */ - req.createNode = function (config, moduleName, url) { - var node = config.xhtml - ? document.createElementNS("http://www.w3.org/1999/xhtml", "html:script") - : document.createElement("script"); - node.type = config.scriptType || "text/javascript"; - node.charset = "utf-8"; - node.async = true; - return node; - }; - - /** - * Does the request to load a module for the browser case. - * Make this a separate function to allow other environments - * to override it. - * - * @param {object} context the require context to find state. - * @param {string} moduleName the name of the module. - * @param {object} url the URL to the module. - */ - req.load = function (context, moduleName, url) { - var config = (context && context.config) || {}, - node; - if (isBrowser) { - //In the browser so use a script tag - node = req.createNode(config, moduleName, url); - if (config.onNodeCreated) { - config.onNodeCreated(node, config, moduleName, url); - } - - node.setAttribute("data-requirecontext", context.contextName); - node.setAttribute("data-requiremodule", moduleName); - - //Set up load listener. Test attachEvent first because IE9 has - //a subtle issue in its addEventListener and script onload firings - //that do not match the behavior of all other browsers with - //addEventListener support, which fire the onload event for a - //script right after the script execution. See: - //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution - //UNFORTUNATELY Opera implements attachEvent but does not follow the script - //script execution mode. - if ( - node.attachEvent && - //Check if node.attachEvent is artificially added by custom script or - //natively supported by browser - //read https://github.com/jrburke/requirejs/issues/187 - //if we can NOT find [native code] then it must NOT natively supported. - //in IE8, node.attachEvent does not have toString() - //Note the test for "[native code" with no closing brace, see: - //https://github.com/jrburke/requirejs/issues/273 - !( - node.attachEvent.toString && - node.attachEvent.toString().indexOf("[native code") < 0 - ) && - !isOpera - ) { - //Probably IE. IE (at least 6-8) do not fire - //script onload right after executing the script, so - //we cannot tie the anonymous define call to a name. - //However, IE reports the script as being in 'interactive' - //readyState at the time of the define call. - useInteractive = true; - - node.attachEvent("onreadystatechange", context.onScriptLoad); - //It would be great to add an error handler here to catch - //404s in IE9+. However, onreadystatechange will fire before - //the error handler, so that does not help. If addEventListener - //is used, then IE will fire error before load, but we cannot - //use that pathway given the connect.microsoft.com issue - //mentioned above about not doing the 'script execute, - //then fire the script load event listener before execute - //next script' that other browsers do. - //Best hope: IE10 fixes the issues, - //and then destroys all installs of IE 6-9. - //node.attachEvent('onerror', context.onScriptError); - } else { - node.addEventListener("load", context.onScriptLoad, false); - node.addEventListener("error", context.onScriptError, false); - } - node.src = url; - - //For some cache cases in IE 6-8, the script executes before the end - //of the appendChild execution, so to tie an anonymous define - //call to the module name (which is stored on the node), hold on - //to a reference to this node, but clear after the DOM insertion. - currentlyAddingScript = node; - if (baseElement) { - head.insertBefore(node, baseElement); - } else { - head.appendChild(node); - } - currentlyAddingScript = null; - - return node; - } else if (isWebWorker) { - try { - //In a web worker, use importScripts. This is not a very - //efficient use of importScripts, importScripts will block until - //its script is downloaded and evaluated. However, if web workers - //are in play, the expectation that a build has been done so that - //only one script needs to be loaded anyway. This may need to be - //reevaluated if other use cases become common. - importScripts(url); - - //Account for anonymous modules - context.completeLoad(moduleName); - } catch (e) { - context.onError( - makeError( - "importscripts", - "importScripts failed for " + moduleName + " at " + url, - e, - [moduleName] - ) - ); - } - } - }; - - function getInteractiveScript() { - if (interactiveScript && interactiveScript.readyState === "interactive") { - return interactiveScript; - } - - eachReverse(scripts(), function (script) { - if (script.readyState === "interactive") { - return (interactiveScript = script); - } - }); - return interactiveScript; - } - - //Look for a data-main script attribute, which could also adjust the baseUrl. - if (isBrowser && !cfg.skipDataMain) { - //Figure out baseUrl. Get it from the script tag with require.js in it. - eachReverse(scripts(), function (script) { - //Set the 'head' where we can append children by - //using the script's parent. - if (!head) { - head = script.parentNode; - } - - //Look for a data-main attribute to set main script for the page - //to load. If it is there, the path to data main becomes the - //baseUrl, if it is not already set. - dataMain = script.getAttribute("data-main"); - if (dataMain) { - //Preserve dataMain in case it is a path (i.e. contains '?') - mainScript = dataMain; - - //Set final baseUrl if there is not already an explicit one. - if (!cfg.baseUrl) { - //Pull off the directory of data-main for use as the - //baseUrl. - src = mainScript.split("/"); - mainScript = src.pop(); - subPath = src.length ? src.join("/") + "/" : "./"; - - cfg.baseUrl = subPath; - } - - //Strip off any trailing .js since mainScript is now - //like a module name. - mainScript = mainScript.replace(jsSuffixRegExp, ""); - - //If mainScript is still a path, fall back to dataMain - if (req.jsExtRegExp.test(mainScript)) { - mainScript = dataMain; - } - - //Put the data-main script in the files to load. - cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; - - return true; - } - }); - } - - /** - * The function that handles definitions of modules. Differs from - * require() in that a string for the module should be the first argument, - * and the function to execute after dependencies are loaded should - * return a value to define the module corresponding to the first argument's - * name. - */ - define = function (name, deps, callback) { - var node, context; - - //Allow for anonymous modules - if (typeof name !== "string") { - //Adjust args appropriately - callback = deps; - deps = name; - name = null; - } - - //This module may not have dependencies - if (!isArray(deps)) { - callback = deps; - deps = null; - } - - //If no name, and callback is a function, then figure out if it a - //CommonJS thing with dependencies. - if (!deps && isFunction(callback)) { - deps = []; - //Remove comments from the callback string, - //look for require calls, and pull them into the dependencies, - //but only if there are function args. - if (callback.length) { - callback - .toString() - .replace(commentRegExp, "") - .replace(cjsRequireRegExp, function (match, dep) { - deps.push(dep); - }); - - //May be a CommonJS thing even without require calls, but still - //could use exports, and module. Avoid doing exports and module - //work though if it just needs require. - //REQUIRES the function to expect the CommonJS variables in the - //order listed below. - deps = (callback.length === 1 - ? ["require"] - : ["require", "exports", "module"] - ).concat(deps); - } - } - - //If in IE 6-8 and hit an anonymous define() call, do the interactive - //work. - if (useInteractive) { - node = currentlyAddingScript || getInteractiveScript(); - if (node) { - if (!name) { - name = node.getAttribute("data-requiremodule"); - } - context = contexts[node.getAttribute("data-requirecontext")]; - } - } - - //Always save off evaluating the def call until the script onload handler. - //This allows multiple modules to be in a file without prematurely - //tracing dependencies, and allows for anonymous module support, - //where the module name is not known until the script onload event - //occurs. If no context, use the global queue, and get it processed - //in the onscript load callback. - if (context) { - context.defQueue.push([name, deps, callback]); - context.defQueueMap[name] = true; - } else { - globalDefQueue.push([name, deps, callback]); - } - }; - - define.amd = { - jQuery: true, - }; - - /** - * Executes the text. Normally just uses eval, but can be modified - * to use a better, environment-specific call. Only used for transpiling - * loader plugins, not for plain JS modules. - * @param {string} text the text to execute/evaluate. - */ - req.exec = function (text) { - /*jslint evil: true */ - return eval(text); - }; - - //Set up with config info. - req(cfg); -})(this); diff --git a/packages/engine/Source/WorkersES6/combineGeometry.js b/packages/engine/Source/Workers/combineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/combineGeometry.js rename to packages/engine/Source/Workers/combineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createBoxGeometry.js b/packages/engine/Source/Workers/createBoxGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createBoxGeometry.js rename to packages/engine/Source/Workers/createBoxGeometry.js diff --git a/packages/engine/Source/WorkersES6/createBoxOutlineGeometry.js b/packages/engine/Source/Workers/createBoxOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createBoxOutlineGeometry.js rename to packages/engine/Source/Workers/createBoxOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createCircleGeometry.js b/packages/engine/Source/Workers/createCircleGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createCircleGeometry.js rename to packages/engine/Source/Workers/createCircleGeometry.js diff --git a/packages/engine/Source/WorkersES6/createCircleOutlineGeometry.js b/packages/engine/Source/Workers/createCircleOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createCircleOutlineGeometry.js rename to packages/engine/Source/Workers/createCircleOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createCoplanarPolygonGeometry.js b/packages/engine/Source/Workers/createCoplanarPolygonGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createCoplanarPolygonGeometry.js rename to packages/engine/Source/Workers/createCoplanarPolygonGeometry.js diff --git a/packages/engine/Source/WorkersES6/createCoplanarPolygonOutlineGeometry.js b/packages/engine/Source/Workers/createCoplanarPolygonOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createCoplanarPolygonOutlineGeometry.js rename to packages/engine/Source/Workers/createCoplanarPolygonOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createCorridorGeometry.js b/packages/engine/Source/Workers/createCorridorGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createCorridorGeometry.js rename to packages/engine/Source/Workers/createCorridorGeometry.js diff --git a/packages/engine/Source/WorkersES6/createCorridorOutlineGeometry.js b/packages/engine/Source/Workers/createCorridorOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createCorridorOutlineGeometry.js rename to packages/engine/Source/Workers/createCorridorOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createCylinderGeometry.js b/packages/engine/Source/Workers/createCylinderGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createCylinderGeometry.js rename to packages/engine/Source/Workers/createCylinderGeometry.js diff --git a/packages/engine/Source/WorkersES6/createCylinderOutlineGeometry.js b/packages/engine/Source/Workers/createCylinderOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createCylinderOutlineGeometry.js rename to packages/engine/Source/Workers/createCylinderOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createEllipseGeometry.js b/packages/engine/Source/Workers/createEllipseGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createEllipseGeometry.js rename to packages/engine/Source/Workers/createEllipseGeometry.js diff --git a/packages/engine/Source/WorkersES6/createEllipseOutlineGeometry.js b/packages/engine/Source/Workers/createEllipseOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createEllipseOutlineGeometry.js rename to packages/engine/Source/Workers/createEllipseOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createEllipsoidGeometry.js b/packages/engine/Source/Workers/createEllipsoidGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createEllipsoidGeometry.js rename to packages/engine/Source/Workers/createEllipsoidGeometry.js diff --git a/packages/engine/Source/WorkersES6/createEllipsoidOutlineGeometry.js b/packages/engine/Source/Workers/createEllipsoidOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createEllipsoidOutlineGeometry.js rename to packages/engine/Source/Workers/createEllipsoidOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createFrustumGeometry.js b/packages/engine/Source/Workers/createFrustumGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createFrustumGeometry.js rename to packages/engine/Source/Workers/createFrustumGeometry.js diff --git a/packages/engine/Source/WorkersES6/createFrustumOutlineGeometry.js b/packages/engine/Source/Workers/createFrustumOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createFrustumOutlineGeometry.js rename to packages/engine/Source/Workers/createFrustumOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createGeometry.js b/packages/engine/Source/Workers/createGeometry.js similarity index 69% rename from packages/engine/Source/WorkersES6/createGeometry.js rename to packages/engine/Source/Workers/createGeometry.js index b45d6a26736b..063453e50e56 100644 --- a/packages/engine/Source/WorkersES6/createGeometry.js +++ b/packages/engine/Source/Workers/createGeometry.js @@ -1,29 +1,27 @@ -/* global require */ import defined from "../Core/defined.js"; import PrimitivePipeline from "../Scene/PrimitivePipeline.js"; import createTaskProcessorWorker from "./createTaskProcessorWorker.js"; const moduleCache = {}; -function getModule(moduleName) { +async function getModule(moduleName) { let module = moduleCache[moduleName]; if (!defined(module)) { if (typeof exports === "object") { // Use CommonJS-style require. + /* global require */ moduleCache[module] = module = require(`Workers/${moduleName}`); } else { - // Use AMD-style require. - // in web workers, require is synchronous - require([`Workers/${moduleName}`], function (f) { - module = f; - moduleCache[module] = f; - }); + // Use ESM-style dynamic import + const result = await import(`./${moduleName}.js`); + module = result.default; + moduleCache[module] = module; } } return module; } -function createGeometry(parameters, transferableObjects) { +async function createGeometry(parameters, transferableObjects) { const subTasks = parameters.subTasks; const length = subTasks.length; const resultsOrPromises = new Array(length); @@ -34,10 +32,11 @@ function createGeometry(parameters, transferableObjects) { const moduleName = task.moduleName; if (defined(moduleName)) { - const createFunction = getModule(moduleName); - resultsOrPromises[i] = createFunction(geometry, task.offset); + resultsOrPromises[i] = getModule(moduleName).then((createFunction) => + createFunction(geometry, task.offset) + ); } else { - //Already created geometry + // Already created geometry resultsOrPromises[i] = geometry; } } diff --git a/packages/engine/Source/WorkersES6/createGroundPolylineGeometry.js b/packages/engine/Source/Workers/createGroundPolylineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createGroundPolylineGeometry.js rename to packages/engine/Source/Workers/createGroundPolylineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createPlaneGeometry.js b/packages/engine/Source/Workers/createPlaneGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createPlaneGeometry.js rename to packages/engine/Source/Workers/createPlaneGeometry.js diff --git a/packages/engine/Source/WorkersES6/createPlaneOutlineGeometry.js b/packages/engine/Source/Workers/createPlaneOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createPlaneOutlineGeometry.js rename to packages/engine/Source/Workers/createPlaneOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createPolygonGeometry.js b/packages/engine/Source/Workers/createPolygonGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createPolygonGeometry.js rename to packages/engine/Source/Workers/createPolygonGeometry.js diff --git a/packages/engine/Source/WorkersES6/createPolygonOutlineGeometry.js b/packages/engine/Source/Workers/createPolygonOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createPolygonOutlineGeometry.js rename to packages/engine/Source/Workers/createPolygonOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createPolylineGeometry.js b/packages/engine/Source/Workers/createPolylineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createPolylineGeometry.js rename to packages/engine/Source/Workers/createPolylineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createPolylineVolumeGeometry.js b/packages/engine/Source/Workers/createPolylineVolumeGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createPolylineVolumeGeometry.js rename to packages/engine/Source/Workers/createPolylineVolumeGeometry.js diff --git a/packages/engine/Source/WorkersES6/createPolylineVolumeOutlineGeometry.js b/packages/engine/Source/Workers/createPolylineVolumeOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createPolylineVolumeOutlineGeometry.js rename to packages/engine/Source/Workers/createPolylineVolumeOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createRectangleGeometry.js b/packages/engine/Source/Workers/createRectangleGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createRectangleGeometry.js rename to packages/engine/Source/Workers/createRectangleGeometry.js diff --git a/packages/engine/Source/WorkersES6/createRectangleOutlineGeometry.js b/packages/engine/Source/Workers/createRectangleOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createRectangleOutlineGeometry.js rename to packages/engine/Source/Workers/createRectangleOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createSimplePolylineGeometry.js b/packages/engine/Source/Workers/createSimplePolylineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createSimplePolylineGeometry.js rename to packages/engine/Source/Workers/createSimplePolylineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createSphereGeometry.js b/packages/engine/Source/Workers/createSphereGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createSphereGeometry.js rename to packages/engine/Source/Workers/createSphereGeometry.js diff --git a/packages/engine/Source/WorkersES6/createSphereOutlineGeometry.js b/packages/engine/Source/Workers/createSphereOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createSphereOutlineGeometry.js rename to packages/engine/Source/Workers/createSphereOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/createTaskProcessorWorker.js b/packages/engine/Source/Workers/createTaskProcessorWorker.js similarity index 54% rename from packages/engine/Source/WorkersES6/createTaskProcessorWorker.js rename to packages/engine/Source/Workers/createTaskProcessorWorker.js index 93f201dd4d18..f2738332e23f 100644 --- a/packages/engine/Source/WorkersES6/createTaskProcessorWorker.js +++ b/packages/engine/Source/Workers/createTaskProcessorWorker.js @@ -1,21 +1,5 @@ -import defaultValue from "../Core/defaultValue.js"; -import defined from "../Core/defined.js"; import formatError from "../Core/formatError.js"; -// createXXXGeometry functions may return Geometry or a Promise that resolves to Geometry -// if the function requires access to ApproximateTerrainHeights. -// For fully synchronous functions, just wrapping the function call in a Promise doesn't -// handle errors correctly, hence try-catch -function callAndWrap(workerFunction, parameters, transferableObjects) { - let resultOrPromise; - try { - resultOrPromise = workerFunction(parameters, transferableObjects); - return resultOrPromise; // errors handled by Promise - } catch (e) { - return Promise.reject(e); - } -} - /** * Creates an adapter function to allow a calculation function to operate as a Web Worker, * paired with TaskProcessor, to receive tasks and return results. @@ -42,11 +26,7 @@ function callAndWrap(workerFunction, parameters, transferableObjects) { * @see {@link http://www.w3.org/TR/html5/common-dom-interfaces.html#transferable-objects|Transferable objects} */ function createTaskProcessorWorker(workerFunction) { - let postMessage; - - return function (event) { - const data = event.data; - + async function onMessageHandler({ data }) { const transferableObjects = []; const responseMessage = { id: data.id, @@ -54,46 +34,48 @@ function createTaskProcessorWorker(workerFunction) { error: undefined, }; - return Promise.resolve( - callAndWrap(workerFunction, data.parameters, transferableObjects) - ) - .then(function (result) { - responseMessage.result = result; - }) - .catch(function (e) { - if (e instanceof Error) { - // Errors can't be posted in a message, copy the properties - responseMessage.error = { - name: e.name, - message: e.message, - stack: e.stack, - }; - } else { - responseMessage.error = e; - } - }) - .finally(function () { - if (!defined(postMessage)) { - postMessage = defaultValue(self.webkitPostMessage, self.postMessage); - } + try { + const result = await workerFunction(data.parameters, transferableObjects); + responseMessage.result = result; + } catch (error) { + if (error instanceof Error) { + responseMessage.error = { + name: error.name, + message: error.message, + stack: error.stack, + }; + } else { + responseMessage.error = error; + } + } - if (!data.canTransferArrayBuffer) { - transferableObjects.length = 0; - } + if (!data.canTransferArrayBuffer) { + transferableObjects.length = 0; + } + + try { + postMessage(responseMessage, transferableObjects); + } catch (error) { + // something went wrong trying to post the message, post a simpler + // error that we can be sure will be cloneable + responseMessage.result = undefined; + responseMessage.error = `postMessage failed with error: ${formatError( + error + )}\n with responseMessage: ${JSON.stringify(responseMessage)}`; + postMessage(responseMessage); + } + } + + function onMessageErrorHandler(event) { + postMessage({ + id: event.data?.id, + error: `postMessage failed with error: ${JSON.stringify(event)}`, + }); + } - try { - postMessage(responseMessage, transferableObjects); - } catch (e) { - // something went wrong trying to post the message, post a simpler - // error that we can be sure will be cloneable - responseMessage.result = undefined; - responseMessage.error = `postMessage failed with error: ${formatError( - e - )}\n with responseMessage: ${JSON.stringify(responseMessage)}`; - postMessage(responseMessage); - } - }); - }; + self.onmessage = onMessageHandler; + self.onmessageerror = onMessageErrorHandler; + return self; } /** diff --git a/packages/engine/Source/WorkersES6/createVectorTileClampedPolylines.js b/packages/engine/Source/Workers/createVectorTileClampedPolylines.js similarity index 100% rename from packages/engine/Source/WorkersES6/createVectorTileClampedPolylines.js rename to packages/engine/Source/Workers/createVectorTileClampedPolylines.js diff --git a/packages/engine/Source/WorkersES6/createVectorTileGeometries.js b/packages/engine/Source/Workers/createVectorTileGeometries.js similarity index 100% rename from packages/engine/Source/WorkersES6/createVectorTileGeometries.js rename to packages/engine/Source/Workers/createVectorTileGeometries.js diff --git a/packages/engine/Source/WorkersES6/createVectorTilePoints.js b/packages/engine/Source/Workers/createVectorTilePoints.js similarity index 100% rename from packages/engine/Source/WorkersES6/createVectorTilePoints.js rename to packages/engine/Source/Workers/createVectorTilePoints.js diff --git a/packages/engine/Source/WorkersES6/createVectorTilePolygons.js b/packages/engine/Source/Workers/createVectorTilePolygons.js similarity index 100% rename from packages/engine/Source/WorkersES6/createVectorTilePolygons.js rename to packages/engine/Source/Workers/createVectorTilePolygons.js diff --git a/packages/engine/Source/WorkersES6/createVectorTilePolylines.js b/packages/engine/Source/Workers/createVectorTilePolylines.js similarity index 100% rename from packages/engine/Source/WorkersES6/createVectorTilePolylines.js rename to packages/engine/Source/Workers/createVectorTilePolylines.js diff --git a/packages/engine/Source/WorkersES6/createVerticesFromGoogleEarthEnterpriseBuffer.js b/packages/engine/Source/Workers/createVerticesFromGoogleEarthEnterpriseBuffer.js similarity index 100% rename from packages/engine/Source/WorkersES6/createVerticesFromGoogleEarthEnterpriseBuffer.js rename to packages/engine/Source/Workers/createVerticesFromGoogleEarthEnterpriseBuffer.js diff --git a/packages/engine/Source/WorkersES6/createVerticesFromHeightmap.js b/packages/engine/Source/Workers/createVerticesFromHeightmap.js similarity index 100% rename from packages/engine/Source/WorkersES6/createVerticesFromHeightmap.js rename to packages/engine/Source/Workers/createVerticesFromHeightmap.js diff --git a/packages/engine/Source/WorkersES6/createVerticesFromQuantizedTerrainMesh.js b/packages/engine/Source/Workers/createVerticesFromQuantizedTerrainMesh.js similarity index 100% rename from packages/engine/Source/WorkersES6/createVerticesFromQuantizedTerrainMesh.js rename to packages/engine/Source/Workers/createVerticesFromQuantizedTerrainMesh.js diff --git a/packages/engine/Source/WorkersES6/createWallGeometry.js b/packages/engine/Source/Workers/createWallGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createWallGeometry.js rename to packages/engine/Source/Workers/createWallGeometry.js diff --git a/packages/engine/Source/WorkersES6/createWallOutlineGeometry.js b/packages/engine/Source/Workers/createWallOutlineGeometry.js similarity index 100% rename from packages/engine/Source/WorkersES6/createWallOutlineGeometry.js rename to packages/engine/Source/Workers/createWallOutlineGeometry.js diff --git a/packages/engine/Source/WorkersES6/decodeDraco.js b/packages/engine/Source/Workers/decodeDraco.js similarity index 92% rename from packages/engine/Source/WorkersES6/decodeDraco.js rename to packages/engine/Source/Workers/decodeDraco.js index c7bf5d321666..14d5d5b268c7 100644 --- a/packages/engine/Source/WorkersES6/decodeDraco.js +++ b/packages/engine/Source/Workers/decodeDraco.js @@ -1,9 +1,9 @@ -/* global require */ import ComponentDatatype from "../Core/ComponentDatatype.js"; import defined from "../Core/defined.js"; import IndexDatatype from "../Core/IndexDatatype.js"; import RuntimeError from "../Core/RuntimeError.js"; import createTaskProcessorWorker from "./createTaskProcessorWorker.js"; +import dracoModule from "draco3d/draco_decoder_nodejs.js"; let draco; @@ -351,39 +351,33 @@ function decodePrimitive(parameters) { return result; } -function decode(parameters) { +async function decode(parameters, transferableObjects) { if (defined(parameters.bufferView)) { return decodePrimitive(parameters); } return decodePointCloud(parameters); } -function initWorker(dracoModule) { - draco = dracoModule; - self.onmessage = createTaskProcessorWorker(decode); - self.postMessage(true); -} +async function initWorker(parameters, transferableObjects) { + // Require and compile WebAssembly module, or use fallback if not supported + const wasmConfig = parameters.webAssemblyConfig; + if (defined(wasmConfig) && defined(wasmConfig.wasmBinaryFile)) { + draco = await dracoModule(wasmConfig); + } else { + draco = await dracoModule(); + } -function decodeDraco(event) { - const data = event.data; + return true; +} +async function decodeDraco(parameters, transferableObjects) { // Expect the first message to be to load a web assembly module - const wasmConfig = data.webAssemblyConfig; + const wasmConfig = parameters.webAssemblyConfig; if (defined(wasmConfig)) { - // Require and compile WebAssembly module, or use fallback if not supported - return require([wasmConfig.modulePath], function (dracoModule) { - if (defined(wasmConfig.wasmBinaryFile)) { - if (!defined(dracoModule)) { - dracoModule = self.DracoDecoderModule; - } - - dracoModule(wasmConfig).then(function (compiledModule) { - initWorker(compiledModule); - }); - } else { - initWorker(dracoModule()); - } - }); + return initWorker(parameters, transferableObjects); } + + return decode(parameters, transferableObjects); } -export default decodeDraco; + +export default createTaskProcessorWorker(decodeDraco); diff --git a/packages/engine/Source/WorkersES6/decodeGoogleEarthEnterprisePacket.js b/packages/engine/Source/Workers/decodeGoogleEarthEnterprisePacket.js similarity index 100% rename from packages/engine/Source/WorkersES6/decodeGoogleEarthEnterprisePacket.js rename to packages/engine/Source/Workers/decodeGoogleEarthEnterprisePacket.js diff --git a/packages/engine/Source/WorkersES6/decodeI3S.js b/packages/engine/Source/Workers/decodeI3S.js similarity index 96% rename from packages/engine/Source/WorkersES6/decodeI3S.js rename to packages/engine/Source/Workers/decodeI3S.js index dda577731877..fb55b1c3837b 100644 --- a/packages/engine/Source/WorkersES6/decodeI3S.js +++ b/packages/engine/Source/Workers/decodeI3S.js @@ -1,4 +1,3 @@ -/* global require */ import createTaskProcessorWorker from "./createTaskProcessorWorker.js"; import defined from "../Core/defined.js"; import WebMercatorProjection from "../Core/WebMercatorProjection.js"; @@ -7,6 +6,7 @@ import Cartographic from "../Core/Cartographic.js"; import Cartesian3 from "../Core/Cartesian3.js"; import Matrix3 from "../Core/Matrix3.js"; import CesiumMath from "../Core/Math.js"; +import dracoModule from "draco3d/draco_decoder_nodejs.js"; let draco; @@ -171,7 +171,6 @@ function transformToLocal( const rotatedNormal = {}; Matrix3.multiplyByVector(parentRotation, normal, rotatedNormal); - // TODO: check if normals are Z-UP or Y-UP and flip y and z normals[indexOffset] = rotatedNormal.x; normals[indexOffset1] = rotatedNormal.y; normals[indexOffset2] = rotatedNormal.z; @@ -890,17 +889,11 @@ function decodeBinaryGeometry(data, schema, bufferInfo, featureData) { // Use default geometry schema for (let i = 0; i < ordering.length; i++) { const decoder = binaryAttributeDecoders[ordering[i]]; - if (!defined(decoder)) { - console.log(ordering[i]); - } offset = decoder(decodedGeometry, data, offset); } for (let j = 0; j < featureAttributeOrder.length; j++) { const curDecoder = binaryAttributeDecoders[featureAttributeOrder[j]]; - if (!defined(curDecoder)) { - console.log(featureAttributeOrder[j]); - } offset = curDecoder(decodedGeometry, data, offset); } } @@ -914,7 +907,7 @@ function decodeBinaryGeometry(data, schema, bufferInfo, featureData) { return decodedGeometry; } -function decodeI3S(parameters) { +function decodeAndCreateGltf(parameters) { // Decode the data into geometry const geometryData = decode( parameters.binaryData, @@ -1012,33 +1005,26 @@ function decodeI3S(parameters) { return results; } -function initWorker(dracoModule) { - draco = dracoModule; - self.onmessage = createTaskProcessorWorker(decodeI3S); - self.postMessage(true); -} +async function initWorker(parameters, transferableObjects) { + // Require and compile WebAssembly module, or use fallback if not supported + const wasmConfig = parameters.webAssemblyConfig; + if (defined(wasmConfig) && defined(wasmConfig.wasmBinaryFile)) { + draco = await dracoModule(wasmConfig); + } else { + draco = await dracoModule(); + } -function decodeI3SStart(event) { - const data = event.data; + return true; +} +function decodeI3S(parameters, transferableObjects) { // Expect the first message to be to load a web assembly module - const wasmConfig = data.webAssemblyConfig; + const wasmConfig = parameters.webAssemblyConfig; if (defined(wasmConfig)) { - // Require and compile WebAssembly module, or use fallback if not supported - return require([wasmConfig.modulePath], function (dracoModule) { - if (defined(wasmConfig.wasmBinaryFile)) { - if (!defined(dracoModule)) { - dracoModule = self.DracoDecoderModule; - } - - dracoModule(wasmConfig).then(function (compiledModule) { - initWorker(compiledModule); - }); - } else { - initWorker(dracoModule()); - } - }); + return initWorker(parameters, transferableObjects); } + + return decodeAndCreateGltf(parameters, transferableObjects); } -export default decodeI3SStart; +export default createTaskProcessorWorker(decodeI3S); diff --git a/packages/engine/Source/Workers/package.json b/packages/engine/Source/Workers/package.json deleted file mode 100644 index 0292b9956f2e..000000000000 --- a/packages/engine/Source/Workers/package.json +++ /dev/null @@ -1 +0,0 @@ -{"type":"commonjs"} \ No newline at end of file diff --git a/packages/engine/Source/WorkersES6/transcodeKTX2.js b/packages/engine/Source/Workers/transcodeKTX2.js similarity index 90% rename from packages/engine/Source/WorkersES6/transcodeKTX2.js rename to packages/engine/Source/Workers/transcodeKTX2.js index 9b20e14c2f1e..9926d303b070 100644 --- a/packages/engine/Source/WorkersES6/transcodeKTX2.js +++ b/packages/engine/Source/Workers/transcodeKTX2.js @@ -1,4 +1,4 @@ -/* global require */ +import defaultValue from "../Core/defaultValue.js"; import defined from "../Core/defined.js"; import Check from "../Core/Check.js"; import PixelFormat from "../Core/PixelFormat.js"; @@ -7,6 +7,7 @@ import VulkanConstants from "../Core//VulkanConstants.js"; import PixelDatatype from "../Renderer/PixelDatatype.js"; import createTaskProcessorWorker from "./createTaskProcessorWorker.js"; import { read } from "ktx-parse"; +import basis from "../ThirdParty/Workers/basis_transcoder.js"; const faceOrder = [ "positiveX", @@ -281,36 +282,28 @@ function transcodeCompressed( return result; } -function initWorker(compiledModule) { - transcoderModule = compiledModule; +async function initWorker(parameters, transferableObjects) { + // Require and compile WebAssembly module, or use fallback if not supported + const wasmConfig = parameters.webAssemblyConfig; + const basisTranscoder = defaultValue(basis, self.BASIS); + if (defined(wasmConfig.wasmBinaryFile)) { + transcoderModule = await basisTranscoder(wasmConfig); + } else { + transcoderModule = await basisTranscoder(); + } + transcoderModule.initializeBasis(); - self.onmessage = createTaskProcessorWorker(transcode); - self.postMessage(true); + return true; } -function transcodeKTX2(event) { - const data = event.data; - +function transcodeKTX2(parameters, transferableObjects) { // Expect the first message to be to load a web assembly module - const wasmConfig = data.webAssemblyConfig; + const wasmConfig = parameters.webAssemblyConfig; if (defined(wasmConfig)) { - // Require and compile WebAssembly module, or use fallback if not supported - return require([wasmConfig.modulePath], function (mscBasisTranscoder) { - if (defined(wasmConfig.wasmBinaryFile)) { - if (!defined(mscBasisTranscoder)) { - mscBasisTranscoder = self.MSC_TRANSCODER; - } - - mscBasisTranscoder(wasmConfig).then(function (compiledModule) { - initWorker(compiledModule); - }); - } else { - return mscBasisTranscoder().then(function (transcoder) { - initWorker(transcoder); - }); - } - }); + return initWorker(parameters, transferableObjects); } + + return transcode(parameters, transferableObjects); } -export default transcodeKTX2; +export default createTaskProcessorWorker(transcodeKTX2); diff --git a/packages/engine/Source/Workers/transferTypedArrayTest.js b/packages/engine/Source/Workers/transferTypedArrayTest.js index 2b391d685c9c..3cebe76ca23f 100644 --- a/packages/engine/Source/Workers/transferTypedArrayTest.js +++ b/packages/engine/Source/Workers/transferTypedArrayTest.js @@ -1,9 +1,3 @@ -// make sure self is defined so that the Dojo build can evaluate this file without crashing. -if (typeof self === "undefined") { - //eslint-disable-next-line no-implicit-globals, no-global-assign - self = {}; -} - self.onmessage = function (event) { const array = event.data.array; const postMessage = self.webkitPostMessage || self.postMessage; diff --git a/packages/engine/Source/WorkersES6/upsampleQuantizedTerrainMesh.js b/packages/engine/Source/Workers/upsampleQuantizedTerrainMesh.js similarity index 100% rename from packages/engine/Source/WorkersES6/upsampleQuantizedTerrainMesh.js rename to packages/engine/Source/Workers/upsampleQuantizedTerrainMesh.js diff --git a/packages/engine/Specs/Scene/PrimitiveSpec.js b/packages/engine/Specs/Scene/PrimitiveSpec.js index 2684b7e0dfbf..c37a7b3cc601 100644 --- a/packages/engine/Specs/Scene/PrimitiveSpec.js +++ b/packages/engine/Specs/Scene/PrimitiveSpec.js @@ -1142,7 +1142,6 @@ describe( }) .catch(function (e) { expect(e).toBe(primitive._error); - // Use toThrow since the error is thrown by RequireJS for the web worker import script expect(function () { scene.render(); }).toThrow(); diff --git a/packages/engine/package.json b/packages/engine/package.json index 9b2228e14eff..acc91ec7876d 100644 --- a/packages/engine/package.json +++ b/packages/engine/package.json @@ -37,6 +37,7 @@ "autolinker": "^4.0.0", "bitmap-sdf": "^1.0.3", "dompurify": "^3.0.2", + "draco3d": "^1.5.1", "earcut": "^2.2.4", "grapheme-splitter": "^1.0.4", "jsep": "^1.3.8", diff --git a/server.js b/server.js index 677776c1d6df..453d4cb732dc 100644 --- a/server.js +++ b/server.js @@ -36,7 +36,6 @@ const argv = yargs(process.argv) .help().argv; import { - bundleWorkers, createCesiumJs, createJsHintOptions, createCombinedSpecList, @@ -51,9 +50,6 @@ const sourceFiles = [ "packages/widgets/Source/**/*.js", "!packages/widgets/Source/*.js", "!packages/engine/Source/Shaders/**", - "!packages/engine/Source/Workers/**", - "!packages/engine/Source/WorkersES6/**", - "packages/engine/Source/WorkersES6/createTaskProcessorWorker.js", "!packages/engine/Source/ThirdParty/Workers/**", "!packages/engine/Source/ThirdParty/google-earth-dbroot-parser.js", "!packages/engine/Source/ThirdParty/_*", @@ -68,7 +64,6 @@ const specFiles = [ "Specs/TestWorkers/*.js", ]; const shaderFiles = ["packages/engine/Source/Shaders/**/*.glsl"]; -const workerSourceFiles = ["packages/engine/Source/WorkersES6/*.js"]; const outputDirectory = path.join("Build", "CesiumDev"); @@ -133,7 +128,7 @@ const serveResult = (result, fileName, res, next) => { (async function () { const gzipHeader = Buffer.from("1F8B08", "hex"); - let esmResult, iifeResult, specResult; + let esmResult, iifeResult, workersResult, specResult; const production = argv.production; let contexts; @@ -209,28 +204,6 @@ const serveResult = (result, fileName, res, next) => { app.get(knownTilesetFormats, checkGzipAndNext); if (!production) { - // Set up file watcher for more expensive operations which would block during - // "just in time" compilation - const workerWatcher = chokidar.watch(workerSourceFiles, { - ignoreInitial: true, - }); - workerWatcher.on("all", async () => { - try { - const start = performance.now(); - await bundleWorkers({ - input: ["packages/engine/Source/Workers/**"], - inputES6: workerSourceFiles, - path: outputDirectory, - sourcemap: true, - }); - console.log( - `Built Workers/* in ${formatTimeSinceInSeconds(start)} seconds.` - ); - } catch (e) { - console.error(e); - } - }); - app.get("/Build/CesiumUnminified/Cesium.js", async function ( //eslint-disable-next-line no-unused-vars req, @@ -340,9 +313,42 @@ const serveResult = (result, fileName, res, next) => { if (iifeResult) { iifeResult.outputFiles = []; } + if (workersResult) { + workersResult.outputFiles = []; + } jsHintOptionsCache = undefined; }); + app.get("/Build/CesiumUnminified/Workers/*.js", async function ( + //eslint-disable-next-line no-unused-vars + req, + //eslint-disable-next-line no-unused-vars + res, + next + ) { + if ( + !workersResult?.outputFiles || + workersResult.outputFiles.length === 0 + ) { + try { + const start = performance.now(); + workersResult = await contexts.workers.rebuild(); + console.log( + `Built Workers/* in ${formatTimeSinceInSeconds(start)} seconds.` + ); + } catch (e) { + next(e); + } + } + + return serveResult( + workersResult, + path.basename(req.originalUrl), + res, + next + ); + }); + app.get("/Apps/Sandcastle/jsHintOptions.js", async function ( //eslint-disable-next-line no-unused-vars req, @@ -530,7 +536,7 @@ const serveResult = (result, fileName, res, next) => { let isFirstSig = true; process.on("SIGINT", function () { if (isFirstSig) { - console.log("Cesium development server shutting down."); + console.log("\nCesium development server shutting down."); server.close(function () { process.exit(0); }); @@ -538,6 +544,7 @@ const serveResult = (result, fileName, res, next) => { if (!production) { contexts.esm.dispose(); contexts.iife.dispose(); + contexts.workers.dispose(); contexts.specs.dispose(); } From edca885538030ab551c22502bbd5ba32bdb54500 Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Fri, 7 Jul 2023 16:16:34 -0400 Subject: [PATCH 02/10] TestWorkers, specs --- Specs/BadGeometry.js | 2 +- Specs/TestWorkers/.eslintrc.json | 12 +- Specs/TestWorkers/createBadGeometry.js | 8 +- Specs/TestWorkers/returnByteLength.js | 10 +- Specs/TestWorkers/returnNonCloneable.js | 14 +- Specs/TestWorkers/returnParameters.js | 10 +- Specs/TestWorkers/returnWasmConfig.js | 11 +- Specs/TestWorkers/throwError.js | 10 +- Specs/TestWorkers/transferArrayBuffer.js | 17 +- build.js | 36 ++- gulpfile.js | 4 +- packages/engine/Source/Core/KTX2Transcoder.js | 4 +- packages/engine/Source/Core/TaskProcessor.js | 15 +- packages/engine/Source/Core/buildModuleUrl.js | 2 +- packages/engine/Source/Scene/DracoLoader.js | 4 +- packages/engine/Source/Scene/I3SDecoder.js | 6 +- packages/engine/Source/Scene/I3SNode.js | 2 +- .../Workers/createTaskProcessorWorker.js | 2 + .../engine/Specs/Core/TaskProcessorSpec.js | 189 ++++++------- packages/engine/Specs/Scene/I3SNodeSpec.js | 100 +++---- server.js | 257 +++++++----------- 21 files changed, 309 insertions(+), 406 deletions(-) diff --git a/Specs/BadGeometry.js b/Specs/BadGeometry.js index 7119e214cc52..d38dae9168b4 100644 --- a/Specs/BadGeometry.js +++ b/Specs/BadGeometry.js @@ -1,7 +1,7 @@ import { queryToObject, RuntimeError } from "@cesium/engine"; function BadGeometry() { - this._workerName = "../../Specs/TestWorkers/createBadGeometry"; + this._workerName = "../../Build/Specs/TestWorkers/createBadGeometry"; // Make this worker loadable when testing against the built version of Cesium. if ( diff --git a/Specs/TestWorkers/.eslintrc.json b/Specs/TestWorkers/.eslintrc.json index 0cdae29f8255..cfa5954c554a 100644 --- a/Specs/TestWorkers/.eslintrc.json +++ b/Specs/TestWorkers/.eslintrc.json @@ -1,10 +1,6 @@ { - "extends": "../.eslintrc.json", - "env": { - "amd": true - }, - "parserOptions": { - "ecmaVersion": 2015, - "sourceType": "script" - } + "extends": "cesium/browser", + "plugins": [ + "es" + ] } \ No newline at end of file diff --git a/Specs/TestWorkers/createBadGeometry.js b/Specs/TestWorkers/createBadGeometry.js index 187b75dc1e27..078c247f9110 100644 --- a/Specs/TestWorkers/createBadGeometry.js +++ b/Specs/TestWorkers/createBadGeometry.js @@ -1,7 +1,5 @@ -define(function () { - "use strict"; +import { createTaskProcessorWorker } from "@cesium/engine"; - return function () { - throw new Error("BadGeometry.createGeometry"); - }; +export default createTaskProcessorWorker(function () { + throw new Error("BadGeometry.createGeometry"); }); diff --git a/Specs/TestWorkers/returnByteLength.js b/Specs/TestWorkers/returnByteLength.js index 070024f8a16d..fa25f1df4f65 100644 --- a/Specs/TestWorkers/returnByteLength.js +++ b/Specs/TestWorkers/returnByteLength.js @@ -1,9 +1,5 @@ -define(["Workers/createTaskProcessorWorker"], function ( - createTaskProcessorWorker -) { - "use strict"; +import { createTaskProcessorWorker } from "@cesium/engine"; - return createTaskProcessorWorker(function (parameters, transferableObjects) { - return parameters.byteLength; - }); +export default createTaskProcessorWorker(function (parameters) { + return parameters.byteLength; }); diff --git a/Specs/TestWorkers/returnNonCloneable.js b/Specs/TestWorkers/returnNonCloneable.js index 817e939f484a..d89b5084a27c 100644 --- a/Specs/TestWorkers/returnNonCloneable.js +++ b/Specs/TestWorkers/returnNonCloneable.js @@ -1,11 +1,7 @@ -define(["Workers/createTaskProcessorWorker"], function ( - createTaskProcessorWorker -) { - "use strict"; +import { createTaskProcessorWorker } from "@cesium/engine"; - return createTaskProcessorWorker(function (parameters, transferableObjects) { - return function () { - //functions are not cloneable - }; - }); +export default createTaskProcessorWorker(function () { + return function () { + //functions are not cloneable + }; }); diff --git a/Specs/TestWorkers/returnParameters.js b/Specs/TestWorkers/returnParameters.js index 356ae06e2584..956a0a4f98a3 100644 --- a/Specs/TestWorkers/returnParameters.js +++ b/Specs/TestWorkers/returnParameters.js @@ -1,9 +1,5 @@ -define(["Workers/createTaskProcessorWorker"], function ( - createTaskProcessorWorker -) { - "use strict"; +import { createTaskProcessorWorker } from "@cesium/engine"; - return createTaskProcessorWorker(function (parameters, transferableObjects) { - return parameters; - }); +export default createTaskProcessorWorker(function (parameters) { + return parameters; }); diff --git a/Specs/TestWorkers/returnWasmConfig.js b/Specs/TestWorkers/returnWasmConfig.js index 975d90d15e32..e9c199373f26 100644 --- a/Specs/TestWorkers/returnWasmConfig.js +++ b/Specs/TestWorkers/returnWasmConfig.js @@ -1,9 +1,6 @@ -define([], function () { - "use strict"; +import { createTaskProcessorWorker } from "@cesium/engine"; - return function returnWasmConfig(event) { - const data = event.data; - const wasmConfig = data.webAssemblyConfig; - self.postMessage(wasmConfig); - }; +export default createTaskProcessorWorker(function returnWasmConfig(parameters) { + const wasmConfig = parameters.webAssemblyConfig; + return wasmConfig; }); diff --git a/Specs/TestWorkers/throwError.js b/Specs/TestWorkers/throwError.js index 6c7298eea26b..0fb1b4dafac8 100644 --- a/Specs/TestWorkers/throwError.js +++ b/Specs/TestWorkers/throwError.js @@ -1,9 +1,5 @@ -define(["Workers/createTaskProcessorWorker"], function ( - createTaskProcessorWorker -) { - "use strict"; +import { createTaskProcessorWorker } from "@cesium/engine"; - return createTaskProcessorWorker(function (parameters, transferableObjects) { - throw new Error(parameters.message); - }); +export default createTaskProcessorWorker(function (parameters) { + throw new Error(parameters.message); }); diff --git a/Specs/TestWorkers/transferArrayBuffer.js b/Specs/TestWorkers/transferArrayBuffer.js index 8a4b8fa8285a..f79f22d0973c 100644 --- a/Specs/TestWorkers/transferArrayBuffer.js +++ b/Specs/TestWorkers/transferArrayBuffer.js @@ -1,11 +1,10 @@ -define(["Workers/createTaskProcessorWorker"], function ( - createTaskProcessorWorker -) { - "use strict"; +import { createTaskProcessorWorker } from "@cesium/engine"; - return createTaskProcessorWorker(function (parameters, transferableObjects) { - const arrayBuffer = new ArrayBuffer(parameters.byteLength); - transferableObjects.push(arrayBuffer); - return arrayBuffer; - }); +export default createTaskProcessorWorker(function ( + parameters, + transferableObjects +) { + const arrayBuffer = new ArrayBuffer(parameters.byteLength); + transferableObjects.push(arrayBuffer); + return arrayBuffer; }); diff --git a/build.js b/build.js index aa7c608c0fdb..9d973ab2553e 100644 --- a/build.js +++ b/build.js @@ -350,7 +350,6 @@ export async function bundleWorkers(options) { workerConfig.banner = { js: combinedCopyrightHeader, }; - workerConfig.treeShaking = true; // Tree shaking must be turned on manually for ESM workerConfig.entryPoints = workers; workerConfig.outdir = path.join(options.path, "Workers"); workerConfig.minify = options.minify; @@ -731,7 +730,7 @@ export async function createJsHintOptions() { * @param {boolean} [options.write=false] true if build output should be written to disk. If false, the files that would have been written as in-memory buffers * @returns {Promise} */ -export function bundleCombinedSpecs(options) { +export async function bundleCombinedSpecs(options) { options = options || {}; let build = esbuild.build; @@ -755,6 +754,33 @@ export function bundleCombinedSpecs(options) { }); } +/** + * Bundles test worker in used specs. + * @param {object} options + * @param {boolean} [options.incremental=false] true if the build should be cached for repeated rebuilds + * @param {boolean} [options.write=false] true if build output should be written to disk. If false, the files that would have been written as in-memory buffers + * @returns {Promise} + */ +export async function bundleTestWorkers(options) { + options = options || {}; + + let build = esbuild.build; + if (options.incremental) { + build = esbuild.context; + } + + const workers = await globby(["Specs/TestWorkers/**.js"]); + return build({ + entryPoints: workers, + bundle: true, + format: "esm", + sourcemap: true, + outdir: path.join("Build", "Specs", "TestWorkers"), + external: ["http", "https", "url", "zlib", "fs", "path"], + write: options.write, + }); +} + /** * Creates the index.js for a package. * @@ -1070,6 +1096,11 @@ export async function buildCesium(options) { write: write, }); + const testWorkersContext = await bundleTestWorkers({ + incremental: incremental, + write: write, + }); + // Copy static assets to the Build folder. await copyEngineAssets(outputDirectory); @@ -1113,5 +1144,6 @@ export async function buildCesium(options) { node: contexts.node, specs: specsContext, workers: workersContext, + testWorkers: testWorkersContext, }; } diff --git a/gulpfile.js b/gulpfile.js index 74335df1475a..52dcbe26982d 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1546,7 +1546,7 @@ export async function test() { { pattern: "Build/CesiumUnminified/**", included: false }, { pattern: "Build/Specs/karma-main.js", included: true, type: "module" }, { pattern: "Build/Specs/SpecList.js", included: true, type: "module" }, - { pattern: "Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**", included: false }, ]; let proxies; @@ -1570,7 +1570,7 @@ export async function test() { { pattern: "packages/engine/Source/ThirdParty/**", included: false }, { pattern: "packages/engine/Source/Widget/*.css", included: false }, { pattern: "Specs/TestWorkers/**/*.wasm", included: false }, - { pattern: "Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**", included: false }, ]; proxies = { diff --git a/packages/engine/Source/Core/KTX2Transcoder.js b/packages/engine/Source/Core/KTX2Transcoder.js index 638805d9e93b..f570a32dc691 100644 --- a/packages/engine/Source/Core/KTX2Transcoder.js +++ b/packages/engine/Source/Core/KTX2Transcoder.js @@ -23,8 +23,8 @@ function makeReadyPromise() { .initWebAssemblyModule({ wasmBinaryFile: "ThirdParty/basis_transcoder.wasm", }) - .then(function (message) { - if (message.result) { + .then(function (result) { + if (result) { return KTX2Transcoder._transcodeTaskProcessor; } diff --git a/packages/engine/Source/Core/TaskProcessor.js b/packages/engine/Source/Core/TaskProcessor.js index 4884834bde18..b1ab677ed090 100644 --- a/packages/engine/Source/Core/TaskProcessor.js +++ b/packages/engine/Source/Core/TaskProcessor.js @@ -117,7 +117,6 @@ async function getWebAssemblyLoaderConfig(processor, wasmOptions) { return config; } - config.modulePath = buildModuleUrl(wasmOptions.modulePath); config.wasmBinaryFile = buildModuleUrl(wasmOptions.wasmBinaryFile); const arrayBuffer = await Resource.fetchArrayBuffer({ @@ -147,7 +146,11 @@ function TaskProcessor(workerPath, maximumActiveTasks) { const isUri = uri.scheme().length !== 0 && uri.fragment().length === 0; this._workerPath = isUri ? workerPath - : getWorkerUrl(`${TaskProcessor._workerModulePrefix + workerPath}.js`); + : getWorkerUrl( + `${ + TaskProcessor._workerModulePrefix + workerPath.replace(/\.js$/, "") + }.js` + ); this._maximumActiveTasks = defaultValue( maximumActiveTasks, Number.POSITIVE_INFINITY @@ -171,6 +174,9 @@ const createOnmessageHandler = (worker, id, resolve, reject) => { } else if (error.name === "DeveloperError") { error = new DeveloperError(data.error.message); error.stack = data.error.stack; + } else if (error.name === "Error") { + error = new Error(data.error.message); + error.stack = data.error.stack; } taskCompletedEvent.raiseEvent(error); reject(error); @@ -205,6 +211,7 @@ async function runTask(processor, parameters, transferableObjects) { processor._worker.postMessage( { id: id, + baseUrl: buildModuleUrl.getCesiumBaseUrl().url, parameters: parameters, canTransferArrayBuffer: canTransfer, }, @@ -277,7 +284,7 @@ TaskProcessor.prototype.scheduleTask = function ( * @param {string} [webAssemblyOptions.modulePath] The path of the web assembly JavaScript wrapper module. * @param {string} [webAssemblyOptions.wasmBinaryFile] The path of the web assembly binary file. * @param {string} [webAssemblyOptions.fallbackModulePath] The path of the fallback JavaScript module to use if web assembly is not supported. - * @returns {Promise} A promise that resolves to the result when the web worker has loaded and compiled the web assembly module and is ready to process tasks. + * @returns {Promise<*>} A promise that resolves to the result when the web worker has loaded and compiled the web assembly module and is ready to process tasks. * * @exception {RuntimeError} This browser does not support Web Assembly, and no backup module was provided */ @@ -304,7 +311,7 @@ TaskProcessor.prototype.initWebAssemblyModule = async function ( const promise = new Promise((resolve, reject) => { worker.onmessage = function ({ data }) { if (data) { - resolve(data); + resolve(data.result); } else { reject(new RuntimeError("Could not configure wasm module")); } diff --git a/packages/engine/Source/Core/buildModuleUrl.js b/packages/engine/Source/Core/buildModuleUrl.js index b51aecff8942..8d99d2b7df17 100644 --- a/packages/engine/Source/Core/buildModuleUrl.js +++ b/packages/engine/Source/Core/buildModuleUrl.js @@ -41,7 +41,7 @@ function getCesiumBaseUrl() { let baseUrlString; if (typeof CESIUM_BASE_URL !== "undefined") { baseUrlString = CESIUM_BASE_URL; - } else if (defined(import.meta)) { + } else if (defined(import.meta) && defined(import.meta.url)) { // ESM baseUrlString = getAbsoluteUri(".", import.meta.url); } else if ( diff --git a/packages/engine/Source/Scene/DracoLoader.js b/packages/engine/Source/Scene/DracoLoader.js index f6d034c11239..56f2eaf71514 100644 --- a/packages/engine/Source/Scene/DracoLoader.js +++ b/packages/engine/Source/Scene/DracoLoader.js @@ -28,8 +28,8 @@ DracoLoader._getDecoderTaskProcessor = function () { .initWebAssemblyModule({ wasmBinaryFile: "ThirdParty/draco_decoder.wasm", }) - .then(function (message) { - if (message.result) { + .then(function (result) { + if (result) { DracoLoader._taskProcessorReady = true; } else { DracoLoader._error = new RuntimeError( diff --git a/packages/engine/Source/Scene/I3SDecoder.js b/packages/engine/Source/Scene/I3SDecoder.js index eeda42c43304..687f516d2425 100644 --- a/packages/engine/Source/Scene/I3SDecoder.js +++ b/packages/engine/Source/Scene/I3SDecoder.js @@ -29,10 +29,10 @@ I3SDecoder._decodeTaskProcessor = new TaskProcessor( I3SDecoder._promise = undefined; async function initializeDecoder() { - const message = await I3SDecoder._decodeTaskProcessor.initWebAssemblyModule({ + const result = await I3SDecoder._decodeTaskProcessor.initWebAssemblyModule({ wasmBinaryFile: "ThirdParty/draco_decoder.wasm", }); - if (message.result) { + if (result) { return I3SDecoder._decodeTaskProcessor; } @@ -43,7 +43,7 @@ async function initializeDecoder() { * Transcodes I3S to glTF in a web worker * @param {String} url custom attributes source URL * @param {Object} defaultGeometrySchema Schema to use during decoding - * @param {Object} geometryData The draco encoded geometry data + * @param {I3SGeometry} geometryData The draco encoded geometry data * @param {Array} [featureData] The draco encoded feature data * @returns Promise Returns a promise which resolves to the glTF result, or undefined if the task cannot be scheduled this frame. * diff --git a/packages/engine/Source/Scene/I3SNode.js b/packages/engine/Source/Scene/I3SNode.js index 9e09e569cb9a..f4038cf204cb 100644 --- a/packages/engine/Source/Scene/I3SNode.js +++ b/packages/engine/Source/Scene/I3SNode.js @@ -653,7 +653,7 @@ I3SNode.prototype._createContentURL = async function () { url, geometrySchema, geometryData, - this._featureData + this._featureData[0] ); if (!defined(result)) { // Postponed diff --git a/packages/engine/Source/Workers/createTaskProcessorWorker.js b/packages/engine/Source/Workers/createTaskProcessorWorker.js index f2738332e23f..deffad5ab06e 100644 --- a/packages/engine/Source/Workers/createTaskProcessorWorker.js +++ b/packages/engine/Source/Workers/createTaskProcessorWorker.js @@ -34,6 +34,8 @@ function createTaskProcessorWorker(workerFunction) { error: undefined, }; + self.CESIUM_BASE_URL = data.baseUrl; + try { const result = await workerFunction(data.parameters, transferableObjects); responseMessage.result = result; diff --git a/packages/engine/Specs/Core/TaskProcessorSpec.js b/packages/engine/Specs/Core/TaskProcessorSpec.js index 2740f2897b33..e4dca8e1761b 100644 --- a/packages/engine/Specs/Core/TaskProcessorSpec.js +++ b/packages/engine/Specs/Core/TaskProcessorSpec.js @@ -6,15 +6,26 @@ describe("Core/TaskProcessor", function () { let taskProcessor; afterEach(function () { + TaskProcessor._workerModulePrefix = + TaskProcessor._defaultWorkerModulePrefix; + if (taskProcessor && !taskProcessor.isDestroyed()) { taskProcessor = taskProcessor.destroy(); } }); - it("works with a simple worker defined as relative to TaskProcessor._workerModulePrefix", function () { - TaskProcessor._workerModulePrefix = absolutize("../Specs/TestWorkers/"); + it("throws runtime error if browser is not supported", async function () { + spyOn(FeatureDetection, "supportsEsmWebWorkers").and.returnValue(false); taskProcessor = new TaskProcessor("returnParameters.js"); + expect(() => taskProcessor.scheduleTask()).toThrowError(RuntimeError); + }); + + it("works with a simple worker", async function () { + taskProcessor = new TaskProcessor( + absolutize("../Build/Specs/TestWorkers/returnParameters.js") + ); + const parameters = { prop: "blah", obj: { @@ -22,20 +33,32 @@ describe("Core/TaskProcessor", function () { }, }; - return taskProcessor - .scheduleTask(parameters) - .then(function (result) { - expect(result).toEqual(parameters); - }) - .finally(function () { - TaskProcessor._workerModulePrefix = - TaskProcessor._defaultWorkerModulePrefix; - }); + await expectAsync(taskProcessor.scheduleTask(parameters)).toBeResolvedTo( + parameters + ); + }); + + it("works with a simple worker defined as relative to TaskProcessor._workerModulePrefix", async function () { + TaskProcessor._workerModulePrefix = absolutize( + "../Build/Specs/TestWorkers/" + ); + taskProcessor = new TaskProcessor("returnParameters.js"); + + const parameters = { + prop: "blah", + obj: { + val: true, + }, + }; + + await expectAsync(taskProcessor.scheduleTask(parameters)).toBeResolvedTo( + parameters + ); }); it("can be destroyed", function () { taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/returnParameters.js") + absolutize("../Specs/Build/TestWorkers/returnParameters.js") ); expect(taskProcessor.isDestroyed()).toEqual(false); @@ -45,35 +68,30 @@ describe("Core/TaskProcessor", function () { expect(taskProcessor.isDestroyed()).toEqual(true); }); - it("can transfer array buffer", function () { + it("can transfer array buffer", async function () { taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/returnByteLength.js") + absolutize("../Build/Specs/TestWorkers/returnByteLength.js") ); const byteLength = 100; const parameters = new ArrayBuffer(byteLength); expect(parameters.byteLength).toEqual(byteLength); - return Promise.resolve(TaskProcessor._canTransferArrayBuffer).then( - function (canTransferArrayBuffer) { - const promise = taskProcessor.scheduleTask(parameters, [parameters]); + const canTransferArrayBuffer = await TaskProcessor._canTransferArrayBuffer; + const result = await taskProcessor.scheduleTask(parameters, [parameters]); - // the worker should see the array with proper byte length - return promise.then(function (result) { - if (canTransferArrayBuffer) { - // array buffer should be neutered when transferred - expect(parameters.byteLength).toEqual(0); - } + // the worker should see the array with proper byte length + if (canTransferArrayBuffer) { + // array buffer should be neutered when transferred + expect(parameters.byteLength).toEqual(0); + } - expect(result).toEqual(byteLength); - }); - } - ); + expect(result).toEqual(byteLength); }); - it("can transfer array buffer back from worker", function () { + it("can transfer array buffer back from worker", async function () { taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/transferArrayBuffer.js") + absolutize("../Build/Specs/TestWorkers/transferArrayBuffer.js") ); const byteLength = 100; @@ -82,14 +100,13 @@ describe("Core/TaskProcessor", function () { }; // the worker should see the array with proper byte length - return taskProcessor.scheduleTask(parameters).then(function (result) { - expect(result.byteLength).toEqual(100); - }); + const result = await taskProcessor.scheduleTask(parameters); + expect(result.byteLength).toEqual(100); }); - it("rejects promise if worker throws", function () { + it("rejects promise if worker throws", async function () { taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/throwError.js") + absolutize("../Build/Specs/TestWorkers/throwError.js") ); const message = "foo"; @@ -97,19 +114,14 @@ describe("Core/TaskProcessor", function () { message: message, }; - return taskProcessor - .scheduleTask(parameters) - .then(function () { - fail("should not be called"); - }) - .catch(function (error) { - expect(error.message).toEqual(message); - }); + await expectAsync( + taskProcessor.scheduleTask(parameters) + ).toBeRejectedWithError(Error, message); }); - it("rejects promise if worker returns a non-clonable result", function () { + it("rejects promise if worker returns a non-clonable result", async function () { taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/returnNonCloneable.js") + absolutize("../Build/Specs/TestWorkers/returnNonCloneable.js") ); const message = "foo"; @@ -117,19 +129,14 @@ describe("Core/TaskProcessor", function () { message: message, }; - return taskProcessor - .scheduleTask(parameters) - .then(function () { - fail("should not be called"); - }) - .catch(function (error) { - expect(error).toContain("postMessage failed"); - }); + await expectAsync(taskProcessor.scheduleTask(parameters)).toBeRejectedWith( + jasmine.stringContaining("postMessage failed") + ); }); - it("successful task raises the taskCompletedEvent", function () { + it("successful task raises the taskCompletedEvent", async function () { taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/returnParameters.js") + absolutize("../Build/Specs/TestWorkers/returnParameters.js") ); const parameters = { @@ -145,19 +152,14 @@ describe("Core/TaskProcessor", function () { } ); - return taskProcessor - .scheduleTask(parameters) - .then(function (result) { - expect(eventRaised).toBe(true); - }) - .finally(function () { - removeListenerCallback(); - }); + await expectAsync(taskProcessor.scheduleTask(parameters)).toBeResolved(); + expect(eventRaised).toBe(true); + removeListenerCallback(); }); - it("unsuccessful task raises the taskCompletedEvent with error", function () { + it("unsuccessful task raises the taskCompletedEvent with error", async function () { taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/returnNonCloneable.js") + absolutize("../Build/Specs/TestWorkers/returnNonCloneable.js") ); const message = "foo"; @@ -173,73 +175,58 @@ describe("Core/TaskProcessor", function () { } ); - return taskProcessor - .scheduleTask(parameters) - .then(function () { - fail("should not be called"); - }) - .catch(function (error) { - expect(eventRaised).toBe(true); - }) - .finally(function () { - removeListenerCallback(); - }); + await expectAsync(taskProcessor.scheduleTask(parameters)).toBeRejected(); + expect(eventRaised).toBe(true); + removeListenerCallback(); }); - it("can load and compile web assembly module", function () { + it("can load and compile web assembly module", async function () { const binaryUrl = absolutize("../Specs/TestWorkers/TestWasm/testWasm.wasm"); taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/returnWasmConfig.js", 5) + absolutize("../Build/Specs/TestWorkers/returnWasmConfig.js", 5) ); - const promise = taskProcessor.initWebAssemblyModule({ - modulePath: "TestWasm/testWasmWrapper", + const result = await taskProcessor.initWebAssemblyModule({ wasmBinaryFile: binaryUrl, fallbackModulePath: "TestWasm/testWasmFallback", }); - return promise.then(function (result) { - expect(result).toBeDefined(); - if (FeatureDetection.supportsWebAssembly()) { - expect(result.modulePath).toMatch(/TestWasm\/testWasmWrapper/); - expect(result.wasmBinary).toBeDefined(); - } - }); + expect(result).toBeDefined(); + if (FeatureDetection.supportsWebAssembly()) { + expect(result.wasmBinary).toBeDefined(); + expect(result.wasmBinaryFile).toEqual(binaryUrl); + } }); - it("uses a backup module if web assembly is not supported", function () { + it("uses a backup module if web assembly is not supported", async function () { const binaryUrl = absolutize("../Specs/TestWorkers/TestWasm/testWasm.wasm"); taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/returnWasmConfig.js", 5) + absolutize("../Build/Specs/TestWorkers/returnWasmConfig.js", 5) ); spyOn(FeatureDetection, "supportsWebAssembly").and.returnValue(false); - const promise = taskProcessor.initWebAssemblyModule({ - modulePath: "TestWasm/testWasmWrapper", + const result = await taskProcessor.initWebAssemblyModule({ wasmBinaryFile: binaryUrl, fallbackModulePath: "TestWasm/testWasmFallback", }); - return promise.then(function (result) { - expect(result).toBeDefined(); - expect(result.modulePath).toMatch(/TestWasm\/testWasmFallback/); - expect(result.wasmBinary).not.toBeDefined(); - }); + expect(result).toBeDefined(); + expect(result.modulePath).toMatch(/TestWasm\/testWasmFallback/); + expect(result.wasmBinary).not.toBeDefined(); }); - it("throws runtime error if web assembly is not supported and no backup is provided", function () { + it("throws runtime error if web assembly is not supported and no backup is provided", async function () { const binaryUrl = absolutize("../Specs/TestWorkers/TestWasm/testWasm.wasm"); taskProcessor = new TaskProcessor( - absolutize("../Specs/TestWorkers/returnWasmConfig.js", 5) + absolutize("../Build/Specs/TestWorkers/returnWasmConfig.js", 5) ); spyOn(FeatureDetection, "supportsWebAssembly").and.returnValue(false); - expect(function () { + await expectAsync( taskProcessor.initWebAssemblyModule({ - modulePath: "TestWasm/testWasmWrapper", wasmBinaryFile: binaryUrl, - }); - }).toThrowError(RuntimeError); + }) + ).toBeRejectedWithError(RuntimeError); }); }); diff --git a/packages/engine/Specs/Scene/I3SNodeSpec.js b/packages/engine/Specs/Scene/I3SNodeSpec.js index 6a3197eafcc3..987f91b0a255 100644 --- a/packages/engine/Specs/Scene/I3SNodeSpec.js +++ b/packages/engine/Specs/Scene/I3SNodeSpec.js @@ -9,6 +9,8 @@ import { I3SNode, I3SLayer, I3SDataProvider, + I3SDecoder, + I3SGeometry, Rectangle, Resource, WebMercatorProjection, @@ -353,7 +355,6 @@ describe("Scene/I3SNode", function () { return tileset; }); const mockI3SProvider = await I3SDataProvider.fromUrl(url); - mockI3SProvider._taskProcessorReadyPromise = Promise.resolve(); mockI3SProvider._geoidDataList = geoidDataList; return mockI3SProvider; } @@ -1278,77 +1279,46 @@ describe("Scene/I3SNode", function () { Promise.resolve(new ArrayBuffer()) ); spyOn(nodeWithMesh, "_loadFeatureData").and.returnValue(Promise.all([])); + spyOn(I3SDecoder, "decode").and.returnValue( + Promise.resolve(i3sGeometryData) + ); - const mockProcessor = { - scheduleTask: function (payload) { - //Expect results to match what was returned by our spy - expect(payload.binaryData).toEqual(new ArrayBuffer()); - - //Expect featureData to be undefined as it is only used for legacy versions (<= 1.6) - expect(payload.featureData).toBeUndefined(); - - expect(payload.bufferInfo).toEqual( - mockI3SLayerWithNodePages._geometryDefinitions[0][1] - ); - - expect(payload.cartographicCenter.longitude).toEqual( - CesiumMath.toRadians(-90) - ); - expect(payload.cartographicCenter.latitude).toEqual( - CesiumMath.toRadians(45) - ); - expect(payload.cartographicCenter.height).toEqual(0); - - expect( - payload.url.endsWith( - "mockProviderUrl/mockLayerUrl/nodes/1/geometries/1/?testQuery=test" - ) - ).toEqual(true); - return Promise.resolve(i3sGeometryData); - }, - }; - spyOn( - nodeWithMesh._dataProvider, - "getDecoderTaskProcessor" - ).and.returnValue(Promise.resolve(mockProcessor)); - - return rootNode - .load() - .then(function () { - return nodeWithMesh.load(); - }) - .then(function () { - return nodeWithMesh._createContentURL(); - }) - .then(function (result) { - expect(result).toBeDefined(); - expect(nodeWithMesh.tile).toBeDefined(); + await rootNode.load(); + await nodeWithMesh.load(); + const result = await nodeWithMesh._createContentURL(); + expect(result).toBeDefined(); + expect(nodeWithMesh.tile).toBeDefined(); + expect(I3SDecoder.decode).toHaveBeenCalledWith( + jasmine.stringContaining( + "mockProviderUrl/mockLayerUrl/nodes/1/geometries/1/?testQuery=test" + ), + jasmine.any(Object), + jasmine.any(I3SGeometry), + undefined + ); - //Test fetching the blob url that was created - return Resource.fetchArrayBuffer(result); - }) - .then(function (data) { - expect(data.error).toBeUndefined(); + //Test fetching the blob url that was created + const data = await Resource.fetchArrayBuffer(result); + expect(data.error).toBeUndefined(); - const magic = new Uint8Array(data, 0, 4); - const version = new Uint32Array(data, 4, 1); - const length = new Uint32Array(data, 8, 1); - const chunkType = new Uint8Array(data, 16, 4); + const magic = new Uint8Array(data, 0, 4); + const version = new Uint32Array(data, 4, 1); + const length = new Uint32Array(data, 8, 1); + const chunkType = new Uint8Array(data, 16, 4); - expect(magic[0]).toEqual("g".charCodeAt()); - expect(magic[1]).toEqual("l".charCodeAt()); - expect(magic[2]).toEqual("T".charCodeAt()); - expect(magic[3]).toEqual("F".charCodeAt()); + expect(magic[0]).toEqual("g".charCodeAt()); + expect(magic[1]).toEqual("l".charCodeAt()); + expect(magic[2]).toEqual("T".charCodeAt()); + expect(magic[3]).toEqual("F".charCodeAt()); - expect(version[0]).toEqual(2); + expect(version[0]).toEqual(2); - expect(length[0]).toEqual(data.byteLength); + expect(length[0]).toEqual(data.byteLength); - expect(chunkType[0]).toEqual("J".charCodeAt()); - expect(chunkType[1]).toEqual("S".charCodeAt()); - expect(chunkType[2]).toEqual("O".charCodeAt()); - expect(chunkType[3]).toEqual("N".charCodeAt()); - }); + expect(chunkType[0]).toEqual("J".charCodeAt()); + expect(chunkType[1]).toEqual("S".charCodeAt()); + expect(chunkType[2]).toEqual("O".charCodeAt()); + expect(chunkType[3]).toEqual("N".charCodeAt()); }); it("picks closest point in geometry", async function () { diff --git a/server.js b/server.js index 453d4cb732dc..90392de66509 100644 --- a/server.js +++ b/server.js @@ -61,7 +61,6 @@ const specFiles = [ "!packages/widgets/Specs/SpecList.js", "Specs/*.js", "!Specs/SpecList.js", - "Specs/TestWorkers/*.js", ]; const shaderFiles = ["packages/engine/Source/Shaders/**/*.glsl"]; @@ -117,7 +116,7 @@ const serveResult = (result, fileName, res, next) => { } if (!bundle) { - next(new Error("Failed to generate bundle")); + next(new Error(`Failed to generate bundle: ${fileName}`)); return; } @@ -126,9 +125,53 @@ const serveResult = (result, fileName, res, next) => { res.send(bundle); }; +class ResultCache { + constructor() { + this.promise = Promise.resolve(); + this.result = undefined; + } + + clear() { + this.result = undefined; + } + + isBuilt() { + return ( + this.result && + this.result.outputFiles && + this.result.outputFiles.length > 0 + ); + } +} + +function createRoute(app, name, route, context) { + const cache = new ResultCache(); + app.get(route, async function (req, res, next) { + // Multiple files may be requested at this path, calling this function in quick succession. + // Await the previous build before re-building again. + await cache.promise; + + if (!cache.isBuilt()) { + try { + const start = performance.now(); + cache.promise = context.rebuild(); + cache.result = await cache.promise; + console.log( + `Built ${name} in ${formatTimeSinceInSeconds(start)} seconds.` + ); + } catch (e) { + next(e); + } + } + + return serveResult(cache.result, path.basename(req.originalUrl), res, next); + }); + + return cache; +} + (async function () { const gzipHeader = Buffer.from("1F8B08", "hex"); - let esmResult, iifeResult, workersResult, specResult; const production = argv.production; let contexts; @@ -204,151 +247,70 @@ const serveResult = (result, fileName, res, next) => { app.get(knownTilesetFormats, checkGzipAndNext); if (!production) { - app.get("/Build/CesiumUnminified/Cesium.js", async function ( - //eslint-disable-next-line no-unused-vars - req, - res, - next - ) { - if (!iifeResult?.outputFiles || iifeResult.outputFiles.length === 0) { - try { - const start = performance.now(); - await createCesiumJs(); - iifeResult = await contexts.iife.rebuild(); - console.log( - `Built Cesium.js in ${formatTimeSinceInSeconds(start)} seconds.` - ); - } catch (e) { - next(e); - } - } - - return serveResult(iifeResult, "Cesium.js", res, next); - }); - - app.get("/Build/CesiumUnminified/Cesium.js.map", async function ( - //eslint-disable-next-line no-unused-vars - req, - res, - next - ) { - if (!iifeResult?.outputFiles || iifeResult.outputFiles.length === 0) { - try { - const start = performance.now(); - await createCesiumJs(); - iifeResult = await contexts.iife.rebuild(); - console.log( - `Built Cesium.js in ${formatTimeSinceInSeconds(start)} seconds.` - ); - } catch (e) { - next(e); - } - } - - return serveResult(iifeResult, "Cesium.js.map", res, next); - }); - - app.get("/Build/CesiumUnminified/index.js", async function ( - //eslint-disable-next-line no-unused-vars - req, - res, - next - ) { - if (!esmResult?.outputFiles || esmResult.outputFiles.length === 0) { - try { - const start = performance.now(); - await createCesiumJs(); - esmResult = await contexts.esm.rebuild(); - console.log( - `Built index.js in ${formatTimeSinceInSeconds(start)} seconds.` - ); - } catch (e) { - next(e); - } - } - - return serveResult(esmResult, "index.js", res, next); - }); - app.get("/Build/CesiumUnminified/index.js.map", async function ( - //eslint-disable-next-line no-unused-vars - req, - res, - next - ) { - if (!esmResult?.outputFiles || esmResult.outputFiles.length === 0) { - try { - const start = performance.now(); - await createCesiumJs(); - esmResult = await contexts.esm.rebuild(); - console.log( - `Built index.js in ${formatTimeSinceInSeconds(start)} seconds.` - ); - } catch (e) { - next(e); - } - } - - return serveResult(esmResult, "index.js.map", res, next); - }); + const iifeCache = createRoute( + app, + "Cesium.js", + "/Build/CesiumUnminified/Cesium.js*", + contexts.iife + ); + const esmCache = createRoute( + app, + "index.js", + "/Build/CesiumUnminified/index.js*", + contexts.esm + ); + const workersCache = createRoute( + app, + "Workers/*", + "/Build/CesiumUnminified/Workers/*.js", + contexts.workers + ); const glslWatcher = chokidar.watch(shaderFiles, { ignoreInitial: true }); glslWatcher.on("all", async () => { await glslToJavaScript(false, "Build/minifyShaders.state", "engine"); - if (esmResult) { - esmResult.outputFiles = []; - } - if (iifeResult) { - iifeResult.outputFiles = []; - } + esmCache.clear(); + iifeCache.clear(); }); let jsHintOptionsCache; const sourceCodeWatcher = chokidar.watch(sourceFiles, { ignoreInitial: true, }); - sourceCodeWatcher.on("all", () => { - if (esmResult) { - esmResult.outputFiles = []; - } - if (iifeResult) { - iifeResult.outputFiles = []; - } - if (workersResult) { - workersResult.outputFiles = []; - } + sourceCodeWatcher.on("all", async () => { + esmCache.clear(); + iifeCache.clear(); + workersCache.clear(); jsHintOptionsCache = undefined; + await createCesiumJs(); }); - app.get("/Build/CesiumUnminified/Workers/*.js", async function ( - //eslint-disable-next-line no-unused-vars - req, - //eslint-disable-next-line no-unused-vars - res, - next - ) { - if ( - !workersResult?.outputFiles || - workersResult.outputFiles.length === 0 - ) { - try { - const start = performance.now(); - workersResult = await contexts.workers.rebuild(); - console.log( - `Built Workers/* in ${formatTimeSinceInSeconds(start)} seconds.` - ); - } catch (e) { - next(e); - } + const testWorkersCache = createRoute( + app, + "TestWorkers/*", + "/Build/Specs/TestWorkers/*", + contexts.testWorkers + ); + chokidar + .watch(["Specs/TestWorkers/*.js"], { ignoreInitial: true }) + .on("all", testWorkersCache.clear); + + const specsCache = createRoute( + app, + "Specs/*", + "/Build/Specs/*", + contexts.specs + ); + const specWatcher = chokidar.watch(specFiles, { ignoreInitial: true }); + specWatcher.on("all", async (event) => { + if (event === "add" || event === "unlink") { + await createCombinedSpecList(); } - return serveResult( - workersResult, - path.basename(req.originalUrl), - res, - next - ); + specsCache.clear(); }); + // Rebuild jsHintOptions as needed and serve as-is app.get("/Apps/Sandcastle/jsHintOptions.js", async function ( //eslint-disable-next-line no-unused-vars req, @@ -365,38 +327,6 @@ const serveResult = (result, fileName, res, next) => { res.send(jsHintOptionsCache); }); - let specRebuildPromise = Promise.resolve(); - //eslint-disable-next-line no-unused-vars - app.get("/Build/Specs/*", async function (req, res, next) { - // Multiple files may be requested at this path, calling this function in quick succession. - // Await the previous build before re-building again. - await specRebuildPromise; - - if (!specResult?.outputFiles || specResult.outputFiles.length === 0) { - try { - const start = performance.now(); - specRebuildPromise = contexts.specs.rebuild(); - specResult = await specRebuildPromise; - console.log( - `Built Specs/* in ${formatTimeSinceInSeconds(start)} seconds.` - ); - } catch (e) { - next(e); - } - } - - return serveResult(specResult, path.basename(req.originalUrl), res, next); - }); - - const specWatcher = chokidar.watch(specFiles, { ignoreInitial: true }); - specWatcher.on("all", async (event) => { - if (event === "add" || event === "unlink") { - await createCombinedSpecList(); - } - - specResult.outputFiles = []; - }); - // Serve any static files starting with "Build/CesiumUnminified" from the // development build instead. That way, previous build output is preserved // while the latest is being served @@ -546,6 +476,7 @@ const serveResult = (result, fileName, res, next) => { contexts.iife.dispose(); contexts.workers.dispose(); contexts.specs.dispose(); + contexts.testWorkers.dispose(); } isFirstSig = false; From 23c10a444c5d1ec6005b8b7a5c6977d39e8efe31 Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Fri, 7 Jul 2023 16:27:50 -0400 Subject: [PATCH 03/10] Update CHANGES.md --- CHANGES.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 42cbe9064e71..1787ba492f6d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,9 +4,14 @@ #### @cesium/engine +##### Breaking Changes :mega: + +- Firefox 114 is now the minimum Firefox version required to run CesiumJS. [#11400](https://github.com/CesiumGS/cesium/pull/11400) +- `TaskProcessor` now loads worker files as ESM instead of AMD. [#11400](https://github.com/CesiumGS/cesium/pull/11400) + ##### Fixes :wrench: -- Fixed dimensions of `tangentEC` in custom shaders [#11394](https://github.com/CesiumGS/cesium/pull/11394). +- Fixed dimensions of `tangentEC` in custom shaders. [#11394](https://github.com/CesiumGS/cesium/pull/11394) - Fixed a bug where `Model` would not respond to different alpha values in a `Cesium3DTileStyle`. [#11399](https://github.com/CesiumGS/cesium/pull/11399) #### @cesium/widgets From d456cddcef0a5e2c2554bd4e44c80c4762cc872d Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Fri, 7 Jul 2023 16:37:56 -0400 Subject: [PATCH 04/10] Fix node smokescreens --- packages/engine/Source/Core/TaskProcessor.js | 24 ++++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/packages/engine/Source/Core/TaskProcessor.js b/packages/engine/Source/Core/TaskProcessor.js index b1ab677ed090..c2aeef4ed77e 100644 --- a/packages/engine/Source/Core/TaskProcessor.js +++ b/packages/engine/Source/Core/TaskProcessor.js @@ -95,7 +95,19 @@ function createWorker(processor) { "This browser is not supported. Please update your browser to continue." ); } - return new Worker(processor._workerPath, { type: "module" }); + + const uri = new Uri(processor._workerPath); + const isUri = uri.scheme().length !== 0 && uri.fragment().length === 0; + const workerPath = isUri + ? processor._workerPath + : getWorkerUrl( + `${ + TaskProcessor._workerModulePrefix + + processor._workerPath.replace(/\.js$/, "") + }.js` + ); + + return new Worker(workerPath, { type: "module" }); } async function getWebAssemblyLoaderConfig(processor, wasmOptions) { @@ -142,15 +154,7 @@ async function getWebAssemblyLoaderConfig(processor, wasmOptions) { * work to be rescheduled in future frames. */ function TaskProcessor(workerPath, maximumActiveTasks) { - const uri = new Uri(workerPath); - const isUri = uri.scheme().length !== 0 && uri.fragment().length === 0; - this._workerPath = isUri - ? workerPath - : getWorkerUrl( - `${ - TaskProcessor._workerModulePrefix + workerPath.replace(/\.js$/, "") - }.js` - ); + this._workerPath = workerPath; this._maximumActiveTasks = defaultValue( maximumActiveTasks, Number.POSITIVE_INFINITY From 146d585ee94bd383cf48c685120ca16ce638c0f1 Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Mon, 10 Jul 2023 09:59:59 -0400 Subject: [PATCH 05/10] Fix release tests --- gulpfile.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulpfile.js b/gulpfile.js index 52dcbe26982d..cfd5db25de58 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1595,7 +1595,7 @@ export async function test() { { pattern: "Build/Cesium/**", included: false }, { pattern: "Build/Specs/karma-main.js", included: true }, { pattern: "Build/Specs/SpecList.js", included: true, type: "module" }, - { pattern: "Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**", included: false }, ]; } From ff7fdf2199502d5ee7608ec16a76d27da1036c85 Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Mon, 10 Jul 2023 10:02:48 -0400 Subject: [PATCH 06/10] Reject on worker error --- packages/engine/Source/Core/TaskProcessor.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/engine/Source/Core/TaskProcessor.js b/packages/engine/Source/Core/TaskProcessor.js index c2aeef4ed77e..d8a996973416 100644 --- a/packages/engine/Source/Core/TaskProcessor.js +++ b/packages/engine/Source/Core/TaskProcessor.js @@ -210,6 +210,16 @@ async function runTask(processor, parameters, transferableObjects) { "message", createOnmessageHandler(processor._worker, id, resolve, reject) ); + + processor._worker.addEventListener( + "error", + createOnmessageHandler((error) => reject(error)) + ); + + processor._worker.addEventListener( + "messageerror", + createOnmessageHandler((error) => reject(error)) + ); }); processor._worker.postMessage( From 60d34b915da8132e9d508e11fe57e02148322f31 Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Mon, 10 Jul 2023 10:16:18 -0400 Subject: [PATCH 07/10] Fix coverage --- gulpfile.js | 4 ++-- packages/engine/Source/Core/TaskProcessor.js | 12 +----------- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/gulpfile.js b/gulpfile.js index cfd5db25de58..64bd3fa10cae 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1357,7 +1357,7 @@ export async function runCoverage(options) { // Static assets are always served from the shared/combined folders. { pattern: "Build/CesiumUnminified/**", included: false }, { pattern: "Specs/Data/**", included: false }, - { pattern: "Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**", included: false }, { pattern: "Specs/TestWorkers/**/*.wasm", included: false }, ]; @@ -1381,7 +1381,7 @@ export async function runCoverage(options) { { pattern: "packages/engine/Source/ThirdParty/**", included: false }, { pattern: "packages/engine/Source/Widget/*.css", included: false }, { pattern: "Specs/TestWorkers/**/*.wasm", included: false }, - { pattern: "Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**", included: false }, ]; proxies = { diff --git a/packages/engine/Source/Core/TaskProcessor.js b/packages/engine/Source/Core/TaskProcessor.js index d8a996973416..4eab98011f27 100644 --- a/packages/engine/Source/Core/TaskProcessor.js +++ b/packages/engine/Source/Core/TaskProcessor.js @@ -210,16 +210,6 @@ async function runTask(processor, parameters, transferableObjects) { "message", createOnmessageHandler(processor._worker, id, resolve, reject) ); - - processor._worker.addEventListener( - "error", - createOnmessageHandler((error) => reject(error)) - ); - - processor._worker.addEventListener( - "messageerror", - createOnmessageHandler((error) => reject(error)) - ); }); processor._worker.postMessage( @@ -324,7 +314,7 @@ TaskProcessor.prototype.initWebAssemblyModule = async function ( const promise = new Promise((resolve, reject) => { worker.onmessage = function ({ data }) { - if (data) { + if (defined(data)) { resolve(data.result); } else { reject(new RuntimeError("Could not configure wasm module")); From 64224a56e5849a9a08fcbb7ed29cbf633e34e242 Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Mon, 24 Jul 2023 09:47:58 -0400 Subject: [PATCH 08/10] Include workspaces in release smokescreen tests --- travis/release.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/travis/release.sh b/travis/release.sh index 494fa7d75473..cf1578ec434e 100755 --- a/travis/release.sh +++ b/travis/release.sh @@ -5,6 +5,7 @@ if [ $TRAVIS_BRANCH == "cesium.com" ]; then else npm --silent run make-zip npm pack &> /dev/null + npm pack --workspaces &> /dev/null fi npm --silent run build-apps From ed8e73c2410168f27eb0a7429b4ad699f511bc6c Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Mon, 24 Jul 2023 10:18:08 -0400 Subject: [PATCH 09/10] Add js extention for clarity --- gulpfile.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/gulpfile.js b/gulpfile.js index 936da7fd236a..d818f7dbbe57 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1357,10 +1357,10 @@ export async function runCoverage(options) { type: "module", }, // Static assets are always served from the shared/combined folders. - { pattern: "Build/CesiumUnminified/**", included: false }, { pattern: "Specs/Data/**", included: false }, - { pattern: "Build/Specs/TestWorkers/**", included: false }, { pattern: "Specs/TestWorkers/**/*.wasm", included: false }, + { pattern: "Build/CesiumUnminified/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**.js", included: false }, ]; let proxies; @@ -1378,12 +1378,12 @@ export async function runCoverage(options) { type: "module", }, { pattern: "Specs/Data/**", included: false }, + { pattern: "Specs/TestWorkers/**/*.wasm", included: false }, { pattern: "packages/engine/Build/Workers/**", included: false }, { pattern: "packages/engine/Source/Assets/**", included: false }, { pattern: "packages/engine/Source/ThirdParty/**", included: false }, { pattern: "packages/engine/Source/Widget/*.css", included: false }, - { pattern: "Specs/TestWorkers/**/*.wasm", included: false }, - { pattern: "Build/Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**.js", included: false }, ]; proxies = { @@ -1548,7 +1548,7 @@ export async function test() { { pattern: "Build/CesiumUnminified/**", included: false }, { pattern: "Build/Specs/karma-main.js", included: true, type: "module" }, { pattern: "Build/Specs/SpecList.js", included: true, type: "module" }, - { pattern: "Build/Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**.js", included: false }, ]; let proxies; @@ -1567,12 +1567,12 @@ export async function test() { type: "module", }, { pattern: "Specs/Data/**", included: false }, + { pattern: "Specs/TestWorkers/**/*.wasm", included: false }, { pattern: "packages/engine/Build/Workers/**", included: false }, { pattern: "packages/engine/Source/Assets/**", included: false }, { pattern: "packages/engine/Source/ThirdParty/**", included: false }, { pattern: "packages/engine/Source/Widget/*.css", included: false }, - { pattern: "Specs/TestWorkers/**/*.wasm", included: false }, - { pattern: "Build/Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**.js", included: false }, ]; proxies = { @@ -1597,7 +1597,7 @@ export async function test() { { pattern: "Build/Cesium/**", included: false }, { pattern: "Build/Specs/karma-main.js", included: true }, { pattern: "Build/Specs/SpecList.js", included: true, type: "module" }, - { pattern: "Build/Specs/TestWorkers/**", included: false }, + { pattern: "Build/Specs/TestWorkers/**.js", included: false }, ]; } From b761c61e05f4a395196b7fc4887028e2f33bff3d Mon Sep 17 00:00:00 2001 From: Gabby Getz Date: Wed, 30 Aug 2023 11:00:07 -0400 Subject: [PATCH 10/10] Update CHANGES.md --- CHANGES.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index ff2c5bd0d920..ae9cc536710d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,6 +4,11 @@ #### @cesium/engine +##### Breaking Changes :mega: + +- Firefox 114 is now the minimum Firefox version required to run CesiumJS. [#11400](https://github.com/CesiumGS/cesium/pull/11400) +- `TaskProcessor` now loads worker files as ESM instead of AMD. [#11400](https://github.com/CesiumGS/cesium/pull/11400) + ##### Additions :tada: - The TypeScript definition of `defined` now uses type predicates to allow TypeScript to use the result during compliation. @@ -27,11 +32,6 @@ #### @cesium/engine -##### Breaking Changes :mega: - -- Firefox 114 is now the minimum Firefox version required to run CesiumJS. [#11400](https://github.com/CesiumGS/cesium/pull/11400) -- `TaskProcessor` now loads worker files as ESM instead of AMD. [#11400](https://github.com/CesiumGS/cesium/pull/11400) - ##### Fixes :wrench: - Fixed issue where terrain with multiple layers was loading higher LOD tiles inconsistently. [#11312](https://github.com/CesiumGS/cesium/issues/11312)