Repository: AskingQuestions/Shadeup Branch: main Commit: 8b25bf92c1aa Files: 402 Total size: 16.3 MB Directory structure: gitextract_91pjwq56/ ├── .gitattributes ├── .gitignore ├── .vscode/ │ └── launch.json ├── README.md ├── cli/ │ ├── README.md │ ├── cli.js │ ├── compiler-dist/ │ │ ├── compiler.d.ts │ │ ├── compiler.js │ │ ├── readme.md │ │ ├── shadeup-compiler.js │ │ └── tree-sitter-shadeup.wasm │ ├── electron/ │ │ ├── index.html │ │ └── main.js │ ├── index.js │ ├── package.json │ ├── test/ │ │ ├── main.d.ts │ │ ├── main.js │ │ ├── other.js │ │ ├── other.shadeup │ │ └── vite-project/ │ │ ├── .gitignore │ │ ├── index.html │ │ ├── package.json │ │ ├── src/ │ │ │ ├── index.ts │ │ │ ├── logoPath.shadeup │ │ │ ├── main.d.ts │ │ │ ├── main.js │ │ │ ├── main.shadeup │ │ │ ├── style.css │ │ │ └── vite-env.d.ts │ │ └── tsconfig.json │ └── vite/ │ ├── .gitignore │ ├── index.html │ ├── main.js │ ├── package.json │ ├── runner.d.ts │ ├── runner.js │ ├── style.css │ └── vite.config.js ├── extension/ │ └── vscode/ │ └── shadeup/ │ ├── .vscodeignore │ ├── CHANGELOG.md │ ├── README.md │ ├── Shadeup-tmLanguage.json │ ├── client/ │ │ ├── package.json │ │ ├── src/ │ │ │ └── extension.ts │ │ ├── testFixture/ │ │ │ ├── completion.txt │ │ │ └── diagnostics.txt │ │ └── tsconfig.json │ ├── lang.ts │ ├── language-configuration.json │ ├── package.json │ ├── server/ │ │ ├── compiler-dist/ │ │ │ ├── compiler.d.ts │ │ │ ├── compiler.js │ │ │ ├── readme.md │ │ │ ├── shadeup-compiler.umd.cjs │ │ │ └── tree-sitter-shadeup.wasm │ │ ├── package.json │ │ ├── src/ │ │ │ └── server.ts │ │ └── tsconfig.json │ ├── shadeup.tmlanguage.json │ ├── syntaxes/ │ │ └── shadeup.tmLanguage.json │ └── tsconfig.json ├── lang/ │ ├── README.md │ ├── shadeup/ │ │ ├── alert.ts │ │ ├── compiler/ │ │ │ ├── assets.json │ │ │ ├── assets.ts │ │ │ ├── common.ts │ │ │ ├── generateDocs.ts │ │ │ ├── generateTsCache.ts │ │ │ ├── interface.ts │ │ │ ├── simple.ts │ │ │ └── worker.ts │ │ ├── engine/ │ │ │ ├── adapters/ │ │ │ │ ├── adapter.ts │ │ │ │ ├── webgl.ts │ │ │ │ └── webgpu.ts │ │ │ ├── amd.ts │ │ │ ├── engine-headless.ts │ │ │ ├── engine.ts │ │ │ ├── frame-embed.html │ │ │ ├── frame-headless.html │ │ │ ├── frame-preview.html │ │ │ ├── frame.html │ │ │ ├── gltf.js │ │ │ ├── input/ │ │ │ │ ├── input.ts │ │ │ │ └── keyboardKeys.ts │ │ │ ├── requirejs.js │ │ │ ├── setZero.ts │ │ │ ├── shader.ts │ │ │ ├── ui/ │ │ │ │ ├── components/ │ │ │ │ │ ├── Button.svelte │ │ │ │ │ ├── Checkbox.svelte │ │ │ │ │ ├── Combo.svelte │ │ │ │ │ ├── FloatingPanel.svelte │ │ │ │ │ ├── Group.svelte │ │ │ │ │ ├── Host.svelte │ │ │ │ │ ├── Label.svelte │ │ │ │ │ ├── Slider.svelte │ │ │ │ │ ├── Text.svelte │ │ │ │ │ └── host.scss │ │ │ │ ├── puck.ts │ │ │ │ └── ui.ts │ │ │ ├── util.ts │ │ │ └── virtual-webgl2.js │ │ ├── environment.ts │ │ ├── environmentWorker.ts │ │ ├── frame.html │ │ ├── library/ │ │ │ ├── buffer.ts │ │ │ ├── color.ts │ │ │ ├── common.shadeup │ │ │ ├── drawAttributes.ts │ │ │ ├── drawCount.ts │ │ │ ├── drawIndexed.ts │ │ │ ├── examples/ │ │ │ │ ├── deferred.shadeup │ │ │ │ ├── shadow-map.shadeup │ │ │ │ └── transparency.shadeup │ │ │ ├── files.ts │ │ │ ├── geo.shadeup │ │ │ ├── mesh.shadeup │ │ │ ├── mesh.ts │ │ │ ├── native.ts │ │ │ ├── paint.ts │ │ │ ├── physics.ts │ │ │ ├── sdf.shadeup │ │ │ ├── std.ts │ │ │ ├── test.shadeup │ │ │ ├── texture.ts │ │ │ ├── textures.shadeup │ │ │ ├── types.ts │ │ │ └── ui.ts │ │ ├── monaco/ │ │ │ └── connector.ts │ │ ├── runner.ts │ │ ├── symbol.ts │ │ ├── vite.config.js │ │ └── worker.ts │ ├── shadeup-frontend/ │ │ ├── .gitignore │ │ ├── f.js │ │ ├── f.ts │ │ ├── index.html │ │ ├── lib/ │ │ │ ├── ariadne-ts/ │ │ │ │ └── src/ │ │ │ │ ├── _extensions.ts │ │ │ │ ├── browser.ts │ │ │ │ ├── data/ │ │ │ │ │ ├── Display.ts │ │ │ │ │ ├── Formatter.ts │ │ │ │ │ ├── Iter.ts │ │ │ │ │ ├── Option.ts │ │ │ │ │ ├── Range.ts │ │ │ │ │ ├── Result.ts │ │ │ │ │ ├── Show.ts │ │ │ │ │ ├── Span.ts │ │ │ │ │ └── Write.ts │ │ │ │ ├── index.ts │ │ │ │ ├── lib/ │ │ │ │ │ ├── Characters.ts │ │ │ │ │ ├── Color.ts │ │ │ │ │ ├── ColorGenerator.ts │ │ │ │ │ ├── Config.ts │ │ │ │ │ ├── Label.ts │ │ │ │ │ ├── LabelInfo.ts │ │ │ │ │ ├── Report.ts │ │ │ │ │ ├── ReportBuilder.ts │ │ │ │ │ ├── ReportKind.ts │ │ │ │ │ ├── Source.ts │ │ │ │ │ ├── SourceGroup.ts │ │ │ │ │ └── chalk/ │ │ │ │ │ └── chalk/ │ │ │ │ │ ├── license │ │ │ │ │ ├── readme.md │ │ │ │ │ └── source/ │ │ │ │ │ ├── index.d.ts │ │ │ │ │ ├── index.js │ │ │ │ │ ├── utilities.js │ │ │ │ │ └── vendor/ │ │ │ │ │ ├── ansi-styles/ │ │ │ │ │ │ ├── index.d.ts │ │ │ │ │ │ └── index.js │ │ │ │ │ └── supports-color/ │ │ │ │ │ ├── browser.d.ts │ │ │ │ │ ├── browser.js │ │ │ │ │ ├── index.d.ts │ │ │ │ │ └── index.js │ │ │ │ ├── stringFormat.ts │ │ │ │ ├── utils/ │ │ │ │ │ ├── binary_search_by_key.ts │ │ │ │ │ ├── include_str.ts │ │ │ │ │ └── index.ts │ │ │ │ └── write.ts │ │ │ ├── environment/ │ │ │ │ ├── Errors.ts │ │ │ │ ├── ShadeupEnvironment.ts │ │ │ │ ├── TypescriptEnvironment.ts │ │ │ │ ├── quickCache.json │ │ │ │ ├── tagGraph.ts │ │ │ │ └── validate.ts │ │ │ ├── fast-diff/ │ │ │ │ └── diff.js │ │ │ ├── generator/ │ │ │ │ ├── eval.js │ │ │ │ ├── glsl.ts │ │ │ │ ├── header.glsl │ │ │ │ ├── header.wgsl │ │ │ │ ├── root.ts │ │ │ │ ├── toposort.ts │ │ │ │ ├── transform.ts │ │ │ │ ├── tsWalk.ts │ │ │ │ ├── util.ts │ │ │ │ └── wgsl.ts │ │ │ ├── main.ts │ │ │ ├── parser/ │ │ │ │ ├── AstContext.ts │ │ │ │ ├── index.ts │ │ │ │ ├── node.cjs │ │ │ │ ├── tree-sitter-javascript.wasm │ │ │ │ ├── tree-sitter-shadeup.wasm │ │ │ │ ├── tree-sitter.wasm │ │ │ │ ├── wasm.ts │ │ │ │ └── web-tree-sitter/ │ │ │ │ └── tree-sitter.js │ │ │ └── std/ │ │ │ ├── all.ts │ │ │ ├── generate-static-math.ts │ │ │ ├── global.d.ts │ │ │ ├── math.ts │ │ │ ├── static-math-db.ts │ │ │ └── static-math.ts │ │ ├── package.json │ │ ├── src/ │ │ │ ├── index.ts │ │ │ ├── main.ts │ │ │ └── vite-env.d.ts │ │ ├── test.js │ │ ├── test.ts │ │ ├── tsconfig.json │ │ ├── vfs.js │ │ └── vite.config.ts │ └── tree-sitter/ │ ├── .gitignore │ ├── .prettierrc │ ├── Cargo.toml │ ├── binding.gyp │ ├── bindings/ │ │ ├── node/ │ │ │ ├── binding.cc │ │ │ └── index.js │ │ └── rust/ │ │ ├── build.rs │ │ └── lib.rs │ ├── build/ │ │ ├── Release/ │ │ │ ├── obj/ │ │ │ │ └── tree_sitter_shadeup_binding/ │ │ │ │ ├── bindings/ │ │ │ │ │ └── node/ │ │ │ │ │ └── binding.obj │ │ │ │ ├── src/ │ │ │ │ │ ├── parser.obj │ │ │ │ │ └── scanner.obj │ │ │ │ ├── tree_sit.A95203FA.tlog/ │ │ │ │ │ ├── CL.command.1.tlog │ │ │ │ │ ├── CL.read.1.tlog │ │ │ │ │ ├── CL.write.1.tlog │ │ │ │ │ ├── link.command.1.tlog │ │ │ │ │ ├── link.read.1.tlog │ │ │ │ │ ├── link.write.1.tlog │ │ │ │ │ ├── tree_sitter_shadeup_binding.lastbuildstate │ │ │ │ │ └── tree_sitter_shadeup_binding.write.1u.tlog │ │ │ │ ├── tree_sitter_shadeup_binding.node.recipe │ │ │ │ └── win_delay_load_hook.obj │ │ │ ├── tree_sitter_shadeup_binding.exp │ │ │ ├── tree_sitter_shadeup_binding.iobj │ │ │ ├── tree_sitter_shadeup_binding.ipdb │ │ │ ├── tree_sitter_shadeup_binding.lib │ │ │ ├── tree_sitter_shadeup_binding.node │ │ │ └── tree_sitter_shadeup_binding.pdb │ │ ├── binding.sln │ │ ├── config.gypi │ │ ├── tree_sitter_shadeup_binding.vcxproj │ │ └── tree_sitter_shadeup_binding.vcxproj.filters │ ├── grammar.js │ ├── grammer-fixed.js │ ├── javascript.js │ ├── package.json │ ├── parser.exp │ ├── parser.lib │ ├── parser.obj │ ├── readme.md │ ├── scanner.obj │ ├── shadeup-javascript.js │ ├── src/ │ │ ├── grammar.json │ │ ├── node-types.json │ │ ├── parser.c │ │ ├── scanner.c │ │ └── tree_sitter/ │ │ └── parser.h │ ├── test.shadeup │ ├── tree-sitter-javascript.wasm │ └── typescript.js ├── package/ │ ├── __lib.d.ts │ ├── __lib.js │ ├── __lib.shadeup │ ├── engine-dist/ │ │ ├── DRACOLoader-4fcd2f44.js │ │ ├── GLTFLoader-94b38cf6.js │ │ ├── host-937690bb.js │ │ ├── host-f3c963cd.js │ │ ├── host-fa5c0296.js │ │ ├── shadeup-engine.js │ │ ├── style.css │ │ ├── three.module-c8091b37.js │ │ ├── ui-37189365.js │ │ └── ui-f4b4a003.js │ ├── engine.js │ ├── index.js │ ├── library.js │ ├── main.d.ts │ ├── math.d.ts │ ├── package.json │ └── util/ │ └── concat.js ├── package.json └── unreal-engine/ ├── .editorconfig ├── .gitattributes ├── .gitignore ├── .prettierignore ├── README.md ├── archive.js ├── archives/ │ └── CustomProxy_Plugin/ │ ├── ShadeupExamplePlugin.uplugin │ ├── ShadeupExamplePlugin.uplugin.back │ └── Source/ │ ├── CustomProxy/ │ │ ├── CustomProxy.Build.cs │ │ ├── Private/ │ │ │ └── CustomProxy.cpp │ │ └── Public/ │ │ └── CustomProxy.h │ └── ShadeupTestPlugin/ │ ├── Private/ │ │ └── ShadeupExamplePlugin.cpp │ ├── Public/ │ │ └── ShadeupExamplePlugin.h │ └── ShadeupExamplePlugin.Build.cs ├── build/ │ └── grammar.js ├── cli.js ├── examples/ │ ├── pixel.shadeup │ └── version2.shadeup ├── extension/ │ └── shadeup/ │ ├── .vscode/ │ │ └── launch.json │ ├── .vscodeignore │ ├── CHANGELOG.md │ ├── README.md │ ├── language-configuration.json │ ├── package.json │ ├── syntaxes/ │ │ └── shadeup.tmLanguage.json │ └── vsc-extension-quickstart.md ├── index.js ├── p.shadeup ├── package.json ├── src/ │ ├── file.js │ ├── grammar.ne │ ├── parse.js │ ├── plugin_template/ │ │ ├── ShadeupExamplePlugin.uplugin │ │ └── Source/ │ │ └── ShadeupTestPlugin/ │ │ ├── Private/ │ │ │ └── ShadeupExamplePlugin.cpp │ │ ├── Public/ │ │ │ └── ShadeupExamplePlugin.h │ │ └── ShadeupExamplePlugin.Build.cs │ ├── string.ne │ ├── template/ │ │ ├── ModulePrivate.cpp │ │ ├── ModulePublic.h │ │ ├── Plugin/ │ │ │ ├── MyPlugin.uplugin │ │ │ ├── Shaders/ │ │ │ │ ├── Compute/ │ │ │ │ │ └── Private/ │ │ │ │ │ └── Template.usf │ │ │ │ └── Factory/ │ │ │ │ └── Private/ │ │ │ │ └── Template.ush │ │ │ └── Source/ │ │ │ └── Module/ │ │ │ ├── Private/ │ │ │ │ ├── ActorTemplate.cpp │ │ │ │ ├── ComputeTemplate.cpp │ │ │ │ ├── ComputeTemplate.h │ │ │ │ ├── FactoryTemplate.cpp │ │ │ │ ├── FactoryTemplate.h │ │ │ │ ├── ModuleTemplate.cpp │ │ │ │ ├── ProxyTemplate.cpp │ │ │ │ └── ProxyTemplate.h │ │ │ ├── Public/ │ │ │ │ ├── ActorTemplate.h │ │ │ │ └── ModuleTemplate.h │ │ │ └── Template.Build.cs │ │ ├── Template.Build.cs │ │ ├── compute.cpp │ │ └── lib/ │ │ ├── ShadeupLib.cpp │ │ ├── ShadeupLib.h │ │ └── readme.md │ ├── templates/ │ │ ├── compute/ │ │ │ └── simple-compute-shader/ │ │ │ └── Plugin/ │ │ │ ├── Shaders/ │ │ │ │ └── [MODULE]/ │ │ │ │ └── Private/ │ │ │ │ └── [NAME]/ │ │ │ │ ├── $base[NAME].usf │ │ │ │ ├── $basemat[NAME].usf │ │ │ │ ├── $mat[NAME].usf │ │ │ │ ├── $pi[NAME].usf │ │ │ │ └── $rt[NAME].usf │ │ │ └── Source/ │ │ │ └── [MODULE]/ │ │ │ ├── Private/ │ │ │ │ └── [NAME]/ │ │ │ │ ├── [NAME].cpp │ │ │ │ └── [NAME].h │ │ │ └── Public/ │ │ │ └── [NAME]/ │ │ │ ├── $base[NAME]_readme.md │ │ │ ├── $basemat[NAME]_readme.md │ │ │ ├── $mat[NAME]_readme.md │ │ │ ├── $pi[NAME]_readme.md │ │ │ ├── $rt[NAME]_readme.md │ │ │ └── [NAME].h │ │ ├── instancing/ │ │ │ ├── compute-indirect-drawing/ │ │ │ │ └── Plugin/ │ │ │ │ ├── Shaders/ │ │ │ │ │ └── [MODULE]/ │ │ │ │ │ └── Private/ │ │ │ │ │ └── [NAME]/ │ │ │ │ │ ├── [NAME].ush │ │ │ │ │ ├── [NAME]Compute.usf │ │ │ │ │ └── [NAME]VertexFactory.ush │ │ │ │ └── Source/ │ │ │ │ └── [MODULE]/ │ │ │ │ ├── Private/ │ │ │ │ │ └── [NAME]/ │ │ │ │ │ ├── [NAME]Actor.cpp │ │ │ │ │ ├── [NAME]Component.cpp │ │ │ │ │ ├── [NAME]SceneProxy.cpp │ │ │ │ │ ├── [NAME]SceneProxy.h │ │ │ │ │ ├── [NAME]VertexFactory.cpp │ │ │ │ │ └── [NAME]VertexFactory.h │ │ │ │ └── Public/ │ │ │ │ └── [NAME]/ │ │ │ │ ├── $base[NAME]_readme.md │ │ │ │ ├── [NAME]Actor.h │ │ │ │ └── [NAME]Component.h │ │ │ └── compute-instanced-static-mesh-component/ │ │ │ └── Plugin/ │ │ │ ├── Shaders/ │ │ │ │ └── [MODULE]/ │ │ │ │ └── Private/ │ │ │ │ └── [NAME]/ │ │ │ │ ├── [NAME].ush │ │ │ │ ├── [NAME]Compute.usf │ │ │ │ └── [NAME]VertexFactory.ush │ │ │ └── Source/ │ │ │ └── [MODULE]/ │ │ │ ├── Private/ │ │ │ │ └── [NAME]/ │ │ │ │ ├── [NAME]Actor.cpp │ │ │ │ ├── [NAME]Component.cpp │ │ │ │ ├── [NAME]SceneProxy.cpp │ │ │ │ ├── [NAME]SceneProxy.h │ │ │ │ ├── [NAME]VertexFactory.cpp │ │ │ │ └── [NAME]VertexFactory.h │ │ │ └── Public/ │ │ │ └── [NAME]/ │ │ │ ├── $inst[NAME]_readme.md │ │ │ ├── [NAME]Actor.h │ │ │ └── [NAME]Component.h │ │ └── nodes/ │ │ ├── dynamic/ │ │ │ └── Plugin/ │ │ │ └── Source/ │ │ │ └── [MODULE]/ │ │ │ ├── Private/ │ │ │ │ └── [NAME]MaterialExpression.cpp │ │ │ └── Public/ │ │ │ ├── [NAME]MaterialExpression.h │ │ │ └── [NAME]_readme.md │ │ ├── fn/ │ │ │ └── Plugin/ │ │ │ └── Source/ │ │ │ └── [MODULE]/ │ │ │ ├── Private/ │ │ │ │ └── [NAME]MaterialExpression.cpp │ │ │ └── Public/ │ │ │ └── [NAME]MaterialExpression.h │ │ ├── input/ │ │ │ └── Plugin/ │ │ │ └── Source/ │ │ │ └── [MODULE]/ │ │ │ ├── Private/ │ │ │ │ └── [NAME]MaterialExpression.cpp │ │ │ └── Public/ │ │ │ └── [NAME]MaterialExpression.h │ │ └── output/ │ │ └── Plugin/ │ │ └── Source/ │ │ └── [MODULE]/ │ │ ├── Private/ │ │ │ └── [NAME]MaterialExpression.cpp │ │ └── Public/ │ │ └── [NAME]MaterialExpression.h │ ├── types/ │ │ ├── actor.js │ │ ├── base.js │ │ ├── compute.js │ │ ├── factory.js │ │ ├── shader.js │ │ ├── template.js │ │ └── value.js │ ├── util.js │ └── whitespace.ne ├── test.hlsl ├── test.js └── test.shadeup ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* .pnpm-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # Snowpack dependency directory (https://snowpack.dev/) web_modules/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional stylelint cache .stylelintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variable files .env .env.development.local .env.test.local .env.production.local .env.local # parcel-bundler cache (https://parceljs.org/) .cache .parcel-cache # Next.js build output .next out # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and not Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # vuepress v2.x temp and cache directory .temp .cache # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Stores VSCode versions used for testing VSCode extensions .vscode-test # yarn v2 .yarn/cache .yarn/unplugged .yarn/build-state.yml .yarn/install-state.gz .pnp.* node_modules ================================================ FILE: .vscode/launch.json ================================================ // A launch configuration that launches the extension inside a new window // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 { "version": "0.2.0", "configurations": [ { "name": "Extension", "type": "extensionHost", "request": "launch", "args": [ "--extensionDevelopmentPath=${workspaceFolder}/extension/vscode/shadeup", "${workspaceFolder}/cli/test/vite-project/src/" ] } ] } ================================================ FILE: README.md ================================================

Shadeup logo

Shadeup

## Write **WebGPU** shaders without the boilerplate Repository for the Shadeup ecosystem and tooling [Shadeup.dev](https://shadeup.dev/) This currently includes: - [Shadeup Language](./lang) - partial codebase - [Shadeup Compiler Tools](./cli) `npm i -g @shadeup/cli` - [Shadeup Engine Package](./package) `npm i shadeup` - [Shadeup - Unreal Engine](./unreal-engine) `npm i -g @shadeup/unreal` - [Shadeup VS Code extension](./extension/vscode) - [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Shadeup.shadeup-vscode) --- ================================================ FILE: cli/README.md ================================================

Shadeup logo

Shadeup CLI

# Shadeup compiler tools ## Installation ```sh npm install -g @shadeup/cli ``` ## Usage ```sh shadeup --help ``` ```sh CLI tool for compiling shadeup files Options: -V, --version output the version number -v -h, --help display help for command Commands: build [options] Build file watch Watch a shadeup file and recompile on change preview Live preview of a shadeup file in electron ``` ## Example ```ts // main.shadeup fn main() { draw(shader { out.color = (in.uv, 0.5, 1.0); }); } ``` ```sh $ shadeup build main.shadeup ``` After running the above command, you should find the following files in the same directory as `main.shadeup`: - `main.js` - `main.d.ts` You can use the above files inside of a vite or webpack project to use the shader in your web application. ```sh $ npm i shadeup ``` ```js // example.ts import { makeShadeupInstance } from "./main"; const canvas = document.querySelector("#canvas")!; (async () => { const engine = await makeShadeupInstance(canvas); // Optionally enable the UI await engine.enableUI(); // The frame loop will start automatically // You can call pub functions on the engine instance // engine.files.main.exampleFunction(); })(); ``` ## Preview mode ```sh $ shadeup preview main.shadeup ``` This will open an electron window with the shader preview. You can use this to quickly test your shader without having to set up a web project. ![Preview](https://i.imgur.com/PVjn7BA.png) ================================================ FILE: cli/cli.js ================================================ #!/usr/bin/env node import colors from "colors"; import path from "path"; import fs from "fs"; import os from "os"; import inquirer from "inquirer"; import { program } from "commander"; import * as url from "url"; import { makeCompiler, makeIncrementalCompiler, } from "./compiler-dist/compiler.js"; if (typeof __dirname == "undefined") { global["__filename"] = url.fileURLToPath(import.meta.url); global["__dirname"] = url.fileURLToPath(new URL(".", import.meta.url)); } function findCommonPath(paths) { // Find the common path without the filename or extension if (paths.length == 0) return ""; if (paths.length == 1) return path.dirname(paths[0]) + "/"; paths = paths.map((p) => p).sort((a, b) => b.length - a.length); let longest = paths[0]; for (let i = 0; i < longest.length; i++) { let char = longest[i]; for (let path of paths) { if (path[i] != char) { return longest.slice(0, i); } } } } function scanImports(baseFile) { let imports = new Set(); imports.add(baseFile); let data = fs.readFileSync(baseFile, "utf8"); let lines = data.split("\n"); for (let line of lines) { let match = line.match(/import[^"]+"([^"]*)"/); if (match) { let importPath = match[1]; if (!importPath.endsWith(".shadeup")) { importPath += ".shadeup"; } if (importPath.startsWith("/")) { continue; } let importFile = path.resolve(path.dirname(baseFile), importPath); if (!imports.has(importFile)) { imports.add(importFile); scanImports(importFile).forEach((i) => imports.add(i)); } } } return imports; } program .name("shadeup") .description("CLI tool for compiling shadeup files") .version("1.3.0") .option("-v") .action(async (opts) => { console.log("Shadeup v1.3.0".magenta); if (opts.v) { return; } try { } catch (e) { console.error(e); } }); function normalizePath(p) { return p.replace(/\\/g, "/"); } function printErrors(errors, common) { for (let error of errors) { let path = (common + error.file) .replace(".ts", ".shadeup") .replace(/^\/([A-Z]:)/g, "$1") .replace(/\/\//g, "/"); console.error( path + "\n\x1b[31m" + error.message.replace(error.file, path) + "\x1b[0m" ); } } const buildFiles = async (files, options) => { let compile = await makeCompiler(); let outputs = []; let common = normalizePath(findCommonPath(files)); outputs.push( compile({ files: files.map((f) => { f = normalizePath(f).replace(common, ""); let data = fs.readFileSync(f, "utf8"); let filename = f.replace(".shadeup", ""); return { name: filename, body: data }; }), }) ); let orig = console.log; console.log = () => {}; let outs = await Promise.all(outputs); console.log = orig; for (let i = 0; i < outs.length; i++) { let out = outs[i]; if (out.errors) { printErrors(out.errors, common); continue; } let file = files[i]; let outPath = options.output || file.replace(".shadeup", ".js"); console.log(`Writing ${outPath}`); fs.writeFileSync(outPath, out.output); if (out.dts) { let dtsPath = file.replace(".shadeup", ".d.ts"); if (options.output) { dtsPath = options.output.replace(".js", ".d.ts"); } console.log(`Writing ${dtsPath}`); fs.writeFileSync(dtsPath, out.dts); } } }; program .command("build") .description("Build file") .option("-o, --output ", "Output path", "") .argument("file", "File to build") .action(async (file, options) => { file = path.resolve(file); if (!fs.existsSync(file)) { console.error(`File ${file} does not exist`); return; } let fileSet = scanImports(file); let files = [...fileSet.values()]; if (!options.output) { delete options.output; } await buildFiles(files, { output: file.replace(".shadeup", ".js"), ...options, }); }); const debounce = (fn, time) => { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => { fn(...args); }, time); }; }; const setupWatcher = async (file, options, outdir = "") => { file = path.resolve(file); let comp = await makeIncrementalCompiler(); let rebuild = debounce(async () => { let fileSet = scanImports(file); let files = [...fileSet.values()]; let common = normalizePath(findCommonPath(files)); let start = performance.now(); let orig = console.log; // console.log = () => {}; let outs = await comp({ files: files.map((f) => { f = normalizePath(f).replace(common, ""); let data = fs.readFileSync(f, "utf8"); let filename = f.replace(".shadeup", ""); return { name: filename, body: data }; }), }); console.log = orig; (async () => { // let errs = await outs.errors; // printErrors(errs, common); })(); let outPath = options.output || file.replace(".shadeup", ".js"); if (outdir) { outPath = path.join(outdir, path.basename(outPath)); } console.log( `\x1b[32mCompiled in ${Math.round( performance.now() - start )}ms\x1b[0m: writing out to ${outPath}` ); fs.writeFileSync(outPath, outs.output); fs.writeFileSync(outPath.replace(/\.js$/, ".d.ts"), outs.dts); }, 100); rebuild(); let handlers = new Map(); const buildHandlers = () => { let fileSet = scanImports(file); let files = Array.from(fileSet); let unwatch = new Set(handlers.keys()); for (let file of files) { unwatch.delete(file); if (!fs.existsSync(file)) { console.error(`File ${file} does not exist`); continue; } if (handlers.has(file)) { continue; } let handler = () => { rebuild(); buildHandlers(); }; let watcher = fs.watch(file, handler); watcher.on("change", handler); watcher.on("error", (e) => { console.error(e); }); handlers.set(file, watcher); } for (let file of unwatch) { handlers.get(file).close(); handlers.delete(file); } }; buildHandlers(); }; program .command("watch") .description("Watch a shadeup file and recompile on change") .argument("file", "Main file to watch") .action(async (file, options) => { setupWatcher(file, options); }); program .command("preview") .description("Live preview of a shadeup file in electron") .argument("file", "Main file to preview") .action(async (file, options) => { const electron = await import("electron"); const proc = await import("node:child_process"); // shadeup home dir for vite const shadeupHome = path.join(os.homedir(), ".shadeup_vite"); // Copy entire vite directory to shadeup home dir if (!fs.existsSync(shadeupHome)) { fs.mkdirSync(shadeupHome); } const viteDir = path.join(__dirname, "vite"); fs.cpSync(viteDir, shadeupHome, { recursive: true }); // run npm install on the vite directory if node_modules doesn't exist if (!fs.existsSync(path.join(shadeupHome, "/node_modules"))) { console.log(shadeupHome); console.log("Installing dependencies..."); proc.execSync("npm install", { cwd: shadeupHome, stdio: "inherit", }); } fs.writeFileSync( path.join(__dirname, "vite/runner.js"), `export const makeShadeupInstance = async (canvas) => { return { enableUI: async () => {}, }; }; ` ); const child = proc.spawn(electron.default, [ path.join(__dirname, "electron/main.js"), ]); child.stdout.on("data", (data) => { console.log(data.toString()); }); child.stderr.on("data", (data) => { console.error(data.toString()); }); setupWatcher( file, { output: path.join(shadeupHome, "runner.js"), }, shadeupHome ); const vite = await import("vite"); const server = await vite.createServer({ root: shadeupHome, server: { port: 5128, }, }); child.on("close", (code) => { console.log(`child process exited with code ${code}`); server.close(); process.exit(); }); await server.listen(); }); program.parse(); ================================================ FILE: cli/compiler-dist/compiler.d.ts ================================================ export function makeLSPCompiler(): Promise; ================================================ FILE: cli/compiler-dist/compiler.js ================================================ import { makeSimpleShadeupEnvironment } from "./shadeup-compiler.js"; import Parser from "web-tree-sitter"; import minify from "uglify-js"; import path from "path"; import { fileURLToPath } from "url"; const __filename = fileURLToPath(new URL(import.meta.url)); function filterDTS(files) { return `import * as __ from "shadeup/math"; declare namespace ShadeupFiles { ${[...files.entries()] .map( ([name, dts]) => ` declare namespace ${name} {\n${dts .split("\n") .map((s) => ` ${s}`) .join("\n") .trimEnd()}\n }` ) .join("\n")} } export declare function makeShadeupInstance( canvas: HTMLCanvasElement, options?: { preferredAdapter?: "webgl" | "webgpu"; limits?: GPUSupportedLimits; ui?: boolean; } ): Promise<{ /** * Set to false to pause */ playing: boolean; canvas: HTMLCanvasElement; adapter: any; hooks: { beforeFrame?: () => void; afterFrame?: () => void; reset?: () => void; }[]; start: () => void; env: { camera: { position: __.float3; rotation: __.float4; width: __.float; height: __.float; fov: __.float; near: __.float; far: __.float; }; camera2d: { position: __.float2; zoom: __.float; }; deltaTime: __.float; frame: __.int; keyboard: any; mouse: any; screenSize: __.float2; time: __.float; }; /** * Used to pass values into the shadeup env (accessed as env.input("name") inside) */ inputValues: Map; enableUI: () => Promise; loadTextureFromImageLike: ( img: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas | HTMLVideoElement ) => Promise<__.texture2d<__.float4>>; loadTexture2dFromURL: (url: string) => Promise<__.texture2d<__.float4>>; loadModelFromURL: (urlGltf: string) => Promise<__.texture2d<__.float4>>; files: typeof ShadeupFiles; }>; `; } const prefixConst = (files) => { let str = `import { bindShadeupEngine } from "shadeup"; export const makeShadeupInstance = bindShadeupEngine((define, localEngineContext) => { const __shadeup_gen_shader = localEngineContext.__shadeup_gen_shader.bind(localEngineContext); const __shadeup_make_shader_inst = localEngineContext.__shadeup_make_shader_inst.bind(localEngineContext); const __shadeup_register_struct = localEngineContext.__shadeup_register_struct.bind(localEngineContext); const env = localEngineContext.env;\n`; str += `((defineFunc) => { let define = (deps, func) => defineFunc("/__meta.js", deps, func); define(["require", "exports"], function (require, exports, __, std___std_all_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.files = [${files.map((f) => JSON.stringify(f)).join(",")}]; }); })(define);`; return str; }; export async function makeCompiler() { await Parser.init(); const parser = new Parser(); const Lang = await Parser.Language.load( path.resolve(path.dirname(__filename), "tree-sitter-shadeup.wasm") ); parser.setLanguage(Lang); global.shadeupParser = () => { return parser; }; let envPool = []; for (let i = 0; i < 1; i++) { envPool.push(await makeSimpleShadeupEnvironment(true, true)); } let queue = []; async function consumeQueue() { if (queue.length == 0) return; if (envPool.length == 0) return; let env = envPool.shift(); let item = queue.shift(); if (!item) return; try { let start = performance.now(); env.reset(); for (let i = 0; i < item.files.length; i++) { const file = item.files[i]; if (i == item.files.length - 1) { await env.writeFile("/" + file.name + ".ts", file.body); } else { env.writeFile("/" + file.name + ".ts", file.body); } } // for (let file of item.files) { // if (file.name == "main") // await env.writeFile("/" + file.name + ".ts", file.body); // } let output = await env.regenerate(); let finalOutput = ""; let dts = ""; let fileDts = new Map(); let errors = await env.errors(); if (errors.length > 0) { item.callback({ errors: errors, }); envPool.push(env); consumeQueue(); return; } for (let o of output) { if ( !item.files.find( (f) => f.name == o.path.replace(/^\//g, "").replace(".js", "").replace(".d.ts", "") ) && !(item.files.length >= 1 && item.files[0].name == "__lib") ) continue; if (o.path.endsWith(".d.ts")) { fileDts.set( o.path.replace(/^\//g, "").replace(".js", "").replace(".d.ts", ""), o.contents .split("\n") .filter((l) => !l.startsWith("import")) .join("\n") ); } else { if (item.files.length >= 1 && item.files[0].name == "__lib") { finalOutput += ` ((defineFunc) => { let define = (deps, func) => defineFunc(${JSON.stringify(o.path)}, deps, func); ${o.contents} })(define); `; } else { finalOutput += ` ((defineFunc) => { let define = (deps, func) => defineFunc(${JSON.stringify(o.path)}, deps, func); ${o.contents} })(define); `; } } } let final = prefixConst(item.files.map((f) => f.name)) + finalOutput + `\n});`; if (item.files.length >= 1 && item.files[0].name == "__lib") { final = finalOutput; } let doMinify = false; if (doMinify) { final = minify.minify(final); // console.log(final); } console.log("Generated in " + (performance.now() - start) + "ms"); item.callback({ output: final, dts: filterDTS(fileDts), }); envPool.push(env); consumeQueue(); } catch (e) { console.error(e); envPool.push(await makeSimpleShadeupEnvironment(true, true)); item.callback({ error: "Fatal error while compiling.", }); consumeQueue(); } } return async function compile(data) { return new Promise((resolve, reject) => { queue.push({ ...data, files: data.files, callback: resolve }); consumeQueue(); }); }; } export async function makeIncrementalCompiler() { await Parser.init(); const parser = new Parser(); const Lang = await Parser.Language.load( path.resolve(path.dirname(__filename), "tree-sitter-shadeup.wasm") ); parser.setLanguage(Lang); global.shadeupParser = () => { return parser; }; const env = await makeSimpleShadeupEnvironment(true, true); const fileCache = new Map(); const fileEmitCache = new Map(); return async function compile(item) { try { let start = performance.now(); let itemsToRegen = []; let dirtyFiles = new Set(); for (let i = 0; i < item.files.length; i++) { const file = item.files[i]; let fileKey = "/" + file.name + ".ts"; let didChange = false; if (fileCache.has(fileKey)) { if (fileCache.get(fileKey) != file.body) { didChange = true; } } else { didChange = true; } if (didChange) { itemsToRegen.push(fileKey); fileCache.set(fileKey, file.body); dirtyFiles.add(fileKey); } } let dirtyFilesArray = Array.from(dirtyFiles); for (let i = 0; i < dirtyFilesArray.length; i++) { const fileKey = dirtyFilesArray[i]; const file = item.files.find((f) => "/" + f.name + ".ts" == fileKey); if (i == dirtyFilesArray.length - 1) { await env.writeFile(fileKey, file.body, true); } else { env.writeFile(fileKey, file.body, true); } } let output = await env.regenerate(itemsToRegen); console.log("Regen took " + (performance.now() - start) + "ms"); let finalOutput = ""; let dts = ""; const fileDts = new Map(); for (let o of output) { if ( !item.files.find( (f) => f.name == o.path.replace(/^\//g, "").replace(".js", "").replace(".d.ts", "") ) && !(item.files.length >= 1 && item.files[0].name == "__lib") ) continue; if (o.path.endsWith(".d.ts")) { // dts += o.contents; fileDts.set( o.path.replace(/^\//g, "").replace(".js", "").replace(".d.ts", ""), o.contents .split("\n") .filter((l) => !l.startsWith("import")) .join("\n") ); } else { if (item.files.length >= 1 && item.files[0].name == "__lib") { finalOutput += ` ((defineFunc) => { let define = (deps, func) => defineFunc(${JSON.stringify(o.path)}, deps, func); ${o.contents} })(define); `; return finalOutput; } else { fileEmitCache.set( o.path, ` ((defineFunc) => { let define = (deps, func) => defineFunc(${JSON.stringify(o.path)}, deps, func); ${o.contents} })(define); ` ); } } } for (let file of item.files) { let fileKey = "/" + file.name + ".js"; if (fileEmitCache.has(fileKey)) { finalOutput += fileEmitCache.get(fileKey); } } let final = prefixConst(item.files.map((f) => f.name)) + finalOutput + `\n});`; console.log("Generated in " + (performance.now() - start) + "ms"); return { output: final, dts: filterDTS(fileDts), // errors: env.errors(), }; } catch (e) { console.error(e); } }; } export async function makeLSPCompiler() { await Parser.init(); const parser = new Parser(); const Lang = await Parser.Language.load( path.resolve(path.dirname(__filename), "tree-sitter-shadeup.wasm") ); parser.setLanguage(Lang); global.shadeupParser = () => { return parser; }; const env = await makeSimpleShadeupEnvironment(true, true); return env; } ================================================ FILE: cli/compiler-dist/readme.md ================================================ modify the output of shadeup-compiler.js to: 1. remove the tree sitter wasm strings 2. Replace getShadeupParse with: async function getShadeupParser() { return global.shadeupParser(); } 3. import fs and replace e4.readFileSync e4 trace up to \_\_viteexternal with fs ================================================ FILE: cli/compiler-dist/shadeup-compiler.js ================================================ import ts from "typescript"; import require$$0$1 from "path"; import require$$1 from "fs"; import { createDefaultMapFromCDN, createSystem, createVirtualTypeScriptEnvironment } from "@typescript/vfs"; var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; } function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a2() { if (this instanceof a2) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, "__esModule", { value: true }); Object.keys(n).forEach(function(k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function() { return n[k]; } }); }); return a; } var sha256$1 = { exports: {} }; (function(module) { (function(root, factory2) { var exports = {}; factory2(exports); var sha2562 = exports["default"]; for (var k in exports) { sha2562[k] = exports[k]; } { module.exports = sha2562; } })(commonjsGlobal, function(exports) { exports.__esModule = true; exports.digestLength = 32; exports.blockSize = 64; var K = new Uint32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); function hashBlocks(w, v, p, pos, len) { var a, b, c2, d, e, f, g2, h, u, i, j, t1, t2; while (len >= 64) { a = v[0]; b = v[1]; c2 = v[2]; d = v[3]; e = v[4]; f = v[5]; g2 = v[6]; h = v[7]; for (i = 0; i < 16; i++) { j = pos + i * 4; w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255; } for (i = 16; i < 64; i++) { u = w[i - 2]; t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10; u = w[i - 15]; t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3; w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0); } for (i = 0; i < 64; i++) { t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g2) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0; t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c2 ^ b & c2) | 0; h = g2; g2 = f; f = e; e = d + t1 | 0; d = c2; c2 = b; b = a; a = t1 + t2 | 0; } v[0] += a; v[1] += b; v[2] += c2; v[3] += d; v[4] += e; v[5] += f; v[6] += g2; v[7] += h; pos += 64; len -= 64; } return pos; } var Hash = ( /** @class */ function() { function Hash2() { this.digestLength = exports.digestLength; this.blockSize = exports.blockSize; this.state = new Int32Array(8); this.temp = new Int32Array(64); this.buffer = new Uint8Array(128); this.bufferLength = 0; this.bytesHashed = 0; this.finished = false; this.reset(); } Hash2.prototype.reset = function() { this.state[0] = 1779033703; this.state[1] = 3144134277; this.state[2] = 1013904242; this.state[3] = 2773480762; this.state[4] = 1359893119; this.state[5] = 2600822924; this.state[6] = 528734635; this.state[7] = 1541459225; this.bufferLength = 0; this.bytesHashed = 0; this.finished = false; return this; }; Hash2.prototype.clean = function() { for (var i = 0; i < this.buffer.length; i++) { this.buffer[i] = 0; } for (var i = 0; i < this.temp.length; i++) { this.temp[i] = 0; } this.reset(); }; Hash2.prototype.update = function(data, dataLength) { if (dataLength === void 0) { dataLength = data.length; } if (this.finished) { throw new Error("SHA256: can't update because hash was finished."); } var dataPos = 0; this.bytesHashed += dataLength; if (this.bufferLength > 0) { while (this.bufferLength < 64 && dataLength > 0) { this.buffer[this.bufferLength++] = data[dataPos++]; dataLength--; } if (this.bufferLength === 64) { hashBlocks(this.temp, this.state, this.buffer, 0, 64); this.bufferLength = 0; } } if (dataLength >= 64) { dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength); dataLength %= 64; } while (dataLength > 0) { this.buffer[this.bufferLength++] = data[dataPos++]; dataLength--; } return this; }; Hash2.prototype.finish = function(out) { if (!this.finished) { var bytesHashed = this.bytesHashed; var left = this.bufferLength; var bitLenHi = bytesHashed / 536870912 | 0; var bitLenLo = bytesHashed << 3; var padLength = bytesHashed % 64 < 56 ? 64 : 128; this.buffer[left] = 128; for (var i = left + 1; i < padLength - 8; i++) { this.buffer[i] = 0; } this.buffer[padLength - 8] = bitLenHi >>> 24 & 255; this.buffer[padLength - 7] = bitLenHi >>> 16 & 255; this.buffer[padLength - 6] = bitLenHi >>> 8 & 255; this.buffer[padLength - 5] = bitLenHi >>> 0 & 255; this.buffer[padLength - 4] = bitLenLo >>> 24 & 255; this.buffer[padLength - 3] = bitLenLo >>> 16 & 255; this.buffer[padLength - 2] = bitLenLo >>> 8 & 255; this.buffer[padLength - 1] = bitLenLo >>> 0 & 255; hashBlocks(this.temp, this.state, this.buffer, 0, padLength); this.finished = true; } for (var i = 0; i < 8; i++) { out[i * 4 + 0] = this.state[i] >>> 24 & 255; out[i * 4 + 1] = this.state[i] >>> 16 & 255; out[i * 4 + 2] = this.state[i] >>> 8 & 255; out[i * 4 + 3] = this.state[i] >>> 0 & 255; } return this; }; Hash2.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; Hash2.prototype._saveState = function(out) { for (var i = 0; i < this.state.length; i++) { out[i] = this.state[i]; } }; Hash2.prototype._restoreState = function(from, bytesHashed) { for (var i = 0; i < this.state.length; i++) { this.state[i] = from[i]; } this.bytesHashed = bytesHashed; this.finished = false; this.bufferLength = 0; }; return Hash2; }() ); exports.Hash = Hash; var HMAC = ( /** @class */ function() { function HMAC2(key) { this.inner = new Hash(); this.outer = new Hash(); this.blockSize = this.inner.blockSize; this.digestLength = this.inner.digestLength; var pad = new Uint8Array(this.blockSize); if (key.length > this.blockSize) { new Hash().update(key).finish(pad).clean(); } else { for (var i = 0; i < key.length; i++) { pad[i] = key[i]; } } for (var i = 0; i < pad.length; i++) { pad[i] ^= 54; } this.inner.update(pad); for (var i = 0; i < pad.length; i++) { pad[i] ^= 54 ^ 92; } this.outer.update(pad); this.istate = new Uint32Array(8); this.ostate = new Uint32Array(8); this.inner._saveState(this.istate); this.outer._saveState(this.ostate); for (var i = 0; i < pad.length; i++) { pad[i] = 0; } } HMAC2.prototype.reset = function() { this.inner._restoreState(this.istate, this.inner.blockSize); this.outer._restoreState(this.ostate, this.outer.blockSize); return this; }; HMAC2.prototype.clean = function() { for (var i = 0; i < this.istate.length; i++) { this.ostate[i] = this.istate[i] = 0; } this.inner.clean(); this.outer.clean(); }; HMAC2.prototype.update = function(data) { this.inner.update(data); return this; }; HMAC2.prototype.finish = function(out) { if (this.outer.finished) { this.outer.finish(out); } else { this.inner.finish(out); this.outer.update(out, this.digestLength).finish(out); } return this; }; HMAC2.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; return HMAC2; }() ); exports.HMAC = HMAC; function hash(data) { var h = new Hash().update(data); var digest = h.digest(); h.clean(); return digest; } exports.hash = hash; exports["default"] = hash; function hmac(key, data) { var h = new HMAC(key).update(data); var digest = h.digest(); h.clean(); return digest; } exports.hmac = hmac; function fillBuffer(buffer2, hmac2, info, counter) { var num = counter[0]; if (num === 0) { throw new Error("hkdf: cannot expand more"); } hmac2.reset(); if (num > 1) { hmac2.update(buffer2); } if (info) { hmac2.update(info); } hmac2.update(counter); hmac2.finish(buffer2); counter[0]++; } var hkdfSalt = new Uint8Array(exports.digestLength); function hkdf(key, salt, info, length) { if (salt === void 0) { salt = hkdfSalt; } if (length === void 0) { length = 32; } var counter = new Uint8Array([1]); var okm = hmac(salt, key); var hmac_ = new HMAC(okm); var buffer2 = new Uint8Array(hmac_.digestLength); var bufpos = buffer2.length; var out = new Uint8Array(length); for (var i = 0; i < length; i++) { if (bufpos === buffer2.length) { fillBuffer(buffer2, hmac_, info, counter); bufpos = 0; } out[i] = buffer2[bufpos++]; } hmac_.clean(); buffer2.fill(0); counter.fill(0); return out; } exports.hkdf = hkdf; function pbkdf2(password, salt, iterations, dkLen) { var prf = new HMAC(password); var len = prf.digestLength; var ctr = new Uint8Array(4); var t = new Uint8Array(len); var u = new Uint8Array(len); var dk = new Uint8Array(dkLen); for (var i = 0; i * len < dkLen; i++) { var c2 = i + 1; ctr[0] = c2 >>> 24 & 255; ctr[1] = c2 >>> 16 & 255; ctr[2] = c2 >>> 8 & 255; ctr[3] = c2 >>> 0 & 255; prf.reset(); prf.update(salt); prf.update(ctr); prf.finish(u); for (var j = 0; j < len; j++) { t[j] = u[j]; } for (var j = 2; j <= iterations; j++) { prf.reset(); prf.update(u).finish(u); for (var k = 0; k < len; k++) { t[k] ^= u[k]; } } for (var j = 0; j < len && i * len + j < dkLen; j++) { dk[i * len + j] = t[j]; } } for (var i = 0; i < len; i++) { t[i] = u[i] = 0; } for (var i = 0; i < 4; i++) { ctr[i] = 0; } prf.clean(); return dk; } exports.pbkdf2 = pbkdf2; }); })(sha256$1); var sha256Exports = sha256$1.exports; const sha256 = /* @__PURE__ */ getDefaultExportFromCjs(sha256Exports); function cleanName(name) { return name.replaceAll("file:///", "").replaceAll(".", "_dot_").replaceAll("/", "_slash_").replaceAll("-", "_dash_"); } function closest(node2, cb) { while (node2) { if (cb(node2)) return node2; node2 = node2.parent; } return null; } function findShadeupTags(declar) { let matcher = /=tag\((.+)\)$/g; let doc = ts.getJSDocTags(declar); for (let d of doc) { if (d.tagName.text !== "shadeup") continue; if (typeof d.comment === "string") { let matches = matcher.exec(d.comment); if (matches) { return matches[1].split(",").map((s) => s.trim()); } } } return []; } function getFunctionDeclarationFromCallExpression(checker, node2) { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && ts.isFunctionDeclaration(funcDeclar)) { return funcDeclar; } } } } function toposort(edges) { return toposortinternal(uniqueNodes(edges), edges); } function toposortinternal(nodes, edges) { var cursor = nodes.length, sorted = new Array(cursor), visited = {}, i = cursor, outgoingEdges = makeOutgoingEdges(edges), nodesHash = makeNodesHash(nodes); edges.forEach(function(edge) { if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) { throw new Error("Unknown node. There is an unknown node in the supplied edges."); } }); while (i--) { if (!visited[i]) visit(nodes[i], i, /* @__PURE__ */ new Set()); } return sorted; function visit(node2, i2, predecessors) { if (predecessors.has(node2)) { var nodeRep; try { nodeRep = ", node was:" + JSON.stringify(node2); } catch (e) { nodeRep = ""; } throw new Error("Cyclic dependency" + nodeRep); } if (!nodesHash.has(node2)) { throw new Error( "Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(node2) ); } if (visited[i2]) return; visited[i2] = true; var outgoing = outgoingEdges.get(node2) || /* @__PURE__ */ new Set(); outgoing = Array.from(outgoing); if (i2 = outgoing.length) { predecessors.add(node2); do { var child = outgoing[--i2]; visit(child, nodesHash.get(child), predecessors); } while (i2); predecessors.delete(node2); } sorted[--cursor] = node2; } } function uniqueNodes(arr) { var res = /* @__PURE__ */ new Set(); for (var i = 0, len = arr.length; i < len; i++) { var edge = arr[i]; res.add(edge[0]); res.add(edge[1]); } return Array.from(res); } function makeOutgoingEdges(arr) { var edges = /* @__PURE__ */ new Map(); for (var i = 0, len = arr.length; i < len; i++) { var edge = arr[i]; if (!edges.has(edge[0])) edges.set(edge[0], /* @__PURE__ */ new Set()); if (!edges.has(edge[1])) edges.set(edge[1], /* @__PURE__ */ new Set()); edges.get(edge[0]).add(edge[1]); } return edges; } function makeNodesHash(arr) { var res = /* @__PURE__ */ new Map(); for (var i = 0, len = arr.length; i < len; i++) { res.set(arr[i], i); } return res; } const wgslHeader = "fn shadeup_up_swizzle_x_u32(n: u32) -> u32{\r\n return n;\r\n}\r\nfn shadeup_up_swizzle_xx_u32(n: u32) -> vec2{\r\n return vec2(n, n);\r\n}\r\nfn shadeup_up_swizzle_xxx_u32(n: u32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\nfn shadeup_up_swizzle_xxxx_u32(n: u32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_u32(n: u32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_u32(n: u32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_u32(n: u32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_x_i32(n: i32) -> i32{\r\n return n;\r\n}\r\n\r\nfn shadeup_up_swizzle_xx_i32(n: i32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxx_i32(n: i32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxxx_i32(n: i32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_i32(n: i32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_i32(n: i32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_i32(n: i32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_x_f32(n: f32) -> f32{\r\n return n;\r\n}\r\n\r\nfn shadeup_up_swizzle_xx_f32(n: f32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxx_f32(n: f32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxxx_f32(n: f32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_f32(n: f32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_f32(n: f32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_f32(n: f32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn squash_bool_vec2(n: vec2) -> bool {\r\n return n.x && n.y;\r\n}\r\n\r\nfn squash_bool_vec3(n: vec3) -> bool {\r\n return n.x && n.y && n.z;\r\n}\r\n\r\nfn squash_bool_vec4(n: vec4) -> bool {\r\n return n.x && n.y && n.z && n.w;\r\n}\r\n\r\nfn matrix_inversefloat4x4(m: mat4x4) -> mat4x4{\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n13 = m[2][0];\r\n let n14 = m[3][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n let n23 = m[2][1];\r\n let n24 = m[3][1];\r\n let n31 = m[0][2];\r\n let n32 = m[1][2];\r\n let n33 = m[2][2];\r\n let n34 = m[3][2];\r\n let n41 = m[0][3];\r\n let n42 = m[1][3];\r\n let n43 = m[2][3];\r\n let n44 = m[3][3];\r\n\r\n let t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;\r\n let t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;\r\n let t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;\r\n let t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;\r\n\r\n let det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat4x4 = mat4x4();\r\n\r\n ret[0][0] = t11 * idet;\r\n ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet;\r\n ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet;\r\n ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet;\r\n\r\n ret[1][0] = t12 * idet;\r\n ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet;\r\n ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet;\r\n ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet;\r\n\r\n ret[2][0] = t13 * idet;\r\n ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet;\r\n ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet;\r\n ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet;\r\n\r\n ret[3][0] = t14 * idet;\r\n ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet;\r\n ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet;\r\n ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_inversefloat3x3(m: mat3x3) -> mat3x3{\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n13 = m[2][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n let n23 = m[2][1];\r\n let n31 = m[0][2];\r\n let n32 = m[1][2];\r\n let n33 = m[2][2];\r\n\r\n let t11 = n22 * n33 - n23 * n32;\r\n let t12 = n13 * n32 - n12 * n33;\r\n let t13 = n12 * n23 - n13 * n22;\r\n\r\n let det = n11 * t11 + n21 * t12 + n31 * t13;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat3x3 = mat3x3();\r\n\r\n ret[0][0] = t11 * idet;\r\n ret[0][1] = (n23 * n31 - n21 * n33) * idet;\r\n ret[0][2] = (n21 * n32 - n22 * n31) * idet;\r\n\r\n ret[1][0] = t12 * idet;\r\n ret[1][1] = (n11 * n33 - n13 * n31) * idet;\r\n ret[1][2] = (n12 * n31 - n11 * n32) * idet;\r\n\r\n ret[2][0] = t13 * idet;\r\n ret[2][1] = (n13 * n21 - n11 * n23) * idet;\r\n ret[2][2] = (n11 * n22 - n12 * n21) * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_inversefloat2x2(m: mat2x2) -> mat2x2 {\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n\r\n let det = n11 * n22 - n12 * n21;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat2x2 = mat2x2();\r\n\r\n ret[0][0] = n22 * idet;\r\n ret[0][1] = -n12 * idet;\r\n ret[1][0] = -n21 * idet;\r\n ret[1][1] = n11 * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_transposefloat2x2(m: mat2x2) -> mat2x2 {\r\n return mat2x2(m[0][0], m[1][0], m[0][1], m[1][1]);\r\n}\r\n\r\nfn matrix_transposefloat3x3(m: mat3x3) -> mat3x3 {\r\n return mat3x3\r\n (\r\n m[0][0], m[1][0], m[2][0],\r\n m[0][1], m[1][1], m[2][1],\r\n m[0][2], m[1][2], m[2][2]\r\n );\r\n}\r\n\r\nfn matrix_transposefloat4x4(m: mat4x4) -> mat4x4 {\r\n return mat4x4\r\n (\r\n m[0][0], m[1][0], m[2][0], m[3][0],\r\n m[0][1], m[1][1], m[2][1], m[3][1],\r\n m[0][2], m[1][2], m[2][2], m[3][2],\r\n m[0][3], m[1][3], m[2][3], m[3][3]\r\n );\r\n}\r\n\r\nfn bilerp_float(a: f32, b: f32, c: f32, d: f32, x: f32, y: f32) -> f32 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float2(a: vec2, b: vec2, c: vec2, d: vec2, x: f32, y: f32) -> vec2 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float3(a: vec3, b: vec3, c: vec3, d: vec3, x: f32, y: f32) -> vec3 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float4(a: vec4, b: vec4, c: vec4, d: vec4, x: f32, y: f32) -> vec4 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float2x2(a: mat2x2, b: mat2x2, c: mat2x2, d: mat2x2, x: f32, y: f32) -> mat2x2 {\r\n return mat2x2\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y)\r\n );\r\n}\r\n\r\nfn bilerp_float3x3(a: mat3x3, b: mat3x3, c: mat3x3, d: mat3x3, x: f32, y: f32) -> mat3x3 {\r\n return mat3x3\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[0][2], b[0][2], c[0][2], d[0][2], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y),\r\n bilerp_float(a[1][2], b[1][2], c[1][2], d[1][2], x, y),\r\n bilerp_float(a[2][0], b[2][0], c[2][0], d[2][0], x, y),\r\n bilerp_float(a[2][1], b[2][1], c[2][1], d[2][1], x, y),\r\n bilerp_float(a[2][2], b[2][2], c[2][2], d[2][2], x, y)\r\n );\r\n}\r\n\r\nfn bilerp_float4x4(a: mat4x4, b: mat4x4, c: mat4x4, d: mat4x4, x: f32, y: f32) -> mat4x4 {\r\n return mat4x4\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[0][2], b[0][2], c[0][2], d[0][2], x, y),\r\n bilerp_float(a[0][3], b[0][3], c[0][3], d[0][3], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y),\r\n bilerp_float(a[1][2], b[1][2], c[1][2], d[1][2], x, y),\r\n bilerp_float(a[1][3], b[1][3], c[1][3], d[1][3], x, y),\r\n bilerp_float(a[2][0], b[2][0], c[2][0], d[2][0], x, y),\r\n bilerp_float(a[2][1], b[2][1], c[2][1], d[2][1], x, y),\r\n bilerp_float(a[2][2], b[2][2], c[2][2], d[2][2], x, y),\r\n bilerp_float(a[2][3], b[2][3], c[2][3], d[2][3], x, y),\r\n bilerp_float(a[3][0], b[3][0], c[3][0], d[3][0], x, y),\r\n bilerp_float(a[3][1], b[3][1], c[3][1], d[3][1], x, y),\r\n bilerp_float(a[3][2], b[3][2], c[3][2], d[3][2], x, y),\r\n bilerp_float(a[3][3], b[3][3], c[3][3], d[3][3], x, y)\r\n );\r\n}"; function validate(file, ast, checker) { performance.now(); const errors2 = []; function add(e) { if (e) { if (Array.isArray(e)) { errors2.push(...e); } else { errors2.push(e); } } } function visit(ctx) { ctx.node.forEachChild( (node2) => visit({ ...ctx, node: node2 }) ); if (ctx.node.kind == ts.SyntaxKind.PropertyAccessExpression) { if (ts.isPropertyAccessExpression(ctx.node)) { add(validatePropertyAccessExpression(ctx, ctx.node)); } } else if (ctx.node.kind == ts.SyntaxKind.ConditionalExpression) { if (ts.isConditionalExpression(ctx.node)) { add(validateConditionalExpression(ctx, ctx.node)); } } else if (ctx.node.kind == ts.SyntaxKind.CallExpression) { if (ts.isCallExpression(ctx.node)) { add(validateCallExpression(ctx, ctx.node)); } } } visit({ file, ast, checker, node: ast }); return errors2; } function validateGraph(env2, file, ast, checker) { performance.now(); const errors2 = []; function add(e) { if (e) { if (Array.isArray(e)) { errors2.push(...e); } else { errors2.push(e); } } } function visit(ctx) { ctx.node.forEachChild( (node2) => visit({ ...ctx, node: node2 }) ); if (ts.isCallExpression(ctx.node)) { let lhsType = checker?.getTypeAtLocation(ctx.node.getChildAt(0)); let sig = lhsType?.getCallSignatures(); if (sig && sig[0] && sig[0].getDeclaration()) { let declaration = sig[0].getDeclaration(); if (ts.isIdentifier(ctx.node.expression) && ctx.node.expression.text == "makeShader") { checker?.getTypeAtLocation(declaration); if (ctx.node.arguments.length >= 2) { if (ts.isArrowFunction(ctx.node.arguments[1])) { add(validateShaderCalls(env2, ctx, ctx.node.arguments[1])); } } } } } if (ts.isExpressionStatement(ctx.node)) { add(validateStatement(ctx, ctx.node)); } if (ts.isArrayLiteralExpression(ctx.node)) { add(validateArrayLiteral(ctx, ctx.node)); } } visit({ file, ast, checker, node: ast }); return errors2; } function isStaticPropertyAccessExpression(checker, node2) { let resultType = checker.getSymbolAtLocation(node2); if (!resultType) return false; let tos = checker.getTypeOfSymbolAtLocation(resultType, node2); let isStaticMember = false; if (resultType.parent) { let p = resultType.parent; if (p.valueDeclaration && p.name != "__" && !ts.isSourceFile(p.valueDeclaration) && p.flags & ts.SymbolFlags.Namespace) { isStaticMember = true; } } tos.getCallSignatures().forEach((s) => { if (s.declaration) { s.declaration.modifiers?.forEach((m) => { if (m.kind == ts.SyntaxKind.StaticKeyword) { isStaticMember = true; } }); } }); return isStaticMember; } function validateStatement({ checker, file }, node2) { if (ts.isLiteralExpression(node2.expression) || ts.isPropertyAccessChain(node2.expression) || ts.isPropertyAccessExpression(node2.expression) || ts.isIdentifier(node2.expression)) { return { file: node2.getSourceFile(), code: 0, messageText: `This expression has no effect`, category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }; } } function validateConditionalExpression({ checker, file }, node2) { let thenType = checker.getTypeAtLocation(node2.whenTrue); let elseType = checker.getTypeAtLocation(node2.whenFalse); if (!isTypeCompatible(checker, thenType, elseType)) { return void 0; } return void 0; } function validateCallExpression({ checker, file }, node2) { if (ts.isPropertyAccessExpression(node2.expression)) { let left = node2.expression.expression; if (!ts.isIdentifier(left)) return void 0; if (left.text != "__") return void 0; let right = node2.expression.name.text; if (right.startsWith("int") && (right[right.length - 1] == "2" || right[right.length - 1] == "3" || right[right.length - 1] == "4")) { for (let i = 0; i < node2.arguments.length; i++) { let arg = node2.arguments[i]; let type2 = checker.getTypeAtLocation(arg); let typeName = checker.typeToString(type2); if (typeName.startsWith("uint")) { if (node2.arguments.length != 1) { return { file: node2.getSourceFile(), code: 0, messageText: `Cannot convert from uint to int during vector construction, use int() before`, category: ts.DiagnosticCategory.Error, start: arg.getStart(), length: arg.getEnd() - arg.getStart() }; } } } } } return void 0; } function validatePropertyAccessExpression({ checker, file }, node2) { let midNode = node2.getChildren()[1]; if (file.mapping && midNode) { let range2 = lookupIndexMappingRange(file.mapping, midNode.getStart(), midNode.getEnd()); let s = file.content.substring(range2.start, range2.end); let isStaticAccess = s == "::"; let resultType = checker.getSymbolAtLocation(node2); if (resultType) { let tos = checker.getTypeOfSymbolAtLocation(resultType, node2); let isStaticMember = false; if (resultType.parent) { let p = resultType.parent; if (p.valueDeclaration && p.name != "__" && !ts.isSourceFile(p.valueDeclaration) && p.flags & ts.SymbolFlags.Namespace) { isStaticMember = true; } } tos.getCallSignatures().forEach((s2) => { if (s2.declaration) { s2.declaration.modifiers?.forEach((m) => { if (m.kind == ts.SyntaxKind.StaticKeyword) { isStaticMember = true; } }); } }); resultType.getDeclarations()?.forEach((d) => { if (ts.canHaveModifiers(d) && d.modifiers) { d.modifiers.forEach((m) => { if (m.kind == ts.SyntaxKind.StaticKeyword) { isStaticMember = true; } }); } }); if (isStaticMember && !isStaticAccess) { return { file: node2.getSourceFile(), code: 0, messageText: `Cannot access static member with '${s}' use '::' instead`, category: ts.DiagnosticCategory.Error, start: midNode.getStart(), length: midNode.getEnd() - midNode.getStart() }; } else if (!isStaticMember && isStaticAccess) { return { file: node2.getSourceFile(), code: 0, messageText: `Cannot access non-static member with '${s}' use '.' instead`, category: ts.DiagnosticCategory.Error, start: midNode.getStart(), length: midNode.getEnd() - midNode.getStart() }; } } } return void 0; } function isTypeCompatible(checker, type2, typeOther) { return checker.isTypeAssignableTo(type2, typeOther); } function validateArrayLiteral({ checker, file }, node2) { if (node2.elements.length == 3) { let name1 = checker.typeToString(checker.getTypeAtLocation(node2.elements[0])); let name2 = checker.typeToString(checker.getTypeAtLocation(node2.elements[1])); let name3 = checker.typeToString(checker.getTypeAtLocation(node2.elements[2])); if (name1 == "0" && name2 == "shader" && name3 == "0") { return void 0; } } return void 0; } const SHADER_TYPE_BLACKLIST = ["string", "null", "map"]; function validateShaderTypeUse(env2, { checker, file }, diags, node2, typeNode) { let type2 = checker.typeToString(typeNode); if (SHADER_TYPE_BLACKLIST.includes(type2) || type2.startsWith("map<")) { diags.push({ file: node2.getSourceFile(), code: 0, messageText: `Cannot use type '${type2}' in shader`, category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }); } if (typeNode.isUnion() && type2 != "boolean") { diags.push({ file: node2.getSourceFile(), code: 0, messageText: `Cannot use union types in shaders ('${type2}')`, category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }); } if (typeNode.isLiteral()) { diags.push({ file: node2.getSourceFile(), code: 0, messageText: `Cannot use literal types in shaders ('${type2}')`, category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }); } } function validateShaderCalls(env2, vs, node2) { let diags = []; const { checker, file } = vs; let visit = (node22) => { if (ts.isCallExpression(node22)) { let declar = getFunctionDeclarationFromCallExpression(checker, node22); if (declar) { let graphNodeName = getFunctionNodeName(declar); let graphNode = env2.tagGraph.getNode(graphNodeName); if (graphNode) { if (graphNode.tags.includes("async")) { let rawChain = env2.tagGraph.resolveTagSourceChain(graphNodeName, "async"); let chain = rawChain.map((m) => m.split(":")[1]).join(" <- "); if (rawChain[rawChain.length - 1].split(":")[1] == "texture2d_internal_empty") ; else { diags.push({ file: node22.getSourceFile(), code: 0, messageText: `Cannot call cpu-only function from a shader. ${chain}`, category: ts.DiagnosticCategory.Error, start: node22.getStart(), length: node22.getEnd() - node22.getStart() }); } } } } validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22)); } if (ts.isPropertyAccessExpression(node22)) { validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22)); } if (ts.isIdentifier(node22)) { validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22)); } if (ts.isElementAccessExpression(node22)) { validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22)); } if (ts.isVariableDeclaration(node22)) { let arrType = checker.getTypeAtLocation(node22); let typeInfo = getArrayTypeInfo(checker, arrType); if (typeInfo.isArray) { if (typeInfo.staticSize <= 0) { diags.push({ file: node22.getSourceFile(), code: 0, messageText: `Please explicitly specify the size of the array (let a: T[10] = ...)`, category: ts.DiagnosticCategory.Error, start: node22.getStart(), length: node22.getEnd() - node22.getStart() }); } } } ts.forEachChild(node22, visit); }; ts.forEachChild(node2, visit); return diags; } var tsutils = {}; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { d2.__proto__ = b2; } || function(d2, b2) { for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign2(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c2 = arguments.length, r = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c2 < 3 ? d(r) : c2 > 3 ? d(target, key, r) : d(target, key)) || r; return c2 > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g2; return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() { return this; }), g2; function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __createBinding(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; } function __exportStar(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function() { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g2 = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i; function verb(n) { if (g2[n]) i[n] = function(v) { return new Promise(function(a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g2[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function(e) { throw e; }), verb("return"), i[Symbol.iterator] = function() { return this; }, i; function verb(n, f) { i[n] = o[n] ? function(v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve({ value: v2, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; } result.default = mod; return result; } function __importDefault(mod) { return mod && mod.__esModule ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } const tslib_es6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, get __assign() { return __assign; }, __asyncDelegator, __asyncGenerator, __asyncValues, __await, __awaiter, __classPrivateFieldGet, __classPrivateFieldSet, __createBinding, __decorate, __exportStar, __extends, __generator, __importDefault, __importStar, __makeTemplateObject, __metadata, __param, __read, __rest, __spread, __spreadArrays, __values }, Symbol.toStringTag, { value: "Module" })); const require$$0 = /* @__PURE__ */ getAugmentedNamespace(tslib_es6); var typeguard = {}; var node$4 = {}; var node$3 = {}; var node$2 = {}; var node$1 = {}; var node = {}; var hasRequiredNode$4; function requireNode$4() { if (hasRequiredNode$4) return node; hasRequiredNode$4 = 1; Object.defineProperty(node, "__esModule", { value: true }); node.isExpressionStatement = node.isExpression = node.isExportSpecifier = node.isExportDeclaration = node.isExportAssignment = node.isEnumMember = node.isEnumDeclaration = node.isEntityNameExpression = node.isEntityName = node.isEmptyStatement = node.isElementAccessExpression = node.isDoStatement = node.isDeleteExpression = node.isDefaultClause = node.isDecorator = node.isDebuggerStatement = node.isComputedPropertyName = node.isContinueStatement = node.isConstructSignatureDeclaration = node.isConstructorTypeNode = node.isConstructorDeclaration = node.isConditionalTypeNode = node.isConditionalExpression = node.isCommaListExpression = node.isClassLikeDeclaration = node.isClassExpression = node.isClassDeclaration = node.isCatchClause = node.isCaseOrDefaultClause = node.isCaseClause = node.isCaseBlock = node.isCallSignatureDeclaration = node.isCallLikeExpression = node.isCallExpression = node.isBreakStatement = node.isBreakOrContinueStatement = node.isBooleanLiteral = node.isBlockLike = node.isBlock = node.isBindingPattern = node.isBindingElement = node.isBinaryExpression = node.isAwaitExpression = node.isAssertionExpression = node.isAsExpression = node.isArrowFunction = node.isArrayTypeNode = node.isArrayLiteralExpression = node.isArrayBindingPattern = node.isAccessorDeclaration = void 0; node.isNamespaceImport = node.isNamespaceDeclaration = node.isNamedImports = node.isNamedExports = node.isModuleDeclaration = node.isModuleBlock = node.isMethodSignature = node.isMethodDeclaration = node.isMetaProperty = node.isMappedTypeNode = node.isLiteralTypeNode = node.isLiteralExpression = node.isLabeledStatement = node.isJsxText = node.isJsxSpreadAttribute = node.isJsxSelfClosingElement = node.isJsxOpeningLikeElement = node.isJsxOpeningFragment = node.isJsxOpeningElement = node.isJsxFragment = node.isJsxExpression = node.isJsxElement = node.isJsxClosingFragment = node.isJsxClosingElement = node.isJsxAttributes = node.isJsxAttributeLike = node.isJsxAttribute = node.isJsDoc = node.isIterationStatement = node.isIntersectionTypeNode = node.isInterfaceDeclaration = node.isInferTypeNode = node.isIndexSignatureDeclaration = node.isIndexedAccessTypeNode = node.isImportSpecifier = node.isImportEqualsDeclaration = node.isImportDeclaration = node.isImportClause = node.isIfStatement = node.isIdentifier = node.isGetAccessorDeclaration = node.isFunctionTypeNode = node.isFunctionExpression = node.isFunctionDeclaration = node.isForStatement = node.isForOfStatement = node.isForInOrOfStatement = node.isForInStatement = node.isExternalModuleReference = node.isExpressionWithTypeArguments = void 0; node.isVariableStatement = node.isVariableDeclaration = node.isUnionTypeNode = node.isTypeQueryNode = node.isTypeReferenceNode = node.isTypePredicateNode = node.isTypeParameterDeclaration = node.isTypeOperatorNode = node.isTypeOfExpression = node.isTypeLiteralNode = node.isTypeAssertion = node.isTypeAliasDeclaration = node.isTupleTypeNode = node.isTryStatement = node.isThrowStatement = node.isTextualLiteral = node.isTemplateLiteral = node.isTemplateExpression = node.isTaggedTemplateExpression = node.isSyntaxList = node.isSwitchStatement = node.isStringLiteral = node.isSpreadElement = node.isSpreadAssignment = node.isSourceFile = node.isSignatureDeclaration = node.isShorthandPropertyAssignment = node.isSetAccessorDeclaration = node.isReturnStatement = node.isRegularExpressionLiteral = node.isQualifiedName = node.isPropertySignature = node.isPropertyDeclaration = node.isPropertyAssignment = node.isPropertyAccessExpression = node.isPrefixUnaryExpression = node.isPostfixUnaryExpression = node.isParenthesizedTypeNode = node.isParenthesizedExpression = node.isParameterDeclaration = node.isOmittedExpression = node.isObjectLiteralExpression = node.isObjectBindingPattern = node.isNumericOrStringLikeLiteral = node.isNumericLiteral = node.isNullLiteral = node.isNoSubstitutionTemplateLiteral = node.isNonNullExpression = node.isNewExpression = node.isNamespaceExportDeclaration = void 0; node.isWithStatement = node.isWhileStatement = node.isVoidExpression = node.isVariableDeclarationList = void 0; const ts$1 = ts; function isAccessorDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.GetAccessor || node2.kind === ts$1.SyntaxKind.SetAccessor; } node.isAccessorDeclaration = isAccessorDeclaration; function isArrayBindingPattern(node2) { return node2.kind === ts$1.SyntaxKind.ArrayBindingPattern; } node.isArrayBindingPattern = isArrayBindingPattern; function isArrayLiteralExpression(node2) { return node2.kind === ts$1.SyntaxKind.ArrayLiteralExpression; } node.isArrayLiteralExpression = isArrayLiteralExpression; function isArrayTypeNode2(node2) { return node2.kind === ts$1.SyntaxKind.ArrayType; } node.isArrayTypeNode = isArrayTypeNode2; function isArrowFunction(node2) { return node2.kind === ts$1.SyntaxKind.ArrowFunction; } node.isArrowFunction = isArrowFunction; function isAsExpression(node2) { return node2.kind === ts$1.SyntaxKind.AsExpression; } node.isAsExpression = isAsExpression; function isAssertionExpression(node2) { return node2.kind === ts$1.SyntaxKind.AsExpression || node2.kind === ts$1.SyntaxKind.TypeAssertionExpression; } node.isAssertionExpression = isAssertionExpression; function isAwaitExpression(node2) { return node2.kind === ts$1.SyntaxKind.AwaitExpression; } node.isAwaitExpression = isAwaitExpression; function isBinaryExpression(node2) { return node2.kind === ts$1.SyntaxKind.BinaryExpression; } node.isBinaryExpression = isBinaryExpression; function isBindingElement(node2) { return node2.kind === ts$1.SyntaxKind.BindingElement; } node.isBindingElement = isBindingElement; function isBindingPattern(node2) { return node2.kind === ts$1.SyntaxKind.ArrayBindingPattern || node2.kind === ts$1.SyntaxKind.ObjectBindingPattern; } node.isBindingPattern = isBindingPattern; function isBlock(node2) { return node2.kind === ts$1.SyntaxKind.Block; } node.isBlock = isBlock; function isBlockLike(node2) { return node2.statements !== void 0; } node.isBlockLike = isBlockLike; function isBooleanLiteral(node2) { return node2.kind === ts$1.SyntaxKind.TrueKeyword || node2.kind === ts$1.SyntaxKind.FalseKeyword; } node.isBooleanLiteral = isBooleanLiteral; function isBreakOrContinueStatement(node2) { return node2.kind === ts$1.SyntaxKind.BreakStatement || node2.kind === ts$1.SyntaxKind.ContinueStatement; } node.isBreakOrContinueStatement = isBreakOrContinueStatement; function isBreakStatement(node2) { return node2.kind === ts$1.SyntaxKind.BreakStatement; } node.isBreakStatement = isBreakStatement; function isCallExpression2(node2) { return node2.kind === ts$1.SyntaxKind.CallExpression; } node.isCallExpression = isCallExpression2; function isCallLikeExpression(node2) { switch (node2.kind) { case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.Decorator: case ts$1.SyntaxKind.JsxOpeningElement: case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.NewExpression: case ts$1.SyntaxKind.TaggedTemplateExpression: return true; default: return false; } } node.isCallLikeExpression = isCallLikeExpression; function isCallSignatureDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.CallSignature; } node.isCallSignatureDeclaration = isCallSignatureDeclaration; function isCaseBlock(node2) { return node2.kind === ts$1.SyntaxKind.CaseBlock; } node.isCaseBlock = isCaseBlock; function isCaseClause(node2) { return node2.kind === ts$1.SyntaxKind.CaseClause; } node.isCaseClause = isCaseClause; function isCaseOrDefaultClause(node2) { return node2.kind === ts$1.SyntaxKind.CaseClause || node2.kind === ts$1.SyntaxKind.DefaultClause; } node.isCaseOrDefaultClause = isCaseOrDefaultClause; function isCatchClause(node2) { return node2.kind === ts$1.SyntaxKind.CatchClause; } node.isCatchClause = isCatchClause; function isClassDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ClassDeclaration; } node.isClassDeclaration = isClassDeclaration; function isClassExpression(node2) { return node2.kind === ts$1.SyntaxKind.ClassExpression; } node.isClassExpression = isClassExpression; function isClassLikeDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ClassDeclaration || node2.kind === ts$1.SyntaxKind.ClassExpression; } node.isClassLikeDeclaration = isClassLikeDeclaration; function isCommaListExpression(node2) { return node2.kind === ts$1.SyntaxKind.CommaListExpression; } node.isCommaListExpression = isCommaListExpression; function isConditionalExpression(node2) { return node2.kind === ts$1.SyntaxKind.ConditionalExpression; } node.isConditionalExpression = isConditionalExpression; function isConditionalTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.ConditionalType; } node.isConditionalTypeNode = isConditionalTypeNode; function isConstructorDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.Constructor; } node.isConstructorDeclaration = isConstructorDeclaration; function isConstructorTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.ConstructorType; } node.isConstructorTypeNode = isConstructorTypeNode; function isConstructSignatureDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ConstructSignature; } node.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isContinueStatement(node2) { return node2.kind === ts$1.SyntaxKind.ContinueStatement; } node.isContinueStatement = isContinueStatement; function isComputedPropertyName(node2) { return node2.kind === ts$1.SyntaxKind.ComputedPropertyName; } node.isComputedPropertyName = isComputedPropertyName; function isDebuggerStatement(node2) { return node2.kind === ts$1.SyntaxKind.DebuggerStatement; } node.isDebuggerStatement = isDebuggerStatement; function isDecorator(node2) { return node2.kind === ts$1.SyntaxKind.Decorator; } node.isDecorator = isDecorator; function isDefaultClause(node2) { return node2.kind === ts$1.SyntaxKind.DefaultClause; } node.isDefaultClause = isDefaultClause; function isDeleteExpression(node2) { return node2.kind === ts$1.SyntaxKind.DeleteExpression; } node.isDeleteExpression = isDeleteExpression; function isDoStatement(node2) { return node2.kind === ts$1.SyntaxKind.DoStatement; } node.isDoStatement = isDoStatement; function isElementAccessExpression(node2) { return node2.kind === ts$1.SyntaxKind.ElementAccessExpression; } node.isElementAccessExpression = isElementAccessExpression; function isEmptyStatement(node2) { return node2.kind === ts$1.SyntaxKind.EmptyStatement; } node.isEmptyStatement = isEmptyStatement; function isEntityName(node2) { return node2.kind === ts$1.SyntaxKind.Identifier || isQualifiedName(node2); } node.isEntityName = isEntityName; function isEntityNameExpression(node2) { return node2.kind === ts$1.SyntaxKind.Identifier || isPropertyAccessExpression2(node2) && isEntityNameExpression(node2.expression); } node.isEntityNameExpression = isEntityNameExpression; function isEnumDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.EnumDeclaration; } node.isEnumDeclaration = isEnumDeclaration; function isEnumMember(node2) { return node2.kind === ts$1.SyntaxKind.EnumMember; } node.isEnumMember = isEnumMember; function isExportAssignment(node2) { return node2.kind === ts$1.SyntaxKind.ExportAssignment; } node.isExportAssignment = isExportAssignment; function isExportDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ExportDeclaration; } node.isExportDeclaration = isExportDeclaration; function isExportSpecifier(node2) { return node2.kind === ts$1.SyntaxKind.ExportSpecifier; } node.isExportSpecifier = isExportSpecifier; function isExpression(node2) { switch (node2.kind) { case ts$1.SyntaxKind.ArrayLiteralExpression: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.AsExpression: case ts$1.SyntaxKind.AwaitExpression: case ts$1.SyntaxKind.BinaryExpression: case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.CommaListExpression: case ts$1.SyntaxKind.ConditionalExpression: case ts$1.SyntaxKind.DeleteExpression: case ts$1.SyntaxKind.ElementAccessExpression: case ts$1.SyntaxKind.FalseKeyword: case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.Identifier: case ts$1.SyntaxKind.JsxElement: case ts$1.SyntaxKind.JsxFragment: case ts$1.SyntaxKind.JsxExpression: case ts$1.SyntaxKind.JsxOpeningElement: case ts$1.SyntaxKind.JsxOpeningFragment: case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.MetaProperty: case ts$1.SyntaxKind.NewExpression: case ts$1.SyntaxKind.NonNullExpression: case ts$1.SyntaxKind.NoSubstitutionTemplateLiteral: case ts$1.SyntaxKind.NullKeyword: case ts$1.SyntaxKind.NumericLiteral: case ts$1.SyntaxKind.ObjectLiteralExpression: case ts$1.SyntaxKind.OmittedExpression: case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.PostfixUnaryExpression: case ts$1.SyntaxKind.PrefixUnaryExpression: case ts$1.SyntaxKind.PropertyAccessExpression: case ts$1.SyntaxKind.RegularExpressionLiteral: case ts$1.SyntaxKind.SpreadElement: case ts$1.SyntaxKind.StringLiteral: case ts$1.SyntaxKind.SuperKeyword: case ts$1.SyntaxKind.TaggedTemplateExpression: case ts$1.SyntaxKind.TemplateExpression: case ts$1.SyntaxKind.ThisKeyword: case ts$1.SyntaxKind.TrueKeyword: case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.TypeOfExpression: case ts$1.SyntaxKind.VoidExpression: case ts$1.SyntaxKind.YieldExpression: return true; default: return false; } } node.isExpression = isExpression; function isExpressionStatement(node2) { return node2.kind === ts$1.SyntaxKind.ExpressionStatement; } node.isExpressionStatement = isExpressionStatement; function isExpressionWithTypeArguments(node2) { return node2.kind === ts$1.SyntaxKind.ExpressionWithTypeArguments; } node.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isExternalModuleReference(node2) { return node2.kind === ts$1.SyntaxKind.ExternalModuleReference; } node.isExternalModuleReference = isExternalModuleReference; function isForInStatement(node2) { return node2.kind === ts$1.SyntaxKind.ForInStatement; } node.isForInStatement = isForInStatement; function isForInOrOfStatement(node2) { return node2.kind === ts$1.SyntaxKind.ForOfStatement || node2.kind === ts$1.SyntaxKind.ForInStatement; } node.isForInOrOfStatement = isForInOrOfStatement; function isForOfStatement(node2) { return node2.kind === ts$1.SyntaxKind.ForOfStatement; } node.isForOfStatement = isForOfStatement; function isForStatement(node2) { return node2.kind === ts$1.SyntaxKind.ForStatement; } node.isForStatement = isForStatement; function isFunctionDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.FunctionDeclaration; } node.isFunctionDeclaration = isFunctionDeclaration; function isFunctionExpression(node2) { return node2.kind === ts$1.SyntaxKind.FunctionExpression; } node.isFunctionExpression = isFunctionExpression; function isFunctionTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.FunctionType; } node.isFunctionTypeNode = isFunctionTypeNode; function isGetAccessorDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.GetAccessor; } node.isGetAccessorDeclaration = isGetAccessorDeclaration; function isIdentifier2(node2) { return node2.kind === ts$1.SyntaxKind.Identifier; } node.isIdentifier = isIdentifier2; function isIfStatement(node2) { return node2.kind === ts$1.SyntaxKind.IfStatement; } node.isIfStatement = isIfStatement; function isImportClause(node2) { return node2.kind === ts$1.SyntaxKind.ImportClause; } node.isImportClause = isImportClause; function isImportDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ImportDeclaration; } node.isImportDeclaration = isImportDeclaration; function isImportEqualsDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ImportEqualsDeclaration; } node.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportSpecifier(node2) { return node2.kind === ts$1.SyntaxKind.ImportSpecifier; } node.isImportSpecifier = isImportSpecifier; function isIndexedAccessTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.IndexedAccessType; } node.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isIndexSignatureDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.IndexSignature; } node.isIndexSignatureDeclaration = isIndexSignatureDeclaration; function isInferTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.InferType; } node.isInferTypeNode = isInferTypeNode; function isInterfaceDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.InterfaceDeclaration; } node.isInterfaceDeclaration = isInterfaceDeclaration; function isIntersectionTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.IntersectionType; } node.isIntersectionTypeNode = isIntersectionTypeNode; function isIterationStatement(node2) { switch (node2.kind) { case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.ForInStatement: case ts$1.SyntaxKind.WhileStatement: case ts$1.SyntaxKind.DoStatement: return true; default: return false; } } node.isIterationStatement = isIterationStatement; function isJsDoc(node2) { return node2.kind === ts$1.SyntaxKind.JSDocComment; } node.isJsDoc = isJsDoc; function isJsxAttribute(node2) { return node2.kind === ts$1.SyntaxKind.JsxAttribute; } node.isJsxAttribute = isJsxAttribute; function isJsxAttributeLike(node2) { return node2.kind === ts$1.SyntaxKind.JsxAttribute || node2.kind === ts$1.SyntaxKind.JsxSpreadAttribute; } node.isJsxAttributeLike = isJsxAttributeLike; function isJsxAttributes(node2) { return node2.kind === ts$1.SyntaxKind.JsxAttributes; } node.isJsxAttributes = isJsxAttributes; function isJsxClosingElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxClosingElement; } node.isJsxClosingElement = isJsxClosingElement; function isJsxClosingFragment(node2) { return node2.kind === ts$1.SyntaxKind.JsxClosingFragment; } node.isJsxClosingFragment = isJsxClosingFragment; function isJsxElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxElement; } node.isJsxElement = isJsxElement; function isJsxExpression(node2) { return node2.kind === ts$1.SyntaxKind.JsxExpression; } node.isJsxExpression = isJsxExpression; function isJsxFragment(node2) { return node2.kind === ts$1.SyntaxKind.JsxFragment; } node.isJsxFragment = isJsxFragment; function isJsxOpeningElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxOpeningElement; } node.isJsxOpeningElement = isJsxOpeningElement; function isJsxOpeningFragment(node2) { return node2.kind === ts$1.SyntaxKind.JsxOpeningFragment; } node.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxOpeningLikeElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxOpeningElement || node2.kind === ts$1.SyntaxKind.JsxSelfClosingElement; } node.isJsxOpeningLikeElement = isJsxOpeningLikeElement; function isJsxSelfClosingElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxSelfClosingElement; } node.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxSpreadAttribute(node2) { return node2.kind === ts$1.SyntaxKind.JsxSpreadAttribute; } node.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxText(node2) { return node2.kind === ts$1.SyntaxKind.JsxText; } node.isJsxText = isJsxText; function isLabeledStatement(node2) { return node2.kind === ts$1.SyntaxKind.LabeledStatement; } node.isLabeledStatement = isLabeledStatement; function isLiteralExpression(node2) { return node2.kind >= ts$1.SyntaxKind.FirstLiteralToken && node2.kind <= ts$1.SyntaxKind.LastLiteralToken; } node.isLiteralExpression = isLiteralExpression; function isLiteralTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.LiteralType; } node.isLiteralTypeNode = isLiteralTypeNode; function isMappedTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.MappedType; } node.isMappedTypeNode = isMappedTypeNode; function isMetaProperty(node2) { return node2.kind === ts$1.SyntaxKind.MetaProperty; } node.isMetaProperty = isMetaProperty; function isMethodDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.MethodDeclaration; } node.isMethodDeclaration = isMethodDeclaration; function isMethodSignature(node2) { return node2.kind === ts$1.SyntaxKind.MethodSignature; } node.isMethodSignature = isMethodSignature; function isModuleBlock(node2) { return node2.kind === ts$1.SyntaxKind.ModuleBlock; } node.isModuleBlock = isModuleBlock; function isModuleDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ModuleDeclaration; } node.isModuleDeclaration = isModuleDeclaration; function isNamedExports(node2) { return node2.kind === ts$1.SyntaxKind.NamedExports; } node.isNamedExports = isNamedExports; function isNamedImports(node2) { return node2.kind === ts$1.SyntaxKind.NamedImports; } node.isNamedImports = isNamedImports; function isNamespaceDeclaration(node2) { return isModuleDeclaration(node2) && node2.name.kind === ts$1.SyntaxKind.Identifier && node2.body !== void 0 && (node2.body.kind === ts$1.SyntaxKind.ModuleBlock || isNamespaceDeclaration(node2.body)); } node.isNamespaceDeclaration = isNamespaceDeclaration; function isNamespaceImport(node2) { return node2.kind === ts$1.SyntaxKind.NamespaceImport; } node.isNamespaceImport = isNamespaceImport; function isNamespaceExportDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.NamespaceExportDeclaration; } node.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isNewExpression(node2) { return node2.kind === ts$1.SyntaxKind.NewExpression; } node.isNewExpression = isNewExpression; function isNonNullExpression(node2) { return node2.kind === ts$1.SyntaxKind.NonNullExpression; } node.isNonNullExpression = isNonNullExpression; function isNoSubstitutionTemplateLiteral(node2) { return node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral; } node.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; function isNullLiteral(node2) { return node2.kind === ts$1.SyntaxKind.NullKeyword; } node.isNullLiteral = isNullLiteral; function isNumericLiteral(node2) { return node2.kind === ts$1.SyntaxKind.NumericLiteral; } node.isNumericLiteral = isNumericLiteral; function isNumericOrStringLikeLiteral(node2) { switch (node2.kind) { case ts$1.SyntaxKind.StringLiteral: case ts$1.SyntaxKind.NumericLiteral: case ts$1.SyntaxKind.NoSubstitutionTemplateLiteral: return true; default: return false; } } node.isNumericOrStringLikeLiteral = isNumericOrStringLikeLiteral; function isObjectBindingPattern(node2) { return node2.kind === ts$1.SyntaxKind.ObjectBindingPattern; } node.isObjectBindingPattern = isObjectBindingPattern; function isObjectLiteralExpression(node2) { return node2.kind === ts$1.SyntaxKind.ObjectLiteralExpression; } node.isObjectLiteralExpression = isObjectLiteralExpression; function isOmittedExpression(node2) { return node2.kind === ts$1.SyntaxKind.OmittedExpression; } node.isOmittedExpression = isOmittedExpression; function isParameterDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.Parameter; } node.isParameterDeclaration = isParameterDeclaration; function isParenthesizedExpression(node2) { return node2.kind === ts$1.SyntaxKind.ParenthesizedExpression; } node.isParenthesizedExpression = isParenthesizedExpression; function isParenthesizedTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.ParenthesizedType; } node.isParenthesizedTypeNode = isParenthesizedTypeNode; function isPostfixUnaryExpression(node2) { return node2.kind === ts$1.SyntaxKind.PostfixUnaryExpression; } node.isPostfixUnaryExpression = isPostfixUnaryExpression; function isPrefixUnaryExpression(node2) { return node2.kind === ts$1.SyntaxKind.PrefixUnaryExpression; } node.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPropertyAccessExpression2(node2) { return node2.kind === ts$1.SyntaxKind.PropertyAccessExpression; } node.isPropertyAccessExpression = isPropertyAccessExpression2; function isPropertyAssignment(node2) { return node2.kind === ts$1.SyntaxKind.PropertyAssignment; } node.isPropertyAssignment = isPropertyAssignment; function isPropertyDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.PropertyDeclaration; } node.isPropertyDeclaration = isPropertyDeclaration; function isPropertySignature(node2) { return node2.kind === ts$1.SyntaxKind.PropertySignature; } node.isPropertySignature = isPropertySignature; function isQualifiedName(node2) { return node2.kind === ts$1.SyntaxKind.QualifiedName; } node.isQualifiedName = isQualifiedName; function isRegularExpressionLiteral(node2) { return node2.kind === ts$1.SyntaxKind.RegularExpressionLiteral; } node.isRegularExpressionLiteral = isRegularExpressionLiteral; function isReturnStatement(node2) { return node2.kind === ts$1.SyntaxKind.ReturnStatement; } node.isReturnStatement = isReturnStatement; function isSetAccessorDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.SetAccessor; } node.isSetAccessorDeclaration = isSetAccessorDeclaration; function isShorthandPropertyAssignment(node2) { return node2.kind === ts$1.SyntaxKind.ShorthandPropertyAssignment; } node.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSignatureDeclaration(node2) { return node2.parameters !== void 0; } node.isSignatureDeclaration = isSignatureDeclaration; function isSourceFile(node2) { return node2.kind === ts$1.SyntaxKind.SourceFile; } node.isSourceFile = isSourceFile; function isSpreadAssignment(node2) { return node2.kind === ts$1.SyntaxKind.SpreadAssignment; } node.isSpreadAssignment = isSpreadAssignment; function isSpreadElement(node2) { return node2.kind === ts$1.SyntaxKind.SpreadElement; } node.isSpreadElement = isSpreadElement; function isStringLiteral(node2) { return node2.kind === ts$1.SyntaxKind.StringLiteral; } node.isStringLiteral = isStringLiteral; function isSwitchStatement(node2) { return node2.kind === ts$1.SyntaxKind.SwitchStatement; } node.isSwitchStatement = isSwitchStatement; function isSyntaxList(node2) { return node2.kind === ts$1.SyntaxKind.SyntaxList; } node.isSyntaxList = isSyntaxList; function isTaggedTemplateExpression(node2) { return node2.kind === ts$1.SyntaxKind.TaggedTemplateExpression; } node.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTemplateExpression(node2) { return node2.kind === ts$1.SyntaxKind.TemplateExpression; } node.isTemplateExpression = isTemplateExpression; function isTemplateLiteral(node2) { return node2.kind === ts$1.SyntaxKind.TemplateExpression || node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral; } node.isTemplateLiteral = isTemplateLiteral; function isTextualLiteral(node2) { return node2.kind === ts$1.SyntaxKind.StringLiteral || node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral; } node.isTextualLiteral = isTextualLiteral; function isThrowStatement(node2) { return node2.kind === ts$1.SyntaxKind.ThrowStatement; } node.isThrowStatement = isThrowStatement; function isTryStatement(node2) { return node2.kind === ts$1.SyntaxKind.TryStatement; } node.isTryStatement = isTryStatement; function isTupleTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.TupleType; } node.isTupleTypeNode = isTupleTypeNode; function isTypeAliasDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.TypeAliasDeclaration; } node.isTypeAliasDeclaration = isTypeAliasDeclaration; function isTypeAssertion(node2) { return node2.kind === ts$1.SyntaxKind.TypeAssertionExpression; } node.isTypeAssertion = isTypeAssertion; function isTypeLiteralNode(node2) { return node2.kind === ts$1.SyntaxKind.TypeLiteral; } node.isTypeLiteralNode = isTypeLiteralNode; function isTypeOfExpression(node2) { return node2.kind === ts$1.SyntaxKind.TypeOfExpression; } node.isTypeOfExpression = isTypeOfExpression; function isTypeOperatorNode(node2) { return node2.kind === ts$1.SyntaxKind.TypeOperator; } node.isTypeOperatorNode = isTypeOperatorNode; function isTypeParameterDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.TypeParameter; } node.isTypeParameterDeclaration = isTypeParameterDeclaration; function isTypePredicateNode(node2) { return node2.kind === ts$1.SyntaxKind.TypePredicate; } node.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node2) { return node2.kind === ts$1.SyntaxKind.TypeReference; } node.isTypeReferenceNode = isTypeReferenceNode; function isTypeQueryNode(node2) { return node2.kind === ts$1.SyntaxKind.TypeQuery; } node.isTypeQueryNode = isTypeQueryNode; function isUnionTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.UnionType; } node.isUnionTypeNode = isUnionTypeNode; function isVariableDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.VariableDeclaration; } node.isVariableDeclaration = isVariableDeclaration; function isVariableStatement(node2) { return node2.kind === ts$1.SyntaxKind.VariableStatement; } node.isVariableStatement = isVariableStatement; function isVariableDeclarationList(node2) { return node2.kind === ts$1.SyntaxKind.VariableDeclarationList; } node.isVariableDeclarationList = isVariableDeclarationList; function isVoidExpression(node2) { return node2.kind === ts$1.SyntaxKind.VoidExpression; } node.isVoidExpression = isVoidExpression; function isWhileStatement(node2) { return node2.kind === ts$1.SyntaxKind.WhileStatement; } node.isWhileStatement = isWhileStatement; function isWithStatement(node2) { return node2.kind === ts$1.SyntaxKind.WithStatement; } node.isWithStatement = isWithStatement; return node; } var hasRequiredNode$3; function requireNode$3() { if (hasRequiredNode$3) return node$1; hasRequiredNode$3 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isImportTypeNode = void 0; const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$4(), exports); const ts$1 = ts; function isImportTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.ImportType; } exports.isImportTypeNode = isImportTypeNode; })(node$1); return node$1; } var hasRequiredNode$2; function requireNode$2() { if (hasRequiredNode$2) return node$2; hasRequiredNode$2 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isSyntheticExpression = exports.isRestTypeNode = exports.isOptionalTypeNode = void 0; const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$3(), exports); const ts$1 = ts; function isOptionalTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.OptionalType; } exports.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.RestType; } exports.isRestTypeNode = isRestTypeNode; function isSyntheticExpression(node2) { return node2.kind === ts$1.SyntaxKind.SyntheticExpression; } exports.isSyntheticExpression = isSyntheticExpression; })(node$2); return node$2; } var hasRequiredNode$1; function requireNode$1() { if (hasRequiredNode$1) return node$3; hasRequiredNode$1 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isBigIntLiteral = void 0; const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$2(), exports); const ts$1 = ts; function isBigIntLiteral(node2) { return node2.kind === ts$1.SyntaxKind.BigIntLiteral; } exports.isBigIntLiteral = isBigIntLiteral; })(node$3); return node$3; } var hasRequiredNode; function requireNode() { if (hasRequiredNode) return node$4; hasRequiredNode = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$1(), exports); })(node$4); return node$4; } var type$5 = {}; var type$4 = {}; var type$3 = {}; var type$2 = {}; var type$1 = {}; var hasRequiredType$5; function requireType$5() { if (hasRequiredType$5) return type$1; hasRequiredType$5 = 1; Object.defineProperty(type$1, "__esModule", { value: true }); type$1.isUniqueESSymbolType = type$1.isUnionType = type$1.isUnionOrIntersectionType = type$1.isTypeVariable = type$1.isTypeReference = type$1.isTypeParameter = type$1.isSubstitutionType = type$1.isObjectType = type$1.isLiteralType = type$1.isIntersectionType = type$1.isInterfaceType = type$1.isInstantiableType = type$1.isIndexedAccessype = type$1.isIndexedAccessType = type$1.isGenericType = type$1.isEnumType = type$1.isConditionalType = void 0; const ts$1 = ts; function isConditionalType(type2) { return (type2.flags & ts$1.TypeFlags.Conditional) !== 0; } type$1.isConditionalType = isConditionalType; function isEnumType(type2) { return (type2.flags & ts$1.TypeFlags.Enum) !== 0; } type$1.isEnumType = isEnumType; function isGenericType(type2) { return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.ClassOrInterface) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.Reference) !== 0; } type$1.isGenericType = isGenericType; function isIndexedAccessType(type2) { return (type2.flags & ts$1.TypeFlags.IndexedAccess) !== 0; } type$1.isIndexedAccessType = isIndexedAccessType; function isIndexedAccessype(type2) { return (type2.flags & ts$1.TypeFlags.Index) !== 0; } type$1.isIndexedAccessype = isIndexedAccessype; function isInstantiableType(type2) { return (type2.flags & ts$1.TypeFlags.Instantiable) !== 0; } type$1.isInstantiableType = isInstantiableType; function isInterfaceType(type2) { return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.ClassOrInterface) !== 0; } type$1.isInterfaceType = isInterfaceType; function isIntersectionType(type2) { return (type2.flags & ts$1.TypeFlags.Intersection) !== 0; } type$1.isIntersectionType = isIntersectionType; function isLiteralType(type2) { return (type2.flags & (ts$1.TypeFlags.StringOrNumberLiteral | ts$1.TypeFlags.BigIntLiteral)) !== 0; } type$1.isLiteralType = isLiteralType; function isObjectType(type2) { return (type2.flags & ts$1.TypeFlags.Object) !== 0; } type$1.isObjectType = isObjectType; function isSubstitutionType(type2) { return (type2.flags & ts$1.TypeFlags.Substitution) !== 0; } type$1.isSubstitutionType = isSubstitutionType; function isTypeParameter(type2) { return (type2.flags & ts$1.TypeFlags.TypeParameter) !== 0; } type$1.isTypeParameter = isTypeParameter; function isTypeReference(type2) { return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.Reference) !== 0; } type$1.isTypeReference = isTypeReference; function isTypeVariable(type2) { return (type2.flags & ts$1.TypeFlags.TypeVariable) !== 0; } type$1.isTypeVariable = isTypeVariable; function isUnionOrIntersectionType(type2) { return (type2.flags & ts$1.TypeFlags.UnionOrIntersection) !== 0; } type$1.isUnionOrIntersectionType = isUnionOrIntersectionType; function isUnionType(type2) { return (type2.flags & ts$1.TypeFlags.Union) !== 0; } type$1.isUnionType = isUnionType; function isUniqueESSymbolType(type2) { return (type2.flags & ts$1.TypeFlags.UniqueESSymbol) !== 0; } type$1.isUniqueESSymbolType = isUniqueESSymbolType; return type$1; } var hasRequiredType$4; function requireType$4() { if (hasRequiredType$4) return type$2; hasRequiredType$4 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireType$5(), exports); })(type$2); return type$2; } var hasRequiredType$3; function requireType$3() { if (hasRequiredType$3) return type$3; hasRequiredType$3 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isTupleTypeReference = exports.isTupleType = void 0; const tslib_1 = require$$0; tslib_1.__exportStar(requireType$4(), exports); const ts$1 = ts; const type_1 = requireType$4(); function isTupleType(type2) { return (type2.flags & ts$1.TypeFlags.Object && type2.objectFlags & ts$1.ObjectFlags.Tuple) !== 0; } exports.isTupleType = isTupleType; function isTupleTypeReference(type2) { return type_1.isTypeReference(type2) && isTupleType(type2.target); } exports.isTupleTypeReference = isTupleTypeReference; })(type$3); return type$3; } var hasRequiredType$2; function requireType$2() { if (hasRequiredType$2) return type$4; hasRequiredType$2 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireType$3(), exports); })(type$4); return type$4; } var hasRequiredType$1; function requireType$1() { if (hasRequiredType$1) return type$5; hasRequiredType$1 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireType$2(), exports); })(type$5); return type$5; } var hasRequiredTypeguard; function requireTypeguard() { if (hasRequiredTypeguard) return typeguard; hasRequiredTypeguard = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireNode(), exports); tslib_1.__exportStar(requireType$1(), exports); })(typeguard); return typeguard; } var util$2 = {}; var util$1 = {}; var _3_2 = {}; var hasRequired_3_2; function require_3_2() { if (hasRequired_3_2) return _3_2; hasRequired_3_2 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$1(), exports); tslib_1.__exportStar(requireType$2(), exports); })(_3_2); return _3_2; } var type = {}; var hasRequiredType; function requireType() { if (hasRequiredType) return type; hasRequiredType = 1; Object.defineProperty(type, "__esModule", { value: true }); type.getBaseClassMemberOfClassElement = type.getIteratorYieldResultFromIteratorResult = type.getInstanceTypeOfClassLikeDeclaration = type.getConstructorTypeOfClassLikeDeclaration = type.getSymbolOfClassLikeDeclaration = type.getPropertyNameFromType = type.symbolHasReadonlyDeclaration = type.isPropertyReadonlyInType = type.getWellKnownSymbolPropertyOfType = type.getPropertyOfType = type.isBooleanLiteralType = type.isFalsyType = type.isThenableType = type.someTypePart = type.intersectionTypeParts = type.unionTypeParts = type.getCallSignaturesOfType = type.isTypeAssignableToString = type.isTypeAssignableToNumber = type.isOptionalChainingUndefinedMarkerType = type.removeOptionalChainingUndefinedMarkerType = type.removeOptionalityFromType = type.isEmptyObjectType = void 0; const ts$1 = ts; const type_1 = requireType$1(); const util_1 = requireUtil$1(); const node_1 = requireNode(); function isEmptyObjectType(type2) { if (type_1.isObjectType(type2) && type2.objectFlags & ts$1.ObjectFlags.Anonymous && type2.getProperties().length === 0 && type2.getCallSignatures().length === 0 && type2.getConstructSignatures().length === 0 && type2.getStringIndexType() === void 0 && type2.getNumberIndexType() === void 0) { const baseTypes = type2.getBaseTypes(); return baseTypes === void 0 || baseTypes.every(isEmptyObjectType); } return false; } type.isEmptyObjectType = isEmptyObjectType; function removeOptionalityFromType(checker, type2) { if (!containsTypeWithFlag(type2, ts$1.TypeFlags.Undefined)) return type2; const allowsNull = containsTypeWithFlag(type2, ts$1.TypeFlags.Null); type2 = checker.getNonNullableType(type2); return allowsNull ? checker.getNullableType(type2, ts$1.TypeFlags.Null) : type2; } type.removeOptionalityFromType = removeOptionalityFromType; function containsTypeWithFlag(type2, flag) { for (const t of unionTypeParts(type2)) if (util_1.isTypeFlagSet(t, flag)) return true; return false; } function removeOptionalChainingUndefinedMarkerType(checker, type2) { if (!type_1.isUnionType(type2)) return isOptionalChainingUndefinedMarkerType(checker, type2) ? type2.getNonNullableType() : type2; let flags = 0; let containsUndefinedMarker = false; for (const t of type2.types) { if (isOptionalChainingUndefinedMarkerType(checker, t)) { containsUndefinedMarker = true; } else { flags |= t.flags; } } return containsUndefinedMarker ? checker.getNullableType(type2.getNonNullableType(), flags) : type2; } type.removeOptionalChainingUndefinedMarkerType = removeOptionalChainingUndefinedMarkerType; function isOptionalChainingUndefinedMarkerType(checker, t) { return util_1.isTypeFlagSet(t, ts$1.TypeFlags.Undefined) && checker.getNullableType(t.getNonNullableType(), ts$1.TypeFlags.Undefined) !== t; } type.isOptionalChainingUndefinedMarkerType = isOptionalChainingUndefinedMarkerType; function isTypeAssignableToNumber(checker, type2) { return isTypeAssignableTo(checker, type2, ts$1.TypeFlags.NumberLike); } type.isTypeAssignableToNumber = isTypeAssignableToNumber; function isTypeAssignableToString(checker, type2) { return isTypeAssignableTo(checker, type2, ts$1.TypeFlags.StringLike); } type.isTypeAssignableToString = isTypeAssignableToString; function isTypeAssignableTo(checker, type2, flags) { flags |= ts$1.TypeFlags.Any; let typeParametersSeen; return function check(t) { if (type_1.isTypeParameter(t) && t.symbol !== void 0 && t.symbol.declarations !== void 0) { if (typeParametersSeen === void 0) { typeParametersSeen = /* @__PURE__ */ new Set([t]); } else if (!typeParametersSeen.has(t)) { typeParametersSeen.add(t); } else { return false; } const declaration = t.symbol.declarations[0]; if (declaration.constraint === void 0) return true; return check(checker.getTypeFromTypeNode(declaration.constraint)); } if (type_1.isUnionType(t)) return t.types.every(check); if (type_1.isIntersectionType(t)) return t.types.some(check); return util_1.isTypeFlagSet(t, flags); }(type2); } function getCallSignaturesOfType(type2) { if (type_1.isUnionType(type2)) { const signatures = []; for (const t of type2.types) signatures.push(...getCallSignaturesOfType(t)); return signatures; } if (type_1.isIntersectionType(type2)) { let signatures; for (const t of type2.types) { const sig = getCallSignaturesOfType(t); if (sig.length !== 0) { if (signatures !== void 0) return []; signatures = sig; } } return signatures === void 0 ? [] : signatures; } return type2.getCallSignatures(); } type.getCallSignaturesOfType = getCallSignaturesOfType; function unionTypeParts(type2) { return type_1.isUnionType(type2) ? type2.types : [type2]; } type.unionTypeParts = unionTypeParts; function intersectionTypeParts(type2) { return type_1.isIntersectionType(type2) ? type2.types : [type2]; } type.intersectionTypeParts = intersectionTypeParts; function someTypePart(type2, predicate, cb) { return predicate(type2) ? type2.types.some(cb) : cb(type2); } type.someTypePart = someTypePart; function isThenableType(checker, node2, type2 = checker.getTypeAtLocation(node2)) { for (const ty of unionTypeParts(checker.getApparentType(type2))) { const then = ty.getProperty("then"); if (then === void 0) continue; const thenType = checker.getTypeOfSymbolAtLocation(then, node2); for (const t of unionTypeParts(thenType)) for (const signature of t.getCallSignatures()) if (signature.parameters.length !== 0 && isCallback2(checker, signature.parameters[0], node2)) return true; } return false; } type.isThenableType = isThenableType; function isCallback2(checker, param, node2) { let type2 = checker.getApparentType(checker.getTypeOfSymbolAtLocation(param, node2)); if (param.valueDeclaration.dotDotDotToken) { type2 = type2.getNumberIndexType(); if (type2 === void 0) return false; } for (const t of unionTypeParts(type2)) if (t.getCallSignatures().length !== 0) return true; return false; } function isFalsyType(type2) { if (type2.flags & (ts$1.TypeFlags.Undefined | ts$1.TypeFlags.Null | ts$1.TypeFlags.Void)) return true; if (type_1.isLiteralType(type2)) return !type2.value; return isBooleanLiteralType(type2, false); } type.isFalsyType = isFalsyType; function isBooleanLiteralType(type2, literal) { return util_1.isTypeFlagSet(type2, ts$1.TypeFlags.BooleanLiteral) && type2.intrinsicName === (literal ? "true" : "false"); } type.isBooleanLiteralType = isBooleanLiteralType; function getPropertyOfType(type2, name) { if (!name.startsWith("__")) return type2.getProperty(name); return type2.getProperties().find((s) => s.escapedName === name); } type.getPropertyOfType = getPropertyOfType; function getWellKnownSymbolPropertyOfType(type2, wellKnownSymbolName, checker) { const prefix = "__@" + wellKnownSymbolName; for (const prop of type2.getProperties()) { if (!prop.name.startsWith(prefix)) continue; const globalSymbol = checker.getApparentType(checker.getTypeAtLocation(prop.valueDeclaration.name.expression)).symbol; if (prop.escapedName === getPropertyNameOfWellKnownSymbol(checker, globalSymbol, wellKnownSymbolName)) return prop; } return; } type.getWellKnownSymbolPropertyOfType = getWellKnownSymbolPropertyOfType; function getPropertyNameOfWellKnownSymbol(checker, symbolConstructor, symbolName) { const knownSymbol = symbolConstructor && checker.getTypeOfSymbolAtLocation(symbolConstructor, symbolConstructor.valueDeclaration).getProperty(symbolName); const knownSymbolType = knownSymbol && checker.getTypeOfSymbolAtLocation(knownSymbol, knownSymbol.valueDeclaration); if (knownSymbolType && type_1.isUniqueESSymbolType(knownSymbolType)) return knownSymbolType.escapedName; return "__@" + symbolName; } function isPropertyReadonlyInType(type2, name, checker) { let seenProperty = false; let seenReadonlySignature = false; for (const t of unionTypeParts(type2)) { if (getPropertyOfType(t, name) === void 0) { const index = (util_1.isNumericPropertyName(name) ? checker.getIndexInfoOfType(t, ts$1.IndexKind.Number) : void 0) || checker.getIndexInfoOfType(t, ts$1.IndexKind.String); if (index !== void 0 && index.isReadonly) { if (seenProperty) return true; seenReadonlySignature = true; } } else if (seenReadonlySignature || isReadonlyPropertyIntersection(t, name, checker)) { return true; } else { seenProperty = true; } } return false; } type.isPropertyReadonlyInType = isPropertyReadonlyInType; function isReadonlyPropertyIntersection(type2, name, checker) { return someTypePart(type2, type_1.isIntersectionType, (t) => { const prop = getPropertyOfType(t, name); if (prop === void 0) return false; if (prop.flags & ts$1.SymbolFlags.Transient) { if (/^(?:[1-9]\d*|0)$/.test(name) && type_1.isTupleTypeReference(t)) return t.target.readonly; switch (isReadonlyPropertyFromMappedType(t, name, checker)) { case true: return true; case false: return false; } } return ( // members of namespace import util_1.isSymbolFlagSet(prop, ts$1.SymbolFlags.ValueModule) || // we unwrapped every mapped type, now we can check the actual declarations symbolHasReadonlyDeclaration(prop, checker) ); }); } function isReadonlyPropertyFromMappedType(type2, name, checker) { if (!type_1.isObjectType(type2) || !util_1.isObjectFlagSet(type2, ts$1.ObjectFlags.Mapped)) return; const declaration = type2.symbol.declarations[0]; if (declaration.readonlyToken !== void 0 && !/^__@[^@]+$/.test(name)) return declaration.readonlyToken.kind !== ts$1.SyntaxKind.MinusToken; return isPropertyReadonlyInType(type2.modifiersType, name, checker); } function symbolHasReadonlyDeclaration(symbol, checker) { return (symbol.flags & ts$1.SymbolFlags.Accessor) === ts$1.SymbolFlags.GetAccessor || symbol.declarations !== void 0 && symbol.declarations.some((node2) => util_1.isModifierFlagSet(node2, ts$1.ModifierFlags.Readonly) || node_1.isVariableDeclaration(node2) && util_1.isNodeFlagSet(node2.parent, ts$1.NodeFlags.Const) || node_1.isCallExpression(node2) && util_1.isReadonlyAssignmentDeclaration(node2, checker) || node_1.isEnumMember(node2) || (node_1.isPropertyAssignment(node2) || node_1.isShorthandPropertyAssignment(node2)) && util_1.isInConstContext(node2.parent)); } type.symbolHasReadonlyDeclaration = symbolHasReadonlyDeclaration; function getPropertyNameFromType(type2) { if (type2.flags & (ts$1.TypeFlags.StringLiteral | ts$1.TypeFlags.NumberLiteral)) { const value = String(type2.value); return { displayName: value, symbolName: ts$1.escapeLeadingUnderscores(value) }; } if (type_1.isUniqueESSymbolType(type2)) return { displayName: `[${type2.symbol ? `${isKnownSymbol(type2.symbol) ? "Symbol." : ""}${type2.symbol.name}` : type2.escapedName.replace(/^__@|@\d+$/g, "")}]`, symbolName: type2.escapedName }; } type.getPropertyNameFromType = getPropertyNameFromType; function isKnownSymbol(symbol) { return util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Property) && symbol.valueDeclaration !== void 0 && node_1.isInterfaceDeclaration(symbol.valueDeclaration.parent) && symbol.valueDeclaration.parent.name.text === "SymbolConstructor" && isGlobalDeclaration(symbol.valueDeclaration.parent); } function isGlobalDeclaration(node2) { return util_1.isNodeFlagSet(node2.parent, ts$1.NodeFlags.GlobalAugmentation) || node_1.isSourceFile(node2.parent) && !ts$1.isExternalModule(node2.parent); } function getSymbolOfClassLikeDeclaration(node2, checker) { var _a; return checker.getSymbolAtLocation((_a = node2.name) !== null && _a !== void 0 ? _a : util_1.getChildOfKind(node2, ts$1.SyntaxKind.ClassKeyword)); } type.getSymbolOfClassLikeDeclaration = getSymbolOfClassLikeDeclaration; function getConstructorTypeOfClassLikeDeclaration(node2, checker) { return node2.kind === ts$1.SyntaxKind.ClassExpression ? checker.getTypeAtLocation(node2) : checker.getTypeOfSymbolAtLocation(getSymbolOfClassLikeDeclaration(node2, checker), node2); } type.getConstructorTypeOfClassLikeDeclaration = getConstructorTypeOfClassLikeDeclaration; function getInstanceTypeOfClassLikeDeclaration(node2, checker) { return node2.kind === ts$1.SyntaxKind.ClassDeclaration ? checker.getTypeAtLocation(node2) : checker.getDeclaredTypeOfSymbol(getSymbolOfClassLikeDeclaration(node2, checker)); } type.getInstanceTypeOfClassLikeDeclaration = getInstanceTypeOfClassLikeDeclaration; function getIteratorYieldResultFromIteratorResult(type2, node2, checker) { return type_1.isUnionType(type2) && type2.types.find((t) => { const done = t.getProperty("done"); return done !== void 0 && isBooleanLiteralType(removeOptionalityFromType(checker, checker.getTypeOfSymbolAtLocation(done, node2)), false); }) || type2; } type.getIteratorYieldResultFromIteratorResult = getIteratorYieldResultFromIteratorResult; function getBaseClassMemberOfClassElement(node2, checker) { if (!node_1.isClassLikeDeclaration(node2.parent)) return; const base = util_1.getBaseOfClassLikeExpression(node2.parent); if (base === void 0) return; const name = util_1.getSingleLateBoundPropertyNameOfPropertyName(node2.name, checker); if (name === void 0) return; const baseType = checker.getTypeAtLocation(util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.StaticKeyword) ? base.expression : base); return getPropertyOfType(baseType, name.symbolName); } type.getBaseClassMemberOfClassElement = getBaseClassMemberOfClassElement; return type; } var hasRequiredUtil$1; function requireUtil$1() { if (hasRequiredUtil$1) return util$1; hasRequiredUtil$1 = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isValidIdentifier = exports.getLineBreakStyle = exports.getLineRanges = exports.forEachComment = exports.forEachTokenWithTrivia = exports.forEachToken = exports.isFunctionWithBody = exports.hasOwnThisReference = exports.isBlockScopeBoundary = exports.isFunctionScopeBoundary = exports.isTypeScopeBoundary = exports.isScopeBoundary = exports.ScopeBoundarySelector = exports.ScopeBoundary = exports.isInSingleStatementContext = exports.isBlockScopedDeclarationStatement = exports.isBlockScopedVariableDeclaration = exports.isBlockScopedVariableDeclarationList = exports.getVariableDeclarationKind = exports.VariableDeclarationKind = exports.forEachDeclaredVariable = exports.forEachDestructuringIdentifier = exports.getPropertyName = exports.getWrappedNodeAtPosition = exports.getAstNodeAtPosition = exports.commentText = exports.isPositionInComment = exports.getCommentAtPosition = exports.getTokenAtPosition = exports.getNextToken = exports.getPreviousToken = exports.getNextStatement = exports.getPreviousStatement = exports.isModifierFlagSet = exports.isObjectFlagSet = exports.isSymbolFlagSet = exports.isTypeFlagSet = exports.isNodeFlagSet = exports.hasAccessModifier = exports.isParameterProperty = exports.hasModifier = exports.getModifier = exports.isThisParameter = exports.isKeywordKind = exports.isJsDocKind = exports.isTypeNodeKind = exports.isAssignmentKind = exports.isNodeKind = exports.isTokenKind = exports.getChildOfKind = void 0; exports.getBaseOfClassLikeExpression = exports.hasExhaustiveCaseClauses = exports.formatPseudoBigInt = exports.unwrapParentheses = exports.getSingleLateBoundPropertyNameOfPropertyName = exports.getLateBoundPropertyNamesOfPropertyName = exports.getLateBoundPropertyNames = exports.getPropertyNameOfWellKnownSymbol = exports.isWellKnownSymbolLiterally = exports.isBindableObjectDefinePropertyCall = exports.isReadonlyAssignmentDeclaration = exports.isInConstContext = exports.isConstAssertion = exports.getTsCheckDirective = exports.getCheckJsDirective = exports.isAmbientModule = exports.isCompilerOptionEnabled = exports.isStrictCompilerOptionEnabled = exports.getIIFE = exports.isAmbientModuleBlock = exports.isStatementInAmbientContext = exports.findImportLikeNodes = exports.findImports = exports.ImportKind = exports.parseJsDocOfNode = exports.getJsDoc = exports.canHaveJsDoc = exports.isReassignmentTarget = exports.getAccessKind = exports.AccessKind = exports.isExpressionValueUsed = exports.getDeclarationOfBindingElement = exports.hasSideEffects = exports.SideEffectOptions = exports.isSameLine = exports.isNumericPropertyName = exports.isValidJsxIdentifier = exports.isValidNumericLiteral = exports.isValidPropertyName = exports.isValidPropertyAccess = void 0; const ts$1 = ts; const node_1 = requireNode(); const _3_2_1 = require_3_2(); const type_1 = requireType(); function getChildOfKind(node2, kind, sourceFile) { for (const child of node2.getChildren(sourceFile)) if (child.kind === kind) return child; } exports.getChildOfKind = getChildOfKind; function isTokenKind(kind) { return kind >= ts$1.SyntaxKind.FirstToken && kind <= ts$1.SyntaxKind.LastToken; } exports.isTokenKind = isTokenKind; function isNodeKind(kind) { return kind >= ts$1.SyntaxKind.FirstNode; } exports.isNodeKind = isNodeKind; function isAssignmentKind(kind) { return kind >= ts$1.SyntaxKind.FirstAssignment && kind <= ts$1.SyntaxKind.LastAssignment; } exports.isAssignmentKind = isAssignmentKind; function isTypeNodeKind(kind) { return kind >= ts$1.SyntaxKind.FirstTypeNode && kind <= ts$1.SyntaxKind.LastTypeNode; } exports.isTypeNodeKind = isTypeNodeKind; function isJsDocKind(kind) { return kind >= ts$1.SyntaxKind.FirstJSDocNode && kind <= ts$1.SyntaxKind.LastJSDocNode; } exports.isJsDocKind = isJsDocKind; function isKeywordKind(kind) { return kind >= ts$1.SyntaxKind.FirstKeyword && kind <= ts$1.SyntaxKind.LastKeyword; } exports.isKeywordKind = isKeywordKind; function isThisParameter(parameter) { return parameter.name.kind === ts$1.SyntaxKind.Identifier && parameter.name.originalKeywordKind === ts$1.SyntaxKind.ThisKeyword; } exports.isThisParameter = isThisParameter; function getModifier(node2, kind) { if (node2.modifiers !== void 0) { for (const modifier of node2.modifiers) if (modifier.kind === kind) return modifier; } } exports.getModifier = getModifier; function hasModifier(modifiers, ...kinds) { if (modifiers === void 0) return false; for (const modifier of modifiers) if (kinds.includes(modifier.kind)) return true; return false; } exports.hasModifier = hasModifier; function isParameterProperty(node2) { return hasModifier(node2.modifiers, ts$1.SyntaxKind.PublicKeyword, ts$1.SyntaxKind.ProtectedKeyword, ts$1.SyntaxKind.PrivateKeyword, ts$1.SyntaxKind.ReadonlyKeyword); } exports.isParameterProperty = isParameterProperty; function hasAccessModifier(node2) { return isModifierFlagSet(node2, ts$1.ModifierFlags.AccessibilityModifier); } exports.hasAccessModifier = hasAccessModifier; function isFlagSet(obj, flag) { return (obj.flags & flag) !== 0; } exports.isNodeFlagSet = isFlagSet; exports.isTypeFlagSet = isFlagSet; exports.isSymbolFlagSet = isFlagSet; function isObjectFlagSet(objectType, flag) { return (objectType.objectFlags & flag) !== 0; } exports.isObjectFlagSet = isObjectFlagSet; function isModifierFlagSet(node2, flag) { return (ts$1.getCombinedModifierFlags(node2) & flag) !== 0; } exports.isModifierFlagSet = isModifierFlagSet; function getPreviousStatement(statement) { const parent = statement.parent; if (node_1.isBlockLike(parent)) { const index = parent.statements.indexOf(statement); if (index > 0) return parent.statements[index - 1]; } } exports.getPreviousStatement = getPreviousStatement; function getNextStatement(statement) { const parent = statement.parent; if (node_1.isBlockLike(parent)) { const index = parent.statements.indexOf(statement); if (index < parent.statements.length) return parent.statements[index + 1]; } } exports.getNextStatement = getNextStatement; function getPreviousToken(node2, sourceFile) { const { pos } = node2; if (pos === 0) return; do node2 = node2.parent; while (node2.pos === pos); return getTokenAtPositionWorker(node2, pos - 1, sourceFile !== null && sourceFile !== void 0 ? sourceFile : node2.getSourceFile(), false); } exports.getPreviousToken = getPreviousToken; function getNextToken(node2, sourceFile) { if (node2.kind === ts$1.SyntaxKind.SourceFile || node2.kind === ts$1.SyntaxKind.EndOfFileToken) return; const end = node2.end; node2 = node2.parent; while (node2.end === end) { if (node2.parent === void 0) return node2.endOfFileToken; node2 = node2.parent; } return getTokenAtPositionWorker(node2, end, sourceFile !== null && sourceFile !== void 0 ? sourceFile : node2.getSourceFile(), false); } exports.getNextToken = getNextToken; function getTokenAtPosition(parent, pos, sourceFile, allowJsDoc) { if (pos < parent.pos || pos >= parent.end) return; if (isTokenKind(parent.kind)) return parent; return getTokenAtPositionWorker(parent, pos, sourceFile !== null && sourceFile !== void 0 ? sourceFile : parent.getSourceFile(), allowJsDoc === true); } exports.getTokenAtPosition = getTokenAtPosition; function getTokenAtPositionWorker(node2, pos, sourceFile, allowJsDoc) { if (!allowJsDoc) { node2 = getAstNodeAtPosition(node2, pos); if (isTokenKind(node2.kind)) return node2; } outer: while (true) { for (const child of node2.getChildren(sourceFile)) { if (child.end > pos && (allowJsDoc || child.kind !== ts$1.SyntaxKind.JSDocComment)) { if (isTokenKind(child.kind)) return child; node2 = child; continue outer; } } return; } } function getCommentAtPosition(sourceFile, pos, parent = sourceFile) { const token = getTokenAtPosition(parent, pos, sourceFile); if (token === void 0 || token.kind === ts$1.SyntaxKind.JsxText || pos >= token.end - (ts$1.tokenToString(token.kind) || "").length) return; const startPos = token.pos === 0 ? (ts$1.getShebang(sourceFile.text) || "").length : token.pos; return startPos !== 0 && ts$1.forEachTrailingCommentRange(sourceFile.text, startPos, commentAtPositionCallback, pos) || ts$1.forEachLeadingCommentRange(sourceFile.text, startPos, commentAtPositionCallback, pos); } exports.getCommentAtPosition = getCommentAtPosition; function commentAtPositionCallback(pos, end, kind, _nl, at) { return at >= pos && at < end ? { pos, end, kind } : void 0; } function isPositionInComment(sourceFile, pos, parent) { return getCommentAtPosition(sourceFile, pos, parent) !== void 0; } exports.isPositionInComment = isPositionInComment; function commentText(sourceText, comment) { return sourceText.substring(comment.pos + 2, comment.kind === ts$1.SyntaxKind.SingleLineCommentTrivia ? comment.end : comment.end - 2); } exports.commentText = commentText; function getAstNodeAtPosition(node2, pos) { if (node2.pos > pos || node2.end <= pos) return; while (isNodeKind(node2.kind)) { const nested = ts$1.forEachChild(node2, (child) => child.pos <= pos && child.end > pos ? child : void 0); if (nested === void 0) break; node2 = nested; } return node2; } exports.getAstNodeAtPosition = getAstNodeAtPosition; function getWrappedNodeAtPosition(wrap, pos) { if (wrap.node.pos > pos || wrap.node.end <= pos) return; outer: while (true) { for (const child of wrap.children) { if (child.node.pos > pos) return wrap; if (child.node.end > pos) { wrap = child; continue outer; } } return wrap; } } exports.getWrappedNodeAtPosition = getWrappedNodeAtPosition; function getPropertyName(propertyName) { if (propertyName.kind === ts$1.SyntaxKind.ComputedPropertyName) { const expression = unwrapParentheses(propertyName.expression); if (node_1.isPrefixUnaryExpression(expression)) { let negate = false; switch (expression.operator) { case ts$1.SyntaxKind.MinusToken: negate = true; case ts$1.SyntaxKind.PlusToken: return node_1.isNumericLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text}` : _3_2_1.isBigIntLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text.slice(0, -1)}` : void 0; default: return; } } if (_3_2_1.isBigIntLiteral(expression)) return expression.text.slice(0, -1); if (node_1.isNumericOrStringLikeLiteral(expression)) return expression.text; return; } return propertyName.kind === ts$1.SyntaxKind.PrivateIdentifier ? void 0 : propertyName.text; } exports.getPropertyName = getPropertyName; function forEachDestructuringIdentifier(pattern, fn) { for (const element of pattern.elements) { if (element.kind !== ts$1.SyntaxKind.BindingElement) continue; let result; if (element.name.kind === ts$1.SyntaxKind.Identifier) { result = fn(element); } else { result = forEachDestructuringIdentifier(element.name, fn); } if (result) return result; } } exports.forEachDestructuringIdentifier = forEachDestructuringIdentifier; function forEachDeclaredVariable(declarationList, cb) { for (const declaration of declarationList.declarations) { let result; if (declaration.name.kind === ts$1.SyntaxKind.Identifier) { result = cb(declaration); } else { result = forEachDestructuringIdentifier(declaration.name, cb); } if (result) return result; } } exports.forEachDeclaredVariable = forEachDeclaredVariable; (function(VariableDeclarationKind) { VariableDeclarationKind[VariableDeclarationKind["Var"] = 0] = "Var"; VariableDeclarationKind[VariableDeclarationKind["Let"] = 1] = "Let"; VariableDeclarationKind[VariableDeclarationKind["Const"] = 2] = "Const"; })(exports.VariableDeclarationKind || (exports.VariableDeclarationKind = {})); function getVariableDeclarationKind(declarationList) { if (declarationList.flags & ts$1.NodeFlags.Let) return 1; if (declarationList.flags & ts$1.NodeFlags.Const) return 2; return 0; } exports.getVariableDeclarationKind = getVariableDeclarationKind; function isBlockScopedVariableDeclarationList(declarationList) { return (declarationList.flags & ts$1.NodeFlags.BlockScoped) !== 0; } exports.isBlockScopedVariableDeclarationList = isBlockScopedVariableDeclarationList; function isBlockScopedVariableDeclaration(declaration) { const parent = declaration.parent; return parent.kind === ts$1.SyntaxKind.CatchClause || isBlockScopedVariableDeclarationList(parent); } exports.isBlockScopedVariableDeclaration = isBlockScopedVariableDeclaration; function isBlockScopedDeclarationStatement(statement) { switch (statement.kind) { case ts$1.SyntaxKind.VariableStatement: return isBlockScopedVariableDeclarationList(statement.declarationList); case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.EnumDeclaration: case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: return true; default: return false; } } exports.isBlockScopedDeclarationStatement = isBlockScopedDeclarationStatement; function isInSingleStatementContext(statement) { switch (statement.parent.kind) { case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.ForInStatement: case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.WhileStatement: case ts$1.SyntaxKind.DoStatement: case ts$1.SyntaxKind.IfStatement: case ts$1.SyntaxKind.WithStatement: case ts$1.SyntaxKind.LabeledStatement: return true; default: return false; } } exports.isInSingleStatementContext = isInSingleStatementContext; (function(ScopeBoundary) { ScopeBoundary[ScopeBoundary["None"] = 0] = "None"; ScopeBoundary[ScopeBoundary["Function"] = 1] = "Function"; ScopeBoundary[ScopeBoundary["Block"] = 2] = "Block"; ScopeBoundary[ScopeBoundary["Type"] = 4] = "Type"; ScopeBoundary[ScopeBoundary["ConditionalType"] = 8] = "ConditionalType"; })(exports.ScopeBoundary || (exports.ScopeBoundary = {})); (function(ScopeBoundarySelector) { ScopeBoundarySelector[ScopeBoundarySelector["Function"] = 1] = "Function"; ScopeBoundarySelector[ScopeBoundarySelector["Block"] = 3] = "Block"; ScopeBoundarySelector[ScopeBoundarySelector["Type"] = 7] = "Type"; ScopeBoundarySelector[ScopeBoundarySelector["InferType"] = 8] = "InferType"; })(exports.ScopeBoundarySelector || (exports.ScopeBoundarySelector = {})); function isScopeBoundary(node2) { return isFunctionScopeBoundary(node2) || isBlockScopeBoundary(node2) || isTypeScopeBoundary(node2); } exports.isScopeBoundary = isScopeBoundary; function isTypeScopeBoundary(node2) { switch (node2.kind) { case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: case ts$1.SyntaxKind.MappedType: return 4; case ts$1.SyntaxKind.ConditionalType: return 8; default: return 0; } } exports.isTypeScopeBoundary = isTypeScopeBoundary; function isFunctionScopeBoundary(node2) { switch (node2.kind) { case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.Constructor: case ts$1.SyntaxKind.ModuleDeclaration: case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.EnumDeclaration: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.MethodSignature: case ts$1.SyntaxKind.CallSignature: case ts$1.SyntaxKind.ConstructSignature: case ts$1.SyntaxKind.ConstructorType: case ts$1.SyntaxKind.FunctionType: return 1; case ts$1.SyntaxKind.SourceFile: return ts$1.isExternalModule(node2) ? 1 : 0; default: return 0; } } exports.isFunctionScopeBoundary = isFunctionScopeBoundary; function isBlockScopeBoundary(node2) { switch (node2.kind) { case ts$1.SyntaxKind.Block: const parent = node2.parent; return parent.kind !== ts$1.SyntaxKind.CatchClause && // blocks inside SourceFile are block scope boundaries (parent.kind === ts$1.SyntaxKind.SourceFile || // blocks that are direct children of a function scope boundary are no scope boundary // for example the FunctionBlock is part of the function scope of the containing function !isFunctionScopeBoundary(parent)) ? 2 : 0; case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.ForInStatement: case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.CaseBlock: case ts$1.SyntaxKind.CatchClause: case ts$1.SyntaxKind.WithStatement: return 2; default: return 0; } } exports.isBlockScopeBoundary = isBlockScopeBoundary; function hasOwnThisReference(node2) { switch (node2.kind) { case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.FunctionExpression: return true; case ts$1.SyntaxKind.FunctionDeclaration: return node2.body !== void 0; case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: return node2.parent.kind === ts$1.SyntaxKind.ObjectLiteralExpression; default: return false; } } exports.hasOwnThisReference = hasOwnThisReference; function isFunctionWithBody(node2) { switch (node2.kind) { case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.Constructor: return node2.body !== void 0; case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.ArrowFunction: return true; default: return false; } } exports.isFunctionWithBody = isFunctionWithBody; function forEachToken(node2, cb, sourceFile = node2.getSourceFile()) { const queue = []; while (true) { if (isTokenKind(node2.kind)) { cb(node2); } else if (node2.kind !== ts$1.SyntaxKind.JSDocComment) { const children = node2.getChildren(sourceFile); if (children.length === 1) { node2 = children[0]; continue; } for (let i = children.length - 1; i >= 0; --i) queue.push(children[i]); } if (queue.length === 0) break; node2 = queue.pop(); } } exports.forEachToken = forEachToken; function forEachTokenWithTrivia(node2, cb, sourceFile = node2.getSourceFile()) { const fullText = sourceFile.text; const scanner = ts$1.createScanner(sourceFile.languageVersion, false, sourceFile.languageVariant, fullText); return forEachToken(node2, (token) => { const tokenStart = token.kind === ts$1.SyntaxKind.JsxText || token.pos === token.end ? token.pos : token.getStart(sourceFile); if (tokenStart !== token.pos) { scanner.setTextPos(token.pos); let kind = scanner.scan(); let pos = scanner.getTokenPos(); while (pos < tokenStart) { const textPos = scanner.getTextPos(); cb(fullText, kind, { pos, end: textPos }, token.parent); if (textPos === tokenStart) break; kind = scanner.scan(); pos = scanner.getTokenPos(); } } return cb(fullText, token.kind, { end: token.end, pos: tokenStart }, token.parent); }, sourceFile); } exports.forEachTokenWithTrivia = forEachTokenWithTrivia; function forEachComment(node2, cb, sourceFile = node2.getSourceFile()) { const fullText = sourceFile.text; const notJsx = sourceFile.languageVariant !== ts$1.LanguageVariant.JSX; return forEachToken(node2, (token) => { if (token.pos === token.end) return; if (token.kind !== ts$1.SyntaxKind.JsxText) ts$1.forEachLeadingCommentRange( fullText, // skip shebang at position 0 token.pos === 0 ? (ts$1.getShebang(fullText) || "").length : token.pos, commentCallback ); if (notJsx || canHaveTrailingTrivia(token)) return ts$1.forEachTrailingCommentRange(fullText, token.end, commentCallback); }, sourceFile); function commentCallback(pos, end, kind) { cb(fullText, { pos, end, kind }); } } exports.forEachComment = forEachComment; function canHaveTrailingTrivia(token) { switch (token.kind) { case ts$1.SyntaxKind.CloseBraceToken: return token.parent.kind !== ts$1.SyntaxKind.JsxExpression || !isJsxElementOrFragment(token.parent.parent); case ts$1.SyntaxKind.GreaterThanToken: switch (token.parent.kind) { case ts$1.SyntaxKind.JsxOpeningElement: return token.end !== token.parent.end; case ts$1.SyntaxKind.JsxOpeningFragment: return false; case ts$1.SyntaxKind.JsxSelfClosingElement: return token.end !== token.parent.end || // if end is not equal, this is part of the type arguments list !isJsxElementOrFragment(token.parent.parent); case ts$1.SyntaxKind.JsxClosingElement: case ts$1.SyntaxKind.JsxClosingFragment: return !isJsxElementOrFragment(token.parent.parent.parent); } } return true; } function isJsxElementOrFragment(node2) { return node2.kind === ts$1.SyntaxKind.JsxElement || node2.kind === ts$1.SyntaxKind.JsxFragment; } function getLineRanges(sourceFile) { const lineStarts = sourceFile.getLineStarts(); const result = []; const length = lineStarts.length; const sourceText = sourceFile.text; let pos = 0; for (let i = 1; i < length; ++i) { const end = lineStarts[i]; let lineEnd = end; for (; lineEnd > pos; --lineEnd) if (!ts$1.isLineBreak(sourceText.charCodeAt(lineEnd - 1))) break; result.push({ pos, end, contentLength: lineEnd - pos }); pos = end; } result.push({ pos, end: sourceFile.end, contentLength: sourceFile.end - pos }); return result; } exports.getLineRanges = getLineRanges; function getLineBreakStyle(sourceFile) { const lineStarts = sourceFile.getLineStarts(); return lineStarts.length === 1 || lineStarts[1] < 2 || sourceFile.text[lineStarts[1] - 2] !== "\r" ? "\n" : "\r\n"; } exports.getLineBreakStyle = getLineBreakStyle; let cachedScanner; function scanToken(text, languageVersion) { if (cachedScanner === void 0) { cachedScanner = ts$1.createScanner(languageVersion, false, void 0, text); } else { cachedScanner.setScriptTarget(languageVersion); cachedScanner.setText(text); } cachedScanner.scan(); return cachedScanner; } function isValidIdentifier(text, languageVersion = ts$1.ScriptTarget.Latest) { const scan = scanToken(text, languageVersion); return scan.isIdentifier() && scan.getTextPos() === text.length && scan.getTokenPos() === 0; } exports.isValidIdentifier = isValidIdentifier; function charSize(ch) { return ch >= 65536 ? 2 : 1; } function isValidPropertyAccess(text, languageVersion = ts$1.ScriptTarget.Latest) { if (text.length === 0) return false; let ch = text.codePointAt(0); if (!ts$1.isIdentifierStart(ch, languageVersion)) return false; for (let i = charSize(ch); i < text.length; i += charSize(ch)) { ch = text.codePointAt(i); if (!ts$1.isIdentifierPart(ch, languageVersion)) return false; } return true; } exports.isValidPropertyAccess = isValidPropertyAccess; function isValidPropertyName(text, languageVersion = ts$1.ScriptTarget.Latest) { if (isValidPropertyAccess(text, languageVersion)) return true; const scan = scanToken(text, languageVersion); return scan.getTextPos() === text.length && scan.getToken() === ts$1.SyntaxKind.NumericLiteral && scan.getTokenValue() === text; } exports.isValidPropertyName = isValidPropertyName; function isValidNumericLiteral(text, languageVersion = ts$1.ScriptTarget.Latest) { const scan = scanToken(text, languageVersion); return scan.getToken() === ts$1.SyntaxKind.NumericLiteral && scan.getTextPos() === text.length && scan.getTokenPos() === 0; } exports.isValidNumericLiteral = isValidNumericLiteral; function isValidJsxIdentifier(text, languageVersion = ts$1.ScriptTarget.Latest) { if (text.length === 0) return false; let seenNamespaceSeparator = false; let ch = text.codePointAt(0); if (!ts$1.isIdentifierStart(ch, languageVersion)) return false; for (let i = charSize(ch); i < text.length; i += charSize(ch)) { ch = text.codePointAt(i); if (!ts$1.isIdentifierPart(ch, languageVersion) && ch !== 45) { if (!seenNamespaceSeparator && ch === 58 && i + charSize(ch) !== text.length) { seenNamespaceSeparator = true; } else { return false; } } } return true; } exports.isValidJsxIdentifier = isValidJsxIdentifier; function isNumericPropertyName(name) { return String(+name) === name; } exports.isNumericPropertyName = isNumericPropertyName; function isSameLine(sourceFile, pos1, pos2) { return ts$1.getLineAndCharacterOfPosition(sourceFile, pos1).line === ts$1.getLineAndCharacterOfPosition(sourceFile, pos2).line; } exports.isSameLine = isSameLine; (function(SideEffectOptions) { SideEffectOptions[SideEffectOptions["None"] = 0] = "None"; SideEffectOptions[SideEffectOptions["TaggedTemplate"] = 1] = "TaggedTemplate"; SideEffectOptions[SideEffectOptions["Constructor"] = 2] = "Constructor"; SideEffectOptions[SideEffectOptions["JsxElement"] = 4] = "JsxElement"; })(exports.SideEffectOptions || (exports.SideEffectOptions = {})); function hasSideEffects(node2, options) { var _a, _b; const queue = []; while (true) { switch (node2.kind) { case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.PostfixUnaryExpression: case ts$1.SyntaxKind.AwaitExpression: case ts$1.SyntaxKind.YieldExpression: case ts$1.SyntaxKind.DeleteExpression: return true; case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.AsExpression: case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.NonNullExpression: case ts$1.SyntaxKind.VoidExpression: case ts$1.SyntaxKind.TypeOfExpression: case ts$1.SyntaxKind.PropertyAccessExpression: case ts$1.SyntaxKind.SpreadElement: case ts$1.SyntaxKind.PartiallyEmittedExpression: node2 = node2.expression; continue; case ts$1.SyntaxKind.BinaryExpression: if (isAssignmentKind(node2.operatorToken.kind)) return true; queue.push(node2.right); node2 = node2.left; continue; case ts$1.SyntaxKind.PrefixUnaryExpression: switch (node2.operator) { case ts$1.SyntaxKind.PlusPlusToken: case ts$1.SyntaxKind.MinusMinusToken: return true; default: node2 = node2.operand; continue; } case ts$1.SyntaxKind.ElementAccessExpression: if (node2.argumentExpression !== void 0) queue.push(node2.argumentExpression); node2 = node2.expression; continue; case ts$1.SyntaxKind.ConditionalExpression: queue.push(node2.whenTrue, node2.whenFalse); node2 = node2.condition; continue; case ts$1.SyntaxKind.NewExpression: if (options & 2) return true; if (node2.arguments !== void 0) queue.push(...node2.arguments); node2 = node2.expression; continue; case ts$1.SyntaxKind.TaggedTemplateExpression: if (options & 1) return true; queue.push(node2.tag); node2 = node2.template; if (node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral) break; case ts$1.SyntaxKind.TemplateExpression: for (const child of node2.templateSpans) queue.push(child.expression); break; case ts$1.SyntaxKind.ClassExpression: { if (node2.decorators !== void 0) return true; for (const child of node2.members) { if (child.decorators !== void 0) return true; if (!hasModifier(child.modifiers, ts$1.SyntaxKind.DeclareKeyword)) { if (((_a = child.name) === null || _a === void 0 ? void 0 : _a.kind) === ts$1.SyntaxKind.ComputedPropertyName) queue.push(child.name.expression); if (node_1.isMethodDeclaration(child)) { for (const p of child.parameters) if (p.decorators !== void 0) return true; } else if (node_1.isPropertyDeclaration(child) && child.initializer !== void 0 && hasModifier(child.modifiers, ts$1.SyntaxKind.StaticKeyword)) { queue.push(child.initializer); } } } const base = getBaseOfClassLikeExpression(node2); if (base === void 0) break; node2 = base.expression; continue; } case ts$1.SyntaxKind.ArrayLiteralExpression: queue.push(...node2.elements); break; case ts$1.SyntaxKind.ObjectLiteralExpression: for (const child of node2.properties) { if (((_b = child.name) === null || _b === void 0 ? void 0 : _b.kind) === ts$1.SyntaxKind.ComputedPropertyName) queue.push(child.name.expression); switch (child.kind) { case ts$1.SyntaxKind.PropertyAssignment: queue.push(child.initializer); break; case ts$1.SyntaxKind.SpreadAssignment: queue.push(child.expression); } } break; case ts$1.SyntaxKind.JsxExpression: if (node2.expression === void 0) break; node2 = node2.expression; continue; case ts$1.SyntaxKind.JsxElement: case ts$1.SyntaxKind.JsxFragment: for (const child of node2.children) if (child.kind !== ts$1.SyntaxKind.JsxText) queue.push(child); if (node2.kind === ts$1.SyntaxKind.JsxFragment) break; node2 = node2.openingElement; case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.JsxOpeningElement: if (options & 4) return true; for (const child of node2.attributes.properties) { if (child.kind === ts$1.SyntaxKind.JsxSpreadAttribute) { queue.push(child.expression); } else if (child.initializer !== void 0) { queue.push(child.initializer); } } break; case ts$1.SyntaxKind.CommaListExpression: queue.push(...node2.elements); } if (queue.length === 0) return false; node2 = queue.pop(); } } exports.hasSideEffects = hasSideEffects; function getDeclarationOfBindingElement(node2) { let parent = node2.parent.parent; while (parent.kind === ts$1.SyntaxKind.BindingElement) parent = parent.parent.parent; return parent; } exports.getDeclarationOfBindingElement = getDeclarationOfBindingElement; function isExpressionValueUsed(node2) { while (true) { const parent = node2.parent; switch (parent.kind) { case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.NewExpression: case ts$1.SyntaxKind.ElementAccessExpression: case ts$1.SyntaxKind.WhileStatement: case ts$1.SyntaxKind.DoStatement: case ts$1.SyntaxKind.WithStatement: case ts$1.SyntaxKind.ThrowStatement: case ts$1.SyntaxKind.ReturnStatement: case ts$1.SyntaxKind.JsxExpression: case ts$1.SyntaxKind.JsxSpreadAttribute: case ts$1.SyntaxKind.JsxElement: case ts$1.SyntaxKind.JsxFragment: case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.ComputedPropertyName: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.ExportSpecifier: case ts$1.SyntaxKind.ExportAssignment: case ts$1.SyntaxKind.ImportDeclaration: case ts$1.SyntaxKind.ExternalModuleReference: case ts$1.SyntaxKind.Decorator: case ts$1.SyntaxKind.TaggedTemplateExpression: case ts$1.SyntaxKind.TemplateSpan: case ts$1.SyntaxKind.ExpressionWithTypeArguments: case ts$1.SyntaxKind.TypeOfExpression: case ts$1.SyntaxKind.AwaitExpression: case ts$1.SyntaxKind.YieldExpression: case ts$1.SyntaxKind.LiteralType: case ts$1.SyntaxKind.JsxAttributes: case ts$1.SyntaxKind.JsxOpeningElement: case ts$1.SyntaxKind.JsxClosingElement: case ts$1.SyntaxKind.IfStatement: case ts$1.SyntaxKind.CaseClause: case ts$1.SyntaxKind.SwitchStatement: return true; case ts$1.SyntaxKind.PropertyAccessExpression: return parent.expression === node2; case ts$1.SyntaxKind.QualifiedName: return parent.left === node2; case ts$1.SyntaxKind.ShorthandPropertyAssignment: return parent.objectAssignmentInitializer === node2 || !isInDestructuringAssignment(parent); case ts$1.SyntaxKind.PropertyAssignment: return parent.initializer === node2 && !isInDestructuringAssignment(parent); case ts$1.SyntaxKind.SpreadAssignment: case ts$1.SyntaxKind.SpreadElement: case ts$1.SyntaxKind.ArrayLiteralExpression: return !isInDestructuringAssignment(parent); case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.AsExpression: case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.PostfixUnaryExpression: case ts$1.SyntaxKind.PrefixUnaryExpression: case ts$1.SyntaxKind.NonNullExpression: node2 = parent; continue; case ts$1.SyntaxKind.ForStatement: return parent.condition === node2; case ts$1.SyntaxKind.ForInStatement: case ts$1.SyntaxKind.ForOfStatement: return parent.expression === node2; case ts$1.SyntaxKind.ConditionalExpression: if (parent.condition === node2) return true; node2 = parent; break; case ts$1.SyntaxKind.PropertyDeclaration: case ts$1.SyntaxKind.BindingElement: case ts$1.SyntaxKind.VariableDeclaration: case ts$1.SyntaxKind.Parameter: case ts$1.SyntaxKind.EnumMember: return parent.initializer === node2; case ts$1.SyntaxKind.ImportEqualsDeclaration: return parent.moduleReference === node2; case ts$1.SyntaxKind.CommaListExpression: if (parent.elements[parent.elements.length - 1] !== node2) return false; node2 = parent; break; case ts$1.SyntaxKind.BinaryExpression: if (parent.right === node2) { if (parent.operatorToken.kind === ts$1.SyntaxKind.CommaToken) { node2 = parent; break; } return true; } switch (parent.operatorToken.kind) { case ts$1.SyntaxKind.CommaToken: case ts$1.SyntaxKind.EqualsToken: return false; case ts$1.SyntaxKind.EqualsEqualsEqualsToken: case ts$1.SyntaxKind.EqualsEqualsToken: case ts$1.SyntaxKind.ExclamationEqualsEqualsToken: case ts$1.SyntaxKind.ExclamationEqualsToken: case ts$1.SyntaxKind.InstanceOfKeyword: case ts$1.SyntaxKind.PlusToken: case ts$1.SyntaxKind.MinusToken: case ts$1.SyntaxKind.AsteriskToken: case ts$1.SyntaxKind.SlashToken: case ts$1.SyntaxKind.PercentToken: case ts$1.SyntaxKind.AsteriskAsteriskToken: case ts$1.SyntaxKind.GreaterThanToken: case ts$1.SyntaxKind.GreaterThanGreaterThanToken: case ts$1.SyntaxKind.GreaterThanGreaterThanGreaterThanToken: case ts$1.SyntaxKind.GreaterThanEqualsToken: case ts$1.SyntaxKind.LessThanToken: case ts$1.SyntaxKind.LessThanLessThanToken: case ts$1.SyntaxKind.LessThanEqualsToken: case ts$1.SyntaxKind.AmpersandToken: case ts$1.SyntaxKind.BarToken: case ts$1.SyntaxKind.CaretToken: case ts$1.SyntaxKind.BarBarToken: case ts$1.SyntaxKind.AmpersandAmpersandToken: case ts$1.SyntaxKind.QuestionQuestionToken: case ts$1.SyntaxKind.InKeyword: case ts$1.SyntaxKind.QuestionQuestionEqualsToken: case ts$1.SyntaxKind.AmpersandAmpersandEqualsToken: case ts$1.SyntaxKind.BarBarEqualsToken: return true; default: node2 = parent; } break; default: return false; } } } exports.isExpressionValueUsed = isExpressionValueUsed; function isInDestructuringAssignment(node2) { switch (node2.kind) { case ts$1.SyntaxKind.ShorthandPropertyAssignment: if (node2.objectAssignmentInitializer !== void 0) return true; case ts$1.SyntaxKind.PropertyAssignment: case ts$1.SyntaxKind.SpreadAssignment: node2 = node2.parent; break; case ts$1.SyntaxKind.SpreadElement: if (node2.parent.kind !== ts$1.SyntaxKind.ArrayLiteralExpression) return false; node2 = node2.parent; } while (true) { switch (node2.parent.kind) { case ts$1.SyntaxKind.BinaryExpression: return node2.parent.left === node2 && node2.parent.operatorToken.kind === ts$1.SyntaxKind.EqualsToken; case ts$1.SyntaxKind.ForOfStatement: return node2.parent.initializer === node2; case ts$1.SyntaxKind.ArrayLiteralExpression: case ts$1.SyntaxKind.ObjectLiteralExpression: node2 = node2.parent; break; case ts$1.SyntaxKind.SpreadAssignment: case ts$1.SyntaxKind.PropertyAssignment: node2 = node2.parent.parent; break; case ts$1.SyntaxKind.SpreadElement: if (node2.parent.parent.kind !== ts$1.SyntaxKind.ArrayLiteralExpression) return false; node2 = node2.parent.parent; break; default: return false; } } } (function(AccessKind) { AccessKind[AccessKind["None"] = 0] = "None"; AccessKind[AccessKind["Read"] = 1] = "Read"; AccessKind[AccessKind["Write"] = 2] = "Write"; AccessKind[AccessKind["Delete"] = 4] = "Delete"; AccessKind[AccessKind["ReadWrite"] = 3] = "ReadWrite"; AccessKind[AccessKind["Modification"] = 6] = "Modification"; })(exports.AccessKind || (exports.AccessKind = {})); function getAccessKind(node2) { const parent = node2.parent; switch (parent.kind) { case ts$1.SyntaxKind.DeleteExpression: return 4; case ts$1.SyntaxKind.PostfixUnaryExpression: return 3; case ts$1.SyntaxKind.PrefixUnaryExpression: return parent.operator === ts$1.SyntaxKind.PlusPlusToken || parent.operator === ts$1.SyntaxKind.MinusMinusToken ? 3 : 1; case ts$1.SyntaxKind.BinaryExpression: return parent.right === node2 ? 1 : !isAssignmentKind(parent.operatorToken.kind) ? 1 : parent.operatorToken.kind === ts$1.SyntaxKind.EqualsToken ? 2 : 3; case ts$1.SyntaxKind.ShorthandPropertyAssignment: return parent.objectAssignmentInitializer === node2 ? 1 : isInDestructuringAssignment(parent) ? 2 : 1; case ts$1.SyntaxKind.PropertyAssignment: return parent.name === node2 ? 0 : isInDestructuringAssignment(parent) ? 2 : 1; case ts$1.SyntaxKind.ArrayLiteralExpression: case ts$1.SyntaxKind.SpreadElement: case ts$1.SyntaxKind.SpreadAssignment: return isInDestructuringAssignment(parent) ? 2 : 1; case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.NonNullExpression: case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.AsExpression: return getAccessKind(parent); case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.ForInStatement: return parent.initializer === node2 ? 2 : 1; case ts$1.SyntaxKind.ExpressionWithTypeArguments: return parent.parent.token === ts$1.SyntaxKind.ExtendsKeyword && parent.parent.parent.kind !== ts$1.SyntaxKind.InterfaceDeclaration ? 1 : 0; case ts$1.SyntaxKind.ComputedPropertyName: case ts$1.SyntaxKind.ExpressionStatement: case ts$1.SyntaxKind.TypeOfExpression: case ts$1.SyntaxKind.ElementAccessExpression: case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.IfStatement: case ts$1.SyntaxKind.DoStatement: case ts$1.SyntaxKind.WhileStatement: case ts$1.SyntaxKind.SwitchStatement: case ts$1.SyntaxKind.WithStatement: case ts$1.SyntaxKind.ThrowStatement: case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.NewExpression: case ts$1.SyntaxKind.TaggedTemplateExpression: case ts$1.SyntaxKind.JsxExpression: case ts$1.SyntaxKind.Decorator: case ts$1.SyntaxKind.TemplateSpan: case ts$1.SyntaxKind.JsxOpeningElement: case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.JsxSpreadAttribute: case ts$1.SyntaxKind.VoidExpression: case ts$1.SyntaxKind.ReturnStatement: case ts$1.SyntaxKind.AwaitExpression: case ts$1.SyntaxKind.YieldExpression: case ts$1.SyntaxKind.ConditionalExpression: case ts$1.SyntaxKind.CaseClause: case ts$1.SyntaxKind.JsxElement: return 1; case ts$1.SyntaxKind.ArrowFunction: return parent.body === node2 ? 1 : 2; case ts$1.SyntaxKind.PropertyDeclaration: case ts$1.SyntaxKind.VariableDeclaration: case ts$1.SyntaxKind.Parameter: case ts$1.SyntaxKind.EnumMember: case ts$1.SyntaxKind.BindingElement: case ts$1.SyntaxKind.JsxAttribute: return parent.initializer === node2 ? 1 : 0; case ts$1.SyntaxKind.PropertyAccessExpression: return parent.expression === node2 ? 1 : 0; case ts$1.SyntaxKind.ExportAssignment: return parent.isExportEquals ? 1 : 0; } return 0; } exports.getAccessKind = getAccessKind; function isReassignmentTarget(node2) { return (getAccessKind(node2) & 2) !== 0; } exports.isReassignmentTarget = isReassignmentTarget; function canHaveJsDoc(node2) { const kind = node2.kind; switch (kind) { case ts$1.SyntaxKind.Parameter: case ts$1.SyntaxKind.CallSignature: case ts$1.SyntaxKind.ConstructSignature: case ts$1.SyntaxKind.MethodSignature: case ts$1.SyntaxKind.PropertySignature: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.SpreadAssignment: case ts$1.SyntaxKind.ShorthandPropertyAssignment: case ts$1.SyntaxKind.PropertyAssignment: case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.LabeledStatement: case ts$1.SyntaxKind.ExpressionStatement: case ts$1.SyntaxKind.VariableStatement: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.Constructor: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.PropertyDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: case ts$1.SyntaxKind.EnumMember: case ts$1.SyntaxKind.EnumDeclaration: case ts$1.SyntaxKind.ModuleDeclaration: case ts$1.SyntaxKind.ImportEqualsDeclaration: case ts$1.SyntaxKind.ImportDeclaration: case ts$1.SyntaxKind.NamespaceExportDeclaration: case ts$1.SyntaxKind.ExportAssignment: case ts$1.SyntaxKind.IndexSignature: case ts$1.SyntaxKind.FunctionType: case ts$1.SyntaxKind.ConstructorType: case ts$1.SyntaxKind.JSDocFunctionType: case ts$1.SyntaxKind.ExportDeclaration: case ts$1.SyntaxKind.NamedTupleMember: case ts$1.SyntaxKind.EndOfFileToken: return true; default: return false; } } exports.canHaveJsDoc = canHaveJsDoc; function getJsDoc(node2, sourceFile) { const result = []; for (const child of node2.getChildren(sourceFile)) { if (!node_1.isJsDoc(child)) break; result.push(child); } return result; } exports.getJsDoc = getJsDoc; function parseJsDocOfNode(node2, considerTrailingComments, sourceFile = node2.getSourceFile()) { if (canHaveJsDoc(node2) && node2.kind !== ts$1.SyntaxKind.EndOfFileToken) { const result = getJsDoc(node2, sourceFile); if (result.length !== 0 || !considerTrailingComments) return result; } return parseJsDocWorker(node2, node2.getStart(sourceFile), sourceFile, considerTrailingComments); } exports.parseJsDocOfNode = parseJsDocOfNode; function parseJsDocWorker(node2, nodeStart, sourceFile, considerTrailingComments) { const start = ts$1[considerTrailingComments && isSameLine(sourceFile, node2.pos, nodeStart) ? "forEachTrailingCommentRange" : "forEachLeadingCommentRange"]( sourceFile.text, node2.pos, // return object to make `0` a truthy value (pos, _end, kind) => kind === ts$1.SyntaxKind.MultiLineCommentTrivia && sourceFile.text[pos + 2] === "*" ? { pos } : void 0 ); if (start === void 0) return []; const startPos = start.pos; const text = sourceFile.text.slice(startPos, nodeStart); const newSourceFile = ts$1.createSourceFile("jsdoc.ts", `${text}var a;`, sourceFile.languageVersion); const result = getJsDoc(newSourceFile.statements[0], newSourceFile); for (const doc of result) updateNode(doc, node2); return result; function updateNode(n, parent) { n.pos += startPos; n.end += startPos; n.parent = parent; return ts$1.forEachChild(n, (child) => updateNode(child, n), (children) => { children.pos += startPos; children.end += startPos; for (const child of children) updateNode(child, n); }); } } (function(ImportKind) { ImportKind[ImportKind["ImportDeclaration"] = 1] = "ImportDeclaration"; ImportKind[ImportKind["ImportEquals"] = 2] = "ImportEquals"; ImportKind[ImportKind["ExportFrom"] = 4] = "ExportFrom"; ImportKind[ImportKind["DynamicImport"] = 8] = "DynamicImport"; ImportKind[ImportKind["Require"] = 16] = "Require"; ImportKind[ImportKind["ImportType"] = 32] = "ImportType"; ImportKind[ImportKind["All"] = 63] = "All"; ImportKind[ImportKind["AllImports"] = 59] = "AllImports"; ImportKind[ImportKind["AllStaticImports"] = 3] = "AllStaticImports"; ImportKind[ImportKind["AllImportExpressions"] = 24] = "AllImportExpressions"; ImportKind[ImportKind["AllRequireLike"] = 18] = "AllRequireLike"; ImportKind[ImportKind["AllNestedImports"] = 56] = "AllNestedImports"; ImportKind[ImportKind["AllTopLevelImports"] = 7] = "AllTopLevelImports"; })(exports.ImportKind || (exports.ImportKind = {})); function findImports(sourceFile, kinds, ignoreFileName = true) { const result = []; for (const node2 of findImportLikeNodes(sourceFile, kinds, ignoreFileName)) { switch (node2.kind) { case ts$1.SyntaxKind.ImportDeclaration: addIfTextualLiteral(node2.moduleSpecifier); break; case ts$1.SyntaxKind.ImportEqualsDeclaration: addIfTextualLiteral(node2.moduleReference.expression); break; case ts$1.SyntaxKind.ExportDeclaration: addIfTextualLiteral(node2.moduleSpecifier); break; case ts$1.SyntaxKind.CallExpression: addIfTextualLiteral(node2.arguments[0]); break; case ts$1.SyntaxKind.ImportType: if (node_1.isLiteralTypeNode(node2.argument)) addIfTextualLiteral(node2.argument.literal); break; default: throw new Error("unexpected node"); } } return result; function addIfTextualLiteral(node2) { if (node_1.isTextualLiteral(node2)) result.push(node2); } } exports.findImports = findImports; function findImportLikeNodes(sourceFile, kinds, ignoreFileName = true) { return new ImportFinder(sourceFile, kinds, ignoreFileName).find(); } exports.findImportLikeNodes = findImportLikeNodes; class ImportFinder { constructor(_sourceFile, _options, _ignoreFileName) { this._sourceFile = _sourceFile; this._options = _options; this._ignoreFileName = _ignoreFileName; this._result = []; } find() { if (this._sourceFile.isDeclarationFile) this._options &= ~24; if (this._options & 7) this._findImports(this._sourceFile.statements); if (this._options & 56) this._findNestedImports(); return this._result; } _findImports(statements) { for (const statement of statements) { if (node_1.isImportDeclaration(statement)) { if (this._options & 1) this._result.push(statement); } else if (node_1.isImportEqualsDeclaration(statement)) { if (this._options & 2 && statement.moduleReference.kind === ts$1.SyntaxKind.ExternalModuleReference) this._result.push(statement); } else if (node_1.isExportDeclaration(statement)) { if (statement.moduleSpecifier !== void 0 && this._options & 4) this._result.push(statement); } else if (node_1.isModuleDeclaration(statement)) { this._findImportsInModule(statement); } } } _findImportsInModule(declaration) { if (declaration.body === void 0) return; if (declaration.body.kind === ts$1.SyntaxKind.ModuleDeclaration) return this._findImportsInModule(declaration.body); this._findImports(declaration.body.statements); } _findNestedImports() { const isJavaScriptFile = this._ignoreFileName || (this._sourceFile.flags & ts$1.NodeFlags.JavaScriptFile) !== 0; let re; let includeJsDoc; if ((this._options & 56) === 16) { if (!isJavaScriptFile) return; re = /\brequire\s*[ 1) this._result.push(token.parent); } } else if (token.kind === ts$1.SyntaxKind.Identifier && token.end - "require".length === match2.index && token.parent.kind === ts$1.SyntaxKind.CallExpression && token.parent.expression === token && token.parent.arguments.length === 1) { this._result.push(token.parent); } } } } function isStatementInAmbientContext(node2) { while (node2.flags & ts$1.NodeFlags.NestedNamespace) node2 = node2.parent; return hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword) || isAmbientModuleBlock(node2.parent); } exports.isStatementInAmbientContext = isStatementInAmbientContext; function isAmbientModuleBlock(node2) { while (node2.kind === ts$1.SyntaxKind.ModuleBlock) { do node2 = node2.parent; while (node2.flags & ts$1.NodeFlags.NestedNamespace); if (hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword)) return true; node2 = node2.parent; } return false; } exports.isAmbientModuleBlock = isAmbientModuleBlock; function getIIFE(func) { let node2 = func.parent; while (node2.kind === ts$1.SyntaxKind.ParenthesizedExpression) node2 = node2.parent; return node_1.isCallExpression(node2) && func.end <= node2.expression.end ? node2 : void 0; } exports.getIIFE = getIIFE; function isStrictCompilerOptionEnabled(options, option) { return (options.strict ? options[option] !== false : options[option] === true) && (option !== "strictPropertyInitialization" || isStrictCompilerOptionEnabled(options, "strictNullChecks")); } exports.isStrictCompilerOptionEnabled = isStrictCompilerOptionEnabled; function isCompilerOptionEnabled(options, option) { switch (option) { case "stripInternal": case "declarationMap": case "emitDeclarationOnly": return options[option] === true && isCompilerOptionEnabled(options, "declaration"); case "declaration": return options.declaration || isCompilerOptionEnabled(options, "composite"); case "incremental": return options.incremental === void 0 ? isCompilerOptionEnabled(options, "composite") : options.incremental; case "skipDefaultLibCheck": return options.skipDefaultLibCheck || isCompilerOptionEnabled(options, "skipLibCheck"); case "suppressImplicitAnyIndexErrors": return options.suppressImplicitAnyIndexErrors === true && isCompilerOptionEnabled(options, "noImplicitAny"); case "allowSyntheticDefaultImports": return options.allowSyntheticDefaultImports !== void 0 ? options.allowSyntheticDefaultImports : isCompilerOptionEnabled(options, "esModuleInterop") || options.module === ts$1.ModuleKind.System; case "noUncheckedIndexedAccess": return options.noUncheckedIndexedAccess === true && isCompilerOptionEnabled(options, "strictNullChecks"); case "allowJs": return options.allowJs === void 0 ? isCompilerOptionEnabled(options, "checkJs") : options.allowJs; case "noImplicitAny": case "noImplicitThis": case "strictNullChecks": case "strictFunctionTypes": case "strictPropertyInitialization": case "alwaysStrict": case "strictBindCallApply": return isStrictCompilerOptionEnabled(options, option); } return options[option] === true; } exports.isCompilerOptionEnabled = isCompilerOptionEnabled; function isAmbientModule(node2) { return node2.name.kind === ts$1.SyntaxKind.StringLiteral || (node2.flags & ts$1.NodeFlags.GlobalAugmentation) !== 0; } exports.isAmbientModule = isAmbientModule; function getCheckJsDirective(source) { return getTsCheckDirective(source); } exports.getCheckJsDirective = getCheckJsDirective; function getTsCheckDirective(source) { let directive; ts$1.forEachLeadingCommentRange(source, (ts$1.getShebang(source) || "").length, (pos, end, kind) => { if (kind === ts$1.SyntaxKind.SingleLineCommentTrivia) { const text = source.slice(pos, end); const match2 = /^\/{2,3}\s*@ts-(no)?check(?:\s|$)/i.exec(text); if (match2 !== null) directive = { pos, end, enabled: match2[1] === void 0 }; } }); return directive; } exports.getTsCheckDirective = getTsCheckDirective; function isConstAssertion(node2) { return node_1.isTypeReferenceNode(node2.type) && node2.type.typeName.kind === ts$1.SyntaxKind.Identifier && node2.type.typeName.escapedText === "const"; } exports.isConstAssertion = isConstAssertion; function isInConstContext(node2) { let current = node2; while (true) { const parent = current.parent; outer: switch (parent.kind) { case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.AsExpression: return isConstAssertion(parent); case ts$1.SyntaxKind.PrefixUnaryExpression: if (current.kind !== ts$1.SyntaxKind.NumericLiteral) return false; switch (parent.operator) { case ts$1.SyntaxKind.PlusToken: case ts$1.SyntaxKind.MinusToken: current = parent; break outer; default: return false; } case ts$1.SyntaxKind.PropertyAssignment: if (parent.initializer !== current) return false; current = parent.parent; break; case ts$1.SyntaxKind.ShorthandPropertyAssignment: current = parent.parent; break; case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.ArrayLiteralExpression: case ts$1.SyntaxKind.ObjectLiteralExpression: case ts$1.SyntaxKind.TemplateExpression: current = parent; break; default: return false; } } } exports.isInConstContext = isInConstContext; function isReadonlyAssignmentDeclaration(node2, checker) { if (!isBindableObjectDefinePropertyCall(node2)) return false; const descriptorType = checker.getTypeAtLocation(node2.arguments[2]); if (descriptorType.getProperty("value") === void 0) return descriptorType.getProperty("set") === void 0; const writableProp = descriptorType.getProperty("writable"); if (writableProp === void 0) return false; const writableType = writableProp.valueDeclaration !== void 0 && node_1.isPropertyAssignment(writableProp.valueDeclaration) ? checker.getTypeAtLocation(writableProp.valueDeclaration.initializer) : checker.getTypeOfSymbolAtLocation(writableProp, node2.arguments[2]); return type_1.isBooleanLiteralType(writableType, false); } exports.isReadonlyAssignmentDeclaration = isReadonlyAssignmentDeclaration; function isBindableObjectDefinePropertyCall(node2) { return node2.arguments.length === 3 && node_1.isEntityNameExpression(node2.arguments[0]) && node_1.isNumericOrStringLikeLiteral(node2.arguments[1]) && node_1.isPropertyAccessExpression(node2.expression) && node2.expression.name.escapedText === "defineProperty" && node_1.isIdentifier(node2.expression.expression) && node2.expression.expression.escapedText === "Object"; } exports.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; function isWellKnownSymbolLiterally(node2) { return ts$1.isPropertyAccessExpression(node2) && ts$1.isIdentifier(node2.expression) && node2.expression.escapedText === "Symbol"; } exports.isWellKnownSymbolLiterally = isWellKnownSymbolLiterally; function getPropertyNameOfWellKnownSymbol(node2) { return { displayName: `[Symbol.${node2.name.text}]`, symbolName: "__@" + node2.name.text }; } exports.getPropertyNameOfWellKnownSymbol = getPropertyNameOfWellKnownSymbol; const isTsBefore43 = (([major, minor]) => major < "4" || major === "4" && minor < "3")(ts$1.versionMajorMinor.split(".")); function getLateBoundPropertyNames(node2, checker) { const result = { known: true, names: [] }; node2 = unwrapParentheses(node2); if (isTsBefore43 && isWellKnownSymbolLiterally(node2)) { result.names.push(getPropertyNameOfWellKnownSymbol(node2)); } else { const type2 = checker.getTypeAtLocation(node2); for (const key of type_1.unionTypeParts(checker.getBaseConstraintOfType(type2) || type2)) { const propertyName = type_1.getPropertyNameFromType(key); if (propertyName) { result.names.push(propertyName); } else { result.known = false; } } } return result; } exports.getLateBoundPropertyNames = getLateBoundPropertyNames; function getLateBoundPropertyNamesOfPropertyName(node2, checker) { const staticName = getPropertyName(node2); return staticName !== void 0 ? { known: true, names: [{ displayName: staticName, symbolName: ts$1.escapeLeadingUnderscores(staticName) }] } : node2.kind === ts$1.SyntaxKind.PrivateIdentifier ? { known: true, names: [{ displayName: node2.text, symbolName: checker.getSymbolAtLocation(node2).escapedName }] } : getLateBoundPropertyNames(node2.expression, checker); } exports.getLateBoundPropertyNamesOfPropertyName = getLateBoundPropertyNamesOfPropertyName; function getSingleLateBoundPropertyNameOfPropertyName(node2, checker) { const staticName = getPropertyName(node2); if (staticName !== void 0) return { displayName: staticName, symbolName: ts$1.escapeLeadingUnderscores(staticName) }; if (node2.kind === ts$1.SyntaxKind.PrivateIdentifier) return { displayName: node2.text, symbolName: checker.getSymbolAtLocation(node2).escapedName }; const { expression } = node2; return isTsBefore43 && isWellKnownSymbolLiterally(expression) ? getPropertyNameOfWellKnownSymbol(expression) : type_1.getPropertyNameFromType(checker.getTypeAtLocation(expression)); } exports.getSingleLateBoundPropertyNameOfPropertyName = getSingleLateBoundPropertyNameOfPropertyName; function unwrapParentheses(node2) { while (node2.kind === ts$1.SyntaxKind.ParenthesizedExpression) node2 = node2.expression; return node2; } exports.unwrapParentheses = unwrapParentheses; function formatPseudoBigInt(v) { return `${v.negative ? "-" : ""}${v.base10Value}n`; } exports.formatPseudoBigInt = formatPseudoBigInt; function hasExhaustiveCaseClauses(node2, checker) { const caseClauses = node2.caseBlock.clauses.filter(node_1.isCaseClause); if (caseClauses.length === 0) return false; const typeParts = type_1.unionTypeParts(checker.getTypeAtLocation(node2.expression)); if (typeParts.length > caseClauses.length) return false; const types2 = new Set(typeParts.map(getPrimitiveLiteralFromType)); if (types2.has(void 0)) return false; const seen = /* @__PURE__ */ new Set(); for (const clause of caseClauses) { const expressionType = checker.getTypeAtLocation(clause.expression); if (exports.isTypeFlagSet(expressionType, ts$1.TypeFlags.Never)) continue; const type2 = getPrimitiveLiteralFromType(expressionType); if (types2.has(type2)) { seen.add(type2); } else if (type2 !== "null" && type2 !== "undefined") { return false; } } return types2.size === seen.size; } exports.hasExhaustiveCaseClauses = hasExhaustiveCaseClauses; function getPrimitiveLiteralFromType(t) { if (exports.isTypeFlagSet(t, ts$1.TypeFlags.Null)) return "null"; if (exports.isTypeFlagSet(t, ts$1.TypeFlags.Undefined)) return "undefined"; if (exports.isTypeFlagSet(t, ts$1.TypeFlags.NumberLiteral)) return `${exports.isTypeFlagSet(t, ts$1.TypeFlags.EnumLiteral) ? "enum:" : ""}${t.value}`; if (exports.isTypeFlagSet(t, ts$1.TypeFlags.StringLiteral)) return `${exports.isTypeFlagSet(t, ts$1.TypeFlags.EnumLiteral) ? "enum:" : ""}string:${t.value}`; if (exports.isTypeFlagSet(t, ts$1.TypeFlags.BigIntLiteral)) return formatPseudoBigInt(t.value); if (_3_2_1.isUniqueESSymbolType(t)) return t.escapedName; if (type_1.isBooleanLiteralType(t, true)) return "true"; if (type_1.isBooleanLiteralType(t, false)) return "false"; } function getBaseOfClassLikeExpression(node2) { var _a; if (((_a = node2.heritageClauses) === null || _a === void 0 ? void 0 : _a[0].token) === ts$1.SyntaxKind.ExtendsKeyword) return node2.heritageClauses[0].types[0]; } exports.getBaseOfClassLikeExpression = getBaseOfClassLikeExpression; })(util$1); return util$1; } var usage = {}; var hasRequiredUsage; function requireUsage() { if (hasRequiredUsage) return usage; hasRequiredUsage = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.collectVariableUsage = exports.getDeclarationDomain = exports.getUsageDomain = exports.UsageDomain = exports.DeclarationDomain = void 0; const util_1 = requireUtil$1(); const ts$1 = ts; (function(DeclarationDomain) { DeclarationDomain[DeclarationDomain["Namespace"] = 1] = "Namespace"; DeclarationDomain[DeclarationDomain["Type"] = 2] = "Type"; DeclarationDomain[DeclarationDomain["Value"] = 4] = "Value"; DeclarationDomain[DeclarationDomain["Import"] = 8] = "Import"; DeclarationDomain[DeclarationDomain["Any"] = 7] = "Any"; })(exports.DeclarationDomain || (exports.DeclarationDomain = {})); (function(UsageDomain) { UsageDomain[UsageDomain["Namespace"] = 1] = "Namespace"; UsageDomain[UsageDomain["Type"] = 2] = "Type"; UsageDomain[UsageDomain["Value"] = 4] = "Value"; UsageDomain[UsageDomain["ValueOrNamespace"] = 5] = "ValueOrNamespace"; UsageDomain[UsageDomain["Any"] = 7] = "Any"; UsageDomain[UsageDomain["TypeQuery"] = 8] = "TypeQuery"; })(exports.UsageDomain || (exports.UsageDomain = {})); function getUsageDomain(node2) { const parent = node2.parent; switch (parent.kind) { case ts$1.SyntaxKind.TypeReference: return node2.originalKeywordKind !== ts$1.SyntaxKind.ConstKeyword ? 2 : void 0; case ts$1.SyntaxKind.ExpressionWithTypeArguments: return parent.parent.token === ts$1.SyntaxKind.ImplementsKeyword || parent.parent.parent.kind === ts$1.SyntaxKind.InterfaceDeclaration ? 2 : 4; case ts$1.SyntaxKind.TypeQuery: return 5 | 8; case ts$1.SyntaxKind.QualifiedName: if (parent.left === node2) { if (getEntityNameParent(parent).kind === ts$1.SyntaxKind.TypeQuery) return 1 | 8; return 1; } break; case ts$1.SyntaxKind.ExportSpecifier: if (parent.propertyName === void 0 || parent.propertyName === node2) return 7; break; case ts$1.SyntaxKind.ExportAssignment: return 7; case ts$1.SyntaxKind.BindingElement: if (parent.initializer === node2) return 5; break; case ts$1.SyntaxKind.Parameter: case ts$1.SyntaxKind.EnumMember: case ts$1.SyntaxKind.PropertyDeclaration: case ts$1.SyntaxKind.VariableDeclaration: case ts$1.SyntaxKind.PropertyAssignment: case ts$1.SyntaxKind.PropertyAccessExpression: case ts$1.SyntaxKind.ImportEqualsDeclaration: if (parent.name !== node2) return 5; break; case ts$1.SyntaxKind.JsxAttribute: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.NamespaceImport: case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.ModuleDeclaration: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.EnumDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.LabeledStatement: case ts$1.SyntaxKind.BreakStatement: case ts$1.SyntaxKind.ContinueStatement: case ts$1.SyntaxKind.ImportClause: case ts$1.SyntaxKind.ImportSpecifier: case ts$1.SyntaxKind.TypePredicate: case ts$1.SyntaxKind.MethodSignature: case ts$1.SyntaxKind.PropertySignature: case ts$1.SyntaxKind.NamespaceExportDeclaration: case ts$1.SyntaxKind.NamespaceExport: case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: case ts$1.SyntaxKind.TypeParameter: case ts$1.SyntaxKind.NamedTupleMember: break; default: return 5; } } exports.getUsageDomain = getUsageDomain; function getDeclarationDomain(node2) { switch (node2.parent.kind) { case ts$1.SyntaxKind.TypeParameter: case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: return 2; case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: return 2 | 4; case ts$1.SyntaxKind.EnumDeclaration: return 7; case ts$1.SyntaxKind.NamespaceImport: case ts$1.SyntaxKind.ImportClause: return 7 | 8; case ts$1.SyntaxKind.ImportEqualsDeclaration: case ts$1.SyntaxKind.ImportSpecifier: return node2.parent.name === node2 ? 7 | 8 : void 0; case ts$1.SyntaxKind.ModuleDeclaration: return 1; case ts$1.SyntaxKind.Parameter: if (node2.parent.parent.kind === ts$1.SyntaxKind.IndexSignature || node2.originalKeywordKind === ts$1.SyntaxKind.ThisKeyword) return; case ts$1.SyntaxKind.BindingElement: case ts$1.SyntaxKind.VariableDeclaration: return node2.parent.name === node2 ? 4 : void 0; case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.FunctionExpression: return 4; } } exports.getDeclarationDomain = getDeclarationDomain; function collectVariableUsage(sourceFile) { return new UsageWalker().getUsage(sourceFile); } exports.collectVariableUsage = collectVariableUsage; class AbstractScope { constructor(_global) { this._global = _global; this._variables = /* @__PURE__ */ new Map(); this._uses = []; this._namespaceScopes = void 0; this._enumScopes = void 0; } addVariable(identifier, name, selector, exported, domain) { const variables = this.getDestinationScope(selector).getVariables(); const declaration = { domain, exported, declaration: name }; const variable = variables.get(identifier); if (variable === void 0) { variables.set(identifier, { domain, declarations: [declaration], uses: [] }); } else { variable.domain |= domain; variable.declarations.push(declaration); } } addUse(use) { this._uses.push(use); } getVariables() { return this._variables; } getFunctionScope() { return this; } end(cb) { if (this._namespaceScopes !== void 0) this._namespaceScopes.forEach((value) => value.finish(cb)); this._namespaceScopes = this._enumScopes = void 0; this._applyUses(); this._variables.forEach((variable) => { for (const declaration of variable.declarations) { const result = { declarations: [], domain: declaration.domain, exported: declaration.exported, inGlobalScope: this._global, uses: [] }; for (const other of variable.declarations) if (other.domain & declaration.domain) result.declarations.push(other.declaration); for (const use of variable.uses) if (use.domain & declaration.domain) result.uses.push(use); cb(result, declaration.declaration, this); } }); } // tslint:disable-next-line:prefer-function-over-method markExported(_name) { } // only relevant for the root scope createOrReuseNamespaceScope(name, _exported, ambient, hasExportStatement) { let scope; if (this._namespaceScopes === void 0) { this._namespaceScopes = /* @__PURE__ */ new Map(); } else { scope = this._namespaceScopes.get(name); } if (scope === void 0) { scope = new NamespaceScope(ambient, hasExportStatement, this); this._namespaceScopes.set(name, scope); } else { scope.refresh(ambient, hasExportStatement); } return scope; } createOrReuseEnumScope(name, _exported) { let scope; if (this._enumScopes === void 0) { this._enumScopes = /* @__PURE__ */ new Map(); } else { scope = this._enumScopes.get(name); } if (scope === void 0) { scope = new EnumScope(this); this._enumScopes.set(name, scope); } return scope; } _applyUses() { for (const use of this._uses) if (!this._applyUse(use)) this._addUseToParent(use); this._uses = []; } _applyUse(use, variables = this._variables) { const variable = variables.get(use.location.text); if (variable === void 0 || (variable.domain & use.domain) === 0) return false; variable.uses.push(use); return true; } _addUseToParent(_use) { } // tslint:disable-line:prefer-function-over-method } class RootScope extends AbstractScope { constructor(_exportAll, global2) { super(global2); this._exportAll = _exportAll; this._exports = void 0; this._innerScope = new NonRootScope( this, 1 /* Function */ ); } addVariable(identifier, name, selector, exported, domain) { if (domain & 8) return super.addVariable(identifier, name, selector, exported, domain); return this._innerScope.addVariable(identifier, name, selector, exported, domain); } addUse(use, origin) { if (origin === this._innerScope) return super.addUse(use); return this._innerScope.addUse(use); } markExported(id) { if (this._exports === void 0) { this._exports = [id.text]; } else { this._exports.push(id.text); } } end(cb) { this._innerScope.end((value, key) => { value.exported = value.exported || this._exportAll || this._exports !== void 0 && this._exports.includes(key.text); value.inGlobalScope = this._global; return cb(value, key, this); }); return super.end((value, key, scope) => { value.exported = value.exported || scope === this && this._exports !== void 0 && this._exports.includes(key.text); return cb(value, key, scope); }); } getDestinationScope() { return this; } } class NonRootScope extends AbstractScope { constructor(_parent, _boundary) { super(false); this._parent = _parent; this._boundary = _boundary; } _addUseToParent(use) { return this._parent.addUse(use, this); } getDestinationScope(selector) { return this._boundary & selector ? this : this._parent.getDestinationScope(selector); } } class EnumScope extends NonRootScope { constructor(parent) { super( parent, 1 /* Function */ ); } end() { this._applyUses(); } } class ConditionalTypeScope extends NonRootScope { constructor(parent) { super( parent, 8 /* ConditionalType */ ); this._state = 0; } updateState(newState) { this._state = newState; } addUse(use) { if (this._state === 2) return void this._uses.push(use); return this._parent.addUse(use, this); } } class FunctionScope extends NonRootScope { constructor(parent) { super( parent, 1 /* Function */ ); } beginBody() { this._applyUses(); } } class AbstractNamedExpressionScope extends NonRootScope { constructor(_name, _domain, parent) { super( parent, 1 /* Function */ ); this._name = _name; this._domain = _domain; } end(cb) { this._innerScope.end(cb); return cb({ declarations: [this._name], domain: this._domain, exported: false, uses: this._uses, inGlobalScope: false }, this._name, this); } addUse(use, source) { if (source !== this._innerScope) return this._innerScope.addUse(use); if (use.domain & this._domain && use.location.text === this._name.text) { this._uses.push(use); } else { return this._parent.addUse(use, this); } } getFunctionScope() { return this._innerScope; } getDestinationScope() { return this._innerScope; } } class FunctionExpressionScope extends AbstractNamedExpressionScope { constructor(name, parent) { super(name, 4, parent); this._innerScope = new FunctionScope(this); } beginBody() { return this._innerScope.beginBody(); } } class ClassExpressionScope extends AbstractNamedExpressionScope { constructor(name, parent) { super(name, 4 | 2, parent); this._innerScope = new NonRootScope( this, 1 /* Function */ ); } } class BlockScope extends NonRootScope { constructor(_functionScope, parent) { super( parent, 2 /* Block */ ); this._functionScope = _functionScope; } getFunctionScope() { return this._functionScope; } } function mapDeclaration(declaration) { return { declaration, exported: true, domain: getDeclarationDomain(declaration) }; } class NamespaceScope extends NonRootScope { constructor(_ambient, _hasExport, parent) { super( parent, 1 /* Function */ ); this._ambient = _ambient; this._hasExport = _hasExport; this._innerScope = new NonRootScope( this, 1 /* Function */ ); this._exports = void 0; } finish(cb) { return super.end(cb); } end(cb) { this._innerScope.end((variable, key, scope) => { if (scope !== this._innerScope || !variable.exported && (!this._ambient || this._exports !== void 0 && !this._exports.has(key.text))) return cb(variable, key, scope); const namespaceVar = this._variables.get(key.text); if (namespaceVar === void 0) { this._variables.set(key.text, { declarations: variable.declarations.map(mapDeclaration), domain: variable.domain, uses: [...variable.uses] }); } else { outer: for (const declaration of variable.declarations) { for (const existing of namespaceVar.declarations) if (existing.declaration === declaration) continue outer; namespaceVar.declarations.push(mapDeclaration(declaration)); } namespaceVar.domain |= variable.domain; for (const use of variable.uses) { if (namespaceVar.uses.includes(use)) continue; namespaceVar.uses.push(use); } } }); this._applyUses(); this._innerScope = new NonRootScope( this, 1 /* Function */ ); } createOrReuseNamespaceScope(name, exported, ambient, hasExportStatement) { if (!exported && (!this._ambient || this._hasExport)) return this._innerScope.createOrReuseNamespaceScope(name, exported, ambient || this._ambient, hasExportStatement); return super.createOrReuseNamespaceScope(name, exported, ambient || this._ambient, hasExportStatement); } createOrReuseEnumScope(name, exported) { if (!exported && (!this._ambient || this._hasExport)) return this._innerScope.createOrReuseEnumScope(name, exported); return super.createOrReuseEnumScope(name, exported); } addUse(use, source) { if (source !== this._innerScope) return this._innerScope.addUse(use); this._uses.push(use); } refresh(ambient, hasExport) { this._ambient = ambient; this._hasExport = hasExport; } markExported(name, _as) { if (this._exports === void 0) this._exports = /* @__PURE__ */ new Set(); this._exports.add(name.text); } getDestinationScope() { return this._innerScope; } } function getEntityNameParent(name) { let parent = name.parent; while (parent.kind === ts$1.SyntaxKind.QualifiedName) parent = parent.parent; return parent; } class UsageWalker { constructor() { this._result = /* @__PURE__ */ new Map(); } getUsage(sourceFile) { const variableCallback = (variable, key) => { this._result.set(key, variable); }; const isModule = ts$1.isExternalModule(sourceFile); this._scope = new RootScope(sourceFile.isDeclarationFile && isModule && !containsExportStatement(sourceFile), !isModule); const cb = (node2) => { if (util_1.isBlockScopeBoundary(node2)) return continueWithScope(node2, new BlockScope(this._scope.getFunctionScope(), this._scope), handleBlockScope); switch (node2.kind) { case ts$1.SyntaxKind.ClassExpression: return continueWithScope(node2, node2.name !== void 0 ? new ClassExpressionScope(node2.name, this._scope) : new NonRootScope( this._scope, 1 /* Function */ )); case ts$1.SyntaxKind.ClassDeclaration: this._handleDeclaration( node2, true, 4 | 2 /* Type */ ); return continueWithScope(node2, new NonRootScope( this._scope, 1 /* Function */ )); case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: this._handleDeclaration( node2, true, 2 /* Type */ ); return continueWithScope(node2, new NonRootScope( this._scope, 4 /* Type */ )); case ts$1.SyntaxKind.EnumDeclaration: this._handleDeclaration( node2, true, 7 /* Any */ ); return continueWithScope(node2, this._scope.createOrReuseEnumScope(node2.name.text, util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword))); case ts$1.SyntaxKind.ModuleDeclaration: return this._handleModule(node2, continueWithScope); case ts$1.SyntaxKind.MappedType: return continueWithScope(node2, new NonRootScope( this._scope, 4 /* Type */ )); case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.Constructor: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.MethodSignature: case ts$1.SyntaxKind.CallSignature: case ts$1.SyntaxKind.ConstructSignature: case ts$1.SyntaxKind.ConstructorType: case ts$1.SyntaxKind.FunctionType: return this._handleFunctionLikeDeclaration(node2, cb, variableCallback); case ts$1.SyntaxKind.ConditionalType: return this._handleConditionalType(node2, cb, variableCallback); case ts$1.SyntaxKind.VariableDeclarationList: this._handleVariableDeclaration(node2); break; case ts$1.SyntaxKind.Parameter: if (node2.parent.kind !== ts$1.SyntaxKind.IndexSignature && (node2.name.kind !== ts$1.SyntaxKind.Identifier || node2.name.originalKeywordKind !== ts$1.SyntaxKind.ThisKeyword)) this._handleBindingName(node2.name, false, false); break; case ts$1.SyntaxKind.EnumMember: this._scope.addVariable( util_1.getPropertyName(node2.name), node2.name, 1, true, 4 /* Value */ ); break; case ts$1.SyntaxKind.ImportClause: case ts$1.SyntaxKind.ImportSpecifier: case ts$1.SyntaxKind.NamespaceImport: case ts$1.SyntaxKind.ImportEqualsDeclaration: this._handleDeclaration( node2, false, 7 | 8 /* Import */ ); break; case ts$1.SyntaxKind.TypeParameter: this._scope.addVariable( node2.name.text, node2.name, node2.parent.kind === ts$1.SyntaxKind.InferType ? 8 : 7, false, 2 /* Type */ ); break; case ts$1.SyntaxKind.ExportSpecifier: if (node2.propertyName !== void 0) return this._scope.markExported(node2.propertyName, node2.name); return this._scope.markExported(node2.name); case ts$1.SyntaxKind.ExportAssignment: if (node2.expression.kind === ts$1.SyntaxKind.Identifier) return this._scope.markExported(node2.expression); break; case ts$1.SyntaxKind.Identifier: const domain = getUsageDomain(node2); if (domain !== void 0) this._scope.addUse({ domain, location: node2 }); return; } return ts$1.forEachChild(node2, cb); }; const continueWithScope = (node2, scope, next = forEachChild) => { const savedScope = this._scope; this._scope = scope; next(node2); this._scope.end(variableCallback); this._scope = savedScope; }; const handleBlockScope = (node2) => { if (node2.kind === ts$1.SyntaxKind.CatchClause && node2.variableDeclaration !== void 0) this._handleBindingName(node2.variableDeclaration.name, true, false); return ts$1.forEachChild(node2, cb); }; ts$1.forEachChild(sourceFile, cb); this._scope.end(variableCallback); return this._result; function forEachChild(node2) { return ts$1.forEachChild(node2, cb); } } _handleConditionalType(node2, cb, varCb) { const savedScope = this._scope; const scope = this._scope = new ConditionalTypeScope(savedScope); cb(node2.checkType); scope.updateState( 1 /* Extends */ ); cb(node2.extendsType); scope.updateState( 2 /* TrueType */ ); cb(node2.trueType); scope.updateState( 3 /* FalseType */ ); cb(node2.falseType); scope.end(varCb); this._scope = savedScope; } _handleFunctionLikeDeclaration(node2, cb, varCb) { if (node2.decorators !== void 0) node2.decorators.forEach(cb); const savedScope = this._scope; if (node2.kind === ts$1.SyntaxKind.FunctionDeclaration) this._handleDeclaration( node2, false, 4 /* Value */ ); const scope = this._scope = node2.kind === ts$1.SyntaxKind.FunctionExpression && node2.name !== void 0 ? new FunctionExpressionScope(node2.name, savedScope) : new FunctionScope(savedScope); if (node2.name !== void 0) cb(node2.name); if (node2.typeParameters !== void 0) node2.typeParameters.forEach(cb); node2.parameters.forEach(cb); if (node2.type !== void 0) cb(node2.type); if (node2.body !== void 0) { scope.beginBody(); cb(node2.body); } scope.end(varCb); this._scope = savedScope; } _handleModule(node2, next) { if (node2.flags & ts$1.NodeFlags.GlobalAugmentation) return next(node2, this._scope.createOrReuseNamespaceScope("-global", false, true, false)); if (node2.name.kind === ts$1.SyntaxKind.Identifier) { const exported = isNamespaceExported(node2); this._scope.addVariable( node2.name.text, node2.name, 1, exported, 1 | 4 /* Value */ ); const ambient = util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword); return next(node2, this._scope.createOrReuseNamespaceScope(node2.name.text, exported, ambient, ambient && namespaceHasExportStatement(node2))); } return next(node2, this._scope.createOrReuseNamespaceScope(`"${node2.name.text}"`, false, true, namespaceHasExportStatement(node2))); } _handleDeclaration(node2, blockScoped, domain) { if (node2.name !== void 0) this._scope.addVariable(node2.name.text, node2.name, blockScoped ? 3 : 1, util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword), domain); } _handleBindingName(name, blockScoped, exported) { if (name.kind === ts$1.SyntaxKind.Identifier) return this._scope.addVariable( name.text, name, blockScoped ? 3 : 1, exported, 4 /* Value */ ); util_1.forEachDestructuringIdentifier(name, (declaration) => { this._scope.addVariable( declaration.name.text, declaration.name, blockScoped ? 3 : 1, exported, 4 /* Value */ ); }); } _handleVariableDeclaration(declarationList) { const blockScoped = util_1.isBlockScopedVariableDeclarationList(declarationList); const exported = declarationList.parent.kind === ts$1.SyntaxKind.VariableStatement && util_1.hasModifier(declarationList.parent.modifiers, ts$1.SyntaxKind.ExportKeyword); for (const declaration of declarationList.declarations) this._handleBindingName(declaration.name, blockScoped, exported); } } function isNamespaceExported(node2) { return node2.parent.kind === ts$1.SyntaxKind.ModuleDeclaration || util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword); } function namespaceHasExportStatement(ns) { if (ns.body === void 0 || ns.body.kind !== ts$1.SyntaxKind.ModuleBlock) return false; return containsExportStatement(ns.body); } function containsExportStatement(block) { for (const statement of block.statements) if (statement.kind === ts$1.SyntaxKind.ExportDeclaration || statement.kind === ts$1.SyntaxKind.ExportAssignment) return true; return false; } })(usage); return usage; } var controlFlow = {}; var hasRequiredControlFlow; function requireControlFlow() { if (hasRequiredControlFlow) return controlFlow; hasRequiredControlFlow = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.callExpressionAffectsControlFlow = exports.SignatureEffect = exports.getControlFlowEnd = exports.endsControlFlow = void 0; const ts$1 = ts; const node_1 = requireNode(); const util_1 = requireUtil$1(); function endsControlFlow(statement, checker) { return getControlFlowEnd(statement, checker).end; } exports.endsControlFlow = endsControlFlow; const defaultControlFlowEnd = { statements: [], end: false }; function getControlFlowEnd(statement, checker) { return node_1.isBlockLike(statement) ? handleBlock(statement, checker) : getControlFlowEndWorker(statement, checker); } exports.getControlFlowEnd = getControlFlowEnd; function getControlFlowEndWorker(statement, checker) { switch (statement.kind) { case ts$1.SyntaxKind.ReturnStatement: case ts$1.SyntaxKind.ThrowStatement: case ts$1.SyntaxKind.ContinueStatement: case ts$1.SyntaxKind.BreakStatement: return { statements: [statement], end: true }; case ts$1.SyntaxKind.Block: return handleBlock(statement, checker); case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.WhileStatement: return handleForAndWhileStatement(statement, checker); case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.ForInStatement: return handleForInOrOfStatement(statement, checker); case ts$1.SyntaxKind.DoStatement: return matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement); case ts$1.SyntaxKind.IfStatement: return handleIfStatement(statement, checker); case ts$1.SyntaxKind.SwitchStatement: return matchBreakOrContinue(handleSwitchStatement(statement, checker), node_1.isBreakStatement); case ts$1.SyntaxKind.TryStatement: return handleTryStatement(statement, checker); case ts$1.SyntaxKind.LabeledStatement: return matchLabel(getControlFlowEndWorker(statement.statement, checker), statement.label); case ts$1.SyntaxKind.WithStatement: return getControlFlowEndWorker(statement.statement, checker); case ts$1.SyntaxKind.ExpressionStatement: if (checker === void 0) return defaultControlFlowEnd; return handleExpressionStatement(statement, checker); default: return defaultControlFlowEnd; } } function handleBlock(statement, checker) { const result = { statements: [], end: false }; for (const s of statement.statements) { const current = getControlFlowEndWorker(s, checker); result.statements.push(...current.statements); if (current.end) { result.end = true; break; } } return result; } function handleForInOrOfStatement(statement, checker) { const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement); end.end = false; return end; } function handleForAndWhileStatement(statement, checker) { const constantCondition = statement.kind === ts$1.SyntaxKind.WhileStatement ? getConstantCondition(statement.expression) : statement.condition === void 0 || getConstantCondition(statement.condition); if (constantCondition === false) return defaultControlFlowEnd; const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement); if (constantCondition === void 0) end.end = false; return end; } function getConstantCondition(node2) { switch (node2.kind) { case ts$1.SyntaxKind.TrueKeyword: return true; case ts$1.SyntaxKind.FalseKeyword: return false; default: return; } } function handleIfStatement(node2, checker) { switch (getConstantCondition(node2.expression)) { case true: return getControlFlowEndWorker(node2.thenStatement, checker); case false: return node2.elseStatement === void 0 ? defaultControlFlowEnd : getControlFlowEndWorker(node2.elseStatement, checker); } const then = getControlFlowEndWorker(node2.thenStatement, checker); if (node2.elseStatement === void 0) return { statements: then.statements, end: false }; const elze = getControlFlowEndWorker(node2.elseStatement, checker); return { statements: [...then.statements, ...elze.statements], end: then.end && elze.end }; } function handleSwitchStatement(node2, checker) { let hasDefault = false; const result = { statements: [], end: false }; for (const clause of node2.caseBlock.clauses) { if (clause.kind === ts$1.SyntaxKind.DefaultClause) hasDefault = true; const current = handleBlock(clause, checker); result.end = current.end; result.statements.push(...current.statements); } result.end && (result.end = hasDefault || checker !== void 0 && util_1.hasExhaustiveCaseClauses(node2, checker)); return result; } function handleTryStatement(node2, checker) { let finallyResult; if (node2.finallyBlock !== void 0) { finallyResult = handleBlock(node2.finallyBlock, checker); if (finallyResult.end) return finallyResult; } const tryResult = handleBlock(node2.tryBlock, checker); if (node2.catchClause === void 0) return { statements: finallyResult.statements.concat(tryResult.statements), end: tryResult.end }; const catchResult = handleBlock(node2.catchClause.block, checker); return { statements: tryResult.statements.filter((s) => s.kind !== ts$1.SyntaxKind.ThrowStatement && s.kind !== ts$1.SyntaxKind.ExpressionStatement).concat(catchResult.statements, finallyResult === void 0 ? [] : finallyResult.statements), end: tryResult.end && catchResult.end // only ends control flow if try AND catch definitely end control flow }; } function isDottedNameWithExplicitTypeAnnotation(node2, checker) { while (true) { switch (node2.kind) { case ts$1.SyntaxKind.Identifier: { const symbol = checker.getExportSymbolOfSymbol(checker.getSymbolAtLocation(node2)); return isExplicitlyTypedSymbol(util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Alias) ? checker.getAliasedSymbol(symbol) : symbol, checker); } case ts$1.SyntaxKind.ThisKeyword: return isExplicitlyTypedThis(node2); case ts$1.SyntaxKind.SuperKeyword: return true; case ts$1.SyntaxKind.PropertyAccessExpression: if (!isExplicitlyTypedSymbol(checker.getSymbolAtLocation(node2), checker)) return false; case ts$1.SyntaxKind.ParenthesizedExpression: node2 = node2.expression; continue; default: return false; } } } function isExplicitlyTypedSymbol(symbol, checker) { if (symbol === void 0) return false; if (util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Function | ts$1.SymbolFlags.Method | ts$1.SymbolFlags.Class | ts$1.SymbolFlags.ValueModule)) return true; if (!util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Variable | ts$1.SymbolFlags.Property)) return false; if (symbol.valueDeclaration === void 0) return false; if (declarationHasExplicitTypeAnnotation(symbol.valueDeclaration)) return true; return node_1.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.parent.parent.kind === ts$1.SyntaxKind.ForOfStatement && isDottedNameWithExplicitTypeAnnotation(symbol.valueDeclaration.parent.parent.expression, checker); } function declarationHasExplicitTypeAnnotation(node2) { if (ts$1.isJSDocPropertyLikeTag(node2)) return node2.typeExpression !== void 0; return (node_1.isVariableDeclaration(node2) || node_1.isParameterDeclaration(node2) || node_1.isPropertyDeclaration(node2) || node_1.isPropertySignature(node2)) && (util_1.isNodeFlagSet(node2, ts$1.NodeFlags.JavaScriptFile) ? ts$1.getJSDocType(node2) : node2.type) !== void 0; } function isExplicitlyTypedThis(node2) { var _a; do { node2 = node2.parent; if (node_1.isDecorator(node2)) { if (node2.parent.kind === ts$1.SyntaxKind.Parameter && node_1.isClassLikeDeclaration(node2.parent.parent.parent)) { node2 = node2.parent.parent.parent.parent; } else if (node_1.isClassLikeDeclaration(node2.parent.parent)) { node2 = node2.parent.parent.parent; } else if (node_1.isClassLikeDeclaration(node2.parent)) { node2 = node2.parent.parent; } } } while (util_1.isFunctionScopeBoundary(node2) !== 1 || node2.kind === ts$1.SyntaxKind.ArrowFunction); return util_1.isFunctionWithBody(node2) && (util_1.isNodeFlagSet(node2, ts$1.NodeFlags.JavaScriptFile) ? ((_a = ts$1.getJSDocThisTag(node2)) === null || _a === void 0 ? void 0 : _a.typeExpression) !== void 0 : node2.parameters.length !== 0 && util_1.isThisParameter(node2.parameters[0]) && node2.parameters[0].type !== void 0) || node_1.isClassLikeDeclaration(node2.parent); } (function(SignatureEffect) { SignatureEffect[SignatureEffect["Never"] = 1] = "Never"; SignatureEffect[SignatureEffect["Asserts"] = 2] = "Asserts"; })(exports.SignatureEffect || (exports.SignatureEffect = {})); function callExpressionAffectsControlFlow(node2, checker) { var _a, _b, _c; if (!node_1.isExpressionStatement(node2.parent) || ts$1.isOptionalChain(node2) || !isDottedNameWithExplicitTypeAnnotation(node2.expression, checker)) return; const signature = checker.getResolvedSignature(node2); if ((signature === null || signature === void 0 ? void 0 : signature.declaration) === void 0) return; const typeNode = ts$1.isJSDocSignature(signature.declaration) ? (_b = (_a = signature.declaration.type) === null || _a === void 0 ? void 0 : _a.typeExpression) === null || _b === void 0 ? void 0 : _b.type : (_c = signature.declaration.type) !== null && _c !== void 0 ? _c : util_1.isNodeFlagSet(signature.declaration, ts$1.NodeFlags.JavaScriptFile) ? ts$1.getJSDocReturnType(signature.declaration) : void 0; if (typeNode === void 0) return; if (node_1.isTypePredicateNode(typeNode) && typeNode.assertsModifier !== void 0) return 2; return util_1.isTypeFlagSet(checker.getTypeFromTypeNode(typeNode), ts$1.TypeFlags.Never) ? 1 : void 0; } exports.callExpressionAffectsControlFlow = callExpressionAffectsControlFlow; function handleExpressionStatement(node2, checker) { if (!node_1.isCallExpression(node2.expression)) return defaultControlFlowEnd; switch (callExpressionAffectsControlFlow(node2.expression, checker)) { case 2: return { statements: [node2], end: false }; case 1: return { statements: [node2], end: true }; case void 0: return defaultControlFlowEnd; } } function matchBreakOrContinue(current, pred) { const result = { statements: [], end: current.end }; for (const statement of current.statements) { if (pred(statement) && statement.label === void 0) { result.end = false; continue; } result.statements.push(statement); } return result; } function matchLabel(current, label) { const result = { statements: [], end: current.end }; const labelText = label.text; for (const statement of current.statements) { switch (statement.kind) { case ts$1.SyntaxKind.BreakStatement: case ts$1.SyntaxKind.ContinueStatement: if (statement.label !== void 0 && statement.label.text === labelText) { result.end = false; continue; } } result.statements.push(statement); } return result; } })(controlFlow); return controlFlow; } var convertAst = {}; var hasRequiredConvertAst; function requireConvertAst() { if (hasRequiredConvertAst) return convertAst; hasRequiredConvertAst = 1; Object.defineProperty(convertAst, "__esModule", { value: true }); convertAst.convertAst = void 0; const ts$1 = ts; const util_1 = requireUtil$1(); function convertAst$1(sourceFile) { const wrapped = { node: sourceFile, parent: void 0, kind: ts$1.SyntaxKind.SourceFile, children: [], next: void 0, skip: void 0 }; const flat = []; let current = wrapped; function collectChildren(node2) { current.children.push({ node: node2, parent: current, kind: node2.kind, children: [], next: void 0, skip: void 0 }); } const stack = []; while (true) { if (current.children.length === 0) { ts$1.forEachChild(current.node, collectChildren); if (current.children.length === 0) { current = current.parent; } else { const firstChild = current.children[0]; current.next = firstChild; flat.push(firstChild.node); if (util_1.isNodeKind(firstChild.kind)) current = firstChild; stack.push(1); } } else { const index = stack[stack.length - 1]; if (index < current.children.length) { const currentChild = current.children[index]; flat.push(currentChild.node); let previous = current.children[index - 1]; while (previous.children.length !== 0) { previous.skip = currentChild; previous = previous.children[previous.children.length - 1]; } previous.skip = previous.next = currentChild; ++stack[stack.length - 1]; if (util_1.isNodeKind(currentChild.kind)) current = currentChild; } else { if (stack.length === 1) break; stack.pop(); current = current.parent; } } } return { wrapped, flat }; } convertAst.convertAst = convertAst$1; return convertAst; } var hasRequiredUtil; function requireUtil() { if (hasRequiredUtil) return util$2; hasRequiredUtil = 1; (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireUtil$1(), exports); tslib_1.__exportStar(requireUsage(), exports); tslib_1.__exportStar(requireControlFlow(), exports); tslib_1.__exportStar(requireType(), exports); tslib_1.__exportStar(requireConvertAst(), exports); })(util$2); return util$2; } (function(exports) { Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireTypeguard(), exports); tslib_1.__exportStar(requireUtil(), exports); })(tsutils); const glslHeader = "uint shadeup_up_swizzle_x_uint(uint n) {\r\n return n;\r\n}\r\n\r\nuvec2 shadeup_up_swizzle_xx_uint(uint n) {\r\n return uvec2(n, n);\r\n}\r\n\r\nuvec3 shadeup_up_swizzle_xxx_uint(uint n) {\r\n return uvec3(n, n, n);\r\n}\r\n\r\nuvec4 shadeup_up_swizzle_xxxx_uint(uint n) {\r\n return uvec4(n, n, n, n);\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xy_uint(uint n) {\r\n return uvec2(n, n);\r\n}\r\n\r\nuvec3 shadeup_up_swizzle_xyz_uint(uint n) {\r\n return uvec3(n, n, n);\r\n}\r\n\r\nuvec4 shadeup_up_swizzle_xyzw_uint(uint n) {\r\n return uvec4(n, n, n, n);\r\n}\r\n\r\nint shadeup_up_swizzle_x_int(int n) {\r\n return n;\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xx_int(int n) {\r\n return ivec2(n, n);\r\n}\r\n\r\nivec3 shadeup_up_swizzle_xxx_int(int n) {\r\n return ivec3(n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xxxx_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xy_int(int n) {\r\n return ivec2(n, n);\r\n}\r\n\r\nivec3 shadeup_up_swizzle_xyz_int(int n) {\r\n return ivec3(n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xyzw_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xxxx_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nfloat shadeup_up_swizzle_x_float(float n) {\r\n return n;\r\n}\r\n\r\nvec2 shadeup_up_swizzle_xx_float(float n) {\r\n return vec2(n, n);\r\n}\r\n\r\nvec3 shadeup_up_swizzle_xxx_float(float n) {\r\n return vec3(n, n, n);\r\n}\r\n\r\nvec4 shadeup_up_swizzle_xxxx_float(float n) {\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nvec2 shadeup_up_swizzle_xy_float(float n) {\r\n return vec2(n, n);\r\n}\r\n\r\nvec3 shadeup_up_swizzle_xyz_float(float n) {\r\n return vec3(n, n, n);\r\n}\r\n\r\nvec4 shadeup_up_swizzle_xyzw_float(float n) {\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nmat4 matrix_inversefloat4x4(mat4 m) {\r\n return inverse(m);\r\n}\r\n\r\nmat3 matrix_inversefloat3x3(mat3 m) {\r\n return inverse(m);\r\n}\r\n\r\nmat2 matrix_inversefloat2x2(mat2 m) {\r\n return inverse(m);\r\n}\r\n\r\nfloat bilerp_float(float a, float b, float c, float d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec2 bilerp_float2(vec2 a, vec2 b, vec2 c, vec2 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec3 bilerp_float3(vec3 a, vec3 b, vec3 c, vec3 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec4 bilerp_float4(vec4 a, vec4 b, vec4 c, vec4 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nmat2 bilerp_float2x2(mat2 a, mat2 b, mat2 c, mat2 d, float u, float v) {\r\n return mat2(bilerp_float2(a[0], b[0], c[0], d[0], u, v), bilerp_float2(a[1], b[1], c[1], d[1], u, v));\r\n}\r\n\r\nmat3 bilerp_float3x3(mat3 a, mat3 b, mat3 c, mat3 d, float u, float v) {\r\n return mat3(bilerp_float3(a[0], b[0], c[0], d[0], u, v), bilerp_float3(a[1], b[1], c[1], d[1], u, v), bilerp_float3(a[2], b[2], c[2], d[2], u, v));\r\n}\r\n\r\nmat4 bilerp_float4x4(mat4 a, mat4 b, mat4 c, mat4 d, float u, float v) {\r\n return mat4(bilerp_float4(a[0], b[0], c[0], d[0], u, v), bilerp_float4(a[1], b[1], c[1], d[1], u, v), bilerp_float4(a[2], b[2], c[2], d[2], u, v), bilerp_float4(a[3], b[3], c[3], d[3], u, v));\r\n}"; let { factory: factory$1, isIdentifier: isIdentifier$1 } = ts; const TYPE_BLACKLIST$1 = [ "never", "object", "symbol", "bigint", "undefined", "null", "map", "string" ]; const RESERVED_WORDS$1 = ["attribute", "sample", "varying", "uniform", "layout"]; class GLSLCompilationError extends Error { constructor(message, node2) { super(message); this.message = message; this.node = node2; this.context = node2; } } function generateDefaultForType$2(checker, _type_node) { let _type = checker.getTypeFromTypeNode(_type_node); let name = (_type.aliasSymbol || _type.getSymbol())?.escapedName.toString(); switch (name) { case "int": return "int(0)"; case "uint": return "uint(0)"; case "uint8": return "uint(0)"; case "float": return "float(0.0)"; case "float2": return "vec2(0.0, 0.0)"; case "float3": return "vec3(0.0, 0.0, 0.0)"; case "float4": return "vec4(0.0, 0.0, 0.0, 0.0)"; case "int2": return "ivec2(0, 0)"; case "int3": return "ivec3(0, 0, 0)"; case "int4": return "ivec4(0, 0, 0, 0)"; case "uint2": return "uvec2(0u, 0u)"; case "uint3": return "uvec3(0u, 0u, 0u)"; case "uint4": return "uvec4(0u, 0u, 0u, 0u)"; case "float2x2": return "mat2(0.0, 0.0, 0.0, 0.0)"; case "float3x3": return "mat3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "float4x4": return "mat4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "bool": return "false"; default: let decl = _type.getSymbol()?.getDeclarations(); if (ts.isTupleTypeNode(_type_node)) { let len = _type_node.elements.length; let args = []; let rootNode = _type_node.elements[0]; if (rootNode) { for (let i = 0; i < len; i++) { args.push(generateDefaultForType$2(checker, _type_node.elements[i])); } let rootType = checker.getTypeFromTypeNode(rootNode); return translateType$1(checker, rootType) + `[${len}] {` + args.join(", ") + "}"; } else { return "0"; } } if (decl && decl.length > 0) { let d = decl[0]; let structProps = []; if (ts.isClassDeclaration(d)) { let symd = _type.getSymbol(); symd?.members?.forEach((v, k) => { let decl2 = v.valueDeclaration; if (decl2 && ts.isPropertyDeclaration(decl2)) { structProps.push([k?.toString() ?? "", decl2.type]); } }); let sortedPropsByKey = structProps.sort((a, b) => { return a[0].localeCompare(b[0]); }); let args = sortedPropsByKey.map((p) => { return "/* " + p[0] + ": */ " + generateDefaultForType$2(checker, p[1]) + "\n"; }); return "_make_struct_" + resolveStructName$1(d) + "(\n" + args.join(", ") + "\n)"; } else { return "0"; } } else { return "0"; } } } function getTypeFallback$2(checker, t) { let n = (t.aliasSymbol || t.getSymbol())?.escapedName; if (!n && t.intrinsicName) n = t.intrinsicName; if (typeof n !== "string") { let props = t.getApparentProperties(); if (props.length > 0) { for (let p of props) { if (p.escapedName.toString() === "_opaque_int") return "int"; if (p.escapedName.toString() === "_opaque_float") return "float"; if (p.escapedName.toString() === "_opaque_uint") return "uint"; } } let btype = t.getBaseTypes(); if (btype && btype.length > 0) { for (let b of btype) { let tn = getTypeFallback$2(checker, b); if (tn) return tn; } return null; } } else { return n; } } function followTypeReferences$1(t) { if (t.flags & ts.TypeFlags.Object && t.objectFlags & ts.ObjectFlags.Reference) { if (t.target === t) { return t; } return followTypeReferences$1(t.target); } else { return t; } } function translateType$1(checker, t, templateFormat = false) { let n = getTypeFallback$2(checker, t); let originalType = t; if (n === void 0) { t = followTypeReferences$1(t); } if (templateFormat) { let name = n?.toString() ?? "unknown"; if (name === "Array" || name === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); return { type: "array", element: translateType$1(checker, args[0], true) }; } if (name == "boolean" || name == "false" || name == "true") name = "bool"; if (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint") || name == "bool" || name == "texture2d" || name == "atomic") return { type: "primitive", name }; let symbol = t.aliasSymbol || t.getSymbol(); if (symbol && symbol.declarations && symbol.declarations.length > 0) { if (ts.isClassDeclaration(symbol.declarations[0])) { let fields = {}; let decl = symbol.declarations[0]; for (let member of decl.members) { if (ts.isPropertyDeclaration(member)) { let name2 = member.name.getText(); let type2 = checker.getTypeFromTypeNode(member.type); fields[name2] = translateType$1(checker, type2, true); } } return { type: "struct", name: resolveStructName$1(decl), fields }; } else { return { type: "unknown" }; } } } else { if (n === "Array" || n === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let toStringed = checker.typeToString(typeRef); let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); let translated = translateType$1(checker, args[0]); if (toStringed.endsWith("[]")) { return translated + "[]"; } else { let staticSize = 0; if (tsutils.isTupleType(t)) { staticSize = t.fixedLength; } return translated + "[" + staticSize + "]"; } } if (n === "texture2d") return `sampler2D`; if (n == "atomic") { let args = t.typeArguments || checker.getTypeArguments(t); let translated = translateType$1(checker, args[0]); return `atomic_${translated}`; } if (n === "bool") return "bool"; if (n === "boolean") return "bool"; if (n === "float") return "float"; if (n === "float2") return "vec2"; if (n === "float3") return "vec3"; if (n === "float4") return "vec4"; if (n === "int") return "int"; if (n === "int2") return "ivec2"; if (n === "int3") return "ivec3"; if (n === "int4") return "ivec4"; if (n === "uint") return "uint"; if (n === "uint8") return "uint"; if (n === "uint2") return "uvec2"; if (n === "uint3") return "uvec3"; if (n === "uint4") return "uvec4"; if (n === "float2x2") return "mat2"; if (n === "float3x3") return "mat3"; if (n === "float4x4") return "mat4"; if (n === "void") return "void"; if (n === "error") return "void"; if (t.isUnion()) { let types2 = t.types.map((t2) => translateType$1(checker, t2)); for (let sub of types2) { if (sub && sub !== "void" && sub !== "undefined") return sub; } } let symbol = t.aliasSymbol || t.getSymbol(); if (symbol && symbol.declarations && symbol.declarations.length > 0) { if (ts.isClassDeclaration(symbol.declarations[0])) { return resolveStructName$1(symbol.declarations[0]); } else { return n?.toString() ?? "void"; } } else { return n?.toString() ?? "void"; } } } function isTypeNameVector$1(name) { if (name.startsWith("float") || name.startsWith("int")) { if (name.endsWith("2") || name.endsWith("3") || name.endsWith("4")) { return true; } } return false; } function getTypeNameVectorElementType$1(name) { if (name == "float") { return ["float", 1]; } if (name == "int") { return ["int", 1]; } if (name == "uint") { return ["uint", 1]; } if (name.startsWith("float")) { return ["float", parseInt(name.substring(5))]; } if (name.startsWith("int")) { return ["int", parseInt(name.substring(3))]; } if (name.startsWith("uint")) { return ["uint", parseInt(name.substring(4))]; } if (name.startsWith("vec")) { return ["float", parseInt(name.substring(3))]; } if (name.startsWith("ivec")) { return ["int", parseInt(name.substring(4))]; } if (name.startsWith("uvec")) { return ["uint", parseInt(name.substring(4))]; } return ["", 0]; } function isTranslatedTypeNameVectorOrScalar$1(name) { if (name == "float" || name == "int" || name == "uint") return true; if (name.startsWith("vec") || name.startsWith("ivec") || name.startsWith("uvec")) { if (name.endsWith("2") || name.endsWith("3") || name.endsWith("4")) { return true; } return true; } return false; } function isVector$1(checker, t) { let name = getTypeFallback$2(checker, t); if (name) { return isTypeNameVector$1(name); } return false; } function getVectorElementType$1(checker, t) { let name = getTypeFallback$2(checker, t); if (name) { return getTypeNameVectorElementType$1(name); } return ["", 0]; } function isNumeric$1(checker, t) { let name = getTypeFallback$2(checker, t); if (name && (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint"))) { return true; } return false; } function escapeIdentifier$1(id) { if (RESERVED_WORDS$1.includes(id)) { return "_" + id; } return id.replaceAll("___", "_ii_").replaceAll("__", "_i_"); } function getVectorMask$1(num) { let outMask = ""; let comps = ["x", "y", "z", "w"]; for (let i = 0; i < num; i++) { outMask += comps[i]; } return outMask; } function isGLSLType$1(name) { return name.startsWith("vec") || name.startsWith("mat") || name.startsWith("sampler") || name.startsWith("texture") || name.startsWith("isampler") || name.startsWith("usampler") || name.startsWith("uvec") || name.startsWith("ivec") || name == "bool" || name == "float" || name == "int" || name == "uint" || name == "uint8" || name == "void"; } function autoCastNumeric$1(value, input, expected) { let inputType = getTypeNameVectorElementType$1(input); let expectedType = getTypeNameVectorElementType$1(expected); if (inputType[0] != expectedType[0]) { if (expectedType[1] == 1) { return new SourceNode(value.startIndex, value.endIndex, [`${expectedType[0]}(`, value, `)`]); } else { return new SourceNode(value.startIndex, value.endIndex, [`${expectedType[0]}(`, value, `)`]); } } return value; } function convertConciseBodyToBlock$1(body) { if (ts.isBlock(body)) { return body; } else { return ts.factory.createBlock([ts.factory.createReturnStatement(body)]); } } function compile$2(ctx, ast, originalMapping) { function c2(ast2) { if (!ast2) { return s([]); } return compile$2(ctx, ast2); } function cplain(ast2) { if (!ast2) { return s([]); } return compile$2( { checker: ctx.checker, parentFunction: ctx.parentFunction }, ast2 ); } function s(c22) { if (originalMapping) { let reverseMapped = lookupIndexMappingRange(originalMapping, ast.getStart(), ast.getEnd()); return new SourceNode(reverseMapped.start, reverseMapped.end, c22); } else { return new SourceNode(0, 0, c22); } } function join(c22, sep) { return c22.reduce((acc, cur) => { if (acc.length === 0) { return [cur]; } return [...acc, sep, cur]; }, []); } function children() { return ast.getChildren().map((child) => c2(child)); } function autoCastParameter(callExpr, argIndex) { let signature = ctx.checker.getResolvedSignature(callExpr); let params = signature.getParameters(); let param = params[argIndex]; let paramType = ctx.checker.getTypeOfSymbolAtLocation(param, callExpr); let paramTypeString = translateType$1(ctx.checker, paramType); let arg = callExpr.arguments[argIndex]; let argType = ctx.checker.getTypeAtLocation(arg); let argTypeString = translateType$1(ctx.checker, argType); if (paramTypeString !== argTypeString) { return autoCastNumeric$1(c2(arg), argTypeString, paramTypeString); } return s([c2(arg)]); } let prefixFunctions = []; if (ctx.composed) { if (ts.isMethodDeclaration(ast) || ts.isFunctionDeclaration(ast)) { for (let [i, arg] of ctx.composed.arguments.entries()) { if (ts.isArrowFunction(arg)) { let paramFromIndex = ast.parameters[i]; let name = paramFromIndex.name.getText() + "_composed_" + arg.pos + "_arg_" + i; let signature = ctx.checker.getSignatureFromDeclaration(arg); let returnType = signature.getReturnType(); let vars = getClosureVars$1(ctx.checker, arg); let vvv = vars.map( (p) => s([ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(p.declarations[0])), " ", p.escapedName ]) ); let joins = join([...arg.parameters.map((p) => cplain(p)), ...vvv], ", "); prefixFunctions.push( s([ translateType$1(ctx.checker, returnType), " ", name, "(", ...joins, ")", " {\n", ...convertConciseBodyToBlock$1(arg.body).statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]) ); } } } } switch (ast.kind) { case ts.SyntaxKind.FirstPunctuation: return s([ast.getText()]); case ts.SyntaxKind.SyntaxList: return s(children()); case ts.SyntaxKind.SourceFile: return s(children()); case ts.SyntaxKind.BreakStatement: return s(["break;"]); case ts.SyntaxKind.ContinueStatement: return s(["continue;"]); case ts.SyntaxKind.MethodDeclaration: let fnDeclar = ast; let fnName = resolveFunctionName$1(fnDeclar); if (ctx.composed) { fnName = fnName + "_composed_" + ctx.composed.pos; } let isStatic = false; let signature = ctx.checker.getSignatureFromDeclaration(fnDeclar); if (ts.canHaveModifiers(fnDeclar)) { let mods = ts.getModifiers(fnDeclar); if (mods) { if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) { isStatic = true; } } } let returnType = signature.getReturnType(); return s([ ...prefixFunctions, translateType$1(ctx.checker, returnType), " ", fnName, "(", , ...join( [ ...isStatic ? [] : [ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(fnDeclar.parent)) + " _this" ], ...fnDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map((p) => c2(p)) ], ", " ), ")", " {\n", ...fnDeclar.body?.statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]); case ts.SyntaxKind.FunctionDeclaration: let mthdDeclar = ast; let mthdsignature = ctx.checker.getSignatureFromDeclaration(mthdDeclar); let mthdreturnType = mthdsignature.getReturnType(); let mthdName = resolveFunctionName$1(mthdDeclar); if (ctx.composed) { mthdName = mthdName + "_composed_" + ctx.composed.pos; } return s([ ...prefixFunctions, translateType$1(ctx.checker, mthdreturnType), " ", mthdName, "(", ...join( mthdDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map((p) => c2(p)), ", " ), ")", " {\n", ...mthdDeclar.body?.statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]); case ts.SyntaxKind.ReturnStatement: let ret = ast; if (!ctx.parentFunction) { if (ret.expression) { return s(["return ", c2(ret.expression), ";\n"]); } else { return s(["return;\n"]); } } else { let expectedReturnType = ctx.checker.getSignatureFromDeclaration(ctx.parentFunction).getReturnType(); let actualReturnType = ctx.checker.getTypeAtLocation(ret.expression); if (ret.expression) { let sss = s([ "return ", autoCastNumeric$1( c2(ret.expression), translateType$1(ctx.checker, actualReturnType), translateType$1(ctx.checker, expectedReturnType) ), ";\n" ]); return sss; } else { return s(["return;\n"]); } } case ts.SyntaxKind.AsExpression: let asExpr = ast; return c2(asExpr.expression); case ts.SyntaxKind.Parameter: let param = ast; if (ctx.composed) { let indexOf2 = param.parent.parameters.indexOf(param); let expr2 = ctx.composed.arguments[indexOf2]; if (expr2) { if (ts.isArrowFunction(expr2)) { let vars = getClosureVars$1(ctx.checker, expr2.body); let closureVars = vars.map((v) => { return s([ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(v.valueDeclaration)), " ", v.name ]); }); return s(join(closureVars, ", ")); } } } return s([ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(param)), " ", escapeIdentifier$1(param.name.getText()) ]); case ts.SyntaxKind.ArrowFunction: let arrow = ast; let body = convertConciseBodyToBlock$1(arrow.body); return s([ "\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/\nvoid main() {\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/\n", ...body.statements.map((s2) => c2(s2)), "\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/\n}\n" ]); case ts.SyntaxKind.VariableStatement: let varStatement = ast; return s([ ...join( varStatement.declarationList.declarations.map((d) => c2(d)), ", " ), ";\n" ]); case ts.SyntaxKind.VariableDeclaration: let varDecl = ast; let type2 = ctx.checker.getTypeAtLocation(varDecl); return s([ translateType$1(ctx.checker, type2), " ", varDecl.name.getText(), " = ", c2(varDecl.initializer) ]); case ts.SyntaxKind.CallExpression: let call = ast; let exprSmybol = ctx.checker.getSymbolAtLocation(call.expression); if (call.expression.getText() == "Math.random") { return s(["0.0"]); } if (!exprSmybol) { return s(["/* TODO: Unknown symbol */"]); } if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = ctx.checker.getAliasedSymbol(exprSmybol); } let symName = exprSmybol?.getName() ?? call.expression.getText(); if (symName == "__index") { if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType$1( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); let returnType2 = ctx.checker.getTypeAtLocation(call); let vecOut = getVectorElementType$1(ctx.checker, returnType2); let outMask = getVectorMask$1(vecOut[1]); if (innerType == "sampler2D") { return s([ "texelFetch(", c2(call.expression.expression), ", ivec2(", c2(call.arguments[0]), "), 0)." + outMask ]); } } return s([c2(call.expression), "[", c2(call.arguments[0]), "]"]); } else if (symName == "len") { let expr2 = call.expression; if (ts.isPropertyAccessExpression(expr2)) { let left = expr2.expression; return s([c2(left), "_size"]); } } else if (symName == "min" || symName == "max") { if (call.arguments.length > 2) { let args2 = call.arguments.map((a) => c2(a)); while (args2.length > 2) { let left = args2.shift(); let right = args2.shift(); args2.unshift(s([symName, "(", left, ",", right, ")"])); } return s([symName, "(", ...join(args2, ","), ")"]); } } else if (symName == "sample") { if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType$1( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); if (innerType == "sampler2D") { return s([ "texture(", c2(call.expression.expression), ", vec2(", c2(call.arguments[0]), "))" ]); } } } else if (symName == "__index_assign") { return s([ c2(call.expression.expression), "[", c2(call.arguments[0]), "] = ", autoCastParameter(call, 1) ]); } else if (symName == "rand" && call.arguments.length == 0 && call.expression.getText() == "rand") { throw new GLSLCompilationError( "rand() in shaders needs to be seeded, use rand(seed) instead", call ); } if (exprSmybol?.getName() == "makeVector" && exprSmybol.valueDeclaration) { if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) { let exprSig2 = ctx.checker.getResolvedSignature(call); if (exprSig2) { return s([ translateType$1(ctx.checker, ctx.checker.getReturnTypeOfSignature(exprSig2)), "(", ...join( call.arguments.map((a) => c2(a)), ", " ), ")" ]); } } } if (exprSmybol?.getName() == "swizzle" && exprSmybol.valueDeclaration) { if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) { ctx.checker.getSignatureFromDeclaration(exprSmybol.valueDeclaration); let arg = call.arguments[0]; let arg2 = call.arguments[1]; let propAccess = ""; if (ts.isStringLiteral(arg2)) { propAccess = arg2.text; } let argType = ctx.checker.getTypeAtLocation(arg); if (isVector$1(ctx.checker, argType)) { return s([c2(arg), ".", propAccess]); } else if (isNumeric$1(ctx.checker, argType)) { let numericType = translateType$1(ctx.checker, argType); return s([`shadeup_up_swizzle_${propAccess}_${numericType}(`, c2(arg), ")"]); } else { return s([c2(arg), ".", propAccess]); } } } if (isTypeNameVector$1(exprSmybol?.getName() ?? "")) { return s([ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(call.expression)), "(", ...join(call.arguments.length == 0 ? [s(["0"])] : call.arguments.map((a) => c2(a)), ", "), ")" ]); } let funcName = c2(call.expression); let callArgs = []; let preArgs = []; let exprSig = ctx.checker.getResolvedSignature(call); let exprDeclar = exprSig.getDeclaration(); if (exprDeclar) { if (ts.isMethodDeclaration(exprDeclar)) { let isStatic2 = false; if (ts.canHaveModifiers(exprDeclar)) { let mods = ts.getModifiers(exprDeclar); if (mods) { if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) { isStatic2 = true; } } } if (!isStatic2) { if (ts.isPropertyAccessExpression(call.expression)) { preArgs.push(c2(call.expression.expression)); } } } } exprSmybol.getName() + "("; for (let [i, arg] of call.arguments.entries()) { let argStr = c2(arg); if (exprSig) { let p = exprSig.getTypeParameterAtPosition(i); if (p) { let translatedBase = translateType$1(ctx.checker, p); let translatedPass = translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(arg)); if (isTranslatedTypeNameVectorOrScalar$1(translatedPass)) { if (translatedBase != translatedPass && isGLSLType$1(translatedBase)) { argStr = s([`${translatedBase}(`, argStr, `)`]); } } } else { translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(arg)); } } if (ts.isArrowFunction(arg)) { let arrow2 = arg; let vars = getClosureVars$1(ctx.checker, arrow2.body); if (vars.length > 0) callArgs.push(vars.map((v) => v.escapedName).join(", ")); } else { callArgs.push(argStr); } } if (exprSmybol) { let signature2 = ctx.checker.getResolvedSignature(call); let mapping = findRealSignatureMappingToGLSL(ctx.checker, signature2) ?? findSignatureMappingToGLSL(ctx.checker, exprSmybol); if (mapping !== null) { if (mapping.startsWith("!")) { let minType = ""; let noOp = false; for (let arg of call.arguments) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeName = translateType$1(ctx.checker, argType); if (!(argTypeName == "float" || argTypeName.startsWith("vec") || argTypeName == "int" || argTypeName.startsWith("ivec") || argTypeName == "uint" || argTypeName.startsWith("uvec"))) { noOp = true; } if (minType == "") { if (argTypeName == "float" || argTypeName.startsWith("vec")) { minType = "float"; } else if (argTypeName == "int" || argTypeName.startsWith("ivec")) { minType = "int"; } else if (argTypeName == "uint" || minType.startsWith("uvec")) { minType = "uint"; } } else if (argTypeName == "float" || minType.startsWith("vec")) { minType = "float"; } } if (!noOp) { for (let i = 0; i < callArgs.length; i++) { let arg = call.arguments[i]; let argType = ctx.checker.getTypeAtLocation(arg); let argTypeName = translateType$1(ctx.checker, argType); let argTypeStripped = ""; if (argTypeName == "float" || argTypeName.startsWith("vec")) { argTypeStripped = "float"; } else if (argTypeName == "int" || argTypeName.startsWith("ivec")) { argTypeStripped = "int"; } else if (argTypeName == "uint" || argTypeName.startsWith("uvec")) { argTypeStripped = "uint"; } if (argTypeStripped != minType) { if (argTypeName.startsWith("float") || argTypeName.startsWith("int")) { callArgs[i] = s([`${minType}(`, callArgs[i], `)`]); } else if (argTypeName.startsWith("vec") || argTypeName.startsWith("ivec")) { let len = argTypeName.match(/\d+/)?.[0]; if (len === void 0) { throw new Error("Invalid type"); } callArgs[i] = s([ `${minType == "float" ? "vec" : "ivec"}${len}(`, callArgs[i], `)` ]); } else ; } } } let template = mapping.slice(1); let outs = []; let argCounter = 0; let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration()); for (let i = 0; i < callArgs.length; i++) { let paramType = ctx.checker.getTypeAtLocation( sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0] ); template = template.replace( "`" + argCounter + "`", ctx.checker.typeToString(paramType) ); argCounter++; } let result = template.split("$"); for (let r of result) { if (/^\d+$/.test(r)) { outs.push(callArgs[parseInt(r)]); } else if (r == "self") { if (call.expression.kind == ts.SyntaxKind.PropertyAccessExpression) { let propAccess = call.expression; outs.push(c2(propAccess.getChildAt(0))); } else { outs.push(c2(call.expression)); } } else { outs.push(r); } } if (outs.includes(" % ")) { if (call.arguments.length == 2) { let first = getVectorElementType$1( ctx.checker, ctx.checker.getTypeAtLocation(call.arguments[0]) ); let last = getVectorElementType$1( ctx.checker, ctx.checker.getTypeAtLocation(call.arguments[1]) ); if (first[1] != last[1] && last[1] == 1) { getVectorMask$1(first[1]); if (first[0] == "float" || last[0] == "float") { outs = [`mod(`, outs[1], ", ", outs[3], ")"]; } } } } return s(outs); } else if (mapping.startsWith("#")) { let typeName = ""; if (call.arguments.length > 0) { let firstArg = call.arguments[0]; let firstArgType = ctx.checker.getTypeAtLocation(firstArg); typeName = ctx.checker.typeToString(firstArgType); } return s([ new SourceNode(call.expression.getStart(), call.expression.getEnd(), [ mapping.substring(1) + typeName ]), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } else { return s([ new SourceNode(call.expression.getStart(), call.expression.getEnd(), [mapping]), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } if (exprSmybol.declarations[0].parent) { let param2 = exprSmybol.declarations[0]; if (ts.isParameter(param2)) ; } let funcDeclar = exprSmybol.valueDeclaration; if (exprSmybol.declarations[0].parent) { let param2 = exprSmybol.declarations[0]; if (ts.isParameter(param2)) { let indexOf2 = param2.parent.parameters.indexOf(param2); let additionalArgs = []; if (ctx.composed) { let realAnonymousFunc = ctx.composed.arguments[indexOf2]; if (ts.isArrowFunction(realAnonymousFunc)) { let vars = getClosureVars$1(ctx.checker, realAnonymousFunc.body); additionalArgs = vars.map((v) => v.escapedName); callArgs.push(...additionalArgs); return s([ funcName, "_composed_", realAnonymousFunc.pos.toString(), "_arg_", indexOf2.toString(), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } } } if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { funcName = new SourceNode( call.expression.getStart(), call.expression.getEnd(), resolveFunctionName$1(funcDeclar) ); let parentDeclar = closest(ast, (n2) => ts.isFunctionDeclaration(n2)); if (parentDeclar && ts.isFunctionDeclaration(parentDeclar)) ; if (isComposedFunction$1(ctx.checker, funcDeclar)) { return s([ funcName, "_composed_", call.pos.toString(), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } } return s([funcName, "(", ...join([...preArgs, ...callArgs], ", "), ")"]); case ts.SyntaxKind.NewExpression: let newExpr = ast; let newExprSymbol = ctx.checker.getSymbolAtLocation(newExpr.expression); let args = []; if (newExpr.arguments?.length == 1 && ts.isObjectLiteralExpression(newExpr.arguments[0])) { let object = newExpr.arguments[0]; let props = object.properties; let sortedPropsByKey = []; let structProps = []; newExprSymbol?.members?.forEach((v, k) => { let decl2 = v.valueDeclaration; if (decl2 && ts.isPropertyDeclaration(decl2)) { structProps.push([k?.toString() ?? "", decl2.type]); } }); sortedPropsByKey = structProps.sort((a, b) => { return a[0].localeCompare(b[0]); }); args = [ ...sortedPropsByKey.map((p) => { let prop2 = props.find((p2) => { if (ts.isPropertyAssignment(p2)) { return p2.name.getText() == p[0]; } else if (ts.isShorthandPropertyAssignment(p2)) { return p2.name.getText() == p[0]; } else { return false; } }); if (prop2) { if (ts.isPropertyAssignment(prop2)) { return s(["/* ", p[0], ": */ ", c2(prop2.initializer), "\n"]); } else if (ts.isShorthandPropertyAssignment(prop2)) { return s(["/* ", p[0], ": */ ", c2(prop2.name), "\n"]); } else { return s(["/* ", c2(prop2), ": */ ", "\n"]); } } else { return s(["/* ", p[0], ": */ ", generateDefaultForType$2(ctx.checker, p[1]), "\n"]); } }) ]; } let decl = ctx.checker.getTypeAtLocation(newExpr.expression).getSymbol()?.getDeclarations(); if (decl && ts.isClassDeclaration(decl[0])) { return s(["_make_struct_", resolveStructName$1(decl[0]), "(\n", ...join(args, ", "), "\n)"]); } else { return s(["/*", ...join(args, ", "), "*/"]); } case ts.SyntaxKind.ExpressionStatement: let expr = ast; return s([c2(expr.expression), ";\n"]); case ts.SyntaxKind.ObjectLiteralExpression: let obj = ast; return s([ "{", ...join( obj.properties.map((p) => { if (ts.isPropertyAssignment(p)) { return s([c2(p.name), ": ", c2(p.initializer)]); } else if (ts.isShorthandPropertyAssignment(p)) { return s([c2(p.name)]); } else { return s(["/*", c2(p), "*/"]); } }), ", " ), "}" ]); case ts.SyntaxKind.ConditionalExpression: let cond = ast; return s([c2(cond.condition), " ? ", c2(cond.whenTrue), " : ", c2(cond.whenFalse)]); case ts.SyntaxKind.Identifier: let id = ast; if (ts.isIdentifier(id)) { let sym = ctx.checker.getSymbolAtLocation(id); if (sym && sym.flags & ts.SymbolFlags.Alias) { sym = ctx.checker.getAliasedSymbol(sym); } if (sym?.declarations?.length == 1) { let decl2 = sym.declarations[0]; if (isUniformable$1(ctx.checker, decl2)) { if (isVariableDeclarationValue$1(ctx.checker, decl2)) { if (!isInSameScope$1(decl2, ast)) { if (!isInShader$2(decl2)) { if (ts.isBinaryExpression(ast.parent)) { if (ast.parent.left == ast) { throw new GLSLCompilationError( `Cannot assign to variable '${id.text.toString()}' because it is not declared in the shader`, ast ); } } let isGlobalVar = isRootNode$1(decl2); let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${id.text.toString()}`; return s([glslVarName]); } else { return s([escapeIdentifier$1(id.text.toString())]); } } } } } return s([escapeIdentifier$1(id.text.toString())]); } else { return c2(id.expression); } case ts.SyntaxKind.PropertyAccessExpression: let prop = ast; let isStaticMember = isStaticPropertyAccessExpression(ctx.checker, prop); if (isStaticMember) { return s([c2(prop.expression), "_static_", c2(prop.name)]); } else { let propName = prop.name.getText(); if (propName == "__index") { return s([c2(prop.expression)]); } else if (propName == "size") { let innerType = translateType$1( ctx.checker, ctx.checker.getTypeAtLocation(prop.expression) ); if (innerType == "sampler2D") { return s([c2(prop.expression), "_", propName]); } } else { return s([c2(prop.expression), ".", c2(prop.name)]); } } case ts.SyntaxKind.ThisKeyword: return s(["_this"]); case ts.SyntaxKind.FirstLiteralToken: let lit = ast; return s([lit.text]); case ts.SyntaxKind.IfStatement: let ifStmt = ast; if (isIdentifier$1(ifStmt.expression)) { if (ifStmt.expression.escapedText == "PLATFORM_WEBGL") { return s([c2(ifStmt.thenStatement)]); } if (ifStmt.expression.escapedText == "PLATFORM_WEBGPU") { if (ifStmt.elseStatement) { return s([c2(ifStmt.elseStatement)]); } else { return s([""]); } } } return s([ "if (", c2(ifStmt.expression), ")", c2(ifStmt.thenStatement), ifStmt.elseStatement ? s(["else \n", c2(ifStmt.elseStatement), "\n"]) : s([""]) ]); case ts.SyntaxKind.TrueKeyword: return s(["true"]); case ts.SyntaxKind.FalseKeyword: return s(["false"]); case ts.SyntaxKind.PostfixUnaryExpression: let post = ast; return s([c2(post.operand), post.operator == ts.SyntaxKind.PlusPlusToken ? "++" : "--"]); case ts.SyntaxKind.PlusPlusToken: return s(["++"]); case ts.SyntaxKind.MinusMinusToken: return s(["--"]); case ts.SyntaxKind.ParenthesizedExpression: let paren = ast; return s(["(", c2(paren.expression), ")"]); case ts.SyntaxKind.VariableDeclarationList: let varDeclList = ast; if (varDeclList.declarations.length > 0) { for (let decl2 of varDeclList.declarations) { let varDecl2 = decl2; let type22 = ctx.checker.getTypeAtLocation(varDecl2); return s([ translateType$1(ctx.checker, type22), " ", varDecl2.name.getText(), " = ", c2(varDecl2.initializer) ]); } } else { return s([""]); } case ts.SyntaxKind.ForStatement: let forStmt = ast; return s([ "for (", c2(forStmt.initializer), ";", c2(forStmt.condition), ";", c2(forStmt.incrementor), ")", c2(forStmt.statement) ]); case ts.SyntaxKind.BinaryExpression: let bin = ast; if (bin.operatorToken.kind == ts.SyntaxKind.EqualsToken) { let leftType = ctx.checker.getTypeAtLocation(bin.left); let rightType = ctx.checker.getTypeAtLocation(bin.right); if (isVector$1(ctx.checker, leftType) && isVector$1(ctx.checker, rightType)) { let [leftElementType, leftElementSize] = getVectorElementType$1(ctx.checker, leftType); let [rightElementType, rightElementSize] = getVectorElementType$1(ctx.checker, rightType); if (leftElementType != rightElementType) { if (leftElementType == "float" && rightElementType == "int") { return s([c2(bin.left), ` = vec${leftElementSize}(`, c2(bin.right), ")"]); } else if (leftElementType == "int" && rightElementType == "float") { return s([c2(bin.left), ` = ivec${leftElementSize}(`, c2(bin.right), ")"]); } } } return s([c2(bin.left), " = ", c2(bin.right)]); } let binExprText = bin.operatorToken.getText(); if (binExprText == "===") { binExprText = "=="; } return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]); case ts.SyntaxKind.StringLiteral: return s(["0"]); case ts.SyntaxKind.ArrayLiteralExpression: let arr = ast; return s([ "[", ...join( arr.elements.map((e) => c2(e)), ", " ), "]" ]); case ts.SyntaxKind.ElementAccessExpression: let elem = ast; return s([c2(elem.expression), "[", c2(elem.argumentExpression), "]"]); case ts.SyntaxKind.Block: let block = ast; return s([ "{\n", ...join( block.statements.map((child) => c2(child)), ";" ), "\n}" ]); case ts.SyntaxKind.TypeOfExpression: return s(["0"]); case ts.SyntaxKind.WhileStatement: let whileStmt = ast; return s(["while (", c2(whileStmt.expression), ") ", c2(whileStmt.statement)]); default: throw new GLSLCompilationError(`Invalid shader syntax '${ast.getText()}'`, ast); } } function getClosureVars$1(checker, func) { let result = []; let recur = (node2) => { if (node2.kind == ts.SyntaxKind.Identifier) { let id = node2; let symbol = checker.getSymbolAtLocation(id); let declar = symbol.valueDeclaration; if (isVariableDeclarationValue$1(checker, declar)) { if (declar) { if (!isInSameScope$1(declar, node2) && isInShader$2(declar)) { result.push(symbol); } } } } else { node2.forEachChild(recur); } }; recur(func); return result; } function getDeclarationType$1(checker, node2) { return node2.type ? checker.getTypeAtLocation(node2.type) : node2.initializer ? checker.getTypeAtLocation(node2.initializer) : checker.getTypeAtLocation(node2); } class GLSLShader { constructor(key, source) { this.globals = {}; this.locals = {}; this.key = key; this.source = source; } } function resolveFunctionName$1(f) { if (ts.isMethodDeclaration(f)) { let parentName = "anon"; if (f.parent && ts.isClassDeclaration(f.parent)) { parentName = f.parent.name?.text ?? "anon"; } return removeDoubleUnderscores$1( `fn_${f.getSourceFile()?.fileName.replaceAll("/", "_").replaceAll(".", "_") ?? "anon"}_${f.getStart()}_${parentName}_static_${f.name.getText() ?? "unknown"}` ); } else { return removeDoubleUnderscores$1( `fn_${f.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${f.getStart()}_${f.name?.text.replaceAll(".", "_dot_") ?? "unknown"}` ); } } function resolveStructName$1(c2) { if (c2.name?.text == "ShaderInput") return "ShaderInput"; if (c2.name?.text == "ShaderOutput") return "ShaderOutput"; return removeDoubleUnderscores$1( `str_${c2.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${c2.getStart()}_${c2.name?.text ?? "unknown"}`.replaceAll("__", "_i_") ); } function isInSameScope$1(node2, other) { return closest(node2, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }) == closest(other, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }); } function isInShader$2(node2) { return closest(node2, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) { if (hasShadeupDocTag(node22, "shader")) { return true; } } return false; }); } function isRootNode$1(node2) { let parentRoot = closest(node2, (node22) => { if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }); return parentRoot && ts.isSourceFile(parentRoot); } function isComposedFunction$1(checker, func) { let isComposed = false; func.parameters.forEach((param) => { let type2 = checker.getTypeAtLocation(param); if (type2.getCallSignatures().length > 0) { isComposed = true; } }); return isComposed; } function resolveDeps$1(checker, root, table = { graph: /* @__PURE__ */ new Map(), functions: /* @__PURE__ */ new Map(), structs: /* @__PURE__ */ new Map(), structsProps: /* @__PURE__ */ new Map(), globals: /* @__PURE__ */ new Map(), composed: /* @__PURE__ */ new Map() }) { function resolveFunction(f1, f2, call) { let n1 = f1 ? resolveFunctionName$1(f1) : "main"; let n2 = resolveFunctionName$1(f2); if (f2.name?.getText() === "__index" || f2.name?.getText() === "__index_assign" || f2.name?.getText() === "__index_assign_op" || f2.name?.getText() === "len" || f2.name?.getText() === "sample" || hasShadeupDocTag(f2, "noemit_gpu")) return; if (isComposedFunction$1(checker, f2)) { n2 = n2 + "_composed_" + call.pos; table.composed.set(n2, call); } let deps = table.graph.get(n1) ?? []; if (!deps.includes(n2)) deps.push(n2); table.graph.set(n1, deps); table.functions.set(n2, f2); } function resolveStruct(decl) { let name = resolveStructName$1(decl); if (table.structs.has(name)) return; for (let member of decl.members) { if (ts.isPropertyDeclaration(member)) { let type2 = checker.getTypeAtLocation(member); resolveTypeUse(type2, member); } } table.structs.set(name, decl); } function isValidShaderType(type2, checker2) { let symbol = type2.aliasSymbol || type2.getSymbol(); let name = checker2.typeToString(type2); let bases = type2.getBaseTypes(); if (bases && bases.length > 0) { for (let base of bases) { if (!isValidShaderType(base, checker2)) return false; } } if (TYPE_BLACKLIST$1.includes(symbol?.getName() ?? "")) { return false; } return !TYPE_BLACKLIST$1.includes(name); } function resolveTypeUse(typeNode, context2, fullStruct = false) { let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); let name = checker.typeToString(typeNode); if (!isValidShaderType(typeNode, checker)) { throw new GLSLCompilationError(`Type '${name}' is not supported in shaders`, context2); } let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { resolveStruct(decl); } let typestr = checker.typeToString(typeNode); if (typeNode.aliasTypeArguments) for (let args of typeNode.aliasTypeArguments) { resolveTypeUse(args, context2, typestr.startsWith("buffer<")); } } function resolvePropertyAccess(node2) { let typeNode = checker.getTypeAtLocation(node2.expression); let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); checker.typeToString(typeNode); if (!isValidShaderType(typeNode, checker)) { throw new GLSLCompilationError( `Type '${symbol?.getName()}' is not supported in shaders`, node2 ); } resolveTypeUse(typeNode, node2); resolveTypeUse(checker.getTypeAtLocation(node2), node2); let prop = node2.name.getText(); let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { let name2 = resolveStructName$1(decl); let props = table.structsProps.get(name2) ?? /* @__PURE__ */ new Set(); props.add(prop); table.structsProps.set(name2, props); } } walkNodes$2(root, (node2) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; exprSmybol.valueDeclaration; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let signature = checker.getResolvedSignature(node2); let mapping = findRealSignatureMappingToGLSL(checker, signature) ?? findSignatureMappingToGLSL(checker, exprSmybol); if (mapping === null) { let parentDeclar = closest( node2, (n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) || ts.isArrowFunction(n) ); if (parentDeclar && ts.isArrowFunction(parentDeclar)) { let parentParentDeclar = closest(parentDeclar, (n) => ts.isCallExpression(n)); if (parentParentDeclar && ts.isCallExpression(parentParentDeclar)) { let parentParentSymbol = checker.getSymbolAtLocation(parentParentDeclar.expression); if (parentParentSymbol && parentParentSymbol.flags & ts.SymbolFlags.Alias) { parentParentSymbol = checker.getAliasedSymbol(parentParentSymbol); } if (parentParentSymbol) { let parentParentFuncDeclar = parentParentSymbol.getDeclarations()?.[0]; if (parentParentFuncDeclar && (ts.isFunctionDeclaration(parentParentFuncDeclar) || ts.isMethodDeclaration(parentParentFuncDeclar))) { resolveFunction(parentParentFuncDeclar, funcDeclar, node2); } } } } else if (parentDeclar && (ts.isFunctionDeclaration(parentDeclar) || ts.isMethodDeclaration(parentDeclar))) { resolveFunction(parentDeclar, funcDeclar, node2); } else { resolveFunction(null, funcDeclar, node2); } if (!table.graph.has(resolveFunctionName$1(funcDeclar))) { table.graph.set(resolveFunctionName$1(funcDeclar), []); resolveDeps$1(checker, funcDeclar, table); } let sig = checker.getSignatureFromDeclaration(funcDeclar); let returnType = checker.getReturnTypeOfSignature(sig); resolveTypeUse(returnType, node2); } } } } if (ts.isPropertyAccessExpression(node2)) { resolvePropertyAccess(node2); } if (ts.isIdentifier(node2)) { if (checker.getSymbolAtLocation(node2)) { let decl = checker.getSymbolAtLocation(node2)?.declarations; let type2 = checker.getTypeAtLocation(node2); resolveTypeUse(type2, node2); if (decl && ts.isVariableDeclaration(decl[0])) { if (!isInSameScope$1(decl[0], node2) && decl[0].getSourceFile().fileName !== root.getSourceFile().fileName) { if (isVariableDeclarationValue$1(checker, decl[0])) { table.globals.set(node2.text.toString(), decl[0]); } } } } } if (ts.isVariableDeclaration(node2)) { let type2 = checker.getTypeAtLocation(node2); resolveTypeUse(type2, node2); } }); return table; } function resolveUniforms$1(checker, root) { let uniforms = []; walkNodesWithCalls$1(checker, root, (node2) => { if (ts.isIdentifier(node2)) { let decl = checker.getSymbolAtLocation(node2); if (decl && decl.flags & ts.SymbolFlags.Alias) { decl = checker.getAliasedSymbol(decl); } if (decl && decl.declarations && decl.declarations.length == 1) { let declNode = decl.declarations[0]; if (declNode) { if (isVariableDeclarationValue$1(checker, declNode)) { if (!isInSameScope$1(declNode, node2) && !isInShader$2(declNode)) { if (uniforms.findIndex((d) => d === declNode) == -1) uniforms.push(declNode); } } } } } }); return uniforms; } function isVariableDeclarationValue$1(checker, node2) { try { if (ts.isVariableDeclaration(node2) || ts.isParameter(node2)) { let type2 = checker.getTypeAtLocation(node2); let calls = type2.getCallSignatures(); return calls.length == 0; } else { return false; } } catch (e) { return false; } } function isUniformable$1(checker, decl) { let exprSmybol = checker.getSymbolAtLocation(decl); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { exprSmybol.getDeclarations()?.[0]; } return ts.isVariableDeclaration(decl) || ts.isParameter(decl); } function addGLSLShader(key, root, checker, env2, isComputeShader = false, computeShaderSize = [1, 1, 1]) { let deps = resolveDeps$1(checker, root); let uniforms = resolveUniforms$1(checker, root); let mapping = [...deps.graph.entries()].map(([k, v]) => v.map((d) => [k, d])).flat(); let sorted = []; try { sorted = toposort(mapping).reverse(); } catch (e) { sorted = []; } let preFuncs = []; for (let s of deps.structs.values()) { let name = resolveStructName$1(s); let hasAnyProperty = false; let sp = deps.structsProps.get(name); let members = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; let type2 = checker.getTypeAtLocation(m); let translated = translateType$1(checker, type2); let preComment = ""; if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { preComment = `// `; } } if (preComment == "") { hasAnyProperty = true; } return new SourceNode( m.getStart(), m.getEnd(), `${preComment} ${translated} ${m.name.getText()}; ` ); }); let memberNames = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; checker.getTypeAtLocation(m); if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { return ""; } } return m.name.getText(); }).filter((m) => m != ""); let memberParams = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; let type2 = checker.getTypeAtLocation(m); let translated = translateType$1(checker, type2); if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { return ""; } } return translated + " " + m.name.getText(); }).filter((m) => m != ""); if (!hasAnyProperty) continue; preFuncs.push( new SourceNode(s.getStart(), s.getEnd(), [`struct ${name} { `, ...members, "\n};\n"]) ); if (name != "ShaderInput" && name != "ShaderOutput") { preFuncs.push( new SourceNode(s.getStart(), s.getEnd(), [ name + " _make_struct_" + name + "(", memberParams.join(", ") + ")", " {\n", name, " _s;", "", ...memberNames.map((m) => ` _s.${m} = ${m}; `), " return _s;\n", "}\n" ]) ); } } for (let u of uniforms) { if (isUniformable$1(checker, u)) { let _type = checker.getTypeAtLocation(u); let translated = translateType$1(checker, _type); let isGlobalVar = isRootNode$1(u); let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`; if (translated.includes("[]")) { translated = translated.replace(/\[\]$/, ``); preFuncs.push( new SourceNode(u.getStart(), u.getEnd(), [ "uniform ", "int", " ", glslVarName, "_size;\n" ]) ); glslVarName += `[%${glslVarName}_size%]`; } preFuncs.push( new SourceNode(u.getStart(), u.getEnd(), ["uniform ", translated, " ", glslVarName, ";\n"]) ); if (translated == "sampler2D") { preFuncs.push( new SourceNode(u.getStart(), u.getEnd(), ["uniform vec2 ", glslVarName, "_size;\n"]) ); } } } for (let k of sorted) { if (k == "main") continue; let v = deps.functions.get(k); if (v) { let sourceFile2 = v.getSourceFile(); let originalFile2 = env2.files.find((f) => f.path == sourceFile2.fileName); preFuncs.push( compile$2( { parentFunction: v, checker, composed: deps.composed.get(k) ?? null }, v, originalFile2?.mapping ) ); } } let sourceFile = root.getSourceFile(); let originalFile = env2.files.find((f) => f.path == sourceFile?.fileName); let main = compile$2( { checker }, root, originalFile.mapping ); preFuncs.push(main); let source = new SourceNode(root.getStart(), root.getEnd(), preFuncs); let ss = { indexMapping: [], str: "" }; source.toString(ss); let matches = glslHeader.match(/^([a-zA-Z_][a-zA-Z0-9_]+ [^\(]+)/gm); let finalShaderOutput = ss.str; let headerSplits = []; for (let i = 0; i < matches.length; i++) { let index = glslHeader.indexOf(matches[i]); let toIndex = i == matches.length - 1 ? glslHeader.length : glslHeader.indexOf(matches[i + 1]); headerSplits.push(glslHeader.substring(index, toIndex)); } let realHeader = ""; for (let i = 0; i < headerSplits.length; i++) { let headerText = headerSplits[i]; let fnName = headerText.match(/^[a-zA-Z_][a-zA-Z0-9_]+ ([^\(]+)/)?.[1]; if (fnName) { if (finalShaderOutput.includes(fnName)) { realHeader += headerText; } } } finalShaderOutput = realHeader + finalShaderOutput; let output = new GLSLShader(`shd_${key}`, finalShaderOutput); output.sourceMapping = ss.indexMapping; for (let u of uniforms) { if (isUniformable$1(checker, u)) { let name = u.name.getText(); let isGlobalVar = isRootNode$1(u); if (name) { let filterProps = function(props) { if (props && props.name) { let sp = deps.structsProps.get(props.name); let realStruct = deps.structs.get(props.name); if (props.type == "struct" && realStruct) { for (let f of Object.keys(props.fields)) { if (!sp || !sp.has(f)) { delete props.fields[f]; } else { if (props.fields[f].type == "struct") { props.fields[f] = filterProps(props.fields[f]); } } } } } return props; }; let typeOut = getDeclarationType$1(checker, u); let typeNode = checker.getTypeAtLocation(u); let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { resolveStructName$1(decl); } if (isGlobalVar) { output.globals[name] = { fileName: getNodeSourceFileName$1(u), structure: filterProps(translateType$1(checker, typeOut, true)) }; } else { output.locals[name] = filterProps(translateType$1(checker, typeOut, true)); } } } } return output; } function getNodeSourceFileName$1(node2) { let found = closest(node2, (n) => ts.isSourceFile(n)); if (found && ts.isSourceFile(found)) { return found.fileName; } else { return ""; } } function walkNodes$2(node2, cb) { cb(node2); node2.forEachChild((n) => walkNodes$2(n, cb)); } function walkNodesWithCalls$1(checker, node2, cb) { cb(node2); node2.forEachChild((n) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let signature = checker.getResolvedSignature(node2); let mapping = findRealSignatureMappingToGLSL(checker, signature) ?? findSignatureMappingToGLSL(checker, exprSmybol); if (mapping === null) { if (funcDeclar.body) { walkNodesWithCalls$1(checker, funcDeclar.body, cb); } } } } } walkNodesWithCalls$1(checker, n, cb); }); } function findSignatureMappingToGLSL(checker, sym) { let matcher = /=(?:glsl|univ)\((.+)\)$/g; if (!sym.valueDeclaration) return null; let doc = ts.getJSDocTags(sym.valueDeclaration); for (let d of doc) { if (d.tagName.text !== "shadeup") continue; if (typeof d.comment === "string") { let matches = matcher.exec(d.comment); if (matches) { return matches[1]; } } } return null; } function findRealSignatureMappingToGLSL(checker, sig) { let matcher = /=(?:glsl|univ)\((.+)\)$/g; let doc = ts.getJSDocTags(sig.getDeclaration()); for (let d of doc) { if (d.tagName.text !== "shadeup") continue; if (typeof d.comment === "string") { let matches = matcher.exec(d.comment); if (matches) { return matches[1]; } } } return null; } function removeDoubleUnderscores$1(str) { return str.replace(/__/g, "_ii"); } let { factory, isArrayTypeNode, isCallExpression, isIdentifier, isPropertyAccessChain, isPropertyAccessExpression } = ts; const TYPE_BLACKLIST = [ "never", "object", "symbol", "bigint", "undefined", "null", "map", "string" ]; const RESERVED_WORDS = [ "this", "target", "attribute", "sample", "varying", "uniform", "layout", "delete" ]; function generateDefaultForType$1(checker, _type_node) { let _type = checker.getTypeFromTypeNode(_type_node); let name = (_type.aliasSymbol || _type.getSymbol())?.escapedName.toString(); switch (name) { case "int": return "i32(0)"; case "float": return "f32(0.0)"; case "float2": return "vec2(0.0, 0.0)"; case "float3": return "vec3(0.0, 0.0, 0.0)"; case "float4": return "vec4(0.0, 0.0, 0.0, 0.0)"; case "int2": return "vec2(0, 0)"; case "int3": return "vec3(0, 0, 0)"; case "int4": return "vec4(0, 0, 0, 0)"; case "uint": return "u32(0)"; case "uint2": return "vec2(0, 0)"; case "uint3": return "vec3(0, 0, 0)"; case "uint4": return "vec4(0, 0, 0, 0)"; case "float2x2": return "mat2x2(0.0, 0.0, 0.0, 0.0)"; case "float3x3": return "mat3x3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "float4x4": return "mat4x4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "bool": return "0"; default: let decl = _type.getSymbol()?.getDeclarations(); if (ts.isTupleTypeNode(_type_node)) { let len = _type_node.elements.length; let args = []; let rootNode = _type_node.elements[0]; if (rootNode) { for (let i = 0; i < len; i++) { args.push(generateDefaultForType$1(checker, _type_node.elements[i])); } let rootType = checker.getTypeFromTypeNode(rootNode); return translateType(checker, rootType) + `[${len}] {` + args.join(", ") + "}"; } else { return "0"; } } if (decl && decl.length > 0) { let d = decl[0]; let structProps = []; if (ts.isClassDeclaration(d)) { let symd = _type.getSymbol(); symd?.members?.forEach((v, k) => { let decl2 = v.valueDeclaration; if (decl2 && ts.isPropertyDeclaration(decl2)) { structProps.push([k?.toString() ?? "", decl2.type]); } }); let sortedPropsByKey = structProps.sort((a, b) => { return a[0].localeCompare(b[0]); }); let args = sortedPropsByKey.map((p) => { return "/* " + p[0] + ": */ " + generateDefaultForType$1(checker, p[1]) + "\n"; }); return "_make_struct_" + resolveStructName(d) + "(\n" + args.join(", ") + "\n)"; } else { return "0"; } } else { return "0"; } } } function getTypeFallback$1(checker, t) { let n = (t.aliasSymbol || t.getSymbol())?.escapedName; if (!n && t.intrinsicName) n = t.intrinsicName; if (typeof n !== "string") { let props = t.getApparentProperties(); if (props.length > 0) { for (let p of props) { if (p.escapedName.toString() === "_opaque_int") return "int"; if (p.escapedName.toString() === "_opaque_float") return "float"; if (p.escapedName.toString() === "_opaque_uint") return "uint"; } } let btype = t.getBaseTypes(); if (btype && btype.length > 0) { for (let b of btype) { let tn = getTypeFallback$1(checker, b); if (tn) return tn; } return null; } } else { return n; } } function followTypeReferences(t) { if (t.flags & ts.TypeFlags.Object && t.objectFlags & ts.ObjectFlags.Reference) { if (t.target === t) { return t; } return followTypeReferences(t.target); } else { return t; } } function getArrayTypeInfo(checker, t) { let n = getTypeFallback$1(checker, t); let originalType = t; if (n === void 0) { t = followTypeReferences(t); } let isArray = false; let staticSize = -1; let elementType = ""; if (n === "Array" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); let translated = translateType(checker, args[0]); if (tsutils.isTupleType(t)) { staticSize = t.fixedLength; } checker.typeToString(typeRef); isArray = true; elementType = translated; } return { isArray, staticSize, elementType }; } function translateType(checker, t, templateFormat = false, usedInsidePotentiallyExternalType = false) { let n = getTypeFallback$1(checker, t); let originalType = t; if (n === void 0) { t = followTypeReferences(t); } if (templateFormat) { let name = n?.toString() ?? "unknown"; if (name === "Array" || name === "array" || name === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); return { type: name == "buffer" ? "buffer" : "array", element: translateType(checker, args[0], true), staticSize: args.length }; } if (name == "boolean" || name == "false" || name == "true") name = "bool"; if (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint") || name == "bool" || name == "texture2d" || name == "texture3d") return { type: "primitive", name }; if (name == "atomic") { let args = t.typeArguments || checker.getTypeArguments(t); let translated = translateType(checker, args[0]); return { type: "primitive", name, element: translated }; } let symbol = t.aliasSymbol || t.getSymbol(); if (symbol && symbol.declarations && symbol.declarations.length > 0) { if (ts.isClassDeclaration(symbol.declarations[0])) { let fields = []; let decl = symbol.declarations[0]; for (let member of decl.members) { if (ts.isPropertyDeclaration(member)) { let name2 = member.name.getText(); let type2 = checker.getTypeFromTypeNode(member.type); fields.push([name2, translateType(checker, type2, true)]); } } return { type: "struct", name: resolveStructName(decl), fields }; } else { return { type: "unknown" }; } } } else { if (n === "Array" || n === "array" || n === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); let translated = translateType(checker, args[0]); let typeInfo = getWGSLTypeInfo(translated); let toStringed = checker.typeToString(typeRef); if (n == "buffer") { return `array<${translated}>`; } if (typeInfo.needsAlignment) { translated = `vec4<${typeInfo.elementType ?? "f32"}>`; } if (toStringed.endsWith("[]")) { return "array<" + translated + ">"; } else { let arraySize = 0; if (tsutils.isTupleType(t)) { arraySize = t.fixedLength; } return "array<" + translated + ", " + arraySize + ">"; } } if (n === "texture2d") return `sampler`; if (n == "atomic") { let args = t.typeArguments || checker.getTypeArguments(t); let translated = translateType(checker, args[0]); return `atomic<${translated}>`; } if (n === "bool") return "bool"; if (n === "boolean") return "bool"; if (n === "uint8") return "f32"; if (n === "float") return "f32"; if (n === "float2") return "vec2"; if (n === "float3") return "vec3"; if (n === "float4") return "vec4"; if (n === "int") return "i32"; if (n === "int2") return "vec2"; if (n === "int3") return "vec3"; if (n === "int4") return "vec4"; if (n === "uint") return "u32"; if (n === "uint2") return "vec2"; if (n === "uint3") return "vec3"; if (n === "uint4") return "vec4"; if (n === "float2x2") return "mat2x2"; if (n === "float3x3") return "mat3x3"; if (n === "float4x4") return "mat4x4"; if (n === "void") return "void"; if (n === "error") return "void"; if (t.isUnion()) { let types2 = t.types.map((t2) => translateType(checker, t2)); for (let sub of types2) { if (sub && sub !== "void" && sub !== "undefined") return sub; } } let symbol = t.aliasSymbol || t.getSymbol(); if (symbol && symbol.declarations && symbol.declarations.length > 0) { if (ts.isClassDeclaration(symbol.declarations[0])) { return resolveStructName(symbol.declarations[0]); } else { return n?.toString() ?? "void"; } } else { return n?.toString() ?? "void"; } } } function isTypeNameVector(name) { if (name == "float2" || name == "float3" || name == "float4" || name == "int2" || name == "int3" || name == "int4" || name == "uint2" || name == "uint3" || name == "uint4") { return true; } return false; } function getTypeNameVectorElementType(name) { if (name == "float") { return ["float", 1]; } if (name == "int") { return ["int", 1]; } if (name == "uint") { return ["uint", 1]; } if (name.startsWith("float")) { return ["float", parseInt(name.substring(5))]; } if (name.startsWith("int")) { return ["int", parseInt(name.substring(3))]; } if (name.startsWith("uint")) { return ["uint", parseInt(name.substring(4))]; } if (name.startsWith("f32")) { return ["f32", 1]; } if (name.startsWith("i32")) { return ["i32", 1]; } if (name.startsWith("u32")) { return ["u32", 1]; } if (name.endsWith("")) { return ["float", parseInt(name.substring(3, 4))]; } if (name.endsWith("")) { return ["int", parseInt(name.substring(3, 4))]; } if (name.endsWith("")) { return ["uint", parseInt(name.substring(3, 4))]; } return ["", 0]; } function getTypeNameVectorElementTypeWGSL(name) { if (name == "f32") { return ["f32", 1]; } if (name == "i32") { return ["i32", 1]; } if (name == "u32") { return ["u32", 1]; } if (name.endsWith("")) { return ["f32", parseInt(name.substring(3, 4))]; } if (name.endsWith("")) { return ["i32", parseInt(name.substring(3, 4))]; } if (name.endsWith("")) { return ["u32", parseInt(name.substring(3, 4))]; } return ["", 0]; } function isTranslatedTypeNameVectorOrScalar(name) { if (name == "float" || name == "int" || name == "uint") return true; if (name.endsWith("") || name.endsWith("") || name.endsWith("")) { if (name.startsWith("vec2") || name.startsWith("vec3") || name.startsWith("vec4")) { return true; } return true; } return false; } function getWGSLTypeInfo(name) { switch (name) { case "bool": return { type: "bool", length: 1, size: 1, needsAlignment: true, elementType: "i32" }; case "u32": return { type: "integer", length: 1, signed: false, size: 4, needsAlignment: true, elementType: "u32" }; case "i32": return { type: "integer", length: 1, signed: true, size: 4, needsAlignment: true, elementType: "i32" }; case "f32": return { type: "float", length: 1, size: 4, needsAlignment: true, elementType: "f32" }; case "vec2": return { type: "vector", length: 2, element: "float", size: 8, needsAlignment: true, elementType: "f32" }; case "vec3": return { type: "vector", length: 3, element: "float", size: 12, needsAlignment: true, elementType: "f32" }; case "vec4": return { type: "vector", length: 4, element: "float", size: 16, needsAlignment: false, elementType: "f32" }; case "vec2": return { type: "vector", length: 2, signed: true, element: "integer", size: 8, needsAlignment: true, elementType: "i32" }; case "vec3": return { type: "vector", length: 3, signed: true, element: "integer", size: 12, needsAlignment: true, elementType: "i32" }; case "vec4": return { type: "vector", length: 4, signed: true, element: "integer", size: 16, needsAlignment: false, elementType: "i32" }; case "vec2": return { type: "vector", length: 2, signed: false, element: "integer", size: 8, needsAlignment: true, elementType: "u32" }; case "vec3": return { type: "vector", length: 3, signed: false, element: "integer", size: 12, needsAlignment: true, elementType: "u32" }; case "vec4": return { type: "vector", length: 4, signed: false, element: "integer", size: 16, needsAlignment: false, elementType: "u32" }; case "mat2x2": return { type: "matrix", element: "float", size: 16, needsAlignment: false }; case "mat3x3": return { type: "matrix", element: "float", size: 36, needsAlignment: false }; case "mat4x4": return { type: "matrix", element: "float", size: 64, needsAlignment: false }; default: return { type: "unknown", size: 0, needsAlignment: false }; } } function isVector(checker, t) { let name = getTypeFallback$1(checker, t); if (name) { return isTypeNameVector(name); } return false; } function getVectorElementType(checker, t) { let name = getTypeFallback$1(checker, t); if (name) { return getTypeNameVectorElementType(name); } return ["", 0]; } function isNumeric(checker, t) { let name = getTypeFallback$1(checker, t); if (name && (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint"))) { return true; } return false; } function escapeIdentifier(id) { if (RESERVED_WORDS.includes(id)) { return "_" + id; } return id.replaceAll("___", "_ii_").replaceAll("__", "_i_"); } function isAssignableType(t) { return !(t.startsWith("texture") || t.startsWith("sampler") || t.startsWith("buffer")); } function isGLSLType(name) { return name.startsWith("vec") || name.startsWith("mat") || name.startsWith("sampler") || name.startsWith("texture") || name == "bool" || name == "f32" || name == "i32" || name == "void"; } function autoCastNumeric(value, input, expected, node2) { let inputType = getTypeNameVectorElementTypeWGSL(input); let expectedType = getTypeNameVectorElementTypeWGSL(expected); if (inputType[0] !== "" && expectedType[0] !== "") { if (inputType[0] != expectedType[0]) { if (expectedType[1] == 1) { if (typeof expectedType[0] == "string" && expectedType[0].startsWith("vector")) { return new SourceNode(value.startIndex, value.endIndex, [value]); } else { if (inputType[0] == "u32") { throw new GLSLCompilationError(`Cannot cast uint to ${expectedType[0]}`, node2); } if (expectedType[0] == "i32") ; return new SourceNode(value.startIndex, value.endIndex, [ `${expectedType[0]}(`, value, `)` ]); } } else { if (inputType[0] == "u32") { throw new GLSLCompilationError(`Cannot cast uint to ${expectedType[0]}`, node2); } return new SourceNode(value.startIndex, value.endIndex, [ `vec${expectedType[1]}<${expectedType[0]}>(`, value, `)` ]); } } } return value; } function isUniformAccess(ctx, expr) { if (isCallExpression(expr)) { expr = expr.expression; } let id = null; if (ts.isIdentifier(expr)) { id = expr; } if (isPropertyAccessExpression(expr)) { let chain = expr; while (chain.expression) { if (ts.isPropertyAccessExpression(chain.expression)) { chain = chain.expression; } else { break; } } id = chain.expression; } if (id) { if (ts.isIdentifier(id)) { let sym = ctx.checker.getSymbolAtLocation(id); if (sym && sym.flags & ts.SymbolFlags.Alias) { sym = ctx.checker.getAliasedSymbol(sym); } if (sym?.declarations?.length == 1) { let decl = sym.declarations[0]; if (isUniformable(ctx.checker, decl)) { if (isVariableDeclarationValue(ctx.checker, decl)) { if (!isInSameScope(decl, id)) { if (!isInShader$1(decl)) { return true; } } } } } } } return false; } function accessWrap(ctx, expr, inner) { if (isPropertyAccessExpression(expr)) { let chain = expr; while (chain.expression) { if (ts.isPropertyAccessExpression(chain.expression)) { chain = chain.expression; } else { break; } } let id = chain.expression; if (ts.isIdentifier(id)) { let sym = ctx.checker.getSymbolAtLocation(id); if (sym && sym.flags & ts.SymbolFlags.Alias) { sym = ctx.checker.getAliasedSymbol(sym); } if (sym?.declarations?.length == 1) { let decl = sym.declarations[0]; if (isUniformable(ctx.checker, decl)) { if (isVariableDeclarationValue(ctx.checker, decl)) { if (!isInSameScope(decl, chain.expression)) { if (!isInShader$1(decl)) { let outputType = ctx.checker.getTypeAtLocation(expr); let isBooleanAccess = false; if (isArrayType$1(outputType, ctx.checker)) { let typeRef = outputType; let args = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef); let t = args[0]; let n = getTypeFallback$1(ctx.checker, t); if (n == "boolean" || n == "bool") { isBooleanAccess = true; } } else { let n = getTypeFallback$1(ctx.checker, outputType); if (n == "boolean" || n == "bool") { isBooleanAccess = true; } } if (isBooleanAccess) { return new SourceNode(inner.startIndex, inner.endIndex, [`((`, inner, `) == 1)`]); } } } } } } } } return inner; } function getVectorMask(num) { let outMask = ""; let comps = ["x", "y", "z", "w"]; for (let i = 0; i < num; i++) { outMask += comps[i]; } return outMask; } function convertConciseBodyToBlock(body) { if (ts.isBlock(body)) { return body; } else { return ts.factory.createBlock([ts.factory.createReturnStatement(body)]); } } function getRealReturnType(checker, call) { let fnCallSignature = checker.getResolvedSignature(call); return fnCallSignature.getReturnType(); } function augmentParameter(checker, p) { const type2 = checker.getTypeAtLocation(p); const tt = translateType(checker, type2); if (tt == "sampler") { const args = checker.getTypeArguments(type2); let innerType = "f32"; if (args && args.length > 0) { let [et, _] = getVectorElementType(checker, args[0]); innerType = { float: "f32", int: "i32", uint: "u32" }[et]; } return [ new SourceNode(p.getStart(), p.getEnd(), [ p.name.getText() + "_texture: texture_2d<" + innerType + ">" ]) ]; } return []; } function augmentArgument(ctx, arg) { let type2 = ctx.checker.getTypeAtLocation(arg); let tt = translateType(ctx.checker, type2); if (tt == "sampler") { let args = ctx.checker.getTypeArguments(type2); if (args && args.length > 0) { getVectorElementType(ctx.checker, args[0]); } return [new SourceNode(arg.getStart(), arg.getEnd(), [compile$1(ctx, arg), "_texture"])]; } return []; } function compile$1(ctx, ast, originalMapping) { function c2(ast2) { if (!ast2) { return s([]); } return compile$1(ctx, ast2); } function cplain(ast2) { if (!ast2) { return s([]); } return compile$1( { checker: ctx.checker, parentFunction: ctx.parentFunction }, ast2 ); } function s(c22) { if (originalMapping) { let reverseMapped = lookupIndexMappingRange(originalMapping, ast.getStart(), ast.getEnd()); return new SourceNode(reverseMapped.start, reverseMapped.end, c22); } else { return new SourceNode(0, 0, c22); } } function join(c22, sep) { return c22.reduce((acc, cur) => { if (acc.length === 0) { return [cur]; } return [...acc, sep, cur]; }, []); } function children() { return ast.getChildren().map((child) => c2(child)); } let prefixFunctions = []; if (ctx.composed) { if (ts.isMethodDeclaration(ast) || ts.isFunctionDeclaration(ast)) { for (let [i, arg] of ctx.composed.arguments.entries()) { if (ts.isArrowFunction(arg)) { let paramFromIndex = ast.parameters[i]; let name = paramFromIndex.name.getText() + "_composed_" + arg.pos + "_arg_" + i; let signature = ctx.checker.getSignatureFromDeclaration(arg); let returnType = signature.getReturnType(); let vars = getClosureVars(ctx.checker, arg); let vvv = vars.map((p) => { let tt = translateType(ctx.checker, ctx.checker.getTypeAtLocation(p.declarations[0])); return s([p.escapedName, isAssignableType(tt) ? "_const" : "", ": ", tt]); }); let joins = join( [ ...arg.parameters.map((p) => { let aug = augmentParameter(ctx.checker, p); return [cplain(p), ...aug]; }).flat(), ...vvv ], ", " ); let returnStr = " -> " + translateType(ctx.checker, returnType); if (returnStr == " -> void") returnStr = ""; prefixFunctions.push( s([ "fn ", name, "(", ...joins, ")", returnStr, " {\n", ...vars.filter((p) => { let type2 = ctx.checker.getTypeAtLocation(p.declarations[0]); let tt = translateType(ctx.checker, type2); return isAssignableType(tt); }).map((p) => { return s([ "var ", p.escapedName.toString(), " = ", p.escapedName.toString(), "_const;\n" ]); }), ...arg.parameters.filter((p) => { let type2 = ctx.checker.getTypeAtLocation(p.type); let tt = translateType(ctx.checker, type2); return isAssignableType(tt); }).map((p) => { return s(["var ", p.name.getText(), " = ", p.name.getText(), "_const;\n"]); }), ...convertConciseBodyToBlock(arg.body).statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]) ); } } } } function autoCastParameter(callExpr, argIndex) { let signature = ctx.checker.getResolvedSignature(callExpr); let params = signature.getParameters(); let param = params[argIndex]; let paramType = ctx.checker.getTypeOfSymbolAtLocation(param, callExpr); let paramTypeString = translateType(ctx.checker, paramType); let arg = callExpr.arguments[argIndex]; let argType = ctx.checker.getTypeAtLocation(arg); let argTypeString = translateType(ctx.checker, argType); if (paramTypeString !== argTypeString) { return autoCastNumeric(c2(arg), argTypeString, paramTypeString, arg); } return s([c2(arg)]); } switch (ast.kind) { case ts.SyntaxKind.FirstPunctuation: return s([ast.getText()]); case ts.SyntaxKind.SyntaxList: return s(children()); case ts.SyntaxKind.SourceFile: return s(children()); case ts.SyntaxKind.BreakStatement: return s(["break;"]); case ts.SyntaxKind.ContinueStatement: return s(["continue;"]); case ts.SyntaxKind.MethodDeclaration: let fnDeclar = ast; let fnName = resolveFunctionName(fnDeclar); if (ctx.composed) { fnName = fnName + "_composed_" + ctx.composed.pos; } let isStatic = false; let signature = ctx.checker.getSignatureFromDeclaration(fnDeclar); if (ts.canHaveModifiers(fnDeclar)) { let mods = ts.getModifiers(fnDeclar); if (mods) { if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) { isStatic = true; } } } let returnType = signature.getReturnType(); let returnStr = " -> " + translateType(ctx.checker, returnType); if (returnStr == " -> void") returnStr = ""; return s([ ...prefixFunctions, "fn ", fnName, "(", ...join( [ ...isStatic ? [] : [ "_this: " + translateType(ctx.checker, ctx.checker.getTypeAtLocation(fnDeclar.parent)) ], ...fnDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map((p) => { const o = c2(p); const aug = augmentParameter(ctx.checker, p); return [o, ...aug]; }).flat() ], ", " ), ")", returnStr, " {\n", ...fnDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map( (p) => s([ "var ", escapeIdentifier(p.name.getText()), " = ", escapeIdentifier(p.name.getText()), "_const;\n" ]) ), ...fnDeclar.body?.statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]); case ts.SyntaxKind.FunctionDeclaration: let mthdDeclar = ast; let mthdsignature = ctx.checker.getSignatureFromDeclaration(mthdDeclar); let mthdreturnType = mthdsignature.getReturnType(); let mthdName = resolveFunctionName(mthdDeclar); if (ctx.composed) { mthdName = mthdName + "_composed_" + ctx.composed.pos; } let returnStrMethod = " -> " + translateType(ctx.checker, mthdreturnType); if (returnStrMethod == " -> void") returnStrMethod = ""; return s([ ...prefixFunctions, "fn ", mthdName, "(", ...join( mthdDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map((p) => { const o = c2(p); const aug = augmentParameter(ctx.checker, p); return [o, ...aug]; }).flat(), ", " ), ")", returnStrMethod, " {\n", ...mthdDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } let tt2 = translateType(ctx.checker, type22); return isAssignableType(tt2); }).map( (p) => s([ "var ", escapeIdentifier(p.name.getText()), " = ", escapeIdentifier(p.name.getText()), "_const;\n" ]) ), ...mthdDeclar.body?.statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]); case ts.SyntaxKind.ReturnStatement: let ret = ast; if (!ctx.parentFunction) { if (ret.expression) { return s(["return ", c2(ret.expression), ";\n"]); } else { return s(["return;\n"]); } } else { let expectedReturnType = ctx.checker.getSignatureFromDeclaration(ctx.parentFunction).getReturnType(); let actualReturnType = ctx.checker.getTypeAtLocation(ret.expression); if (ret.expression) { let sss = s([ "return ", autoCastNumeric( c2(ret.expression), translateType(ctx.checker, actualReturnType), translateType(ctx.checker, expectedReturnType), ret.expression ), ";\n" ]); return sss; } else { return s(["return;\n"]); } } case ts.SyntaxKind.AsExpression: let asExpr = ast; return c2(asExpr.expression); case ts.SyntaxKind.Parameter: let param = ast; if (ctx.composed) { let indexOf2 = param.parent.parameters.indexOf(param); let expr2 = ctx.composed.arguments[indexOf2]; if (expr2) { if (ts.isArrowFunction(expr2)) { let vars = getClosureVars(ctx.checker, expr2.body); let closureVars = vars.map((v) => { return s([ v.name, ": ", translateType(ctx.checker, ctx.checker.getTypeAtLocation(v.valueDeclaration)) ]); }); return s(join(closureVars, ", ")); } } } const tt = translateType(ctx.checker, ctx.checker.getTypeAtLocation(param)); return s([ escapeIdentifier(param.name.getText()), isAssignableType(tt) ? "_const" : "", ": ", tt ]); case ts.SyntaxKind.ArrowFunction: let arrow = ast; let body = convertConciseBodyToBlock(arrow.body); let preMain = ""; if (ctx.isComputeShader) { preMain = ` @compute @workgroup_size(${ctx.computeSize[0]}, ${ctx.computeSize[1]}, ${ctx.computeSize[2]})`; } return s([ "\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/" + preMain + "\nfn main(/*__SHADEUP_TEMPLATE_INPUT*/)" + (ctx.isComputeShader ? "" : "-> /*__SHADEUP_TEMPLATE_OUTPUT*/") + "{\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/\n", ...body.statements.filter((s2) => !ts.isFunctionDeclaration(s2)).map((s2) => c2(s2)), "\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/\n}\n" ]); case ts.SyntaxKind.VariableStatement: let varStatement = ast; return s([ ...join( varStatement.declarationList.declarations.map((d) => c2(d)), ", " ), ";\n" ]); case ts.SyntaxKind.VariableDeclaration: let varDecl = ast; let type2 = ctx.checker.getTypeAtLocation(varDecl); let fullText = varDecl.getSourceFile().getFullText(); let fullStart = varDecl.getFullStart(); let prefix = `// @workgroup `; let mySelf = fullText.slice(fullStart - prefix.length, fullStart); if (mySelf.includes("@workgroup")) { return s([]); } else { let translated = translateType(ctx.checker, type2); if (translated.startsWith("array")) { translated = ""; } if (isInShader$1(varDecl)) { let arrType = ctx.checker.getTypeAtLocation(varDecl); let typeInfo = getArrayTypeInfo(ctx.checker, arrType); if (typeInfo.isArray) { if (typeInfo.staticSize <= 0) { throw new GLSLCompilationError( "Cannot declare an array without a static size in a shader", varDecl ); } } } let initializerVal = c2(varDecl.initializer); if (translated) { let leftType2 = type2; let rightType2 = ctx.checker.getTypeAtLocation(varDecl.initializer); if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) { let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2); let [rightElementType, rightElementSize] = getVectorElementType(ctx.checker, rightType2); if (leftElementType != rightElementType) { if (leftElementType == "float" && rightElementType == "int") { initializerVal = s([`vec${leftElementSize}f(`, initializerVal, ")"]); } else if (leftElementType == "int" && rightElementType == "float") { initializerVal = s([`vec${leftElementSize}i(`, initializerVal, ")"]); } } } if (isNumeric(ctx.checker, leftType2) && isNumeric(ctx.checker, rightType2)) { let leftTypeStr = translateType(ctx.checker, leftType2); let rightTypeStr = translateType(ctx.checker, rightType2); if (leftTypeStr != rightTypeStr) { initializerVal = s([ autoCastNumeric(initializerVal, rightTypeStr, leftTypeStr, varDecl.initializer) ]); } } } if (translated == "___atomic_compare_exchange_result") { translated = ""; } return s([ "var ", escapeIdentifier(varDecl.name.getText()), translated ? ": " : "", translated, " = ", initializerVal ]); } case ts.SyntaxKind.CallExpression: let call = ast; let exprSmybol = ctx.checker.getSymbolAtLocation(call.expression); if (call.expression.getText() == "Math.random") { return s(["0.0"]); } if (!exprSmybol) { return s(["/* TODO: Unknown symbol */"]); } if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = ctx.checker.getAliasedSymbol(exprSmybol); } let symName = exprSmybol?.getName() ?? call.expression.getText(); if (ts.isIdentifier(call.expression)) { if (isUniformAccess(ctx, call.expression)) { let typ = ctx.checker.getTypeAtLocation(call.expression); if (typ.getSymbol().getName().startsWith("shader") || typ.aliasSymbol && typ.aliasSymbol.getName() == "shader") { console.log("Uniform access to shader", typ.getSymbol().getName()); } } } if (symName == "__index") { let postfix2 = ""; let t2 = ctx.checker.getTypeAtLocation( call.expression.expression ); isUniformAccess( ctx, call.expression.expression ); if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); let returnType2 = getRealReturnType(ctx.checker, call); let vecOut = getVectorElementType(ctx.checker, returnType2); let outMask = getVectorMask(vecOut[1]); if (innerType == "sampler") { if (ts.isCallExpression(call.expression.expression)) { let callIndex = call.expression.expression; return s([ "textureLoad(", c2(callIndex.expression), "_texture, ", ...join([...callIndex.arguments.map((a) => c2(a))], ","), ", vec2(", c2(call.arguments[0]), "), 0)." + outMask ]); } else { return s([ "textureLoad(", c2(call.expression.expression), "_texture, vec2(", c2(call.arguments[0]), "), 0)." + outMask ]); } } } let translatedOut = translateType(ctx.checker, ctx.checker.getTypeAtLocation(call)); if (isArrayType$1(t2, ctx.checker) && isUniformAccess(ctx, call.expression.expression) && !translatedOut.startsWith("mat")) { let typeRef = t2; let args2 = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef); let translated = translateType(ctx.checker, args2[0]); let typeInfo = getWGSLTypeInfo(translated); if (typeInfo.needsAlignment) { translated = `vec4<${typeInfo.elementType ?? "f32"}>`; } let lengths = { 1: "x", 2: "xy", 3: "xyz", 4: "xyzw" }; if (typeInfo.type != "unknown") { postfix2 = `.${lengths[typeInfo.length ?? 1]}`; } } return accessWrap( ctx, call.expression.expression, s([c2(call.expression), "[", c2(call.arguments[0]), "]", postfix2]) ); } else if (symName == "attr") { let expr2 = call.expression; if (ts.isPropertyAccessExpression(expr2)) { let left2 = expr2.expression; let leftName = ctx.checker.getTypeAtLocation(left2).getSymbol()?.getName() ?? ""; if (leftName == "ShaderInput") { if (call.arguments.length >= 1) { let arg1 = call.arguments[0]; if (ts.isCallExpression(arg1)) { arg1 = arg1.arguments[0]; } if (!ts.isNumericLiteral(arg1)) { throw new GLSLCompilationError("Attribute index must be a number literal", arg1); } let index = parseInt(arg1.getText()); let interpMode = "perspective"; if (call.arguments.length >= 2) { let arg2 = call.arguments[1]; if (ts.isStringLiteral(arg2)) { interpMode = arg2.text; } } let valType = ""; if (call.typeArguments.length == 1) { valType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.typeArguments[0]) ); } ctx.addCustomAttribute("in", index, valType, interpMode); return s(["_i_in.custom", index.toString()]); } } else if (leftName == "ShaderOutput") { if (call.arguments.length >= 2) { let arg1 = call.arguments[0]; if (ts.isCallExpression(arg1)) { arg1 = arg1.arguments[0]; } if (!ts.isNumericLiteral(arg1)) { throw new GLSLCompilationError("Attribute index must be a number literal", arg1); } let index = parseInt(arg1.getText()); let interpMode = "perspective"; if (call.arguments.length >= 3) { let arg2 = call.arguments[2]; if (ts.isStringLiteral(arg2)) { interpMode = arg2.text; } } let valType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.arguments[1]) ); ctx.addCustomAttribute("out", index, valType, interpMode); return s(["_i_out.custom", index.toString(), " = ", c2(call.arguments[1])]); } } } } else if (symName == "len") { let expr2 = call.expression; if (ts.isPropertyAccessExpression(expr2)) { let left2 = expr2.expression; if (isUniformAccess(ctx, left2)) { return s(["_in_uniforms.", c2(left2), "_size"]); } else { let arrType = ctx.checker.getTypeAtLocation(left2); let typeInfo = getArrayTypeInfo(ctx.checker, arrType); return s([typeInfo.staticSize.toString()]); } } } else if (symName == "min" || symName == "max") { if (call.arguments.length > 2) { let args2 = call.arguments.map((a) => c2(a)); while (args2.length > 2) { let left2 = args2.shift(); let right2 = args2.shift(); args2.unshift(s([symName, "(", left2, ",", right2, ")"])); } return s([symName, "(", ...join(args2, ","), ")"]); } } else if (symName == "clamp") { if (call.arguments.length == 3) { let inType = ctx.checker.getTypeAtLocation(call.arguments[0]); let vType = translateType(ctx.checker, inType); let vTypeInfo = getWGSLTypeInfo(vType); if (vTypeInfo.type == "vector") { let minV = call.arguments[1]; let maxV = call.arguments[2]; let minType = ctx.checker.getTypeAtLocation(minV); let maxType = ctx.checker.getTypeAtLocation(maxV); let minTypeInfo = getWGSLTypeInfo(translateType(ctx.checker, minType)); let maxTypeInfo = getWGSLTypeInfo(translateType(ctx.checker, maxType)); if (minTypeInfo.type == "vector" && maxTypeInfo.type == "vector") ; else { let minStr = c2(minV); let maxStr = c2(maxV); if (minTypeInfo.type != "vector") { minStr = s([`vec${vTypeInfo.length}<${vTypeInfo.elementType}>(`, minStr, ")"]); } if (maxTypeInfo.type != "vector") { maxStr = s([`vec${vTypeInfo.length}<${vTypeInfo.elementType}>(`, maxStr, ")"]); } return s(["clamp(", c2(call.arguments[0]), ",", minStr, ",", maxStr, ")"]); } } } } else if (symName == "atomic") { throw new GLSLCompilationError( "Atomics cannot be constructed in shaders, create them outside or in a workgroup", call.expression ); } else if (symName == "sample") { if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); if (innerType == "sampler") { if (ts.isCallExpression(call.expression.expression)) { let callIndex = call.expression.expression; return s([ "textureSample(", c2(callIndex.expression), "_texture, ", c2(callIndex.expression), ",", "vec2(", c2(call.arguments[0]), "),", ...join([...callIndex.arguments.map((a) => c2(a))], ","), ")" ]); } else { return s([ "textureSample(", c2(call.expression.expression), "_texture, ", c2(call.expression.expression), ", vec2(", c2(call.arguments[0]), "))" ]); } } } } else if (symName == "__index_assign") { let postfix2 = ""; if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); if (innerType == "sampler") { if (ts.isCallExpression(call.expression.expression)) { let callIndex = call.expression.expression; return s([ "textureStore(", c2(callIndex.expression), "_texture_write, ", ...join([...callIndex.arguments.map((a) => c2(a))], ","), ", vec2(", c2(call.arguments[0]), "), vec4(", autoCastParameter(call, 1), "))" ]); } else { return s([ "textureStore(", c2(call.expression.expression), "_texture_write, vec2(", c2(call.arguments[0]), "), vec4(", autoCastParameter(call, 1), "))" ]); } } } ctx.checker.getTypeAtLocation( call.expression.expression ); return accessWrap( ctx, call.expression.expression, s([ c2(call.expression.expression), "[", c2(call.arguments[0]), "]", postfix2, " = ", autoCastParameter(call, 1) ]) ); } else if (symName == "eq" && call.expression.getText() == "__.eq") { let leftArg = call.arguments[0]; let rightArg = call.arguments[1]; let leftType2 = ctx.checker.getTypeAtLocation(leftArg); let rightType2 = ctx.checker.getTypeAtLocation(rightArg); let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2); if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) { return s([ "squash_bool_vec", leftElementSize.toString(), "(", c2(leftArg), " == ", c2(rightArg), ")" ]); } } else if (symName == "rand" && call.arguments.length == 0 && call.expression.getText() == "rand") { throw new GLSLCompilationError( "rand() in shaders needs to be seeded, use rand(seed) instead", call ); } if (exprSmybol?.getName() == "makeVector" && exprSmybol.valueDeclaration) { if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) { let exprSig2 = ctx.checker.getResolvedSignature(call); if (exprSig2) { let returnType2 = ctx.checker.getReturnTypeOfSignature(exprSig2); let returnTypeStr = translateType(ctx.checker, returnType2); let returnTypeInfo = getWGSLTypeInfo(returnTypeStr); let callType = translateType(ctx.checker, returnType2); let argStrs = []; for (let [i, arg] of call.arguments.entries()) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeStr = translateType(ctx.checker, argType); let argTypeInfo = getWGSLTypeInfo(argTypeStr); let paramType = ctx.checker.getTypeAtLocation( exprSig2.parameters[i].getDeclarations()[0] ); let paramTypeStr = translateType(ctx.checker, paramType); if (argTypeInfo.elementType !== returnTypeInfo.elementType) { paramTypeStr = `vec${argTypeInfo.length}<${returnTypeInfo.elementType}>`; } argStrs.push(autoCastNumeric(c2(arg), argTypeStr, paramTypeStr, arg)); } return s([callType, "(", ...join(argStrs, ", "), ")"]); } } } if (exprSmybol?.getName() == "swizzle" && exprSmybol.valueDeclaration) { if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) { ctx.checker.getSignatureFromDeclaration(exprSmybol.valueDeclaration); let arg = call.arguments[0]; let arg2 = call.arguments[1]; let propAccess = ""; if (ts.isStringLiteral(arg2)) { propAccess = arg2.text; } let argType = ctx.checker.getTypeAtLocation(arg); if (isVector(ctx.checker, argType)) { if (call.arguments.length == 2) { return s([c2(arg), ".", propAccess]); } else { let t2 = s([ "var tempVal_", call.getStart().toString(), " = ", c2(call.arguments[2]), ";\n" ]); let assigns = []; for (let i = 0; i < propAccess.length; i++) { let char = propAccess[i]; assigns.push( s([ c2(arg), ".", char, " = ", "tempVal_", call.getStart().toString(), ...propAccess.length > 1 ? [".", char] : [], ";\n" ]) ); } return s([t2, ...assigns]); } } else if (isNumeric(ctx.checker, argType)) { let numericType = translateType(ctx.checker, argType); return s([`shadeup_up_swizzle_${propAccess}_${numericType}(`, c2(arg), ")"]); } else { return s([c2(arg), ".", propAccess]); } } } let mutations = { arguments: new Array(call.arguments.length) }; for (let [i, arg] of call.arguments.entries()) { mutations.arguments[i] = null; } if (exprSmybol?.getName() == "max" || exprSmybol?.getName() == "min") { let exprSig2 = ctx.checker.getResolvedSignature(call); if (exprSig2 && exprSig2.parameters.length == 2) { let skip = false; let unbalanced = false; let singleArg = -1; let targetLength = 0; let targetType = ""; for (let [i, arg] of call.arguments.entries()) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeStr = translateType(ctx.checker, argType); let argTypeInfo = getWGSLTypeInfo(argTypeStr); if (argTypeInfo.length === 1) { if (unbalanced) { skip = true; } unbalanced = true; singleArg = i; } } for (let [i, arg] of call.arguments.entries()) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeStr = translateType(ctx.checker, argType); let argTypeInfo = getWGSLTypeInfo(argTypeStr); if (argTypeInfo.length !== 1) { targetLength = argTypeInfo.length; targetType = argTypeInfo.elementType; } } if (!skip && unbalanced && singleArg !== -1) { mutations.arguments[singleArg] = s([ `vec${targetLength}<${targetType}>(`, c2(call.arguments[singleArg]), `)` ]); } } } let funcName = c2(call.expression); let callArgs = []; let preArgs = []; let exprSig = ctx.checker.getResolvedSignature(call); let exprDeclar = exprSig.getDeclaration(); if (exprDeclar) { if (ts.isMethodDeclaration(exprDeclar)) { let isStatic2 = false; if (ts.canHaveModifiers(exprDeclar)) { let mods = ts.getModifiers(exprDeclar); if (mods) { if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) { isStatic2 = true; } } } if (!isStatic2) { if (ts.isPropertyAccessExpression(call.expression)) { preArgs.push(c2(call.expression.expression)); } } } } exprSmybol.getName() + "("; for (let [i, arg] of call.arguments.entries()) { let argStr = c2(arg); if (exprSig) { let p = exprSig.getTypeParameterAtPosition(i); if (p) { let translatedBase = translateType(ctx.checker, p); let translatedPass = translateType(ctx.checker, ctx.checker.getTypeAtLocation(arg)); if (isTranslatedTypeNameVectorOrScalar(translatedPass)) { if (translatedBase != translatedPass && isGLSLType(translatedBase)) { if (translatedBase == "vector2" || translatedBase == "vector3" || translatedBase == "vector4") { argStr = argStr; } else { argStr = s([`${translatedBase}(`, argStr, `)`]); } } } } else { translateType(ctx.checker, ctx.checker.getTypeAtLocation(arg)); } } if (ts.isArrowFunction(arg)) { let arrow2 = arg; let vars = getClosureVars(ctx.checker, arrow2.body); if (vars.length > 0) callArgs.push(vars.map((v) => v.escapedName).join(", ")); } else { let augs = augmentArgument(ctx, arg); if (augs.length > 0) { argStr = s([argStr, ",", ...join(augs, ",")]); } callArgs.push(argStr); } } const levelCalls = { mix: true }; const constructs = { "vec2": true, "vec3": true, "vec4": true, "vec2": true, "vec3": true, "vec4": true, "vec2": true, "vec3": true, "vec4": true, "mat2x2": true, "mat3x3": true, "mat4x4": true, "mat2x2": true, "mat3x3": true, "mat4x4": true }; if (exprSmybol) { let mapping = findSignatureMappingToWGSL(ctx.checker, exprSmybol); if (mapping !== null) { let levelCastArguments = mapping.startsWith("!") || (levelCalls[mapping] ?? false) || (constructs[mapping] ?? false); if (levelCastArguments) { let minType = ""; let noOp = false; for (let arg of call.arguments) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeName = translateType(ctx.checker, argType); if (!(argTypeName == "f32" || argTypeName.endsWith("") || argTypeName == "i32" || argTypeName.endsWith(""))) { noOp = true; } if (minType == "") { if (argTypeName == "f32" || argTypeName.endsWith("")) { minType = "f32"; } else if (argTypeName == "i32" || argTypeName.endsWith("")) { minType = "i32"; } } else if (argTypeName == "f32" || minType.endsWith("")) { minType = "f32"; } } if (constructs[mapping]) { noOp = false; if (mapping.endsWith("")) { minType = "f32"; } else if (mapping.endsWith("")) { minType = "i32"; } } if (!noOp) { for (let i = 0; i < callArgs.length; i++) { let arg = call.arguments[i]; let argType = ctx.checker.getTypeAtLocation(arg); let argTypeName = translateType(ctx.checker, argType); let argTypeStripped = ""; if (argTypeName == "f32" || argTypeName.endsWith("")) { argTypeStripped = "f32"; } else if (argTypeName == "i32" || argTypeName.endsWith("")) { argTypeStripped = "i32"; } if (argTypeStripped != minType) { if (argTypeName.startsWith("f32") || argTypeName.startsWith("i32")) { callArgs[i] = s([`${minType}(`, callArgs[i], `)`]); } else if (argTypeName.endsWith("") || argTypeName.endsWith("")) { let len = argTypeName.match(/\d+/)?.[0]; if (len === void 0) { throw new Error("Invalid type"); } callArgs[i] = s([`vec${len}<${minType}>(`, callArgs[i], `)`]); } else ; } } } } else { let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration()); sig = exprSig; for (let i = 0; i < callArgs.length; i++) { let arg = call.arguments[i]; let argType = ctx.checker.getTypeAtLocation(arg); let paramType = ctx.checker.getTypeAtLocation( sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0] ); paramType = sig.getTypeParameterAtPosition(Math.min(i, sig.parameters.length - 1)) ?? paramType; let carg = c2(arg); let augs = augmentArgument(ctx, arg); if (augs.length > 0) { carg = s([carg, ",", ...join(augs, ",")]); } callArgs[i] = autoCastNumeric( carg, translateType(ctx.checker, argType), translateType(ctx.checker, paramType), arg ); } } if (mapping.startsWith("!")) { let template = mapping.slice(1); let outs = []; let argCounter = 0; let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration()); for (let i = 0; i < callArgs.length; i++) { let paramType = ctx.checker.getTypeAtLocation( sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0] ); template = template.replace( "`" + argCounter + "`", ctx.checker.typeToString(paramType) ); argCounter++; } let result = template.split("$"); for (let r of result) { if (/^\d+$/.test(r)) { outs.push(callArgs[parseInt(r)]); } else if (/^\[\d+\]$/.test(r)) { let templateType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.typeArguments[parseInt(r.slice(1, -1))]) ); outs.push(templateType); } else if (r == "self") { if (call.expression.kind == ts.SyntaxKind.PropertyAccessExpression) { let propAccess = call.expression; outs.push(c2(propAccess.getChildAt(0))); } else { outs.push(c2(call.expression)); } } else { outs.push(r); } } return s(outs); } else if (mapping.startsWith("#")) { let typeName = ""; if (call.arguments.length > 0) { let firstArg = call.arguments[0]; let firstArgType = ctx.checker.getTypeAtLocation(firstArg); typeName = ctx.checker.typeToString(firstArgType); } return s([ new SourceNode(call.expression.getStart(), call.expression.getEnd(), [ mapping.substring(1) + typeName ]), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } else { for (let [i, mutation] of mutations.arguments.entries()) { if (mutation) { callArgs[i] = mutation; } } return s([ new SourceNode(call.expression.getStart(), call.expression.getEnd(), [mapping]), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } else { let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration()); for (let i = 0; i < callArgs.length; i++) { let arg = call.arguments[i]; let argType = ctx.checker.getTypeAtLocation(arg); let paramType = ctx.checker.getTypeAtLocation(sig.parameters[i].getDeclarations()[0]); let carg = c2(arg); let augs = augmentArgument(ctx, arg); if (augs.length > 0) { carg = s([carg, ",", ...join(augs, ",")]); } callArgs[i] = autoCastNumeric( carg, translateType(ctx.checker, argType), translateType(ctx.checker, paramType), arg ); } } if (exprSmybol.declarations[0].parent) { let param2 = exprSmybol.declarations[0]; if (ts.isParameter(param2)) ; } let funcDeclar = exprSmybol.valueDeclaration; if (exprSmybol.declarations[0].parent) { let param2 = exprSmybol.declarations[0]; if (ts.isParameter(param2)) { let indexOf2 = param2.parent.parameters.indexOf(param2); let additionalArgs = []; if (ctx.composed) { let realAnonymousFunc = ctx.composed.arguments[indexOf2]; if (ts.isArrowFunction(realAnonymousFunc)) { let vars = getClosureVars(ctx.checker, realAnonymousFunc.body); additionalArgs = vars.map((v) => v.escapedName); callArgs.push(...additionalArgs); return s([ funcName, "_composed_", realAnonymousFunc.pos.toString(), "_arg_", indexOf2.toString(), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } } } if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { funcName = new SourceNode( call.expression.getStart(), call.expression.getEnd(), resolveFunctionName(funcDeclar) ); let parentDeclar = closest(ast, (n3) => ts.isFunctionDeclaration(n3)); if (parentDeclar && ts.isFunctionDeclaration(parentDeclar)) ; if (isComposedFunction(ctx.checker, funcDeclar)) { return s([ funcName, "_composed_", call.pos.toString(), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } } for (let [i, mutation] of mutations.arguments.entries()) { if (mutation) { callArgs[i] = mutation; } } return s([funcName, "(", ...join([...preArgs, ...callArgs], ", "), ")"]); case ts.SyntaxKind.NewExpression: let newExpr = ast; let newExprSymbol = getSymbolAtLocationAndFollowAliases(ctx.checker, newExpr.expression); let args = []; if (newExpr.arguments?.length == 1 && ts.isObjectLiteralExpression(newExpr.arguments[0])) { let object = newExpr.arguments[0]; let props = object.properties; let sortedPropsByKey = []; let structProps = []; newExprSymbol?.members?.forEach((v, k) => { let decl2 = v.valueDeclaration; if (decl2 && ts.isPropertyDeclaration(decl2)) { const typeStr = translateType(ctx.checker, ctx.checker.getTypeAtLocation(decl2)); if (typeStr.startsWith("atomic<")) { return; } structProps.push([k?.toString() ?? "", decl2.type]); } }); sortedPropsByKey = structProps.sort((a, b) => { return a[0].localeCompare(b[0]); }); args = [ ...sortedPropsByKey.map((p) => { let prop2 = props.find((p2) => { if (ts.isPropertyAssignment(p2)) { return p2.name.getText() == p[0]; } else if (ts.isShorthandPropertyAssignment(p2)) { return p2.name.getText() == p[0]; } else { return false; } }); if (prop2) { if (ts.isPropertyAssignment(prop2)) { let propType = ctx.checker.getTypeAtLocation(p[1]); let propValType = ctx.checker.getTypeAtLocation(prop2.initializer); let propTypeStr = translateType(ctx.checker, propType); let propValTypeStr = translateType(ctx.checker, propValType); if (propTypeStr != propValTypeStr) { return s([ "/* ", p[0], ": */ ", autoCastNumeric(c2(prop2.initializer), propValTypeStr, propTypeStr, prop2), "\n" ]); } else { return s(["/* ", p[0], ": */ ", c2(prop2.initializer), "\n"]); } } else if (ts.isShorthandPropertyAssignment(prop2)) { return s(["/* ", p[0], ": */ ", c2(prop2.name), "\n"]); } else { return s(["/* ", c2(prop2), ": */ ", "\n"]); } } else { return s(["/* ", p[0], ": */ ", generateDefaultForType$1(ctx.checker, p[1]), "\n"]); } }) ]; } let decl = ctx.checker.getTypeAtLocation(newExpr.expression).getSymbol()?.getDeclarations(); if (decl && ts.isClassDeclaration(decl[0])) { return s(["_make_struct_", resolveStructName(decl[0]), "(\n", ...join(args, ", "), "\n)"]); } else { return s(["/*", ...join(args, ", "), "*/"]); } case ts.SyntaxKind.ExpressionStatement: let expr = ast; return s([c2(expr.expression), ";\n"]); case ts.SyntaxKind.ObjectLiteralExpression: let obj = ast; return s([ "{", ...join( obj.properties.map((p) => { if (ts.isPropertyAssignment(p)) { return s([c2(p.name), ": ", c2(p.initializer)]); } else if (ts.isShorthandPropertyAssignment(p)) { return s([c2(p.name)]); } else { return s(["/*", c2(p), "*/"]); } }), ", " ), "}" ]); case ts.SyntaxKind.ConditionalExpression: let cond = ast; let left = c2(cond.whenTrue); let right = c2(cond.whenFalse); let leftType = ctx.checker.getTypeAtLocation(cond.whenTrue); let rightType = ctx.checker.getTypeAtLocation(cond.whenFalse); if (isVector(ctx.checker, leftType) && isVector(ctx.checker, rightType) || isNumeric(ctx.checker, leftType) && isNumeric(ctx.checker, rightType)) { let leftTypeStr = translateType(ctx.checker, leftType); let rightTypeStr = translateType(ctx.checker, rightType); let leftTypeInfo = getWGSLTypeInfo(leftTypeStr); let rightTypeInfo = getWGSLTypeInfo(rightTypeStr); if (leftTypeInfo.elementType == "f32") { right = autoCastNumeric( right, translateType(ctx.checker, rightType), translateType(ctx.checker, leftType), cond ); } if (rightTypeInfo.elementType == "f32") { left = autoCastNumeric( left, translateType(ctx.checker, leftType), translateType(ctx.checker, rightType), cond ); } } return s(["select(", right, ", ", left, ", ", c2(cond.condition), ")"]); case ts.SyntaxKind.Identifier: let id = ast; if (ts.isIdentifier(id)) { let sym = ctx.checker.getSymbolAtLocation(id); if (sym && sym.flags & ts.SymbolFlags.Alias) { sym = ctx.checker.getAliasedSymbol(sym); } if (sym?.declarations?.length == 1) { let decl2 = sym.declarations[0]; if (isUniformable(ctx.checker, decl2)) { if (isVariableDeclarationValue(ctx.checker, decl2)) { if (!isInSameScope(decl2, ast)) { if (!isInShader$1(decl2)) { if (ts.isBinaryExpression(ast.parent)) { if (ast.parent.left == ast) { throw new GLSLCompilationError( `Cannot assign to variable '${id.text.toString()}' because it is not declared in the shader`, ast ); } } let _type = ctx.checker.getTypeAtLocation(decl2); let translated = translateType(ctx.checker, _type); let isGlobalVar = isRootNode(decl2); let glslVarName = `${!isSpecialUniformType(translated) ? "_in_uniforms." : ""}_ext_uniform_${isGlobalVar ? "global" : "local"}_${id.text.toString()}`; return s([glslVarName]); } else { return s([escapeIdentifier(id.text.toString())]); } } } } } return s([escapeIdentifier(id.text.toString())]); } else { return c2(id.expression); } case ts.SyntaxKind.PropertyAccessExpression: let prop = ast; let isStaticMember = isStaticPropertyAccessExpression(ctx.checker, prop); if (isStaticMember) { return s([c2(prop.expression), "_static_", c2(prop.name)]); } else { let propName = prop.name.getText(); if (propName == "__index") { return s([c2(prop.expression)]); } else if (propName == "size") { let innerType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(prop.expression) ); if (innerType == "sampler") { return s(["vec2(textureDimensions(", c2(prop.expression), "_texture))"]); } } else { return s([c2(prop.expression), ".", c2(prop.name)]); } } case ts.SyntaxKind.ThisKeyword: return s(["_this"]); case ts.SyntaxKind.FirstLiteralToken: let lit = ast; return s([lit.text]); case ts.SyntaxKind.IfStatement: let ifStmt = ast; if (isIdentifier(ifStmt.expression)) { if (ifStmt.expression.escapedText == "PLATFORM_WEBGPU") { return s([c2(ifStmt.thenStatement)]); } if (ifStmt.expression.escapedText == "PLATFORM_WEBGL") { if (ifStmt.elseStatement) { return s([c2(ifStmt.elseStatement)]); } else { return s([""]); } } } let addBraces = false; if (!ts.isBlock(ifStmt.thenStatement)) { addBraces = true; } return s([ "if (", c2(ifStmt.expression), `) ${addBraces ? "{" : ""} `, c2(ifStmt.thenStatement), `${addBraces ? "}" : ""} `, ifStmt.elseStatement ? s(["else \n", c2(ifStmt.elseStatement), "\n"]) : s([""]) ]); case ts.SyntaxKind.TrueKeyword: return s(["true"]); case ts.SyntaxKind.FalseKeyword: return s(["false"]); case ts.SyntaxKind.PostfixUnaryExpression: let post = ast; return s([c2(post.operand), post.operator == ts.SyntaxKind.PlusPlusToken ? "++" : "--"]); case ts.SyntaxKind.PlusPlusToken: return s(["++"]); case ts.SyntaxKind.MinusMinusToken: return s(["--"]); case ts.SyntaxKind.ParenthesizedExpression: let paren = ast; return s(["(", c2(paren.expression), ")"]); case ts.SyntaxKind.VariableDeclarationList: let varDeclList = ast; if (varDeclList.declarations.length > 0) { for (let decl2 of varDeclList.declarations) { let varDecl2 = decl2; let type22 = ctx.checker.getTypeAtLocation(varDecl2); let translated = translateType(ctx.checker, type22); let postType = ": " + translated; if (translated == "___atomic_compare_exchange_result") { postType = ""; } return s(["var ", varDecl2.name.getText(), postType, " = ", c2(varDecl2.initializer)]); } } else { return s([""]); } case ts.SyntaxKind.ForStatement: let forStmt = ast; return s([ "for (", c2(forStmt.initializer), ";", c2(forStmt.condition), ";", c2(forStmt.incrementor), ")", c2(forStmt.statement) ]); case ts.SyntaxKind.BinaryExpression: let bin = ast; let binExprText = bin.operatorToken.getText(); if (binExprText == "===") { binExprText = "=="; } if (bin.operatorToken.kind == ts.SyntaxKind.EqualsToken) { let leftType2 = ctx.checker.getTypeAtLocation(bin.left); let rightType2 = ctx.checker.getTypeAtLocation(bin.right); if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) { let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2); let [rightElementType, rightElementSize] = getVectorElementType(ctx.checker, rightType2); if (leftElementType != rightElementType) { if (leftElementType == "float" && rightElementType == "int") { return s([c2(bin.left), ` = vec${leftElementSize}f(`, c2(bin.right), ")"]); } else if (leftElementType == "int" && rightElementType == "float") { return s([c2(bin.left), ` = vec${leftElementSize}i(`, c2(bin.right), ")"]); } } } if (isNumeric(ctx.checker, leftType2) && isNumeric(ctx.checker, rightType2)) { let leftTypeStr = translateType(ctx.checker, leftType2); let rightTypeStr = translateType(ctx.checker, rightType2); if (leftTypeStr != rightTypeStr) { return s([ c2(bin.left), ` = `, autoCastNumeric(c2(bin.right), rightTypeStr, leftTypeStr, bin) ]); } } if (isUniformAccess(ctx, bin.left)) { if (translateType(ctx.checker, ctx.checker.getTypeAtLocation(bin.left)) == "bool") { return s([c2(bin.left), " = select(0, 1, ", c2(bin.right), ")"]); } } return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]); } return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]); case ts.SyntaxKind.StringLiteral: return s(["0"]); case ts.SyntaxKind.ArrayLiteralExpression: let arr = ast; return s([ "array(", ...join( arr.elements.map((e) => c2(e)), ", " ), ")" ]); case ts.SyntaxKind.ElementAccessExpression: let elem = ast; let t = ctx.checker.getTypeAtLocation(elem.expression); let n2 = getTypeFallback$1(ctx.checker, t); let postfix = ""; if (n2 === "Array" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = t; let args2 = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef); let translated = translateType(ctx.checker, args2[0]); let typeInfo = getWGSLTypeInfo(translated); args2.length; if (typeInfo.needsAlignment) { translated = `vec4<${typeInfo.elementType ?? "f32"}>`; } let lengths = { 1: "x", 2: "xy", 3: "xyz", 4: "xyzw" }; postfix = `.${lengths[typeInfo.length ?? 1]}`; } return s([c2(elem.expression), "[", c2(elem.argumentExpression), "]", postfix]); case ts.SyntaxKind.Block: let block = ast; return s([ "{\n", ...join( block.statements.map((child) => c2(child)), ";" ), "\n}" ]); case ts.SyntaxKind.TypeOfExpression: return s(["0"]); case ts.SyntaxKind.WhileStatement: let whileStmt = ast; return s(["while (", c2(whileStmt.expression), ") ", c2(whileStmt.statement)]); default: throw new GLSLCompilationError(`Invalid shader syntax '${ast.getText()}'`, ast); } } function getClosureVars(checker, func) { let result = []; let recur = (node2) => { if (node2.kind == ts.SyntaxKind.Identifier) { let id = node2; let symbol = checker.getSymbolAtLocation(id); let declar = symbol.valueDeclaration; if (isVariableDeclarationValue(checker, declar)) { if (declar) { if (!isInSameScope(declar, node2) && isInShader$1(declar)) { result.push(symbol); } } } } else { node2.forEachChild(recur); } }; recur(func); return result; } function getDeclarationType(checker, node2) { return node2.type ? checker.getTypeAtLocation(node2.type) : node2.initializer ? checker.getTypeAtLocation(node2.initializer) : checker.getTypeAtLocation(node2); } function isArrayType$1(type2, checker) { return checker.isTupleType(type2) || checker.isArrayType(type2); } class WGSLShader { constructor(key, source) { this.globals = []; this.locals = []; this.attributeInput = ""; this.attributeOutput = ""; this.key = key; this.source = source; } } function resolveFunctionName(f) { if (ts.isMethodDeclaration(f)) { let parentName = "anon"; if (f.parent && ts.isClassDeclaration(f.parent)) { parentName = f.parent.name?.text ?? "anon"; } return removeDoubleUnderscores( `fn_${f.getSourceFile()?.fileName.replaceAll("/", "_").replaceAll(".", "_") ?? "anon"}_${f.getStart()}_${parentName}_static_${f.name.getText() ?? "unknown"}` ); } else { return removeDoubleUnderscores( `fn_${f.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${f.getStart()}_${f.name?.text.replaceAll(".", "_dot_") ?? "unknown"}` ); } } function resolveStructName(c2) { if (c2.name?.text == "ShaderInput") return "ShaderInput"; if (c2.name?.text == "ShaderOutput") return "ShaderOutput"; return removeDoubleUnderscores( `str_${c2.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${c2.getStart()}_${c2.name?.text ?? "unknown"}`.replaceAll("__", "_i_") ); } function isInSameScope(node2, other) { return closest(node2, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }) == closest(other, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }); } function isInShader$1(node2) { return closest(node2, (node22) => { if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) { if (hasShadeupDocTag(node22, "shader")) { return true; } } return false; }); } function isInRoot(node2) { let c2 = closest(node2, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22) || ts.isSourceFile(node22)) { return true; } }); return c2 ? ts.isSourceFile(c2) : false; } function isRootNode(node2) { let parentRoot = closest(node2, (node22) => { if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }); return parentRoot && ts.isSourceFile(parentRoot); } function isComposedFunction(checker, func) { let isComposed = false; func.parameters.forEach((param) => { let type2 = checker.getTypeAtLocation(param); if (type2.getCallSignatures().length > 0) { isComposed = true; } }); return isComposed; } function resolveDeps(checker, root, table = { graph: /* @__PURE__ */ new Map(), functions: /* @__PURE__ */ new Map(), structs: /* @__PURE__ */ new Map(), structsProps: /* @__PURE__ */ new Map(), globals: /* @__PURE__ */ new Map(), composed: /* @__PURE__ */ new Map() }) { function resolveFunction(f1, f2, call) { let n1 = f1 ? resolveFunctionName(f1) : "main"; let n2 = resolveFunctionName(f2); if (f2.name?.getText() === "__index" || f2.name?.getText() === "__index_assign" || f2.name?.getText() === "__index_assign_op" || f2.name?.getText() === "len" || f2.name?.getText() === "sample" || f2.name?.getText() === "atomic" || hasShadeupDocTag(f2, "noemit_gpu")) return; if (isComposedFunction(checker, f2)) { n2 = n2 + "_composed_" + call.pos; table.composed.set(n2, call); } let deps = table.graph.get(n1) ?? []; if (!deps.includes(n2)) deps.push(n2); table.graph.set(n1, deps); table.functions.set(n2, f2); } function resolveStruct(decl, fullStruct = false) { let name = resolveStructName(decl); if (decl.name?.text == "atomic_internal") { return; } if (table.structs.has(name)) { if (!fullStruct) { return; } } let props = table.structsProps.get(name) ?? /* @__PURE__ */ new Set(); for (let member of decl.members) { if (ts.isPropertyDeclaration(member)) { let type2 = checker.getTypeAtLocation(member); resolveTypeUse(type2, member); if (fullStruct) { props.add(member.name.getText()); } } } if (fullStruct) { table.structsProps.set(name, props); } table.structs.set(name, decl); } function isValidShaderType(type2, checker2) { let symbol = type2.aliasSymbol || type2.getSymbol(); let name = checker2.typeToString(type2); let bases = type2.getBaseTypes(); if (bases && bases.length > 0) { for (let base of bases) { if (!isValidShaderType(base, checker2)) return false; } } if (TYPE_BLACKLIST.includes(symbol?.getName() ?? "")) { return false; } return !TYPE_BLACKLIST.includes(name); } function resolveTypeUse(typeNode, context2, fullStruct = false) { let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); if (TYPE_BLACKLIST.includes(symbol?.getName() ?? "")) { throw new GLSLCompilationError( `Type '${symbol?.getName()}' is not supported in shaders`, context2 ); } let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { resolveStruct(decl, fullStruct); } let typestr = checker.typeToString(typeNode); if (typeNode.aliasTypeArguments) for (let args of typeNode.aliasTypeArguments) { resolveTypeUse( args, context2, typestr.startsWith("buffer<") || typestr.startsWith("buffer_internal<") ); } } function resolvePropertyAccess(node2) { let typeNode = checker.getTypeAtLocation(node2.expression); let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); checker.typeToString(typeNode); if (!isValidShaderType(typeNode, checker)) { throw new GLSLCompilationError( `Type '${symbol?.getName()}' is not supported in shaders`, node2 ); } let full = checker.getTypeAtLocation(node2).getCallSignatures().length > 0; resolveTypeUse(typeNode, node2, full); resolveTypeUse(checker.getTypeAtLocation(node2), node2); let prop = node2.name.getText(); let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { let name2 = resolveStructName(decl); let props = table.structsProps.get(name2) ?? /* @__PURE__ */ new Set(); props.add(prop); table.structsProps.set(name2, props); } } walkNodes$1(root, (node2) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; exprSmybol.valueDeclaration; if (ts.isPropertyAccessExpression(node2.expression)) { resolveTypeUse( checker.getTypeAtLocation(node2.expression.expression), node2.expression.expression ); } if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let mapping = findSignatureMappingToWGSL(checker, exprSmybol); if (mapping === null) { let parentDeclar = closest( node2, (n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) || ts.isArrowFunction(n) ); if (parentDeclar && ts.isArrowFunction(parentDeclar)) { let parentParentDeclar = closest(parentDeclar, (n) => ts.isCallExpression(n)); if (parentParentDeclar && ts.isCallExpression(parentParentDeclar)) { let parentParentSymbol = checker.getSymbolAtLocation(parentParentDeclar.expression); if (parentParentSymbol && parentParentSymbol.flags & ts.SymbolFlags.Alias) { parentParentSymbol = checker.getAliasedSymbol(parentParentSymbol); } if (parentParentSymbol) { let parentParentFuncDeclar = parentParentSymbol.getDeclarations()?.[0]; if (parentParentFuncDeclar && (ts.isFunctionDeclaration(parentParentFuncDeclar) || ts.isMethodDeclaration(parentParentFuncDeclar))) { resolveFunction(parentParentFuncDeclar, funcDeclar, node2); } } } } else if (parentDeclar && (ts.isFunctionDeclaration(parentDeclar) || ts.isMethodDeclaration(parentDeclar))) { resolveFunction(parentDeclar, funcDeclar, node2); } else { resolveFunction(null, funcDeclar, node2); } if (!table.graph.has(resolveFunctionName(funcDeclar))) { table.graph.set(resolveFunctionName(funcDeclar), []); resolveDeps(checker, funcDeclar, table); } let sig = checker.getSignatureFromDeclaration(funcDeclar); let returnType = checker.getReturnTypeOfSignature(sig); resolveTypeUse(returnType, node2); } } } } if (ts.isNewExpression(node2)) { resolveTypeUse(checker.getTypeAtLocation(node2), node2.expression, true); } if (ts.isPropertyAccessExpression(node2)) { resolvePropertyAccess(node2); } if (ts.isIdentifier(node2)) { let type2 = checker.getTypeAtLocation(node2); resolveTypeUse(type2, node2); if (checker.getSymbolAtLocation(node2)) { let decl = checker.getSymbolAtLocation(node2)?.declarations; if (decl && ts.isVariableDeclaration(decl[0])) { if (!isInSameScope(decl[0], node2) && decl[0].getSourceFile().fileName !== root.getSourceFile().fileName) { if (isVariableDeclarationValue(checker, decl[0])) { table.globals.set(node2.text.toString(), decl[0]); } } } } } if (ts.isVariableDeclaration(node2)) { let type2 = checker.getTypeAtLocation(node2); resolveTypeUse(type2, node2); } }); return table; } function resolveUniforms(checker, root) { let uniforms = []; walkNodesWithCalls(checker, root, (node2) => { if (ts.isIdentifier(node2)) { let decl = checker.getSymbolAtLocation(node2); if (decl && decl.flags & ts.SymbolFlags.Alias) { decl = checker.getAliasedSymbol(decl); } if (decl && decl.declarations && decl.declarations.length == 1) { let declNode = decl.declarations[0]; if (declNode) { if (isVariableDeclarationValue(checker, declNode)) { if (!isInSameScope(declNode, node2) && !isInShader$1(declNode)) { let indexAssign = false; let indexRead = false; let sampler = false; let parent = node2.parent; if (parent && ts.isPropertyAccessExpression(parent)) { if (parent.expression == node2) { if (parent.name.getText() == "__index_assign") { indexAssign = true; } if (parent.name.getText() == "__index") { indexRead = true; if (parent.parent && parent.parent.parent && ts.isPropertyAccessExpression(parent.parent.parent)) { if (parent.parent.parent.parent && ts.isBinaryExpression(parent.parent.parent.parent) && parent.parent.parent.parent.left == parent.parent.parent) { if (parent.parent.parent.parent.operatorToken.kind == ts.SyntaxKind.EqualsToken) { indexAssign = true; } } if (parent.parent.parent.parent && ts.isPropertyAccessExpression(parent.parent.parent.parent)) { let propType = checker.getTypeAtLocation(parent.parent.parent); let translatedPropType = translateType(checker, propType); if (translatedPropType.startsWith("atomic<")) { if (parent.parent.parent.parent.name.getText() != "read") { indexAssign = true; } else { indexRead = true; } } } } } if (parent.name.getText() == "sample") { sampler = true; } } } let idx = uniforms.findIndex((d) => d.declaration === declNode); if (idx == -1) { let translated = translateType(checker, checker.getTypeAtLocation(declNode)); if (translated.includes("atomic<")) { indexAssign = true; } uniforms.push({ declaration: declNode, usesIndexAssign: indexAssign, usesIndexRead: indexRead, usesSampler: sampler }); } else { uniforms[idx].usesIndexAssign = uniforms[idx].usesIndexAssign || indexAssign; uniforms[idx].usesIndexRead = uniforms[idx].usesIndexRead || indexRead; uniforms[idx].usesSampler = uniforms[idx].usesSampler || sampler; } } } } } } }); return uniforms; } function isVariableDeclarationValue(checker, node2) { try { if (ts.isVariableDeclaration(node2) || ts.isParameter(node2)) { let type2 = checker.getTypeAtLocation(node2); let calls = type2.getCallSignatures(); if (calls.length != 0) { if (type2.aliasSymbol) { if (type2.aliasSymbol.getName() == "shader") { return true; } } } return calls.length == 0; } else { return false; } } catch (e) { return false; } } function isUniformable(checker, decl) { let exprSmybol = checker.getSymbolAtLocation(decl); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { exprSmybol.getDeclarations()?.[0]; } return ts.isVariableDeclaration(decl) || ts.isParameter(decl); } function isValidStructType(checker, type2) { let t = translateType(checker, type2); return t != "sampler"; } function addWGSLShader(key, root, checker, env2, isComputeShader = false, computeShaderSize = [1, 1, 1]) { let deps = resolveDeps(checker, root); let uniforms = resolveUniforms(checker, root); let mapping = [...deps.graph.entries()].map(([k, v]) => v.map((d) => [k, d])).flat(); let sorted = []; try { sorted = toposort(mapping).reverse(); } catch (e) { sorted = []; } let preFuncs = []; for (let s of deps.structs.values()) { let name = resolveStructName(s); let hasAnyProperty = false; let sp = deps.structsProps.get(name); let members = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; let type2 = checker.getTypeAtLocation(m); let translated = translateType(checker, type2); if (translated == "bool") { translated = "i32"; } let preComment = ""; if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { preComment = `// `; } } if (!isValidStructType(checker, type2)) { preComment = `// `; } if (preComment == "") { hasAnyProperty = true; } return new SourceNode( m.getStart(), m.getEnd(), `${preComment} ${isAlignable(translated) ? "@align(16) " : ""} ${escapeIdentifier( m.name.getText() )}: ${translated}, ` ); }); s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; let type2 = checker.getTypeAtLocation(m); let translated = translateType(checker, type2); if (translated == "bool") { translated = "i32"; } let preComment = ""; if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { preComment = `// `; } } if (preComment == "") { hasAnyProperty = true; } return new SourceNode( m.getStart(), m.getEnd(), `${preComment} ${escapeIdentifier(m.name.getText())}: ${translated}, ` ); }); let hasAtomic = false; let memberNames = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ["", ""]; let type2 = checker.getTypeAtLocation(m); let translated = translateType(checker, type2); if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { return ["", ""]; } } if (translated.startsWith("atomic<")) { hasAtomic = true; } return [escapeIdentifier(m.name.getText()), translated, m]; }).filter((m) => m[0] != "").filter((m) => { return isValidStructType(checker, checker.getTypeAtLocation(m[2])); }).sort((a, b) => { return a[0].localeCompare(b[0]); }); if (!hasAnyProperty) continue; if (name == "ShaderInput" || name == "ShaderOutput") { members.push(new SourceNode(s.getStart(), s.getEnd(), ["// %SHADER_" + name + "%"])); } preFuncs.push( new SourceNode(s.getStart(), s.getEnd(), [`struct ${name} { `, ...members, "\n};\n"]) ); if (name != "ShaderInput" && name != "ShaderOutput") { if (!hasAtomic) { preFuncs.push( new SourceNode(s.getStart(), s.getEnd(), [ "fn _make_struct_" + name + "(", ...memberNames.map((m) => { return ` ${m[0]}: ${m[1]},`; }), ") -> ", name, " {\n", "var _s: ", name, ";\n", ...memberNames.map((m) => { if (m[1] == "bool") { return ` _s.${m[0]} = select(0, 1, ${m[0]}); `; } else { return ` _s.${m[0]} = ${m[0]}; `; } }), "\nreturn _s; \n}\n" ]) ); } } } let specialUniforms = []; preFuncs.push( new SourceNode(0, 0, ["struct _InUniformsStruct {\n/*SHADEUP_UNIFORM_STRUCT_START*/\n"]) ); let localStrs = []; let globalStrs = []; let workgroupVars = []; let checkDecl = (node2) => { let fullText = node2.getSourceFile().getFullText(); let fullStart = node2.getFullStart(); let prefix = `// @workgroup `; let mySelf = fullText.slice(fullStart - prefix.length, fullStart); if (mySelf.includes("@workgroup")) { workgroupVars.push(node2); } }; if (ts.isArrowFunction(root)) { ts.forEachChild(root.body, (node2) => { if (ts.isVariableDeclaration(node2) || ts.isVariableStatement(node2) || ts.isVariableDeclarationList) { if (ts.isVariableDeclaration(node2)) { checkDecl(node2); } else if (ts.isVariableStatement(node2)) { node2.declarationList.declarations.forEach((d) => { checkDecl(d); }); } else if (ts.isVariableDeclarationList(node2)) { for (let d of node2.declarations) { checkDecl(d); } } } }); } let globalUnis = []; let localUnis = []; for (let uniformData of uniforms) { let u = uniformData.declaration; if (isUniformable(checker, u)) { let _type = checker.getTypeAtLocation(u); let translated = translateType(checker, _type); let isGlobalVar = isRootNode(u); let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`; let isSpecial = isSpecialUniformType(translated); let pushTo = isGlobalVar ? globalStrs : localStrs; if (translated.startsWith("array")) { pushTo.push( new SourceNode(u.getStart(), u.getEnd(), ["@align(16) ", glslVarName, "_size: i32,\n"]) ); } if (translated.startsWith("atomic")) { pushTo.push( new SourceNode(u.getStart(), u.getEnd(), ["@align(16) ", glslVarName, "_dummy: u32,\n"]) ); } if (translated == "sampler") { pushTo.push( new SourceNode(u.getStart(), u.getEnd(), [ "@align(16) ", glslVarName, "_size: vec2,\n" ]) ); } if (isSpecial) { if (isGlobalVar) { globalUnis.push(uniformData); } else { localUnis.push(uniformData); } } else { pushTo.push( new SourceNode(u.getStart(), u.getEnd(), [ (isAlignable(translated) ? "@align(16) " : "") + glslVarName, ": ", translated, ",\n" ]) ); } } } specialUniforms.push(...localUnis, ...globalUnis); if (localStrs.length == 0 && globalStrs.length == 0) { preFuncs.push(new SourceNode(0, 0, ["", "dummy", ": vec4,\n"])); } else { preFuncs = [...preFuncs, ...localStrs, ...globalStrs]; } preFuncs.push(new SourceNode(0, 0, ["};\n"])); preFuncs.push( new SourceNode(0, 0, [ "@group(%GROUP_INDEX%) @binding(1) var _in_uniforms: _InUniformsStruct;\n" ]) ); let specialUniformsCounter = 2; for (let uniformData of specialUniforms) { let u = uniformData.declaration; if (isUniformable(checker, u)) { let _type = checker.getTypeAtLocation(u); let translated = translateType(checker, _type, false, true); let isGlobalVar = isRootNode(u); let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`; if (translated == "sampler" || translated.startsWith("array]+)>/g; innerTranslated = innerTranslated.replace(vecRegex, "$1"); let textureKind = "texture_2d"; let textureKindStorage = "texture_storage_2d"; if (isArrayType$1(_type, checker)) { textureKind = "texture_2d_array"; textureKindStorage = "texture_storage_2d_array"; } if (translated.startsWith("array; `, `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}: ${translated}; `, `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 2}) var ${glslVarName}_texture_write: ${textureKindStorage}<%WRITE_TYPE_${glslVarName}%, write>; ` ]) ); specialUniformsCounter += 2; } else if (uniformData.usesIndexAssign) { preFuncs.push( new SourceNode(0, 0, [ `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}_texture: ${textureKind}<${innerTranslated}>; `, `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}_texture_write: ${textureKindStorage}<%WRITE_TYPE_${glslVarName}%, write>; ` ]) ); specialUniformsCounter += 1; } else if (uniformData.usesSampler || uniformData.usesIndexRead) { preFuncs.push( new SourceNode(0, 0, [ `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}_texture: ${textureKind}<${innerTranslated}>; `, `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}: ${translated}; ` ]) ); specialUniformsCounter += 1; } } else if (translated.startsWith("atomic")) { preFuncs.push( new SourceNode(0, 0, [ `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}: ${translated}; ` ]) ); } else if (translated.startsWith("array") || translated.startsWith("buffer")) { let usageType = "read"; if (uniformData.usesIndexAssign) { usageType = "read_write"; } preFuncs.push( new SourceNode(0, 0, [ `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}: ${translated}; ` ]) ); } specialUniformsCounter++; } } for (let workgroupVar of workgroupVars) { preFuncs.push( new SourceNode(0, 0, [ `var ${escapeIdentifier(workgroupVar.name.getText())}: ${translateType( checker, checker.getTypeAtLocation(workgroupVar.type) )}; ` ]) ); } for (let k of sorted) { if (k == "main") continue; let v = deps.functions.get(k); if (v) { let sourceFile2 = v.getSourceFile(); let originalFile2 = env2.files.find((f) => f.path == sourceFile2.fileName); preFuncs.push( compile$1( { parentFunction: v, checker, composed: deps.composed.get(k) ?? null }, v, originalFile2?.mapping ) ); } } let sourceFile = root.getSourceFile(); let originalFile = env2.files.find((f) => f.path == sourceFile?.fileName); let customAttributesIn = /* @__PURE__ */ new Map(); let customAttributesOut = /* @__PURE__ */ new Map(); let main = compile$1( { checker, isComputeShader, computeSize: computeShaderSize, addCustomAttribute(type2, idx, valType, interp) { if (type2 == "in") { customAttributesIn.set(idx, [valType, interp]); } else if (type2 == "out") { customAttributesOut.set(idx, [valType, interp]); } } }, root, originalFile.mapping ); preFuncs.push(main); let source = new SourceNode(root.getStart(), root.getEnd(), preFuncs); let ss = { indexMapping: [], str: "" }; source.toString(ss); let finalShaderOutput = ss.str; let customIns = []; for (let [idx, [valType, interp]] of customAttributesIn.entries()) { customIns.push(`@location(${7 + idx}) @interpolate(${interp}) custom${idx}: ${valType}, `); } finalShaderOutput = finalShaderOutput.replace("// %SHADER_ShaderInput%\n", customIns.join("")); let customOuts = []; for (let [idx, [valType, interp]] of customAttributesOut.entries()) { customOuts.push(`@location(${7 + idx}) @interpolate(${interp}) custom${idx}: ${valType}, `); } let matches = wgslHeader.match(/fn ([^\(]+)/gm); let headerSplits = []; for (let i = 0; i < matches.length; i++) { let index = wgslHeader.indexOf(matches[i]); let toIndex = i == matches.length - 1 ? wgslHeader.length : wgslHeader.indexOf(matches[i + 1]); headerSplits.push(wgslHeader.substring(index, toIndex)); } let realHeader = ""; for (let i = 0; i < headerSplits.length; i++) { let headerText = headerSplits[i]; let fnName = headerText.match(/fn ([^\(]+)/)?.[1]; if (fnName) { if (finalShaderOutput.includes(fnName)) { realHeader += headerText; } } } finalShaderOutput = realHeader + finalShaderOutput; let output = new WGSLShader(`shd_${key}`, finalShaderOutput); output.sourceMapping = ss.indexMapping; output.attributeInput = customIns.join(""); output.attributeOutput = customOuts.join(""); for (let uniformData of uniforms) { let u = uniformData.declaration; if (isUniformable(checker, u)) { let name = u.name.getText(); let isGlobalVar = isRootNode(u); if (name) { let filterProps = function(props) { if (props && props.name) { let sp = deps.structsProps.get(props.name); let realStruct = deps.structs.get(props.name); if (props.type == "struct" && realStruct) { for (let fi = props.fields.length - 1; fi >= 0; fi--) { let f = props.fields[fi]; if (!sp || !sp.has(f[0])) { props.fields.splice(fi, 1); } else { if (f[1].type == "struct") { f[1] = filterProps(f[1]); } } } } } if (props && (props.type == "buffer" || props.type == "primitive" && props.name == "texture2d")) { if (uniformData.usesSampler && uniformData.usesIndexAssign) { props.access = "sample_write"; } else if (uniformData.usesIndexAssign) { props.access = "write"; } else if (uniformData.usesSampler) { props.access = "sample"; } else { props.access = "read"; } } else if (props && props.type == "array" && props.element.type == "primitive" && props.element.name == "texture2d") { if (uniformData.usesSampler && uniformData.usesIndexAssign) { props.element.access = "sample_write"; } else if (uniformData.usesIndexAssign) { props.element.access = "write"; } else if (uniformData.usesSampler) { props.element.access = "sample"; } else { props.element.access = "read"; } } return props; }; getDeclarationType(checker, u); let typeNode = checker.getTypeAtLocation(u); let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { resolveStructName(decl); } if (isGlobalVar) { let typeOut2 = getDeclarationType(checker, u); output.globals.push([ name, { fileName: getNodeSourceFileName(u), structure: filterProps(translateType(checker, typeOut2, true)) } ]); } else { output.locals.push([ name, filterProps(translateType(checker, getDeclarationType(checker, u), true)) ]); } } } } return output; } function isAlignable(t) { return t.startsWith("vec") || t == "f32" || t == "i32" || t == "u32"; } function isSpecialUniformType(t) { return t == "sampler" || t.startsWith("array") || t.startsWith("buffer") || t.startsWith("atomic"); } function getNodeSourceFileName(node2) { let found = closest(node2, (n) => ts.isSourceFile(n)); if (found && ts.isSourceFile(found)) { return found.fileName; } else { return ""; } } function walkNodes$1(node2, cb) { cb(node2); node2.forEachChild((n) => walkNodes$1(n, cb)); } function walkNodesWithCalls(checker, node2, cb) { cb(node2); node2.forEachChild((n) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let mapping = findSignatureMappingToWGSL(checker, exprSmybol); if (mapping === null) { if (funcDeclar.body) { walkNodesWithCalls(checker, funcDeclar.body, cb); } } } } } walkNodesWithCalls(checker, n, cb); }); } function getSymbolAtLocationAndFollowAliases(checker, node2) { let exprSmybol = checker.getSymbolAtLocation(node2); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } return exprSmybol; } function findSignatureMappingToWGSL(checker, sym) { let matcher = /=(?:wgsl|univ)\((.+)\)$/g; if (!sym.valueDeclaration) return null; let doc = ts.getJSDocTags(sym.valueDeclaration); for (let d of doc) { if (d.tagName.text !== "shadeup") continue; if (typeof d.comment === "string") { let matches = matcher.exec(d.comment); if (matches) { return matches[1]; } } } return null; } function removeDoubleUnderscores(str) { return str.replace(/__/g, "_ii"); } let rootSymbolsFromMath = [ "abs", "floor", "ceil", "round", "sign", "cos", "sin", "tan", "acos", "asin", "atan", "atan2", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "exp", "log", "pow", "log2", "log10", "sqrt", "inversesqrt", "frac", "min", "max", "step", "clamp", "saturate", "smoothstep", "lerp", "bilerp", "length", "distance", "dist", "normalize", "dot", "reflect", "refract", "cross", "degrees", "radians", "wrap", "rand", "rand2", "rand3", "float2x2", "float3x3", "float4x4", "inverse", "transpose", "pingpong", "atomic", "mod", "workgroupBarrier", "storageBarrier", "workgroupUniformLoad", "discard", "ddx", "ddy", "ddxFine", "ddyFine", "ddxCoarse", "ddyCoarse", "bitcast", "pack4x8snorm", "pack4x8unorm", "pack2x16snorm", "pack2x16unorm", "pack2x16float", "unpack4x8snorm", "unpack4x8unorm", "unpack2x16snorm", "unpack2x16unorm", "unpack2x16float" ]; let rootSymbolsFromAll = [ "print", "stat", "statGraph", "time", "compute", // 'type shader', "flush", // 'addressWorkgroup', // 'drawAlt', // 'shader_start_shd_', "globalVarInit", // 'type ShaderInput', // 'type ShaderOutput', "sleep", "__makeMap", "__deepClone", "map", "array" ]; let rootSymbolsFromDraw = [ "drawIndexed", "drawInstanced", "draw", "makeShader", "ShaderInput", "ShaderOutput", "shader", "drawAlt2", // 'drawIndexedIndirect', // 'drawInstancedIndexed', // 'drawIndirect', "drawCount", "drawAttributes", "drawAdvanced", "computeIndirect", "drawFullscreen", "shader_start_shd_" ]; let rootSymbolsFromCommon = [ "pixelToClip", "PI", "quat", "noise", "spatial", // 'mat4', "Camera", "Camera2d", "buffer", "matrix", "texture2d", "texture3d", "ui", "screenAA", "randColor", "randColor2", "hsl", "hsla", "rgb", "rgba", "hslFromColor", "hslaFromColor", "rgbFromColor", "rgbaFromColor", "hsv", "hsva", "hsvFromColor", "hsvaFromColor", "cmyk", "cmykFromColor", "hex", "hexFromColor", "sin1", "cos1", "tan1", "remap", "remap1", "color", "wrap2", "wrap3", "wrap4", "bezier" ]; let rootSymbolsFromMesh = ["mesh", "Mesh", "Model", "ModelPart", "Material"]; const header = `// This file was generated by Shadeup. import * as __ from "/std_math"; import {${rootSymbolsFromMath.join(", ")}} from "/std_math"; import {${rootSymbolsFromAll.join(", ")}, globalVarGet as __globalVarGet} from "/std___std_all"; import {${rootSymbolsFromDraw.join(", ")}} from "/_std/drawIndexed"; import { physics, PhysicsRigidBody2d, PhysicsCollider2d, PhysicsEngine2d } from "/_std/physics"; let globalVarGet = __globalVarGet; /**__SHADEUP_STRUCT_INJECTION_HOOK__*/ `; class SourceNode { constructor(startIndex, endIndex, children) { this.startIndex = startIndex; this.endIndex = endIndex; if (Array.isArray(children)) { this.children = children; } else { this.children = [children]; } } toString(s) { let start = s.str.length; for (const child of this.children) { if (typeof child === "string") { s.str += child; } else if (child instanceof SourceNode) { child.toString(s); } } s.indexMapping.push([this.startIndex, this.endIndex, start, s.str.length]); } print() { const s = { str: "", indexMapping: [] }; this.toString(s); return s.str; } } function lookupIndexMapping(indexMapping, index) { for (const [start, end, newStart, newEnd] of indexMapping) { if (index >= newStart && index <= newEnd) { return start + (index - newStart); } } return -1; } function lookupIndexMappingRange(indexMapping, start, end) { let minStart = Infinity; let maxEnd = -Infinity; let size = 0; for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) { if (start >= newStart && end <= newEnd) { if (oldEnd - oldStart < size || size === 0) { minStart = oldStart; maxEnd = oldEnd; size = oldEnd - oldStart; } } } return { start: minStart, end: maxEnd }; } function reverseLookupIndexMappingRange(indexMapping, start, end) { let minStart = Infinity; let maxEnd = -Infinity; let size = 0; for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) { if (start >= oldStart && end <= oldEnd) { if (newEnd - newStart < size || size === 0) { minStart = newStart; maxEnd = newEnd; size = newEnd - newStart; } } } return { start: minStart, end: maxEnd }; } function reverseLookupIndexMappingCursor(indexMapping, cursor) { let exact = -Infinity; let size = 0; for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) { if (cursor >= oldStart && cursor <= oldEnd) { if (newEnd - newStart < size || size === 0) { exact = cursor - oldStart + newStart; size = newEnd - newStart; } } } return exact; } function prePass(ctx, ast) { for (const child of ast.namedChildren) { if (child.type === "impl_declaration") { let _for = child.childForFieldName("for"); const name = child.childForFieldName("name"); if (_for) { ctx.addImplFor(name.text, child); } else { ctx.addImpl(name.text, child); } } if (child.type == "lexical_declaration") { let variable_declarator = child.firstNamedChild; if (variable_declarator.type == "variable_declarator") { ctx.globals.push(variable_declarator.firstNamedChild.text); } } } } const math_primitives = [ "atomic", "uint", "uint2", "uint3", "uint4", "uint8", "int", "float", "float2", "float3", "float4", "int2", "int3", "int4", "float2x2", "float3x3", "float4x4", "bool" ]; const operators = { "+": "add", "-": "sub", "*": "mul", "**": "pow", "/": "div", "%": "mod", "==": "eq", "!=": "neq", "<": "lt", "<=": "lte", ">": "gt", ">=": "gte", "&&": "and", "||": "or", "!": "not", "&": "bitand", "|": "bitor", "^": "bitxor", "<<": "lshift", ">>": "rshift", "~": "bitnot" }; const keyFunctions = { float: "__.float", int: "__.int", uint: "__.uint", uint2: "__.uint2", uint3: "__.uint3", uint4: "__.uint4", uint8: "__.uint8", float2: "__.float2", float3: "__.float3", float4: "__.float4", int2: "__.int2", int3: "__.int3", int4: "__.int4", float2x2: "__.float2x2", float3x3: "__.float3x3", float4x4: "__.float4x4" }; const escapeWords = { in: true, out: true }; function generateDefaultForType(name) { switch (name) { case "any": return "null"; case "int": return "__.int(0)"; case "uint": return "__.uint(0)"; case "uint8": return "__.uint8(0)"; case "float": return "__.float(0.0)"; case "float2": return "__.float2(0.0, 0.0)"; case "float3": return "__.float3(0.0, 0.0, 0.0)"; case "float4": return "__.float4(0.0, 0.0, 0.0, 0.0)"; case "int2": return "__.int2(0, 0)"; case "int3": return "__.int3(0, 0, 0)"; case "int4": return "__.int4(0, 0, 0, 0)"; case "float2x2": return "__.float2x2(0.0, 0.0, 0.0, 0.0)"; case "float3x3": return "__.float3x3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "float4x4": return "__.float4x4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "bool": return "false"; case "string": return '""'; case "atomic": return "atomic<__.uint>(__.uint(0))"; case "atomic": return "atomic<__.int>(__.int(0))"; default: if (name.endsWith("[]")) { return "[]"; } else if (name.endsWith("]")) { let matches = name.match(/(.+)\[(\d+)\]$/); if (matches && matches.length > 2) { let type2 = matches[1]; let count2 = matches[2]; let args = []; for (let i = 0; i < parseInt(count2); i++) { args.push(generateDefaultForType(type2)); } return "[" + args.join(",") + "]"; } else { return "[]"; } } else { if (name.startsWith("buffer") || name.startsWith("texture2d") || name.startsWith("texture3d")) { return "null"; } else { return "new " + name + "({})"; } } } } function isValidInteger(str) { let n = parseInt(str); if (n > Math.pow(2, 31) - 1 || n < -Math.pow(2, 31)) { return false; } return true; } function compile(ctx, ast) { function c2(myAst, errorMessage = "Syntax error") { if (!myAst) { console.log("error"); ctx.report(ast, errorMessage); return s(["/*", errorMessage, "*/"]); } else { return compile(ctx, myAst); } } function s(c22) { return new SourceNode(ast.startIndex, ast.endIndex, c22); } function n(type2) { return ast.childForFieldName(type2); } function flat(...c22) { return c22.reduce((acc, cur) => { return [...acc, ...cur]; }, []); } function join(c22, sep) { return c22.filter((v) => { if (typeof v == "string" && v.length == 0 || v instanceof SourceNode && v.children.length == 0) { return false; } return true; }).reduce((acc, cur) => { if (acc.length === 0) { return [cur]; } return [...acc, sep, cur]; }, []); } function children() { return ast.namedChildren.map((child) => c2(child)); } function hasName(name) { return ast.childForFieldName(name) !== null; } if (!ast) { return new SourceNode(0, 0, ["/*", "Syntax error", "*/"]); } switch (ast.type) { case "program": return s([ header, ...ctx.fileName != "file:////_std/common.ts" ? [`import {${rootSymbolsFromCommon.join(", ")}} from "/_std/common";`] : [], ...ctx.fileName != "file:////_std/mesh.ts" ? [`import {${rootSymbolsFromMesh.join(", ")}} from "/_std/mesh";`] : [], ...ctx.fileName != "file:////_std/sdf.ts" ? [`import { sdf } from "/_std/sdf";`] : [], ...ast.children.map((child) => c2(child)) ]); case "expression_statement": if (ast.firstChild) { if (ast.lastNamedChild?.type === "ERROR") { return s([c2(ast.firstNamedChild), "."]); } if (ast.firstNamedChild.type == "workgroup") { return s([c2(ast.firstNamedChild), "\n"]); } else { return s([c2(ast.firstNamedChild), ";\n"]); } } case "binary_expression": if (ast.firstChild && ast.lastChild) { if (ast.lastChild.text == "null" && (ast.children[1].text == "!=" || ast.children[1].text == "==")) { return s([c2(ast.firstChild), ast.children[1].text + "=", "null"]); } return s([ "__.", operators[ast.children[1].text.trim()] ?? ast.children[1].text.trim(), "( ", c2(ast.firstNamedChild), ", ", c2(ast.lastNamedChild), " )" ]); } case "identifier": if (keyFunctions[ast.text]) { return s([String(keyFunctions[ast.text])]); } else if (escapeWords[ast.text]) { return s([String("__" + ast.text)]); } return s([ String(ast.text === "self" ? isInShader(ast) ? "shader_self_temp" : "this" : ast.text) ]); case "number": if (ast.parent?.type == "pair" && ast.parent.firstNamedChild == ast) { return s([String(ast.text)]); } if (ast.text.match(/.[xyzwrgba]+$/)) { let swizzle = (ast.text.match(/.[xyzwrgba]+$/) ?? [""])[0]; swizzle = swizzle.replace(".", ""); let raw = ast.text.replace(/.[xyzwrgba]+$/, ""); let isUint2 = raw.indexOf("u") !== -1; let isFloat2 = raw.indexOf(".") !== -1; return s([ String( "__.swizzle(" + (isFloat2 ? "__.float" : isUint2 ? "__.uint" : "__.int") + "(" + raw.replace("u", "") + '), "' + swizzle + '")' ) ]); } let isFloat = ast.text.indexOf(".") !== -1; let isUint = ast.text.indexOf("u") !== -1; if (!isFloat && !isValidInteger(ast.text) && !isUint) { ctx.report( ast, "Invalid integer, this overflows the 32 bit integer limit, add a .0 to the end to make it a float" ); } return s([ (isFloat ? "__.float" : isUint ? "__.uint" : "__.int") + "(", new SourceNode(ast.startIndex, ast.endIndex, ast.text.replace("u", "")), ")" ]); case "string": return s([String(ast.text)]); case "function_declaration": if (ast.firstChild && ast.lastChild) { let funcName = n("name").text; let prefix = ""; if (funcName === "main") { prefix += ""; prefix += "export "; } return s([ prefix + "function ", c2(n("name")), c2(n("parameters")), ...hasName("return_type") ? [c2(n("return_type")), " "] : [], c2(n("body")), "\n" ]); } case "block": return s(children()); case "formal_parameters": return s(["(", ...join(children(), ", "), ")"]); case "required_parameter": if (n("pattern")?.text === "self") { return s([]); } return s( flat( [c2(n("pattern"))], hasName("type") ? [": ", c2(n("type"))] : [], hasName("value") ? [" = ", c2(n("value"))] : [] ) ); case "type_annotation": return s([c2(ast.firstNamedChild)]); case "type_identifier": if (math_primitives.indexOf(ast.text) !== -1) { return s([String("__." + ast.text)]); } return s([String(ast.text)]); case "predefined_type": if (math_primitives.indexOf(ast.text) !== -1) { return s([String("__." + ast.text)]); } return s([String(ast.text)]); case "function_type": return s([c2(n("parameters")), " => ", c2(n("return_type"))]); case "lookup_type": let len = parseInt(ast.lastNamedChild?.text ?? "0"); let repeats = []; for (let i = 0; i < len; i++) { repeats.push(c2(ast.firstNamedChild)); } return s(["[", ...join(repeats, ", "), "]"]); case "arrow_function": return s([ c2(n("parameters")), " => ", ...hasName("return_type") ? [c2(n("return_type")), " "] : [], c2(n("body")) ]); case "literal_type": return s([c2(ast.firstNamedChild)]); case "return_statement": if (ast.namedChildCount === 0) { return s(["return;"]); } else { if (ast.lastNamedChild?.type === "ERROR") { return s(["return ", c2(ast.firstNamedChild), "."]); } return s(["return ", c2(ast.firstNamedChild), ";"]); } case "export_statement": return s(["export ", c2(ast.firstNamedChild), ";"]); case "export_clause": return s(["{", ...join(children(), ", "), "}"]); case "export_specifier": return s([c2(ast.firstNamedChild)]); case "array": return s(["[", ...join(children(), ", "), "]"]); case "template_string": return s(["`", ...join(children(), ""), "`"]); case "template_substitution": return s(["${", c2(n("expression")), "}"]); case "template_string_segment": return s([String(ast.text)]); case "type_alias_declaration": ctx.report(ast, "Type aliases aren't supported yet"); return s(["/*error*/0"]); case "import": return s([""]); case "comment": return s([String(ast.text), "\n"]); case "call_expression": if (n("type_arguments")) { if (n("function").text == "buffer" || n("function").text == "texture2d" || n("function").text == "texture3d") { let internalArgs = s([ "(", ...join( [ ...n("arguments").namedChildren.map((chi) => c2(chi)), ...n("arguments").namedChildren.length == 1 && n("function").text == "texture2d" || n("function").text == "texture3d" ? [s(['"auto"'])] : [], s(['"', n("type_arguments").namedChild(0).text, '"']) ], ", " ), ")" ]); return s([c2(n("function")), c2(n("type_arguments")), internalArgs]); } return s([c2(n("function")), c2(n("type_arguments")), c2(n("arguments"))]); } else { return s([c2(n("function")), c2(n("arguments"))]); } case "construct_expression": return s(["new ", c2(n("identifier")), "(", c2(n("body")), ")"]); case "member_expression": let prop = n("property"); let p = prop.text ?? ""; let isParentAssignment = ast.parent?.type == "assignment_expression" || ast.parent?.type == "augmented_assignment_expression"; if (isParentAssignment) { let left2 = ast.parent.childForFieldName("left"); isParentAssignment = left2.startIndex == ast.startIndex && left2.endIndex == ast.endIndex; } if (p.length > 0 && p.length < 5) { let isSwizzle = true; for (let i = 0; i < p.length; i++) { let char = p[i]; if (char !== "x" && char !== "y" && char !== "z" && char !== "w" && char !== "r" && char !== "g" && char !== "b" && char !== "a") { isSwizzle = false; break; } } if (isSwizzle) { if (isParentAssignment) { ast.parent.childForFieldName("right"); } return s([ `__.swizzle(`, c2(n("object")), `, '`, new SourceNode(prop.startIndex, prop.endIndex, p), `'`, ...isParentAssignment ? [`, `, c2(ast.parent.childForFieldName("right"))] : [], `)` // new SourceNode(ast.children[1].startIndex, ast.children[1].endIndex, '.'), // c(n('property')!) ]); } } return s([ c2(n("object")), new SourceNode(ast.children[1].startIndex, ast.children[1].endIndex, "."), c2(n("property")) ]); case "pair": return s([c2(n("key")), ": ", c2(n("value"), "Expected value in pair")]); case "object": let childrens = ast.namedChildren.filter((subc) => subc.type !== "comment").map((subc) => c2(subc)); return s(["{", ...join(childrens, ", "), "}"]); case "property_identifier": return s([String(ast.text)]); case "arguments": return s(["(", ...join(children(), ", "), ")"]); case "parenthesized_expression": if (ast.lastNamedChild?.type === "ERROR") { return s(["(", c2(ast.firstNamedChild), ".", ")"]); } return s(["(", c2(ast.firstNamedChild), ")"]); case "function_signature": ctx.report(ast, "Missing function body"); return s(["/*error*/0"]); case "parenthesized_expression_vector": if (ast.firstNamedChild) { if (ast.firstNamedChild.type === "sequence_expression") { return s(["__.makeVector(", c2(ast.firstNamedChild), ")"]); } else { return s(["(", c2(ast.firstNamedChild), ")"]); } } case "if_statement": return s([ "if ", c2(n("condition")), c2(n("consequence")), hasName("alternative") ? c2(n("alternative")) : "" ]); case "else": return s([" else ", c2(ast.firstNamedChild), "\n"]); case "generic_type": return s([c2(n("name")), c2(n("type_arguments"))]); case "type_arguments": return s(["<", ...join(children(), ", "), ">"]); case "array_type": if (ast.namedChildCount == 2) { return s([c2(ast.firstNamedChild), "[", c2(ast.lastNamedChild), "]"]); } else { return s([c2(ast.firstNamedChild), "[]"]); } case "ternary_expression": return s([c2(n("condition")), " ? ", c2(n("consequence")), " : ", c2(n("alternative"))]); case "update_expression": return s([c2(n("argument")), n("operator").text]); case "augmented_assignment_expression": let opMapping = { "+=": "add", "-=": "sub", "*=": "mul", "/=": "div", "%=": "mod" }; let leftAssignAug = n("left"); if (leftAssignAug?.type === "subscript_expression") { return s([ c2(leftAssignAug.childForFieldName("object")), ".__index_assign_op(__.", opMapping[n("operator").text], ", ", c2(leftAssignAug.childForFieldName("index")), ", ", c2(n("right")), ")" ]); } return s([ c2(n("left")), " = __.", opMapping[n("operator").text], "(", c2(n("left")), ", ", c2(n("right")), ")" ]); case "for_statement": return s([ "for (", c2(n("initializer")), " ", c2(n("condition")), " ", c2(n("increment")), ") ", c2(n("body")) ]); case "for_in_statement": let leftFor = n("left"); let rightFor = n("right"); if (leftFor.type === "parenthesized_expression") { let forComponents = []; for (let i = 0; i < leftFor.namedChildren[0].namedChildren.length; i++) { let name = leftFor.namedChildren[0].namedChildren[i]; if (name.type != "identifier") { ctx.report( leftFor.namedChild(i), "Invalid for loop variable name, must be x, y, z or w" ); } let key2 = name.text; if (!["x", "y", "z", "w"].includes(key2)) { ctx.report( leftFor.namedChild(i), "Invalid for loop variable name, must be x, y, z or w" ); } if (forComponents.includes(key2)) { ctx.report(leftFor.namedChild(i), "Duplicate for loop variable name"); } forComponents.push(key2); } forComponents = forComponents.reverse(); let parts = []; parts.push(s(["let __for_iter = ", c2(rightFor), ";\n"])); let indexes = ["x", "y", "z", "w"]; for (let n2 of forComponents) { parts.push( s([ "for (let ", n2, ": __.int = __.int(0); ", n2, " < __for_iter[", indexes.indexOf(n2).toString(), "]; ", n2, "++) {\n" ]) ); } parts.push(s([c2(n("body")), "\n"])); for (let n2 of forComponents) { parts.push(s(["}\n"])); } return s(parts); } return s(["for (let ", c2(n("left")), " of ", c2(n("right")), ") ", c2(n("body"))]); case "while_statement": return s(["while (", c2(n("condition")), ") ", c2(n("body"))]); case "break_statement": return s(["break;"]); case "continue_statement": return s(["continue;"]); case "new_expression": return s(["new ", c2(n("constructor")), c2(n("arguments"))]); case "else_clause": return s([" else ", c2(ast.firstNamedChild), "\n"]); case "statement_block": if (ast.parent.type == "method_definition") { let recur = function(a) { if (a.type == "identifier") { if (a.text == "self") { doesRefSelf = true; } } a.children.forEach(recur); }; let doesRefSelf = false; ast.children.forEach(recur); if (doesRefSelf) { return s(["{let shader_self_temp = this;", ...children(), "}"]); } } return s(["{", ...children(), "}"]); case "import_statement": let sourceString = n("source"); let fromString = sourceString.firstNamedChild?.text; if (fromString) { if (!fromString.startsWith("/") && !fromString.startsWith("@") && !fromString.startsWith(".")) { fromString = "/" + fromString; } } return s([ "import ", ...ast.namedChildCount == 2 ? [" ", c2(ast.firstNamedChild), " from "] : [], new SourceNode(sourceString.startIndex, sourceString.endIndex, [ JSON.stringify(fromString) ]), ";" ]); case "named_imports": return s(["{", ...join(children(), ", "), "}"]); case "import_clause": return s([c2(ast.firstChild)]); case "import_specifier": return hasName("alias") ? s([c2(n("name")), " as ", c2(n("alias"))]) : c2(n("name")); case "predefined_type": return s([String(ast.text)]); case "interface_declaration": return s(["interface ", c2(n("name")), c2(n("body")), "\n"]); case "object_method_signature_type": return s(["{\n", ...children(), "\n}"]); case "method_signature": let isStaticSignature = n("parameters")?.firstNamedChild?.text != "self"; let accessibilityMethod = ast.firstNamedChild?.type === "accessibility_modifier_member" ? "public" : "private"; if (ast.parent?.type === "object_method_signature_type" && ast.parent?.parent?.type === "interface_declaration") { accessibilityMethod = ""; } return s([ accessibilityMethod, " ", ...isStaticSignature ? ["static "] : [], c2(n("name")), c2(n("parameters")), c2(n("return_type")), ";\n" ]); case "type_annotation_arrow": return s([": ", c2(ast.firstNamedChild)]); case "struct_declaration": let impls = ctx.implsFor.get(n("name").text) ?? []; let properties = n("body")?.namedChildren ?? []; properties = properties.filter((i) => { let isStatic2 = false; for (let child of i.children) { if (child.type === "static") { isStatic2 = true; } } return !isStatic2; }); let implBodies = [ ...(ctx.implsFor.get(n("name").text) ?? []).map((i) => i.childForFieldName("body")), ...(ctx.impls.get(n("name").text) ?? []).map((i) => i.childForFieldName("body")), ...properties ]; let staticProperties = n("body")?.namedChildren ?? []; staticProperties = staticProperties.filter((i) => { let isStatic2 = false; for (let child of i.children) { if (child.type === "static") { isStatic2 = true; } } return isStatic2; }); let props = properties.map((i) => ({ name: i.childForFieldName("name")?.text ?? "_unknown", type: i.childForFieldName("type")?.firstNamedChild?.text ?? "", renderedType: compileToString(ctx, i.childForFieldName("type")), default: i.childForFieldName("value") ? compileToString(ctx, i.childForFieldName("value")) : generateDefaultForType(i.childForFieldName("type")?.firstNamedChild?.text ?? "") })); let cls = s([ "/**@shadeup=struct*/class ", c2(n("name")), ...impls.length > 0 ? [ " implements ", ...join( impls.map((i) => c2(i.childForFieldName("for"))), "," ) ] : [], " {\n", ...join( staticProperties.map((i) => { return s([ "public static ", c2(i.childForFieldName("name")), ": ", c2(i.childForFieldName("type")), " = ", c2(i.childForFieldName("value")), ";\n" ]); }), "" ), `constructor(data: {`, `${props.map( (i) => `${i.name}?: ${math_primitives.includes(i.type ?? "") ? "__." + i.type : i.renderedType},` ).join("\n")}`, `}) { `, `${props.map((i) => `this.${i.name} = (data.${i.name} ?? ${i.default}) as any;`).join("\n")}`, ` } `, ...join( implBodies.map((i) => c2(i)), "\n" ), "\n", `clone(): `, c2(n("name")), ` { `, `return new `, c2(n("name")), `({ `, `${props.map((i) => { return `${i.name}: __deepClone(this.${i.name}),`; }).join("\n")}`, `}); `, `} `, "\n}", "\n" ]); return cls; case "object_method_type": return s([...children()]); case "method_definition": let isStatic = n("parameters")?.firstNamedChild?.text != "self"; return s([ ...isStatic ? ["static "] : [], c2(n("name")), c2(n("parameters")), c2(n("body")), "\n" ]); case "impl_for_clause": return s([ast.firstNamedChild.text]); case "unary_expression": let op = ast.firstChild?.text ?? ""; if (op == "-") { return s(["__.negate(", c2(n("argument")), ")"]); } else if (op == "+") { return s(["__.positive(", c2(n("argument")), ")"]); } else if (op == "!") { return s(["__.not(", c2(n("argument")), ")"]); } else { return s([c2(n("argument"))]); } case "class_body": return s(["{\n", ...children(), "\n}"]); case "public_field_definition": let accessibility = ast.firstNamedChild?.type === "accessibility_modifier_member" ? "public" : "private"; return s([accessibility, " ", c2(n("name")), ": ", c2(n("type")), ";\n"]); case "impl_declaration": return s([`/* impl ${n("name")?.text} */ `]); case "lexical_declaration": return s([...children().map((i) => s(["let ", i, ";\n"]))]); case "variable_declarator": let isRoot = ast?.parent?.parent.type === "program"; return s([ c2(n("name")), n("type") ? s([": ", c2(n("type"))]) : "", ...hasName("value") ? [ " = ", ...isRoot ? [ 'globalVarInit("' + cleanName(ctx.fileName) + '", "', c2(n("name")), '", () => { return ', c2(n("value")), "; }, () => { return ", c2(n("name")), "; })" ] : [c2(n("value"))] ] : [" = ", generateDefaultForType(n("type").text.replace(/^:/, "")).trim()] ]); case "object_type": return s([ "{", ...join( ast.namedChildren.map((i) => { return s([c2(i), ","]); }), "" ), "}" ]); case "property_signature": return s([c2(n("name")), ": ", c2(n("type"))]); case "workgroup_member": let typeName = ast.childForFieldName("type")?.firstNamedChild?.text ?? ""; if (typeName === "atomic" || typeName === "atomic") { if (hasName("value")) { ctx.report(ast, "Atomic variables cannot have a default value"); } return s([ "\n// @workgroup\n let ", c2(n("name")), ": ", c2(n("type")), " = ", generateDefaultForType(typeName), ";\n" ]); } if (hasName("value")) { return s([ "\n// @workgroup\n let ", c2(n("name")), ": ", c2(n("type")), " = ", c2(n("value")), ";\n" ]); } else { let t = c2(n("type")); return s([ "\n// @workgroup\n let ", c2(n("name")), ": ", t, " = ", generateDefaultForType(typeName), ";\n" ]); } case "workgroup": return s([...children()]); case "async_block": return s([ "/** Runs immediately but does not block when running async code inside (e.g. downloading textures from the gpu)*/(async () => ", c2(n("body")), ")()" ]); case "shader": let encoder = new TextEncoder(); let u8a = encoder.encode(n("body").text); let key = sha256(u8a).map((x) => x.toString(16).padStart(2, "0")).join(""); if (hasName("type_arguments")) { let isComputeShader = n("type_arguments")?.namedChildCount == 3; if (isComputeShader) { let templateArgsRaw = join( n(`type_arguments`).namedChildren.map((nc) => { let innerString = c2(nc).print(); return innerString.replace(/__\.int\((\d+)\)/g, "$1"); }), ", " ); let templateArgs = join( n(`type_arguments`).namedChildren.map((nc) => { return c2(nc); }), ", " ); return new SourceNode(ast.startIndex, ast.endIndex, [ new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`), new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`), `"${key}", /**@shadeup=shader*/(__in: ShaderInput`, `, __out: {}`, `) => `, c2(n("body")), `) as any, [`, ...templateArgs, `]) as shader<`, ...templateArgsRaw, ">" ]); } else { let arg1 = n("type_arguments")?.firstNamedChild; let arg2 = n("type_arguments")?.lastNamedChild; return new SourceNode(ast.startIndex, ast.endIndex, [ new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`), new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`), `"${key}", /**@shadeup=shader*/(__in:`, c2(arg1), ` & {vertexIndex: __.int}, __out: `, c2(arg2), `) => `, c2(n("body")), `))` ]); } } else { return new SourceNode(ast.startIndex, ast.endIndex, [ new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`), new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`), `"${key}", /**@shadeup=shader*/(__in, __out) => `, c2(n("body")), `))` ]); } case "assignment_expression": let left = n("left"); if (left?.type === "subscript_expression") { return s([ c2(left.childForFieldName("object")), ".__index_assign(", c2(left.childForFieldName("index")), ", ", c2(n("right")), ")" ]); } else if (left?.type == "member_expression") { let prop2 = left.childForFieldName("property"); let p2 = prop2.text ?? ""; if (p2.length > 0 && p2.length < 5) { let isSwizzle = true; for (let i = 0; i < p2.length; i++) { let char = p2[i]; if (char !== "x" && char !== "y" && char !== "z" && char !== "w" && char !== "r" && char !== "g" && char !== "b" && char !== "a") { isSwizzle = false; break; } } if (isSwizzle) { return s([c2(n("left"))]); } else { return s([c2(n("left")), " = ", c2(n("right"))]); } } else { return s([c2(n("left")), " = ", c2(n("right"))]); } } else { return s([c2(n("left")), " = ", c2(n("right"))]); } case "sequence_expression": return s([...join(children(), ", ")]); case "subscript_expression": return s([c2(n("object")), ".__index(", c2(n("index")), ")"]); case "empty_statement": return s([""]); case "true": return s(["true"]); case "false": return s(["false"]); case "null": return s(["null"]); case "union_type": return s([...join(children(), " | ")]); case "intersection_type": return s([...join(children(), " & ")]); case "ERROR": ctx.report(ast, "Syntax error"); if (ast.firstNamedChild?.type == "identifier") { return s([c2(ast.firstNamedChild), "."]); } return s(["/* ERROR */ 0"]); default: ctx.report(ast, "Unsupported syntax"); console.error(new Error("Bad AST " + ast.type)); return s(["/* ERROR */ 0"]); } } function compileToString(ctx, ast) { let sn = compile(ctx, ast); let ss = { str: "", indexMapping: [] }; sn.toString(ss); return ss.str; } function isInShader(ast) { if (ast.type === "shader") { return true; } if (ast.parent) { return isInShader(ast.parent); } return false; } var treeSitter = { exports: {} }; (function(module, exports) { var Module = void 0 !== Module ? Module : {}, TreeSitter = function() { var e, t = "object" == typeof window ? { currentScript: window.document.currentScript } : null; class Parser2 { constructor() { this.initialize(); } initialize() { throw new Error("cannot construct a Parser before calling `init()`"); } static init(r) { return e || (Module = Object.assign({}, Module, r), e = new Promise((e2) => { var r2, n = {}; for (r2 in Module) Module.hasOwnProperty(r2) && (n[r2] = Module[r2]); var o, s, _ = [], a = "./this.program", i = function(e3, t2) { throw t2; }, u = false, l = false; u = "object" == typeof window, l = "function" == typeof importScripts, o = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, s = !u && !o && !l; var d, c2, m, f, p, h = ""; o ? (h = l ? require$$0$1.dirname(h) + "/" : __dirname + "/", d = function(e3, t2) { return f || (f = require$$1), p || (p = require$$0$1), e3 = p.normalize(e3), f.readFileSync(e3, t2 ? null : "utf8"); }, m = function(e3) { var t2 = d(e3, true); return t2.buffer || (t2 = new Uint8Array(t2)), k(t2.buffer), t2; }, process.argv.length > 1 && (a = process.argv[1].replace(/\\/g, "/")), _ = process.argv.slice(2), module.exports = Module, i = function(e3) { process.exit(e3); }, Module.inspect = function() { return "[Emscripten Module object]"; }) : s ? ("undefined" != typeof read && (d = function(e3) { return read(e3); }), m = function(e3) { var t2; return "function" == typeof readbuffer ? new Uint8Array(readbuffer(e3)) : (k("object" == typeof (t2 = read(e3, "binary"))), t2); }, "undefined" != typeof scriptArgs ? _ = scriptArgs : void 0 !== arguments && (_ = arguments), "function" == typeof quit && (i = function(e3) { quit(e3); }), "undefined" != typeof print && ("undefined" == typeof console && (console = {}), console.log = print, console.warn = console.error = "undefined" != typeof printErr ? printErr : print)) : (u || l) && (l ? h = self.location.href : void 0 !== t && t.currentScript && (h = t.currentScript.src), h = 0 !== h.indexOf("blob:") ? h.substr(0, h.lastIndexOf("/") + 1) : "", d = function(e3) { var t2 = new XMLHttpRequest(); return t2.open("GET", e3, false), t2.send(null), t2.responseText; }, l && (m = function(e3) { var t2 = new XMLHttpRequest(); return t2.open("GET", e3, false), t2.responseType = "arraybuffer", t2.send(null), new Uint8Array(t2.response); }), c2 = function(e3, t2, r3) { var n2 = new XMLHttpRequest(); n2.open("GET", e3, true), n2.responseType = "arraybuffer", n2.onload = function() { 200 == n2.status || 0 == n2.status && n2.response ? t2(n2.response) : r3(); }, n2.onerror = r3, n2.send(null); }); Module.print || console.log.bind(console); var g2 = Module.printErr || console.warn.bind(console); for (r2 in n) n.hasOwnProperty(r2) && (Module[r2] = n[r2]); n = null, Module.arguments && (_ = Module.arguments), Module.thisProgram && (a = Module.thisProgram), Module.quit && (i = Module.quit); var w = 16; var M, y = []; function b(e3, t2) { if (!M) { M = /* @__PURE__ */ new WeakMap(); for (var r3 = 0; r3 < K.length; r3++) { var n2 = K.get(r3); n2 && M.set(n2, r3); } } if (M.has(e3)) return M.get(e3); var o2 = function() { if (y.length) return y.pop(); try { K.grow(1); } catch (e4) { if (!(e4 instanceof RangeError)) throw e4; throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."; } return K.length - 1; }(); try { K.set(o2, e3); } catch (r4) { if (!(r4 instanceof TypeError)) throw r4; var s2 = function(e4, t3) { if ("function" == typeof WebAssembly.Function) { for (var r5 = { i: "i32", j: "i64", f: "f32", d: "f64" }, n3 = { parameters: [], results: "v" == t3[0] ? [] : [r5[t3[0]]] }, o3 = 1; o3 < t3.length; ++o3) n3.parameters.push(r5[t3[o3]]); return new WebAssembly.Function(n3, e4); } var s3 = [1, 0, 1, 96], _2 = t3.slice(0, 1), a2 = t3.slice(1), i2 = { i: 127, j: 126, f: 125, d: 124 }; for (s3.push(a2.length), o3 = 0; o3 < a2.length; ++o3) s3.push(i2[a2[o3]]); "v" == _2 ? s3.push(0) : s3 = s3.concat([1, i2[_2]]), s3[1] = s3.length - 2; var u2 = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0].concat(s3, [2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0])), l2 = new WebAssembly.Module(u2); return new WebAssembly.Instance(l2, { e: { f: e4 } }).exports.f; }(e3, t2); K.set(o2, s2); } return M.set(e3, o2), o2; } var v, S = Module.dynamicLibraries || []; Module.wasmBinary && (v = Module.wasmBinary); var I, A = Module.noExitRuntime || true; function x(e3, t2, r3, n2) { switch ("*" === (r3 = r3 || "i8").charAt(r3.length - 1) && (r3 = "i32"), r3) { case "i1": case "i8": q[e3 >> 0] = t2; break; case "i16": R[e3 >> 1] = t2; break; case "i32": W[e3 >> 2] = t2; break; case "i64": ie = [t2 >>> 0, (ae = t2, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[e3 >> 2] = ie[0], W[e3 + 4 >> 2] = ie[1]; break; case "float": L[e3 >> 2] = t2; break; case "double": O[e3 >> 3] = t2; break; default: se("invalid type for setValue: " + r3); } } function N(e3, t2, r3) { switch ("*" === (t2 = t2 || "i8").charAt(t2.length - 1) && (t2 = "i32"), t2) { case "i1": case "i8": return q[e3 >> 0]; case "i16": return R[e3 >> 1]; case "i32": case "i64": return W[e3 >> 2]; case "float": return L[e3 >> 2]; case "double": return O[e3 >> 3]; default: se("invalid type for getValue: " + t2); } return null; } "object" != typeof WebAssembly && se("no native wasm support detected"); var P = false; function k(e3, t2) { e3 || se("Assertion failed: " + t2); } var F = 1; var C, q, T, R, W, L, O, j = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0; function $(e3, t2, r3) { for (var n2 = t2 + r3, o2 = t2; e3[o2] && !(o2 >= n2); ) ++o2; if (o2 - t2 > 16 && e3.subarray && j) return j.decode(e3.subarray(t2, o2)); for (var s2 = ""; t2 < o2; ) { var _2 = e3[t2++]; if (128 & _2) { var a2 = 63 & e3[t2++]; if (192 != (224 & _2)) { var i2 = 63 & e3[t2++]; if ((_2 = 224 == (240 & _2) ? (15 & _2) << 12 | a2 << 6 | i2 : (7 & _2) << 18 | a2 << 12 | i2 << 6 | 63 & e3[t2++]) < 65536) s2 += String.fromCharCode(_2); else { var u2 = _2 - 65536; s2 += String.fromCharCode(55296 | u2 >> 10, 56320 | 1023 & u2); } } else s2 += String.fromCharCode((31 & _2) << 6 | a2); } else s2 += String.fromCharCode(_2); } return s2; } function Z(e3, t2) { return e3 ? $(T, e3, t2) : ""; } function D(e3, t2, r3, n2) { if (!(n2 > 0)) return 0; for (var o2 = r3, s2 = r3 + n2 - 1, _2 = 0; _2 < e3.length; ++_2) { var a2 = e3.charCodeAt(_2); if (a2 >= 55296 && a2 <= 57343) a2 = 65536 + ((1023 & a2) << 10) | 1023 & e3.charCodeAt(++_2); if (a2 <= 127) { if (r3 >= s2) break; t2[r3++] = a2; } else if (a2 <= 2047) { if (r3 + 1 >= s2) break; t2[r3++] = 192 | a2 >> 6, t2[r3++] = 128 | 63 & a2; } else if (a2 <= 65535) { if (r3 + 2 >= s2) break; t2[r3++] = 224 | a2 >> 12, t2[r3++] = 128 | a2 >> 6 & 63, t2[r3++] = 128 | 63 & a2; } else { if (r3 + 3 >= s2) break; t2[r3++] = 240 | a2 >> 18, t2[r3++] = 128 | a2 >> 12 & 63, t2[r3++] = 128 | a2 >> 6 & 63, t2[r3++] = 128 | 63 & a2; } } return t2[r3] = 0, r3 - o2; } function z(e3, t2, r3) { return D(e3, T, t2, r3); } function U(e3) { for (var t2 = 0, r3 = 0; r3 < e3.length; ++r3) { var n2 = e3.charCodeAt(r3); n2 >= 55296 && n2 <= 57343 && (n2 = 65536 + ((1023 & n2) << 10) | 1023 & e3.charCodeAt(++r3)), n2 <= 127 ? ++t2 : t2 += n2 <= 2047 ? 2 : n2 <= 65535 ? 3 : 4; } return t2; } function H(e3) { var t2 = U(e3) + 1, r3 = Be(t2); return D(e3, q, r3, t2), r3; } function G(e3) { C = e3, Module.HEAP8 = q = new Int8Array(e3), Module.HEAP16 = R = new Int16Array(e3), Module.HEAP32 = W = new Int32Array(e3), Module.HEAPU8 = T = new Uint8Array(e3), Module.HEAPU16 = new Uint16Array(e3), Module.HEAPU32 = new Uint32Array(e3), Module.HEAPF32 = L = new Float32Array(e3), Module.HEAPF64 = O = new Float64Array(e3); } var B = Module.INITIAL_MEMORY || 33554432; (I = Module.wasmMemory ? Module.wasmMemory : new WebAssembly.Memory({ initial: B / 65536, maximum: 32768 })) && (C = I.buffer), B = C.byteLength, G(C); var K = new WebAssembly.Table({ initial: 20, element: "anyfunc" }), V = [], X = [], Q = [], J = [], Y = false; var ee = 0, re = null; function ne(e3) { ee++, Module.monitorRunDependencies && Module.monitorRunDependencies(ee); } function oe(e3) { if (ee--, Module.monitorRunDependencies && Module.monitorRunDependencies(ee), 0 == ee && re) { var t2 = re; re = null, t2(); } } function se(e3) { throw Module.onAbort && Module.onAbort(e3), g2(e3 += ""), P = true, e3 = "abort(" + e3 + "). Build with -s ASSERTIONS=1 for more info.", new WebAssembly.RuntimeError(e3); } Module.preloadedImages = {}, Module.preloadedAudios = {}, Module.preloadedWasm = {}; var _e, ae, ie, ue = "data:application/octet-stream;base64,"; function le(e3) { return e3.startsWith(ue); } function de(e3) { return e3.startsWith("file://"); } function ce(e3) { try { if (e3 == _e && v) return new Uint8Array(v); if (m) return m(e3); throw "both async and sync fetching of the wasm failed"; } catch (e4) { se(e4); } } le(_e = "tree-sitter.wasm") || (_e = function(e3) { return Module.locateFile ? Module.locateFile(e3, h) : h + e3; }(_e)); var me = {}, fe = { get: function(e3, t2) { return me[t2] || (me[t2] = new WebAssembly.Global({ value: "i32", mutable: true })), me[t2]; } }; function pe(e3) { for (; e3.length > 0; ) { var t2 = e3.shift(); if ("function" != typeof t2) { var r3 = t2.func; "number" == typeof r3 ? void 0 === t2.arg ? K.get(r3)() : K.get(r3)(t2.arg) : r3(void 0 === t2.arg ? null : t2.arg); } else t2(Module); } } function he(e3) { var t2 = 0; function r3() { for (var r4 = 0, n3 = 1; ; ) { var o3 = e3[t2++]; if (r4 += (127 & o3) * n3, n3 *= 128, !(128 & o3)) break; } return r4; } if (e3 instanceof WebAssembly.Module) { var n2 = WebAssembly.Module.customSections(e3, "dylink"); k(0 != n2.length, "need dylink section"), e3 = new Int8Array(n2[0]); } else { k(1836278016 == new Uint32Array(new Uint8Array(e3.subarray(0, 24)).buffer)[0], "need to see wasm magic number"), k(0 === e3[8], "need the dylink section to be first"), t2 = 9, r3(), k(6 === e3[t2]), k(e3[++t2] === "d".charCodeAt(0)), k(e3[++t2] === "y".charCodeAt(0)), k(e3[++t2] === "l".charCodeAt(0)), k(e3[++t2] === "i".charCodeAt(0)), k(e3[++t2] === "n".charCodeAt(0)), k(e3[++t2] === "k".charCodeAt(0)), t2++; } var o2 = {}; o2.memorySize = r3(), o2.memoryAlign = r3(), o2.tableSize = r3(), o2.tableAlign = r3(); var s2 = r3(); o2.neededDynlibs = []; for (var _2 = 0; _2 < s2; ++_2) { var a2 = r3(), i2 = e3.subarray(t2, t2 + a2); t2 += a2; var u2 = $(i2, 0); o2.neededDynlibs.push(u2); } return o2; } var ge = 0; function we() { return A || ge > 0; } function Me(e3) { return 0 == e3.indexOf("dynCall_") || ["stackAlloc", "stackSave", "stackRestore"].includes(e3) ? e3 : "_" + e3; } function ye(e3, t2) { for (var r3 in e3) if (e3.hasOwnProperty(r3)) { De.hasOwnProperty(r3) || (De[r3] = e3[r3]); var n2 = Me(r3); Module.hasOwnProperty(n2) || (Module[n2] = e3[r3]); } } var be = { nextHandle: 1, loadedLibs: {}, loadedLibNames: {} }; function ve(e3, t2, r3) { return e3.includes("j") ? function(e4, t3, r4) { var n2 = Module["dynCall_" + e4]; return r4 && r4.length ? n2.apply(null, [t3].concat(r4)) : n2.call(null, t3); }(e3, t2, r3) : K.get(t2).apply(null, r3); } var Ee = 5251072; function Se(e3) { return ["__cpp_exception", "__wasm_apply_data_relocs", "__dso_handle", "__set_stack_limits"].includes(e3); } function Ie(e3, t2) { var r3 = {}; for (var n2 in e3) { var o2 = e3[n2]; "object" == typeof o2 && (o2 = o2.value), "number" == typeof o2 && (o2 += t2), r3[n2] = o2; } return function(e4) { for (var t3 in e4) if (!Se(t3)) { var r4 = false, n3 = e4[t3]; t3.startsWith("orig$") && (t3 = t3.split("$")[1], r4 = true), me[t3] || (me[t3] = new WebAssembly.Global({ value: "i32", mutable: true })), (r4 || 0 == me[t3].value) && ("function" == typeof n3 ? me[t3].value = b(n3) : "number" == typeof n3 ? me[t3].value = n3 : g2("unhandled export type for `" + t3 + "`: " + typeof n3)); } }(r3), r3; } function Ae(e3, t2) { var r3, n2; return t2 && (r3 = De["orig$" + e3]), r3 || (r3 = De[e3]), r3 || (r3 = Module[Me(e3)]), !r3 && e3.startsWith("invoke_") && (n2 = e3.split("_")[1], r3 = function() { var e4 = He(); try { return ve(n2, arguments[0], Array.prototype.slice.call(arguments, 1)); } catch (t3) { if (Ge(e4), t3 !== t3 + 0 && "longjmp" !== t3) throw t3; Ke(1, 0); } }), r3; } function xe(e3, t2) { var r3 = he(e3); function n2() { var n3 = Math.pow(2, r3.memoryAlign); n3 = Math.max(n3, w); var o2, s2, _2, a2 = (o2 = function(e4) { if (Y) return ze(e4); var t3 = Ee, r4 = t3 + e4 + 15 & -16; return Ee = r4, me.__heap_base.value = r4, t3; }(r3.memorySize + n3), (s2 = n3) || (s2 = w), Math.ceil(o2 / s2) * s2), i2 = K.length; K.grow(r3.tableSize); for (var u2 = a2; u2 < a2 + r3.memorySize; u2++) q[u2] = 0; for (u2 = i2; u2 < i2 + r3.tableSize; u2++) K.set(u2, null); var l2 = new Proxy({}, { get: function(e4, t3) { switch (t3) { case "__memory_base": return a2; case "__table_base": return i2; } if (t3 in De) return De[t3]; var r4; t3 in e4 || (e4[t3] = function() { return r4 || (r4 = function(e5) { var t4 = Ae(e5, false); return t4 || (t4 = _2[e5]), t4; }(t3)), r4.apply(null, arguments); }); return e4[t3]; } }), d2 = { "GOT.mem": new Proxy({}, fe), "GOT.func": new Proxy({}, fe), env: l2, wasi_snapshot_preview1: l2 }; function c3(e4) { for (var n4 = 0; n4 < r3.tableSize; n4++) { var o3 = K.get(i2 + n4); o3 && M.set(o3, i2 + n4); } _2 = Ie(e4.exports, a2), t2.allowUndefined || Pe(); var s3 = _2.__wasm_call_ctors; return s3 || (s3 = _2.__post_instantiate), s3 && (Y ? s3() : X.push(s3)), _2; } if (t2.loadAsync) { if (e3 instanceof WebAssembly.Module) { var m2 = new WebAssembly.Instance(e3, d2); return Promise.resolve(c3(m2)); } return WebAssembly.instantiate(e3, d2).then(function(e4) { return c3(e4.instance); }); } var f2 = e3 instanceof WebAssembly.Module ? e3 : new WebAssembly.Module(e3); return c3(m2 = new WebAssembly.Instance(f2, d2)); } return t2.loadAsync ? r3.neededDynlibs.reduce(function(e4, r4) { return e4.then(function() { return Ne(r4, t2); }); }, Promise.resolve()).then(function() { return n2(); }) : (r3.neededDynlibs.forEach(function(e4) { Ne(e4, t2); }), n2()); } function Ne(e3, t2) { "__main__" != e3 || be.loadedLibNames[e3] || (be.loadedLibs[-1] = { refcount: 1 / 0, name: "__main__", module: Module.asm, global: true }, be.loadedLibNames.__main__ = -1), t2 = t2 || { global: true, nodelete: true }; var r3, n2 = be.loadedLibNames[e3]; if (n2) return r3 = be.loadedLibs[n2], t2.global && !r3.global && (r3.global = true, "loading" !== r3.module && ye(r3.module)), t2.nodelete && r3.refcount !== 1 / 0 && (r3.refcount = 1 / 0), r3.refcount++, t2.loadAsync ? Promise.resolve(n2) : n2; function o2(e4) { if (t2.fs) { var r4 = t2.fs.readFile(e4, { encoding: "binary" }); return r4 instanceof Uint8Array || (r4 = new Uint8Array(r4)), t2.loadAsync ? Promise.resolve(r4) : r4; } return t2.loadAsync ? (n3 = e4, fetch(n3, { credentials: "same-origin" }).then(function(e5) { if (!e5.ok) throw "failed to load binary file at '" + n3 + "'"; return e5.arrayBuffer(); }).then(function(e5) { return new Uint8Array(e5); })) : m(e4); var n3; } function s2() { if (void 0 !== Module.preloadedWasm && void 0 !== Module.preloadedWasm[e3]) { var r4 = Module.preloadedWasm[e3]; return t2.loadAsync ? Promise.resolve(r4) : r4; } return t2.loadAsync ? o2(e3).then(function(e4) { return xe(e4, t2); }) : xe(o2(e3), t2); } function _2(e4) { r3.global && ye(e4), r3.module = e4; } return n2 = be.nextHandle++, r3 = { refcount: t2.nodelete ? 1 / 0 : 1, name: e3, module: "loading", global: t2.global }, be.loadedLibNames[e3] = n2, be.loadedLibs[n2] = r3, t2.loadAsync ? s2().then(function(e4) { return _2(e4), n2; }) : (_2(s2()), n2); } function Pe() { for (var e3 in me) if (0 == me[e3].value) { var t2 = Ae(e3, true); "function" == typeof t2 ? me[e3].value = b(t2, t2.sig) : "number" == typeof t2 ? me[e3].value = t2 : k(false, "bad export type for `" + e3 + "`: " + typeof t2); } } Module.___heap_base = Ee; var ke, Fe = new WebAssembly.Global({ value: "i32", mutable: true }, 5251072); function Ce() { se(); } Module._abort = Ce, Ce.sig = "v", ke = o ? function() { var e3 = process.hrtime(); return 1e3 * e3[0] + e3[1] / 1e6; } : "undefined" != typeof dateNow ? dateNow : function() { return performance.now(); }; var qe = true; function Te(e3, t2) { var r3, n2; if (0 === e3) r3 = Date.now(); else { if (1 !== e3 && 4 !== e3 || !qe) return n2 = 28, W[Ue() >> 2] = n2, -1; r3 = ke(); } return W[t2 >> 2] = r3 / 1e3 | 0, W[t2 + 4 >> 2] = r3 % 1e3 * 1e3 * 1e3 | 0, 0; } function Re(e3) { try { return I.grow(e3 - C.byteLength + 65535 >>> 16), G(I.buffer), 1; } catch (e4) { } } function We(e3) { Je(e3); } Te.sig = "iii", We.sig = "vi"; var Le = { mappings: {}, DEFAULT_POLLMASK: 5, umask: 511, calculateAt: function(e3, t2, r3) { if ("/" === t2[0]) return t2; var n2; if (-100 === e3) n2 = FS.cwd(); else { var o2 = FS.getStream(e3); if (!o2) throw new FS.ErrnoError(8); n2 = o2.path; } if (0 == t2.length) { if (!r3) throw new FS.ErrnoError(44); return n2; } return PATH.join2(n2, t2); }, doStat: function(e3, t2, r3) { try { var n2 = e3(t2); } catch (e4) { if (e4 && e4.node && PATH.normalize(t2) !== PATH.normalize(FS.getPath(e4.node))) return -54; throw e4; } return W[r3 >> 2] = n2.dev, W[r3 + 4 >> 2] = 0, W[r3 + 8 >> 2] = n2.ino, W[r3 + 12 >> 2] = n2.mode, W[r3 + 16 >> 2] = n2.nlink, W[r3 + 20 >> 2] = n2.uid, W[r3 + 24 >> 2] = n2.gid, W[r3 + 28 >> 2] = n2.rdev, W[r3 + 32 >> 2] = 0, ie = [n2.size >>> 0, (ae = n2.size, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[r3 + 40 >> 2] = ie[0], W[r3 + 44 >> 2] = ie[1], W[r3 + 48 >> 2] = 4096, W[r3 + 52 >> 2] = n2.blocks, W[r3 + 56 >> 2] = n2.atime.getTime() / 1e3 | 0, W[r3 + 60 >> 2] = 0, W[r3 + 64 >> 2] = n2.mtime.getTime() / 1e3 | 0, W[r3 + 68 >> 2] = 0, W[r3 + 72 >> 2] = n2.ctime.getTime() / 1e3 | 0, W[r3 + 76 >> 2] = 0, ie = [n2.ino >>> 0, (ae = n2.ino, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[r3 + 80 >> 2] = ie[0], W[r3 + 84 >> 2] = ie[1], 0; }, doMsync: function(e3, t2, r3, n2, o2) { var s2 = T.slice(e3, e3 + r3); FS.msync(t2, s2, o2, r3, n2); }, doMkdir: function(e3, t2) { return "/" === (e3 = PATH.normalize(e3))[e3.length - 1] && (e3 = e3.substr(0, e3.length - 1)), FS.mkdir(e3, t2, 0), 0; }, doMknod: function(e3, t2, r3) { switch (61440 & t2) { case 32768: case 8192: case 24576: case 4096: case 49152: break; default: return -28; } return FS.mknod(e3, t2, r3), 0; }, doReadlink: function(e3, t2, r3) { if (r3 <= 0) return -28; var n2 = FS.readlink(e3), o2 = Math.min(r3, U(n2)), s2 = q[t2 + o2]; return z(n2, t2, r3 + 1), q[t2 + o2] = s2, o2; }, doAccess: function(e3, t2) { if (-8 & t2) return -28; var r3; if (!(r3 = FS.lookupPath(e3, { follow: true }).node)) return -44; var n2 = ""; return 4 & t2 && (n2 += "r"), 2 & t2 && (n2 += "w"), 1 & t2 && (n2 += "x"), n2 && FS.nodePermissions(r3, n2) ? -2 : 0; }, doDup: function(e3, t2, r3) { var n2 = FS.getStream(r3); return n2 && FS.close(n2), FS.open(e3, t2, 0, r3, r3).fd; }, doReadv: function(e3, t2, r3, n2) { for (var o2 = 0, s2 = 0; s2 < r3; s2++) { var _2 = W[t2 + 8 * s2 >> 2], a2 = W[t2 + (8 * s2 + 4) >> 2], i2 = FS.read(e3, q, _2, a2, n2); if (i2 < 0) return -1; if (o2 += i2, i2 < a2) break; } return o2; }, doWritev: function(e3, t2, r3, n2) { for (var o2 = 0, s2 = 0; s2 < r3; s2++) { var _2 = W[t2 + 8 * s2 >> 2], a2 = W[t2 + (8 * s2 + 4) >> 2], i2 = FS.write(e3, q, _2, a2, n2); if (i2 < 0) return -1; o2 += i2; } return o2; }, varargs: void 0, get: function() { return Le.varargs += 4, W[Le.varargs - 4 >> 2]; }, getStr: function(e3) { return Z(e3); }, getStreamFromFD: function(e3) { var t2 = FS.getStream(e3); if (!t2) throw new FS.ErrnoError(8); return t2; }, get64: function(e3, t2) { return e3; } }; function Oe(e3) { try { var t2 = Le.getStreamFromFD(e3); return FS.close(t2), 0; } catch (e4) { return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno; } } function je(e3, t2, r3, n2) { try { var o2 = Le.getStreamFromFD(e3), s2 = Le.doWritev(o2, t2, r3); return W[n2 >> 2] = s2, 0; } catch (e4) { return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno; } } function $e(e3) { } Oe.sig = "ii", je.sig = "iiiii", $e.sig = "vi"; var Ze, De = { __heap_base: Ee, __indirect_function_table: K, __memory_base: 1024, __stack_pointer: Fe, __table_base: 1, abort: Ce, clock_gettime: Te, emscripten_memcpy_big: function(e3, t2, r3) { T.copyWithin(e3, t2, t2 + r3); }, emscripten_resize_heap: function(e3) { var t2, r3, n2 = T.length; if ((e3 >>>= 0) > 2147483648) return false; for (var o2 = 1; o2 <= 4; o2 *= 2) { var s2 = n2 * (1 + 0.2 / o2); if (s2 = Math.min(s2, e3 + 100663296), Re(Math.min(2147483648, ((t2 = Math.max(e3, s2)) % (r3 = 65536) > 0 && (t2 += r3 - t2 % r3), t2)))) return true; } return false; }, exit: We, fd_close: Oe, fd_seek: function(e3, t2, r3, n2, o2) { try { var s2 = Le.getStreamFromFD(e3), _2 = 4294967296 * r3 + (t2 >>> 0); return _2 <= -9007199254740992 || _2 >= 9007199254740992 ? -61 : (FS.llseek(s2, _2, n2), ie = [s2.position >>> 0, (ae = s2.position, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[o2 >> 2] = ie[0], W[o2 + 4 >> 2] = ie[1], s2.getdents && 0 === _2 && 0 === n2 && (s2.getdents = null), 0); } catch (e4) { return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno; } }, fd_write: je, memory: I, setTempRet0: $e, tree_sitter_log_callback: function(e3, t2) { if (pt) { const r3 = Z(t2); pt(r3, 0 !== e3); } }, tree_sitter_parse_callback: function(e3, t2, r3, n2, o2) { var s2 = ft(t2, { row: r3, column: n2 }); "string" == typeof s2 ? (x(o2, s2.length, "i32"), function(e4, t3, r4) { if (void 0 === r4 && (r4 = 2147483647), r4 < 2) return 0; for (var n3 = (r4 -= 2) < 2 * e4.length ? r4 / 2 : e4.length, o3 = 0; o3 < n3; ++o3) { var s3 = e4.charCodeAt(o3); R[t3 >> 1] = s3, t3 += 2; } R[t3 >> 1] = 0; }(s2, e3, 10240)) : x(o2, 0, "i32"); } }, ze = (function() { var e3 = { env: De, wasi_snapshot_preview1: De, "GOT.mem": new Proxy(De, fe), "GOT.func": new Proxy(De, fe) }; function t2(e4, t3) { var r4 = e4.exports; r4 = Ie(r4, 1024), Module.asm = r4; var n3, o2 = he(t3); o2.neededDynlibs && (S = o2.neededDynlibs.concat(S)), ye(r4), n3 = Module.asm.__wasm_call_ctors, X.unshift(n3), oe(); } function r3(e4) { t2(e4.instance, e4.module); } function n2(t3) { return function() { if (!v && (u || l)) { if ("function" == typeof fetch && !de(_e)) return fetch(_e, { credentials: "same-origin" }).then(function(e4) { if (!e4.ok) throw "failed to load wasm binary file at '" + _e + "'"; return e4.arrayBuffer(); }).catch(function() { return ce(_e); }); if (c2) return new Promise(function(e4, t4) { c2(_e, function(t5) { e4(new Uint8Array(t5)); }, t4); }); } return Promise.resolve().then(function() { return ce(_e); }); }().then(function(t4) { return WebAssembly.instantiate(t4, e3); }).then(t3, function(e4) { g2("failed to asynchronously prepare wasm: " + e4), se(e4); }); } if (ne(), Module.instantiateWasm) try { return Module.instantiateWasm(e3, t2); } catch (e4) { return g2("Module.instantiateWasm callback failed with error: " + e4), false; } v || "function" != typeof WebAssembly.instantiateStreaming || le(_e) || de(_e) || "function" != typeof fetch ? n2(r3) : fetch(_e, { credentials: "same-origin" }).then(function(t3) { return WebAssembly.instantiateStreaming(t3, e3).then(r3, function(e4) { return g2("wasm streaming compile failed: " + e4), g2("falling back to ArrayBuffer instantiation"), n2(r3); }); }); }(), Module.___wasm_call_ctors = function() { return (Module.___wasm_call_ctors = Module.asm.__wasm_call_ctors).apply(null, arguments); }, Module._malloc = function() { return (ze = Module._malloc = Module.asm.malloc).apply(null, arguments); }), Ue = (Module._calloc = function() { return (Module._calloc = Module.asm.calloc).apply(null, arguments); }, Module._realloc = function() { return (Module._realloc = Module.asm.realloc).apply(null, arguments); }, Module._free = function() { return (Module._free = Module.asm.free).apply(null, arguments); }, Module._ts_language_symbol_count = function() { return (Module._ts_language_symbol_count = Module.asm.ts_language_symbol_count).apply(null, arguments); }, Module._ts_language_version = function() { return (Module._ts_language_version = Module.asm.ts_language_version).apply(null, arguments); }, Module._ts_language_field_count = function() { return (Module._ts_language_field_count = Module.asm.ts_language_field_count).apply(null, arguments); }, Module._ts_language_symbol_name = function() { return (Module._ts_language_symbol_name = Module.asm.ts_language_symbol_name).apply(null, arguments); }, Module._ts_language_symbol_for_name = function() { return (Module._ts_language_symbol_for_name = Module.asm.ts_language_symbol_for_name).apply(null, arguments); }, Module._ts_language_symbol_type = function() { return (Module._ts_language_symbol_type = Module.asm.ts_language_symbol_type).apply(null, arguments); }, Module._ts_language_field_name_for_id = function() { return (Module._ts_language_field_name_for_id = Module.asm.ts_language_field_name_for_id).apply(null, arguments); }, Module._memcpy = function() { return (Module._memcpy = Module.asm.memcpy).apply(null, arguments); }, Module._ts_parser_delete = function() { return (Module._ts_parser_delete = Module.asm.ts_parser_delete).apply(null, arguments); }, Module._ts_parser_reset = function() { return (Module._ts_parser_reset = Module.asm.ts_parser_reset).apply(null, arguments); }, Module._ts_parser_set_language = function() { return (Module._ts_parser_set_language = Module.asm.ts_parser_set_language).apply(null, arguments); }, Module._ts_parser_timeout_micros = function() { return (Module._ts_parser_timeout_micros = Module.asm.ts_parser_timeout_micros).apply(null, arguments); }, Module._ts_parser_set_timeout_micros = function() { return (Module._ts_parser_set_timeout_micros = Module.asm.ts_parser_set_timeout_micros).apply(null, arguments); }, Module._memmove = function() { return (Module._memmove = Module.asm.memmove).apply(null, arguments); }, Module._memcmp = function() { return (Module._memcmp = Module.asm.memcmp).apply(null, arguments); }, Module._ts_query_new = function() { return (Module._ts_query_new = Module.asm.ts_query_new).apply(null, arguments); }, Module._ts_query_delete = function() { return (Module._ts_query_delete = Module.asm.ts_query_delete).apply(null, arguments); }, Module._iswspace = function() { return (Module._iswspace = Module.asm.iswspace).apply(null, arguments); }, Module._iswalnum = function() { return (Module._iswalnum = Module.asm.iswalnum).apply(null, arguments); }, Module._ts_query_pattern_count = function() { return (Module._ts_query_pattern_count = Module.asm.ts_query_pattern_count).apply(null, arguments); }, Module._ts_query_capture_count = function() { return (Module._ts_query_capture_count = Module.asm.ts_query_capture_count).apply(null, arguments); }, Module._ts_query_string_count = function() { return (Module._ts_query_string_count = Module.asm.ts_query_string_count).apply(null, arguments); }, Module._ts_query_capture_name_for_id = function() { return (Module._ts_query_capture_name_for_id = Module.asm.ts_query_capture_name_for_id).apply(null, arguments); }, Module._ts_query_string_value_for_id = function() { return (Module._ts_query_string_value_for_id = Module.asm.ts_query_string_value_for_id).apply(null, arguments); }, Module._ts_query_predicates_for_pattern = function() { return (Module._ts_query_predicates_for_pattern = Module.asm.ts_query_predicates_for_pattern).apply(null, arguments); }, Module._ts_tree_copy = function() { return (Module._ts_tree_copy = Module.asm.ts_tree_copy).apply(null, arguments); }, Module._ts_tree_delete = function() { return (Module._ts_tree_delete = Module.asm.ts_tree_delete).apply(null, arguments); }, Module._ts_init = function() { return (Module._ts_init = Module.asm.ts_init).apply(null, arguments); }, Module._ts_parser_new_wasm = function() { return (Module._ts_parser_new_wasm = Module.asm.ts_parser_new_wasm).apply(null, arguments); }, Module._ts_parser_enable_logger_wasm = function() { return (Module._ts_parser_enable_logger_wasm = Module.asm.ts_parser_enable_logger_wasm).apply(null, arguments); }, Module._ts_parser_parse_wasm = function() { return (Module._ts_parser_parse_wasm = Module.asm.ts_parser_parse_wasm).apply(null, arguments); }, Module._ts_language_type_is_named_wasm = function() { return (Module._ts_language_type_is_named_wasm = Module.asm.ts_language_type_is_named_wasm).apply(null, arguments); }, Module._ts_language_type_is_visible_wasm = function() { return (Module._ts_language_type_is_visible_wasm = Module.asm.ts_language_type_is_visible_wasm).apply(null, arguments); }, Module._ts_tree_root_node_wasm = function() { return (Module._ts_tree_root_node_wasm = Module.asm.ts_tree_root_node_wasm).apply(null, arguments); }, Module._ts_tree_edit_wasm = function() { return (Module._ts_tree_edit_wasm = Module.asm.ts_tree_edit_wasm).apply(null, arguments); }, Module._ts_tree_get_changed_ranges_wasm = function() { return (Module._ts_tree_get_changed_ranges_wasm = Module.asm.ts_tree_get_changed_ranges_wasm).apply(null, arguments); }, Module._ts_tree_cursor_new_wasm = function() { return (Module._ts_tree_cursor_new_wasm = Module.asm.ts_tree_cursor_new_wasm).apply(null, arguments); }, Module._ts_tree_cursor_delete_wasm = function() { return (Module._ts_tree_cursor_delete_wasm = Module.asm.ts_tree_cursor_delete_wasm).apply(null, arguments); }, Module._ts_tree_cursor_reset_wasm = function() { return (Module._ts_tree_cursor_reset_wasm = Module.asm.ts_tree_cursor_reset_wasm).apply(null, arguments); }, Module._ts_tree_cursor_goto_first_child_wasm = function() { return (Module._ts_tree_cursor_goto_first_child_wasm = Module.asm.ts_tree_cursor_goto_first_child_wasm).apply(null, arguments); }, Module._ts_tree_cursor_goto_next_sibling_wasm = function() { return (Module._ts_tree_cursor_goto_next_sibling_wasm = Module.asm.ts_tree_cursor_goto_next_sibling_wasm).apply(null, arguments); }, Module._ts_tree_cursor_goto_parent_wasm = function() { return (Module._ts_tree_cursor_goto_parent_wasm = Module.asm.ts_tree_cursor_goto_parent_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_type_id_wasm = function() { return (Module._ts_tree_cursor_current_node_type_id_wasm = Module.asm.ts_tree_cursor_current_node_type_id_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_is_named_wasm = function() { return (Module._ts_tree_cursor_current_node_is_named_wasm = Module.asm.ts_tree_cursor_current_node_is_named_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_is_missing_wasm = function() { return (Module._ts_tree_cursor_current_node_is_missing_wasm = Module.asm.ts_tree_cursor_current_node_is_missing_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_id_wasm = function() { return (Module._ts_tree_cursor_current_node_id_wasm = Module.asm.ts_tree_cursor_current_node_id_wasm).apply(null, arguments); }, Module._ts_tree_cursor_start_position_wasm = function() { return (Module._ts_tree_cursor_start_position_wasm = Module.asm.ts_tree_cursor_start_position_wasm).apply(null, arguments); }, Module._ts_tree_cursor_end_position_wasm = function() { return (Module._ts_tree_cursor_end_position_wasm = Module.asm.ts_tree_cursor_end_position_wasm).apply(null, arguments); }, Module._ts_tree_cursor_start_index_wasm = function() { return (Module._ts_tree_cursor_start_index_wasm = Module.asm.ts_tree_cursor_start_index_wasm).apply(null, arguments); }, Module._ts_tree_cursor_end_index_wasm = function() { return (Module._ts_tree_cursor_end_index_wasm = Module.asm.ts_tree_cursor_end_index_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_field_id_wasm = function() { return (Module._ts_tree_cursor_current_field_id_wasm = Module.asm.ts_tree_cursor_current_field_id_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_wasm = function() { return (Module._ts_tree_cursor_current_node_wasm = Module.asm.ts_tree_cursor_current_node_wasm).apply(null, arguments); }, Module._ts_node_symbol_wasm = function() { return (Module._ts_node_symbol_wasm = Module.asm.ts_node_symbol_wasm).apply(null, arguments); }, Module._ts_node_child_count_wasm = function() { return (Module._ts_node_child_count_wasm = Module.asm.ts_node_child_count_wasm).apply(null, arguments); }, Module._ts_node_named_child_count_wasm = function() { return (Module._ts_node_named_child_count_wasm = Module.asm.ts_node_named_child_count_wasm).apply(null, arguments); }, Module._ts_node_child_wasm = function() { return (Module._ts_node_child_wasm = Module.asm.ts_node_child_wasm).apply(null, arguments); }, Module._ts_node_named_child_wasm = function() { return (Module._ts_node_named_child_wasm = Module.asm.ts_node_named_child_wasm).apply(null, arguments); }, Module._ts_node_child_by_field_id_wasm = function() { return (Module._ts_node_child_by_field_id_wasm = Module.asm.ts_node_child_by_field_id_wasm).apply(null, arguments); }, Module._ts_node_next_sibling_wasm = function() { return (Module._ts_node_next_sibling_wasm = Module.asm.ts_node_next_sibling_wasm).apply(null, arguments); }, Module._ts_node_prev_sibling_wasm = function() { return (Module._ts_node_prev_sibling_wasm = Module.asm.ts_node_prev_sibling_wasm).apply(null, arguments); }, Module._ts_node_next_named_sibling_wasm = function() { return (Module._ts_node_next_named_sibling_wasm = Module.asm.ts_node_next_named_sibling_wasm).apply(null, arguments); }, Module._ts_node_prev_named_sibling_wasm = function() { return (Module._ts_node_prev_named_sibling_wasm = Module.asm.ts_node_prev_named_sibling_wasm).apply(null, arguments); }, Module._ts_node_parent_wasm = function() { return (Module._ts_node_parent_wasm = Module.asm.ts_node_parent_wasm).apply(null, arguments); }, Module._ts_node_descendant_for_index_wasm = function() { return (Module._ts_node_descendant_for_index_wasm = Module.asm.ts_node_descendant_for_index_wasm).apply(null, arguments); }, Module._ts_node_named_descendant_for_index_wasm = function() { return (Module._ts_node_named_descendant_for_index_wasm = Module.asm.ts_node_named_descendant_for_index_wasm).apply(null, arguments); }, Module._ts_node_descendant_for_position_wasm = function() { return (Module._ts_node_descendant_for_position_wasm = Module.asm.ts_node_descendant_for_position_wasm).apply(null, arguments); }, Module._ts_node_named_descendant_for_position_wasm = function() { return (Module._ts_node_named_descendant_for_position_wasm = Module.asm.ts_node_named_descendant_for_position_wasm).apply(null, arguments); }, Module._ts_node_start_point_wasm = function() { return (Module._ts_node_start_point_wasm = Module.asm.ts_node_start_point_wasm).apply(null, arguments); }, Module._ts_node_end_point_wasm = function() { return (Module._ts_node_end_point_wasm = Module.asm.ts_node_end_point_wasm).apply(null, arguments); }, Module._ts_node_start_index_wasm = function() { return (Module._ts_node_start_index_wasm = Module.asm.ts_node_start_index_wasm).apply(null, arguments); }, Module._ts_node_end_index_wasm = function() { return (Module._ts_node_end_index_wasm = Module.asm.ts_node_end_index_wasm).apply(null, arguments); }, Module._ts_node_to_string_wasm = function() { return (Module._ts_node_to_string_wasm = Module.asm.ts_node_to_string_wasm).apply(null, arguments); }, Module._ts_node_children_wasm = function() { return (Module._ts_node_children_wasm = Module.asm.ts_node_children_wasm).apply(null, arguments); }, Module._ts_node_named_children_wasm = function() { return (Module._ts_node_named_children_wasm = Module.asm.ts_node_named_children_wasm).apply(null, arguments); }, Module._ts_node_descendants_of_type_wasm = function() { return (Module._ts_node_descendants_of_type_wasm = Module.asm.ts_node_descendants_of_type_wasm).apply(null, arguments); }, Module._ts_node_is_named_wasm = function() { return (Module._ts_node_is_named_wasm = Module.asm.ts_node_is_named_wasm).apply(null, arguments); }, Module._ts_node_has_changes_wasm = function() { return (Module._ts_node_has_changes_wasm = Module.asm.ts_node_has_changes_wasm).apply(null, arguments); }, Module._ts_node_has_error_wasm = function() { return (Module._ts_node_has_error_wasm = Module.asm.ts_node_has_error_wasm).apply(null, arguments); }, Module._ts_node_is_missing_wasm = function() { return (Module._ts_node_is_missing_wasm = Module.asm.ts_node_is_missing_wasm).apply(null, arguments); }, Module._ts_query_matches_wasm = function() { return (Module._ts_query_matches_wasm = Module.asm.ts_query_matches_wasm).apply(null, arguments); }, Module._ts_query_captures_wasm = function() { return (Module._ts_query_captures_wasm = Module.asm.ts_query_captures_wasm).apply(null, arguments); }, Module._iswdigit = function() { return (Module._iswdigit = Module.asm.iswdigit).apply(null, arguments); }, Module._iswalpha = function() { return (Module._iswalpha = Module.asm.iswalpha).apply(null, arguments); }, Module._iswlower = function() { return (Module._iswlower = Module.asm.iswlower).apply(null, arguments); }, Module._towupper = function() { return (Module._towupper = Module.asm.towupper).apply(null, arguments); }, Module.___errno_location = function() { return (Ue = Module.___errno_location = Module.asm.__errno_location).apply(null, arguments); }), He = (Module._memchr = function() { return (Module._memchr = Module.asm.memchr).apply(null, arguments); }, Module._strlen = function() { return (Module._strlen = Module.asm.strlen).apply(null, arguments); }, Module.stackSave = function() { return (He = Module.stackSave = Module.asm.stackSave).apply(null, arguments); }), Ge = Module.stackRestore = function() { return (Ge = Module.stackRestore = Module.asm.stackRestore).apply(null, arguments); }, Be = Module.stackAlloc = function() { return (Be = Module.stackAlloc = Module.asm.stackAlloc).apply(null, arguments); }, Ke = Module._setThrew = function() { return (Ke = Module._setThrew = Module.asm.setThrew).apply(null, arguments); }; Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm).apply(null, arguments); }, Module.__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm = function() { return (Module.__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm = Module.asm._ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev = function() { return (Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev = Module.asm._ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw = function() { return (Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw = Module.asm._ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw).apply(null, arguments); }, Module.__Znwm = function() { return (Module.__Znwm = Module.asm._Znwm).apply(null, arguments); }, Module.__ZdlPv = function() { return (Module.__ZdlPv = Module.asm._ZdlPv).apply(null, arguments); }, Module.dynCall_jiji = function() { return (Module.dynCall_jiji = Module.asm.dynCall_jiji).apply(null, arguments); }, Module._orig$ts_parser_timeout_micros = function() { return (Module._orig$ts_parser_timeout_micros = Module.asm.orig$ts_parser_timeout_micros).apply(null, arguments); }, Module._orig$ts_parser_set_timeout_micros = function() { return (Module._orig$ts_parser_set_timeout_micros = Module.asm.orig$ts_parser_set_timeout_micros).apply(null, arguments); }; function Ve(e3) { this.name = "ExitStatus", this.message = "Program terminated with exit(" + e3 + ")", this.status = e3; } Module.allocate = function(e3, t2) { var r3; return r3 = t2 == F ? Be(e3.length) : ze(e3.length), e3.subarray || e3.slice ? T.set(e3, r3) : T.set(new Uint8Array(e3), r3), r3; }; re = function e3() { Ze || Qe(), Ze || (re = e3); }; var Xe = false; function Qe(e3) { function t2() { Ze || (Ze = true, Module.calledRun = true, P || (Y = true, pe(X), pe(Q), Module.onRuntimeInitialized && Module.onRuntimeInitialized(), Ye && function(e4) { var t3 = Module._main; if (t3) { var r3 = (e4 = e4 || []).length + 1, n2 = Be(4 * (r3 + 1)); W[n2 >> 2] = H(a); for (var o2 = 1; o2 < r3; o2++) W[(n2 >> 2) + o2] = H(e4[o2 - 1]); W[(n2 >> 2) + r3] = 0; try { Je(t3(r3, n2), true); } catch (e5) { if (e5 instanceof Ve) return; if ("unwind" == e5) return; var s2 = e5; e5 && "object" == typeof e5 && e5.stack && (s2 = [e5, e5.stack]), g2("exception thrown: " + s2), i(1, e5); } finally { } } }(e3), function() { if (Module.postRun) for ("function" == typeof Module.postRun && (Module.postRun = [Module.postRun]); Module.postRun.length; ) e4 = Module.postRun.shift(), J.unshift(e4); var e4; pe(J); }())); } e3 = e3 || _, ee > 0 || !Xe && (function() { if (S.length) { if (!m) return ne(), void S.reduce(function(e4, t3) { return e4.then(function() { return Ne(t3, { loadAsync: true, global: true, nodelete: true, allowUndefined: true }); }); }, Promise.resolve()).then(function() { oe(), Pe(); }); S.forEach(function(e4) { Ne(e4, { global: true, nodelete: true, allowUndefined: true }); }), Pe(); } else Pe(); }(), Xe = true, ee > 0) || (!function() { if (Module.preRun) for ("function" == typeof Module.preRun && (Module.preRun = [Module.preRun]); Module.preRun.length; ) e4 = Module.preRun.shift(), V.unshift(e4); var e4; pe(V); }(), ee > 0 || (Module.setStatus ? (Module.setStatus("Running..."), setTimeout(function() { setTimeout(function() { Module.setStatus(""); }, 1), t2(); }, 1)) : t2())); } function Je(e3, t2) { t2 && we() && 0 === e3 || (we() || (Module.onExit && Module.onExit(e3), P = true), i(e3, new Ve(e3))); } if (Module.run = Qe, Module.preInit) for ("function" == typeof Module.preInit && (Module.preInit = [Module.preInit]); Module.preInit.length > 0; ) Module.preInit.pop()(); var Ye = true; Module.noInitialRun && (Ye = false), Qe(); const et = Module, tt = {}, rt = 4, nt = 5 * rt, ot = 2 * rt, st = 2 * rt + 2 * ot, _t = { row: 0, column: 0 }, at = /[\w-.]*/g, it = 1, ut = 2, lt = /^_?tree_sitter_\w+/; var dt, ct, mt, ft, pt; class ParserImpl { static init() { mt = et._ts_init(), dt = N(mt, "i32"), ct = N(mt + rt, "i32"); } initialize() { et._ts_parser_new_wasm(), this[0] = N(mt, "i32"), this[1] = N(mt + rt, "i32"); } delete() { et._ts_parser_delete(this[0]), et._free(this[1]), this[0] = 0, this[1] = 0; } setLanguage(e3) { let t2; if (e3) { if (e3.constructor !== Language) throw new Error("Argument must be a Language"); { t2 = e3[0]; const r3 = et._ts_language_version(t2); if (r3 < ct || dt < r3) throw new Error(`Incompatible language version ${r3}. Compatibility range ${ct} through ${dt}.`); } } else t2 = 0, e3 = null; return this.language = e3, et._ts_parser_set_language(this[0], t2), this; } getLanguage() { return this.language; } parse(e3, t2, r3) { if ("string" == typeof e3) ft = (t3, r4, n3) => e3.slice(t3, n3); else { if ("function" != typeof e3) throw new Error("Argument must be a string or a function"); ft = e3; } this.logCallback ? (pt = this.logCallback, et._ts_parser_enable_logger_wasm(this[0], 1)) : (pt = null, et._ts_parser_enable_logger_wasm(this[0], 0)); let n2 = 0, o2 = 0; if (r3 && r3.includedRanges) { n2 = r3.includedRanges.length; let e4 = o2 = et._calloc(n2, st); for (let t3 = 0; t3 < n2; t3++) At(e4, r3.includedRanges[t3]), e4 += st; } const s2 = et._ts_parser_parse_wasm(this[0], this[1], t2 ? t2[0] : 0, o2, n2); if (!s2) throw ft = null, pt = null, new Error("Parsing failed"); const _2 = new Tree(tt, s2, this.language, ft); return ft = null, pt = null, _2; } reset() { et._ts_parser_reset(this[0]); } setTimeoutMicros(e3) { et._ts_parser_set_timeout_micros(this[0], e3); } getTimeoutMicros() { return et._ts_parser_timeout_micros(this[0]); } setLogger(e3) { if (e3) { if ("function" != typeof e3) throw new Error("Logger callback must be a function"); } else e3 = null; return this.logCallback = e3, this; } getLogger() { return this.logCallback; } } class Tree { constructor(e3, t2, r3, n2) { wt(e3), this[0] = t2, this.language = r3, this.textCallback = n2; } copy() { const e3 = et._ts_tree_copy(this[0]); return new Tree(tt, e3, this.language, this.textCallback); } delete() { et._ts_tree_delete(this[0]), this[0] = 0; } edit(e3) { !function(e4) { let t2 = mt; St(t2, e4.startPosition), St(t2 += ot, e4.oldEndPosition), St(t2 += ot, e4.newEndPosition), x(t2 += ot, e4.startIndex, "i32"), x(t2 += rt, e4.oldEndIndex, "i32"), x(t2 += rt, e4.newEndIndex, "i32"), t2 += rt; }(e3), et._ts_tree_edit_wasm(this[0]); } get rootNode() { return et._ts_tree_root_node_wasm(this[0]), bt(this); } getLanguage() { return this.language; } walk() { return this.rootNode.walk(); } getChangedRanges(e3) { if (e3.constructor !== Tree) throw new TypeError("Argument must be a Tree"); et._ts_tree_get_changed_ranges_wasm(this[0], e3[0]); const t2 = N(mt, "i32"), r3 = N(mt + rt, "i32"), n2 = new Array(t2); if (t2 > 0) { let e4 = r3; for (let r4 = 0; r4 < t2; r4++) n2[r4] = xt(e4), e4 += st; et._free(r3); } return n2; } } class Node { constructor(e3, t2) { wt(e3), this.tree = t2; } get typeId() { return yt(this), et._ts_node_symbol_wasm(this.tree[0]); } get type() { return this.tree.language.types[this.typeId] || "ERROR"; } get endPosition() { return yt(this), et._ts_node_end_point_wasm(this.tree[0]), It(mt); } get endIndex() { return yt(this), et._ts_node_end_index_wasm(this.tree[0]); } get text() { return ht(this.tree, this.startIndex, this.endIndex); } isNamed() { return yt(this), 1 === et._ts_node_is_named_wasm(this.tree[0]); } hasError() { return yt(this), 1 === et._ts_node_has_error_wasm(this.tree[0]); } hasChanges() { return yt(this), 1 === et._ts_node_has_changes_wasm(this.tree[0]); } isMissing() { return yt(this), 1 === et._ts_node_is_missing_wasm(this.tree[0]); } equals(e3) { return this.id === e3.id; } child(e3) { return yt(this), et._ts_node_child_wasm(this.tree[0], e3), bt(this.tree); } namedChild(e3) { return yt(this), et._ts_node_named_child_wasm(this.tree[0], e3), bt(this.tree); } childForFieldId(e3) { return yt(this), et._ts_node_child_by_field_id_wasm(this.tree[0], e3), bt(this.tree); } childForFieldName(e3) { const t2 = this.tree.language.fields.indexOf(e3); if (-1 !== t2) return this.childForFieldId(t2); } get childCount() { return yt(this), et._ts_node_child_count_wasm(this.tree[0]); } get namedChildCount() { return yt(this), et._ts_node_named_child_count_wasm(this.tree[0]); } get firstChild() { return this.child(0); } get firstNamedChild() { return this.namedChild(0); } get lastChild() { return this.child(this.childCount - 1); } get lastNamedChild() { return this.namedChild(this.namedChildCount - 1); } get children() { if (!this._children) { yt(this), et._ts_node_children_wasm(this.tree[0]); const e3 = N(mt, "i32"), t2 = N(mt + rt, "i32"); if (this._children = new Array(e3), e3 > 0) { let r3 = t2; for (let t3 = 0; t3 < e3; t3++) this._children[t3] = bt(this.tree, r3), r3 += nt; et._free(t2); } } return this._children; } get namedChildren() { if (!this._namedChildren) { yt(this), et._ts_node_named_children_wasm(this.tree[0]); const e3 = N(mt, "i32"), t2 = N(mt + rt, "i32"); if (this._namedChildren = new Array(e3), e3 > 0) { let r3 = t2; for (let t3 = 0; t3 < e3; t3++) this._namedChildren[t3] = bt(this.tree, r3), r3 += nt; et._free(t2); } } return this._namedChildren; } descendantsOfType(e3, t2, r3) { Array.isArray(e3) || (e3 = [e3]), t2 || (t2 = _t), r3 || (r3 = _t); const n2 = [], o2 = this.tree.language.types; for (let t3 = 0, r4 = o2.length; t3 < r4; t3++) e3.includes(o2[t3]) && n2.push(t3); const s2 = et._malloc(rt * n2.length); for (let e4 = 0, t3 = n2.length; e4 < t3; e4++) x(s2 + e4 * rt, n2[e4], "i32"); yt(this), et._ts_node_descendants_of_type_wasm(this.tree[0], s2, n2.length, t2.row, t2.column, r3.row, r3.column); const _2 = N(mt, "i32"), a2 = N(mt + rt, "i32"), i2 = new Array(_2); if (_2 > 0) { let e4 = a2; for (let t3 = 0; t3 < _2; t3++) i2[t3] = bt(this.tree, e4), e4 += nt; } return et._free(a2), et._free(s2), i2; } get nextSibling() { return yt(this), et._ts_node_next_sibling_wasm(this.tree[0]), bt(this.tree); } get previousSibling() { return yt(this), et._ts_node_prev_sibling_wasm(this.tree[0]), bt(this.tree); } get nextNamedSibling() { return yt(this), et._ts_node_next_named_sibling_wasm(this.tree[0]), bt(this.tree); } get previousNamedSibling() { return yt(this), et._ts_node_prev_named_sibling_wasm(this.tree[0]), bt(this.tree); } get parent() { return yt(this), et._ts_node_parent_wasm(this.tree[0]), bt(this.tree); } descendantForIndex(e3, t2 = e3) { if ("number" != typeof e3 || "number" != typeof t2) throw new Error("Arguments must be numbers"); yt(this); let r3 = mt + nt; return x(r3, e3, "i32"), x(r3 + rt, t2, "i32"), et._ts_node_descendant_for_index_wasm(this.tree[0]), bt(this.tree); } namedDescendantForIndex(e3, t2 = e3) { if ("number" != typeof e3 || "number" != typeof t2) throw new Error("Arguments must be numbers"); yt(this); let r3 = mt + nt; return x(r3, e3, "i32"), x(r3 + rt, t2, "i32"), et._ts_node_named_descendant_for_index_wasm(this.tree[0]), bt(this.tree); } descendantForPosition(e3, t2 = e3) { if (!Mt(e3) || !Mt(t2)) throw new Error("Arguments must be {row, column} objects"); yt(this); let r3 = mt + nt; return St(r3, e3), St(r3 + ot, t2), et._ts_node_descendant_for_position_wasm(this.tree[0]), bt(this.tree); } namedDescendantForPosition(e3, t2 = e3) { if (!Mt(e3) || !Mt(t2)) throw new Error("Arguments must be {row, column} objects"); yt(this); let r3 = mt + nt; return St(r3, e3), St(r3 + ot, t2), et._ts_node_named_descendant_for_position_wasm(this.tree[0]), bt(this.tree); } walk() { return yt(this), et._ts_tree_cursor_new_wasm(this.tree[0]), new TreeCursor(tt, this.tree); } toString() { yt(this); const e3 = et._ts_node_to_string_wasm(this.tree[0]), t2 = function(e4) { for (var t3 = ""; ; ) { var r3 = T[e4++ >> 0]; if (!r3) return t3; t3 += String.fromCharCode(r3); } }(e3); return et._free(e3), t2; } } class TreeCursor { constructor(e3, t2) { wt(e3), this.tree = t2, Et(this); } delete() { vt(this), et._ts_tree_cursor_delete_wasm(this.tree[0]), this[0] = this[1] = this[2] = 0; } reset(e3) { yt(e3), vt(this, mt + nt), et._ts_tree_cursor_reset_wasm(this.tree[0]), Et(this); } get nodeType() { return this.tree.language.types[this.nodeTypeId] || "ERROR"; } get nodeTypeId() { return vt(this), et._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]); } get nodeId() { return vt(this), et._ts_tree_cursor_current_node_id_wasm(this.tree[0]); } get nodeIsNamed() { return vt(this), 1 === et._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]); } get nodeIsMissing() { return vt(this), 1 === et._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]); } get nodeText() { vt(this); const e3 = et._ts_tree_cursor_start_index_wasm(this.tree[0]), t2 = et._ts_tree_cursor_end_index_wasm(this.tree[0]); return ht(this.tree, e3, t2); } get startPosition() { return vt(this), et._ts_tree_cursor_start_position_wasm(this.tree[0]), It(mt); } get endPosition() { return vt(this), et._ts_tree_cursor_end_position_wasm(this.tree[0]), It(mt); } get startIndex() { return vt(this), et._ts_tree_cursor_start_index_wasm(this.tree[0]); } get endIndex() { return vt(this), et._ts_tree_cursor_end_index_wasm(this.tree[0]); } currentNode() { return vt(this), et._ts_tree_cursor_current_node_wasm(this.tree[0]), bt(this.tree); } currentFieldId() { return vt(this), et._ts_tree_cursor_current_field_id_wasm(this.tree[0]); } currentFieldName() { return this.tree.language.fields[this.currentFieldId()]; } gotoFirstChild() { vt(this); const e3 = et._ts_tree_cursor_goto_first_child_wasm(this.tree[0]); return Et(this), 1 === e3; } gotoNextSibling() { vt(this); const e3 = et._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]); return Et(this), 1 === e3; } gotoParent() { vt(this); const e3 = et._ts_tree_cursor_goto_parent_wasm(this.tree[0]); return Et(this), 1 === e3; } } class Language { constructor(e3, t2) { wt(e3), this[0] = t2, this.types = new Array(et._ts_language_symbol_count(this[0])); for (let e4 = 0, t3 = this.types.length; e4 < t3; e4++) et._ts_language_symbol_type(this[0], e4) < 2 && (this.types[e4] = Z(et._ts_language_symbol_name(this[0], e4))); this.fields = new Array(et._ts_language_field_count(this[0]) + 1); for (let e4 = 0, t3 = this.fields.length; e4 < t3; e4++) { const t4 = et._ts_language_field_name_for_id(this[0], e4); this.fields[e4] = 0 !== t4 ? Z(t4) : null; } } get version() { return et._ts_language_version(this[0]); } get fieldCount() { return this.fields.length - 1; } fieldIdForName(e3) { const t2 = this.fields.indexOf(e3); return -1 !== t2 ? t2 : null; } fieldNameForId(e3) { return this.fields[e3] || null; } idForNodeType(e3, t2) { const r3 = U(e3), n2 = et._malloc(r3 + 1); z(e3, n2, r3 + 1); const o2 = et._ts_language_symbol_for_name(this[0], n2, r3, t2); return et._free(n2), o2 || null; } get nodeTypeCount() { return et._ts_language_symbol_count(this[0]); } nodeTypeForId(e3) { const t2 = et._ts_language_symbol_name(this[0], e3); return t2 ? Z(t2) : null; } nodeTypeIsNamed(e3) { return !!et._ts_language_type_is_named_wasm(this[0], e3); } nodeTypeIsVisible(e3) { return !!et._ts_language_type_is_visible_wasm(this[0], e3); } query(e3) { const t2 = U(e3), r3 = et._malloc(t2 + 1); z(e3, r3, t2 + 1); const n2 = et._ts_query_new(this[0], r3, t2, mt, mt + rt); if (!n2) { const t3 = N(mt + rt, "i32"), n3 = Z(r3, N(mt, "i32")).length, o3 = e3.substr(n3, 100).split("\n")[0]; let s3, _3 = o3.match(at)[0]; switch (t3) { case 2: s3 = new RangeError(`Bad node name '${_3}'`); break; case 3: s3 = new RangeError(`Bad field name '${_3}'`); break; case 4: s3 = new RangeError(`Bad capture name @${_3}`); break; case 5: s3 = new TypeError(`Bad pattern structure at offset ${n3}: '${o3}'...`), _3 = ""; break; default: s3 = new SyntaxError(`Bad syntax at offset ${n3}: '${o3}'...`), _3 = ""; } throw s3.index = n3, s3.length = _3.length, et._free(r3), s3; } const o2 = et._ts_query_string_count(n2), s2 = et._ts_query_capture_count(n2), _2 = et._ts_query_pattern_count(n2), a2 = new Array(s2), i2 = new Array(o2); for (let e4 = 0; e4 < s2; e4++) { const t3 = et._ts_query_capture_name_for_id(n2, e4, mt), r4 = N(mt, "i32"); a2[e4] = Z(t3, r4); } for (let e4 = 0; e4 < o2; e4++) { const t3 = et._ts_query_string_value_for_id(n2, e4, mt), r4 = N(mt, "i32"); i2[e4] = Z(t3, r4); } const u2 = new Array(_2), l2 = new Array(_2), d2 = new Array(_2), c3 = new Array(_2), m2 = new Array(_2); for (let e4 = 0; e4 < _2; e4++) { const t3 = et._ts_query_predicates_for_pattern(n2, e4, mt), r4 = N(mt, "i32"); c3[e4] = [], m2[e4] = []; const o3 = []; let s3 = t3; for (let t4 = 0; t4 < r4; t4++) { const t5 = N(s3, "i32"), r5 = N(s3 += rt, "i32"); if (s3 += rt, t5 === it) o3.push({ type: "capture", name: a2[r5] }); else if (t5 === ut) o3.push({ type: "string", value: i2[r5] }); else if (o3.length > 0) { if ("string" !== o3[0].type) throw new Error("Predicates must begin with a literal value"); const t6 = o3[0].value; let r6 = true; switch (t6) { case "not-eq?": r6 = false; case "eq?": if (3 !== o3.length) throw new Error(`Wrong number of arguments to \`#eq?\` predicate. Expected 2, got ${o3.length - 1}`); if ("capture" !== o3[1].type) throw new Error(`First argument of \`#eq?\` predicate must be a capture. Got "${o3[1].value}"`); if ("capture" === o3[2].type) { const t7 = o3[1].name, n4 = o3[2].name; m2[e4].push(function(e5) { let o4, s5; for (const r7 of e5) r7.name === t7 && (o4 = r7.node), r7.name === n4 && (s5 = r7.node); return void 0 === o4 || void 0 === s5 || o4.text === s5.text === r6; }); } else { const t7 = o3[1].name, n4 = o3[2].value; m2[e4].push(function(e5) { for (const o4 of e5) if (o4.name === t7) return o4.node.text === n4 === r6; return true; }); } break; case "not-match?": r6 = false; case "match?": if (3 !== o3.length) throw new Error(`Wrong number of arguments to \`#match?\` predicate. Expected 2, got ${o3.length - 1}.`); if ("capture" !== o3[1].type) throw new Error(`First argument of \`#match?\` predicate must be a capture. Got "${o3[1].value}".`); if ("string" !== o3[2].type) throw new Error(`Second argument of \`#match?\` predicate must be a string. Got @${o3[2].value}.`); const n3 = o3[1].name, s4 = new RegExp(o3[2].value); m2[e4].push(function(e5) { for (const t7 of e5) if (t7.name === n3) return s4.test(t7.node.text) === r6; return true; }); break; case "set!": if (o3.length < 2 || o3.length > 3) throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${o3.length - 1}.`); if (o3.some((e5) => "string" !== e5.type)) throw new Error('Arguments to `#set!` predicate must be a strings.".'); u2[e4] || (u2[e4] = {}), u2[e4][o3[1].value] = o3[2] ? o3[2].value : null; break; case "is?": case "is-not?": if (o3.length < 2 || o3.length > 3) throw new Error(`Wrong number of arguments to \`#${t6}\` predicate. Expected 1 or 2. Got ${o3.length - 1}.`); if (o3.some((e5) => "string" !== e5.type)) throw new Error(`Arguments to \`#${t6}\` predicate must be a strings.".`); const _3 = "is?" === t6 ? l2 : d2; _3[e4] || (_3[e4] = {}), _3[e4][o3[1].value] = o3[2] ? o3[2].value : null; break; default: c3[e4].push({ operator: t6, operands: o3.slice(1) }); } o3.length = 0; } } Object.freeze(u2[e4]), Object.freeze(l2[e4]), Object.freeze(d2[e4]); } return et._free(r3), new Query(tt, n2, a2, m2, c3, Object.freeze(u2), Object.freeze(l2), Object.freeze(d2)); } static load(e3) { let t2; if (e3 instanceof Uint8Array) t2 = Promise.resolve(e3); else { const r4 = e3; if ("undefined" != typeof process && process.versions && process.versions.node) { const e4 = require$$1; t2 = Promise.resolve(e4.readFileSync(r4)); } else t2 = fetch(r4).then((e4) => e4.arrayBuffer().then((t3) => { if (e4.ok) return new Uint8Array(t3); { const r5 = new TextDecoder("utf-8").decode(t3); throw new Error(`Language.load failed with status ${e4.status}. ${r5}`); } })); } const r3 = "function" == typeof loadSideModule ? loadSideModule : xe; return t2.then((e4) => r3(e4, { loadAsync: true })).then((e4) => { const t3 = Object.keys(e4), r4 = t3.find((e5) => lt.test(e5) && !e5.includes("external_scanner_")); r4 || console.log(`Couldn't find language function in WASM file. Symbols: ${JSON.stringify(t3, null, 2)}`); const n2 = e4[r4](); return new Language(tt, n2); }); } } class Query { constructor(e3, t2, r3, n2, o2, s2, _2, a2) { wt(e3), this[0] = t2, this.captureNames = r3, this.textPredicates = n2, this.predicates = o2, this.setProperties = s2, this.assertedProperties = _2, this.refutedProperties = a2, this.exceededMatchLimit = false; } delete() { et._ts_query_delete(this[0]), this[0] = 0; } matches(e3, t2, r3, n2) { t2 || (t2 = _t), r3 || (r3 = _t), n2 || (n2 = {}); let o2 = n2.matchLimit; if (void 0 === o2) o2 = 0; else if ("number" != typeof o2) throw new Error("Arguments must be numbers"); yt(e3), et._ts_query_matches_wasm(this[0], e3.tree[0], t2.row, t2.column, r3.row, r3.column, o2); const s2 = N(mt, "i32"), _2 = N(mt + rt, "i32"), a2 = N(mt + 2 * rt, "i32"), i2 = new Array(s2); this.exceededMatchLimit = !!a2; let u2 = 0, l2 = _2; for (let t3 = 0; t3 < s2; t3++) { const r4 = N(l2, "i32"), n3 = N(l2 += rt, "i32"); l2 += rt; const o3 = new Array(n3); if (l2 = gt(this, e3.tree, l2, o3), this.textPredicates[r4].every((e4) => e4(o3))) { i2[u2++] = { pattern: r4, captures: o3 }; const e4 = this.setProperties[r4]; e4 && (i2[t3].setProperties = e4); const n4 = this.assertedProperties[r4]; n4 && (i2[t3].assertedProperties = n4); const s3 = this.refutedProperties[r4]; s3 && (i2[t3].refutedProperties = s3); } } return i2.length = u2, et._free(_2), i2; } captures(e3, t2, r3, n2) { t2 || (t2 = _t), r3 || (r3 = _t), n2 || (n2 = {}); let o2 = n2.matchLimit; if (void 0 === o2) o2 = 0; else if ("number" != typeof o2) throw new Error("Arguments must be numbers"); yt(e3), et._ts_query_captures_wasm(this[0], e3.tree[0], t2.row, t2.column, r3.row, r3.column, o2); const s2 = N(mt, "i32"), _2 = N(mt + rt, "i32"), a2 = N(mt + 2 * rt, "i32"), i2 = []; this.exceededMatchLimit = !!a2; const u2 = []; let l2 = _2; for (let t3 = 0; t3 < s2; t3++) { const t4 = N(l2, "i32"), r4 = N(l2 += rt, "i32"), n3 = N(l2 += rt, "i32"); if (l2 += rt, u2.length = r4, l2 = gt(this, e3.tree, l2, u2), this.textPredicates[t4].every((e4) => e4(u2))) { const e4 = u2[n3], r5 = this.setProperties[t4]; r5 && (e4.setProperties = r5); const o3 = this.assertedProperties[t4]; o3 && (e4.assertedProperties = o3); const s3 = this.refutedProperties[t4]; s3 && (e4.refutedProperties = s3), i2.push(e4); } } return et._free(_2), i2; } predicatesForPattern(e3) { return this.predicates[e3]; } didExceedMatchLimit() { return this.exceededMatchLimit; } } function ht(e3, t2, r3) { const n2 = r3 - t2; let o2 = e3.textCallback(t2, null, r3); for (t2 += o2.length; t2 < r3; ) { const n3 = e3.textCallback(t2, null, r3); if (!(n3 && n3.length > 0)) break; t2 += n3.length, o2 += n3; } return t2 > r3 && (o2 = o2.slice(0, n2)), o2; } function gt(e3, t2, r3, n2) { for (let o2 = 0, s2 = n2.length; o2 < s2; o2++) { const s3 = N(r3, "i32"), _2 = bt(t2, r3 += rt); r3 += nt, n2[o2] = { name: e3.captureNames[s3], node: _2 }; } return r3; } function wt(e3) { if (e3 !== tt) throw new Error("Illegal constructor"); } function Mt(e3) { return e3 && "number" == typeof e3.row && "number" == typeof e3.column; } function yt(e3) { let t2 = mt; x(t2, e3.id, "i32"), x(t2 += rt, e3.startIndex, "i32"), x(t2 += rt, e3.startPosition.row, "i32"), x(t2 += rt, e3.startPosition.column, "i32"), x(t2 += rt, e3[0], "i32"); } function bt(e3, t2 = mt) { const r3 = N(t2, "i32"); if (0 === r3) return null; const n2 = N(t2 += rt, "i32"), o2 = N(t2 += rt, "i32"), s2 = N(t2 += rt, "i32"), _2 = N(t2 += rt, "i32"), a2 = new Node(tt, e3); return a2.id = r3, a2.startIndex = n2, a2.startPosition = { row: o2, column: s2 }, a2[0] = _2, a2; } function vt(e3, t2 = mt) { x(t2 + 0 * rt, e3[0], "i32"), x(t2 + 1 * rt, e3[1], "i32"), x(t2 + 2 * rt, e3[2], "i32"); } function Et(e3) { e3[0] = N(mt + 0 * rt, "i32"), e3[1] = N(mt + 1 * rt, "i32"), e3[2] = N(mt + 2 * rt, "i32"); } function St(e3, t2) { x(e3, t2.row, "i32"), x(e3 + rt, t2.column, "i32"); } function It(e3) { return { row: N(e3, "i32"), column: N(e3 + rt, "i32") }; } function At(e3, t2) { St(e3, t2.startPosition), St(e3 += ot, t2.endPosition), x(e3 += ot, t2.startIndex, "i32"), x(e3 += rt, t2.endIndex, "i32"), e3 += rt; } function xt(e3) { const t2 = {}; return t2.startPosition = It(e3), e3 += ot, t2.endPosition = It(e3), e3 += ot, t2.startIndex = N(e3, "i32"), e3 += rt, t2.endIndex = N(e3, "i32"), t2; } for (const e3 of Object.getOwnPropertyNames(ParserImpl.prototype)) Object.defineProperty(Parser2.prototype, e3, { value: ParserImpl.prototype[e3], enumerable: false, writable: false }); Parser2.Language = Language, Module.onRuntimeInitialized = () => { ParserImpl.init(), e2(); }; })); } } return Parser2; }(); module.exports = TreeSitter; })(treeSitter); var treeSitterExports = treeSitter.exports; const Parser = /* @__PURE__ */ getDefaultExportFromCjs(treeSitterExports); const treeSitterShadeupURL = ""; async function getShadeupParser() { if (typeof process === "object" && process.versions && process.versions.node) { return global.shadeupParser(); } let url = treeSitterShadeupURL; let shadeUrl = treeSitterShadeupURL; await Parser.init({ locateFile(scriptName, scriptDirectory) { return url; } }); const parser = new Parser(); parser.setLanguage(await Parser.Language.load(shadeUrl)); return parser; } class AstContext { constructor(fileName) { this.impls = /* @__PURE__ */ new Map(); this.implsFor = /* @__PURE__ */ new Map(); this.shaders = []; this.diagnostics = []; this.globals = []; this.fileName = fileName; } report(node2, message) { this.diagnostics.push({ message, node: node2 }); } addImpl(name, node2) { if (this.impls.has(name)) { this.impls.get(name).push(node2); } else { this.impls.set(name, [node2]); } } addImplFor(name, node2) { if (this.implsFor.has(name)) { this.implsFor.get(name).push(node2); } else { this.implsFor.set(name, [node2]); } } } const stdMath = "export type bool = boolean;\r\nexport type float = number & { _opaque_float: 2 };\r\nexport type int = number & { _opaque_int: 1 } & float;\r\nexport type uint = number & { _opaque_uint: 1 };\r\ntype scalar = float | int | uint;\r\n\r\nexport type float2 = [float, float] & { _opaque_vector_float_2: 2; length: 2 };\r\nexport type float3 = [float, float, float] & { _opaque_vector_float_3: 3; length: 3 };\r\nexport type float4 = [float, float, float, float] & { _opaque_vector_float_4: 4; length: 4 };\r\nexport type int2 = [int, int] & { _opaque_vector_int_2: 2 } & float2;\r\nexport type int3 = [int, int, int] & { _opaque_vector_int_3: 3 } & float3;\r\nexport type int4 = [int, int, int, int] & { _opaque_vector_int_4: 4 } & float4;\r\n\r\nexport type uint2 = [uint, uint] & { _opaque_vector_uint_2: 2 } & float2;\r\nexport type uint3 = [uint, uint, uint] & { _opaque_vector_uint_3: 3 } & float3;\r\nexport type uint4 = [uint, uint, uint, uint] & { _opaque_vector_uint_4: 4 } & float4;\r\n\r\nexport type uint8 = number & { _opaque_uint8: 1 };\r\n\r\ntype anyFloat = float2 | float3 | float4;\r\ntype anyInt = int2 | int3 | int4;\r\ntype anyUint = uint2 | uint3 | uint4;\r\n\r\ntype vector2 = float2 | int2 | uint2;\r\ntype vector3 = float3 | int3 | uint3;\r\ntype vector4 = float4 | int4 | uint4;\r\n\r\ntype vector = vector2 | vector3 | vector4;\r\n\r\ntype vectorOrScalar = vector | scalar;\r\n\r\nexport interface float2x2 extends Omit<[float, float, float, float], '__index'> {\r\n __matrix: 2;\r\n [index: int]: float;\r\n __index(index: number): [float, float];\r\n}\r\n\r\nexport interface float3x3\r\n extends Omit<[float, float, float, float, float, float, float, float, float], '__index'> {\r\n __matrix: 3;\r\n [index: int]: float;\r\n __index(index: number): [float, float, float];\r\n}\r\n\r\nexport interface float4x4\r\n extends Omit<\r\n [\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float\r\n ],\r\n '__index'\r\n > {\r\n __matrix: 4;\r\n [index: int]: float;\r\n __index(index: number): [float, float, float, float];\r\n}\r\n\r\nfunction isVector(v: vectorOrScalar): v is vector {\r\n return Array.isArray(v);\r\n}\r\n\r\nfunction isScalar(v: vectorOrScalar): v is scalar {\r\n return typeof v === 'number';\r\n}\r\n\r\nfunction isMatrix(v: number[]): v is float2x2 | float3x3 | float4x4 {\r\n return !!(v as any).__matrix;\r\n}\r\n\r\n/** @shadeup=glsl(!mat2(0)) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(): float2x2;\r\n/** @shadeup=glsl(mat2) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(m00: number, m01: number, m10: number, m11: number): float2x2;\r\n/** @shadeup=glsl(mat2) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(...args: float[]): float2x2 {\r\n let arr = [0, 0, 0, 0] as any as float2x2;\r\n if (args.length === 4) {\r\n arr = [...args] as any as float2x2;\r\n }\r\n\r\n applyMatrix2x2Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\n/** @shadeup=glsl(!mat3(0)) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(): float3x3;\r\n/** @shadeup=glsl(mat3) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(\r\n m00: number,\r\n m01: number,\r\n m02: number,\r\n m10: number,\r\n m11: number,\r\n m12: number,\r\n m20: number,\r\n m21: number,\r\n m22: number\r\n): float3x3;\r\n/** @shadeup=glsl(mat3) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(...args: float[]): float3x3 {\r\n let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0] as any as float3x3;\r\n if (args.length === 9) {\r\n arr = [...args] as any as float3x3;\r\n }\r\n\r\n applyMatrix3x3Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\nfunction applyMatrix4x4Methods(arr: float4x4): void {\r\n (arr as any).__matrix = 4;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 4], arr[index * 4 + 1], arr[index * 4 + 2], arr[index * 4 + 3]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 4 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 4 + index_inner] = op_fn(arr[index * 4 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float4) {\r\n arr[index * 4] = value[0];\r\n arr[index * 4 + 1] = value[1];\r\n arr[index * 4 + 2] = value[2];\r\n arr[index * 4 + 3] = value[3];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 4] = op_fn(arr[index * 4], value[0]);\r\n arr[index * 4 + 1] = op_fn(arr[index * 4 + 1], value[1]);\r\n arr[index * 4 + 2] = op_fn(arr[index * 4 + 2], value[2]);\r\n arr[index * 4 + 3] = op_fn(arr[index * 4 + 3], value[3]);\r\n };\r\n}\r\n(window as any).applyMatrix4x4Methods = applyMatrix4x4Methods;\r\n\r\nfunction applyMatrix3x3Methods(arr: float3x3): void {\r\n (arr as any).__matrix = 3;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 3], arr[index * 3 + 1], arr[index * 3 + 2]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 3 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 3 + index_inner] = op_fn(arr[index * 3 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float3) {\r\n arr[index * 3] = value[0];\r\n arr[index * 3 + 1] = value[1];\r\n arr[index * 3 + 2] = value[2];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 3] = op_fn(arr[index * 3], value[0]);\r\n arr[index * 3 + 1] = op_fn(arr[index * 3 + 1], value[1]);\r\n arr[index * 3 + 2] = op_fn(arr[index * 3 + 2], value[2]);\r\n };\r\n}\r\n\r\n(window as any).applyMatrix3x3Methods = applyMatrix3x3Methods;\r\n\r\nfunction applyMatrix2x2Methods(arr: float2x2): void {\r\n (arr as any).__matrix = 2;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 2], arr[index * 2 + 1]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 2 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 2 + index_inner] = op_fn(arr[index * 2 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float3) {\r\n arr[index * 2] = value[0];\r\n arr[index * 2 + 1] = value[1];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 2] = op_fn(arr[index * 2], value[0]);\r\n arr[index * 2 + 1] = op_fn(arr[index * 2 + 1], value[1]);\r\n };\r\n}\r\n\r\n(window as any).applyMatrix2x2Methods = applyMatrix2x2Methods;\r\n\r\n/** @shadeup=glsl(!mat4(0)) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(): float4x4;\r\n/** @shadeup=glsl(mat4) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(\r\n m00: number,\r\n m01: number,\r\n m02: number,\r\n m03: number,\r\n m10: number,\r\n m11: number,\r\n m12: number,\r\n m13: number,\r\n m20: number,\r\n m21: number,\r\n m22: number,\r\n m23: number,\r\n m30: number,\r\n m31: number,\r\n m32: number,\r\n m33: number\r\n): float4x4;\r\n/** @shadeup=glsl(mat4) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(...args: float[]): float4x4 {\r\n let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] as any as float4x4;\r\n if (args.length === 16) {\r\n arr = [...args] as any as float4x4;\r\n }\r\n\r\n applyMatrix4x4Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\n/** @shadeup=glsl(float) @shadeup=wgsl(f32) */\r\nexport function float(x: number): float {\r\n return x as float;\r\n}\r\n\r\n/** @shadeup=glsl(int) @shadeup=wgsl(i32) */\r\nexport function int(x: number): int {\r\n return (x | 0) as int;\r\n}\r\n\r\n/** @shadeup=glsl(uint) @shadeup=wgsl(u32) */\r\nexport function uint(x: number): uint {\r\n return (x >>> 0) as uint;\r\n}\r\n\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(x: number, y: number): float2;\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(xy: vector2): float2;\r\n\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(...args: (vectorOrScalar | number)[]): float2 {\r\n return args.flat() as float2;\r\n}\r\n\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(x: number, y: number, z: number): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(xy: vector2, z: number): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(x: number, yz: vector2): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(xyz: vector3): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(...args: (vectorOrScalar | number)[]): float3 {\r\n return args.flat() as float3;\r\n}\r\n\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, y: number, z: number, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, yz: vector2, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xy: vector2, z: number, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, y: number, zw: vector2): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xy: vector2, zw: vector2): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xyz: vector3, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, yzw: vector3): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xyzw: int4): float4;\r\nexport function float4(xyzw: float4): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(...args: (vectorOrScalar | number)[]): float4 {\r\n return args.flat() as float4;\r\n}\r\n\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(x: number, y: number): int2;\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(xy: vector2): int2;\r\n\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(...args: (vectorOrScalar | number)[]): int2 {\r\n return args.flat().map((x) => x | 0) as int2;\r\n}\r\n\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(x: number, y: number, z: number): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(xy: vector2, z: number): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(x: number, yz: vector2): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(xyz: vector3): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(...args: (vectorOrScalar | number)[]): int3 {\r\n return args.flat().map((x) => x | 0) as int3;\r\n}\r\n\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, y: number, z: number, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, yz: vector2, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xy: vector2, z: number, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, y: number, zw: vector2): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xy: vector2, zw: vector2): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xyz: vector3, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, yzw: vector3): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xyzw: float4): int4;\r\nexport function int4(xyzw: int4): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(...args: (vectorOrScalar | number)[]): int4 {\r\n return args.flat().map((x) => x | 0) as int4;\r\n}\r\n\r\n/** @shadeup=glsl(uint2) @shadeup=wgsl(vec2) */\r\nexport function uint2(x: number, y: number): uint2;\r\n/** @shadeup=glsl(uint2) @shadeup=wgsl(vec2) */\r\nexport function uint2(xy: vector2): uint2;\r\nexport function uint2(...args: (vectorOrScalar | number)[]): uint2 {\r\n return args.flat().map((x) => x >>> 0) as uint2;\r\n}\r\n\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(x: number, y: number, z: number): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(xy: vector2, z: number): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(x: number, yz: vector2): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(xyz: vector3): uint3;\r\nexport function uint3(...args: (vectorOrScalar | number)[]): uint3 {\r\n return args.flat().map((x) => x >>> 0) as uint3;\r\n}\r\n\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, y: number, z: number, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, yz: vector2, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(xy: vector2, z: number, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, y: number, zw: vector2): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(xy: vector2, zw: vector2): uint4;\r\nexport function uint4(xyz: vector3, w: number): uint4;\r\nexport function uint4(x: number, yzw: vector3): uint4;\r\nexport function uint4(xyzw: float4): uint4;\r\nexport function uint4(xyzw: uint4): uint4;\r\nexport function uint4(...args: (vectorOrScalar | number)[]): uint4 {\r\n return args.flat().map((x) => x >>> 0) as uint4;\r\n}\r\n\r\nexport function uint8(x: number): uint8 {\r\n return ((x >>> 0) & 0xff) as uint8;\r\n}\r\n\r\nfunction componentMath(a: any, b: any, f: (a: number, b: number) => number): vectorOrScalar {\r\n let aIsScalar = isScalar(a);\r\n let bIsScalar = isScalar(b);\r\n if (aIsScalar && bIsScalar) {\r\n return f(a, b) as scalar;\r\n }\r\n if (!aIsScalar && !bIsScalar) {\r\n if (a.length !== b.length) {\r\n throw new Error('Cannot perform component-wise math on vectors of different lengths');\r\n }\r\n // return a.map((a, i) => f(a, b[i])) as vector;\r\n if (a.length == 2) {\r\n return [f(a[0], b[0]), f(a[1], b[1])] as vector;\r\n } else if (a.length == 3) {\r\n return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2])] as vector;\r\n } else if (a.length == 4) {\r\n return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2]), f(a[3], b[3])] as vector;\r\n }\r\n } else if (!aIsScalar && bIsScalar) {\r\n if (a.length == 2) {\r\n return [f(a[0], b), f(a[1], b)] as vector;\r\n } else if (a.length == 3) {\r\n return [f(a[0], b), f(a[1], b), f(a[2], b)] as vector;\r\n } else if (a.length == 4) {\r\n return [f(a[0], b), f(a[1], b), f(a[2], b), f(a[3], b)] as vector;\r\n }\r\n } else if (!bIsScalar && aIsScalar) {\r\n if (b.length == 2) {\r\n return [f(a, b[0]), f(a, b[1])] as vector;\r\n } else if (b.length == 3) {\r\n return [f(a, b[0]), f(a, b[1]), f(a, b[2])] as vector;\r\n } else if (b.length == 4) {\r\n return [f(a, b[0]), f(a, b[1]), f(a, b[2]), f(a, b[3])] as vector;\r\n }\r\n }\r\n\r\n throw new Error('Cannot perform component-wise math on a scalar and a vector');\r\n}\r\n\r\nfunction componentMathSingular(a: vectorOrScalar, f: (a: number) => number): vectorOrScalar {\r\n if (isScalar(a)) {\r\n return f(a) as scalar;\r\n }\r\n if (isVector(a)) {\r\n return a.map((a, i) => f(a)) as vector;\r\n }\r\n\r\n throw new Error('Cannot perform component-wise math on a scalar and a vector');\r\n}\r\n\r\ntype cCallCb = (a: number, b: number) => number;\r\ntype cCallCbSingle = (a: number) => number;\r\n\r\nfunction cCall(cb: cCallCb, a: scalar, b: scalar): scalar;\r\nfunction cCall(cb: cCallCb, a: vector, b: scalar): vector;\r\nfunction cCall(cb: cCallCb, a: vector2, b: vector2): vector2;\r\nfunction cCall(cb: cCallCb, a: vector3, b: vector3): vector3;\r\nfunction cCall(cb: cCallCb, a: vector4, b: vector4): vector4;\r\nfunction cCall(cb: cCallCb, a: vectorOrScalar, b: vectorOrScalar): vectorOrScalar {\r\n return componentMath(a, b, (a, b) => a + b);\r\n}\r\n\r\nexport type vectorOverload_2to1_3to3 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float3;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int3;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float3;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float3;\r\n};\r\nexport type vectorOverload_2to1_3to3_4to4 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float3;\r\n (a: float4, b: int4): float4;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float3;\r\n (a: int4, b: float4): float4;\r\n};\r\nexport type vectorOverload_2to1_3to1_4to1 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float;\r\n (a: float4, b: float4): float;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int;\r\n (a: int4, b: int4): int;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float;\r\n (a: float4, b: int4): float;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float;\r\n (a: int4, b: float4): float;\r\n};\r\n\r\nexport type componentOverload = {\r\n (a: int, b: int): int;\r\n (a: int2, b: int2): int2;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n\r\n (a: int, b: float): float;\r\n (a: float, b: int): float;\r\n\r\n (a: float, b: float): float;\r\n\r\n (a: float2, b: float): float2;\r\n (a: float3, b: float): float3;\r\n (a: float4, b: float): float4;\r\n\r\n (a: int2, b: int): int2;\r\n (a: int3, b: int): int3;\r\n (a: int4, b: int): int4;\r\n\r\n (a: int2, b: float): float2;\r\n (a: int3, b: float): float3;\r\n (a: int4, b: float): float4;\r\n\r\n (a: float2, b: int): float2;\r\n (a: float3, b: int): float3;\r\n (a: float4, b: int): float4;\r\n (a: float2, b: float): float2;\r\n\r\n (a: float, b: float2): float2;\r\n (a: float, b: float3): float3;\r\n (a: float, b: float4): float4;\r\n\r\n (a: int, b: int2): int2;\r\n (a: int, b: int3): int3;\r\n (a: int, b: int4): int4;\r\n\r\n (a: float, b: int2): float2;\r\n (a: float, b: int3): float3;\r\n (a: float, b: int4): float4;\r\n\r\n (a: int, b: float2): float2;\r\n (a: int, b: float3): float3;\r\n (a: int, b: float4): float4;\r\n\r\n (a: float2, b: float2): float2;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n\r\n (a: float2, b: int2): float2;\r\n (a: float3, b: int3): float3;\r\n (a: float4, b: int4): float4;\r\n\r\n (a: int2, b: float2): float2;\r\n (a: int3, b: float3): float3;\r\n (a: int4, b: float4): float4;\r\n\r\n (a: uint, b: uint): uint;\r\n (a: uint2, b: uint2): uint2;\r\n (a: uint3, b: uint3): uint3;\r\n (a: uint4, b: uint4): uint4;\r\n};\r\n\r\nexport type componentOverloadMatch = {\r\n (a: uint, b: uint): uint;\r\n (a: uint2, b: uint2): uint2;\r\n (a: uint3, b: uint3): uint3;\r\n (a: uint4, b: uint4): uint4;\r\n (a: uint2, b: uint): uint2;\r\n (a: uint3, b: uint): uint3;\r\n (a: uint4, b: uint): uint4;\r\n\r\n (a: int, b: int): int;\r\n (a: int2, b: int2): int2;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n (a: int2, b: int): int2;\r\n (a: int3, b: int): int3;\r\n (a: int4, b: int): int4;\r\n\r\n (a: float, b: float): float;\r\n (a: float2, b: float2): float2;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n (a: float2, b: float): float2;\r\n (a: float3, b: float): float3;\r\n (a: float4, b: float): float4;\r\n};\r\n\r\nexport type componentOverloadSingular = {\r\n (a: int): int;\r\n (a: float): float;\r\n\r\n (a: float2): float2;\r\n (a: float3): float3;\r\n (a: float4): float4;\r\n\r\n (a: int2): int2;\r\n (a: int3): int3;\r\n (a: int4): int4;\r\n\r\n (a: uint): uint;\r\n (a: uint2): uint2;\r\n (a: uint3): uint3;\r\n (a: uint4): uint4;\r\n};\r\n\r\nexport type componentOverloadSingularFloat = {\r\n // (a: int): int;\r\n (a: float): float;\r\n\r\n (a: float2): float2;\r\n (a: float3): float3;\r\n (a: float4): float4;\r\n\r\n // (a: int2): int2;\r\n // (a: int3): int3;\r\n // (a: int4): int4;\r\n};\r\n\r\nexport type componentOverloadMatrix = {\r\n (a: float2x2, b: float2): float2;\r\n (a: float3x3, b: float3): float3;\r\n (a: float4x4, b: float4): float4;\r\n\r\n (a: float2, b: float2x2): float2;\r\n (a: float3, b: float3x3): float3;\r\n (a: float4, b: float4x4): float4;\r\n\r\n (a: float2x2, b: float2x2): float2x2;\r\n (a: float3x3, b: float3x3): float3x3;\r\n (a: float4x4, b: float4x4): float4x4;\r\n\r\n (a: float2x2, b: float): float2x2;\r\n (a: float3x3, b: float): float3x3;\r\n (a: float4x4, b: float): float4x4;\r\n\r\n (a: float, b: float2x2): float2x2;\r\n (a: float, b: float3x3): float3x3;\r\n (a: float, b: float4x4): float4x4;\r\n};\r\n\r\nfunction componentOp(cb: cCallCb): componentOverload;\r\n\r\nfunction componentOp(cb: cCallCb) {\r\n return (a: any, b: any) => componentMath(a, b, cb);\r\n}\r\n\r\nfunction componentOpMatch(cb: cCallCb): componentOverloadMatch;\r\nfunction componentOpMatch(cb: cCallCb) {\r\n return (a: any, b: any) => componentMath(a, b, cb);\r\n}\r\n\r\nfunction componentOpSingular(cb: cCallCbSingle): componentOverloadSingular;\r\n\r\nfunction componentOpSingular(cb: cCallCbSingle) {\r\n return (a: any) => componentMathSingular(a, cb);\r\n}\r\n\r\nfunction componentOpSingularFloat(cb: cCallCbSingle): componentOverloadSingularFloat;\r\n\r\nfunction componentOpSingularFloat(cb: cCallCbSingle) {\r\n return (a: any) => componentMathSingular(a, cb);\r\n}\r\n\r\n/** @shadeup=univ(!$0$ + $1$)*/\r\nexport const add: componentOverload & ((a: string, b: string) => string) = (\r\n a: any,\r\n b: any\r\n): any => {\r\n if (typeof a === 'string' && typeof b === 'string') {\r\n return `${a}${b}`;\r\n } else {\r\n let addOp: (a: any, b: any) => any = componentOp((a, b) => a + b);\r\n let v: any = addOp(a, b);\r\n return v;\r\n }\r\n};\r\n\r\n/** @shadeup=univ(!$0$ - $1$)*/\r\nexport const sub = componentOp((a, b) => a - b);\r\n\r\ntype matrix = float2x2 | float3x3 | float4x4;\r\n\r\nfunction matrixMul(a: matrix, b: matrix): matrix {\r\n // Multiply two square matrices of the same dimension row-major\r\n\r\n let dimension = a.__matrix;\r\n\r\n let out: float2x2 | float3x3 | float4x4;\r\n if (dimension === 2) {\r\n out = float2x2();\r\n } else if (dimension === 3) {\r\n out = float3x3();\r\n } else if (dimension === 4) {\r\n var a00 = a[0 * 4 + 0];\r\n var a01 = a[0 * 4 + 1];\r\n var a02 = a[0 * 4 + 2];\r\n var a03 = a[0 * 4 + 3];\r\n var a10 = a[1 * 4 + 0];\r\n var a11 = a[1 * 4 + 1];\r\n var a12 = a[1 * 4 + 2];\r\n var a13 = a[1 * 4 + 3];\r\n var a20 = a[2 * 4 + 0];\r\n var a21 = a[2 * 4 + 1];\r\n var a22 = a[2 * 4 + 2];\r\n var a23 = a[2 * 4 + 3];\r\n var a30 = a[3 * 4 + 0];\r\n var a31 = a[3 * 4 + 1];\r\n var a32 = a[3 * 4 + 2];\r\n var a33 = a[3 * 4 + 3];\r\n var b00 = b[0 * 4 + 0];\r\n var b01 = b[0 * 4 + 1];\r\n var b02 = b[0 * 4 + 2];\r\n var b03 = b[0 * 4 + 3];\r\n var b10 = b[1 * 4 + 0];\r\n var b11 = b[1 * 4 + 1];\r\n var b12 = b[1 * 4 + 2];\r\n var b13 = b[1 * 4 + 3];\r\n var b20 = b[2 * 4 + 0];\r\n var b21 = b[2 * 4 + 1];\r\n var b22 = b[2 * 4 + 2];\r\n var b23 = b[2 * 4 + 3];\r\n var b30 = b[3 * 4 + 0];\r\n var b31 = b[3 * 4 + 1];\r\n var b32 = b[3 * 4 + 2];\r\n var b33 = b[3 * 4 + 3];\r\n return float4x4(\r\n b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30,\r\n b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31,\r\n b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32,\r\n b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33,\r\n b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30,\r\n b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31,\r\n b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32,\r\n b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33,\r\n b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30,\r\n b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31,\r\n b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32,\r\n b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33,\r\n b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30,\r\n b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31,\r\n b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32,\r\n b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33\r\n );\r\n out = float4x4();\r\n }\r\n\r\n for (let i = 0; i < dimension; i++) {\r\n for (let j = 0; j < dimension; j++) {\r\n let sum: float = float(0);\r\n for (let k = 0; k < dimension; k++) {\r\n sum += float(a[i * dimension + k] * b[k * dimension + j]);\r\n }\r\n out[i * dimension + j] = sum;\r\n }\r\n }\r\n\r\n return out;\r\n\r\n if (a.__matrix === 2 && b.__matrix === 2) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a10 = a[2];\r\n let a11 = a[3];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b10 = b[2];\r\n let b11 = b[3];\r\n\r\n let v = float2x2(\r\n a00 * b00 + a01 * b10,\r\n a00 * b01 + a01 * b11,\r\n a10 * b00 + a11 * b10,\r\n a10 * b01 + a11 * b11\r\n );\r\n\r\n return v;\r\n } else if (a.__matrix === 3 && b.__matrix === 3) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a02 = a[2];\r\n let a10 = a[3];\r\n let a11 = a[4];\r\n let a12 = a[5];\r\n let a20 = a[6];\r\n let a21 = a[7];\r\n let a22 = a[8];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b02 = b[2];\r\n let b10 = b[3];\r\n let b11 = b[4];\r\n let b12 = b[5];\r\n let b20 = b[6];\r\n let b21 = b[7];\r\n let b22 = b[8];\r\n\r\n let v = float3x3(\r\n a00 * b00 + a01 * b10 + a02 * b20,\r\n a00 * b01 + a01 * b11 + a02 * b21,\r\n a00 * b02 + a01 * b12 + a02 * b22,\r\n a10 * b00 + a11 * b10 + a12 * b20,\r\n a10 * b01 + a11 * b11 + a12 * b21,\r\n a10 * b02 + a11 * b12 + a12 * b22,\r\n a20 * b00 + a21 * b10 + a22 * b20,\r\n a20 * b01 + a21 * b11 + a22 * b21,\r\n a20 * b02 + a21 * b12 + a22 * b22\r\n );\r\n return v;\r\n } else if (a.__matrix === 4 && b.__matrix === 4) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a02 = a[2];\r\n let a03 = a[3];\r\n let a10 = a[4];\r\n let a11 = a[5];\r\n let a12 = a[6];\r\n let a13 = a[7];\r\n let a20 = a[8];\r\n let a21 = a[9];\r\n let a22 = a[10];\r\n let a23 = a[11];\r\n let a30 = a[12];\r\n let a31 = a[13];\r\n let a32 = a[14];\r\n let a33 = a[15];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b02 = b[2];\r\n let b03 = b[3];\r\n let b10 = b[4];\r\n let b11 = b[5];\r\n let b12 = b[6];\r\n let b13 = b[7];\r\n let b20 = b[8];\r\n let b21 = b[9];\r\n let b22 = b[10];\r\n let b23 = b[11];\r\n let b30 = b[12];\r\n let b31 = b[13];\r\n let b32 = b[14];\r\n let b33 = b[15];\r\n\r\n let v = float4x4(\r\n a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30,\r\n a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31,\r\n a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32,\r\n a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33,\r\n a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30,\r\n a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31,\r\n a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32,\r\n a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33,\r\n a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30,\r\n a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31,\r\n a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32,\r\n a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33,\r\n a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30,\r\n a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31,\r\n a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32,\r\n a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33\r\n );\r\n\r\n return v;\r\n } else {\r\n throw new Error('Invalid matrix multiplication');\r\n }\r\n}\r\n\r\nfunction matrixInversefloat2x2(m: float2x2): float2x2 {\r\n let a = m.__index(0).__index(0),\r\n b = m.__index(1).__index(0),\r\n c = m.__index(0).__index(1),\r\n d = m.__index(1).__index(1);\r\n let det = a * d - b * c;\r\n if (det === 0) {\r\n throw new Error('Matrix determinant is zero');\r\n }\r\n let detInv = 1.0 / det;\r\n return float2x2(d * detInv, -b * detInv, -c * detInv, a * detInv);\r\n}\r\nfunction matrixInversefloat3x3(m: float3x3): float3x3 {\r\n let n11 = m.__index(0).__index(0),\r\n n12 = m.__index(1).__index(0),\r\n n13 = m.__index(2).__index(0);\r\n let n21 = m.__index(0).__index(1),\r\n n22 = m.__index(1).__index(1),\r\n n23 = m.__index(2).__index(1);\r\n let n31 = m.__index(0).__index(2),\r\n n32 = m.__index(1).__index(2),\r\n n33 = m.__index(2).__index(2);\r\n let t11 = n33 * n22 - n32 * n23,\r\n t12 = n32 * n13 - n33 * n12,\r\n t13 = n23 * n12 - n22 * n13;\r\n let det = n11 * t11 + n21 * t12 + n31 * t13;\r\n if (det === 0) {\r\n throw new Error('Invalid matrix inverse');\r\n }\r\n let detInv = 1 / det;\r\n let v = float3x3(\r\n t11 * detInv,\r\n (n31 * n23 - n33 * n21) * detInv,\r\n (n32 * n21 - n31 * n22) * detInv,\r\n t12 * detInv,\r\n (n33 * n11 - n31 * n13) * detInv,\r\n (n31 * n12 - n32 * n11) * detInv,\r\n t13 * detInv,\r\n (n21 * n13 - n23 * n11) * detInv,\r\n (n22 * n11 - n21 * n12) * detInv\r\n );\r\n return v;\r\n}\r\nfunction matrixInversefloat4x4(m: float4x4): float4x4 {\r\n var m00 = m[0 * 4 + 0];\r\n var m01 = m[0 * 4 + 1];\r\n var m02 = m[0 * 4 + 2];\r\n var m03 = m[0 * 4 + 3];\r\n var m10 = m[1 * 4 + 0];\r\n var m11 = m[1 * 4 + 1];\r\n var m12 = m[1 * 4 + 2];\r\n var m13 = m[1 * 4 + 3];\r\n var m20 = m[2 * 4 + 0];\r\n var m21 = m[2 * 4 + 1];\r\n var m22 = m[2 * 4 + 2];\r\n var m23 = m[2 * 4 + 3];\r\n var m30 = m[3 * 4 + 0];\r\n var m31 = m[3 * 4 + 1];\r\n var m32 = m[3 * 4 + 2];\r\n var m33 = m[3 * 4 + 3];\r\n var tmp_0 = m22 * m33;\r\n var tmp_1 = m32 * m23;\r\n var tmp_2 = m12 * m33;\r\n var tmp_3 = m32 * m13;\r\n var tmp_4 = m12 * m23;\r\n var tmp_5 = m22 * m13;\r\n var tmp_6 = m02 * m33;\r\n var tmp_7 = m32 * m03;\r\n var tmp_8 = m02 * m23;\r\n var tmp_9 = m22 * m03;\r\n var tmp_10 = m02 * m13;\r\n var tmp_11 = m12 * m03;\r\n var tmp_12 = m20 * m31;\r\n var tmp_13 = m30 * m21;\r\n var tmp_14 = m10 * m31;\r\n var tmp_15 = m30 * m11;\r\n var tmp_16 = m10 * m21;\r\n var tmp_17 = m20 * m11;\r\n var tmp_18 = m00 * m31;\r\n var tmp_19 = m30 * m01;\r\n var tmp_20 = m00 * m21;\r\n var tmp_21 = m20 * m01;\r\n var tmp_22 = m00 * m11;\r\n var tmp_23 = m10 * m01;\r\n\r\n var t0 = tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31 - (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);\r\n var t1 = tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31 - (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);\r\n var t2 = tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31 - (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);\r\n var t3 = tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21 - (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);\r\n\r\n var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);\r\n if (d === 0) {\r\n throw new Error('Invalid matrix inverse');\r\n }\r\n return float4x4(\r\n d * t0,\r\n d * t1,\r\n d * t2,\r\n d * t3,\r\n d * (tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30 - (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30)),\r\n d * (tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30 - (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30)),\r\n d * (tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30 - (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30)),\r\n d * (tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20 - (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20)),\r\n d * (tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33 - (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33)),\r\n d * (tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33 - (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33)),\r\n d * (tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33 - (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33)),\r\n d * (tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23 - (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23)),\r\n d * (tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12 - (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22)),\r\n d * (tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22 - (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02)),\r\n d * (tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02 - (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12)),\r\n d * (tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12 - (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02))\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat2x2(m: float2x2): float2x2 {\r\n return float2x2(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1)\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat3x3(m: float3x3): float3x3 {\r\n return float3x3(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(2).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1),\r\n m.__index(2).__index(1),\r\n m.__index(0).__index(2),\r\n m.__index(1).__index(2),\r\n m.__index(2).__index(2)\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat4x4(m: float4x4): float4x4 {\r\n return float4x4(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(2).__index(0),\r\n m.__index(3).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1),\r\n m.__index(2).__index(1),\r\n m.__index(3).__index(1),\r\n m.__index(0).__index(2),\r\n m.__index(1).__index(2),\r\n m.__index(2).__index(2),\r\n m.__index(3).__index(2),\r\n m.__index(0).__index(3),\r\n m.__index(1).__index(3),\r\n m.__index(2).__index(3),\r\n m.__index(3).__index(3)\r\n );\r\n}\r\n\r\nfunction matrixMul2x2float2(a: float2x2, b: float2): float2 {\r\n let c: number[] = [0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 2; j++) {\r\n for (let i = 0; i < 2; i++) {\r\n c[i] += a[j * 2 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float2;\r\n}\r\n\r\nfunction matrixMul3x3float3(a: float3x3, b: float3): float3 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 3; i++) {\r\n for (let j = 0; j < 3; j++) {\r\n c[i] += a[j * 3 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float3;\r\n}\r\n\r\nfunction matrixMul4x4float4(a: float4x4, b: float4): float4 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 4; j++) {\r\n for (let i = 0; i < 4; i++) {\r\n c[i] += a[j * 4 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float4;\r\n}\r\n\r\nfunction matrixMulfloat22x2(a: float2, b: float2x2): float2 {\r\n let c: number[] = [0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 2; j++) {\r\n for (let i = 0; i < 2; i++) {\r\n c[i] += a[j] * b[i * 2 + j];\r\n }\r\n }\r\n\r\n return c as float2;\r\n}\r\n\r\nfunction matrixMulfloat33x3(a: float3, b: float3x3): float3 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 3; i++) {\r\n for (let j = 0; j < 3; j++) {\r\n c[i] += a[j] * b[i * 3 + j];\r\n }\r\n }\r\n\r\n return c as float3;\r\n}\r\n\r\nfunction matrixMulfloat44x4(a: float4, b: float4x4): float4 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 4; i++) {\r\n for (let j = 0; j < 4; j++) {\r\n c[i] += a[j] * b[i * 4 + j];\r\n }\r\n }\r\n\r\n return c as float4;\r\n}\r\n\r\nlet mulFunc: (a: any, b: any) => any = componentOp((a, b) => a * b);\r\n\r\n/** @shadeup=univ(#matrix_inverse)*/\r\nexport function inverse(a: float2x2): float2x2;\r\nexport function inverse(a: float3x3): float3x3;\r\nexport function inverse(a: float4x4): float4x4;\r\nexport function inverse(a: float2x2 | float3x3 | float4x4): float2x2 | float3x3 | float4x4 {\r\n if (a.__matrix == 2) {\r\n return matrixInversefloat2x2(a as float2x2);\r\n } else if (a.__matrix == 3) {\r\n return matrixInversefloat3x3(a as float3x3);\r\n } else if (a.__matrix == 4) {\r\n return matrixInversefloat4x4(a as float4x4);\r\n }\r\n}\r\n\r\n/** @shadeup=univ(#matrix_transpose)*/\r\nexport function transpose(a: float2x2): float2x2;\r\nexport function transpose(a: float3x3): float3x3;\r\nexport function transpose(a: float4x4): float4x4;\r\nexport function transpose(a: float2x2 | float3x3 | float4x4): float2x2 | float3x3 | float4x4 {\r\n if (a.__matrix == 2) {\r\n return matrixTransposefloat2x2(a as float2x2);\r\n } else if (a.__matrix == 3) {\r\n return matrixTransposefloat3x3(a as float3x3);\r\n } else if (a.__matrix == 4) {\r\n return matrixTransposefloat4x4(a as float4x4);\r\n }\r\n}\r\n\r\n/** @shadeup=univ(!$0$ * $1$)*/\r\nexport const mul: componentOverload & componentOverloadMatrix = (a: any, b: any): any => {\r\n if (isMatrix(a) || isMatrix(b)) {\r\n if (isMatrix(a) && isMatrix(b)) {\r\n return matrixMul(a, b);\r\n } else {\r\n if (isMatrix(a) && typeof b == 'number') {\r\n return componentMath(b as scalar, a as any, (a, b) => a * b);\r\n } else if (isMatrix(b) && typeof a == 'number') {\r\n return componentMath(a as scalar, b as any, (a, b) => a * b);\r\n } else {\r\n if (isMatrix(a)) {\r\n if (a.length == 4) {\r\n return matrixMul2x2float2(a as float2x2, b as float2);\r\n } else if (a.length == 9) {\r\n return matrixMul3x3float3(a as float3x3, b as float3);\r\n } else if (a.length == 16) {\r\n return matrixMul4x4float4(a as float4x4, b as float4);\r\n }\r\n } else if (isMatrix(b)) {\r\n if (b.length == 4) {\r\n return matrixMulfloat22x2(a as float2, b as float2x2);\r\n } else if (b.length == 9) {\r\n return matrixMulfloat33x3(a as float3, b as float3x3);\r\n } else if (b.length == 16) {\r\n return matrixMulfloat44x4(a as float4, b as float4x4);\r\n }\r\n }\r\n }\r\n }\r\n } else {\r\n return mulFunc(a, b);\r\n }\r\n};\r\n\r\n/** @shadeup=univ(!$0$ / $1$)*/\r\nexport const div = componentOp((a, b) => a / b);\r\n\r\n/** @shadeup=glsl(!$0$ ** $1$) @shadeup=wgsl(!pow($0$, $1$))*/\r\nexport const pow = componentOp((a, b) => Math.pow(a, b));\r\n\r\n/** @shadeup=wgsl(!$0$ % $1$) @shadeup=glsl(!mod($0$, $1$))*/\r\nexport const mod = componentOpMatch((a, b) => a - b * Math.floor(a / b));\r\n\r\n/** @shadeup=univ(!$0$ & $1$)*/\r\nexport const bitand = componentOp((a, b) => a & b);\r\n\r\n/** @shadeup=univ(!$0$ | $1$)*/\r\nexport const bitor = componentOp((a, b) => a | b);\r\n\r\n/** @shadeup=univ(!$0$ ^ $1$)*/\r\nexport const bitxor = componentOp((a, b) => a ^ b);\r\n\r\n/** @shadeup=glsl(!$0$ << $1$) @shadeup=wgsl(!$0$ << u32($1$))*/\r\nexport const lshift = componentOp((a, b) => a << b);\r\n\r\n/** @shadeup=glsl(!$0$ >> $1$) @shadeup=wgsl(!$0$ >> u32($1$))*/\r\nexport const rshift = componentOp((a, b) => a >> b);\r\n\r\n/** @shadeup=univ(!~$0$)*/\r\nexport const bitnot = componentOpSingular((a) => ~a);\r\n\r\n/** @shadeup=univ(!-($0$))*/\r\nexport const negate = componentOpSingular((a) => -a);\r\n\r\n/** @shadeup=univ(!+($0$))*/\r\nexport const positive = componentOpSingular((a) => Math.abs(a));\r\n\r\n/** @shadeup=univ(abs)*/\r\nexport const abs = componentOpSingular((a) => Math.abs(a));\r\n\r\n/** @shadeup=glsl(floor) @shadeup=wgsl(!floor(f32(1.0) * $0$))*/\r\nexport const floor = componentOpSingular(Math.floor);\r\n\r\n/** @shadeup=glsl(ceil) @shadeup=wgsl(!ceil(f32(1.0) * $0$))*/\r\nexport const ceil = componentOpSingular(Math.ceil);\r\n\r\n/** @shadeup=univ(round)*/\r\nexport const round = componentOpSingular(Math.round);\r\n\r\n/** @shadeup=univ(sign)*/\r\nexport const sign = componentOpSingular(Math.sign);\r\n\r\n/** @shadeup=univ(cos) */\r\nexport const cos = componentOpSingular(Math.cos);\r\n\r\n/** @shadeup=univ(sin) */\r\nexport const sin = componentOpSingularFloat(Math.sin);\r\n\r\n/** @shadeup=univ(tan) */\r\nexport const tan = componentOpSingular(Math.tan);\r\n\r\n/** @shadeup=univ(acos) */\r\nexport const acos = componentOpSingular(Math.acos);\r\n\r\n/** @shadeup=univ(asin) */\r\nexport const asin = componentOpSingular(Math.asin);\r\n\r\n/** @shadeup=univ(atan) */\r\nexport const atan = componentOpSingular(Math.atan);\r\n\r\n/** @shadeup=univ(atan2) */\r\nexport const atan2: (dy: float, dx: float) => float = Math.atan2 as any;\r\n\r\n/** @shadeup=univ(cosh) */\r\nexport const cosh = componentOpSingular(Math.cosh);\r\n\r\n/** @shadeup=univ(sinh) */\r\nexport const sinh = componentOpSingular(Math.sinh);\r\n\r\n/** @shadeup=univ(tanh) */\r\nexport const tanh = componentOpSingular(Math.tanh);\r\n\r\n/** @shadeup=univ(acosh) */\r\nexport const acosh = componentOpSingular(Math.acosh);\r\n\r\n/** @shadeup=univ(asinh) */\r\nexport const asinh = componentOpSingular(Math.asinh);\r\n\r\n/** @shadeup=univ(atanh) */\r\nexport const atanh = componentOpSingular(Math.atanh);\r\n\r\n/** @shadeup=univ(exp) */\r\nexport const exp = componentOpSingular(Math.exp);\r\n\r\n/** @shadeup=univ(log) */\r\nexport const log = componentOpSingular(Math.log);\r\n\r\n/** @shadeup=univ(log2) */\r\nexport const log2 = componentOpSingular(Math.log2);\r\n\r\n/** @shadeup=univ(log10) */\r\nexport const log10 = componentOpSingular(Math.log10);\r\n\r\n/** @shadeup=univ(sqrt) */\r\nexport const sqrt = componentOpSingular(Math.sqrt);\r\n\r\n/** @shadeup=univ(inversesqrt) */\r\nexport const inversesqrt = componentOpSingular((a) => 1 / Math.sqrt(a));\r\n\r\n/** @shadeup=univ(fract)*/\r\nexport const frac = componentOpSingular((a) => a - Math.floor(a));\r\n\r\nexport function wrap(x: float, low: float, high: float): float {\r\n if (lt(x, low)) {\r\n let rng = sub(high, low);\r\n let s1 = sub(low, x);\r\n let ms = mod(s1, rng);\r\n return sub(high, ms);\r\n } else if (gte(x, high)) {\r\n let rng = sub(high, low);\r\n let s1 = sub(x, high);\r\n let ms = mod(s1, rng);\r\n return add(low, ms);\r\n } else {\r\n return x;\r\n }\r\n // return add(mod(sub(x, low), sub(high, low)), low) as T;\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\n\r\nexport function rand(seed?: float): float {\r\n if (typeof seed === 'number') {\r\n return frac(mul(sin(mul(seed, float(91.3458))), float(47453.5453))) as float;\r\n } else {\r\n return Math.random() as float;\r\n }\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\nexport function rand2(seed: float2): float {\r\n return frac(mul(sin(dot(seed, float2(12.9898, 4.1414))), float(43758.5453)));\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\nexport function rand3(seed: float3): float {\r\n return rand2(add(swizzle(seed, 'xy'), rand(swizzle(seed, 'z'))));\r\n}\r\n\r\n// export function remap(x: float, low1: float, high1: float, low2: float, high2: float): float {\r\n// return add(low2, mul(div(sub(x, low1), sub(high1, low1)), sub(high2, low2)));\r\n// }\r\n\r\nexport function pingpong(x: float, length: float): float {\r\n const t = mod(x, mul(length, float(2)));\r\n return sub(length, abs(sub(t, length)));\r\n}\r\n\r\nfunction vectorMath_2to1_3to3(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => vector3\r\n): vectorOverload_2to1_3to3 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\n\r\nfunction vectorMath_2to1_3to3_4to4(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => vector3,\r\n cb4: (a: vector4, b: vector4) => vector4\r\n): vectorOverload_2to1_3to3_4to4 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return cb4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\nfunction vectorMath_2to1_3to1_4to1(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => scalar,\r\n cb4: (a: vector4, b: vector4) => scalar\r\n): vectorOverload_2to1_3to1_4to1 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return cb4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\n\r\nfunction cross2(a: float2, b: float2): any {\r\n return a[0] * b[1] - a[1] * b[0];\r\n}\r\n\r\nfunction cross3(a: float3, b: float3): any {\r\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\r\n}\r\n\r\nexport const cross = vectorMath_2to1_3to3(cross2, cross3);\r\n\r\nfunction dot2(a: float2, b: float2): any {\r\n return a[0] * b[0] + a[1] * b[1];\r\n}\r\n\r\nfunction dot3(a: float3, b: float3): any {\r\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\r\n}\r\n\r\nfunction dot4(a: float4, b: float4): any {\r\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\r\n}\r\n\r\n/** @shadeup=univ(dot)*/\r\nexport const dot = vectorMath_2to1_3to1_4to1(dot2, dot3, dot4);\r\n\r\nfunction lerp1(a: float, b: float, t: float): float {\r\n return (a + (b - a) * t) as float;\r\n}\r\n\r\nfunction lerp2(a: float2, b: float2, t: float): float2 {\r\n return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t)] as float2;\r\n}\r\n\r\nfunction lerp3(a: float3, b: float3, t: float): float3 {\r\n return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t)] as float3;\r\n}\r\n\r\nfunction lerp4(a: float4, b: float4, t: float): float4 {\r\n return [\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t)\r\n ] as float4;\r\n}\r\n\r\nfunction lerp2x2(a: float2x2, b: float2x2, t: float): float2x2 {\r\n return float2x2(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t)\r\n );\r\n}\r\n\r\nfunction lerp3x3(a: float3x3, b: float3x3, t: float): float3x3 {\r\n return float3x3(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t),\r\n lerp1(a[4], b[4], t),\r\n lerp1(a[5], b[5], t),\r\n lerp1(a[6], b[6], t),\r\n lerp1(a[7], b[7], t),\r\n lerp1(a[8], b[8], t)\r\n );\r\n}\r\n\r\nfunction lerp4x4(a: float4x4, b: float4x4, t: float): float4x4 {\r\n return float4x4(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t),\r\n lerp1(a[4], b[4], t),\r\n lerp1(a[5], b[5], t),\r\n lerp1(a[6], b[6], t),\r\n lerp1(a[7], b[7], t),\r\n lerp1(a[8], b[8], t),\r\n lerp1(a[9], b[9], t),\r\n lerp1(a[10], b[10], t),\r\n lerp1(a[11], b[11], t),\r\n lerp1(a[12], b[12], t),\r\n lerp1(a[13], b[13], t),\r\n lerp1(a[14], b[14], t),\r\n lerp1(a[15], b[15], t)\r\n );\r\n}\r\n\r\n/** @shadeup=univ(mix)*/\r\nexport function lerp(a: float, b: float, t: float): float;\r\nexport function lerp(a: float2, b: float2, t: float): float2;\r\nexport function lerp(a: float3, b: float3, t: float): float3;\r\nexport function lerp(a: float4, b: float4, t: float): float4;\r\nexport function lerp(a: float2x2, b: float2x2, t: float): float2x2;\r\nexport function lerp(a: float3x3, b: float3x3, t: float): float3x3;\r\nexport function lerp(a: float4x4, b: float4x4, t: float): float4x4;\r\n/** @shadeup=univ(mix)*/\r\nexport function lerp(a: any, b: any, t: float): any {\r\n if (typeof a === 'number' && typeof b === 'number' && typeof t === 'number') {\r\n return lerp1(a as float, b as float, t);\r\n } else if (isMatrix(a) && isMatrix(b)) {\r\n if (a.length === 4 && b.length === 4) {\r\n return lerp2x2(a as float2x2, b as float2x2, t);\r\n } else if (a.length === 9 && b.length === 9) {\r\n return lerp3x3(a as float3x3, b as float3x3, t);\r\n } else if (a.length === 16 && b.length === 16) {\r\n return lerp4x4(a as float4x4, b as float4x4, t);\r\n } else {\r\n throw new Error('Invalid matrix length');\r\n }\r\n } else if (a.length === 2 && b.length === 2 && typeof t === 'number') {\r\n return lerp2(a, b, t as float);\r\n } else if (a.length === 3 && b.length === 3 && typeof t === 'number') {\r\n return lerp3(a, b, t);\r\n } else if (a.length === 4 && b.length === 4 && typeof t === 'number') {\r\n return lerp4(a, b, t);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(!bilerp_`0`($0$, $1$, $2$, $3$, $4$, $5$)) */\r\nexport function bilerp(a: float, b: float, c: float, d: float, u: float, v: float): float;\r\nexport function bilerp(a: float2, b: float2, c: float2, d: float2, u: float, v: float): float2;\r\nexport function bilerp(a: float3, b: float3, c: float3, d: float3, u: float, v: float): float3;\r\nexport function bilerp(a: float4, b: float4, c: float4, d: float4, u: float, v: float): float4;\r\nexport function bilerp(\r\n a: float2x2,\r\n b: float2x2,\r\n c: float2x2,\r\n d: float2x2,\r\n u: float,\r\n v: float\r\n): float2x2;\r\nexport function bilerp(\r\n a: float3x3,\r\n b: float3x3,\r\n c: float3x3,\r\n d: float3x3,\r\n u: float,\r\n v: float\r\n): float3x3;\r\nexport function bilerp(\r\n a: float4x4,\r\n b: float4x4,\r\n c: float4x4,\r\n d: float4x4,\r\n u: float,\r\n v: float\r\n): float4x4;\r\n/** @shadeup=univ(!bilerp_`0`($0$, $1$, $2$, $3$, $4$, $5$)) */\r\nexport function bilerp(a: any, b: any, c: any, d: any, u: float, v: float): any {\r\n return lerp(lerp(a, b, u), lerp(c, d, u), v);\r\n}\r\n\r\n/** @shadeup=univ(length)*/\r\nexport function length(a: float): float;\r\nexport function length(a: float2): float;\r\nexport function length(a: float3): float;\r\nexport function length(a: float4): float;\r\n/** @shadeup=univ(length)*/\r\nexport function length(a: any): any {\r\n if (typeof a === 'number') {\r\n return Math.abs(a);\r\n } else if (a.length === 2) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2));\r\n } else if (a.length === 3) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2));\r\n } else if (a.length === 4) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2));\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(distance)*/\r\nexport function dist(a: float, b: float): float;\r\nexport function dist(a: float2, b: float2): float;\r\nexport function dist(a: float3, b: float3): float;\r\nexport function dist(a: float4, b: float4): float;\r\nexport function dist(a: T, b: T): float {\r\n return length(sub(a, b));\r\n}\r\n\r\n/** @shadeup=univ(distance)*/\r\nexport const distance = dist;\r\n\r\n/** @shadeup=univ(normalize)*/\r\nexport function normalize(a: float2): float2;\r\nexport function normalize(a: float3): float3;\r\nexport function normalize(a: float4): float4;\r\n/** @shadeup=univ(normalize)*/\r\nexport function normalize(a: any): any {\r\n if (a.length === 2) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l];\r\n } else if (a.length === 3) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l, a[2] / l];\r\n } else if (a.length === 4) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l, a[2] / l, a[3] / l];\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(reflect)*/\r\nexport function reflect(a: float2, b: float2): float2;\r\nexport function reflect(a: float3, b: float3): float3;\r\nexport function reflect(a: float4, b: float4): float4;\r\n/** @shadeup=univ(reflect)*/\r\nexport function reflect(a: any, b: any): any {\r\n if (a.length === 2 && b.length === 2) {\r\n return reflect2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return reflect3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return reflect4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\nfunction reflect2(b, a) {\r\n let dot = dot2(a, b);\r\n return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1]];\r\n}\r\n\r\nfunction reflect3(b, a) {\r\n let dot = dot3(a, b);\r\n return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1], b[2] - 2 * dot * a[2]];\r\n}\r\n\r\nfunction reflect4(b, a) {\r\n let dot = dot4(a, b);\r\n return [\r\n b[0] - 2 * dot * a[0],\r\n b[1] - 2 * dot * a[1],\r\n b[2] - 2 * dot * a[2],\r\n b[3] - 2 * dot * a[3]\r\n ];\r\n}\r\n\r\n/** @shadeup=univ(refract)*/\r\nexport function refract(a: float2, b: float2, eta: float): float2;\r\nexport function refract(a: float3, b: float3, eta: float): float3;\r\nexport function refract(a: float4, b: float4, eta: float): float4;\r\n/** @shadeup=univ(refract)*/\r\nexport function refract(a: any, b: any, eta: number): any {\r\n if (a.length === 2 && b.length === 2) {\r\n return refract2(a, b, eta);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return refract3(a, b, eta);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return refract4(a, b, eta);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\nfunction refract2(b, a, eta) {\r\n let dot = dot2(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1]\r\n ];\r\n}\r\n\r\nfunction refract3(b, a, eta) {\r\n let dot = dot3(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1],\r\n eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2]\r\n ];\r\n}\r\n\r\nfunction refract4(b, a, eta) {\r\n let dot = dot4(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0, 0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1],\r\n eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2],\r\n eta * b[3] - (eta * dot + Math.sqrt(k)) * a[3]\r\n ];\r\n}\r\n\r\n/** @shadeup=univ(degrees)*/\r\nexport function degrees(a: float): float {\r\n return float((a * 180) / Math.PI);\r\n}\r\n\r\n/** @shadeup=univ(radians)*/\r\nexport function radians(a: float): float {\r\n return float((a * Math.PI) / 180);\r\n}\r\n\r\n/** @shadeup=univ(step)*/\r\nexport function step(edge: float, x: float): float;\r\nexport function step(edge: int, x: float): float;\r\nexport function step(edge: T, x: T): T;\r\nexport function step(edge: float, x: T): T;\r\nexport function step(edge: int, x: T): T;\r\n/** @shadeup=univ(step)*/\r\nexport function step(edge: any, x: any): any {\r\n if (typeof edge === 'number') {\r\n if (typeof x === 'number') {\r\n return x < edge ? 0 : 1;\r\n } else {\r\n return x.map((v) => (v < edge ? 0 : 1));\r\n }\r\n } else {\r\n if (typeof x === 'number') {\r\n return edge.map((v) => (x < v ? 0 : 1));\r\n } else {\r\n return edge.map((v, i) => (x[i] < v ? 0 : 1));\r\n }\r\n }\r\n}\r\n\r\nfunction _smoothstep(a, b, x) {\r\n let t = clamp((x - a) / (b - a), 0, 1);\r\n return t * t * (3 - 2 * t);\r\n}\r\n\r\n/** @shadeup=univ(smoothstep)*/\r\nexport function smoothstep(a: float, b: float, x: float): float;\r\nexport function smoothstep(a: float2, b: float2, x: float2): float2;\r\nexport function smoothstep(a: float3, b: float3, x: float3): float3;\r\nexport function smoothstep(a: float4, b: float4, x: float4): float4;\r\n/** @shadeup=univ(smoothstep)*/\r\nexport function smoothstep(a: any, b: any, x: any): any {\r\n if (typeof a === 'number' && typeof b === 'number' && typeof x === 'number') {\r\n return _smoothstep(a, b, x);\r\n } else if (typeof a === 'number' && typeof b === 'number') {\r\n return x.map((v) => _smoothstep(a, b, v));\r\n } else {\r\n return a.map((v, i) => _smoothstep(v, b[i], x[i]));\r\n }\r\n}\r\n\r\nfunction componentReduce(vectors: vector[], cb: (a: scalar[]) => scalar) {\r\n let result: scalar[] = [];\r\n for (let i = 0; i < vectors[0].length; i++) {\r\n result.push(cb(vectors.map((v) => v[i])));\r\n }\r\n return result;\r\n}\r\n\r\n/** @shadeup=univ(min)*/\r\n\r\nexport function min(a: int, ...b: int[]): int;\r\nexport function min(a: int2, ...b: int2[]): int2;\r\nexport function min(a: int3, ...b: int3[]): int3;\r\nexport function min(a: int4, ...b: int4[]): int4;\r\nexport function min(a: float, ...b: float[]): float;\r\nexport function min(a: float2, ...b: float2[]): float2;\r\nexport function min(a: float3, ...b: float3[]): float3;\r\nexport function min(a: float4, ...b: float4[]): float4;\r\n\r\nexport function min(a: float, b: T): T;\r\nexport function min(a: T, b: float): T;\r\nexport function min(a: int, b: T): T;\r\nexport function min(a: T, b: int): T;\r\n\r\n/** @shadeup=univ(min)*/\r\nexport function min(...args: T[]): T {\r\n if (args.length == 1) {\r\n if (Array.isArray(args[0])) {\r\n return Math.min(...args[0]) as T;\r\n } else {\r\n return args[0];\r\n }\r\n } else {\r\n if (Array.isArray(args[0]) && !Array.isArray(args[1])) {\r\n let minTo = args[1] as float;\r\n return args[0].map((v) => Math.min(v, minTo)) as T;\r\n } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) {\r\n let minFrom = args[0] as float;\r\n return args[1].map((v) => Math.min(minFrom, v)) as T;\r\n } else if (Array.isArray(args[0])) {\r\n return componentReduce(args as vector[], (a) => Math.min(...a) as scalar) as T;\r\n } else {\r\n return Math.min(...(args as number[])) as T;\r\n }\r\n }\r\n}\r\n\r\n/** @shadeup=univ(max)*/\r\n\r\nexport function max(a: int, ...b: int[]): int;\r\nexport function max(a: float, ...b: int[]): float;\r\nexport function max(a: int, ...b: float[]): float;\r\nexport function max(a: int2, ...b: int2[]): int2;\r\nexport function max(a: int3, ...b: int3[]): int3;\r\nexport function max(a: int4, ...b: int4[]): int4;\r\nexport function max(a: float, ...b: float[]): float;\r\nexport function max(a: float2, ...b: float2[]): float2;\r\nexport function max(a: float3, ...b: float3[]): float3;\r\nexport function max(a: float4, ...b: float4[]): float4;\r\n\r\nexport function max(a: float, b: T): T;\r\nexport function max(a: T, b: float): T;\r\nexport function max(a: int, b: T): T;\r\nexport function max(a: T, b: int): T;\r\n/** @shadeup=univ(max)*/\r\nexport function max(...args: T[]): T {\r\n if (args.length == 1) {\r\n if (Array.isArray(args[0])) {\r\n return Math.max(...args[0]) as T;\r\n } else {\r\n return args[0];\r\n }\r\n } else {\r\n if (Array.isArray(args[0]) && !Array.isArray(args[1])) {\r\n let maxTo = args[1] as float;\r\n return args[0].map((v) => Math.max(v, maxTo)) as T;\r\n } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) {\r\n let maxFrom = args[0] as float;\r\n return args[1].map((v) => Math.max(maxFrom, v)) as T;\r\n } else if (Array.isArray(args[0])) {\r\n return componentReduce(args as vector[], (a) => Math.max(...a) as scalar) as T;\r\n } else {\r\n return Math.max(...(args as number[])) as T;\r\n }\r\n }\r\n}\r\n\r\n/** @shadeup=univ(clamp)*/\r\nexport function clamp(arg: int, min: int, max: int): int;\r\nexport function clamp(arg: int2, min: int, max: int): int2;\r\nexport function clamp(arg: int3, min: int, max: int): int3;\r\nexport function clamp(arg: int4, min: int, max: int): int4;\r\n\r\nexport function clamp(arg: int2, min: int2, max: int2): int2;\r\nexport function clamp(arg: int3, min: int3, max: int3): int3;\r\nexport function clamp(arg: int4, min: int3, max: int3): int4;\r\n\r\nexport function clamp(arg: float, min: float, max: float): float;\r\nexport function clamp(arg: float2, min: float, max: float): float2;\r\nexport function clamp(arg: float3, min: float, max: float): float3;\r\nexport function clamp(arg: float4, min: float, max: float): float4;\r\n\r\nexport function clamp(arg: float2, min: float2, max: float2): float2;\r\nexport function clamp(arg: float3, min: float3, max: float3): float3;\r\nexport function clamp(arg: float4, min: float4, max: float4): float4;\r\n/** @shadeup=univ(clamp)*/\r\nexport function clamp(arg: any, min: any, max: any): any {\r\n if (Array.isArray(arg)) {\r\n if (Array.isArray(min) && Array.isArray(max)) {\r\n return arg.map((a, i) => Math.min(Math.max(a, min[i]), max[i]));\r\n } else {\r\n return arg.map((a) => Math.min(Math.max(a, min), max));\r\n }\r\n } else {\r\n return Math.min(Math.max(arg, min), max);\r\n }\r\n}\r\n\r\n/** @shadeup=glsl(!clamp($0$, 0.0, 1.0)) @shadeup=wgsl(saturate)*/\r\nexport function saturate(arg: float): float;\r\nexport function saturate(arg: float2): float2;\r\nexport function saturate(arg: float3): float3;\r\nexport function saturate(arg: float4): float4;\r\n/** @shadeup=glsl(!clamp($0$, 0.0, 1.0)) @shadeup=wgsl(saturate) */\r\nexport function saturate(arg: any): any {\r\n return clamp(arg, float(0), float(1));\r\n}\r\n\r\n/** @shadeup=univ(!($0$ == $1$))*/\r\nexport function eq(a: T, b: T): bool;\r\nexport function eq(a: any, b: any): bool {\r\n let ta = typeof a;\r\n let tb = typeof b;\r\n if (ta != tb) {\r\n return false;\r\n } else if (\r\n (ta == 'number' && tb == 'number') ||\r\n (ta == 'string' && tb == 'string') ||\r\n (ta == 'boolean' && tb == 'boolean') ||\r\n (ta == 'undefined' && tb == 'undefined')\r\n ) {\r\n return a == b;\r\n } else if (ta == 'object' && tb == 'object') {\r\n if (Array.isArray(a) && Array.isArray(b)) {\r\n if (a.length != b.length) {\r\n return false;\r\n }\r\n for (let i = 0; i < a.length; i++) {\r\n if (!eq(a[i], b[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n } else {\r\n return a == b;\r\n }\r\n }\r\n}\r\n\r\n/** @shadeup=univ(!($0$ != $1$))*/\r\nexport const neq = (a, b) => !eq(a, b);\r\n\r\n/** @shadeup=univ(!($0$ < $1$))*/\r\nexport const lt = (a: scalar, b: scalar) => a < b;\r\n\r\n/** @shadeup=univ(!($0$ <= $1$))*/\r\nexport const lte = (a: scalar, b: scalar) => a <= b;\r\n\r\n/** @shadeup=univ(!($0$ > $1$))*/\r\nexport const gt = (a: scalar, b: scalar) => a > b;\r\n\r\n/** @shadeup=univ(!($0$ >= $1$))*/\r\nexport const gte = (a: scalar, b: scalar) => a >= b;\r\n\r\n/** @shadeup=univ(!($0$ && $1$))*/\r\nexport const and = (a: boolean, b: boolean) => a && b;\r\n\r\n/** @shadeup=univ(!($0$ || $1$))*/\r\nexport const or = (a: boolean, b: boolean) => a || b;\r\n\r\n/** @shadeup=univ(!(!$0$))*/\r\nexport const not = (a: boolean) => !a;\r\n\r\n/** @shadeup=univ(~)*/\r\nexport function makeVector(x: int, y: int): int2;\r\nexport function makeVector(x: float, y: int): float2;\r\nexport function makeVector(x: int, y: float): float2;\r\nexport function makeVector(x: float, y: float): float2;\r\n\r\nexport function makeVector(x: int, y: int, z: int): int3;\r\nexport function makeVector(xy: int2, z: int): int3;\r\nexport function makeVector(x: int, yz: int2): int3;\r\n\r\nexport function makeVector(x: float, y: int, z: int): float3;\r\nexport function makeVector(x: int, y: float, z: int): float3;\r\nexport function makeVector(x: int, y: int, z: float): float3;\r\nexport function makeVector(x: float, y: float, z: int): float3;\r\nexport function makeVector(x: float, y: int, z: float): float3;\r\nexport function makeVector(x: int, y: float, z: float): float3;\r\nexport function makeVector(x: float, y: float, z: float): float3;\r\nexport function makeVector(xy: float2, z: float): float3;\r\nexport function makeVector(x: float, yz: float2): float3;\r\nexport function makeVector(xy: int2, z: float): float3;\r\nexport function makeVector(x: int, yz: float2): float3;\r\nexport function makeVector(xy: float2, z: int): float3;\r\nexport function makeVector(x: float, yz: int2): float3;\r\n\r\nexport function makeVector(x: int, y: int, z: int, w: int): int4;\r\nexport function makeVector(xyz: int3, w: int): int4;\r\nexport function makeVector(x: int, yzw: int3): int4;\r\n\r\nexport function makeVector(x: int, y: int, zw: int2): int4;\r\nexport function makeVector(xy: int2, z: int, w: int): int4;\r\nexport function makeVector(x: int, yz: int2, w: int): int4;\r\n\r\nexport function makeVector(xy: int2, zw: int2): int4;\r\n\r\nexport function makeVector(x: float, y: int, z: int, w: int): float4;\r\nexport function makeVector(x: int, y: float, z: int, w: int): float4;\r\nexport function makeVector(x: int, y: int, z: float, w: int): float4;\r\nexport function makeVector(x: int, y: int, z: int, w: float): float4;\r\nexport function makeVector(x: float, y: float, z: int, w: int): float4;\r\nexport function makeVector(x: float, y: int, z: float, w: int): float4;\r\nexport function makeVector(x: float, y: int, z: int, w: float): float4;\r\nexport function makeVector(x: int, y: float, z: float, w: int): float4;\r\nexport function makeVector(x: int, y: float, z: int, w: float): float4;\r\nexport function makeVector(x: int, y: int, z: float, w: float): float4;\r\nexport function makeVector(x: float, y: float, z: float, w: int): float4;\r\nexport function makeVector(x: float, y: float, z: int, w: float): float4;\r\nexport function makeVector(x: float, y: int, z: float, w: float): float4;\r\nexport function makeVector(x: int, y: float, z: float, w: float): float4;\r\nexport function makeVector(xyz: float3, w: float): float4;\r\nexport function makeVector(x: float, yzw: float3): float4;\r\nexport function makeVector(xyz: int3, w: float): float4;\r\nexport function makeVector(x: int, yzw: float3): float4;\r\nexport function makeVector(xyz: float3, w: int): float4;\r\nexport function makeVector(x: float, yzw: int3): float4;\r\nexport function makeVector(x: float, yz: float2, w: int): float4;\r\nexport function makeVector(x: float, yz: int2, w: float): float4;\r\nexport function makeVector(x: int, yz: float2, w: float): float4;\r\nexport function makeVector(x: float, y: float, zw: float2): float4;\r\nexport function makeVector(x: float, y: int, zw: float2): float4;\r\nexport function makeVector(x: float, y: int, zw: int2): float4;\r\nexport function makeVector(x: int, y: float, zw: float2): float4;\r\nexport function makeVector(x: int, y: float, zw: int2): float4;\r\nexport function makeVector(x: int, y: int, zw: float2): float4;\r\nexport function makeVector(x: float, y: float, z: float, w: float): float4;\r\nexport function makeVector(xy: float2, z: float, w: float): float4;\r\nexport function makeVector(x: float, yz: float2, w: float): float4;\r\nexport function makeVector(x: float, y: float, zw: float2): float4;\r\nexport function makeVector(xy: int2, z: float, w: float): float4;\r\nexport function makeVector(x: int, yz: float2, w: float): float4;\r\nexport function makeVector(x: int, y: float, zw: float2): float4;\r\nexport function makeVector(xy: float2, z: int, w: float): float4;\r\nexport function makeVector(x: float, yz: int2, w: float): float4;\r\nexport function makeVector(x: float, y: int, zw: float2): float4;\r\nexport function makeVector(xy: int2, z: float, w: int): float4;\r\nexport function makeVector(x: int, yz: float2, w: int): float4;\r\nexport function makeVector(x: int, y: float, zw: int2): float4;\r\nexport function makeVector(xy: float2, z: int, w: int): float4;\r\nexport function makeVector(x: float, yz: int2, w: int): float4;\r\nexport function makeVector(x: float, y: int, zw: int2): float4;\r\nexport function makeVector(xy: int2, z: int, w: float): float4;\r\nexport function makeVector(x: int, yz: int2, w: float): float4;\r\nexport function makeVector(x: int, y: int, zw: float2): float4;\r\nexport function makeVector(xy: int2, z: int, w: int): int4;\r\n/** @shadeup=univ()*/\r\nexport function makeVector() {\r\n let out = [];\r\n for (let i = 0; i < arguments.length; i++) {\r\n let a = arguments[i];\r\n if (typeof a === 'number') {\r\n out.push(a);\r\n } else {\r\n for (let j = 0; j < a.length; j++) {\r\n out.push(a[j]);\r\n }\r\n }\r\n }\r\n return out;\r\n\r\n throw new Error('Invalid vector length');\r\n}\r\n\r\n// add('test', int(1));\r\n\r\ntype swizChar = 'x' | 'y' | 'z' | 'w' | 'r' | 'g' | 'b' | 'a';\r\ntype swizStr4 = `${swizChar}${swizChar}${swizChar}${swizChar}`;\r\ntype swizStr3 = `${swizChar}${swizChar}${swizChar}`;\r\ntype swizStr2 = `${swizChar}${swizChar}`;\r\ntype swizStr1 = `${swizChar}`;\r\ntype swizStr4Ord = `xyzw` | `rgba` | `xxxx` | `rrrr`;\r\ntype swizStr3Ord = `xyz` | `rgb` | `xxx` | `rrr`;\r\ntype swizStr2Ord = `xy` | `rg` | `xx` | `rr`;\r\ntype swizStr1Ord = `x` | `r`;\r\n\r\nconst swizIndex: { [key: string]: number } = {\r\n x: 0,\r\n y: 1,\r\n z: 2,\r\n w: 3,\r\n r: 0,\r\n g: 1,\r\n b: 2,\r\n a: 3\r\n};\r\n\r\nconst getSwizIndexFast = (swiz: string) => {\r\n switch (swiz) {\r\n case 'x':\r\n return 0;\r\n case 'y':\r\n return 1;\r\n case 'z':\r\n return 2;\r\n case 'w':\r\n return 3;\r\n case 'r':\r\n return 0;\r\n case 'g':\r\n return 1;\r\n case 'b':\r\n return 2;\r\n case 'a':\r\n return 3;\r\n }\r\n};\r\n\r\n/** @shadeup=shader */\r\nexport function testDocComment() {\r\n return 1;\r\n}\r\n\r\n/** @shadeup=univ(~)*/\r\nexport function swizzle(v: T, swiz: S, assign?: T): int4;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): uint4;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): float4;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): int3;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): uint3;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): float3;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): int2;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): uint2;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): float2;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): int;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): uint;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): float;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: int4): int4;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: uint4\r\n): uint4;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: float4\r\n): float4;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: int3): int3;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: uint3\r\n): uint3;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: float3\r\n): float3;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: int2): int2;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: uint2\r\n): uint2;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: float2\r\n): float2;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: int): int;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: uint): uint;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: float\r\n): float;\r\n\r\nexport function swizzle(v: T, swiz: A, assign?: T): T[A];\r\n\r\nexport function swizzle(v: any, swiz: string, assign?: any) {\r\n if (typeof v === 'number') {\r\n if (swiz.length === 1) {\r\n return v;\r\n } else if (swiz.length === 2) {\r\n return [v, v];\r\n } else if (swiz.length === 3) {\r\n return [v, v, v];\r\n } else if (swiz.length === 4) {\r\n return [v, v, v, v];\r\n }\r\n } else if (Array.isArray(v)) {\r\n if (typeof assign !== 'undefined') {\r\n for (let i = 0; i < swiz.length; i++) {\r\n v[getSwizIndexFast(swiz[i])] = assign[i] ?? assign;\r\n }\r\n return v;\r\n }\r\n if (swiz.length === 1) {\r\n return v[getSwizIndexFast(swiz)];\r\n } else if (swiz.length === 2) {\r\n return [v[getSwizIndexFast(swiz[0])], v[getSwizIndexFast(swiz[1])]];\r\n } else if (swiz.length === 3) {\r\n return [\r\n v[getSwizIndexFast(swiz[0])],\r\n v[getSwizIndexFast(swiz[1])],\r\n v[getSwizIndexFast(swiz[2])]\r\n ];\r\n } else if (swiz.length === 4) {\r\n return [\r\n v[getSwizIndexFast(swiz[0])],\r\n v[getSwizIndexFast(swiz[1])],\r\n v[getSwizIndexFast(swiz[2])],\r\n v[getSwizIndexFast(swiz[3])]\r\n ];\r\n }\r\n } else {\r\n return (v as any)[swiz];\r\n }\r\n}\r\n\r\nexport function intifyVector(v: vector) {\r\n if (typeof v === 'number') {\r\n return v;\r\n } else if (Array.isArray(v)) {\r\n return v.map((v) => v | 0);\r\n } else {\r\n return v;\r\n }\r\n}\r\n\r\nimport { FM as FastMath } from './static-math';\r\nexport const FM = FastMath;\r\n\r\n// type f32 = number & { __float: never };\r\n// type i32 = number & { __int: never };\r\n// type num = f32 | i32;\r\n\r\n// function f32(a: number): f32 {\r\n// return a as f32;\r\n// }\r\n\r\n// function i32(a: number): i32 {\r\n// return a as i32;\r\n// }\r\n\r\n// type numeric2 = (a: A, b: B) => (A extends f32 ? f32 : (B extends f32 ? f32 : i32));\r\n// type numeric3 = (a: A, b: B, c: C) => (A extends f32 ? f32 : (B extends f32 ? f32 : (C extends f32 ? f32 : i32)));\r\n\r\n// export const abc: numeric2 = (a, b, c) => a + b + c;\r\n\r\n// abc(f32(1), i32(2));\r\n\r\nexport class atomic_internal {\r\n private __type: T;\r\n private __value: number;\r\n constructor(value: T) {\r\n this.__value = value;\r\n }\r\n\r\n private $mutate?: (to: value) => void;\r\n\r\n /** @shadeup=univ(!atomicLoad(&$self$))*/\r\n load(): T {\r\n return this.__value as T;\r\n }\r\n /** @shadeup=univ(!atomicStore(&$self$, $0$))*/\r\n store(value: T): void {\r\n this.__value = value as any;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n }\r\n\r\n /** @shadeup=univ(!atomicAdd(&$self$, $0$))*/\r\n add(value: T): T {\r\n let old = this.__value;\r\n this.__value += value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicSub(&$self$, $0$))*/\r\n sub(value: T): T {\r\n let old = this.__value;\r\n this.__value -= value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicMax(&$self$, $0$))*/\r\n max(value: T): T {\r\n let old = this.__value;\r\n this.__value = Math.max(value, this.__value);\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicMin(&$self$, $0$))*/\r\n min(value: T): T {\r\n let old = this.__value;\r\n this.__value = Math.min(value, this.__value);\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicAnd(&$self$, $0$))*/\r\n and(value: T): T {\r\n let old = this.__value;\r\n this.__value = value & this.__value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicOr(&$self$, $0$))*/\r\n or(value: T): T {\r\n let old = this.__value;\r\n this.__value = value | this.__value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicXor(&$self$, $0$))*/\r\n xor(value: T): T {\r\n let old = this.__value;\r\n this.__value = value ^ this.__value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicExchange(&$self$, $0$))*/\r\n exchange(value: T): T {\r\n let old = this.__value;\r\n this.__value = value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicCompareExchangeWeak(&$self$, $0$, $1$))*/\r\n compareExchangeWeak(compare: T, value: T): __atomic_compare_exchange_result {\r\n let old = this.__value;\r\n if (old == compare) {\r\n this.__value = value;\r\n }\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return {\r\n old_value: old as T,\r\n exchanged: old == compare\r\n };\r\n }\r\n}\r\n\r\nexport type __atomic_compare_exchange_result = {\r\n old_value: T;\r\n exchanged: boolean;\r\n};\r\n\r\nexport type atomic = atomic_internal;\r\n\r\nexport function atomic(value: T): atomic {\r\n return new atomic_internal(value);\r\n}\r\n\r\n(window as any).makeAtomic = atomic;\r\n\r\n/**\r\n * Executes a control barrier synchronization function that affects memory and atomic operations in the workgroup address space.\r\n *\r\n * See: https://www.w3.org/TR/WGSL/#workgroupBarrier-builtin\r\n *\r\n * @shadeup=univ(!workgroupBarrier())\r\n */\r\nexport function workgroupBarrier() {}\r\n\r\n/**\r\n * Executes a storage barrier synchronization function that affects memory and atomic operations in the workgroup address space.\r\n *\r\n * See: https://www.w3.org/TR/WGSL/#storageBarrier-builtin\r\n *\r\n * @shadeup=univ(!storageBarrier())\r\n */\r\nexport function storageBarrier() {}\r\n\r\n/**\r\n * See: https://www.w3.org/TR/WGSL/#workgroupUniformLoad-builtin\r\n *\r\n * @shadeup=univ(!workgroupUniformLoad(&$0$))\r\n */\r\nexport function workgroupUniformLoad(p: T): T {\r\n return p;\r\n}\r\n\r\n/**\r\n * Discards the current fragment.\r\n *\r\n * A discard statement converts the invocation into a helper invocation and throws away the fragment. The discard statement must only be used in a fragment shader stage.\r\n *\r\n * See: https://www.w3.org/TR/WGSL/#discard-statement\r\n *\r\n * @shadeup=univ(!discard;)\r\n */\r\nexport function discard() {}\r\n\r\n/**\r\n * Returns the derivative of the input value with respect to the window-space x coordinate.\r\n * @param value - The input value.\r\n * @returns The derivative of the input value with respect to the window-space x coordinate.\r\n * @shadeup=glsl(!dFdx($0$))\r\n * @shadeup=wgsl(!dpdx($0$))\r\n */\r\nexport function ddx(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * Returns the derivative of the input value with respect to the window-space y coordinate.\r\n * @param value - The input value.\r\n *\r\n * @returns The derivative of the input value with respect to the window-space y coordinate.\r\n * @shadeup=glsl(!dFdy($0$))\r\n * @shadeup=wgsl(!dpdy($0$))\r\n */\r\nexport function ddy(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!dFdxFine($0$))\r\n * @shadeup=wgsl(!dpdxFine($0$))\r\n */\r\nexport function ddxFine(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!dFdyFine($0$))\r\n * @shadeup=wgsl(!dpdyFine($0$))\r\n */\r\nexport function ddyFine(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!dFdxCoarse($0$))\r\n * @shadeup=wgsl(!dpdxCoarse($0$))\r\n */\r\nexport function ddxCoarse(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!dFdyCoarse($0$))\r\n * @shadeup=wgsl(!dpdyCoarse($0$))\r\n */\r\nexport function ddyCoarse(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!bitcast<$[0]$>($0$))\r\n */\r\nexport function bitcast(value: scalar): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack4x8snorm($0$))\r\n */\r\nexport function pack4x8snorm(value: float4): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack4x8unorm($0$))\r\n */\r\nexport function pack4x8unorm(value: float4): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack2x16snorm($0$))\r\n */\r\nexport function pack2x16snorm(value: float2): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack2x16unorm($0$))\r\n */\r\nexport function pack2x16unorm(value: float2): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack2x16float($0$))\r\n */\r\nexport function pack2x16float(value: float2): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack4x8snorm($0$))\r\n */\r\nexport function unpack4x8snorm(value: uint): float4 {\r\n return float4(0, 0, 0, 0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack4x8unorm($0$))\r\n */\r\nexport function unpack4x8unorm(value: uint): float4 {\r\n return float4(0, 0, 0, 0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack2x16snorm($0$))\r\n */\r\nexport function unpack2x16snorm(value: uint): float2 {\r\n return float2(0, 0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack2x16unorm($0$))\r\n */\r\nexport function unpack2x16unorm(value: uint): float2 {\r\n return float2(0, 0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack2x16float($0$))\r\n */\r\nexport function unpack2x16float(value: uint): float2 {\r\n return float2(0, 0);\r\n}\r\n"; const stdStaticMath = "\n///\n/// GENERATED\n/// DO NOT EDIT THIS FILE\n/// see generate-static-math.ts\n///\nexport const FM = {\n add_1_1(a: number, b: number): number { return a + b; },\n add_2_1(a: [number, number], b: number): [number, number] { return [a[0] + b, a[1] + b]; },\n add_1_2(a: number, b: [number, number]): [number, number] { return [a + b[0], a + b[1]]; },\n add_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] + b[0], a[1] + b[1]]; },\n add_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] + b, a[1] + b, a[2] + b]; },\n add_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a + b[0], a + b[1], a + b[2]]; },\n add_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; },\n add_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] + b, a[1] + b, a[2] + b, a[3] + b]; },\n add_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a + b[0], a + b[1], a + b[2], a + b[3]]; },\n add_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]]; },\n sub_1_1(a: number, b: number): number { return a - b; },\n sub_2_1(a: [number, number], b: number): [number, number] { return [a[0] - b, a[1] - b]; },\n sub_1_2(a: number, b: [number, number]): [number, number] { return [a - b[0], a - b[1]]; },\n sub_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] - b[0], a[1] - b[1]]; },\n sub_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] - b, a[1] - b, a[2] - b]; },\n sub_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a - b[0], a - b[1], a - b[2]]; },\n sub_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; },\n sub_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] - b, a[1] - b, a[2] - b, a[3] - b]; },\n sub_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a - b[0], a - b[1], a - b[2], a - b[3]]; },\n sub_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]]; },\n div_1_1(a: number, b: number): number { return a / b; },\n div_2_1(a: [number, number], b: number): [number, number] { return [a[0] / b, a[1] / b]; },\n div_1_2(a: number, b: [number, number]): [number, number] { return [a / b[0], a / b[1]]; },\n div_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] / b[0], a[1] / b[1]]; },\n div_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] / b, a[1] / b, a[2] / b]; },\n div_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a / b[0], a / b[1], a / b[2]]; },\n div_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] / b[0], a[1] / b[1], a[2] / b[2]]; },\n div_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] / b, a[1] / b, a[2] / b, a[3] / b]; },\n div_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a / b[0], a / b[1], a / b[2], a / b[3]]; },\n div_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]]; },\n mul_1_1(a: number, b: number): number { return a * b; },\n mul_2_1(a: [number, number], b: number): [number, number] { return [a[0] * b, a[1] * b]; },\n mul_1_2(a: number, b: [number, number]): [number, number] { return [a * b[0], a * b[1]]; },\n mul_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] * b[0], a[1] * b[1]]; },\n mul_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] * b, a[1] * b, a[2] * b]; },\n mul_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a * b[0], a * b[1], a * b[2]]; },\n mul_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] * b[0], a[1] * b[1], a[2] * b[2]]; },\n mul_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] * b, a[1] * b, a[2] * b, a[3] * b]; },\n mul_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a * b[0], a * b[1], a * b[2], a * b[3]]; },\n mul_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]]; },\n mod_1_1(a: number, b: number): number { return a % b; },\n mod_2_1(a: [number, number], b: number): [number, number] { return [a[0] % b, a[1] % b]; },\n mod_1_2(a: number, b: [number, number]): [number, number] { return [a % b[0], a % b[1]]; },\n mod_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] % b[0], a[1] % b[1]]; },\n mod_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] % b, a[1] % b, a[2] % b]; },\n mod_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a % b[0], a % b[1], a % b[2]]; },\n mod_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] % b[0], a[1] % b[1], a[2] % b[2]]; },\n mod_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] % b, a[1] % b, a[2] % b, a[3] % b]; },\n mod_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a % b[0], a % b[1], a % b[2], a % b[3]]; },\n mod_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] % b[0], a[1] % b[1], a[2] % b[2], a[3] % b[3]]; },\n bitand_1_1(a: number, b: number): number { return a & b; },\n bitand_2_1(a: [number, number], b: number): [number, number] { return [a[0] & b, a[1] & b]; },\n bitand_1_2(a: number, b: [number, number]): [number, number] { return [a & b[0], a & b[1]]; },\n bitand_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] & b[0], a[1] & b[1]]; },\n bitand_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] & b, a[1] & b, a[2] & b]; },\n bitand_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a & b[0], a & b[1], a & b[2]]; },\n bitand_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] & b[0], a[1] & b[1], a[2] & b[2]]; },\n bitand_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] & b, a[1] & b, a[2] & b, a[3] & b]; },\n bitand_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a & b[0], a & b[1], a & b[2], a & b[3]]; },\n bitand_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] & b[0], a[1] & b[1], a[2] & b[2], a[3] & b[3]]; },\n bitor_1_1(a: number, b: number): number { return a | b; },\n bitor_2_1(a: [number, number], b: number): [number, number] { return [a[0] | b, a[1] | b]; },\n bitor_1_2(a: number, b: [number, number]): [number, number] { return [a | b[0], a | b[1]]; },\n bitor_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] | b[0], a[1] | b[1]]; },\n bitor_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] | b, a[1] | b, a[2] | b]; },\n bitor_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a | b[0], a | b[1], a | b[2]]; },\n bitor_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] | b[0], a[1] | b[1], a[2] | b[2]]; },\n bitor_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] | b, a[1] | b, a[2] | b, a[3] | b]; },\n bitor_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a | b[0], a | b[1], a | b[2], a | b[3]]; },\n bitor_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] | b[0], a[1] | b[1], a[2] | b[2], a[3] | b[3]]; },\n bitxor_1_1(a: number, b: number): number { return a ^ b; },\n bitxor_2_1(a: [number, number], b: number): [number, number] { return [a[0] ^ b, a[1] ^ b]; },\n bitxor_1_2(a: number, b: [number, number]): [number, number] { return [a ^ b[0], a ^ b[1]]; },\n bitxor_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] ^ b[0], a[1] ^ b[1]]; },\n bitxor_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] ^ b, a[1] ^ b, a[2] ^ b]; },\n bitxor_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a ^ b[0], a ^ b[1], a ^ b[2]]; },\n bitxor_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2]]; },\n bitxor_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] ^ b, a[1] ^ b, a[2] ^ b, a[3] ^ b]; },\n bitxor_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a ^ b[0], a ^ b[1], a ^ b[2], a ^ b[3]]; },\n bitxor_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]; },\n lshift_1_1(a: number, b: number): number { return a << b; },\n lshift_2_1(a: [number, number], b: number): [number, number] { return [a[0] << b, a[1] << b]; },\n lshift_1_2(a: number, b: [number, number]): [number, number] { return [a << b[0], a << b[1]]; },\n lshift_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] << b[0], a[1] << b[1]]; },\n lshift_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] << b, a[1] << b, a[2] << b]; },\n lshift_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a << b[0], a << b[1], a << b[2]]; },\n lshift_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] << b[0], a[1] << b[1], a[2] << b[2]]; },\n lshift_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] << b, a[1] << b, a[2] << b, a[3] << b]; },\n lshift_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a << b[0], a << b[1], a << b[2], a << b[3]]; },\n lshift_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] << b[0], a[1] << b[1], a[2] << b[2], a[3] << b[3]]; },\n rshift_1_1(a: number, b: number): number { return a >> b; },\n rshift_2_1(a: [number, number], b: number): [number, number] { return [a[0] >> b, a[1] >> b]; },\n rshift_1_2(a: number, b: [number, number]): [number, number] { return [a >> b[0], a >> b[1]]; },\n rshift_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] >> b[0], a[1] >> b[1]]; },\n rshift_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] >> b, a[1] >> b, a[2] >> b]; },\n rshift_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a >> b[0], a >> b[1], a >> b[2]]; },\n rshift_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] >> b[0], a[1] >> b[1], a[2] >> b[2]]; },\n rshift_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] >> b, a[1] >> b, a[2] >> b, a[3] >> b]; },\n rshift_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a >> b[0], a >> b[1], a >> b[2], a >> b[3]]; },\n rshift_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] >> b[0], a[1] >> b[1], a[2] >> b[2], a[3] >> b[3]]; },\n bitnot_1(a: number): number { return ~a; },\n bitnot_2(a: [number, number]): [number, number] { return [~a[0], ~a[1]]; },\n bitnot_3(a: [number, number, number]): [number, number, number] { return [~a[0], ~a[1], ~a[2]]; },\n bitnot_4(a: [number, number, number, number]): [number, number, number, number] { return [~a[0], ~a[1], ~a[2], ~a[3]]; },\n negate_1(a: number): number { return -a; },\n negate_2(a: [number, number]): [number, number] { return [-a[0], -a[1]]; },\n negate_3(a: [number, number, number]): [number, number, number] { return [-a[0], -a[1], -a[2]]; },\n negate_4(a: [number, number, number, number]): [number, number, number, number] { return [-a[0], -a[1], -a[2], -a[3]]; },\n positive_1(a: number): number { return Math.abs(a); },\n positive_2(a: [number, number]): [number, number] { return [Math.abs(a[0]), Math.abs(a[1])]; },\n positive_3(a: [number, number, number]): [number, number, number] { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])]; },\n positive_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2]), Math.abs(a[3])]; },\n abs_1(a: number): number { return Math.abs(a); },\n abs_2(a: [number, number]): [number, number] { return [Math.abs(a[0]), Math.abs(a[1])]; },\n abs_3(a: [number, number, number]): [number, number, number] { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])]; },\n abs_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2]), Math.abs(a[3])]; },\n floor_1(a: number): number { return Math.floor(a); },\n floor_2(a: [number, number]): [number, number] { return [Math.floor(a[0]), Math.floor(a[1])]; },\n floor_3(a: [number, number, number]): [number, number, number] { return [Math.floor(a[0]), Math.floor(a[1]), Math.floor(a[2])]; },\n floor_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.floor(a[0]), Math.floor(a[1]), Math.floor(a[2]), Math.floor(a[3])]; },\n ceil_1(a: number): number { return Math.ceil(a); },\n ceil_2(a: [number, number]): [number, number] { return [Math.ceil(a[0]), Math.ceil(a[1])]; },\n ceil_3(a: [number, number, number]): [number, number, number] { return [Math.ceil(a[0]), Math.ceil(a[1]), Math.ceil(a[2])]; },\n ceil_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.ceil(a[0]), Math.ceil(a[1]), Math.ceil(a[2]), Math.ceil(a[3])]; },\n round_1(a: number): number { return Math.round(a); },\n round_2(a: [number, number]): [number, number] { return [Math.round(a[0]), Math.round(a[1])]; },\n round_3(a: [number, number, number]): [number, number, number] { return [Math.round(a[0]), Math.round(a[1]), Math.round(a[2])]; },\n round_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.round(a[0]), Math.round(a[1]), Math.round(a[2]), Math.round(a[3])]; },\n sign_1(a: number): number { return Math.sign(a); },\n sign_2(a: [number, number]): [number, number] { return [Math.sign(a[0]), Math.sign(a[1])]; },\n sign_3(a: [number, number, number]): [number, number, number] { return [Math.sign(a[0]), Math.sign(a[1]), Math.sign(a[2])]; },\n sign_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.sign(a[0]), Math.sign(a[1]), Math.sign(a[2]), Math.sign(a[3])]; },\n cos_1(a: number): number { return Math.cos(a); },\n cos_2(a: [number, number]): [number, number] { return [Math.cos(a[0]), Math.cos(a[1])]; },\n cos_3(a: [number, number, number]): [number, number, number] { return [Math.cos(a[0]), Math.cos(a[1]), Math.cos(a[2])]; },\n cos_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.cos(a[0]), Math.cos(a[1]), Math.cos(a[2]), Math.cos(a[3])]; },\n sin_1(a: number): number { return Math.sin(a); },\n sin_2(a: [number, number]): [number, number] { return [Math.sin(a[0]), Math.sin(a[1])]; },\n sin_3(a: [number, number, number]): [number, number, number] { return [Math.sin(a[0]), Math.sin(a[1]), Math.sin(a[2])]; },\n sin_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.sin(a[0]), Math.sin(a[1]), Math.sin(a[2]), Math.sin(a[3])]; },\n tan_1(a: number): number { return Math.tan(a); },\n tan_2(a: [number, number]): [number, number] { return [Math.tan(a[0]), Math.tan(a[1])]; },\n tan_3(a: [number, number, number]): [number, number, number] { return [Math.tan(a[0]), Math.tan(a[1]), Math.tan(a[2])]; },\n tan_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.tan(a[0]), Math.tan(a[1]), Math.tan(a[2]), Math.tan(a[3])]; },\n acos_1(a: number): number { return Math.acos(a); },\n acos_2(a: [number, number]): [number, number] { return [Math.acos(a[0]), Math.acos(a[1])]; },\n acos_3(a: [number, number, number]): [number, number, number] { return [Math.acos(a[0]), Math.acos(a[1]), Math.acos(a[2])]; },\n acos_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.acos(a[0]), Math.acos(a[1]), Math.acos(a[2]), Math.acos(a[3])]; },\n asin_1(a: number): number { return Math.asin(a); },\n asin_2(a: [number, number]): [number, number] { return [Math.asin(a[0]), Math.asin(a[1])]; },\n asin_3(a: [number, number, number]): [number, number, number] { return [Math.asin(a[0]), Math.asin(a[1]), Math.asin(a[2])]; },\n asin_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.asin(a[0]), Math.asin(a[1]), Math.asin(a[2]), Math.asin(a[3])]; },\n atan_1(a: number): number { return Math.atan(a); },\n atan_2(a: [number, number]): [number, number] { return [Math.atan(a[0]), Math.atan(a[1])]; },\n atan_3(a: [number, number, number]): [number, number, number] { return [Math.atan(a[0]), Math.atan(a[1]), Math.atan(a[2])]; },\n atan_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.atan(a[0]), Math.atan(a[1]), Math.atan(a[2]), Math.atan(a[3])]; },\n cosh_1(a: number): number { return Math.cosh(a); },\n cosh_2(a: [number, number]): [number, number] { return [Math.cosh(a[0]), Math.cosh(a[1])]; },\n cosh_3(a: [number, number, number]): [number, number, number] { return [Math.cosh(a[0]), Math.cosh(a[1]), Math.cosh(a[2])]; },\n cosh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.cosh(a[0]), Math.cosh(a[1]), Math.cosh(a[2]), Math.cosh(a[3])]; },\n sinh_1(a: number): number { return Math.sinh(a); },\n sinh_2(a: [number, number]): [number, number] { return [Math.sinh(a[0]), Math.sinh(a[1])]; },\n sinh_3(a: [number, number, number]): [number, number, number] { return [Math.sinh(a[0]), Math.sinh(a[1]), Math.sinh(a[2])]; },\n sinh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.sinh(a[0]), Math.sinh(a[1]), Math.sinh(a[2]), Math.sinh(a[3])]; },\n tanh_1(a: number): number { return Math.tanh(a); },\n tanh_2(a: [number, number]): [number, number] { return [Math.tanh(a[0]), Math.tanh(a[1])]; },\n tanh_3(a: [number, number, number]): [number, number, number] { return [Math.tanh(a[0]), Math.tanh(a[1]), Math.tanh(a[2])]; },\n tanh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.tanh(a[0]), Math.tanh(a[1]), Math.tanh(a[2]), Math.tanh(a[3])]; },\n acosh_1(a: number): number { return Math.acosh(a); },\n acosh_2(a: [number, number]): [number, number] { return [Math.acosh(a[0]), Math.acosh(a[1])]; },\n acosh_3(a: [number, number, number]): [number, number, number] { return [Math.acosh(a[0]), Math.acosh(a[1]), Math.acosh(a[2])]; },\n acosh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.acosh(a[0]), Math.acosh(a[1]), Math.acosh(a[2]), Math.acosh(a[3])]; },\n asinh_1(a: number): number { return Math.asinh(a); },\n asinh_2(a: [number, number]): [number, number] { return [Math.asinh(a[0]), Math.asinh(a[1])]; },\n asinh_3(a: [number, number, number]): [number, number, number] { return [Math.asinh(a[0]), Math.asinh(a[1]), Math.asinh(a[2])]; },\n asinh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.asinh(a[0]), Math.asinh(a[1]), Math.asinh(a[2]), Math.asinh(a[3])]; },\n atanh_1(a: number): number { return Math.atanh(a); },\n atanh_2(a: [number, number]): [number, number] { return [Math.atanh(a[0]), Math.atanh(a[1])]; },\n atanh_3(a: [number, number, number]): [number, number, number] { return [Math.atanh(a[0]), Math.atanh(a[1]), Math.atanh(a[2])]; },\n atanh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.atanh(a[0]), Math.atanh(a[1]), Math.atanh(a[2]), Math.atanh(a[3])]; },\n exp_1(a: number): number { return Math.exp(a); },\n exp_2(a: [number, number]): [number, number] { return [Math.exp(a[0]), Math.exp(a[1])]; },\n exp_3(a: [number, number, number]): [number, number, number] { return [Math.exp(a[0]), Math.exp(a[1]), Math.exp(a[2])]; },\n exp_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.exp(a[0]), Math.exp(a[1]), Math.exp(a[2]), Math.exp(a[3])]; },\n log_1(a: number): number { return Math.log(a); },\n log_2(a: [number, number]): [number, number] { return [Math.log(a[0]), Math.log(a[1])]; },\n log_3(a: [number, number, number]): [number, number, number] { return [Math.log(a[0]), Math.log(a[1]), Math.log(a[2])]; },\n log_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.log(a[0]), Math.log(a[1]), Math.log(a[2]), Math.log(a[3])]; },\n log2_1(a: number): number { return Math.log2(a); },\n log2_2(a: [number, number]): [number, number] { return [Math.log2(a[0]), Math.log2(a[1])]; },\n log2_3(a: [number, number, number]): [number, number, number] { return [Math.log2(a[0]), Math.log2(a[1]), Math.log2(a[2])]; },\n log2_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.log2(a[0]), Math.log2(a[1]), Math.log2(a[2]), Math.log2(a[3])]; },\n log10_1(a: number): number { return Math.log10(a); },\n log10_2(a: [number, number]): [number, number] { return [Math.log10(a[0]), Math.log10(a[1])]; },\n log10_3(a: [number, number, number]): [number, number, number] { return [Math.log10(a[0]), Math.log10(a[1]), Math.log10(a[2])]; },\n log10_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.log10(a[0]), Math.log10(a[1]), Math.log10(a[2]), Math.log10(a[3])]; },\n sqrt_1(a: number): number { return Math.sqrt(a); },\n sqrt_2(a: [number, number]): [number, number] { return [Math.sqrt(a[0]), Math.sqrt(a[1])]; },\n sqrt_3(a: [number, number, number]): [number, number, number] { return [Math.sqrt(a[0]), Math.sqrt(a[1]), Math.sqrt(a[2])]; },\n sqrt_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.sqrt(a[0]), Math.sqrt(a[1]), Math.sqrt(a[2]), Math.sqrt(a[3])]; },\n int_2_1_1(a: number, b: number): [number, number] { return [a|0, b|0]; },\n int_2_2(a: [number, number]): [number, number] { return [a[0]|0, a[1]|0]; },\n int_3_1_1_1(a: number, b: number, c: number): [number, number, number] { return [a|0, b|0, c|0]; },\n int_3_2_1(a: [number, number], b: number): [number, number, number] { return [a[0]|0, a[1]|0, b|0]; },\n int_3_1_2(a: number, b: [number, number]): [number, number, number] { return [a|0, b[0]|0, b[1]|0]; },\n int_3_3(a: [number, number, number]): [number, number, number] { return [a[0]|0, a[1]|0, a[2]|0]; },\n int_4_1_1_1_1(a: number, b: number, c: number, d: number): [number, number, number, number] { return [a|0, b|0, c|0, d|0]; },\n int_4_2_1_1(a: [number, number], b: number, c: number): [number, number, number, number] { return [a[0]|0, a[1]|0, b|0, c|0]; },\n int_4_1_2_1(a: number, b: [number, number], c: number): [number, number, number, number] { return [a|0, b[0]|0, b[1]|0, c|0]; },\n int_4_1_1_2(a: number, b: number, c: [number, number]): [number, number, number, number] { return [a|0, b|0, c[0]|0, c[1]|0]; },\n int_4_3_1(a: [number, number, number], b: number): [number, number, number, number] { return [a[0]|0, a[1]|0, a[2]|0, b|0]; },\n int_4_1_3(a: number, b: [number, number, number]): [number, number, number, number] { return [a|0, b[0]|0, b[1]|0, b[2]|0]; },\n int_4_2_2(a: [number, number], b: [number, number]): [number, number, number, number] { return [a[0]|0, a[1]|0, b[0]|0, b[1]|0]; },\n int_4_4(a: [number, number, number, number]): [number, number, number, number] { return [a[0]|0, a[1]|0, a[2]|0, a[3]|0]; },\n float_2_1_1(a: number, b: number): [number, number] { return [a, b]; },\n float_2_2(a: [number, number]): [number, number] { return [a[0], a[1]]; },\n float_3_1_1_1(a: number, b: number, c: number): [number, number, number] { return [a, b, c]; },\n float_3_2_1(a: [number, number], b: number): [number, number, number] { return [a[0], a[1], b]; },\n float_3_1_2(a: number, b: [number, number]): [number, number, number] { return [a, b[0], b[1]]; },\n float_3_3(a: [number, number, number]): [number, number, number] { return [a[0], a[1], a[2]]; },\n float_4_1_1_1_1(a: number, b: number, c: number, d: number): [number, number, number, number] { return [a, b, c, d]; },\n float_4_2_1_1(a: [number, number], b: number, c: number): [number, number, number, number] { return [a[0], a[1], b, c]; },\n float_4_1_2_1(a: number, b: [number, number], c: number): [number, number, number, number] { return [a, b[0], b[1], c]; },\n float_4_1_1_2(a: number, b: number, c: [number, number]): [number, number, number, number] { return [a, b, c[0], c[1]]; },\n float_4_3_1(a: [number, number, number], b: number): [number, number, number, number] { return [a[0], a[1], a[2], b]; },\n float_4_1_3(a: number, b: [number, number, number]): [number, number, number, number] { return [a, b[0], b[1], b[2]]; },\n float_4_2_2(a: [number, number], b: [number, number]): [number, number, number, number] { return [a[0], a[1], b[0], b[1]]; },\n float_4_4(a: [number, number, number, number]): [number, number, number, number] { return [a[0], a[1], a[2], a[3]]; },\n uint_2_1_1(a: number, b: number): [number, number] { return [a>>>0, b>>>0]; },\n uint_2_2(a: [number, number]): [number, number] { return [a[0]>>>0, a[1]>>>0]; },\n uint_3_1_1_1(a: number, b: number, c: number): [number, number, number] { return [a>>>0, b>>>0, c>>>0]; },\n uint_3_2_1(a: [number, number], b: number): [number, number, number] { return [a[0]>>>0, a[1]>>>0, b>>>0]; },\n uint_3_1_2(a: number, b: [number, number]): [number, number, number] { return [a>>>0, b[0]>>>0, b[1]>>>0]; },\n uint_3_3(a: [number, number, number]): [number, number, number] { return [a[0]>>>0, a[1]>>>0, a[2]>>>0]; },\n uint_4_1_1_1_1(a: number, b: number, c: number, d: number): [number, number, number, number] { return [a>>>0, b>>>0, c>>>0, d>>>0]; },\n uint_4_2_1_1(a: [number, number], b: number, c: number): [number, number, number, number] { return [a[0]>>>0, a[1]>>>0, b>>>0, c>>>0]; },\n uint_4_1_2_1(a: number, b: [number, number], c: number): [number, number, number, number] { return [a>>>0, b[0]>>>0, b[1]>>>0, c>>>0]; },\n uint_4_1_1_2(a: number, b: number, c: [number, number]): [number, number, number, number] { return [a>>>0, b>>>0, c[0]>>>0, c[1]>>>0]; },\n uint_4_3_1(a: [number, number, number], b: number): [number, number, number, number] { return [a[0]>>>0, a[1]>>>0, a[2]>>>0, b>>>0]; },\n uint_4_1_3(a: number, b: [number, number, number]): [number, number, number, number] { return [a>>>0, b[0]>>>0, b[1]>>>0, b[2]>>>0]; },\n uint_4_2_2(a: [number, number], b: [number, number]): [number, number, number, number] { return [a[0]>>>0, a[1]>>>0, b[0]>>>0, b[1]>>>0]; },\n uint_4_4(a: [number, number, number, number]): [number, number, number, number] { return [a[0]>>>0, a[1]>>>0, a[2]>>>0, a[3]>>>0]; },\n}\n"; const stdAll = `/**__SHADEUP_STRUCT_INJECTION_HOOK__*/\r export const __dummy = 1;\r \r import {\r bool,\r float,\r float2,\r float3,\r float4,\r int,\r int2,\r int3,\r int4,\r uint,\r uint3,\r atomic\r } from '/std_math';\r // import { Mesh } from '/_std/mesh';\r \r export class Mesh {\r private vertices: float3[] = [];\r private triangles: int[] = [];\r private normals: float3[] = [];\r private tangents: float3[] = [];\r private bitangents: float3[] = [];\r private uvs: float2[] = [];\r private colors: float4[] = [];\r symbol: Symbol;\r \r constructor(prefils: {\r vertices?: float3[];\r triangles?: int[];\r normals?: float3[];\r tangents?: float3[];\r bitangents?: float3[];\r uvs?: float2[];\r colors?: float4[];\r }) {\r this.symbol = Symbol();\r if (prefils.vertices) this.vertices = prefils.vertices;\r if (prefils.triangles) this.triangles = prefils.triangles;\r if (prefils.normals) this.normals = prefils.normals;\r if (prefils.tangents) this.tangents = prefils.tangents;\r if (prefils.bitangents) this.bitangents = prefils.bitangents;\r if (prefils.uvs) this.uvs = prefils.uvs;\r if (prefils.colors) this.colors = prefils.colors;\r }\r \r getVertices() {\r return this.vertices;\r }\r \r getTriangles() {\r return this.triangles;\r }\r \r getNormals() {\r return this.normals;\r }\r \r getTangents() {\r return this.tangents;\r }\r \r getBitangents() {\r return this.bitangents;\r }\r \r getUVs() {\r return this.uvs;\r }\r \r getColors() {\r return this.colors;\r }\r }\r \r declare global {\r const localEngineContext: any;\r }\r \r export const getShadeupLocalContext = (): any => {\r if (typeof localEngineContext !== 'undefined') {\r return localEngineContext;\r } else {\r return window;\r }\r };\r \r /**\r * Prints a set of value(s) to the console. Values will be converted to strings before printing.\r *\r * @param args Any number of values to print to the console\r */\r export function print(...args: any[]) {\r console.log(...args);\r if (typeof getShadeupLocalContext()['__shadeup_print'] === 'function') {\r getShadeupLocalContext()['__shadeup_print'](...args);\r }\r }\r \r /**\r * Flushes (executes) all queued compute or draw calls\r * @shadeup=tag(async) @shadeup=noemit_gpu\r */\r export async function flush() {\r if (typeof getShadeupLocalContext()['flushAdapter'] === 'function') {\r return await getShadeupLocalContext()['flushAdapter']();\r }\r }\r \r /**\r * Displays a single value in the stats panel at the top right\r *\r * @param name key for this stat (e.g. "fps")\r * @param value any value\r */\r export function stat(name: string, value: any) {\r if (typeof getShadeupLocalContext()['__shadeup_stat'] === 'function') {\r getShadeupLocalContext()['__shadeup_stat'](name, value);\r }\r }\r \r /**\r * Display a graph of a numeric value over time\r *\r * @param name key for this stat (e.g. "fps")\r * @param value any numeric value\r * @param sampleRate how often should the graph be updated (e.g. 1 = every call, 2 = every second call, etc.)\r */\r export function statGraph(name: string, value: float, sampleRate: int = 1) {\r if (typeof getShadeupLocalContext()['__shadeup_statGraph'] === 'function') {\r getShadeupLocalContext()['__shadeup_statGraph'](name, value);\r }\r }\r \r // type InferPayload1 = {\r // data: [T];\r // callback: (a: { attachment0: T }) => void;\r // };\r \r // type InferPayload2 = {\r // data: [T, I];\r // callback: (a: { attachment0: T; attachment1: I }) => void;\r // };\r \r // function infer(payload: InferPayload1 | InferPayload2);\r // function infer(a: any) {}\r \r // infer({\r // data: [67],\r // callback: (a) => {\r // a[0];\r // }\r // });\r \r type FnPass = (a: T) => void;\r \r function infer(fn: (a: I, b: O) => void): shader {\r return fn as shader;\r }\r \r // export function drawAlt(keys: shader) {}\r // export function draw(fullScreenPixelShader: shader): void;\r // export function draw(\r // first: Mesh | any | shader,\r // second?: shader,\r // third?: shader\r // ) {\r // if ('vertices' in first && second && third) {\r // __shadeup_dispatch_draw_geometry(first, second, third);\r // } else if (first && !second && !third) {\r // __shadeup_dispatch_draw(first as shader);\r // }\r // }\r \r // draw(makeShader('', (a, b) => {}));\r // drawAlt(\r // makeShader(\r // '000004808000091289258019303699031390005438610',\r // /**@shadeup=shader*/ (__in, __out) => {\r // __out.color;\r // }\r // )\r // );\r // /**\r // *\r // */\r export function compute(workgroups: int3, computeShader: shader) {\r getShadeupLocalContext().__shadeup_dispatch_compute(workgroups, computeShader);\r }\r \r // function draww(s: shader<{ abc: 123 }, { test: 123 }>) {}\r \r // type x = { x: T };\r \r // function makeTex(a: T): x {\r // return { x: a };\r // }\r // draw({\r // vertex: shader('abc', (__in, __out) => {}),\r // attachments: [\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 })\r // ],\r // mesh: new Mesh(),\r // fragment: shader('abc', (__in, __out) => {\r // //__out.attachment0\r // })\r // });\r \r export function globalVarInit(\r fileName: string,\r varName: string,\r initFn: () => T,\r getterFn: any\r ): T {\r if (!getShadeupLocalContext()['shadeup_globals']) {\r getShadeupLocalContext()['shadeup_globals'] = {};\r }\r \r if (!getShadeupLocalContext()['shadeup_globals'][fileName]) {\r getShadeupLocalContext()['shadeup_globals'][fileName] = {};\r }\r \r // Disable caching for now\r const cache = false;\r if (!(varName in getShadeupLocalContext()['shadeup_globals'][fileName]) || !cache) {\r getShadeupLocalContext()['shadeup_globals'][fileName][varName] = initFn();\r }\r getShadeupLocalContext()['shadeup_globals'][fileName]['$getter_' + varName] = getterFn;\r return getShadeupLocalContext()['shadeup_globals'][fileName][varName] as T;\r }\r \r export function globalVarGet(fileName, varName) {\r if (varName == 'env' || varName == 'PLATFORM_WEBGPU' || varName == 'PLATFORM_WEBGL') {\r return getShadeupLocalContext()[varName];\r }\r \r return getShadeupLocalContext()['shadeup_globals'][fileName]['$getter_' + varName]();\r }\r \r interface ToString {\r toString(): string;\r }\r \r type HashableType =\r | string\r | float\r | int\r | bool\r | float2\r | float3\r | float4\r | int2\r | int3\r | int4\r | ToString;\r \r export function hashableTypeToString(k: HashableType) {\r if (typeof k == 'number') {\r return k.toString();\r } else if (typeof k == 'object') {\r if (Array.isArray(k)) {\r return k.map(hashableTypeToString).join(',');\r } else {\r return k.toString();\r }\r } else {\r return k.toString();\r }\r }\r \r declare global {\r const PLATFORM_WEBGPU: boolean;\r const PLATFORM_WEBGL: boolean;\r \r interface Array {\r len(): int;\r push(...items: T[]): void;\r pop(): T;\r \r last(): T;\r first(): T;\r \r append(items: T[]): void;\r remove(index: int): void;\r \r indexOf(item: T): int;\r \r __index(index: int | uint): T;\r \r __index_assign(index: int | uint, value: T): void;\r __index_assign_op(op_fn: (a: T, b: T) => T, index: int | uint, value: T): void;\r \r [index: number]: T;\r }\r }\r \r Array.prototype.len = function () {\r return this.length;\r };\r \r Array.prototype.last = function () {\r return this[this.length - 1];\r };\r \r Array.prototype.first = function () {\r return this[0];\r };\r \r Array.prototype.append = function (items: any[]) {\r for (let i = 0; i < items.length; i++) {\r this.push(items[i]);\r }\r };\r \r Array.prototype.remove = function (index: int) {\r this.splice(index, 1);\r };\r \r Array.prototype.__index = function (index: int) {\r return this[index];\r };\r \r Array.prototype.__index_assign = function (index: int, value: any) {\r this[index] = value;\r };\r \r Array.prototype.__index_assign_op = function (\r op_fn: (a: any, b: any) => any,\r index: int,\r value: any\r ) {\r this[index] = op_fn(this[index], value);\r };\r \r /** @shadeup=tag(async) */\r export function sleep(seconds: float) {\r return new Promise((resolve) => setTimeout(resolve, seconds * 1000));\r }\r \r export type array = Array;\r export function array(count: number, initializer: any = null): array {\r let arr = new Array(count);\r if (initializer) {\r for (let i = 0; i < count; i++) {\r arr[i] = initializer;\r }\r }\r return arr;\r }\r \r export class map {\r pairs: Map = new Map();\r \r constructor(entries?: [K, V][]) {\r if (entries)\r for (let e of entries) {\r this.__index_assign(e[0], e[1]);\r }\r }\r \r __index(key: K): V {\r if (!this.pairs.has(hashableTypeToString(key))) {\r throw new Error('Key not found: ' + hashableTypeToString(key));\r }\r \r return this.pairs.get(hashableTypeToString(key))[1];\r }\r \r __index_assign(key: K, value: V) {\r this.pairs.set(hashableTypeToString(key), [key, value]);\r }\r \r __index_assign_op(op_fn: (a: V, b: V) => V, key: K, value: V) {\r this.pairs.set(hashableTypeToString(key), [key, op_fn(this.__index(key), value)]);\r }\r \r delete(key: K) {\r this.pairs.delete(hashableTypeToString(key));\r }\r \r has(key: K): bool {\r return this.pairs.has(hashableTypeToString(key));\r }\r \r keys(): K[] {\r return Array.from(this.pairs.values()).map((k) => k[0]);\r }\r \r values(): V[] {\r return Array.from(this.pairs.values()).map((k) => k[1]);\r }\r \r static new(entries?: [K, V][]): map {\r return new map(entries);\r }\r }\r \r export function __makeMap(initial: { [key: number]: V }): map;\r export function __makeMap(initial: { [key: string]: V }): map;\r export function __makeMap(initial: { [key: string | number]: V }): map {\r return new map(Object.entries(initial));\r }\r \r export function __deepClone(value: any) {\r if (typeof value == 'object') {\r if (Array.isArray(value)) {\r let res = new Array(value.length);\r for (let i = 0; i < value.length; i++) {\r res[i] = __deepClone(value[i]);\r }\r return res;\r } else {\r if (value && typeof value.clone == 'function') {\r return value.clone();\r } else {\r return value;\r }\r }\r } else {\r return value;\r }\r }\r \r export interface Spatial2d {\r getPosition(): float2;\r getBoundsMin(): float2;\r getBoundsMax(): float2;\r getRadius(): float;\r \r setPosition(pos: float2): void;\r }\r \r export interface Spatial3d {\r getPosition(): float3;\r getBoundsMin(): float3;\r getBoundsMax(): float3;\r getRadius(): float;\r \r setPosition(pos: float3): void;\r }\r \r export class time {\r /** Saves the current time with a key of name */\r static start(name?: string) {\r performance.mark((name ?? '_default') + '_start');\r }\r \r /** Returns the difference in milliseconds between a start with the same key */\r static stop(name?: string): float {\r performance.mark((name ?? '_default') + '_end');\r \r let res = performance.measure(\r (name ?? '_default') + '_diff',\r (name ?? '_default') + '_start',\r (name ?? '_default') + '_end'\r );\r \r return res.duration;\r }\r \r /**\r * This returns a decimal resolution time in milliseconds since the page started. Useful for measuring time differences\r *\r * This uses performance.now() under the hood:\r * The performance.now() method returns a high resolution timestamp in milliseconds. It represents the time elapsed since Performance.timeOrigin\r */\r static now(): float {\r return performance.now();\r }\r }\r `; const globalDTS = "/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n\r\n/// \r\n\r\n/// \r\n/// \r\n\r\n/////////////////////////////\r\n/// ECMAScript APIs\r\n/////////////////////////////\r\n\r\ntype float = number & { _opaque_float: 2 };\r\ntype int = number & { _opaque_int: 1 } & float;\r\n\r\ndeclare var NaN: number;\r\ndeclare var Infinity: number;\r\n\r\n/**\r\n * Converts a string to an integer.\r\n * @param string A string to convert into a number.\r\n * @param radix A value between 2 and 36 that specifies the base of the number in `string`.\r\n * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\r\n * All other strings are considered decimal.\r\n */\r\ndeclare function parseInt(string: string, radix?: number): number;\r\n\r\n/**\r\n * Converts a string to a floating-point number.\r\n * @param string A string that contains a floating-point number.\r\n */\r\ndeclare function parseFloat(string: string): number;\r\n\r\n/**\r\n * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).\r\n * @param number A numeric value.\r\n */\r\ndeclare function isNaN(number: number): boolean;\r\n\r\n/**\r\n * Determines whether a supplied number is finite.\r\n * @param number Any numeric value.\r\n */\r\ndeclare function isFinite(number: number): boolean;\r\n\r\n/**\r\n * Gets the unencoded version of an encoded Uniform Resource Identifier (URI).\r\n * @param encodedURI A value representing an encoded URI.\r\n */\r\ndeclare function decodeURI(encodedURI: string): string;\r\n\r\n/**\r\n * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).\r\n * @param encodedURIComponent A value representing an encoded URI component.\r\n */\r\ndeclare function decodeURIComponent(encodedURIComponent: string): string;\r\n\r\n/**\r\n * Encodes a text string as a valid Uniform Resource Identifier (URI)\r\n * @param uri A value representing an unencoded URI.\r\n */\r\ndeclare function encodeURI(uri: string): string;\r\n\r\n/**\r\n * Encodes a text string as a valid component of a Uniform Resource Identifier (URI).\r\n * @param uriComponent A value representing an unencoded URI component.\r\n */\r\ndeclare function encodeURIComponent(uriComponent: string | number | boolean): string;\r\n\r\n/**\r\n * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.\r\n * @deprecated A legacy feature for browser compatibility\r\n * @param string A string value\r\n */\r\ndeclare function escape(string: string): string;\r\n\r\n/**\r\n * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents.\r\n * @deprecated A legacy feature for browser compatibility\r\n * @param string A string value\r\n */\r\ndeclare function unescape(string: string): string;\r\n\r\ninterface Symbol {\r\n /** Returns a string representation of an object. */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): symbol;\r\n}\r\n\r\ndeclare type PropertyKey = string | number | symbol;\r\n\r\ninterface PropertyDescriptor {\r\n configurable?: boolean;\r\n enumerable?: boolean;\r\n value?: any;\r\n writable?: boolean;\r\n get?(): any;\r\n set?(v: any): void;\r\n}\r\n\r\ninterface PropertyDescriptorMap {\r\n [key: PropertyKey]: PropertyDescriptor;\r\n}\r\n\r\ninterface Object {\r\n /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */\r\n constructor: Function;\r\n\r\n /** Returns a string representation of an object. */\r\n toString(): string;\r\n\r\n /** Returns a date converted to a string using the current locale. */\r\n toLocaleString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Object;\r\n\r\n /**\r\n * Determines whether an object has a property with the specified name.\r\n * @param v A property name.\r\n */\r\n hasOwnProperty(v: PropertyKey): boolean;\r\n\r\n /**\r\n * Determines whether an object exists in another object's prototype chain.\r\n * @param v Another object whose prototype chain is to be checked.\r\n */\r\n isPrototypeOf(v: Object): boolean;\r\n\r\n /**\r\n * Determines whether a specified property is enumerable.\r\n * @param v A property name.\r\n */\r\n propertyIsEnumerable(v: PropertyKey): boolean;\r\n}\r\n\r\ninterface ObjectConstructor {\r\n new (value?: any): Object;\r\n (): any;\r\n (value: any): any;\r\n\r\n /** A reference to the prototype for a class of objects. */\r\n readonly prototype: Object;\r\n\r\n /**\r\n * Returns the prototype of an object.\r\n * @param o The object that references the prototype.\r\n */\r\n getPrototypeOf(o: any): any;\r\n\r\n /**\r\n * Gets the own property descriptor of the specified object.\r\n * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.\r\n * @param o Object that contains the property.\r\n * @param p Name of the property.\r\n */\r\n getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined;\r\n\r\n /**\r\n * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly\r\n * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions.\r\n * @param o Object that contains the own properties.\r\n */\r\n getOwnPropertyNames(o: any): string[];\r\n\r\n /**\r\n * Creates an object that has the specified prototype or that has null prototype.\r\n * @param o Object to use as a prototype. May be null.\r\n */\r\n create(o: object | null): any;\r\n\r\n /**\r\n * Creates an object that has the specified prototype, and that optionally contains specified properties.\r\n * @param o Object to use as a prototype. May be null\r\n * @param properties JavaScript object that contains one or more property descriptors.\r\n */\r\n create(o: object | null, properties: PropertyDescriptorMap & ThisType): any;\r\n\r\n /**\r\n * Adds a property to an object, or modifies attributes of an existing property.\r\n * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object.\r\n * @param p The property name.\r\n * @param attributes Descriptor for the property. It can be for a data property or an accessor property.\r\n */\r\n defineProperty(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType): T;\r\n\r\n /**\r\n * Adds one or more properties to an object, and/or modifies attributes of existing properties.\r\n * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object.\r\n * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property.\r\n */\r\n defineProperties(o: T, properties: PropertyDescriptorMap & ThisType): T;\r\n\r\n /**\r\n * Prevents the modification of attributes of existing properties, and prevents the addition of new properties.\r\n * @param o Object on which to lock the attributes.\r\n */\r\n seal(o: T): T;\r\n\r\n /**\r\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\r\n * @param f Object on which to lock the attributes.\r\n */\r\n freeze(f: T): T;\r\n\r\n /**\r\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\r\n * @param o Object on which to lock the attributes.\r\n */\r\n freeze<\r\n T extends { [idx: string]: U | null | undefined | object },\r\n U extends string | bigint | number | boolean | symbol\r\n >(\r\n o: T\r\n ): Readonly;\r\n\r\n /**\r\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\r\n * @param o Object on which to lock the attributes.\r\n */\r\n freeze(o: T): Readonly;\r\n\r\n /**\r\n * Prevents the addition of new properties to an object.\r\n * @param o Object to make non-extensible.\r\n */\r\n preventExtensions(o: T): T;\r\n\r\n /**\r\n * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object.\r\n * @param o Object to test.\r\n */\r\n isSealed(o: any): boolean;\r\n\r\n /**\r\n * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object.\r\n * @param o Object to test.\r\n */\r\n isFrozen(o: any): boolean;\r\n\r\n /**\r\n * Returns a value that indicates whether new properties can be added to an object.\r\n * @param o Object to test.\r\n */\r\n isExtensible(o: any): boolean;\r\n\r\n /**\r\n * Returns the names of the enumerable string properties and methods of an object.\r\n * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.\r\n */\r\n keys(o: object): string[];\r\n}\r\n\r\n/**\r\n * Provides functionality common to all JavaScript objects.\r\n */\r\ndeclare var Object: ObjectConstructor;\r\n\r\n/**\r\n * Creates a new function.\r\n */\r\ninterface Function {\r\n /**\r\n * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.\r\n * @param thisArg The object to be used as the this object.\r\n * @param argArray A set of arguments to be passed to the function.\r\n */\r\n apply(this: Function, thisArg: any, argArray?: any): any;\r\n\r\n /**\r\n * Calls a method of an object, substituting another object for the current object.\r\n * @param thisArg The object to be used as the current object.\r\n * @param argArray A list of arguments to be passed to the method.\r\n */\r\n call(this: Function, thisArg: any, ...argArray: any[]): any;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg An object to which the this keyword can refer inside the new function.\r\n * @param argArray A list of arguments to be passed to the new function.\r\n */\r\n bind(this: Function, thisArg: any, ...argArray: any[]): any;\r\n\r\n /** Returns a string representation of a function. */\r\n toString(): string;\r\n\r\n prototype: any;\r\n readonly length: int;\r\n\r\n // Non-standard extensions\r\n arguments: any;\r\n caller: Function;\r\n}\r\n\r\ninterface FunctionConstructor {\r\n /**\r\n * Creates a new function.\r\n * @param args A list of arguments the function accepts.\r\n */\r\n new (...args: string[]): Function;\r\n (...args: string[]): Function;\r\n readonly prototype: Function;\r\n}\r\n\r\ndeclare var Function: FunctionConstructor;\r\n\r\n/**\r\n * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.\r\n */\r\ntype ThisParameterType = T extends (this: infer U, ...args: never) => any ? U : unknown;\r\n\r\n/**\r\n * Removes the 'this' parameter from a function type.\r\n */\r\ntype OmitThisParameter = unknown extends ThisParameterType\r\n ? T\r\n : T extends (...args: infer A) => infer R\r\n ? (...args: A) => R\r\n : T;\r\n\r\ninterface CallableFunction extends Function {\r\n /**\r\n * Calls the function with the specified object as the this value and the elements of specified array as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n */\r\n apply(this: (this: T) => R, thisArg: T): R;\r\n\r\n /**\r\n * Calls the function with the specified object as the this value and the elements of specified array as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args An array of argument values to be passed to the function.\r\n */\r\n apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R;\r\n\r\n /**\r\n * Calls the function with the specified object as the this value and the specified rest arguments as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args Argument values to be passed to the function.\r\n */\r\n call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg The object to be used as the this object.\r\n */\r\n bind(this: T, thisArg: ThisParameterType): OmitThisParameter;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args Arguments to bind to the parameters of the function.\r\n */\r\n bind(\r\n this: (this: T, ...args: [...A, ...B]) => R,\r\n thisArg: T,\r\n ...args: A\r\n ): (...args: B) => R;\r\n}\r\n\r\ninterface NewableFunction extends Function {\r\n /**\r\n * Calls the function with the specified object as the this value and the elements of specified array as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n */\r\n apply(this: new () => T, thisArg: T): void;\r\n /**\r\n * Calls the function with the specified object as the this value and the elements of specified array as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args An array of argument values to be passed to the function.\r\n */\r\n apply(this: new (...args: A) => T, thisArg: T, args: A): void;\r\n\r\n /**\r\n * Calls the function with the specified object as the this value and the specified rest arguments as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args Argument values to be passed to the function.\r\n */\r\n call(this: new (...args: A) => T, thisArg: T, ...args: A): void;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg The object to be used as the this object.\r\n */\r\n bind(this: T, thisArg: any): T;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args Arguments to bind to the parameters of the function.\r\n */\r\n bind(\r\n this: new (...args: [...A, ...B]) => R,\r\n thisArg: any,\r\n ...args: A\r\n ): new (...args: B) => R;\r\n}\r\n\r\ninterface IArguments {\r\n [index: number]: any;\r\n length: int;\r\n callee: Function;\r\n}\r\n\r\ninterface String {\r\n /** Returns a string representation of a string. */\r\n toString(): string;\r\n\r\n /**\r\n * Returns the character at the specified index.\r\n * @param pos The zero-based index of the desired character.\r\n */\r\n charAt(pos: number): string;\r\n\r\n /**\r\n * Returns the Unicode value of the character at the specified location.\r\n * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.\r\n */\r\n charCodeAt(index: number): number;\r\n\r\n /**\r\n * Returns a string that contains the concatenation of two or more strings.\r\n * @param strings The strings to append to the end of the string.\r\n */\r\n concat(...strings: string[]): string;\r\n\r\n /**\r\n * Returns the position of the first occurrence of a substring.\r\n * @param searchString The substring to search for in the string\r\n * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.\r\n */\r\n indexOf(searchString: string, position?: number): number;\r\n\r\n /**\r\n * Returns the last occurrence of a substring in the string.\r\n * @param searchString The substring to search for.\r\n * @param position The index at which to begin searching. If omitted, the search begins at the end of the string.\r\n */\r\n lastIndexOf(searchString: string, position?: number): number;\r\n\r\n /**\r\n * Determines whether two strings are equivalent in the current locale.\r\n * @param that String to compare to target string\r\n */\r\n localeCompare(that: string): number;\r\n\r\n /**\r\n * Matches a string with a regular expression, and returns an array containing the results of that search.\r\n * @param regexp A variable name or string literal containing the regular expression pattern and flags.\r\n */\r\n match(regexp: string | RegExp): RegExpMatchArray | null;\r\n\r\n /**\r\n * Replaces text in a string, using a regular expression or search string.\r\n * @param searchValue A string or regular expression to search for.\r\n * @param replaceValue A string containing the text to replace. When the {@linkcode searchValue} is a `RegExp`, all matches are replaced if the `g` flag is set (or only those matches at the beginning, if the `y` flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.\r\n */\r\n replace(searchValue: string | RegExp, replaceValue: string): string;\r\n\r\n /**\r\n * Replaces text in a string, using a regular expression or search string.\r\n * @param searchValue A string to search for.\r\n * @param replacer A function that returns the replacement text.\r\n */\r\n replace(\r\n searchValue: string | RegExp,\r\n replacer: (substring: string, ...args: any[]) => string\r\n ): string;\r\n\r\n /**\r\n * Finds the first substring match in a regular expression search.\r\n * @param regexp The regular expression pattern and applicable flags.\r\n */\r\n search(regexp: string | RegExp): number;\r\n\r\n /**\r\n * Returns a section of a string.\r\n * @param start The index to the beginning of the specified portion of stringObj.\r\n * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.\r\n * If this value is not specified, the substring continues to the end of stringObj.\r\n */\r\n slice(start?: number, end?: number): string;\r\n\r\n /**\r\n * Split a string into substrings using the specified separator and return them as an array.\r\n * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.\r\n * @param limit A value used to limit the number of elements returned in the array.\r\n */\r\n split(separator: string | RegExp, limit?: number): string[];\r\n\r\n /**\r\n * Returns the substring at the specified location within a String object.\r\n * @param start The zero-based index number indicating the beginning of the substring.\r\n * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.\r\n * If end is omitted, the characters from start through the end of the original string are returned.\r\n */\r\n substring(start: number, end?: number): string;\r\n\r\n /** Converts all the alphabetic characters in a string to lowercase. */\r\n toLowerCase(): string;\r\n\r\n /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */\r\n toLocaleLowerCase(locales?: string | string[]): string;\r\n\r\n /** Converts all the alphabetic characters in a string to uppercase. */\r\n toUpperCase(): string;\r\n\r\n /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */\r\n toLocaleUpperCase(locales?: string | string[]): string;\r\n\r\n /** Removes the leading and trailing white space and line terminator characters from a string. */\r\n trim(): string;\r\n\r\n /** Returns the length of a String object. */\r\n readonly length: int;\r\n\r\n // IE extensions\r\n /**\r\n * Gets a substring beginning at the specified location and having the specified length.\r\n * @deprecated A legacy feature for browser compatibility\r\n * @param from The starting position of the desired substring. The index of the first character in the string is zero.\r\n * @param length The number of characters to include in the returned substring.\r\n */\r\n substr(from: number, length?: number): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): string;\r\n\r\n readonly [index: number]: string;\r\n}\r\n\r\ninterface StringConstructor {\r\n new (value?: any): String;\r\n (value?: any): string;\r\n readonly prototype: String;\r\n fromCharCode(...codes: number[]): string;\r\n}\r\n\r\n/**\r\n * Allows manipulation and formatting of text strings and determination and location of substrings within strings.\r\n */\r\ndeclare var String: StringConstructor;\r\n\r\ninterface Boolean {\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): boolean;\r\n}\r\n\r\ninterface BooleanConstructor {\r\n new (value?: any): Boolean;\r\n (value?: T): boolean;\r\n readonly prototype: Boolean;\r\n}\r\n\r\ndeclare var Boolean: BooleanConstructor;\r\n\r\ninterface Number {\r\n /**\r\n * Returns a string representation of an object.\r\n * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.\r\n */\r\n toString(radix?: number): string;\r\n\r\n /**\r\n * Returns a string representing a number in fixed-point notation.\r\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\r\n */\r\n toFixed(fractionDigits?: number): string;\r\n\r\n /**\r\n * Returns a string containing a number represented in exponential notation.\r\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\r\n */\r\n toExponential(fractionDigits?: number): string;\r\n\r\n /**\r\n * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.\r\n * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.\r\n */\r\n toPrecision(precision?: number): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): number;\r\n}\r\n\r\ninterface NumberConstructor {\r\n new (value?: any): Number;\r\n (value?: any): number;\r\n readonly prototype: Number;\r\n\r\n /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */\r\n readonly MAX_VALUE: number;\r\n\r\n /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */\r\n readonly MIN_VALUE: number;\r\n\r\n /**\r\n * A value that is not a number.\r\n * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function.\r\n */\r\n readonly NaN: number;\r\n\r\n /**\r\n * A value that is less than the largest negative number that can be represented in JavaScript.\r\n * JavaScript displays NEGATIVE_INFINITY values as -infinity.\r\n */\r\n readonly NEGATIVE_INFINITY: number;\r\n\r\n /**\r\n * A value greater than the largest number that can be represented in JavaScript.\r\n * JavaScript displays POSITIVE_INFINITY values as infinity.\r\n */\r\n readonly POSITIVE_INFINITY: number;\r\n}\r\n\r\n/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */\r\ndeclare var Number: NumberConstructor;\r\n\r\ninterface TemplateStringsArray extends ReadonlyArray {\r\n readonly raw: readonly string[];\r\n}\r\n\r\n/**\r\n * The type of `import.meta`.\r\n *\r\n * If you need to declare that a given property exists on `import.meta`,\r\n * this type may be augmented via interface merging.\r\n */\r\ninterface ImportMeta {}\r\n\r\n/**\r\n * The type for the optional second argument to `import()`.\r\n *\r\n * If your host environment supports additional options, this type may be\r\n * augmented via interface merging.\r\n */\r\ninterface ImportCallOptions {\r\n assert?: ImportAssertions;\r\n}\r\n\r\n/**\r\n * The type for the `assert` property of the optional second argument to `import()`.\r\n */\r\ninterface ImportAssertions {\r\n [key: string]: string;\r\n}\r\n\r\ninterface Math {\r\n /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */\r\n readonly E: number;\r\n /** The natural logarithm of 10. */\r\n readonly LN10: number;\r\n /** The natural logarithm of 2. */\r\n readonly LN2: number;\r\n /** The base-2 logarithm of e. */\r\n readonly LOG2E: number;\r\n /** The base-10 logarithm of e. */\r\n readonly LOG10E: number;\r\n /** Pi. This is the ratio of the circumference of a circle to its diameter. */\r\n readonly PI: number;\r\n /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */\r\n readonly SQRT1_2: number;\r\n /** The square root of 2. */\r\n readonly SQRT2: number;\r\n /**\r\n * Returns the absolute value of a number (the value without regard to whether it is positive or negative).\r\n * For example, the absolute value of -5 is the same as the absolute value of 5.\r\n * @param x A numeric expression for which the absolute value is needed.\r\n */\r\n abs(x: number): number;\r\n /**\r\n * Returns the arc cosine (or inverse cosine) of a number.\r\n * @param x A numeric expression.\r\n */\r\n acos(x: number): number;\r\n /**\r\n * Returns the arcsine of a number.\r\n * @param x A numeric expression.\r\n */\r\n asin(x: number): number;\r\n /**\r\n * Returns the arctangent of a number.\r\n * @param x A numeric expression for which the arctangent is needed.\r\n */\r\n atan(x: number): number;\r\n /**\r\n * Returns the angle (in radians) from the X axis to a point.\r\n * @param y A numeric expression representing the cartesian y-coordinate.\r\n * @param x A numeric expression representing the cartesian x-coordinate.\r\n */\r\n atan2(y: number, x: number): number;\r\n /**\r\n * Returns the smallest integer greater than or equal to its numeric argument.\r\n * @param x A numeric expression.\r\n */\r\n ceil(x: number): number;\r\n /**\r\n * Returns the cosine of a number.\r\n * @param x A numeric expression that contains an angle measured in radians.\r\n */\r\n cos(x: number): number;\r\n /**\r\n * Returns e (the base of natural logarithms) raised to a power.\r\n * @param x A numeric expression representing the power of e.\r\n */\r\n exp(x: number): number;\r\n /**\r\n * Returns the greatest integer less than or equal to its numeric argument.\r\n * @param x A numeric expression.\r\n */\r\n floor(x: number): number;\r\n /**\r\n * Returns the natural logarithm (base e) of a number.\r\n * @param x A numeric expression.\r\n */\r\n log(x: number): number;\r\n /**\r\n * Returns the larger of a set of supplied numeric expressions.\r\n * @param values Numeric expressions to be evaluated.\r\n */\r\n max(...values: number[]): number;\r\n /**\r\n * Returns the smaller of a set of supplied numeric expressions.\r\n * @param values Numeric expressions to be evaluated.\r\n */\r\n min(...values: number[]): number;\r\n /**\r\n * Returns the value of a base expression taken to a specified power.\r\n * @param x The base value of the expression.\r\n * @param y The exponent value of the expression.\r\n */\r\n pow(x: number, y: number): number;\r\n /** Returns a pseudorandom number between 0 and 1. */\r\n random(): number;\r\n /**\r\n * Returns a supplied numeric expression rounded to the nearest integer.\r\n * @param x The value to be rounded to the nearest integer.\r\n */\r\n round(x: number): number;\r\n /**\r\n * Returns the sine of a number.\r\n * @param x A numeric expression that contains an angle measured in radians.\r\n */\r\n sin(x: number): number;\r\n /**\r\n * Returns the square root of a number.\r\n * @param x A numeric expression.\r\n */\r\n sqrt(x: number): number;\r\n /**\r\n * Returns the tangent of a number.\r\n * @param x A numeric expression that contains an angle measured in radians.\r\n */\r\n tan(x: number): number;\r\n}\r\n/** An intrinsic object that provides basic mathematics functionality and constants. */\r\ndeclare var Math: Math;\r\n\r\n/** Enables basic storage and retrieval of dates and times. */\r\ninterface Date {\r\n /** Returns a string representation of a date. The format of the string depends on the locale. */\r\n toString(): string;\r\n /** Returns a date as a string value. */\r\n toDateString(): string;\r\n /** Returns a time as a string value. */\r\n toTimeString(): string;\r\n /** Returns a value as a string value appropriate to the host environment's current locale. */\r\n toLocaleString(): string;\r\n /** Returns a date as a string value appropriate to the host environment's current locale. */\r\n toLocaleDateString(): string;\r\n /** Returns a time as a string value appropriate to the host environment's current locale. */\r\n toLocaleTimeString(): string;\r\n /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */\r\n valueOf(): number;\r\n /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */\r\n getTime(): number;\r\n /** Gets the year, using local time. */\r\n getFullYear(): number;\r\n /** Gets the year using Universal Coordinated Time (UTC). */\r\n getUTCFullYear(): number;\r\n /** Gets the month, using local time. */\r\n getMonth(): number;\r\n /** Gets the month of a Date object using Universal Coordinated Time (UTC). */\r\n getUTCMonth(): number;\r\n /** Gets the day-of-the-month, using local time. */\r\n getDate(): number;\r\n /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */\r\n getUTCDate(): number;\r\n /** Gets the day of the week, using local time. */\r\n getDay(): number;\r\n /** Gets the day of the week using Universal Coordinated Time (UTC). */\r\n getUTCDay(): number;\r\n /** Gets the hours in a date, using local time. */\r\n getHours(): number;\r\n /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */\r\n getUTCHours(): number;\r\n /** Gets the minutes of a Date object, using local time. */\r\n getMinutes(): number;\r\n /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */\r\n getUTCMinutes(): number;\r\n /** Gets the seconds of a Date object, using local time. */\r\n getSeconds(): number;\r\n /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */\r\n getUTCSeconds(): number;\r\n /** Gets the milliseconds of a Date, using local time. */\r\n getMilliseconds(): number;\r\n /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */\r\n getUTCMilliseconds(): number;\r\n /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */\r\n getTimezoneOffset(): number;\r\n /**\r\n * Sets the date and time value in the Date object.\r\n * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.\r\n */\r\n setTime(time: number): number;\r\n /**\r\n * Sets the milliseconds value in the Date object using local time.\r\n * @param ms A numeric value equal to the millisecond value.\r\n */\r\n setMilliseconds(ms: number): number;\r\n /**\r\n * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).\r\n * @param ms A numeric value equal to the millisecond value.\r\n */\r\n setUTCMilliseconds(ms: number): number;\r\n\r\n /**\r\n * Sets the seconds value in the Date object using local time.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setSeconds(sec: number, ms?: number): number;\r\n /**\r\n * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setUTCSeconds(sec: number, ms?: number): number;\r\n /**\r\n * Sets the minutes value in the Date object using local time.\r\n * @param min A numeric value equal to the minutes value.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setMinutes(min: number, sec?: number, ms?: number): number;\r\n /**\r\n * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).\r\n * @param min A numeric value equal to the minutes value.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setUTCMinutes(min: number, sec?: number, ms?: number): number;\r\n /**\r\n * Sets the hour value in the Date object using local time.\r\n * @param hours A numeric value equal to the hours value.\r\n * @param min A numeric value equal to the minutes value.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setHours(hours: number, min?: number, sec?: number, ms?: number): number;\r\n /**\r\n * Sets the hours value in the Date object using Universal Coordinated Time (UTC).\r\n * @param hours A numeric value equal to the hours value.\r\n * @param min A numeric value equal to the minutes value.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;\r\n /**\r\n * Sets the numeric day-of-the-month value of the Date object using local time.\r\n * @param date A numeric value equal to the day of the month.\r\n */\r\n setDate(date: number): number;\r\n /**\r\n * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).\r\n * @param date A numeric value equal to the day of the month.\r\n */\r\n setUTCDate(date: number): number;\r\n /**\r\n * Sets the month value in the Date object using local time.\r\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\r\n * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.\r\n */\r\n setMonth(month: number, date?: number): number;\r\n /**\r\n * Sets the month value in the Date object using Universal Coordinated Time (UTC).\r\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\r\n * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.\r\n */\r\n setUTCMonth(month: number, date?: number): number;\r\n /**\r\n * Sets the year of the Date object using local time.\r\n * @param year A numeric value for the year.\r\n * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.\r\n * @param date A numeric value equal for the day of the month.\r\n */\r\n setFullYear(year: number, month?: number, date?: number): number;\r\n /**\r\n * Sets the year value in the Date object using Universal Coordinated Time (UTC).\r\n * @param year A numeric value equal to the year.\r\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.\r\n * @param date A numeric value equal to the day of the month.\r\n */\r\n setUTCFullYear(year: number, month?: number, date?: number): number;\r\n /** Returns a date converted to a string using Universal Coordinated Time (UTC). */\r\n toUTCString(): string;\r\n /** Returns a date as a string value in ISO format. */\r\n toISOString(): string;\r\n /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */\r\n toJSON(key?: any): string;\r\n}\r\n\r\ninterface DateConstructor {\r\n new (): Date;\r\n new (value: number | string): Date;\r\n /**\r\n * Creates a new Date.\r\n * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.\r\n * @param monthIndex The month as a number between 0 and 11 (January to December).\r\n * @param date The date as a number between 1 and 31.\r\n * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour.\r\n * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes.\r\n * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds.\r\n * @param ms A number from 0 to 999 that specifies the milliseconds.\r\n */\r\n new (\r\n year: number,\r\n monthIndex: number,\r\n date?: number,\r\n hours?: number,\r\n minutes?: number,\r\n seconds?: number,\r\n ms?: number\r\n ): Date;\r\n (): string;\r\n readonly prototype: Date;\r\n /**\r\n * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.\r\n * @param s A date string\r\n */\r\n parse(s: string): number;\r\n /**\r\n * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.\r\n * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.\r\n * @param monthIndex The month as a number between 0 and 11 (January to December).\r\n * @param date The date as a number between 1 and 31.\r\n * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour.\r\n * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes.\r\n * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds.\r\n * @param ms A number from 0 to 999 that specifies the milliseconds.\r\n */\r\n UTC(\r\n year: number,\r\n monthIndex: number,\r\n date?: number,\r\n hours?: number,\r\n minutes?: number,\r\n seconds?: number,\r\n ms?: number\r\n ): number;\r\n /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC). */\r\n now(): number;\r\n}\r\n\r\ndeclare var Date: DateConstructor;\r\n\r\ninterface RegExpMatchArray extends Array {\r\n /**\r\n * The index of the search at which the result was found.\r\n */\r\n index?: number;\r\n /**\r\n * A copy of the search string.\r\n */\r\n input?: string;\r\n /**\r\n * The first match. This will always be present because `null` will be returned if there are no matches.\r\n */\r\n 0: string;\r\n}\r\n\r\ninterface RegExpExecArray extends Array {\r\n /**\r\n * The index of the search at which the result was found.\r\n */\r\n index: number;\r\n /**\r\n * A copy of the search string.\r\n */\r\n input: string;\r\n /**\r\n * The first match. This will always be present because `null` will be returned if there are no matches.\r\n */\r\n 0: string;\r\n}\r\n\r\ninterface RegExp {\r\n /**\r\n * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.\r\n * @param string The String object or string literal on which to perform the search.\r\n */\r\n exec(string: string): RegExpExecArray | null;\r\n\r\n /**\r\n * Returns a Boolean value that indicates whether or not a pattern exists in a searched string.\r\n * @param string String on which to perform the search.\r\n */\r\n test(string: string): boolean;\r\n\r\n /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */\r\n readonly source: string;\r\n\r\n /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */\r\n readonly global: boolean;\r\n\r\n /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */\r\n readonly ignoreCase: boolean;\r\n\r\n /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */\r\n readonly multiline: boolean;\r\n\r\n lastIndex: number;\r\n\r\n // Non-standard extensions\r\n /** @deprecated A legacy feature for browser compatibility */\r\n compile(pattern: string, flags?: string): this;\r\n}\r\n\r\ninterface RegExpConstructor {\r\n new (pattern: RegExp | string): RegExp;\r\n new (pattern: string, flags?: string): RegExp;\r\n (pattern: RegExp | string): RegExp;\r\n (pattern: string, flags?: string): RegExp;\r\n readonly prototype: RegExp;\r\n\r\n // Non-standard extensions\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $1: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $2: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $3: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $4: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $5: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $6: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $7: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $8: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $9: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n input: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $_: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n lastMatch: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n '$&': string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n lastParen: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n '$+': string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n leftContext: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n '$`': string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n rightContext: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n \"$'\": string;\r\n}\r\n\r\ndeclare var RegExp: RegExpConstructor;\r\n\r\ninterface Error {\r\n name: string;\r\n message: string;\r\n stack?: string;\r\n}\r\n\r\ninterface ErrorConstructor {\r\n new (message?: string): Error;\r\n (message?: string): Error;\r\n readonly prototype: Error;\r\n}\r\n\r\ndeclare var Error: ErrorConstructor;\r\n\r\ninterface EvalError extends Error {}\r\n\r\ninterface EvalErrorConstructor extends ErrorConstructor {\r\n new (message?: string): EvalError;\r\n (message?: string): EvalError;\r\n readonly prototype: EvalError;\r\n}\r\n\r\ndeclare var EvalError: EvalErrorConstructor;\r\n\r\ninterface RangeError extends Error {}\r\n\r\ninterface RangeErrorConstructor extends ErrorConstructor {\r\n new (message?: string): RangeError;\r\n (message?: string): RangeError;\r\n readonly prototype: RangeError;\r\n}\r\n\r\ndeclare var RangeError: RangeErrorConstructor;\r\n\r\ninterface ReferenceError extends Error {}\r\n\r\ninterface ReferenceErrorConstructor extends ErrorConstructor {\r\n new (message?: string): ReferenceError;\r\n (message?: string): ReferenceError;\r\n readonly prototype: ReferenceError;\r\n}\r\n\r\ndeclare var ReferenceError: ReferenceErrorConstructor;\r\n\r\ninterface SyntaxError extends Error {}\r\n\r\ninterface SyntaxErrorConstructor extends ErrorConstructor {\r\n new (message?: string): SyntaxError;\r\n (message?: string): SyntaxError;\r\n readonly prototype: SyntaxError;\r\n}\r\n\r\ndeclare var SyntaxError: SyntaxErrorConstructor;\r\n\r\ninterface TypeError extends Error {}\r\n\r\ninterface TypeErrorConstructor extends ErrorConstructor {\r\n new (message?: string): TypeError;\r\n (message?: string): TypeError;\r\n readonly prototype: TypeError;\r\n}\r\n\r\ndeclare var TypeError: TypeErrorConstructor;\r\n\r\ninterface URIError extends Error {}\r\n\r\ninterface URIErrorConstructor extends ErrorConstructor {\r\n new (message?: string): URIError;\r\n (message?: string): URIError;\r\n readonly prototype: URIError;\r\n}\r\n\r\ndeclare var URIError: URIErrorConstructor;\r\n\r\ninterface JSON {\r\n /**\r\n * Converts a JavaScript Object Notation (JSON) string into an object.\r\n * @param text A valid JSON string.\r\n * @param reviver A function that transforms the results. This function is called for each member of the object.\r\n * If a member contains nested objects, the nested objects are transformed before the parent object is.\r\n */\r\n parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;\r\n /**\r\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\r\n * @param value A JavaScript value, usually an object or array, to be converted.\r\n * @param replacer A function that transforms the results.\r\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\r\n */\r\n stringify(\r\n value: any,\r\n replacer?: (this: any, key: string, value: any) => any,\r\n space?: string | number\r\n ): string;\r\n /**\r\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\r\n * @param value A JavaScript value, usually an object or array, to be converted.\r\n * @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.\r\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\r\n */\r\n stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;\r\n}\r\n\r\n/**\r\n * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.\r\n */\r\ndeclare var JSON: JSON;\r\n\r\n/////////////////////////////\r\n/// ECMAScript Array API (specially handled by compiler)\r\n/////////////////////////////\r\n\r\ninterface ReadonlyArray {\r\n /**\r\n * Gets the length of the array. This is a number one higher than the highest element defined in an array.\r\n */\r\n readonly length: int;\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n /**\r\n * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.\r\n */\r\n toLocaleString(): string;\r\n /**\r\n * Combines two or more arrays.\r\n * @param items Additional items to add to the end of array1.\r\n */\r\n concat(...items: ConcatArray[]): T[];\r\n /**\r\n * Combines two or more arrays.\r\n * @param items Additional items to add to the end of array1.\r\n */\r\n concat(...items: (T | ConcatArray)[]): T[];\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): T[];\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\r\n */\r\n indexOf(searchElement: T, fromIndex?: number): number;\r\n /**\r\n * Returns the index of the last occurrence of a specified value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\r\n */\r\n lastIndexOf(searchElement: T, fromIndex?: number): number;\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: T, index: number, array: readonly T[]) => value is S,\r\n thisArg?: any\r\n ): this is readonly S[];\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: T, index: number, array: readonly T[]) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: T, index: number, array: readonly T[]) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void;\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[];\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: T, index: number, array: readonly T[]) => value is S,\r\n thisArg?: any\r\n ): S[];\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[];\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T\r\n ): T;\r\n reduce(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T,\r\n initialValue: T\r\n ): T;\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U,\r\n initialValue: U\r\n ): U;\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T\r\n ): T;\r\n reduceRight(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T,\r\n initialValue: T\r\n ): T;\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n readonly [n: number]: T;\r\n}\r\n\r\ninterface ConcatArray {\r\n readonly length: int;\r\n readonly [n: number]: T;\r\n join(separator?: string): string;\r\n slice(start?: number, end?: number): T[];\r\n}\r\n\r\ninterface Array {\r\n /**\r\n * Gets or sets the length of the array. This is a number one higher than the highest index in the array.\r\n */\r\n length: int;\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n /**\r\n * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.\r\n */\r\n toLocaleString(): string;\r\n /**\r\n * Removes the last element from an array and returns it.\r\n * If the array is empty, undefined is returned and the array is not modified.\r\n */\r\n pop(): T | undefined;\r\n /**\r\n * Appends new elements to the end of an array, and returns the new length of the array.\r\n * @param items New elements to add to the array.\r\n */\r\n push(...items: T[]): number;\r\n /**\r\n * Combines two or more arrays.\r\n * This method returns a new array without modifying any existing arrays.\r\n * @param items Additional arrays and/or items to add to the end of the array.\r\n */\r\n concat(...items: ConcatArray[]): T[];\r\n /**\r\n * Combines two or more arrays.\r\n * This method returns a new array without modifying any existing arrays.\r\n * @param items Additional arrays and/or items to add to the end of the array.\r\n */\r\n concat(...items: (T | ConcatArray)[]): T[];\r\n /**\r\n * Adds all the elements of an array into a string, separated by the specified separator string.\r\n * @param separator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n /**\r\n * Reverses the elements in an array in place.\r\n * This method mutates the array and returns a reference to the same array.\r\n */\r\n reverse(): T[];\r\n /**\r\n * Removes the first element from an array and returns it.\r\n * If the array is empty, undefined is returned and the array is not modified.\r\n */\r\n shift(): T | undefined;\r\n /**\r\n * Returns a copy of a section of an array.\r\n * For both start and end, a negative index can be used to indicate an offset from the end of the array.\r\n * For example, -2 refers to the second to last element of the array.\r\n * @param start The beginning index of the specified portion of the array.\r\n * If start is undefined, then the slice begins at index 0.\r\n * @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n * If end is undefined, then the slice extends to the end of the array.\r\n */\r\n slice(start?: number, end?: number): T[];\r\n /**\r\n * Sorts an array in place.\r\n * This method mutates the array and returns a reference to the same array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: T, b: T) => number): this;\r\n /**\r\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\r\n * @param start The zero-based location in the array from which to start removing elements.\r\n * @param deleteCount The number of elements to remove.\r\n * @returns An array containing the elements that were deleted.\r\n */\r\n splice(start: number, deleteCount?: number): T[];\r\n /**\r\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\r\n * @param start The zero-based location in the array from which to start removing elements.\r\n * @param deleteCount The number of elements to remove.\r\n * @param items Elements to insert into the array in place of the deleted elements.\r\n * @returns An array containing the elements that were deleted.\r\n */\r\n splice(start: number, deleteCount: number, ...items: T[]): T[];\r\n /**\r\n * Inserts new elements at the start of an array, and returns the new length of the array.\r\n * @param items Elements to insert at the start of the array.\r\n */\r\n unshift(...items: T[]): number;\r\n /**\r\n * Returns the index of the first occurrence of a value in an array, or -1 if it is not present.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\r\n */\r\n indexOf(searchElement: T, fromIndex?: number): number;\r\n /**\r\n * Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.\r\n */\r\n lastIndexOf(searchElement: T, fromIndex?: number): number;\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: T, index: number, array: T[]) => value is S,\r\n thisArg?: any\r\n ): this is S[];\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: T, index: number, array: T[]) => value is S,\r\n thisArg?: any\r\n ): S[];\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\r\n reduce(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T,\r\n initialValue: T\r\n ): T;\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U,\r\n initialValue: U\r\n ): U;\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T\r\n ): T;\r\n reduceRight(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T,\r\n initialValue: T\r\n ): T;\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n [n: number]: T;\r\n}\r\n\r\ninterface ArrayConstructor {\r\n new (arrayLength?: number): any[];\r\n new (arraylength: int): T[];\r\n new (...items: T[]): T[];\r\n (arrayLength?: number): any[];\r\n (arraylength: int): T[];\r\n (...items: T[]): T[];\r\n isArray(arg: any): arg is any[];\r\n readonly prototype: any[];\r\n}\r\n\r\ndeclare var Array: ArrayConstructor;\r\n\r\ninterface TypedPropertyDescriptor {\r\n enumerable?: boolean;\r\n configurable?: boolean;\r\n writable?: boolean;\r\n value?: T;\r\n get?: () => T;\r\n set?: (value: T) => void;\r\n}\r\n\r\ndeclare type PromiseConstructorLike = new (\r\n executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void\r\n) => PromiseLike;\r\n\r\ninterface PromiseLike {\r\n /**\r\n * Attaches callbacks for the resolution and/or rejection of the Promise.\r\n * @param onfulfilled The callback to execute when the Promise is resolved.\r\n * @param onrejected The callback to execute when the Promise is rejected.\r\n * @returns A Promise for the completion of which ever callback is executed.\r\n */\r\n then(\r\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null,\r\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null\r\n ): PromiseLike;\r\n}\r\n\r\n/**\r\n * Represents the completion of an asynchronous operation\r\n */\r\ninterface Promise {\r\n /**\r\n * Attaches callbacks for the resolution and/or rejection of the Promise.\r\n * @param onfulfilled The callback to execute when the Promise is resolved.\r\n * @param onrejected The callback to execute when the Promise is rejected.\r\n * @returns A Promise for the completion of which ever callback is executed.\r\n */\r\n then(\r\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null,\r\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null\r\n ): Promise;\r\n\r\n /**\r\n * Attaches a callback for only the rejection of the Promise.\r\n * @param onrejected The callback to execute when the Promise is rejected.\r\n * @returns A Promise for the completion of the callback.\r\n */\r\n catch(\r\n onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null\r\n ): Promise;\r\n}\r\n\r\n/**\r\n * Recursively unwraps the \"awaited type\" of a type. Non-promise \"thenables\" should resolve to `never`. This emulates the behavior of `await`.\r\n */\r\ntype Awaited = T extends null | undefined\r\n ? T // special case for `null | undefined` when not in `--strictNullChecks` mode\r\n : T extends object & { then(onfulfilled: infer F, ...args: infer _): any } // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped\r\n ? F extends (value: infer V, ...args: infer _) => any // if the argument to `then` is callable, extracts the first argument\r\n ? Awaited // recursively unwrap the value\r\n : never // the argument to `then` was not callable\r\n : T; // non-object or non-thenable\r\n\r\ninterface ArrayLike {\r\n readonly length: int;\r\n readonly [n: number]: T;\r\n}\r\n\r\n/**\r\n * Make all properties in T optional\r\n */\r\ntype Partial = {\r\n [P in keyof T]?: T[P];\r\n};\r\n\r\n/**\r\n * Make all properties in T required\r\n */\r\ntype Required = {\r\n [P in keyof T]-?: T[P];\r\n};\r\n\r\n/**\r\n * Make all properties in T readonly\r\n */\r\ntype Readonly = {\r\n readonly [P in keyof T]: T[P];\r\n};\r\n\r\n/**\r\n * From T, pick a set of properties whose keys are in the union K\r\n */\r\ntype Pick = {\r\n [P in K]: T[P];\r\n};\r\n\r\n/**\r\n * Construct a type with a set of properties K of type T\r\n */\r\ntype Record = {\r\n [P in K]: T;\r\n};\r\n\r\n/**\r\n * Exclude from T those types that are assignable to U\r\n */\r\ntype Exclude = T extends U ? never : T;\r\n\r\n/**\r\n * Extract from T those types that are assignable to U\r\n */\r\ntype Extract = T extends U ? T : never;\r\n\r\n/**\r\n * Construct a type with the properties of T except for those in type K.\r\n */\r\ntype Omit = Pick>;\r\n\r\n/**\r\n * Exclude null and undefined from T\r\n */\r\ntype NonNullable = T & {};\r\n\r\n/**\r\n * Obtain the parameters of a function type in a tuple\r\n */\r\ntype Parameters any> = T extends (...args: infer P) => any ? P : never;\r\n\r\n/**\r\n * Obtain the parameters of a constructor function type in a tuple\r\n */\r\ntype ConstructorParameters any> = T extends abstract new (\r\n ...args: infer P\r\n) => any\r\n ? P\r\n : never;\r\n\r\n/**\r\n * Obtain the return type of a function type\r\n */\r\ntype ReturnType any> = T extends (...args: any) => infer R ? R : any;\r\n\r\n/**\r\n * Obtain the return type of a constructor function type\r\n */\r\ntype InstanceType any> = T extends abstract new (\r\n ...args: any\r\n) => infer R\r\n ? R\r\n : any;\r\n\r\n/**\r\n * Convert string literal type to uppercase\r\n */\r\ntype Uppercase = intrinsic;\r\n\r\n/**\r\n * Convert string literal type to lowercase\r\n */\r\ntype Lowercase = intrinsic;\r\n\r\n/**\r\n * Convert first character of string literal type to uppercase\r\n */\r\ntype Capitalize = intrinsic;\r\n\r\n/**\r\n * Convert first character of string literal type to lowercase\r\n */\r\ntype Uncapitalize = intrinsic;\r\n\r\n/**\r\n * Marker for contextual 'this' type\r\n */\r\ninterface ThisType {}\r\n\r\n/**\r\n * Represents a raw buffer of binary data, which is used to store data for the\r\n * different typed arrays. ArrayBuffers cannot be read from or written to directly,\r\n * but can be passed to a typed array or DataView Object to interpret the raw\r\n * buffer as needed.\r\n */\r\ninterface ArrayBuffer {\r\n /**\r\n * Read-only. The length of the ArrayBuffer (in bytes).\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * Returns a section of an ArrayBuffer.\r\n */\r\n slice(begin: number, end?: number): ArrayBuffer;\r\n}\r\n\r\n/**\r\n * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.\r\n */\r\ninterface ArrayBufferTypes {\r\n ArrayBuffer: ArrayBuffer;\r\n}\r\ntype ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];\r\n\r\ninterface ArrayBufferConstructor {\r\n readonly prototype: ArrayBuffer;\r\n new (bytelength: int): ArrayBuffer;\r\n isView(arg: any): arg is ArrayBufferView;\r\n}\r\ndeclare var ArrayBuffer: ArrayBufferConstructor;\r\n\r\ninterface ArrayBufferView {\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n byteOffset: number;\r\n}\r\n\r\ninterface DataView {\r\n readonly buffer: ArrayBuffer;\r\n readonly bytelength: int;\r\n readonly byteOffset: number;\r\n /**\r\n * Gets the Float32 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getFloat32(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Gets the Float64 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getFloat64(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Gets the Int8 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n */\r\n getInt8(byteOffset: number): number;\r\n\r\n /**\r\n * Gets the Int16 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getInt16(byteOffset: number, littleEndian?: boolean): number;\r\n /**\r\n * Gets the Int32 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getInt32(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Gets the Uint8 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n */\r\n getUint8(byteOffset: number): number;\r\n\r\n /**\r\n * Gets the Uint16 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getUint16(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Gets the Uint32 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getUint32(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Stores an Float32 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Float64 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Int8 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n */\r\n setInt8(byteOffset: number, value: number): void;\r\n\r\n /**\r\n * Stores an Int16 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setInt16(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Int32 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setInt32(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Uint8 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n */\r\n setUint8(byteOffset: number, value: number): void;\r\n\r\n /**\r\n * Stores an Uint16 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setUint16(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Uint32 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setUint32(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n}\r\n\r\ninterface DataViewConstructor {\r\n readonly prototype: DataView;\r\n new (\r\n buffer: ArrayBufferLike & { BYTES_PER_ELEMENT?: never },\r\n byteOffset?: number,\r\n byteLength?: number\r\n ): DataView;\r\n}\r\ndeclare var DataView: DataViewConstructor;\r\n\r\n/**\r\n * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested\r\n * number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Int8Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Int8Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Int8Array) => any,\r\n thisArg?: any\r\n ): Int8Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Int8Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Int8Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Int8Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Int8Array) => number,\r\n thisArg?: any\r\n ): Int8Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Int8Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Int8Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Int8Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Int8Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Int8Array;\r\n\r\n [index: number]: number;\r\n}\r\ninterface Int8ArrayConstructor {\r\n readonly prototype: Int8Array;\r\n new (length: int): Int8Array;\r\n new (array: ArrayLike | ArrayBufferLike): Int8Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Int8Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Int8Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array;\r\n}\r\ndeclare var Int8Array: Int8ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Uint8Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Uint8Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Uint8Array) => any,\r\n thisArg?: any\r\n ): Uint8Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Uint8Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Uint8Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Uint8Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Uint8Array) => number,\r\n thisArg?: any\r\n ): Uint8Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Uint8Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Uint8Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Uint8Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Uint8Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Uint8Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Uint8ArrayConstructor {\r\n readonly prototype: Uint8Array;\r\n new (length: int): Uint8Array;\r\n new (array: ArrayLike | ArrayBufferLike): Uint8Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Uint8Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Uint8Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array;\r\n}\r\ndeclare var Uint8Array: Uint8ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.\r\n * If the requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Uint8ClampedArray {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Uint8ClampedArray) => any,\r\n thisArg?: any\r\n ): Uint8ClampedArray;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number,\r\n thisArg?: any\r\n ): Uint8ClampedArray;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Uint8ClampedArray;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Uint8ClampedArray;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Uint8ClampedArray;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Uint8ClampedArray;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Uint8ClampedArrayConstructor {\r\n readonly prototype: Uint8ClampedArray;\r\n new (length: int): Uint8ClampedArray;\r\n new (array: ArrayLike | ArrayBufferLike): Uint8ClampedArray;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Uint8ClampedArray;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Uint8ClampedArray;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(\r\n arrayLike: ArrayLike,\r\n mapfn: (v: T, k: number) => number,\r\n thisArg?: any\r\n ): Uint8ClampedArray;\r\n}\r\ndeclare var Uint8ClampedArray: Uint8ClampedArrayConstructor;\r\n\r\n/**\r\n * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Int16Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Int16Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Int16Array) => any,\r\n thisArg?: any\r\n ): Int16Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Int16Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Int16Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Int16Array) => void,\r\n thisArg?: any\r\n ): void;\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Int16Array) => number,\r\n thisArg?: any\r\n ): Int16Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Int16Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Int16Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Int16Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Int16Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Int16Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Int16ArrayConstructor {\r\n readonly prototype: Int16Array;\r\n new (length: int): Int16Array;\r\n new (array: ArrayLike | ArrayBufferLike): Int16Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Int16Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Int16Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array;\r\n}\r\ndeclare var Int16Array: Int16ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Uint16Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Uint16Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Uint16Array) => any,\r\n thisArg?: any\r\n ): Uint16Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Uint16Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Uint16Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Uint16Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Uint16Array) => number,\r\n thisArg?: any\r\n ): Uint16Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Uint16Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Uint16Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Uint16Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Uint16Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Uint16Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Uint16ArrayConstructor {\r\n readonly prototype: Uint16Array;\r\n new (length: int): Uint16Array;\r\n new (array: ArrayLike | ArrayBufferLike): Uint16Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Uint16Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Uint16Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array;\r\n}\r\ndeclare var Uint16Array: Uint16ArrayConstructor;\r\n/**\r\n * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Int32Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Int32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Int32Array) => any,\r\n thisArg?: any\r\n ): Int32Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Int32Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Int32Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Int32Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Int32Array) => number,\r\n thisArg?: any\r\n ): Int32Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Int32Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Int32Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Int32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Int32Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Int32Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Int32ArrayConstructor {\r\n readonly prototype: Int32Array;\r\n new (length: int): Int32Array;\r\n new (array: ArrayLike | ArrayBufferLike): Int32Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Int32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Int32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array;\r\n}\r\ndeclare var Int32Array: Int32ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Uint32Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Uint32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Uint32Array) => any,\r\n thisArg?: any\r\n ): Uint32Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Uint32Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Uint32Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Uint32Array) => void,\r\n thisArg?: any\r\n ): void;\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Uint32Array) => number,\r\n thisArg?: any\r\n ): Uint32Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Uint32Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Uint32Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Uint32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Uint32Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Uint32Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Uint32ArrayConstructor {\r\n readonly prototype: Uint32Array;\r\n new (length: int): Uint32Array;\r\n new (array: ArrayLike | ArrayBufferLike): Uint32Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Uint32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Uint32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array;\r\n}\r\ndeclare var Uint32Array: Uint32ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number\r\n * of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Float32Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Float32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Float32Array) => any,\r\n thisArg?: any\r\n ): Float32Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Float32Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Float32Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Float32Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Float32Array) => number,\r\n thisArg?: any\r\n ): Float32Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Float32Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Float32Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Float32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Float32Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Float32Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Float32ArrayConstructor {\r\n readonly prototype: Float32Array;\r\n new (length: int): Float32Array;\r\n new (array: ArrayLike | ArrayBufferLike): Float32Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Float32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Float32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array;\r\n}\r\ndeclare var Float32Array: Float32ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 64-bit float values. The contents are initialized to 0. If the requested\r\n * number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Float64Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Float64Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Float64Array) => any,\r\n thisArg?: any\r\n ): Float64Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Float64Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Float64Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Float64Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Float64Array) => number,\r\n thisArg?: any\r\n ): Float64Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Float64Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Float64Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Float64Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Float64Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Float64Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Float64ArrayConstructor {\r\n readonly prototype: Float64Array;\r\n new (length: int): Float64Array;\r\n new (array: ArrayLike | ArrayBufferLike): Float64Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Float64Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Float64Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array;\r\n}\r\ndeclare var Float64Array: Float64ArrayConstructor;\r\n\r\n/////////////////////////////\r\n/// ECMAScript Internationalization API\r\n/////////////////////////////\r\n\r\ndeclare namespace Intl {\r\n interface CollatorOptions {\r\n usage?: 'sort' | 'search' | undefined;\r\n localeMatcher?: 'lookup' | 'best fit' | undefined;\r\n numeric?: boolean | undefined;\r\n caseFirst?: 'upper' | 'lower' | 'false' | undefined;\r\n sensitivity?: 'base' | 'accent' | 'case' | 'variant' | undefined;\r\n collation?:\r\n | 'big5han'\r\n | 'compat'\r\n | 'dict'\r\n | 'direct'\r\n | 'ducet'\r\n | 'emoji'\r\n | 'eor'\r\n | 'gb2312'\r\n | 'phonebk'\r\n | 'phonetic'\r\n | 'pinyin'\r\n | 'reformed'\r\n | 'searchjl'\r\n | 'stroke'\r\n | 'trad'\r\n | 'unihan'\r\n | 'zhuyin'\r\n | undefined;\r\n ignorePunctuation?: boolean | undefined;\r\n }\r\n\r\n interface ResolvedCollatorOptions {\r\n locale: string;\r\n usage: string;\r\n sensitivity: string;\r\n ignorePunctuation: boolean;\r\n collation: string;\r\n caseFirst: string;\r\n numeric: boolean;\r\n }\r\n\r\n interface Collator {\r\n compare(x: string, y: string): number;\r\n resolvedOptions(): ResolvedCollatorOptions;\r\n }\r\n var Collator: {\r\n new (locales?: string | string[], options?: CollatorOptions): Collator;\r\n (locales?: string | string[], options?: CollatorOptions): Collator;\r\n supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[];\r\n };\r\n\r\n interface NumberFormatOptions {\r\n localeMatcher?: string | undefined;\r\n style?: string | undefined;\r\n currency?: string | undefined;\r\n currencySign?: string | undefined;\r\n useGrouping?: boolean | undefined;\r\n minimumIntegerDigits?: number | undefined;\r\n minimumFractionDigits?: number | undefined;\r\n maximumFractionDigits?: number | undefined;\r\n minimumSignificantDigits?: number | undefined;\r\n maximumSignificantDigits?: number | undefined;\r\n }\r\n\r\n interface ResolvedNumberFormatOptions {\r\n locale: string;\r\n numberingSystem: string;\r\n style: string;\r\n currency?: string;\r\n minimumIntegerDigits: number;\r\n minimumFractionDigits: number;\r\n maximumFractionDigits: number;\r\n minimumSignificantDigits?: number;\r\n maximumSignificantDigits?: number;\r\n useGrouping: boolean;\r\n }\r\n\r\n interface NumberFormat {\r\n format(value: number): string;\r\n resolvedOptions(): ResolvedNumberFormatOptions;\r\n }\r\n var NumberFormat: {\r\n new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\r\n (locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\r\n supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[];\r\n readonly prototype: NumberFormat;\r\n };\r\n\r\n interface DateTimeFormatOptions {\r\n localeMatcher?: 'best fit' | 'lookup' | undefined;\r\n weekday?: 'long' | 'short' | 'narrow' | undefined;\r\n era?: 'long' | 'short' | 'narrow' | undefined;\r\n year?: 'numeric' | '2-digit' | undefined;\r\n month?: 'numeric' | '2-digit' | 'long' | 'short' | 'narrow' | undefined;\r\n day?: 'numeric' | '2-digit' | undefined;\r\n hour?: 'numeric' | '2-digit' | undefined;\r\n minute?: 'numeric' | '2-digit' | undefined;\r\n second?: 'numeric' | '2-digit' | undefined;\r\n timeZoneName?:\r\n | 'short'\r\n | 'long'\r\n | 'shortOffset'\r\n | 'longOffset'\r\n | 'shortGeneric'\r\n | 'longGeneric'\r\n | undefined;\r\n formatMatcher?: 'best fit' | 'basic' | undefined;\r\n hour12?: boolean | undefined;\r\n timeZone?: string | undefined;\r\n }\r\n\r\n interface ResolvedDateTimeFormatOptions {\r\n locale: string;\r\n calendar: string;\r\n numberingSystem: string;\r\n timeZone: string;\r\n hour12?: boolean;\r\n weekday?: string;\r\n era?: string;\r\n year?: string;\r\n month?: string;\r\n day?: string;\r\n hour?: string;\r\n minute?: string;\r\n second?: string;\r\n timeZoneName?: string;\r\n }\r\n\r\n interface DateTimeFormat {\r\n format(date?: Date | number): string;\r\n resolvedOptions(): ResolvedDateTimeFormatOptions;\r\n }\r\n var DateTimeFormat: {\r\n new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\r\n (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\r\n supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[];\r\n readonly prototype: DateTimeFormat;\r\n };\r\n}\r\n\r\ninterface String {\r\n /**\r\n * Determines whether two strings are equivalent in the current or specified locale.\r\n * @param that String to compare to target string\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.\r\n * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.\r\n */\r\n localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number;\r\n}\r\n\r\ninterface Number {\r\n /**\r\n * Converts a number to a string by using the current or specified locale.\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\r\n * @param options An object that contains one or more properties that specify comparison options.\r\n */\r\n toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;\r\n}\r\n\r\ninterface Date {\r\n /**\r\n * Converts a date and time to a string by using the current or specified locale.\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\r\n * @param options An object that contains one or more properties that specify comparison options.\r\n */\r\n toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\r\n /**\r\n * Converts a date to a string by using the current or specified locale.\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\r\n * @param options An object that contains one or more properties that specify comparison options.\r\n */\r\n toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\r\n\r\n /**\r\n * Converts a time to a string by using the current or specified locale.\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\r\n * @param options An object that contains one or more properties that specify comparison options.\r\n */\r\n toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\r\n}\r\n"; const simpleFunctions = [ ["add", "+"], ["sub", "-"], ["div", "/"], ["mul", "*"], ["mod", "%"], ["bitand", "&"], ["bitor", "|"], ["bitxor", "^"], ["lshift", "<<"], ["rshift", ">>"] ]; const singleFunctions = [ ["bitnot", (a) => `~${a}`], ["negate", (a) => `-${a}`], ["positive", "Math.abs"], ["abs", "Math.abs"], ["floor", "Math.floor"], ["ceil", "Math.ceil"], ["round", "Math.round"], ["sign", "Math.sign"], ["cos", "Math.cos"], ["sin", "Math.sin"], ["tan", "Math.tan"], ["acos", "Math.acos"], ["asin", "Math.asin"], ["atan", "Math.atan"], ["cosh", "Math.cosh"], ["sinh", "Math.sinh"], ["tanh", "Math.tanh"], ["acosh", "Math.acosh"], ["asinh", "Math.asinh"], ["atanh", "Math.atanh"], ["exp", "Math.exp"], ["log", "Math.log"], ["log2", "Math.log2"], ["log10", "Math.log10"], ["sqrt", "Math.sqrt"] ]; const makeVectors = [ ["int", "|0"], ["float", ""], ["uint", ">>>0"] ]; const simpleFuncMap = new Map(simpleFunctions); const singleFuncMap = new Map(singleFunctions); const makeVectorsMap = new Map(makeVectors); function getTypeFallback(checker, t) { let n = (t.aliasSymbol || t.getSymbol())?.escapedName; if (!n && t.intrinsicName) n = t.intrinsicName; if (typeof n !== "string") { let props = t.getApparentProperties(); if (props.length > 0) { for (let p of props) { if (p.escapedName.toString() === "_opaque_int") return "int"; if (p.escapedName.toString() === "_opaque_float") return "float"; if (p.escapedName.toString() === "_opaque_uint") return "uint"; } } let btype = t.getBaseTypes(); if (btype && btype.length > 0) { for (let b of btype) { let tn = getTypeFallback(checker, b); if (tn) return tn; } return null; } } else { return n; } } function getVectorLen(checker, type2) { let typeFall = getTypeFallback(checker, type2); if (type2.flags & (ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike | ts.TypeFlags.NumberLiteral) || typeFall == "int" || typeFall == "float" || typeFall == "uint") { return 1; } else if (typeFall == "int2" || typeFall == "float2" || typeFall == "uint2") { return 2; } else if (typeFall == "int3" || typeFall == "float3" || typeFall == "uint3") { return 3; } else if (typeFall == "int4" || typeFall == "float4" || typeFall == "uint4") { return 4; } return 0; } function isArrayType(type2, checker) { return checker.isTupleType(type2) || checker.isArrayType(type2); } const updateIntegerMixing = (getChecker) => (context2) => { let [checker, env2, loads] = getChecker(); loads.clear(); env2.libraries.clear(); return (rootNode) => { const { factory: factory2 } = context2; function visit(node2) { if (!node2) { return node2; } if (ts.isCallExpression(node2)) { let sig = checker.getResolvedSignature(node2); let returnType = checker.getReturnTypeOfSignature(sig); let symbol = returnType.aliasSymbol || returnType.getSymbol(); let expressionText = node2.expression.getText(); let ops = { gte: ts.SyntaxKind.GreaterThanEqualsToken, lte: ts.SyntaxKind.LessThanEqualsToken, gt: ts.SyntaxKind.GreaterThanToken, lt: ts.SyntaxKind.LessThanToken, eq: ts.SyntaxKind.EqualsEqualsToken, neq: ts.SyntaxKind.ExclamationEqualsToken, and: ts.SyntaxKind.AmpersandAmpersandToken, or: ts.SyntaxKind.BarBarToken }; if (expressionText == "physics.engine2d") { env2.libraries.add("rapier2d"); } if (expressionText == "physics.engine3d") { env2.libraries.add("rapier3d"); } if (expressionText == "load") { if (!loads.has(rootNode.fileName)) { loads.set(rootNode.fileName, []); } if (node2.arguments.length > 0 && ts.isStringLiteral(node2.arguments[0])) { let realId = env2.assetMappings.get(node2.arguments[0].text); loads.get(rootNode.fileName).push(node2.arguments[0].text); if (realId) return factory2.createCallExpression(factory2.createIdentifier("load"), void 0, [ factory2.createStringLiteral(realId[0]) ]); } return node2; } if (expressionText.endsWith("__index")) { let innerExpr = node2.expression; if (ts.isPropertyAccessExpression(innerExpr)) { let left = innerExpr.expression; let leftType = checker.getTypeAtLocation(left); let leftStr = checker.typeToString(leftType); if (isArrayType(leftType, checker)) { return factory2.createElementAccessExpression(visit(left), visit(node2.arguments[0])); } if (leftStr == "buffer") { return factory2.createElementAccessExpression( factory2.createPropertyAccessExpression(visit(left), "floatArray"), visit(node2.arguments[0]) ); } else if (leftStr == "buffer") { return factory2.createElementAccessExpression( factory2.createPropertyAccessExpression(visit(left), "intArray"), visit(node2.arguments[0]) ); } else if (leftStr == "buffer") { return factory2.createElementAccessExpression( factory2.createPropertyAccessExpression(visit(left), "uintArray"), visit(node2.arguments[0]) ); } else if (!leftType.getProperty("__index")) { console.log("Optim no __index", leftStr, leftType); return factory2.createElementAccessExpression(visit(left), visit(node2.arguments[0])); } } } if (expressionText.startsWith("__.") && ops[expressionText.replace("__.", "")]) { if (node2.arguments.length != 2) { return visit(node2.arguments[0]); } else { let left = node2.arguments[0]; let right = node2.arguments[1]; let leftLen = getVectorLen(checker, checker.getTypeAtLocation(left)); let rightLen = getVectorLen(checker, checker.getTypeAtLocation(right)); if (leftLen == 1 && rightLen == 1) { return factory2.createBinaryExpression( visit(node2.arguments[0]), ops[expressionText.replace("__.", "")], visit(node2.arguments[1]) ); } } } if (simpleFuncMap.has(expressionText.replace("__.", ""))) { let left = node2.arguments[0]; let right = node2.arguments[1]; let leftLen = getVectorLen(checker, checker.getTypeAtLocation(left)); let rightLen = getVectorLen(checker, checker.getTypeAtLocation(right)); if (leftLen == 1 && rightLen == 1) { let funcDef = simpleFuncMap.get(expressionText.replace("__.", "")); if (typeof funcDef == "string") { let tokenKinds = { "+": ts.SyntaxKind.PlusToken, "-": ts.SyntaxKind.MinusToken, "/": ts.SyntaxKind.SlashToken, "*": ts.SyntaxKind.AsteriskToken, "%": ts.SyntaxKind.PercentToken, "&": ts.SyntaxKind.AmpersandToken, "|": ts.SyntaxKind.BarToken, "^": ts.SyntaxKind.CaretToken, "<<": ts.SyntaxKind.LessThanLessThanToken, ">>": ts.SyntaxKind.GreaterThanGreaterThanToken }; return factory2.createBinaryExpression( visit(left), factory2.createToken(tokenKinds[funcDef]), visit(right) ); } } if (leftLen > 0 && rightLen > 0) { let leftHoist = factory2.createTempVariable(context2.hoistVariableDeclaration, true); let rightHoist = factory2.createTempVariable(context2.hoistVariableDeclaration, true); let leftAss = factory2.createAssignment(leftHoist, visit(left)); let rightAss = factory2.createAssignment(rightHoist, visit(right)); let tokenKinds = { mul: ts.SyntaxKind.AsteriskToken, div: ts.SyntaxKind.SlashToken, add: ts.SyntaxKind.PlusToken, sub: ts.SyntaxKind.MinusToken, mod: ts.SyntaxKind.PercentToken, and: ts.SyntaxKind.AmpersandToken, or: ts.SyntaxKind.BarToken, xor: ts.SyntaxKind.CaretToken, lshift: ts.SyntaxKind.LessThanLessThanToken, rshift: ts.SyntaxKind.GreaterThanGreaterThanToken }; let innerElems = []; if (leftLen == rightLen) { for (let i = 0; i < leftLen; i++) { innerElems.push( factory2.createBinaryExpression( factory2.createElementAccessExpression( leftHoist, factory2.createNumericLiteral(i) ), factory2.createToken(tokenKinds[expressionText.replace("__.", "")]), factory2.createElementAccessExpression( rightHoist, factory2.createNumericLiteral(i) ) ) ); } } else if (leftLen == 1) { for (let i = 0; i < rightLen; i++) { innerElems.push( factory2.createBinaryExpression( leftHoist, factory2.createToken(tokenKinds[expressionText.replace("__.", "")]), factory2.createElementAccessExpression( rightHoist, factory2.createNumericLiteral(i) ) ) ); } } else if (rightLen == 1) { for (let i = 0; i < leftLen; i++) { innerElems.push( factory2.createBinaryExpression( factory2.createElementAccessExpression( leftHoist, factory2.createNumericLiteral(i) ), factory2.createToken(tokenKinds[expressionText.replace("__.", "")]), rightHoist ) ); } } let expr = factory2.createArrayLiteralExpression(innerElems); return factory2.createCommaListExpression([leftAss, rightAss, expr]); } } if (singleFuncMap.has(expressionText.replace("__.", ""))) { let left = node2.arguments[0]; let leftLen = getVectorLen(checker, checker.getTypeAtLocation(left)); let funcDef = singleFuncMap.get(expressionText.replace("__.", "")); if (leftLen == 1) { if (typeof funcDef == "string") { return factory2.createCallExpression( factory2.createIdentifier(funcDef), [], [visit(left)] ); } } if (leftLen > 0) { if (typeof funcDef == "string") { let leftHoist = factory2.createTempVariable(context2.hoistVariableDeclaration, true); let leftAss = factory2.createAssignment(leftHoist, visit(left)); let innerElems = []; for (let i = 0; i < leftLen; i++) { innerElems.push( factory2.createCallExpression( factory2.createIdentifier(funcDef), [], [ factory2.createElementAccessExpression( leftHoist, factory2.createNumericLiteral(i) ) ] ) ); } let expr = factory2.createArrayLiteralExpression(innerElems); return factory2.createCommaListExpression([leftAss, expr]); } else { return factory2.createParenthesizedExpression( factory2.createCallExpression( factory2.createPropertyAccessExpression( factory2.createPropertyAccessExpression( factory2.createIdentifier("__"), factory2.createIdentifier("FM") ), factory2.createIdentifier(expressionText.replace("__.", "") + `_${leftLen}`) ), [], [visit(left)] ) ); } } } if (expressionText == "__.swizzle" && node2.arguments.length == 2) { let index = { x: 0, y: 1, z: 2, w: 3, r: 0, g: 1, b: 2, a: 3 }; let vecLen = getVectorLen(checker, checker.getTypeAtLocation(node2.arguments[0])); if (vecLen != 0) { let swizzleLiteral = node2.arguments[1]; let swiz = ""; if (ts.isStringLiteral(swizzleLiteral)) { swiz = swizzleLiteral.text; } if (swiz.length == 1) { return factory2.createElementAccessExpression( visit(node2.arguments[0]), factory2.createNumericLiteral(index[swiz]) ); } let temp = factory2.createTempVariable(context2.hoistVariableDeclaration, true); let tempAss = factory2.createAssignment(temp, visit(node2.arguments[0])); let elems = []; for (let i = 0; i < swiz.length; i++) { if (vecLen == 1) { elems.push(temp); } else { elems.push( factory2.createElementAccessExpression( temp, factory2.createNumericLiteral(index[swiz[i]]) ) ); } } return factory2.createCommaListExpression([ tempAss, factory2.createArrayLiteralExpression(elems) ]); } } if (expressionText.startsWith("__.") && makeVectorsMap.has(expressionText.replace("__.", "").replace(/\d/g, ""))) { let arg_lengths = node2.arguments.map( (x) => getVectorLen(checker, checker.getTypeAtLocation(x)) ); let matches = expressionText.match(/\d/g); if (matches) { let targetLen = matches[0]; let targetName = expressionText.replace("__.", "").replace(/\d/g, ""); return factory2.createCallExpression( factory2.createPropertyAccessExpression( factory2.createPropertyAccessExpression( factory2.createIdentifier("__"), factory2.createIdentifier("FM") ), factory2.createIdentifier(targetName + `_${targetLen}_${arg_lengths.join("_")}`) ), [], node2.arguments.map((x) => ts.visitEachChild(x, visit, context2)) ); } else { if (expressionText == "__.float") { return ts.visitEachChild(node2.arguments[0], visit, context2); } else if (expressionText == "__.int") { return factory2.createParenthesizedExpression( factory2.createBinaryExpression( ts.visitEachChild(node2.arguments[0], visit, context2), factory2.createToken(ts.SyntaxKind.BarToken), factory2.createNumericLiteral("0") ) ); } else if (expressionText == "__.uint") { return factory2.createParenthesizedExpression( factory2.createBinaryExpression( ts.visitEachChild(node2.arguments[0], visit, context2), factory2.createToken(ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken), factory2.createNumericLiteral("0") ) ); } } } if (symbol && symbol.name == "int") { return factory2.createParenthesizedExpression( factory2.createBinaryExpression( ts.visitEachChild(node2, visit, context2), factory2.createToken(ts.SyntaxKind.BarToken), factory2.createNumericLiteral("0") ) ); } else if (symbol && (symbol.name == "int2" || symbol.name == "int3" || symbol.name == "int4")) { return factory2.createCallExpression( factory2.createPropertyAccessExpression( factory2.createIdentifier("__"), factory2.createIdentifier("intifyVector") ), [], [ts.visitEachChild(node2, visit, context2)] ); } } return ts.visitEachChild(node2, visit, context2); } rootNode = ts.visitNode(rootNode, visit); return rootNode; }; }; const updateClassStructure = (getChecker) => (context2) => { let checker = getChecker(); return (rootNode) => { const { factory: factory2 } = context2; function visit(node2) { if (ts.isClassDeclaration(node2)) { return [ factory2.updateClassDeclaration( node2, node2.modifiers, node2.name, node2.typeParameters, node2.heritageClauses, [ ...node2.members.map((m) => ts.visitEachChild(m, visit, context2)), factory2.createMethodDeclaration( void 0, void 0, factory2.createIdentifier("_getStructure"), void 0, void 0, [], void 0, factory2.createBlock( [ factory2.createReturnStatement( factory2.createCallExpression( factory2.createPropertyAccessExpression( factory2.createIdentifier("JSON"), "parse" ), void 0, [ factory2.createStringLiteral( JSON.stringify( translateType(checker, checker.getTypeAtLocation(node2), true) ) ) ] ) ) ], true ) ) ] ), factory2.createCallExpression( factory2.createIdentifier("__shadeup_register_struct"), void 0, [ factory2.createCallExpression( factory2.createPropertyAccessExpression(factory2.createIdentifier("JSON"), "parse"), void 0, [ factory2.createStringLiteral( JSON.stringify(translateType(checker, checker.getTypeAtLocation(node2), true)) ) ] ), factory2.createIdentifier(node2.name.text) ] ) ]; } else if (ts.isCallExpression(node2)) { let symbol = checker.getSymbolAtLocation(node2.expression); if (symbol && symbol.name == "buffer") { let isInScope = false; let sym = checker.getTypeAtLocation(node2.typeArguments[0]).getSymbol(); if (sym) { let syms = checker.getSymbolsInScope( node2, ts.SymbolFlags.Alias | ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Type ); for (let s of syms) { if (s == sym) { isInScope = true; break; } } } return factory2.updateCallExpression(node2, node2.expression, node2.typeArguments, [ ...node2.arguments, factory2.createObjectLiteralExpression([ factory2.createSpreadAssignment( factory2.createCallExpression( factory2.createPropertyAccessExpression(factory2.createIdentifier("JSON"), "parse"), void 0, [ factory2.createStringLiteral( JSON.stringify( translateType( checker, checker.getTypeAtLocation(node2.typeArguments[0]), true ) ) ) ] ) ), ...isInScope ? [ factory2.createPropertyAssignment( "__type", factory2.createIdentifier( checker.getTypeAtLocation(node2.typeArguments[0]).getSymbol().getName() ) ) ] : [] ]) ]); } } return ts.visitEachChild(node2, visit, context2); } return ts.visitNode(rootNode, visit); }; }; const updateAsyncCalls = (getChecker) => (context2) => { let [checker, env2] = getChecker(); return (rootNode) => { const { factory: factory2 } = context2; function visit(node2) { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let graphNodeName = getFunctionNodeName(funcDeclar); let graphNode = env2.tagGraph.getNode(graphNodeName); if (graphNode) { if (!isInShader$1(node2) && !isInRoot(node2)) { if (graphNode.tags.includes("async")) { return factory2.createAwaitExpression(ts.visitEachChild(node2, visit, context2)); } } } } } if (node2.expression && ts.isIdentifier(node2.expression) && node2.expression.text.startsWith("shader_start_shd_")) { let inner = node2.arguments[0]; if (ts.isAsExpression(inner)) { inner = inner.expression; } if (ts.isCallExpression(inner) && inner.arguments[0]) { let shaderKey = inner.arguments[0]; if (ts.isStringLiteral(shaderKey)) { let key = shaderKey.text; let file = env2.files.find((x) => x.path == rootNode.fileName); let shader = file.shaders.find((x) => x.glsl.key == "shd_" + key); if (shader) { let params = []; for (let param of Object.keys(shader.glsl.locals)) { shader.glsl.locals[param]; let symbols = checker.getSymbolsInScope(node2, ts.SymbolFlags.Variable); let symbol = symbols.find((x) => x.name == param); let findInside = (node22) => { if (ts.isIdentifier(node22) && checker.getSymbolAtLocation(node22) == symbol) { return node22; } return ts.forEachChild(node22, findInside); }; let found = findInside(inner.arguments[1]); if (found) { params.push([`_ext_uniform_local_${param}`, found]); } else { params.push([`_ext_uniform_local_${param}`, factory2.createIdentifier(param)]); } } for (let param of Object.keys(shader.glsl.globals)) { let u = shader.glsl.globals[param]; params.push([ `_ext_uniform_global_${param}`, factory2.createCallExpression( factory2.createIdentifier("globalVarGet"), void 0, [ factory2.createStringLiteral(cleanName(u.fileName)), factory2.createStringLiteral(param) ] ) ]); } let innerArg = inner.arguments[1]; if (ts.isAsExpression(innerArg)) { innerArg = innerArg.expression; } if (ts.isParenthesizedExpression(innerArg)) { innerArg = innerArg.expression; } if (!ts.isArrowFunction(innerArg)) { throw new Error("Expected arrow function"); } let arrow = innerArg; let mods = ts.getModifiers(arrow) || []; return factory2.createCallExpression( factory2.createIdentifier("__shadeup_make_shader_inst"), [], [ ...[ factory2.createStringLiteral(shader.glsl.key), factory2.createObjectLiteralExpression( params.map(([name, value]) => factory2.createPropertyAssignment(name, value)) ), factory2.updateArrowFunction( arrow, [...mods, factory2.createModifier(ts.SyntaxKind.AsyncKeyword)], arrow.typeParameters, arrow.parameters, arrow.type, arrow.equalsGreaterThanToken, arrow.body ) ], ...inner.arguments.length == 3 ? [inner.arguments[2]] : [] ] ); } } } } } if (ts.isFunctionDeclaration(node2)) { let graphNodeName = getFunctionNodeName(node2, rootNode); let graphNode = env2.tagGraph.getNode(graphNodeName); if (graphNode) { if (graphNode.tags.includes("async")) { let mods = ts.getModifiers(node2) || []; return factory2.updateFunctionDeclaration( node2, [...mods, factory2.createModifier(ts.SyntaxKind.AsyncKeyword)], node2.asteriskToken, node2.name, node2.typeParameters, node2.parameters, node2.type, ts.visitEachChild(node2.body, visit, context2) ); } } } if (ts.isClassDeclaration(node2)) { ts.forEachChild(node2, (n) => { if (ts.isMethodDeclaration(n)) { let graphNodeName = getFunctionNodeName(n, rootNode); let graphNode = env2.tagGraph.getNode(graphNodeName); if (graphNode) { if (graphNode.tags.includes("async")) { let mods = ts.getModifiers(node2) || []; return factory2.updateMethodDeclaration( n, [...mods, factory2.createModifier(ts.SyntaxKind.AsyncKeyword)], n.asteriskToken, n.name, n.questionToken, n.typeParameters, n.parameters, n.type, ts.visitEachChild(n.body, visit, context2) ); } } } }); } return ts.visitEachChild(node2, visit, context2); } return ts.visitNode(rootNode, visit); }; }; async function makeTypescriptEnvironment(shadeupEnv) { const shouldCache = false; let fsMap = await createDefaultMapFromCDN( { target: ts.ScriptTarget.ES2015, lib: ["es5", "es2015", "es2015.promise"] }, "3.7.3", shouldCache, ts ); fsMap = /* @__PURE__ */ new Map(); fsMap.set("/file.ts", ""); fsMap.set("/std_math.ts", stdMath); fsMap.set("/static-math.ts", stdStaticMath); fsMap.set("/std___std_all.ts", stdAll); fsMap.set("/global.d.ts", globalDTS); const system = createSystem(fsMap); system.$fsMap = fsMap; system.writeFile("/std___std_all.ts", stdAll); system.writeFile("/std_math.ts", stdMath); system.writeFile("/static-math.ts", stdStaticMath); system.writeFile("/global.d.ts", globalDTS); const compilerOpts = { module: ts.ModuleKind.AMD, removeComments: false, lib: ["es5"], //noImplicitUseStrict: true, alwaysStrict: true, strictNullChecks: true, strictFunctionTypes: true, strictBindCallApply: true, strictPropertyInitialization: true, noImplicitThis: true, strict: true, noImplicitAny: true, noImplicitReturns: true, declaration: shadeupEnv.options?.declaration ?? false }; if (shadeupEnv.options.esnext) ; let transformers = { before: [ updateIntegerMixing(() => [ env2.languageService.getProgram().getTypeChecker(), shadeupEnv, shadeupEnv.loads ]), updateAsyncCalls(() => [env2.languageService.getProgram().getTypeChecker(), shadeupEnv]), // updateAsyncArrows(() => [env.languageService.getProgram().getTypeChecker(), shadeupEnv]), updateClassStructure(() => env2.languageService.getProgram().getTypeChecker()) ] }; const env2 = createVirtualTypeScriptEnvironment( system, Object.keys(fsMap), ts, compilerOpts, transformers ); env2.createFile("/std___std_all.ts", stdAll); env2.createFile("/std_math.ts", stdMath); env2.createFile("/static-math.ts", stdStaticMath); env2.createFile("/global.d.ts", globalDTS); return { env: env2, fsMap, system }; } var DIFF_DELETE = -1; var DIFF_INSERT = 1; var DIFF_EQUAL = 0; function diff_main(text1, text2, cursor_pos, _fix_unicode) { if (text1 === text2) { if (text1) { return [[DIFF_EQUAL, text1]]; } return []; } if (cursor_pos != null) { var editdiff = find_cursor_edit_diff(text1, text2, cursor_pos); if (editdiff) { return editdiff; } } var commonlength = diff_commonPrefix(text1, text2); var commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); commonlength = diff_commonSuffix(text1, text2); var commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text2 = text2.substring(0, text2.length - commonlength); var diffs = diff_compute_(text1, text2); if (commonprefix) { diffs.unshift([DIFF_EQUAL, commonprefix]); } if (commonsuffix) { diffs.push([DIFF_EQUAL, commonsuffix]); } diff_cleanupMerge(diffs, _fix_unicode); return diffs; } function diff_compute_(text1, text2) { var diffs; if (!text1) { return [[DIFF_INSERT, text2]]; } if (!text2) { return [[DIFF_DELETE, text1]]; } var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; var i = longtext.indexOf(shorttext); if (i !== -1) { diffs = [ [DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)] ]; if (text1.length > text2.length) { diffs[0][0] = diffs[2][0] = DIFF_DELETE; } return diffs; } if (shorttext.length === 1) { return [ [DIFF_DELETE, text1], [DIFF_INSERT, text2] ]; } var hm = diff_halfMatch_(text1, text2); if (hm) { var text1_a = hm[0]; var text1_b = hm[1]; var text2_a = hm[2]; var text2_b = hm[3]; var mid_common = hm[4]; var diffs_a = diff_main(text1_a, text2_a); var diffs_b = diff_main(text1_b, text2_b); return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); } return diff_bisect_(text1, text2); } function diff_bisect_(text1, text2) { var text1_length = text1.length; var text2_length = text2.length; var max_d = Math.ceil((text1_length + text2_length) / 2); var v_offset = max_d; var v_length = 2 * max_d; var v1 = new Array(v_length); var v2 = new Array(v_length); for (var x = 0; x < v_length; x++) { v1[x] = -1; v2[x] = -1; } v1[v_offset + 1] = 0; v2[v_offset + 1] = 0; var delta = text1_length - text2_length; var front = delta % 2 !== 0; var k1start = 0; var k1end = 0; var k2start = 0; var k2end = 0; for (var d = 0; d < max_d; d++) { for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { var k1_offset = v_offset + k1; var x1; if (k1 === -d || k1 !== d && v1[k1_offset - 1] < v1[k1_offset + 1]) { x1 = v1[k1_offset + 1]; } else { x1 = v1[k1_offset - 1] + 1; } var y1 = x1 - k1; while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) === text2.charAt(y1)) { x1++; y1++; } v1[k1_offset] = x1; if (x1 > text1_length) { k1end += 2; } else if (y1 > text2_length) { k1start += 2; } else if (front) { var k2_offset = v_offset + delta - k1; if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) { var x2 = text1_length - v2[k2_offset]; if (x1 >= x2) { return diff_bisectSplit_(text1, text2, x1, y1); } } } } for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { var k2_offset = v_offset + k2; var x2; if (k2 === -d || k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1]) { x2 = v2[k2_offset + 1]; } else { x2 = v2[k2_offset - 1] + 1; } var y2 = x2 - k2; while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) === text2.charAt(text2_length - y2 - 1)) { x2++; y2++; } v2[k2_offset] = x2; if (x2 > text1_length) { k2end += 2; } else if (y2 > text2_length) { k2start += 2; } else if (!front) { var k1_offset = v_offset + delta - k2; if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] !== -1) { var x1 = v1[k1_offset]; var y1 = v_offset + x1 - k1_offset; x2 = text1_length - x2; if (x1 >= x2) { return diff_bisectSplit_(text1, text2, x1, y1); } } } } } return [ [DIFF_DELETE, text1], [DIFF_INSERT, text2] ]; } function diff_bisectSplit_(text1, text2, x, y) { var text1a = text1.substring(0, x); var text2a = text2.substring(0, y); var text1b = text1.substring(x); var text2b = text2.substring(y); var diffs = diff_main(text1a, text2a); var diffsb = diff_main(text1b, text2b); return diffs.concat(diffsb); } function diff_commonPrefix(text1, text2) { if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { return 0; } var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } if (is_surrogate_pair_start(text1.charCodeAt(pointermid - 1))) { pointermid--; } return pointermid; } function diff_commonSuffix(text1, text2) { if (!text1 || !text2 || text1.slice(-1) !== text2.slice(-1)) { return 0; } var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } if (is_surrogate_pair_end(text1.charCodeAt(text1.length - pointermid))) { pointermid--; } return pointermid; } function diff_halfMatch_(text1, text2) { var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; } function diff_halfMatchI_(longtext2, shorttext2, i) { var seed = longtext2.substring(i, i + Math.floor(longtext2.length / 4)); var j = -1; var best_common = ""; var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; while ((j = shorttext2.indexOf(seed, j + 1)) !== -1) { var prefixLength = diff_commonPrefix(longtext2.substring(i), shorttext2.substring(j)); var suffixLength = diff_commonSuffix(longtext2.substring(0, i), shorttext2.substring(0, j)); if (best_common.length < suffixLength + prefixLength) { best_common = shorttext2.substring(j - suffixLength, j) + shorttext2.substring(j, j + prefixLength); best_longtext_a = longtext2.substring(0, i - suffixLength); best_longtext_b = longtext2.substring(i + prefixLength); best_shorttext_a = shorttext2.substring(0, j - suffixLength); best_shorttext_b = shorttext2.substring(j + prefixLength); } } if (best_common.length * 2 >= longtext2.length) { return [best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common]; } else { return null; } } var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); var hm; if (!hm1 && !hm2) { return null; } else if (!hm2) { hm = hm1; } else if (!hm1) { hm = hm2; } else { hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } var text1_a, text1_b, text2_a, text2_b; if (text1.length > text2.length) { text1_a = hm[0]; text1_b = hm[1]; text2_a = hm[2]; text2_b = hm[3]; } else { text2_a = hm[0]; text2_b = hm[1]; text1_a = hm[2]; text1_b = hm[3]; } var mid_common = hm[4]; return [text1_a, text1_b, text2_a, text2_b, mid_common]; } function diff_cleanupMerge(diffs, fix_unicode) { diffs.push([DIFF_EQUAL, ""]); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ""; var text_insert = ""; var commonlength; while (pointer < diffs.length) { if (pointer < diffs.length - 1 && !diffs[pointer][1]) { diffs.splice(pointer, 1); continue; } switch (diffs[pointer][0]) { case DIFF_INSERT: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: var previous_equality = pointer - count_insert - count_delete - 1; if (fix_unicode) { if (previous_equality >= 0 && ends_with_pair_start(diffs[previous_equality][1])) { var stray = diffs[previous_equality][1].slice(-1); diffs[previous_equality][1] = diffs[previous_equality][1].slice(0, -1); text_delete = stray + text_delete; text_insert = stray + text_insert; if (!diffs[previous_equality][1]) { diffs.splice(previous_equality, 1); pointer--; var k = previous_equality - 1; if (diffs[k] && diffs[k][0] === DIFF_INSERT) { count_insert++; text_insert = diffs[k][1] + text_insert; k--; } if (diffs[k] && diffs[k][0] === DIFF_DELETE) { count_delete++; text_delete = diffs[k][1] + text_delete; k--; } previous_equality = k; } } if (starts_with_pair_end(diffs[pointer][1])) { var stray = diffs[pointer][1].charAt(0); diffs[pointer][1] = diffs[pointer][1].slice(1); text_delete += stray; text_insert += stray; } } if (pointer < diffs.length - 1 && !diffs[pointer][1]) { diffs.splice(pointer, 1); break; } if (text_delete.length > 0 || text_insert.length > 0) { if (text_delete.length > 0 && text_insert.length > 0) { commonlength = diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if (previous_equality >= 0) { diffs[previous_equality][1] += text_insert.substring(0, commonlength); } else { diffs.splice(0, 0, [DIFF_EQUAL, text_insert.substring(0, commonlength)]); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } commonlength = diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring(0, text_insert.length - commonlength); text_delete = text_delete.substring(0, text_delete.length - commonlength); } } var n = count_insert + count_delete; if (text_delete.length === 0 && text_insert.length === 0) { diffs.splice(pointer - n, n); pointer = pointer - n; } else if (text_delete.length === 0) { diffs.splice(pointer - n, n, [DIFF_INSERT, text_insert]); pointer = pointer - n + 1; } else if (text_insert.length === 0) { diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete]); pointer = pointer - n + 1; } else { diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete], [DIFF_INSERT, text_insert]); pointer = pointer - n + 2; } } if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } } if (diffs[diffs.length - 1][1] === "") { diffs.pop(); } var changes = false; pointer = 1; while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } if (changes) { diff_cleanupMerge(diffs, fix_unicode); } } function is_surrogate_pair_start(charCode) { return charCode >= 55296 && charCode <= 56319; } function is_surrogate_pair_end(charCode) { return charCode >= 56320 && charCode <= 57343; } function starts_with_pair_end(str) { return is_surrogate_pair_end(str.charCodeAt(0)); } function ends_with_pair_start(str) { return is_surrogate_pair_start(str.charCodeAt(str.length - 1)); } function remove_empty_tuples(tuples) { var ret = []; for (var i = 0; i < tuples.length; i++) { if (tuples[i][1].length > 0) { ret.push(tuples[i]); } } return ret; } function make_edit_splice(before, oldMiddle, newMiddle, after) { if (ends_with_pair_start(before) || starts_with_pair_end(after)) { return null; } return remove_empty_tuples([ [DIFF_EQUAL, before], [DIFF_DELETE, oldMiddle], [DIFF_INSERT, newMiddle], [DIFF_EQUAL, after] ]); } function find_cursor_edit_diff(oldText, newText, cursor_pos) { var oldRange = typeof cursor_pos === "number" ? { index: cursor_pos, length: 0 } : cursor_pos.oldRange; var newRange = typeof cursor_pos === "number" ? null : cursor_pos.newRange; var oldLength = oldText.length; var newLength = newText.length; if (oldRange.length === 0 && (newRange === null || newRange.length === 0)) { var oldCursor = oldRange.index; var oldBefore = oldText.slice(0, oldCursor); var oldAfter = oldText.slice(oldCursor); var maybeNewCursor = newRange ? newRange.index : null; editBefore: { var newCursor = oldCursor + newLength - oldLength; if (maybeNewCursor !== null && maybeNewCursor !== newCursor) { break editBefore; } if (newCursor < 0 || newCursor > newLength) { break editBefore; } var newBefore = newText.slice(0, newCursor); var newAfter = newText.slice(newCursor); if (newAfter !== oldAfter) { break editBefore; } var prefixLength = Math.min(oldCursor, newCursor); var oldPrefix = oldBefore.slice(0, prefixLength); var newPrefix = newBefore.slice(0, prefixLength); if (oldPrefix !== newPrefix) { break editBefore; } var oldMiddle = oldBefore.slice(prefixLength); var newMiddle = newBefore.slice(prefixLength); return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldAfter); } editAfter: { if (maybeNewCursor !== null && maybeNewCursor !== oldCursor) { break editAfter; } var cursor = oldCursor; var newBefore = newText.slice(0, cursor); var newAfter = newText.slice(cursor); if (newBefore !== oldBefore) { break editAfter; } var suffixLength = Math.min(oldLength - cursor, newLength - cursor); var oldSuffix = oldAfter.slice(oldAfter.length - suffixLength); var newSuffix = newAfter.slice(newAfter.length - suffixLength); if (oldSuffix !== newSuffix) { break editAfter; } var oldMiddle = oldAfter.slice(0, oldAfter.length - suffixLength); var newMiddle = newAfter.slice(0, newAfter.length - suffixLength); return make_edit_splice(oldBefore, oldMiddle, newMiddle, oldSuffix); } } if (oldRange.length > 0 && newRange && newRange.length === 0) { replaceRange: { var oldPrefix = oldText.slice(0, oldRange.index); var oldSuffix = oldText.slice(oldRange.index + oldRange.length); var prefixLength = oldPrefix.length; var suffixLength = oldSuffix.length; if (newLength < prefixLength + suffixLength) { break replaceRange; } var newPrefix = newText.slice(0, prefixLength); var newSuffix = newText.slice(newLength - suffixLength); if (oldPrefix !== newPrefix || oldSuffix !== newSuffix) { break replaceRange; } var oldMiddle = oldText.slice(prefixLength, oldLength - suffixLength); var newMiddle = newText.slice(prefixLength, newLength - suffixLength); return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldSuffix); } } return null; } function diff(text1, text2, cursor_pos) { return diff_main(text1, text2, cursor_pos, true); } diff.INSERT = DIFF_INSERT; diff.DELETE = DIFF_DELETE; diff.EQUAL = DIFF_EQUAL; Array.prototype.enumerate = function() { let i = 0; let rv = []; for (let item of this) rv.push([i++, item]); return rv; }; Array.prototype.filter_map = function(fn) { return this.map(fn).filter((n) => n !== null); }; Array.prototype.max_by_key = function(fn) { const max2 = (self2) => { return Math.max.apply(null, self2); }; return max2(this.map(fn)); }; Array.prototype.chain = function(that) { return this.concat(that); }; Number.prototype.saturating_sub = function(n) { return this.valueOf() - n; }; Number.prototype.max = function(n) { return Math.max(this.valueOf(), n); }; Number.prototype.min = function(n) { return Math.min(this.valueOf(), n); }; class Option { static from(obj) { if (obj === void 0 || obj === null) return none(); return some(obj); } } class Some { constructor(value) { this.value = value; } map(fn) { return some(fn(this.value)); } map_or(d, fn) { return fn(this.value); } filter(fn) { if (fn(this.value)) return some(this.value); return none(); } or(d) { return this; } iter() { return [this.value]; } unwrap() { return this.value; } unwrap_or_else(d) { return this.unwrap(); } is_some() { return true; } is_none() { return false; } equal(other) { if (other.is_some()) return this.value === other.value; return false; } static is(o) { return o instanceof Some; } } class None { map(fn) { return none(); } map_or(d, fn) { return d; } filter(fn) { return none(); } or(d) { return d; } iter() { return []; } unwrap() { throw new Error("Unwrapped None"); } unwrap_or_else(d) { return d(); } is_some() { return false; } is_none() { return true; } equal(other) { return other.is_none(); } static is(o) { return o instanceof None; } } const some = (value) => { return new Some(value); }; const none = () => { return new None(); }; const isOption = (o) => { return o instanceof Some || o instanceof None; }; class Ok { constructor(value) { this.value = value; } map(fn) { return ok(fn(this.value)); } map_or(d, fn) { return ok(fn(this.value)); } or(d) { return this; } is_ok() { return true; } is_err() { return false; } unwrap() { return this.value; } unwrap_or_else(d) { return d(this.value); } static is(o) { return o instanceof Ok; } } class Err { constructor(value) { this.value = value; } map(fn) { return ok(fn(this.value)); } map_or(d, fn) { return ok(d); } or(d) { return d; } unwrap() { return this.value; } unwrap_or_else(d) { return d(this.value); } is_ok() { return false; } is_err() { return true; } static is(o) { return o instanceof Err; } } const ok = (value) => { return new Ok(value); }; const err = (value) => { return new Err(value); }; const isResult = (o) => { return o instanceof Ok || o instanceof Err; }; function binary_search_by_key(arr, x, fn) { let start = 0, end = arr.length - 1, mid, val; while (start < end) { mid = Math.floor((start + end) / 2); val = fn(arr[mid]); if (val === x) return ok(mid); else if (val < x) start = mid + 1; else end = mid - 1; } return err(get_sorted_index(arr, x, fn)); } function get_sorted_index(arr, x, fn) { let low = 0, high = arr.length; while (low < high) { let mid = low + high >>> 1; if (x > fn(arr[mid])) low = mid + 1; else high = mid; } return low; } function range(start, end) { let rv = []; while (start < end) { rv.push(start); start++; } return rv; } function* rangeIter(start, end) { while (start < end) { yield start; start++; } return; } const max = (self2) => { if (self2.length === 0) return void 0; return Math.max.apply(null, self2); }; const bton = (b) => b === true ? 1 : 0; function sort_by_key(arr, fn) { arr.sort((a, b) => { return fn(a) - fn(b); }); } function min_by_key(arr, fn) { let res = [Infinity, null]; for (let val of arr) { if (fn(val) < res[0]) { res = [fn(val), val]; } } return Option.from(res[1]); } const isString = (o) => typeof o === "string"; const isNumber = (o) => typeof o === "number"; const isBoolean = (o) => typeof o === "boolean"; const isCallback = (maybeFunction) => typeof maybeFunction === "function"; class Display { constructor(value) { this.value = typeof value === "string" ? value : value.value; } fg(color) { if (isOption(color)) { let func = color.is_some() ? color.unwrap() : (a) => a; this.value = func(this.value); } else if (isCallback(color)) { this.value = color(this.value); } return this; } bg(color) { if (isOption(color)) { let func = color.is_some() ? color.unwrap() : (a) => a; this.value = func(this.value); } else if (isCallback(color)) { this.value = color(this.value); } return this; } chars() { return this.value; } map(fn) { return new Display(fn(this.value)); } display() { return this.value; } toString() { return this.value; } unwrap_or_else(d) { return this.value ?? d(); } static { this.is = (o) => o instanceof Display; } } const isDisplay = Display.is; class Span { constructor(_start, _end) { this._start = _start; this._end = _end; } /// Get the identifier of the source that this span refers to. source() { return this.SourceId; } set start(value) { this._start = value; } get start() { return this._start; } set end(value) { this._end = value; } get end() { return this._end; } /// Get the length of this span (difference between the start of the span and the end of the span). len() { return this.end.saturating_sub(this.start); } /// Determine whether the span contains the given offset. contains(offset) { return range(this.start, this.end).includes(offset); } static { this.is = (o) => o instanceof Span; } static from(o) { if (isNumber(o[0]) && isNumber(o[1])) return new Span(o[0], o[1]); if (isString(o[0]) && Range.is(o[1])) { const s = new Span(o[1].start, o[1].end); s.SourceId = o[0]; return s; } throw new Error(`Invalid SpanInit`); } } Span.is; class Range extends Span { constructor() { super(...arguments); this.SourceId = null; } source() { return this.SourceId; } len() { return Math.abs(this.start - this.end); } contains(item) { return item >= this.start && item < this.end; } static is(o) { return o instanceof Range; } static from(o) { if (isNumber(o[0]) && isNumber(o[1])) return new Span(o[0], o[1]); if (isString(o[0]) && Range.is(o[1])) { const s = new Range(o[1].start, o[1].end); s.SourceId = o[0]; return s; } throw new Error(`Invalid SpanInit`); } static new(start, end) { return new Range(start, end); } } function ValueError(message) { var err2 = new Error(message); err2.name = "ValueError"; return err2; } function create(transformers) { return function(template) { var args = Array.prototype.slice.call(arguments, 1); var idx = 0; var state = "UNDEFINED"; return template.replace( /([{}])\1|[{](.*?)(?:!(.+?))?[}]/g, function(match2, literal, _key, xf) { if (literal != null) { return literal; } var key = _key; if (key.length > 0) { if (state === "IMPLICIT") { throw ValueError("cannot switch from implicit to explicit numbering"); } state = "EXPLICIT"; } else { if (state === "EXPLICIT") { throw ValueError("cannot switch from explicit to implicit numbering"); } state = "IMPLICIT"; key = String(idx); idx += 1; } var path = key.split("."); var value = (/^\d+$/.test(path[0]) ? path : ["0"].concat(path)).reduce( function(maybe, key2) { return maybe.reduce(function(_, x) { return x != null && key2 in Object(x) ? [typeof x[key2] === "function" ? x[key2]() : x[key2]] : []; }, []); }, [args] ).reduce(function(_, x) { return x; }, ""); if (xf == null) { return value; } else if (Object.prototype.hasOwnProperty.call(transformers, xf)) { return transformers[xf](value); } else { throw ValueError('no transformer named "' + xf + '"'); } } ); }; } var format$1 = create({}); format$1.create = create; format$1.extend = function(prototype, transformers) { var $format = create(transformers); prototype.format = function() { var args = Array.prototype.slice.call(arguments); args.unshift(this); return $format.apply(global, args); }; }; const stringFormatter = () => new class { constructor() { this.flags = 0; this.fill = ""; this.align = "Left"; this.width = none(); this.precision = none(); this.buf = mkStringWriter(); } unwrap() { return this.buf.unwrap(); } }(); class Show { constructor(self2) { this.self = self2; } fmt(f) { if (isOption(this.self)) { this.self.map((x) => new Show(x).fmt(f)); return; } if (isResult(this.self)) { this.self.map((x) => new Show(x).fmt(f)); return; } if (typeof this.self === "string") { write(f.buf, "{}", this.self); return; } if (Array.isArray(this.self) && this.self.length === 2) { if (isCallback(this.self[1])) { for (let x of this.self[0]) { const func = this.self[1]; func(f, x); } } else { for (let _ of range(0, this.self[1])) { write(f.buf, "{}", this.self[0]); } } } else { const x = this.self[0]; write(f.buf, "{}", x); return; } } static { this.is = (o) => o instanceof Show; } } const isShow = Show.is; function write(w, ...args) { w.write_fmt(format(...args.map(fromRust))); } function format(...args) { const [head, ...rest] = args.map(fromRust); return format$1(head, ...rest); } function fromRust(node2) { if (isDisplay(node2)) { return node2.display(); } if (isShow(node2)) { let f = stringFormatter(); node2.fmt(f); return f.unwrap(); } if (isOption(node2)) { return node2.unwrap_or_else(() => ""); } if (isResult(node2)) { return node2.unwrap_or_else(() => "<(Unwrap Err)>"); } return node2.toString(); } function writeln(w, ...args) { let val = format(...args.map(fromRust)); w.write_fmt(val); w.write_fmt("\n"); } function eprintln(...args) { console.error(format(...args)); } class StdoutWriter { write_str(s) { throw new Error("Function not implemented"); } write_char(c2) { throw new Error("Function not implemented"); } write_fmt(...args) { console.log(format(...args)); return ok(null); } } class StderrWriter { write_str(s) { throw new Error("Function not implemented"); } write_char(c2) { throw new Error("Function not implemented"); } write_fmt(...args) { process.stderr.write(format(...args)); return ok(null); } } class StringWriter { constructor() { this.value = []; } write_str(s) { this.value.push(s); return ok(null); } write_char(c2) { this.value.push(c2); return ok(null); } write_fmt(...args) { this.value.push(format(...args)); return ok(null); } map(fn) { return fn(this.unwrap()); } unwrap() { return this.value.join(""); } } const stdoutWriter = new StdoutWriter(); const stderrWriter = new StderrWriter(); const mkStringWriter = () => new StringWriter(); const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`; const styles$1 = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], gray: [90, 39], // Alias of `blackBright` grey: [90, 39], // Alias of `blackBright` redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgGray: [100, 49], // Alias of `bgBlackBright` bgGrey: [100, 49], // Alias of `bgBlackBright` bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; Object.keys(styles$1.modifier); const foregroundColorNames = Object.keys(styles$1.color); const backgroundColorNames = Object.keys(styles$1.bgColor); [...foregroundColorNames, ...backgroundColorNames]; function assembleStyles() { const codes = /* @__PURE__ */ new Map(); for (const [groupName, group] of Object.entries(styles$1)) { for (const [styleName, style] of Object.entries(group)) { styles$1[styleName] = { open: `\x1B[${style[0]}m`, close: `\x1B[${style[1]}m` }; group[styleName] = styles$1[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles$1, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles$1, "codes", { value: codes, enumerable: false }); styles$1.color.close = "\x1B[39m"; styles$1.bgColor.close = "\x1B[49m"; styles$1.color.ansi = wrapAnsi16(); styles$1.color.ansi256 = wrapAnsi256(); styles$1.color.ansi16m = wrapAnsi16m(); styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); Object.defineProperties(styles$1, { rgbToAnsi256: { value(red, green, blue) { if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round((red - 8) / 247 * 24) + 232; } return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); }, enumerable: false }, hexToRgb: { value(hex) { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map((character) => character + character).join(""); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ integer >> 16 & 255, integer >> 8 & 255, integer & 255 /* eslint-enable no-bitwise */ ]; }, enumerable: false }, hexToAnsi256: { value: (hex) => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)), enumerable: false }, ansi256ToAnsi: { value(code) { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = ((code - 232) * 10 + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = remainder % 6 / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false }, rgbToAnsi: { value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)), enumerable: false }, hexToAnsi: { value: (hex) => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)), enumerable: false } }); return styles$1; } const ansiStyles = assembleStyles(); const env = { FORCE_COLOR: "false" }; let flagForceColor; function envForceColor() { if ("FORCE_COLOR" in env) { if (env.FORCE_COLOR === "true") { return 1; } if (env.FORCE_COLOR === "false") { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== void 0) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if ("TF_BUILD" in env && "AGENT_NAME" in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === void 0) { return 0; } const min = forceColor || 0; if (env.TERM === "dumb") { return min; } if ("CI" in env) { if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) { return 3; } if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some( (sign) => sign in env ) || env.CI_NAME === "codeship") { return 1; } return min; } if ("TEAMCITY_VERSION" in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === "truecolor") { return 3; } if (env.TERM === "xterm-kitty") { return 3; } if ("TERM_PROGRAM" in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); switch (env.TERM_PROGRAM) { case "iTerm.app": { return version >= 3 ? 3 : 2; } case "Apple_Terminal": { return 2; } } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ("COLORTERM" in env) { return 1; } return min; } function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options }); return translateLevel(level); } const supportsColor = { stdout: createSupportsColor({ isTTY: false }), stderr: createSupportsColor({ isTTY: false }) }; function stringReplaceAll(string, substring, replacer) { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ""; do { returnValue += string.slice(endIndex, index) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { let endIndex = 0; let returnValue = ""; do { const gotCR = string[index - 1] === "\r"; returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix; endIndex = index + 1; index = string.indexOf("\n", endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } const { stdout: stdoutColor, stderr: stderrColor } = supportsColor; const GENERATOR = Symbol("GENERATOR"); const STYLER = Symbol("STYLER"); const IS_EMPTY = Symbol("IS_EMPTY"); const levelMapping = ["ansi", "ansi", "ansi256", "ansi16m"]; const styles = /* @__PURE__ */ Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error("The `level` option should be an integer from 0 to 3"); } const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === void 0 ? colorLevel : options.level; }; const chalkFactory = (options) => { const chalk2 = (...strings) => strings.join(" "); applyOptions(chalk2, options); Object.setPrototypeOf(chalk2, createChalk.prototype); return chalk2; }; function createChalk(options) { return chalkFactory(options); } Object.setPrototypeOf(createChalk.prototype, Function.prototype); for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder( this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY] ); Object.defineProperty(this, styleName, { value: builder }); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this[STYLER], true); Object.defineProperty(this, "visible", { value: builder }); return builder; } }; const getModelAnsi = (model, level, type2, ...arguments_) => { if (model === "rgb") { if (level === "ansi16m") { return ansiStyles[type2].ansi16m(...arguments_); } if (level === "ansi256") { return ansiStyles[type2].ansi256(ansiStyles.rgbToAnsi256(...arguments_)); } return ansiStyles[type2].ansi(ansiStyles.rgbToAnsi(...arguments_)); } if (model === "hex") { return getModelAnsi("rgb", level, type2, ...ansiStyles.hexToRgb(...arguments_)); } return ansiStyles[type2][model](...arguments_); }; const usedModels = ["rgb", "hex", "ansi256"]; for (const model of usedModels) { styles[model] = { get() { const { level } = this; return function(...arguments_) { const styler = createStyler( getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansiStyles.color.close, this[STYLER] ); return createBuilder(this, styler, this[IS_EMPTY]); }; } }; const bgModel = "bg" + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const { level } = this; return function(...arguments_) { const styler = createStyler( getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansiStyles.bgColor.close, this[STYLER] ); return createBuilder(this, styler, this[IS_EMPTY]); }; } }; } const proto = Object.defineProperties(() => { }, { ...styles, level: { enumerable: true, get() { return this[GENERATOR].level; }, set(level) { this[GENERATOR].level = level; } } }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === void 0) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self2, _styler, _isEmpty) => { const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")); Object.setPrototypeOf(builder, proto); builder[GENERATOR] = self2; builder[STYLER] = _styler; builder[IS_EMPTY] = _isEmpty; return builder; }; const applyStyle = (self2, string) => { if (self2.level <= 0 || !string) { return self2[IS_EMPTY] ? "" : string; } let styler = self2[STYLER]; if (styler === void 0) { return string; } const { openAll, closeAll } = styler; if (string.includes("\x1B")) { while (styler !== void 0) { string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } const lfIndex = string.indexOf("\n"); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; Object.defineProperties(createChalk.prototype, styles); const chalk = createChalk(); createChalk({ level: stderrColor ? stderrColor.level : 0 }); const c = chalk; const colors = { blue: c.blue, green: c.green, red: c.red, yellow: c.yellow }; ({ blue: c.bgBlue, green: c.bgGreen, red: c.bgRed, yellow: c.bgYellow }); class Color { static { this.Fixed = Fixed; } } function Fixed(n) { return c.ansi256(n); } class Config { constructor(cross_gap, label_attach, compact, underlines, multiline_arrows, color, tab_width, char_set) { this.cross_gap = cross_gap; this.label_attach = label_attach; this.compact = compact; this.underlines = underlines; this.multiline_arrows = multiline_arrows; this.color = color; this.tab_width = tab_width; this.char_set = char_set; } static default() { return new Config( true, "Middle", false, true, true, true, 4, "Unicode" /* Unicode */ ); } /// When label lines cross one-another, should there be a gap? /// /// The alternative to this is to insert crossing characters. However, these interact poorly with label colours. /// /// If unspecified, this defaults to [`false`]. with_cross_gap(cross_gap) { this.cross_gap = cross_gap; return this; } /// Where should inline labels attach to their spans? /// /// If unspecified, this defaults to [`LabelAttach.Middle`]. with_label_attach(label_attach) { this.label_attach = label_attach; return this; } /// Should the report remove gaps to minimise used space? /// /// If unspecified, this defaults to [`false`]. with_compact(compact) { this.compact = compact; return this; } /// Should underlines be used for label span where possible? /// /// If unspecified, this defaults to [`true`]. with_underlines(underlines) { this.underlines = underlines; return this; } /// Should arrows be used to point to the bounds of multi-line spans? /// /// If unspecified, this defaults to [`true`]. with_multiline_arrows(multiline_arrows) { this.multiline_arrows = multiline_arrows; return this; } /// Should colored output should be enabled? /// /// If unspecified, this defaults to [`true`]. with_color(color) { this.color = color; return this; } /// How many characters width should tab characters be? /// /// If unspecified, this defaults to `4`. with_tab_width(tab_width) { this.tab_width = tab_width; return this; } /// What character set should be used to display dynamic elements such as boxes and arrows? /// /// If unspecified, this defaults to [`CharSet.Unicode`]. with_char_set(char_set) { this.char_set = char_set; return this; } error_color() { return some(colors.red).filter(() => this.color); } warning_color() { return some(colors.yellow).filter(() => this.color); } advice_color() { return some(Fixed(147)).filter(() => this.color); } margin_color() { return some(Fixed(246)).filter(() => this.color); } unimportant_color() { return some(Fixed(249)).filter(() => this.color); } note_color() { return some(Fixed(115)).filter(() => this.color); } // Find the character that should be drawn and the number of times it should be drawn for each char char_width(c2, col) { if (c2 === " ") { let tab_end = (col / this.tab_width + 1) * this.tab_width; return [new Display(" "), tab_end - col]; } if (c2.match(/[\s]/)) return [new Display(" "), 1]; return [new Display(c2), 1]; } } var LabelAttach = /* @__PURE__ */ ((LabelAttach2) => { LabelAttach2["Start"] = "Start"; LabelAttach2["Middle"] = "Middle"; LabelAttach2["End"] = "End"; return LabelAttach2; })(LabelAttach || {}); var CharSet = /* @__PURE__ */ ((CharSet2) => { CharSet2["Unicode"] = "Unicode"; CharSet2["Ascii"] = "Ascii"; return CharSet2; })(CharSet || {}); class Label { /// Create a new [`Label`]. constructor(span) { this.span = span; this.msg = none(); this.color = none(); this.order = 0; this.priority = 0; } /// Give this label a message. with_message(msg) { this.msg = some(msg); return this; } /// Give this label a highlight colour. with_color(color) { this.color = some(color); return this; } /// Specify the order of this label relative to other labels. /// /// Lower values correspond to this label having an earlier order. /// /// If unspecified, labels default to an order of `0`. /// /// When labels are displayed after a line the crate needs to decide which labels should be displayed first. By /// Default, the orders labels based on where their associated line meets the text (see [`LabelAttach`]). /// Additionally, multi-line labels are ordered before inline labels. You can this this function to override this /// behaviour. with_order(order) { this.order = order; return this; } /// Specify the priority of this label relative to other labels. /// /// Higher values correspond to this label having a higher priority. /// /// If unspecified, labels default to a priority of `0`. /// /// Label spans can overlap. When this happens, the crate needs to decide which labels to prioritise for various /// purposes such as highlighting. By default, spans with a smaller length get a higher priority. You can this this /// function to override this behaviour. with_priority(priority) { this.priority = priority; return this; } last_offset() { return this.span.end.saturating_sub(1).max(this.span.start); } static { this.from = Label.new; } static new(obj) { return new Label(Range.from(obj)); } static is(other) { return other instanceof Label; } } var assert$1 = { exports: {} }; var errors = {}; var util = {}; var types = {}; var shams$1 = function hasSymbols() { if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { return false; } if (typeof Symbol.iterator === "symbol") { return true; } var obj = {}; var sym = Symbol("test"); var symObj = Object(sym); if (typeof sym === "string") { return false; } if (Object.prototype.toString.call(sym) !== "[object Symbol]") { return false; } if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === "function") { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; var hasSymbols$1 = shams$1; var shams = function hasToStringTagShams() { return hasSymbols$1() && !!Symbol.toStringTag; }; var hasSymbols2; var hasRequiredHasSymbols; function requireHasSymbols() { if (hasRequiredHasSymbols) return hasSymbols2; hasRequiredHasSymbols = 1; var origSymbol = typeof Symbol !== "undefined" && Symbol; var hasSymbolSham = shams$1; hasSymbols2 = function hasNativeSymbols() { if (typeof origSymbol !== "function") { return false; } if (typeof Symbol !== "function") { return false; } if (typeof origSymbol("foo") !== "symbol") { return false; } if (typeof Symbol("bar") !== "symbol") { return false; } return hasSymbolSham(); }; return hasSymbols2; } var implementation$3; var hasRequiredImplementation$3; function requireImplementation$3() { if (hasRequiredImplementation$3) return implementation$3; hasRequiredImplementation$3 = 1; var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; var slice = Array.prototype.slice; var toStr2 = Object.prototype.toString; var funcType = "[object Function]"; implementation$3 = function bind(that) { var target = this; if (typeof target !== "function" || toStr2.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function() { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push("$" + i); } bound = Function("binder", "return function (" + boundArgs.join(",") + "){ return binder.apply(this,arguments); }")(binder); if (target.prototype) { var Empty = function Empty2() { }; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; return implementation$3; } var functionBind; var hasRequiredFunctionBind; function requireFunctionBind() { if (hasRequiredFunctionBind) return functionBind; hasRequiredFunctionBind = 1; var implementation2 = requireImplementation$3(); functionBind = Function.prototype.bind || implementation2; return functionBind; } var src; var hasRequiredSrc; function requireSrc() { if (hasRequiredSrc) return src; hasRequiredSrc = 1; var bind = requireFunctionBind(); src = bind.call(Function.call, Object.prototype.hasOwnProperty); return src; } var getIntrinsic; var hasRequiredGetIntrinsic; function requireGetIntrinsic() { if (hasRequiredGetIntrinsic) return getIntrinsic; hasRequiredGetIntrinsic = 1; var undefined$1; var $SyntaxError = SyntaxError; var $Function = Function; var $TypeError = TypeError; var getEvalledConstructor = function(expressionSyntax) { try { return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); } catch (e) { } }; var $gOPD2 = Object.getOwnPropertyDescriptor; if ($gOPD2) { try { $gOPD2({}, ""); } catch (e) { $gOPD2 = null; } } var throwTypeError = function() { throw new $TypeError(); }; var ThrowTypeError = $gOPD2 ? function() { try { arguments.callee; return throwTypeError; } catch (calleeThrows) { try { return $gOPD2(arguments, "callee").get; } catch (gOPDthrows) { return throwTypeError; } } }() : throwTypeError; var hasSymbols3 = requireHasSymbols()(); var getProto2 = Object.getPrototypeOf || function(x) { return x.__proto__; }; var needsEval = {}; var TypedArray = typeof Uint8Array === "undefined" ? undefined$1 : getProto2(Uint8Array); var INTRINSICS = { "%AggregateError%": typeof AggregateError === "undefined" ? undefined$1 : AggregateError, "%Array%": Array, "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined$1 : ArrayBuffer, "%ArrayIteratorPrototype%": hasSymbols3 ? getProto2([][Symbol.iterator]()) : undefined$1, "%AsyncFromSyncIteratorPrototype%": undefined$1, "%AsyncFunction%": needsEval, "%AsyncGenerator%": needsEval, "%AsyncGeneratorFunction%": needsEval, "%AsyncIteratorPrototype%": needsEval, "%Atomics%": typeof Atomics === "undefined" ? undefined$1 : Atomics, "%BigInt%": typeof BigInt === "undefined" ? undefined$1 : BigInt, "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined$1 : BigInt64Array, "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined$1 : BigUint64Array, "%Boolean%": Boolean, "%DataView%": typeof DataView === "undefined" ? undefined$1 : DataView, "%Date%": Date, "%decodeURI%": decodeURI, "%decodeURIComponent%": decodeURIComponent, "%encodeURI%": encodeURI, "%encodeURIComponent%": encodeURIComponent, "%Error%": Error, "%eval%": eval, // eslint-disable-line no-eval "%EvalError%": EvalError, "%Float32Array%": typeof Float32Array === "undefined" ? undefined$1 : Float32Array, "%Float64Array%": typeof Float64Array === "undefined" ? undefined$1 : Float64Array, "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined$1 : FinalizationRegistry, "%Function%": $Function, "%GeneratorFunction%": needsEval, "%Int8Array%": typeof Int8Array === "undefined" ? undefined$1 : Int8Array, "%Int16Array%": typeof Int16Array === "undefined" ? undefined$1 : Int16Array, "%Int32Array%": typeof Int32Array === "undefined" ? undefined$1 : Int32Array, "%isFinite%": isFinite, "%isNaN%": isNaN, "%IteratorPrototype%": hasSymbols3 ? getProto2(getProto2([][Symbol.iterator]())) : undefined$1, "%JSON%": typeof JSON === "object" ? JSON : undefined$1, "%Map%": typeof Map === "undefined" ? undefined$1 : Map, "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols3 ? undefined$1 : getProto2((/* @__PURE__ */ new Map())[Symbol.iterator]()), "%Math%": Math, "%Number%": Number, "%Object%": Object, "%parseFloat%": parseFloat, "%parseInt%": parseInt, "%Promise%": typeof Promise === "undefined" ? undefined$1 : Promise, "%Proxy%": typeof Proxy === "undefined" ? undefined$1 : Proxy, "%RangeError%": RangeError, "%ReferenceError%": ReferenceError, "%Reflect%": typeof Reflect === "undefined" ? undefined$1 : Reflect, "%RegExp%": RegExp, "%Set%": typeof Set === "undefined" ? undefined$1 : Set, "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols3 ? undefined$1 : getProto2((/* @__PURE__ */ new Set())[Symbol.iterator]()), "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined$1 : SharedArrayBuffer, "%String%": String, "%StringIteratorPrototype%": hasSymbols3 ? getProto2(""[Symbol.iterator]()) : undefined$1, "%Symbol%": hasSymbols3 ? Symbol : undefined$1, "%SyntaxError%": $SyntaxError, "%ThrowTypeError%": ThrowTypeError, "%TypedArray%": TypedArray, "%TypeError%": $TypeError, "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined$1 : Uint8Array, "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined$1 : Uint8ClampedArray, "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined$1 : Uint16Array, "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined$1 : Uint32Array, "%URIError%": URIError, "%WeakMap%": typeof WeakMap === "undefined" ? undefined$1 : WeakMap, "%WeakRef%": typeof WeakRef === "undefined" ? undefined$1 : WeakRef, "%WeakSet%": typeof WeakSet === "undefined" ? undefined$1 : WeakSet }; try { null.error; } catch (e) { var errorProto = getProto2(getProto2(e)); INTRINSICS["%Error.prototype%"] = errorProto; } var doEval = function doEval2(name) { var value; if (name === "%AsyncFunction%") { value = getEvalledConstructor("async function () {}"); } else if (name === "%GeneratorFunction%") { value = getEvalledConstructor("function* () {}"); } else if (name === "%AsyncGeneratorFunction%") { value = getEvalledConstructor("async function* () {}"); } else if (name === "%AsyncGenerator%") { var fn = doEval2("%AsyncGeneratorFunction%"); if (fn) { value = fn.prototype; } } else if (name === "%AsyncIteratorPrototype%") { var gen = doEval2("%AsyncGenerator%"); if (gen) { value = getProto2(gen.prototype); } } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], "%ArrayPrototype%": ["Array", "prototype"], "%ArrayProto_entries%": ["Array", "prototype", "entries"], "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], "%ArrayProto_keys%": ["Array", "prototype", "keys"], "%ArrayProto_values%": ["Array", "prototype", "values"], "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], "%BooleanPrototype%": ["Boolean", "prototype"], "%DataViewPrototype%": ["DataView", "prototype"], "%DatePrototype%": ["Date", "prototype"], "%ErrorPrototype%": ["Error", "prototype"], "%EvalErrorPrototype%": ["EvalError", "prototype"], "%Float32ArrayPrototype%": ["Float32Array", "prototype"], "%Float64ArrayPrototype%": ["Float64Array", "prototype"], "%FunctionPrototype%": ["Function", "prototype"], "%Generator%": ["GeneratorFunction", "prototype"], "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], "%Int8ArrayPrototype%": ["Int8Array", "prototype"], "%Int16ArrayPrototype%": ["Int16Array", "prototype"], "%Int32ArrayPrototype%": ["Int32Array", "prototype"], "%JSONParse%": ["JSON", "parse"], "%JSONStringify%": ["JSON", "stringify"], "%MapPrototype%": ["Map", "prototype"], "%NumberPrototype%": ["Number", "prototype"], "%ObjectPrototype%": ["Object", "prototype"], "%ObjProto_toString%": ["Object", "prototype", "toString"], "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], "%PromisePrototype%": ["Promise", "prototype"], "%PromiseProto_then%": ["Promise", "prototype", "then"], "%Promise_all%": ["Promise", "all"], "%Promise_reject%": ["Promise", "reject"], "%Promise_resolve%": ["Promise", "resolve"], "%RangeErrorPrototype%": ["RangeError", "prototype"], "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], "%RegExpPrototype%": ["RegExp", "prototype"], "%SetPrototype%": ["Set", "prototype"], "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], "%StringPrototype%": ["String", "prototype"], "%SymbolPrototype%": ["Symbol", "prototype"], "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], "%TypedArrayPrototype%": ["TypedArray", "prototype"], "%TypeErrorPrototype%": ["TypeError", "prototype"], "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], "%URIErrorPrototype%": ["URIError", "prototype"], "%WeakMapPrototype%": ["WeakMap", "prototype"], "%WeakSetPrototype%": ["WeakSet", "prototype"] }; var bind = requireFunctionBind(); var hasOwn = requireSrc(); var $concat = bind.call(Function.call, Array.prototype.concat); var $spliceApply = bind.call(Function.apply, Array.prototype.splice); var $replace = bind.call(Function.call, String.prototype.replace); var $strSlice = bind.call(Function.call, String.prototype.slice); var $exec = bind.call(Function.call, RegExp.prototype.exec); var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; var stringToPath = function stringToPath2(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === "%" && last !== "%") { throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); } else if (last === "%" && first !== "%") { throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); } var result = []; $replace(string, rePropName, function(match2, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match2; }); return result; }; var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = "%" + alias[0] + "%"; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) { value = doEval(intrinsicName); } if (typeof value === "undefined" && !allowMissing) { throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); } return { alias, name: intrinsicName, value }; } throw new $SyntaxError("intrinsic " + name + " does not exist!"); }; getIntrinsic = function GetIntrinsic2(name, allowMissing) { if (typeof name !== "string" || name.length === 0) { throw new $TypeError("intrinsic name must be a non-empty string"); } if (arguments.length > 1 && typeof allowMissing !== "boolean") { throw new $TypeError('"allowMissing" argument must be a boolean'); } if ($exec(/^%?[^%]*%?$/, name) === null) { throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); } var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { throw new $SyntaxError("property names with quotes must have matching quotes"); } if (part === "constructor" || !isOwn) { skipFurtherCaching = true; } intrinsicBaseName += "." + part; intrinsicRealName = "%" + intrinsicBaseName + "%"; if (hasOwn(INTRINSICS, intrinsicRealName)) { value = INTRINSICS[intrinsicRealName]; } else if (value != null) { if (!(part in value)) { if (!allowMissing) { throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); } return void 0; } if ($gOPD2 && i + 1 >= parts.length) { var desc = $gOPD2(value, part); isOwn = !!desc; if (isOwn && "get" in desc && !("originalValue" in desc.get)) { value = desc.get; } else { value = value[part]; } } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) { INTRINSICS[intrinsicRealName] = value; } } } return value; }; return getIntrinsic; } var callBind$1 = { exports: {} }; var hasRequiredCallBind; function requireCallBind() { if (hasRequiredCallBind) return callBind$1.exports; hasRequiredCallBind = 1; (function(module) { var bind = requireFunctionBind(); var GetIntrinsic2 = requireGetIntrinsic(); var $apply = GetIntrinsic2("%Function.prototype.apply%"); var $call = GetIntrinsic2("%Function.prototype.call%"); var $reflectApply = GetIntrinsic2("%Reflect.apply%", true) || bind.call($call, $apply); var $gOPD2 = GetIntrinsic2("%Object.getOwnPropertyDescriptor%", true); var $defineProperty = GetIntrinsic2("%Object.defineProperty%", true); var $max = GetIntrinsic2("%Math.max%"); if ($defineProperty) { try { $defineProperty({}, "a", { value: 1 }); } catch (e) { $defineProperty = null; } } module.exports = function callBind2(originalFunction) { var func = $reflectApply(bind, $call, arguments); if ($gOPD2 && $defineProperty) { var desc = $gOPD2(func, "length"); if (desc.configurable) { $defineProperty( func, "length", { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } ); } } return func; }; var applyBind = function applyBind2() { return $reflectApply(bind, $apply, arguments); }; if ($defineProperty) { $defineProperty(module.exports, "apply", { value: applyBind }); } else { module.exports.apply = applyBind; } })(callBind$1); return callBind$1.exports; } var GetIntrinsic$1 = requireGetIntrinsic(); var callBind = requireCallBind(); var $indexOf$1 = callBind(GetIntrinsic$1("String.prototype.indexOf")); var callBound$3 = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic$1(name, !!allowMissing); if (typeof intrinsic === "function" && $indexOf$1(name, ".prototype.") > -1) { return callBind(intrinsic); } return intrinsic; }; var hasToStringTag$4 = shams(); var callBound$2 = callBound$3; var $toString$2 = callBound$2("Object.prototype.toString"); var isStandardArguments = function isArguments(value) { if (hasToStringTag$4 && value && typeof value === "object" && Symbol.toStringTag in value) { return false; } return $toString$2(value) === "[object Arguments]"; }; var isLegacyArguments = function isArguments2(value) { if (isStandardArguments(value)) { return true; } return value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && $toString$2(value) !== "[object Array]" && $toString$2(value.callee) === "[object Function]"; }; var supportsStandardArguments = function() { return isStandardArguments(arguments); }(); isStandardArguments.isLegacyArguments = isLegacyArguments; var isArguments$1 = supportsStandardArguments ? isStandardArguments : isLegacyArguments; var toStr$2 = Object.prototype.toString; var fnToStr$1 = Function.prototype.toString; var isFnRegex = /^\s*(?:function)?\*/; var hasToStringTag$3 = shams(); var getProto = Object.getPrototypeOf; var getGeneratorFunc = function() { if (!hasToStringTag$3) { return false; } try { return Function("return function*() {}")(); } catch (e) { } }; var GeneratorFunction; var isGeneratorFunction = function isGeneratorFunction2(fn) { if (typeof fn !== "function") { return false; } if (isFnRegex.test(fnToStr$1.call(fn))) { return true; } if (!hasToStringTag$3) { var str = toStr$2.call(fn); return str === "[object GeneratorFunction]"; } if (!getProto) { return false; } if (typeof GeneratorFunction === "undefined") { var generatorFunc = getGeneratorFunc(); GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; } return getProto(fn) === GeneratorFunction; }; var fnToStr = Function.prototype.toString; var reflectApply = typeof Reflect === "object" && Reflect !== null && Reflect.apply; var badArrayLike; var isCallableMarker; if (typeof reflectApply === "function" && typeof Object.defineProperty === "function") { try { badArrayLike = Object.defineProperty({}, "length", { get: function() { throw isCallableMarker; } }); isCallableMarker = {}; reflectApply(function() { throw 42; }, null, badArrayLike); } catch (_) { if (_ !== isCallableMarker) { reflectApply = null; } } } else { reflectApply = null; } var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr$1 = Object.prototype.toString; var objectClass = "[object Object]"; var fnClass = "[object Function]"; var genClass = "[object GeneratorFunction]"; var ddaClass = "[object HTMLAllCollection]"; var ddaClass2 = "[object HTML document.all class]"; var ddaClass3 = "[object HTMLCollection]"; var hasToStringTag$2 = typeof Symbol === "function" && !!Symbol.toStringTag; var isIE68 = !(0 in [,]); var isDDA = function isDocumentDotAll() { return false; }; if (typeof document === "object") { var all = document.all; if (toStr$1.call(all) === toStr$1.call(document.all)) { isDDA = function isDocumentDotAll2(value) { if ((isIE68 || !value) && (typeof value === "undefined" || typeof value === "object")) { try { var str = toStr$1.call(value); return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null; } catch (e) { } } return false; }; } } var isCallable$1 = reflectApply ? function isCallable(value) { if (isDDA(value)) { return true; } if (!value) { return false; } if (typeof value !== "function" && typeof value !== "object") { return false; } try { reflectApply(value, null, badArrayLike); } catch (e) { if (e !== isCallableMarker) { return false; } } return !isES6ClassFn(value) && tryFunctionObject(value); } : function isCallable2(value) { if (isDDA(value)) { return true; } if (!value) { return false; } if (typeof value !== "function" && typeof value !== "object") { return false; } if (hasToStringTag$2) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr$1.call(value); if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass)) { return false; } return tryFunctionObject(value); }; var isCallable3 = isCallable$1; var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var forEachArray = function forEachArray2(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; var forEachString = function forEachString2(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; var forEachObject = function forEachObject2(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; var forEach$2 = function forEach(list, iterator, thisArg) { if (!isCallable3(iterator)) { throw new TypeError("iterator must be a function"); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (toStr.call(list) === "[object Array]") { forEachArray(list, iterator, receiver); } else if (typeof list === "string") { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; var forEach_1 = forEach$2; var possibleNames = [ "BigInt64Array", "BigUint64Array", "Float32Array", "Float64Array", "Int16Array", "Int32Array", "Int8Array", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray" ]; var g$2 = typeof globalThis === "undefined" ? commonjsGlobal : globalThis; var availableTypedArrays$2 = function availableTypedArrays() { var out = []; for (var i = 0; i < possibleNames.length; i++) { if (typeof g$2[possibleNames[i]] === "function") { out[out.length] = possibleNames[i]; } } return out; }; var GetIntrinsic = requireGetIntrinsic(); var $gOPD = GetIntrinsic("%Object.getOwnPropertyDescriptor%", true); if ($gOPD) { try { $gOPD([], "length"); } catch (e) { $gOPD = null; } } var gopd = $gOPD; var forEach$1 = forEach_1; var availableTypedArrays$1 = availableTypedArrays$2; var callBound$1 = callBound$3; var $toString$1 = callBound$1("Object.prototype.toString"); var hasToStringTag$1 = shams(); var gOPD$1 = gopd; var g$1 = typeof globalThis === "undefined" ? commonjsGlobal : globalThis; var typedArrays$1 = availableTypedArrays$1(); var $indexOf = callBound$1("Array.prototype.indexOf", true) || function indexOf(array, value) { for (var i = 0; i < array.length; i += 1) { if (array[i] === value) { return i; } } return -1; }; var $slice$1 = callBound$1("String.prototype.slice"); var toStrTags$1 = {}; var getPrototypeOf$1 = Object.getPrototypeOf; if (hasToStringTag$1 && gOPD$1 && getPrototypeOf$1) { forEach$1(typedArrays$1, function(typedArray) { var arr = new g$1[typedArray](); if (Symbol.toStringTag in arr) { var proto2 = getPrototypeOf$1(arr); var descriptor = gOPD$1(proto2, Symbol.toStringTag); if (!descriptor) { var superProto = getPrototypeOf$1(proto2); descriptor = gOPD$1(superProto, Symbol.toStringTag); } toStrTags$1[typedArray] = descriptor.get; } }); } var tryTypedArrays$1 = function tryAllTypedArrays(value) { var anyTrue = false; forEach$1(toStrTags$1, function(getter, typedArray) { if (!anyTrue) { try { anyTrue = getter.call(value) === typedArray; } catch (e) { } } }); return anyTrue; }; var isTypedArray$1 = function isTypedArray(value) { if (!value || typeof value !== "object") { return false; } if (!hasToStringTag$1 || !(Symbol.toStringTag in value)) { var tag = $slice$1($toString$1(value), 8, -1); return $indexOf(typedArrays$1, tag) > -1; } if (!gOPD$1) { return false; } return tryTypedArrays$1(value); }; var forEach2 = forEach_1; var availableTypedArrays2 = availableTypedArrays$2; var callBound = callBound$3; var gOPD = gopd; var $toString = callBound("Object.prototype.toString"); var hasToStringTag = shams(); var g = typeof globalThis === "undefined" ? commonjsGlobal : globalThis; var typedArrays = availableTypedArrays2(); var $slice = callBound("String.prototype.slice"); var toStrTags = {}; var getPrototypeOf = Object.getPrototypeOf; if (hasToStringTag && gOPD && getPrototypeOf) { forEach2(typedArrays, function(typedArray) { if (typeof g[typedArray] === "function") { var arr = new g[typedArray](); if (Symbol.toStringTag in arr) { var proto2 = getPrototypeOf(arr); var descriptor = gOPD(proto2, Symbol.toStringTag); if (!descriptor) { var superProto = getPrototypeOf(proto2); descriptor = gOPD(superProto, Symbol.toStringTag); } toStrTags[typedArray] = descriptor.get; } } }); } var tryTypedArrays = function tryAllTypedArrays2(value) { var foundName = false; forEach2(toStrTags, function(getter, typedArray) { if (!foundName) { try { var name = getter.call(value); if (name === typedArray) { foundName = name; } } catch (e) { } } }); return foundName; }; var isTypedArray2 = isTypedArray$1; var whichTypedArray = function whichTypedArray2(value) { if (!isTypedArray2(value)) { return false; } if (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); } return tryTypedArrays(value); }; (function(exports) { var isArgumentsObject = isArguments$1; var isGeneratorFunction$1 = isGeneratorFunction; var whichTypedArray$1 = whichTypedArray; var isTypedArray3 = isTypedArray$1; function uncurryThis(f) { return f.call.bind(f); } var BigIntSupported = typeof BigInt !== "undefined"; var SymbolSupported = typeof Symbol !== "undefined"; var ObjectToString = uncurryThis(Object.prototype.toString); var numberValue = uncurryThis(Number.prototype.valueOf); var stringValue = uncurryThis(String.prototype.valueOf); var booleanValue = uncurryThis(Boolean.prototype.valueOf); if (BigIntSupported) { var bigIntValue = uncurryThis(BigInt.prototype.valueOf); } if (SymbolSupported) { var symbolValue = uncurryThis(Symbol.prototype.valueOf); } function checkBoxedPrimitive(value, prototypeValueOf) { if (typeof value !== "object") { return false; } try { prototypeValueOf(value); return true; } catch (e) { return false; } } exports.isArgumentsObject = isArgumentsObject; exports.isGeneratorFunction = isGeneratorFunction$1; exports.isTypedArray = isTypedArray3; function isPromise(input) { return typeof Promise !== "undefined" && input instanceof Promise || input !== null && typeof input === "object" && typeof input.then === "function" && typeof input.catch === "function"; } exports.isPromise = isPromise; function isArrayBufferView(value) { if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { return ArrayBuffer.isView(value); } return isTypedArray3(value) || isDataView(value); } exports.isArrayBufferView = isArrayBufferView; function isUint8Array(value) { return whichTypedArray$1(value) === "Uint8Array"; } exports.isUint8Array = isUint8Array; function isUint8ClampedArray(value) { return whichTypedArray$1(value) === "Uint8ClampedArray"; } exports.isUint8ClampedArray = isUint8ClampedArray; function isUint16Array(value) { return whichTypedArray$1(value) === "Uint16Array"; } exports.isUint16Array = isUint16Array; function isUint32Array(value) { return whichTypedArray$1(value) === "Uint32Array"; } exports.isUint32Array = isUint32Array; function isInt8Array(value) { return whichTypedArray$1(value) === "Int8Array"; } exports.isInt8Array = isInt8Array; function isInt16Array(value) { return whichTypedArray$1(value) === "Int16Array"; } exports.isInt16Array = isInt16Array; function isInt32Array(value) { return whichTypedArray$1(value) === "Int32Array"; } exports.isInt32Array = isInt32Array; function isFloat32Array(value) { return whichTypedArray$1(value) === "Float32Array"; } exports.isFloat32Array = isFloat32Array; function isFloat64Array(value) { return whichTypedArray$1(value) === "Float64Array"; } exports.isFloat64Array = isFloat64Array; function isBigInt64Array(value) { return whichTypedArray$1(value) === "BigInt64Array"; } exports.isBigInt64Array = isBigInt64Array; function isBigUint64Array(value) { return whichTypedArray$1(value) === "BigUint64Array"; } exports.isBigUint64Array = isBigUint64Array; function isMapToString(value) { return ObjectToString(value) === "[object Map]"; } isMapToString.working = typeof Map !== "undefined" && isMapToString(/* @__PURE__ */ new Map()); function isMap(value) { if (typeof Map === "undefined") { return false; } return isMapToString.working ? isMapToString(value) : value instanceof Map; } exports.isMap = isMap; function isSetToString(value) { return ObjectToString(value) === "[object Set]"; } isSetToString.working = typeof Set !== "undefined" && isSetToString(/* @__PURE__ */ new Set()); function isSet(value) { if (typeof Set === "undefined") { return false; } return isSetToString.working ? isSetToString(value) : value instanceof Set; } exports.isSet = isSet; function isWeakMapToString(value) { return ObjectToString(value) === "[object WeakMap]"; } isWeakMapToString.working = typeof WeakMap !== "undefined" && isWeakMapToString(/* @__PURE__ */ new WeakMap()); function isWeakMap(value) { if (typeof WeakMap === "undefined") { return false; } return isWeakMapToString.working ? isWeakMapToString(value) : value instanceof WeakMap; } exports.isWeakMap = isWeakMap; function isWeakSetToString(value) { return ObjectToString(value) === "[object WeakSet]"; } isWeakSetToString.working = typeof WeakSet !== "undefined" && isWeakSetToString(/* @__PURE__ */ new WeakSet()); function isWeakSet(value) { return isWeakSetToString(value); } exports.isWeakSet = isWeakSet; function isArrayBufferToString(value) { return ObjectToString(value) === "[object ArrayBuffer]"; } isArrayBufferToString.working = typeof ArrayBuffer !== "undefined" && isArrayBufferToString(new ArrayBuffer()); function isArrayBuffer(value) { if (typeof ArrayBuffer === "undefined") { return false; } return isArrayBufferToString.working ? isArrayBufferToString(value) : value instanceof ArrayBuffer; } exports.isArrayBuffer = isArrayBuffer; function isDataViewToString(value) { return ObjectToString(value) === "[object DataView]"; } isDataViewToString.working = typeof ArrayBuffer !== "undefined" && typeof DataView !== "undefined" && isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)); function isDataView(value) { if (typeof DataView === "undefined") { return false; } return isDataViewToString.working ? isDataViewToString(value) : value instanceof DataView; } exports.isDataView = isDataView; var SharedArrayBufferCopy = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : void 0; function isSharedArrayBufferToString(value) { return ObjectToString(value) === "[object SharedArrayBuffer]"; } function isSharedArrayBuffer(value) { if (typeof SharedArrayBufferCopy === "undefined") { return false; } if (typeof isSharedArrayBufferToString.working === "undefined") { isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); } return isSharedArrayBufferToString.working ? isSharedArrayBufferToString(value) : value instanceof SharedArrayBufferCopy; } exports.isSharedArrayBuffer = isSharedArrayBuffer; function isAsyncFunction(value) { return ObjectToString(value) === "[object AsyncFunction]"; } exports.isAsyncFunction = isAsyncFunction; function isMapIterator(value) { return ObjectToString(value) === "[object Map Iterator]"; } exports.isMapIterator = isMapIterator; function isSetIterator(value) { return ObjectToString(value) === "[object Set Iterator]"; } exports.isSetIterator = isSetIterator; function isGeneratorObject(value) { return ObjectToString(value) === "[object Generator]"; } exports.isGeneratorObject = isGeneratorObject; function isWebAssemblyCompiledModule(value) { return ObjectToString(value) === "[object WebAssembly.Module]"; } exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; function isNumberObject(value) { return checkBoxedPrimitive(value, numberValue); } exports.isNumberObject = isNumberObject; function isStringObject(value) { return checkBoxedPrimitive(value, stringValue); } exports.isStringObject = isStringObject; function isBooleanObject(value) { return checkBoxedPrimitive(value, booleanValue); } exports.isBooleanObject = isBooleanObject; function isBigIntObject(value) { return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); } exports.isBigIntObject = isBigIntObject; function isSymbolObject(value) { return SymbolSupported && checkBoxedPrimitive(value, symbolValue); } exports.isSymbolObject = isSymbolObject; function isBoxedPrimitive(value) { return isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value); } exports.isBoxedPrimitive = isBoxedPrimitive; function isAnyArrayBuffer(value) { return typeof Uint8Array !== "undefined" && (isArrayBuffer(value) || isSharedArrayBuffer(value)); } exports.isAnyArrayBuffer = isAnyArrayBuffer; ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function(method) { Object.defineProperty(exports, method, { enumerable: false, value: function() { throw new Error(method + " is not supported in userland"); } }); }); })(types); var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === "object" && typeof arg.copy === "function" && typeof arg.fill === "function" && typeof arg.readUInt8 === "function"; }; var inherits_browser = { exports: {} }; if (typeof Object.create === "function") { inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function() { }; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } var inherits_browserExports = inherits_browser.exports; (function(exports) { var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors2(obj) { var keys = Object.keys(obj); var descriptors = {}; for (var i = 0; i < keys.length; i++) { descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); } return descriptors; }; var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString2(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(" "); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x2) { if (x2 === "%%") return "%"; if (i >= len) return x2; switch (x2) { case "%s": return String(args[i++]); case "%d": return Number(args[i++]); case "%j": try { return JSON.stringify(args[i++]); } catch (_) { return "[Circular]"; } default: return x2; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += " " + x; } else { str += " " + inspect(x); } } return str; }; exports.deprecate = function(fn, msg) { if (typeof process !== "undefined" && process.noDeprecation === true) { return fn; } if (typeof process === "undefined") { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnvRegex = /^$/; if (process.env.NODE_DEBUG) { var debugEnv = process.env.NODE_DEBUG; debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase(); debugEnvRegex = new RegExp("^" + debugEnv + "$", "i"); } exports.debuglog = function(set) { set = set.toUpperCase(); if (!debugs[set]) { if (debugEnvRegex.test(set)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error("%s %d: %s", set, pid, msg); }; } else { debugs[set] = function() { }; } } return debugs[set]; }; function inspect(obj, opts) { var ctx = { seen: [], stylize: stylizeNoColor }; if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean2(opts)) { ctx.showHidden = opts; } else if (opts) { exports._extend(ctx, opts); } if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; inspect.colors = { "bold": [1, 22], "italic": [3, 23], "underline": [4, 24], "inverse": [7, 27], "white": [37, 39], "grey": [90, 39], "black": [30, 39], "blue": [34, 39], "cyan": [36, 39], "green": [32, 39], "magenta": [35, 39], "red": [31, 39], "yellow": [33, 39] }; inspect.styles = { "special": "cyan", "number": "yellow", "boolean": "yellow", "undefined": "grey", "null": "bold", "string": "green", "date": "magenta", // "name": intentionally not styling "regexp": "red" }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m"; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString2(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) { return formatError(value); } if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ": " + value.name : ""; return ctx.stylize("[Function" + name + "]", "special"); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), "date"); } if (isError(value)) { return formatError(value); } } var base = "", array = false, braces = ["{", "}"]; if (isArray(value)) { array = true; braces = ["[", "]"]; } if (isFunction(value)) { var n = value.name ? ": " + value.name : ""; base = " [Function" + n + "]"; } if (isRegExp(value)) { base = " " + RegExp.prototype.toString.call(value); } if (isDate(value)) { base = " " + Date.prototype.toUTCString.call(value); } if (isError(value)) { base = " " + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); } else { return ctx.stylize("[Object]", "special"); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize("undefined", "undefined"); if (isString2(value)) { var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; return ctx.stylize(simple, "string"); } if (isNumber2(value)) return ctx.stylize("" + value, "number"); if (isBoolean2(value)) return ctx.stylize("" + value, "boolean"); if (isNull(value)) return ctx.stylize("null", "null"); } function formatError(value) { return "[" + Error.prototype.toString.call(value) + "]"; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty2(value, String(i))) { output.push(formatProperty( ctx, value, recurseTimes, visibleKeys, String(i), true )); } else { output.push(""); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty( ctx, value, recurseTimes, visibleKeys, key, true )); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize("[Getter/Setter]", "special"); } else { str = ctx.stylize("[Getter]", "special"); } } else { if (desc.set) { str = ctx.stylize("[Setter]", "special"); } } if (!hasOwnProperty2(visibleKeys, key)) { name = "[" + key + "]"; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf("\n") > -1) { if (array) { str = str.split("\n").map(function(line) { return " " + line; }).join("\n").slice(2); } else { str = "\n" + str.split("\n").map(function(line) { return " " + line; }).join("\n"); } } } else { str = ctx.stylize("[Circular]", "special"); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify("" + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.slice(1, -1); name = ctx.stylize(name, "name"); } else { name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, "string"); } } return name + ": " + str; } function reduceToSingleString(output, base, braces) { var length = output.reduce(function(prev, cur) { if (cur.indexOf("\n") >= 0) ; return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1; }, 0); if (length > 60) { return braces[0] + (base === "" ? "" : base + "\n ") + " " + output.join(",\n ") + " " + braces[1]; } return braces[0] + base + " " + output.join(", ") + " " + braces[1]; } exports.types = types; function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean2(arg) { return typeof arg === "boolean"; } exports.isBoolean = isBoolean2; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber2(arg) { return typeof arg === "number"; } exports.isNumber = isNumber2; function isString2(arg) { return typeof arg === "string"; } exports.isString = isString2; function isSymbol(arg) { return typeof arg === "symbol"; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === "[object RegExp]"; } exports.isRegExp = isRegExp; exports.types.isRegExp = isRegExp; function isObject(arg) { return typeof arg === "object" && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === "[object Date]"; } exports.isDate = isDate; exports.types.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error); } exports.isError = isError; exports.types.isNativeError = isError; function isFunction(arg) { return typeof arg === "function"; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol typeof arg === "undefined"; } exports.isPrimitive = isPrimitive; exports.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? "0" + n.toString(10) : n.toString(10); } var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; function timestamp() { var d = /* @__PURE__ */ new Date(); var time = [ pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds()) ].join(":"); return [d.getDate(), months[d.getMonth()], time].join(" "); } exports.log = function() { console.log("%s - %s", timestamp(), exports.format.apply(exports, arguments)); }; exports.inherits = inherits_browserExports; exports._extend = function(origin, add) { if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty2(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : void 0; exports.promisify = function promisify(original) { if (typeof original !== "function") throw new TypeError('The "original" argument must be of type Function'); if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { var fn = original[kCustomPromisifiedSymbol]; if (typeof fn !== "function") { throw new TypeError('The "util.promisify.custom" argument must be of type Function'); } Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return fn; } function fn() { var promiseResolve, promiseReject; var promise = new Promise(function(resolve, reject) { promiseResolve = resolve; promiseReject = reject; }); var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } args.push(function(err2, value) { if (err2) { promiseReject(err2); } else { promiseResolve(value); } }); try { original.apply(this, args); } catch (err2) { promiseReject(err2); } return promise; } Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return Object.defineProperties( fn, getOwnPropertyDescriptors(original) ); }; exports.promisify.custom = kCustomPromisifiedSymbol; function callbackifyOnRejected(reason, cb) { if (!reason) { var newReason = new Error("Promise was rejected with a falsy value"); newReason.reason = reason; reason = newReason; } return cb(reason); } function callbackify(original) { if (typeof original !== "function") { throw new TypeError('The "original" argument must be of type Function'); } function callbackified() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== "function") { throw new TypeError("The last argument must be of type Function"); } var self2 = this; var cb = function() { return maybeCb.apply(self2, arguments); }; original.apply(this, args).then( function(ret) { process.nextTick(cb.bind(null, null, ret)); }, function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)); } ); } Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); Object.defineProperties( callbackified, getOwnPropertyDescriptors(original) ); return callbackified; } exports.callbackify = callbackify; })(util); var hasRequiredErrors; function requireErrors() { if (hasRequiredErrors) return errors; hasRequiredErrors = 1; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof2(obj2) { return typeof obj2; }; } else { _typeof = function _typeof2(obj2) { return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self2, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self2); } function _assertThisInitialized(self2) { if (self2 === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self2; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o2) { return o2.__proto__ || Object.getPrototypeOf(o2); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var codes = {}; var assert2; var util$12; function createErrorType(code, message, Base) { if (!Base) { Base = Error; } function getMessage(arg1, arg2, arg3) { if (typeof message === "string") { return message; } else { return message(arg1, arg2, arg3); } } var NodeError = /* @__PURE__ */ function(_Base) { _inherits(NodeError2, _Base); function NodeError2(arg1, arg2, arg3) { var _this; _classCallCheck(this, NodeError2); _this = _possibleConstructorReturn(this, _getPrototypeOf(NodeError2).call(this, getMessage(arg1, arg2, arg3))); _this.code = code; return _this; } return NodeError2; }(Base); codes[code] = NodeError; } function oneOf(expected, thing) { if (Array.isArray(expected)) { var len = expected.length; expected = expected.map(function(i) { return String(i); }); if (len > 2) { return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; } else if (len === 2) { return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); } else { return "of ".concat(thing, " ").concat(expected[0]); } } else { return "of ".concat(thing, " ").concat(String(expected)); } } function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } function endsWith(str, search, this_len) { if (this_len === void 0 || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } function includes(str, search, start) { if (typeof start !== "number") { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType("ERR_AMBIGUOUS_ARGUMENT", 'The "%s" argument is ambiguous. %s', TypeError); createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { if (assert2 === void 0) assert2 = requireAssert(); assert2(typeof name === "string", "'name' must be a string"); var determiner; if (typeof expected === "string" && startsWith(expected, "not ")) { determiner = "must not be"; expected = expected.replace(/^not /, ""); } else { determiner = "must be"; } var msg; if (endsWith(name, " argument")) { msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, "type")); } else { var type2 = includes(name, ".") ? "property" : "argument"; msg = 'The "'.concat(name, '" ').concat(type2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); } msg += ". Received type ".concat(_typeof(actual)); return msg; }, TypeError); createErrorType("ERR_INVALID_ARG_VALUE", function(name, value) { var reason = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "is invalid"; if (util$12 === void 0) util$12 = util; var inspected = util$12.inspect(value); if (inspected.length > 128) { inspected = "".concat(inspected.slice(0, 128), "..."); } return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); }, TypeError); createErrorType("ERR_INVALID_RETURN_VALUE", function(input, name, value) { var type2; if (value && value.constructor && value.constructor.name) { type2 = "instance of ".concat(value.constructor.name); } else { type2 = "type ".concat(_typeof(value)); } return "Expected ".concat(input, ' to be returned from the "').concat(name, '"') + " function but got ".concat(type2, "."); }, TypeError); createErrorType("ERR_MISSING_ARGS", function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (assert2 === void 0) assert2 = requireAssert(); assert2(args.length > 0, "At least one arg needs to be specified"); var msg = "The "; var len = args.length; args = args.map(function(a) { return '"'.concat(a, '"'); }); switch (len) { case 1: msg += "".concat(args[0], " argument"); break; case 2: msg += "".concat(args[0], " and ").concat(args[1], " arguments"); break; default: msg += args.slice(0, len - 1).join(", "); msg += ", and ".concat(args[len - 1], " arguments"); break; } return "".concat(msg, " must be specified"); }, TypeError); errors.codes = codes; return errors; } var assertion_error; var hasRequiredAssertion_error; function requireAssertion_error() { if (hasRequiredAssertion_error) return assertion_error; hasRequiredAssertion_error = 1; function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === "function") { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self2, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self2); } function _assertThisInitialized(self2) { if (self2 === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self2; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0; _wrapNativeSuper = function _wrapNativeSuper2(Class2) { if (Class2 === null || !_isNativeFunction(Class2)) return Class2; if (typeof Class2 !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class2)) return _cache.get(Class2); _cache.set(Class2, Wrapper); } function Wrapper() { return _construct(Class2, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class2.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class2); }; return _wrapNativeSuper(Class); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function() { })); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct2(Parent2, args2, Class2) { var a = [null]; a.push.apply(a, args2); var Constructor = Function.bind.apply(Parent2, a); var instance = new Constructor(); if (Class2) _setPrototypeOf(instance, Class2.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o2) { return o2.__proto__ || Object.getPrototypeOf(o2); }; return _getPrototypeOf(o); } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof2(obj2) { return typeof obj2; }; } else { _typeof = function _typeof2(obj2) { return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; }; } return _typeof(obj); } var _require = util, inspect = _require.inspect; var _require2 = requireErrors(), ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; function endsWith(str, search, this_len) { if (this_len === void 0 || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } function repeat(str, count2) { count2 = Math.floor(count2); if (str.length == 0 || count2 == 0) return ""; var maxCount = str.length * count2; count2 = Math.floor(Math.log(count2) / Math.log(2)); while (count2) { str += str; count2--; } str += str.substring(0, maxCount - str.length); return str; } var blue = ""; var green = ""; var red = ""; var white = ""; var kReadableOperator = { deepStrictEqual: "Expected values to be strictly deep-equal:", strictEqual: "Expected values to be strictly equal:", strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', deepEqual: "Expected values to be loosely deep-equal:", equal: "Expected values to be loosely equal:", notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', notStrictEqual: 'Expected "actual" to be strictly unequal to:', notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', notEqual: 'Expected "actual" to be loosely unequal to:', notIdentical: "Values identical but not reference-equal:" }; var kMaxShortLength = 10; function copyError(source) { var keys = Object.keys(source); var target = Object.create(Object.getPrototypeOf(source)); keys.forEach(function(key) { target[key] = source[key]; }); Object.defineProperty(target, "message", { value: source.message }); return target; } function inspectValue(val) { return inspect(val, { compact: false, customInspect: false, depth: 1e3, maxArrayLength: Infinity, // Assert compares only enumerable properties (with a few exceptions). showHidden: false, // Having a long line as error is better than wrapping the line for // comparison for now. // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we // have meta information about the inspected properties (i.e., know where // in what line the property starts and ends). breakLength: Infinity, // Assert does not detect proxies currently. showProxy: false, sorted: true, // Inspect getters as we also check them when comparing entries. getters: true }); } function createErrDiff(actual, expected, operator) { var other = ""; var res = ""; var lastPos = 0; var end = ""; var skipped = false; var actualInspected = inspectValue(actual); var actualLines = actualInspected.split("\n"); var expectedLines = inspectValue(expected).split("\n"); var i = 0; var indicator = ""; if (operator === "strictEqual" && _typeof(actual) === "object" && _typeof(expected) === "object" && actual !== null && expected !== null) { operator = "strictEqualObject"; } if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { var inputLength = actualLines[0].length + expectedLines[0].length; if (inputLength <= kMaxShortLength) { if ((_typeof(actual) !== "object" || actual === null) && (_typeof(expected) !== "object" || expected === null) && (actual !== 0 || expected !== 0)) { return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); } } else if (operator !== "strictEqualObject") { var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; if (inputLength < maxLength) { while (actualLines[0][i] === expectedLines[0][i]) { i++; } if (i > 2) { indicator = "\n ".concat(repeat(" ", i), "^"); i = 0; } } } } var a = actualLines[actualLines.length - 1]; var b = expectedLines[expectedLines.length - 1]; while (a === b) { if (i++ < 2) { end = "\n ".concat(a).concat(end); } else { other = a; } actualLines.pop(); expectedLines.pop(); if (actualLines.length === 0 || expectedLines.length === 0) break; a = actualLines[actualLines.length - 1]; b = expectedLines[expectedLines.length - 1]; } var maxLines = Math.max(actualLines.length, expectedLines.length); if (maxLines === 0) { var _actualLines = actualInspected.split("\n"); if (_actualLines.length > 30) { _actualLines[26] = "".concat(blue, "...").concat(white); while (_actualLines.length > 27) { _actualLines.pop(); } } return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join("\n"), "\n"); } if (i > 3) { end = "\n".concat(blue, "...").concat(white).concat(end); skipped = true; } if (other !== "") { end = "\n ".concat(other).concat(end); other = ""; } var printedLines = 0; var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); for (i = 0; i < maxLines; i++) { var cur = i - lastPos; if (actualLines.length < i + 1) { if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(expectedLines[i - 2]); printedLines++; } res += "\n ".concat(expectedLines[i - 1]); printedLines++; } lastPos = i; other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); printedLines++; } else if (expectedLines.length < i + 1) { if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(actualLines[i - 2]); printedLines++; } res += "\n ".concat(actualLines[i - 1]); printedLines++; } lastPos = i; res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); printedLines++; } else { var expectedLine = expectedLines[i]; var actualLine = actualLines[i]; var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ",") || actualLine.slice(0, -1) !== expectedLine); if (divergingLines && endsWith(expectedLine, ",") && expectedLine.slice(0, -1) === actualLine) { divergingLines = false; actualLine += ","; } if (divergingLines) { if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(actualLines[i - 2]); printedLines++; } res += "\n ".concat(actualLines[i - 1]); printedLines++; } lastPos = i; res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); printedLines += 2; } else { res += other; other = ""; if (cur === 1 || i === 0) { res += "\n ".concat(actualLine); printedLines++; } } } if (printedLines > 20 && i < maxLines - 2) { return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white); } } return "".concat(msg).concat(skipped ? skippedMsg : "", "\n").concat(res).concat(other).concat(end).concat(indicator); } var AssertionError = /* @__PURE__ */ function(_Error) { _inherits(AssertionError2, _Error); function AssertionError2(options) { var _this; _classCallCheck(this, AssertionError2); if (_typeof(options) !== "object" || options === null) { throw new ERR_INVALID_ARG_TYPE("options", "Object", options); } var message = options.message, operator = options.operator, stackStartFn = options.stackStartFn; var actual = options.actual, expected = options.expected; var limit = Error.stackTraceLimit; Error.stackTraceLimit = 0; if (message != null) { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, String(message))); } else { if (process.stderr && process.stderr.isTTY) { if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) { blue = "\x1B[34m"; green = "\x1B[32m"; white = "\x1B[39m"; red = "\x1B[31m"; } else { blue = ""; green = ""; white = ""; red = ""; } } if (_typeof(actual) === "object" && actual !== null && _typeof(expected) === "object" && expected !== null && "stack" in actual && actual instanceof Error && "stack" in expected && expected instanceof Error) { actual = copyError(actual); expected = copyError(expected); } if (operator === "deepStrictEqual" || operator === "strictEqual") { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, createErrDiff(actual, expected, operator))); } else if (operator === "notDeepStrictEqual" || operator === "notStrictEqual") { var base = kReadableOperator[operator]; var res = inspectValue(actual).split("\n"); if (operator === "notStrictEqual" && _typeof(actual) === "object" && actual !== null) { base = kReadableOperator.notStrictEqualObject; } if (res.length > 30) { res[26] = "".concat(blue, "...").concat(white); while (res.length > 27) { res.pop(); } } if (res.length === 1) { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, "".concat(base, " ").concat(res[0]))); } else { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, "".concat(base, "\n\n").concat(res.join("\n"), "\n"))); } } else { var _res = inspectValue(actual); var other = ""; var knownOperators = kReadableOperator[operator]; if (operator === "notDeepEqual" || operator === "notEqual") { _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); if (_res.length > 1024) { _res = "".concat(_res.slice(0, 1021), "..."); } } else { other = "".concat(inspectValue(expected)); if (_res.length > 512) { _res = "".concat(_res.slice(0, 509), "..."); } if (other.length > 512) { other = "".concat(other.slice(0, 509), "..."); } if (operator === "deepEqual" || operator === "equal") { _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); } else { other = " ".concat(operator, " ").concat(other); } } _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, "".concat(_res).concat(other))); } } Error.stackTraceLimit = limit; _this.generatedMessage = !message; Object.defineProperty(_assertThisInitialized(_this), "name", { value: "AssertionError [ERR_ASSERTION]", enumerable: false, writable: true, configurable: true }); _this.code = "ERR_ASSERTION"; _this.actual = actual; _this.expected = expected; _this.operator = operator; if (Error.captureStackTrace) { Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); } _this.stack; _this.name = "AssertionError"; return _possibleConstructorReturn(_this); } _createClass(AssertionError2, [{ key: "toString", value: function toString() { return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); } }, { key: inspect.custom, value: function value(recurseTimes, ctx) { return inspect(this, _objectSpread({}, ctx, { customInspect: false, depth: 0 })); } }]); return AssertionError2; }(_wrapNativeSuper(Error)); assertion_error = AssertionError; return assertion_error; } var es6ObjectAssign; var hasRequiredEs6ObjectAssign; function requireEs6ObjectAssign() { if (hasRequiredEs6ObjectAssign) return es6ObjectAssign; hasRequiredEs6ObjectAssign = 1; function assign(target, firstSource) { if (target === void 0 || target === null) { throw new TypeError("Cannot convert first argument to object"); } var to = Object(target); for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === void 0 || nextSource === null) { continue; } var keysArray = Object.keys(Object(nextSource)); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { var nextKey = keysArray[nextIndex]; var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== void 0 && desc.enumerable) { to[nextKey] = nextSource[nextKey]; } } } return to; } function polyfill2() { if (!Object.assign) { Object.defineProperty(Object, "assign", { enumerable: false, configurable: true, writable: true, value: assign }); } } es6ObjectAssign = { assign, polyfill: polyfill2 }; return es6ObjectAssign; } var isArguments3; var hasRequiredIsArguments; function requireIsArguments() { if (hasRequiredIsArguments) return isArguments3; hasRequiredIsArguments = 1; var toStr2 = Object.prototype.toString; isArguments3 = function isArguments4(value) { var str = toStr2.call(value); var isArgs = str === "[object Arguments]"; if (!isArgs) { isArgs = str !== "[object Array]" && value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && toStr2.call(value.callee) === "[object Function]"; } return isArgs; }; return isArguments3; } var implementation$2; var hasRequiredImplementation$2; function requireImplementation$2() { if (hasRequiredImplementation$2) return implementation$2; hasRequiredImplementation$2 = 1; var keysShim; if (!Object.keys) { var has = Object.prototype.hasOwnProperty; var toStr2 = Object.prototype.toString; var isArgs = requireIsArguments(); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, "toString"); var hasProtoEnumBug = isEnumerable.call(function() { }, "prototype"); var dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ]; var equalsConstructorPrototype = function(o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $onmozfullscreenchange: true, $onmozfullscreenerror: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = function() { if (typeof window === "undefined") { return false; } for (var k in window) { try { if (!excludedKeys["$" + k] && has.call(window, k) && window[k] !== null && typeof window[k] === "object") { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }(); var equalsConstructorPrototypeIfNotBuggy = function(o) { if (typeof window === "undefined" || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; keysShim = function keys(object) { var isObject = object !== null && typeof object === "object"; var isFunction = toStr2.call(object) === "[object Function]"; var isArguments4 = isArgs(object); var isString2 = isObject && toStr2.call(object) === "[object String]"; var theKeys = []; if (!isObject && !isFunction && !isArguments4) { throw new TypeError("Object.keys called on a non-object"); } var skipProto = hasProtoEnumBug && isFunction; if (isString2 && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments4 && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === "prototype") && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === "constructor") && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } implementation$2 = keysShim; return implementation$2; } var objectKeys; var hasRequiredObjectKeys; function requireObjectKeys() { if (hasRequiredObjectKeys) return objectKeys; hasRequiredObjectKeys = 1; var slice = Array.prototype.slice; var isArgs = requireIsArguments(); var origKeys = Object.keys; var keysShim = origKeys ? function keys(o) { return origKeys(o); } : requireImplementation$2(); var originalKeys = Object.keys; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = function() { var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2); if (!keysWorksWithArguments) { Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; objectKeys = keysShim; return objectKeys; } var hasPropertyDescriptors_1; var hasRequiredHasPropertyDescriptors; function requireHasPropertyDescriptors() { if (hasRequiredHasPropertyDescriptors) return hasPropertyDescriptors_1; hasRequiredHasPropertyDescriptors = 1; var GetIntrinsic2 = requireGetIntrinsic(); var $defineProperty = GetIntrinsic2("%Object.defineProperty%", true); var hasPropertyDescriptors = function hasPropertyDescriptors2() { if ($defineProperty) { try { $defineProperty({}, "a", { value: 1 }); return true; } catch (e) { return false; } } return false; }; hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { if (!hasPropertyDescriptors()) { return null; } try { return $defineProperty([], "length", { value: 1 }).length !== 1; } catch (e) { return true; } }; hasPropertyDescriptors_1 = hasPropertyDescriptors; return hasPropertyDescriptors_1; } var defineProperties_1; var hasRequiredDefineProperties; function requireDefineProperties() { if (hasRequiredDefineProperties) return defineProperties_1; hasRequiredDefineProperties = 1; var keys = requireObjectKeys(); var hasSymbols3 = typeof Symbol === "function" && typeof Symbol("foo") === "symbol"; var toStr2 = Object.prototype.toString; var concat = Array.prototype.concat; var origDefineProperty = Object.defineProperty; var isFunction = function(fn) { return typeof fn === "function" && toStr2.call(fn) === "[object Function]"; }; var hasPropertyDescriptors = requireHasPropertyDescriptors()(); var supportsDescriptors = origDefineProperty && hasPropertyDescriptors; var defineProperty = function(object, name, value, predicate) { if (name in object) { if (predicate === true) { if (object[name] === value) { return; } } else if (!isFunction(predicate) || !predicate()) { return; } } if (supportsDescriptors) { origDefineProperty(object, name, { configurable: true, enumerable: false, value, writable: true }); } else { object[name] = value; } }; var defineProperties = function(object, map2) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map2); if (hasSymbols3) { props = concat.call(props, Object.getOwnPropertySymbols(map2)); } for (var i = 0; i < props.length; i += 1) { defineProperty(object, props[i], map2[props[i]], predicates[props[i]]); } }; defineProperties.supportsDescriptors = !!supportsDescriptors; defineProperties_1 = defineProperties; return defineProperties_1; } var implementation$1; var hasRequiredImplementation$1; function requireImplementation$1() { if (hasRequiredImplementation$1) return implementation$1; hasRequiredImplementation$1 = 1; var numberIsNaN = function(value) { return value !== value; }; implementation$1 = function is(a, b) { if (a === 0 && b === 0) { return 1 / a === 1 / b; } if (a === b) { return true; } if (numberIsNaN(a) && numberIsNaN(b)) { return true; } return false; }; return implementation$1; } var polyfill$1; var hasRequiredPolyfill$1; function requirePolyfill$1() { if (hasRequiredPolyfill$1) return polyfill$1; hasRequiredPolyfill$1 = 1; var implementation2 = requireImplementation$1(); polyfill$1 = function getPolyfill() { return typeof Object.is === "function" ? Object.is : implementation2; }; return polyfill$1; } var shim$1; var hasRequiredShim$1; function requireShim$1() { if (hasRequiredShim$1) return shim$1; hasRequiredShim$1 = 1; var getPolyfill = requirePolyfill$1(); var define = requireDefineProperties(); shim$1 = function shimObjectIs() { var polyfill2 = getPolyfill(); define(Object, { is: polyfill2 }, { is: function testObjectIs() { return Object.is !== polyfill2; } }); return polyfill2; }; return shim$1; } var objectIs; var hasRequiredObjectIs; function requireObjectIs() { if (hasRequiredObjectIs) return objectIs; hasRequiredObjectIs = 1; var define = requireDefineProperties(); var callBind2 = requireCallBind(); var implementation2 = requireImplementation$1(); var getPolyfill = requirePolyfill$1(); var shim2 = requireShim$1(); var polyfill2 = callBind2(getPolyfill(), Object); define(polyfill2, { getPolyfill, implementation: implementation2, shim: shim2 }); objectIs = polyfill2; return objectIs; } var implementation; var hasRequiredImplementation; function requireImplementation() { if (hasRequiredImplementation) return implementation; hasRequiredImplementation = 1; implementation = function isNaN2(value) { return value !== value; }; return implementation; } var polyfill; var hasRequiredPolyfill; function requirePolyfill() { if (hasRequiredPolyfill) return polyfill; hasRequiredPolyfill = 1; var implementation2 = requireImplementation(); polyfill = function getPolyfill() { if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN("a")) { return Number.isNaN; } return implementation2; }; return polyfill; } var shim; var hasRequiredShim; function requireShim() { if (hasRequiredShim) return shim; hasRequiredShim = 1; var define = requireDefineProperties(); var getPolyfill = requirePolyfill(); shim = function shimNumberIsNaN() { var polyfill2 = getPolyfill(); define(Number, { isNaN: polyfill2 }, { isNaN: function testIsNaN() { return Number.isNaN !== polyfill2; } }); return polyfill2; }; return shim; } var isNan; var hasRequiredIsNan; function requireIsNan() { if (hasRequiredIsNan) return isNan; hasRequiredIsNan = 1; var callBind2 = requireCallBind(); var define = requireDefineProperties(); var implementation2 = requireImplementation(); var getPolyfill = requirePolyfill(); var shim2 = requireShim(); var polyfill2 = callBind2(getPolyfill(), Number); define(polyfill2, { getPolyfill, implementation: implementation2, shim: shim2 }); isNan = polyfill2; return isNan; } var comparisons; var hasRequiredComparisons; function requireComparisons() { if (hasRequiredComparisons) return comparisons; hasRequiredComparisons = 1; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = void 0; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err2) { _d = true; _e = err2; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof2(obj2) { return typeof obj2; }; } else { _typeof = function _typeof2(obj2) { return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; }; } return _typeof(obj); } var regexFlagsSupported = /a/g.flags !== void 0; var arrayFromSet = function arrayFromSet2(set) { var array = []; set.forEach(function(value) { return array.push(value); }); return array; }; var arrayFromMap = function arrayFromMap2(map2) { var array = []; map2.forEach(function(value, key) { return array.push([key, value]); }); return array; }; var objectIs2 = Object.is ? Object.is : requireObjectIs(); var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function() { return []; }; var numberIsNaN = Number.isNaN ? Number.isNaN : requireIsNan(); function uncurryThis(f) { return f.call.bind(f); } var hasOwnProperty2 = uncurryThis(Object.prototype.hasOwnProperty); var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); var objectToString = uncurryThis(Object.prototype.toString); var _require$types = util.types, isAnyArrayBuffer = _require$types.isAnyArrayBuffer, isArrayBufferView = _require$types.isArrayBufferView, isDate = _require$types.isDate, isMap = _require$types.isMap, isRegExp = _require$types.isRegExp, isSet = _require$types.isSet, isNativeError = _require$types.isNativeError, isBoxedPrimitive = _require$types.isBoxedPrimitive, isNumberObject = _require$types.isNumberObject, isStringObject = _require$types.isStringObject, isBooleanObject = _require$types.isBooleanObject, isBigIntObject = _require$types.isBigIntObject, isSymbolObject = _require$types.isSymbolObject, isFloat32Array = _require$types.isFloat32Array, isFloat64Array = _require$types.isFloat64Array; function isNonIndex(key) { if (key.length === 0 || key.length > 10) return true; for (var i = 0; i < key.length; i++) { var code = key.charCodeAt(i); if (code < 48 || code > 57) return true; } return key.length === 10 && key >= Math.pow(2, 32); } function getOwnNonIndexProperties(value) { return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); } /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a, b) { if (a === b) { return 0; } var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) { return -1; } if (y < x) { return 1; } return 0; } var kStrict = true; var kLoose = false; var kNoIterator = 0; var kIsArray = 1; var kIsSet = 2; var kIsMap = 3; function areSimilarRegExps(a, b) { return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); } function areSimilarFloatArrays(a, b) { if (a.byteLength !== b.byteLength) { return false; } for (var offset = 0; offset < a.byteLength; offset++) { if (a[offset] !== b[offset]) { return false; } } return true; } function areSimilarTypedArrays(a, b) { if (a.byteLength !== b.byteLength) { return false; } return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; } function areEqualArrayBuffers(buf1, buf2) { return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; } function isEqualBoxedPrimitive(val1, val2) { if (isNumberObject(val1)) { return isNumberObject(val2) && objectIs2(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); } if (isStringObject(val1)) { return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); } if (isBooleanObject(val1)) { return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); } if (isBigIntObject(val1)) { return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); } return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); } function innerDeepEqual(val1, val2, strict, memos) { if (val1 === val2) { if (val1 !== 0) return true; return strict ? objectIs2(val1, val2) : true; } if (strict) { if (_typeof(val1) !== "object") { return typeof val1 === "number" && numberIsNaN(val1) && numberIsNaN(val2); } if (_typeof(val2) !== "object" || val1 === null || val2 === null) { return false; } if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { return false; } } else { if (val1 === null || _typeof(val1) !== "object") { if (val2 === null || _typeof(val2) !== "object") { return val1 == val2; } return false; } if (val2 === null || _typeof(val2) !== "object") { return false; } } var val1Tag = objectToString(val1); var val2Tag = objectToString(val2); if (val1Tag !== val2Tag) { return false; } if (Array.isArray(val1)) { if (val1.length !== val2.length) { return false; } var keys1 = getOwnNonIndexProperties(val1); var keys2 = getOwnNonIndexProperties(val2); if (keys1.length !== keys2.length) { return false; } return keyCheck(val1, val2, strict, memos, kIsArray, keys1); } if (val1Tag === "[object Object]") { if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) { return false; } } if (isDate(val1)) { if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { return false; } } else if (isRegExp(val1)) { if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { return false; } } else if (isNativeError(val1) || val1 instanceof Error) { if (val1.message !== val2.message || val1.name !== val2.name) { return false; } } else if (isArrayBufferView(val1)) { if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { if (!areSimilarFloatArrays(val1, val2)) { return false; } } else if (!areSimilarTypedArrays(val1, val2)) { return false; } var _keys = getOwnNonIndexProperties(val1); var _keys2 = getOwnNonIndexProperties(val2); if (_keys.length !== _keys2.length) { return false; } return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); } else if (isSet(val1)) { if (!isSet(val2) || val1.size !== val2.size) { return false; } return keyCheck(val1, val2, strict, memos, kIsSet); } else if (isMap(val1)) { if (!isMap(val2) || val1.size !== val2.size) { return false; } return keyCheck(val1, val2, strict, memos, kIsMap); } else if (isAnyArrayBuffer(val1)) { if (!areEqualArrayBuffers(val1, val2)) { return false; } } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { return false; } return keyCheck(val1, val2, strict, memos, kNoIterator); } function getEnumerables(val, keys) { return keys.filter(function(k) { return propertyIsEnumerable(val, k); }); } function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { if (arguments.length === 5) { aKeys = Object.keys(val1); var bKeys = Object.keys(val2); if (aKeys.length !== bKeys.length) { return false; } } var i = 0; for (; i < aKeys.length; i++) { if (!hasOwnProperty2(val2, aKeys[i])) { return false; } } if (strict && arguments.length === 5) { var symbolKeysA = objectGetOwnPropertySymbols(val1); if (symbolKeysA.length !== 0) { var count2 = 0; for (i = 0; i < symbolKeysA.length; i++) { var key = symbolKeysA[i]; if (propertyIsEnumerable(val1, key)) { if (!propertyIsEnumerable(val2, key)) { return false; } aKeys.push(key); count2++; } else if (propertyIsEnumerable(val2, key)) { return false; } } var symbolKeysB = objectGetOwnPropertySymbols(val2); if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count2) { return false; } } else { var _symbolKeysB = objectGetOwnPropertySymbols(val2); if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { return false; } } } if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { return true; } if (memos === void 0) { memos = { val1: /* @__PURE__ */ new Map(), val2: /* @__PURE__ */ new Map(), position: 0 }; } else { var val2MemoA = memos.val1.get(val1); if (val2MemoA !== void 0) { var val2MemoB = memos.val2.get(val2); if (val2MemoB !== void 0) { return val2MemoA === val2MemoB; } } memos.position++; } memos.val1.set(val1, memos.position); memos.val2.set(val2, memos.position); var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); memos.val1.delete(val1); memos.val2.delete(val2); return areEq; } function setHasEqualElement(set, val1, strict, memo) { var setValues = arrayFromSet(set); for (var i = 0; i < setValues.length; i++) { var val2 = setValues[i]; if (innerDeepEqual(val1, val2, strict, memo)) { set.delete(val2); return true; } } return false; } function findLooseMatchingPrimitives(prim) { switch (_typeof(prim)) { case "undefined": return null; case "object": return void 0; case "symbol": return false; case "string": prim = +prim; case "number": if (numberIsNaN(prim)) { return false; } } return true; } function setMightHaveLoosePrim(a, b, prim) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) return altValue; return b.has(altValue) && !a.has(altValue); } function mapMightHaveLoosePrim(a, b, prim, item, memo) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) { return altValue; } var curB = b.get(altValue); if (curB === void 0 && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { return false; } return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); } function setEquiv(a, b, strict, memo) { var set = null; var aValues = arrayFromSet(a); for (var i = 0; i < aValues.length; i++) { var val = aValues[i]; if (_typeof(val) === "object" && val !== null) { if (set === null) { set = /* @__PURE__ */ new Set(); } set.add(val); } else if (!b.has(val)) { if (strict) return false; if (!setMightHaveLoosePrim(a, b, val)) { return false; } if (set === null) { set = /* @__PURE__ */ new Set(); } set.add(val); } } if (set !== null) { var bValues = arrayFromSet(b); for (var _i = 0; _i < bValues.length; _i++) { var _val = bValues[_i]; if (_typeof(_val) === "object" && _val !== null) { if (!setHasEqualElement(set, _val, strict, memo)) return false; } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) { return false; } } return set.size === 0; } return true; } function mapHasEqualEntry(set, map2, key1, item1, strict, memo) { var setValues = arrayFromSet(set); for (var i = 0; i < setValues.length; i++) { var key2 = setValues[i]; if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map2.get(key2), strict, memo)) { set.delete(key2); return true; } } return false; } function mapEquiv(a, b, strict, memo) { var set = null; var aEntries = arrayFromMap(a); for (var i = 0; i < aEntries.length; i++) { var _aEntries$i = _slicedToArray(aEntries[i], 2), key = _aEntries$i[0], item1 = _aEntries$i[1]; if (_typeof(key) === "object" && key !== null) { if (set === null) { set = /* @__PURE__ */ new Set(); } set.add(key); } else { var item2 = b.get(key); if (item2 === void 0 && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) { if (strict) return false; if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; if (set === null) { set = /* @__PURE__ */ new Set(); } set.add(key); } } } if (set !== null) { var bEntries = arrayFromMap(b); for (var _i2 = 0; _i2 < bEntries.length; _i2++) { var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), key = _bEntries$_i[0], item = _bEntries$_i[1]; if (_typeof(key) === "object" && key !== null) { if (!mapHasEqualEntry(set, a, key, item, strict, memo)) return false; } else if (!strict && (!a.has(key) || !innerDeepEqual(a.get(key), item, false, memo)) && !mapHasEqualEntry(set, a, key, item, false, memo)) { return false; } } return set.size === 0; } return true; } function objEquiv(a, b, strict, keys, memos, iterationType) { var i = 0; if (iterationType === kIsSet) { if (!setEquiv(a, b, strict, memos)) { return false; } } else if (iterationType === kIsMap) { if (!mapEquiv(a, b, strict, memos)) { return false; } } else if (iterationType === kIsArray) { for (; i < a.length; i++) { if (hasOwnProperty2(a, i)) { if (!hasOwnProperty2(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { return false; } } else if (hasOwnProperty2(b, i)) { return false; } else { var keysA = Object.keys(a); for (; i < keysA.length; i++) { var key = keysA[i]; if (!hasOwnProperty2(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { return false; } } if (keysA.length !== Object.keys(b).length) { return false; } return true; } } } for (i = 0; i < keys.length; i++) { var _key = keys[i]; if (!innerDeepEqual(a[_key], b[_key], strict, memos)) { return false; } } return true; } function isDeepEqual(val1, val2) { return innerDeepEqual(val1, val2, kLoose); } function isDeepStrictEqual(val1, val2) { return innerDeepEqual(val1, val2, kStrict); } comparisons = { isDeepEqual, isDeepStrictEqual }; return comparisons; } var hasRequiredAssert; function requireAssert() { if (hasRequiredAssert) return assert$1.exports; hasRequiredAssert = 1; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof2(obj2) { return typeof obj2; }; } else { _typeof = function _typeof2(obj2) { return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = requireErrors(), _require$codes = _require.codes, ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; var AssertionError = requireAssertion_error(); var _require2 = util, inspect = _require2.inspect; var _require$types = util.types, isPromise = _require$types.isPromise, isRegExp = _require$types.isRegExp; var objectAssign = Object.assign ? Object.assign : requireEs6ObjectAssign().assign; var objectIs2 = Object.is ? Object.is : requireObjectIs(); var isDeepEqual; var isDeepStrictEqual; function lazyLoadComparison() { var comparison = requireComparisons(); isDeepEqual = comparison.isDeepEqual; isDeepStrictEqual = comparison.isDeepStrictEqual; } var warned = false; var assert2 = assert$1.exports = ok2; var NO_EXCEPTION_SENTINEL = {}; function innerFail(obj) { if (obj.message instanceof Error) throw obj.message; throw new AssertionError(obj); } function fail(actual, expected, message, operator, stackStartFn) { var argsLen = arguments.length; var internalMessage; if (argsLen === 0) { internalMessage = "Failed"; } else if (argsLen === 1) { message = actual; actual = void 0; } else { if (warned === false) { warned = true; var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console); warn("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.", "DeprecationWarning", "DEP0094"); } if (argsLen === 2) operator = "!="; } if (message instanceof Error) throw message; var errArgs = { actual, expected, operator: operator === void 0 ? "fail" : operator, stackStartFn: stackStartFn || fail }; if (message !== void 0) { errArgs.message = message; } var err2 = new AssertionError(errArgs); if (internalMessage) { err2.message = internalMessage; err2.generatedMessage = true; } throw err2; } assert2.fail = fail; assert2.AssertionError = AssertionError; function innerOk(fn, argLen, value, message) { if (!value) { var generatedMessage = false; if (argLen === 0) { generatedMessage = true; message = "No value argument passed to `assert.ok()`"; } else if (message instanceof Error) { throw message; } var err2 = new AssertionError({ actual: value, expected: true, message, operator: "==", stackStartFn: fn }); err2.generatedMessage = generatedMessage; throw err2; } } function ok2() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } innerOk.apply(void 0, [ok2, args.length].concat(args)); } assert2.ok = ok2; assert2.equal = function equal(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (actual != expected) { innerFail({ actual, expected, message, operator: "==", stackStartFn: equal }); } }; assert2.notEqual = function notEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (actual == expected) { innerFail({ actual, expected, message, operator: "!=", stackStartFn: notEqual }); } }; assert2.deepEqual = function deepEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (isDeepEqual === void 0) lazyLoadComparison(); if (!isDeepEqual(actual, expected)) { innerFail({ actual, expected, message, operator: "deepEqual", stackStartFn: deepEqual }); } }; assert2.notDeepEqual = function notDeepEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (isDeepEqual === void 0) lazyLoadComparison(); if (isDeepEqual(actual, expected)) { innerFail({ actual, expected, message, operator: "notDeepEqual", stackStartFn: notDeepEqual }); } }; assert2.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (isDeepEqual === void 0) lazyLoadComparison(); if (!isDeepStrictEqual(actual, expected)) { innerFail({ actual, expected, message, operator: "deepStrictEqual", stackStartFn: deepStrictEqual }); } }; assert2.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (isDeepEqual === void 0) lazyLoadComparison(); if (isDeepStrictEqual(actual, expected)) { innerFail({ actual, expected, message, operator: "notDeepStrictEqual", stackStartFn: notDeepStrictEqual }); } } assert2.strictEqual = function strictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (!objectIs2(actual, expected)) { innerFail({ actual, expected, message, operator: "strictEqual", stackStartFn: strictEqual }); } }; assert2.notStrictEqual = function notStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (objectIs2(actual, expected)) { innerFail({ actual, expected, message, operator: "notStrictEqual", stackStartFn: notStrictEqual }); } }; var Comparison = function Comparison2(obj, keys, actual) { var _this = this; _classCallCheck(this, Comparison2); keys.forEach(function(key) { if (key in obj) { if (actual !== void 0 && typeof actual[key] === "string" && isRegExp(obj[key]) && obj[key].test(actual[key])) { _this[key] = actual[key]; } else { _this[key] = obj[key]; } } }); }; function compareExceptionKey(actual, expected, key, message, keys, fn) { if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { if (!message) { var a = new Comparison(actual, keys); var b = new Comparison(expected, keys, actual); var err2 = new AssertionError({ actual: a, expected: b, operator: "deepStrictEqual", stackStartFn: fn }); err2.actual = actual; err2.expected = expected; err2.operator = fn.name; throw err2; } innerFail({ actual, expected, message, operator: fn.name, stackStartFn: fn }); } } function expectedException(actual, expected, msg, fn) { if (typeof expected !== "function") { if (isRegExp(expected)) return expected.test(actual); if (arguments.length === 2) { throw new ERR_INVALID_ARG_TYPE("expected", ["Function", "RegExp"], expected); } if (_typeof(actual) !== "object" || actual === null) { var err2 = new AssertionError({ actual, expected, message: msg, operator: "deepStrictEqual", stackStartFn: fn }); err2.operator = fn.name; throw err2; } var keys = Object.keys(expected); if (expected instanceof Error) { keys.push("name", "message"); } else if (keys.length === 0) { throw new ERR_INVALID_ARG_VALUE("error", expected, "may not be an empty object"); } if (isDeepEqual === void 0) lazyLoadComparison(); keys.forEach(function(key) { if (typeof actual[key] === "string" && isRegExp(expected[key]) && expected[key].test(actual[key])) { return; } compareExceptionKey(actual, expected, key, msg, keys, fn); }); return true; } if (expected.prototype !== void 0 && actual instanceof expected) { return true; } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function getActual(fn) { if (typeof fn !== "function") { throw new ERR_INVALID_ARG_TYPE("fn", "Function", fn); } try { fn(); } catch (e) { return e; } return NO_EXCEPTION_SENTINEL; } function checkIsPromise(obj) { return isPromise(obj) || obj !== null && _typeof(obj) === "object" && typeof obj.then === "function" && typeof obj.catch === "function"; } function waitForActual(promiseFn) { return Promise.resolve().then(function() { var resultPromise; if (typeof promiseFn === "function") { resultPromise = promiseFn(); if (!checkIsPromise(resultPromise)) { throw new ERR_INVALID_RETURN_VALUE("instance of Promise", "promiseFn", resultPromise); } } else if (checkIsPromise(promiseFn)) { resultPromise = promiseFn; } else { throw new ERR_INVALID_ARG_TYPE("promiseFn", ["Function", "Promise"], promiseFn); } return Promise.resolve().then(function() { return resultPromise; }).then(function() { return NO_EXCEPTION_SENTINEL; }).catch(function(e) { return e; }); }); } function expectsError(stackStartFn, actual, error, message) { if (typeof error === "string") { if (arguments.length === 4) { throw new ERR_INVALID_ARG_TYPE("error", ["Object", "Error", "Function", "RegExp"], error); } if (_typeof(actual) === "object" && actual !== null) { if (actual.message === error) { throw new ERR_AMBIGUOUS_ARGUMENT("error/message", 'The error message "'.concat(actual.message, '" is identical to the message.')); } } else if (actual === error) { throw new ERR_AMBIGUOUS_ARGUMENT("error/message", 'The error "'.concat(actual, '" is identical to the message.')); } message = error; error = void 0; } else if (error != null && _typeof(error) !== "object" && typeof error !== "function") { throw new ERR_INVALID_ARG_TYPE("error", ["Object", "Error", "Function", "RegExp"], error); } if (actual === NO_EXCEPTION_SENTINEL) { var details = ""; if (error && error.name) { details += " (".concat(error.name, ")"); } details += message ? ": ".concat(message) : "."; var fnType = stackStartFn.name === "rejects" ? "rejection" : "exception"; innerFail({ actual: void 0, expected: error, operator: stackStartFn.name, message: "Missing expected ".concat(fnType).concat(details), stackStartFn }); } if (error && !expectedException(actual, error, message, stackStartFn)) { throw actual; } } function expectsNoError(stackStartFn, actual, error, message) { if (actual === NO_EXCEPTION_SENTINEL) return; if (typeof error === "string") { message = error; error = void 0; } if (!error || expectedException(actual, error)) { var details = message ? ": ".concat(message) : "."; var fnType = stackStartFn.name === "doesNotReject" ? "rejection" : "exception"; innerFail({ actual, expected: error, operator: stackStartFn.name, message: "Got unwanted ".concat(fnType).concat(details, "\n") + 'Actual message: "'.concat(actual && actual.message, '"'), stackStartFn }); } throw actual; } assert2.throws = function throws(promiseFn) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args)); }; assert2.rejects = function rejects(promiseFn) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return waitForActual(promiseFn).then(function(result) { return expectsError.apply(void 0, [rejects, result].concat(args)); }); }; assert2.doesNotThrow = function doesNotThrow(fn) { for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); }; assert2.doesNotReject = function doesNotReject(fn) { for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { args[_key5 - 1] = arguments[_key5]; } return waitForActual(fn).then(function(result) { return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); }); }; assert2.ifError = function ifError(err2) { if (err2 !== null && err2 !== void 0) { var message = "ifError got unwanted exception: "; if (_typeof(err2) === "object" && typeof err2.message === "string") { if (err2.message.length === 0 && err2.constructor) { message += err2.constructor.name; } else { message += err2.message; } } else { message += inspect(err2); } var newErr = new AssertionError({ actual: err2, expected: null, operator: "ifError", message, stackStartFn: ifError }); var origStack = err2.stack; if (typeof origStack === "string") { var tmp2 = origStack.split("\n"); tmp2.shift(); var tmp1 = newErr.stack.split("\n"); for (var i = 0; i < tmp2.length; i++) { var pos = tmp1.indexOf(tmp2[i]); if (pos !== -1) { tmp1 = tmp1.slice(0, pos); break; } } newErr.stack = "".concat(tmp1.join("\n"), "\n").concat(tmp2.join("\n")); } throw newErr; } }; function strict() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } innerOk.apply(void 0, [strict, args.length].concat(args)); } assert2.strict = objectAssign(strict, assert2, { equal: assert2.strictEqual, deepEqual: assert2.deepStrictEqual, notEqual: assert2.notStrictEqual, notDeepEqual: assert2.notDeepStrictEqual }); assert2.strict.strict = assert2.strict; return assert$1.exports; } var assertExports = requireAssert(); const assert = /* @__PURE__ */ getDefaultExportFromCjs(assertExports); class Characters { static unicode() { return { hbar: "─", vbar: "│", xbar: "┼", vbar_break: "·", vbar_gap: "⋮", uarrow: "▲", rarrow: "▶", ltop: "╭", mtop: "┬", rtop: "╮", lbot: "╰", mbot: "┴", rbot: "╯", lbox: "[", rbox: "]", lcross: "├", rcross: "┤", underbar: "┬", underline: "─" }; } static ascii() { return { hbar: "-", vbar: "|", xbar: "+", vbar_break: "*", vbar_gap: ":", uarrow: "^", rarrow: ">", ltop: ",", mtop: "v", rtop: ".", lbot: "`", mbot: "^", rbot: "'", lbox: "[", rbox: "]", lcross: "|", rcross: "|", underbar: "|", underline: "^" }; } } var LabelKind = /* @__PURE__ */ ((LabelKind2) => { LabelKind2["Inline"] = "Inline"; LabelKind2["Multiline"] = "Multiline"; return LabelKind2; })(LabelKind || {}); class LabelInfo { constructor(kind, label) { this.kind = kind; this.label = label; } } class ReportBuilder { constructor(kind, code, msg, note, help, location, labels, config) { this.kind = kind; this.code = code; this.msg = msg; this.note = note; this.help = help; this.location = location; this.labels = labels; this.config = config; } /// Give this report a numerical code that may be used to more precisely look up the error in documentation. with_code(code) { this.code = some(code.toString().padStart(2, "0")); return this; } /// Set the message of this report. set_message(msg) { this.msg = some(msg); } /// Add a message to this report. with_message(msg) { this.msg = some(msg); return this; } /// Set the note of this report. set_note(note) { this.note = some(note); } /// Set the note of this report. with_note(note) { this.set_note(note); return this; } /// Set the help message of this report. set_help(note) { this.help = some(note); } /// Set the help message of this report. with_help(note) { this.set_help(note); return this; } /// Add a label to the report. add_label(label) { this.labels.push(label); } /// Add multiple labels to the report. add_labels(labels) { this.labels.push(...labels); } /// Add a label to the report. with_label(label) { this.add_label(label); return this; } /// Use the given [`Config`] to determine diagnostic attributes. with_config(config) { this.config = config; return this; } /// Finish building the [`Report`]. finish() { const r = new Report( this.kind, this.code, this.msg, this.note, this.help, this.location, this.labels, this.config ); return r; } } class ReportKind { constructor(...args) { } fmt(f) { if (this instanceof ReportKind.Error) return write(f.buf, "Error"); if (this instanceof ReportKind.Warning) return write(f.buf, "Warning"); if (this instanceof ReportKind.Advice) return write(f.buf, "Advice"); if (this instanceof ReportKind.Custom) return write(f.buf, "{}", this.s); throw "invalid ReportKind"; } static { this.Error = class Error extends ReportKind { }; } static { this.Warning = class Warning extends ReportKind { }; } static { this.Advice = class Advice extends ReportKind { }; } static { this.Custom = class Custom extends ReportKind { constructor(s, color) { super(); this.s = s; this.color = color; } }; } } class Cache { static from(init) { if (Source.is(init)) return init; if (FnCache.is(init)) return init; const [id, source] = init; return new IdSource(source.lines(), source.len(), init); } } class Line { constructor(_offset, _len, _chars) { this._offset = _offset; this._len = _len; this._chars = _chars; } /// Get the offset of this line in the original [`Source`] (i.e: the number of characters that precede it). offset() { return this._offset; } /// Get the character length of this line. len() { return this._len; } /// Get the offset span of this line in the original [`Source`]. span() { return new Range(this.offset(), this.offset() + this.len()); } /// Return an iterator over the characters in the line, excluding trailing whitespace. chars() { return this._chars; } } class Source { constructor(_lines, _len) { this._lines = _lines; this._len = _len; } /// Generate a [`Source`] from the given [`str`]. /// /// Note that this function can be expensive for long strings. Use an implementor of [`Cache`] where possible. static from(s, ...args) { let offset = 0; const lines = s.split("\n").map((line) => { let l = new Line( offset, line.length + 1, // line.chars().count() + 1, line.trimEnd() ); offset += l.len(); return l; }); return new Source(lines, offset); } /// Get the length of the total number of characters in the source. len() { return this._len; } /// Return an iterator over the characters in the source. chars() { return this.lines().map((l) => l.chars()).flat(); } /// Get access to a specific, zero-indexed [`Line`]. line(idx) { const line = this.lines()[idx]; return line === void 0 ? none() : some(line); } /// Return an iterator over the [`Line`]s in this source. lines() { return this._lines; } /// Get the line that the given offset appears on, and the line/column numbers of the offset. /// /// Note that the line/column numbers are zero-indexed. get_offset_line(offset) { if (offset <= this.len()) { let idx = binary_search_by_key(this.lines(), offset, (line2) => line2.offset()).unwrap_or_else( (idx2) => Math.max(0, idx2.saturating_sub(1)) ); let line = this.lines()[idx]; assert( line && offset >= line.offset(), format("offset = {}, line.offset = {}, idx = {}", offset, line?.offset() ?? Infinity, idx) ); const os = line.offset(); return some([line, idx, offset - os]); } else { return none(); } } /// Get the range of lines that this span runs across. /// /// The resulting range is guaranteed to contain valid line indices (i.e: those that can be used for /// [`Source::line`]). get_line_range(span) { let start = this.get_offset_line(span.start).map_or(0, ([_, l, __]) => l); let end = this.get_offset_line(span.end.saturating_sub(1).max(span.start)).map_or( this.lines().length, ([_, l, __]) => l + 1 ); return new Range(start, end); } fetch(_) { return ok(this); } display(_) { return none(); } static is(other) { return other instanceof Source; } } class IdSource extends Source { constructor(_lines, _len, data) { super(_lines, _len); this.data = data; } fetch(id) { return id === this.data[0] ? ok(this.data[1]) : err(format("Failed to fetch source '{}'", id)); } display(id) { return some(new Display(id)); } } class FnCache { constructor(sources2, get) { this.sources = sources2; this.get = get; } /// Create a new [`FnCache`] with the given fetch function. static new(get) { return new FnCache(/* @__PURE__ */ new Map(), get); } /// Pre-insert a selection of [`Source`]s into this cache. with_sources(sources2) { for (let [id, src2] of sources2) { this.sources.set(id, src2); } return this; } fetch(id) { const entry = this.sources.get(id); if (entry !== void 0) return ok(entry); const source = Source.from(this.get(id)); this.sources.set(id, source); return ok(source); } display(id) { return some(id); } static is(other) { return other instanceof FnCache; } } class SourceGroup { constructor(src_id, span, labels) { this.src_id = src_id; this.span = span; this.labels = labels; } } class Report { constructor(kind, code, msg, note, help, location, labels, config) { this.kind = kind; this.code = code; this.msg = msg; this.note = note; this.help = help; this.location = location; this.labels = labels; this.config = config; } /// Begin building a new [`Report`]. static build(kind, src_id, offset) { const builder = new ReportBuilder( kind, none(), none(), none(), none(), [Option.from(src_id), offset], [], Config.default() ); return builder; } /// Write this diagnostic out to `stderr`. eprint(init) { const cache = Cache.from(init); this.write(cache, stderrWriter); } /// Write this diagnostic out to `stdout`. /// /// In most cases, [`Report::eprint`] is the /// ['more correct'](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) function to use. print(init) { const cache = Cache.from(init); this.write(cache, stdoutWriter); } printTo(init, writer) { const cache = Cache.from(init); this.write(cache, writer); } get_source_groups(cache) { let groups = []; for (let label of this.labels) { let src_display = cache.display(label.span.source()); let res = cache.fetch(label.span.source()); if (res.is_err()) { console.error("Unable to fetch source '{}': {}", src_display, res.unwrap()); continue; } let src2 = res.unwrap(); assert(label.span.start <= label.span.end, "Label start is after its end"); let start_line = src2.get_offset_line(label.span.start).map(([_, l, __]) => l); let end_line = src2.get_offset_line(label.span.end.saturating_sub(1).max(label.span.start)).map(([_, l, __]) => l); let label_info = new LabelInfo( start_line.equal(end_line) ? LabelKind.Inline : LabelKind.Multiline, label ); const group = groups.find((g2) => g2.src_id === label.span.source()); if (group) { group.span.start = group.span.start.min(label.span.start); group.span.end = group.span.end.max(label.span.end); group.labels.push(label_info); } else { groups.push( new SourceGroup(label.span.source(), new Range(label.span.start, label.span.end), [ label_info ]) ); } } return groups; } /// Write this diagnostic to an implementor of [`Write`]. /// /// If you wish to write to `stderr` or `stdout`, you can do so via [`Report::eprint`] or [`Report::print`] respectively. write(cache, w) { let draw = match(this.config.char_set, [ [CharSet.Unicode, () => Characters.unicode()], [CharSet.Ascii, () => Characters.ascii()] ]); let code = this.code ? format("[E{}] ", this.code) : ""; let id = format("{}{}:", code, this.kind.name); let kind_color = match(this.kind, [ [ReportKind.Error, () => this.config.error_color()], [ReportKind.Warning, () => this.config.warning_color()], [ReportKind.Advice, () => this.config.advice_color()], [ReportKind.Custom, (kind) => kind.color] ]); writeln(w, "{} {}", new Display(id).fg(kind_color), new Show(this.msg)); let groups = this.get_source_groups(cache); let filtered_groups = groups.filter_map(({ span, src_id }) => { let src_name = cache.display(src_id).map((d) => d.toString()).unwrap_or_else(() => ""); let res = cache.fetch(src_id); if (res.is_err()) { eprintln("Unable to fetch source {}: {}", src_name, res.unwrap()); return null; } let src2 = res.unwrap(); let line_range = src2.get_line_range(span); let iter = rangeIter(1, Infinity); iter = map(iter, (x) => Math.pow(10, x)); iter = take_while(iter, (x) => { const d = Math.floor(line_range.end / x); return d !== 0; }); const cnt = count(iter); return cnt + 1; }); let line_no_width = max(filtered_groups) ?? 0; let groups_len = groups.length; for (let [group_idx, { src_id, span, labels }] of enumerate(groups)) { let src_name = cache.display(src_id).map((d) => d.toString()).unwrap_or_else(() => ""); let res = cache.fetch(src_id); if (res.is_err()) { eprintln("Unable to fetch source {}: {}", src_name, res.unwrap()); continue; } let src2 = res.unwrap(); let line_range = src2.get_line_range(span); let location = src_id === this.location[0] ? this.location[1] : labels[0].label.span.start; let [line_no, col_no] = src2.get_offset_line(location).map(([_, idx, col]) => [format("{}", idx + 1), format("{}", col + 1)]).unwrap_or_else(() => ["?", "?"]); let line_ref = format(":{}:{}", line_no, col_no); writeln( w, "{}{}{}{}{}{}{}", new Show([" ", line_no_width + 2]), new Display(group_idx === 0 ? draw.ltop : draw.lcross).fg(this.config.margin_color()), new Display(draw.hbar).fg(this.config.margin_color()), new Display(draw.lbox).fg(this.config.margin_color()), src_name, line_ref, new Display(draw.rbox).fg(this.config.margin_color()) ); if (!this.config.compact) { writeln( w, "{}{}", new Show([" ", line_no_width + 2]), new Display(draw.vbar).fg(this.config.margin_color()) ); } class LineLabel { constructor(col, label, multi, draw_msg) { this.col = col; this.label = label; this.multi = multi; this.draw_msg = draw_msg; this.col = Math.floor(col); } } let multi_labels = []; for (let label_info of labels) { if (label_info.kind === LabelKind.Multiline) { multi_labels.push(label_info.label); } } multi_labels.sort((a, b) => b.span.len() - a.span.len()); let write_margin = (w2, idx, is_line, is_ellipsis2, draw_labels, report_row, line_labels, margin_label) => { let line_no_margin; if (is_line && !is_ellipsis2) { let line_no2 = format("{}", idx + 1); line_no_margin = format( "{}{} {}", new Show([" ", line_no_width - line_no2.length]), line_no2, draw.vbar ); } else { line_no_margin = format( "{}{}", new Show([" ", line_no_width + 1]), is_ellipsis2 ? draw.vbar_gap : draw.vbar_break ); } write( w2, " {}{}", new Display(line_no_margin).fg(this.config.margin_color()), new Show(some(" ").filter(() => !this.config.compact)) ); if (draw_labels) { for (let col of range(0, multi_labels.length + bton(multi_labels.length > 0))) { let corner = none(); let hbar = none(); let vbar = none(); let margin_ptr = none(); let multi_label = Option.from(multi_labels[col]); let line_span = src2.line(idx).unwrap().span(); for (let [i, label] of enumerate( multi_labels.slice(0, (col + 1).min(multi_labels.length)) )) { let margin = margin_label.filter((m) => label === m.label); if (label.span.start <= line_span.end && label.span.end > line_span.start) { let is_parent = i !== col; let is_start = line_span.contains(label.span.start); let is_end = line_span.contains(label.last_offset()); if (margin.filter(() => is_line).is_some()) { let _margin = margin.filter(() => is_line); margin_ptr = some([_margin.unwrap(), is_start]); } else if (!is_start && (!is_end || is_line)) { vbar = vbar.or(some(label).filter(() => !is_parent)); } else { if (report_row.is_some() && report_row.map_or(false, (o) => isNumber(o[0]) && isBoolean(o[1]))) { let [_report_row, is_arrow] = report_row.unwrap(); let label_row = Option.from( line_labels.enumerate().find(([_, l]) => label === l.label) ).map_or(0, ([r, _]) => r); if (_report_row === label_row) { if (margin.is_some()) { vbar = some(margin.unwrap().label).filter(() => col === i); if (is_start) { continue; } } if (is_arrow) { hbar = some(label); if (!is_parent) { corner = some([label, is_start]); } } else if (!is_start) { vbar = vbar.or(some(label).filter(() => !is_parent)); } } else { vbar = vbar.or( some(label).filter( () => !is_parent && !!(bton(is_start) ^ bton(_report_row < label_row)) ) ); } } } } } if (margin_ptr.is_some() && margin_ptr.map_or(false, (o) => Label.is(o[0]) && isBoolean(o[1])) && is_line) { let [margin, _is_start] = margin_ptr.unwrap(); if (_is_start) { let is_col = multi_label.map_or(false, (ml) => ml === margin.label); let is_limit = col + 1 === multi_labels.length; if (!is_col && !is_limit) { hbar = hbar.or(some(margin.label)); } } } hbar = hbar.filter( (l) => margin_label.map_or(true, (margin) => margin.label !== l) || !is_line ); const getCorners = () => { if (corner.is_some() && Array.isArray(corner.unwrap()) && Label.is(corner.unwrap()[0]) && isBoolean(corner.unwrap()[1])) { let [label, is_start] = corner.unwrap(); return [ new Display(is_start ? draw.ltop : draw.lbot).fg(label.color), new Display(draw.hbar).fg(label.color) ]; } else if (hbar.filter(() => vbar.is_some() && !this.config.cross_gap).is_some()) { let label = hbar.filter(() => vbar.is_some() && !this.config.cross_gap).unwrap(); return [ new Display(draw.xbar).fg(label.color), new Display(draw.hbar).fg(label.color) ]; } else if (hbar.is_some()) { let label = hbar.unwrap(); const d = new Display(draw.hbar).fg(label.color); return [d, d]; } else if (vbar.is_some()) { let label = vbar.unwrap(); let vb = new Display(is_ellipsis2 ? draw.vbar_gap : draw.vbar); return [vb.fg(label.color), new Display(" ").fg(none())]; } else if (margin_ptr.is_some() && is_line) { let [margin, is_start] = margin_ptr.unwrap(); let is_col = multi_label.map_or(false, (ml) => ml === margin.label); let is_limit = col === multi_labels.length; return [ new Display( is_limit ? draw.rarrow : is_col ? is_start ? draw.ltop : draw.lcross : draw.hbar ).fg(margin.label.color), new Display(!is_limit ? draw.hbar : " ").fg(margin.label.color) ]; } else { const d = new Display(" ").fg(none()); return [d, d]; } }; let [a, b] = getCorners(); write(w2, "{}", a); if (!this.config.compact) { write(w2, "{}", b); } } } }; let is_ellipsis = false; for (let idx of range(line_range.start, line_range.end)) { if (src2.line(idx).is_none()) { continue; } let line = src2.line(idx).unwrap(); const f_labels = multi_labels.enumerate().filter_map(([_i, label]) => { let is_start = line.span().contains(label.span.start); let is_end = line.span().contains(label.last_offset()); if (is_start) { return new LineLabel(label.span.start - line.offset(), label, true, false); } else if (is_end) { return new LineLabel(label.last_offset() - line.offset(), label, true, true); } else { return null; } }); let margin_label = min_by_key(f_labels, (ll) => ll.col); let line_labels = multi_labels.enumerate().filter_map(([_i, label]) => { let is_start = line.span().contains(label.span.start); let is_end = line.span().contains(label.last_offset()); if (is_start && margin_label.map_or(true, (m) => label !== m.label)) { return new LineLabel( label.span.start - line.offset(), label, true, false // Multi-line spans don;t have their messages drawn at the start ); } else if (is_end) { return new LineLabel( label.last_offset() - line.offset(), label, true, true // Multi-line spans have their messages drawn at the end ); } else { return null; } }); for (let label_info of labels.filter( (l) => l.label.span.start >= line.span().start && l.label.span.end <= line.span().end )) { if (label_info.kind === LabelKind.Inline) { let col = match(this.config.label_attach, [ [LabelAttach.Start, () => label_info.label.span.start], [ LabelAttach.Middle, () => (label_info.label.span.start + label_info.label.span.end) / 2 ], [LabelAttach.End, () => label_info.label.last_offset()] ]); line_labels.push( new LineLabel( col.max(label_info.label.span.start) - line.offset(), label_info.label, false, true ) ); } } if (line_labels.length === 0 && margin_label.is_none()) { let within_label = multi_labels.some((label) => label.span.contains(line.span().start)); if (!is_ellipsis && within_label) { is_ellipsis = true; } else { if (!this.config.compact && !is_ellipsis) { write_margin(w, idx, false, is_ellipsis, false, none(), [], none()); write(w, "\n"); } is_ellipsis = true; continue; } } else { is_ellipsis = false; } sort_by_key(line_labels, (ll) => ll.label.order); sort_by_key(line_labels, (ll) => ll.col); sort_by_key(line_labels, (ll) => bton(!ll.label.span.start)); let arrow_end_space = this.config.compact ? 1 : 2; let arrow_len = line_labels.reduce((l, ll) => { return ll.multi ? line.len() : l.max(ll.label.span.end.saturating_sub(line.offset())); }, 0) + arrow_end_space; let get_vbar = (col, row) => Option.from( line_labels.enumerate().filter( ([_, ll]) => ll.label.msg.is_some() && margin_label.map_or(true, (m) => ll.label !== m.label) ).find( ([j, ll]) => ll.col === col && (row <= j && !ll.multi || row <= j && ll.multi) ) ).map(([_, ll]) => ll); let get_highlight = (col) => min_by_key( margin_label.iter().map((ll) => ll.label).chain(multi_labels.map((l) => l)).chain(line_labels.map((l) => l.label)).filter((l) => l.span.contains(line.offset() + col)), // Prioritise displaying smaller spans // .min_by_key((l: any) => [-l.priority, l.span.len()]); // .min_by_key(l => l.span.len())); (l) => -l.priority + l.span.len() ); let get_underline = (col) => min_by_key( line_labels.filter((ll) => { return this.config.underlines && // Underlines only occur for inline spans (highlighting can occur for all spans) !ll.multi && ll.label.span.contains(line.offset() + col); }), // Prioritise displaying smaller spans // .min_by_key(ll => [-ll.label.priority, ll.label.span.len()]); // .min_by_key(ll => ll.label.span.len())); // ll => -ll.label.priority + ll.label.span.len()); (ll) => ll.label.span.len() ); write_margin(w, idx, true, is_ellipsis, true, none(), line_labels, margin_label); if (!is_ellipsis) { for (let [col, _c] of enumerate(line.chars())) { let highlight = get_highlight(col); let color = highlight.is_some() ? highlight.unwrap().color : this.config.unimportant_color(); let [c2, width] = this.config.char_width(_c, col); for (let _ of range(0, width)) { write(w, "{}", new Display(c2).fg(color)); } } } write(w, "\n"); for (let row of range(0, line_labels.length)) { let line_label = line_labels[row]; if (!this.config.compact) { write_margin( w, idx, false, is_ellipsis, true, some([row, false]), line_labels, margin_label ); let chars2 = line.chars(); let { next: next2 } = makeIter(chars2); for (let col of range(0, arrow_len)) { let width = next2().map_or(1, (c22) => this.config.char_width(c22, col)[1]); let vbar = get_vbar(col, row); let underline = get_underline(col).filter(() => row === 0); const getCTailOuter = () => { if (vbar.is_some()) { let vbar_ll = vbar.unwrap(); const getCTailInner = () => { if (underline.is_some()) { if (vbar_ll.label.span.len() <= 1) { return [draw.underbar, draw.underline]; } else if (line.offset() + col === vbar_ll.label.span.start) { return [draw.ltop, draw.underbar]; } else if (line.offset() + col === vbar_ll.label.last_offset()) { return [draw.rtop, draw.underbar]; } else { return [draw.underbar, draw.underline]; } } else if (vbar_ll.multi && row === 0 && this.config.multiline_arrows) { return [draw.uarrow, new Display(" ")]; } else { return [draw.vbar, new Display(" ")]; } }; let [c22, tail2] = getCTailInner(); return [ new Display(c22).fg(vbar_ll.label.color), new Display(tail2).fg(vbar_ll.label.color) ]; } else if (underline.is_some()) { let underline_ll = underline.unwrap(); return [ new Display(draw.underline).fg(underline_ll.label.color), new Display(draw.underline).fg(underline_ll.label.color) ]; } else { return [new Display(" ").fg(none()), new Display(" ").fg(none())]; } }; let [c2, tail] = getCTailOuter(); for (let i of range(0, width)) { write(w, "{}", i === 0 ? c2 : tail); } } write(w, "\n"); } write_margin( w, idx, false, is_ellipsis, true, some([row, true]), line_labels, margin_label ); let chars = line.chars(); let { next } = makeIter(chars); for (let col of range(0, arrow_len)) { let n = next(); let width = n.map_or(1, (c22) => this.config.char_width(c22, col)[1]); let is_hbar = ((col > line_label.col ? 1 : 0) ^ (line_label.multi ? 1 : 0) || line_label.label.msg.is_some() && line_label.draw_msg && col > line_label.col) && line_label.label.msg.is_some(); const getctail = () => { if (col === line_label.col && line_label.label.msg.is_some() && margin_label.map_or(true, (m) => line_label.label != m.label)) { return [ new Display( line_label.multi ? line_label.draw_msg ? draw.mbot : draw.rbot : draw.lbot ).fg(line_label.label.color), new Display(draw.hbar).fg(line_label.label.color) ]; } else if (get_vbar(col, row).filter(() => col != line_label.col || line_label.label.msg.is_some()).is_some()) { let vbar_ll = get_vbar(col, row).filter(() => col != line_label.col || line_label.label.msg.is_some()).unwrap(); if (!this.config.cross_gap && is_hbar) { return [ new Display(draw.xbar).fg(line_label.label.color), new Display(" ").fg(line_label.label.color) ]; } else if (is_hbar) { let d = new Display(draw.hbar).fg(line_label.label.color); return [d, d]; } else { return [ new Display( vbar_ll.multi && row === 0 && this.config.compact ? draw.uarrow : draw.vbar ).fg(vbar_ll.label.color), new Display(" ").fg(line_label.label.color) ]; } } else if (is_hbar) { let d = new Display(draw.hbar).fg(line_label.label.color); return [d, d]; } else { let d = new Display(" ").fg(none()); return [d, d]; } }; let [c2, tail] = getctail(); if (width > 0) { write(w, "{}", c2); } for (let _ of range(1, width)) { write(w, "{}", tail); } } if (line_label.draw_msg) { write(w, " {}", new Show(line_label.label.msg)); } write(w, "\n"); } } let is_final_group = group_idx + 1 === groups_len; if (this.help.is_some() && is_final_group) { let note = this.help.unwrap(); if (!this.config.compact) { write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, "\n"); } write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, "{}: {}\n", new Display("Help").fg(this.config.note_color()), note); } if (this.note.is_some() && is_final_group) { let note = this.note.unwrap(); if (!this.config.compact) { write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, "\n"); } write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, "{}: {}\n", new Display("Note").fg(this.config.note_color()), note); } if (!this.config.compact) { if (is_final_group) { let final_margin = format("{}{}", new Show([draw.hbar, line_no_width + 2]), draw.rbot); writeln(w, "{}", new Display(final_margin).fg(this.config.margin_color())); } else { writeln( w, "{}{}", new Show([" ", line_no_width + 2]), new Display(draw.vbar).fg(this.config.margin_color()) ); } } } if (groups_len === 0) { if (this.help.is_some()) { let note = this.help.unwrap(); if (!this.config.compact) { write(w, "\n"); } write(w, "{}: {}\n", new Display("Help").fg(this.config.note_color()), note); } if (this.note.is_some()) { let note = this.note.unwrap(); if (!this.config.compact) { write(w, "\n"); } write(w, "{}: {}\n", new Display("Note").fg(this.config.note_color()), note); } } } } function match(kind, matchers) { for (let [type2, then] of matchers) { if (kind === type2) return then(kind); } return null; } function* enumerate(groups) { for (let i = 0; i < groups.length; i++) yield [i, groups[i]]; return; } function* map(a, f) { let value = a.next(); while (value.done === false) { yield f(value.value); value = a.next(); } } function* take_while(a, p) { let current = a.next(); while (current.done === false) { if (p(current.value)) yield current.value; else break; current = a.next(); } } function to_array(a) { let result = []; let current = a.next(); while (current.done === false) { result.push(current.value); current = a.next(); } return result; } function count(a) { return to_array(a).length; } function makeIter(arr) { let cursor = 0; let next = () => { const res = arr[cursor++]; if (res === void 0) return none(); return some(res); }; return { next, cursor }; } var ansi_up = {}; (function(exports) { (function(root, factory2) { if (typeof exports.nodeName !== "string") { factory2(exports); } else { var exp = {}; factory2(exp); root.AnsiUp = exp.default; } })(commonjsGlobal, function(exports2) { var __makeTemplateObject2 = this && this.__makeTemplateObject || function(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var PacketKind; (function(PacketKind2) { PacketKind2[PacketKind2["EOS"] = 0] = "EOS"; PacketKind2[PacketKind2["Text"] = 1] = "Text"; PacketKind2[PacketKind2["Incomplete"] = 2] = "Incomplete"; PacketKind2[PacketKind2["ESC"] = 3] = "ESC"; PacketKind2[PacketKind2["Unknown"] = 4] = "Unknown"; PacketKind2[PacketKind2["SGR"] = 5] = "SGR"; PacketKind2[PacketKind2["OSCURL"] = 6] = "OSCURL"; })(PacketKind || (PacketKind = {})); var AnsiUp2 = function() { function AnsiUp3() { this.VERSION = "5.1.0"; this.setup_palettes(); this._use_classes = false; this.bold = false; this.italic = false; this.underline = false; this.fg = this.bg = null; this._buffer = ""; this._url_whitelist = { "http": 1, "https": 1 }; } Object.defineProperty(AnsiUp3.prototype, "use_classes", { get: function() { return this._use_classes; }, set: function(arg) { this._use_classes = arg; }, enumerable: false, configurable: true }); Object.defineProperty(AnsiUp3.prototype, "url_whitelist", { get: function() { return this._url_whitelist; }, set: function(arg) { this._url_whitelist = arg; }, enumerable: false, configurable: true }); AnsiUp3.prototype.setup_palettes = function() { var _this = this; this.ansi_colors = [ [ { rgb: [0, 0, 0], class_name: "ansi-black" }, { rgb: [187, 0, 0], class_name: "ansi-red" }, { rgb: [0, 187, 0], class_name: "ansi-green" }, { rgb: [187, 187, 0], class_name: "ansi-yellow" }, { rgb: [0, 0, 187], class_name: "ansi-blue" }, { rgb: [187, 0, 187], class_name: "ansi-magenta" }, { rgb: [0, 187, 187], class_name: "ansi-cyan" }, { rgb: [255, 255, 255], class_name: "ansi-white" } ], [ { rgb: [85, 85, 85], class_name: "ansi-bright-black" }, { rgb: [255, 85, 85], class_name: "ansi-bright-red" }, { rgb: [0, 255, 0], class_name: "ansi-bright-green" }, { rgb: [255, 255, 85], class_name: "ansi-bright-yellow" }, { rgb: [85, 85, 255], class_name: "ansi-bright-blue" }, { rgb: [255, 85, 255], class_name: "ansi-bright-magenta" }, { rgb: [85, 255, 255], class_name: "ansi-bright-cyan" }, { rgb: [255, 255, 255], class_name: "ansi-bright-white" } ] ]; this.palette_256 = []; this.ansi_colors.forEach(function(palette) { palette.forEach(function(rec) { _this.palette_256.push(rec); }); }); var levels = [0, 95, 135, 175, 215, 255]; for (var r = 0; r < 6; ++r) { for (var g2 = 0; g2 < 6; ++g2) { for (var b = 0; b < 6; ++b) { var col = { rgb: [levels[r], levels[g2], levels[b]], class_name: "truecolor" }; this.palette_256.push(col); } } } var grey_level = 8; for (var i = 0; i < 24; ++i, grey_level += 10) { var gry = { rgb: [grey_level, grey_level, grey_level], class_name: "truecolor" }; this.palette_256.push(gry); } }; AnsiUp3.prototype.escape_txt_for_html = function(txt) { return txt.replace(/[&<>"']/gm, function(str) { if (str === "&") return "&"; if (str === "<") return "<"; if (str === ">") return ">"; if (str === '"') return """; if (str === "'") return "'"; }); }; AnsiUp3.prototype.append_buffer = function(txt) { var str = this._buffer + txt; this._buffer = str; }; AnsiUp3.prototype.get_next_packet = function() { var pkt = { kind: PacketKind.EOS, text: "", url: "" }; var len = this._buffer.length; if (len == 0) return pkt; var pos = this._buffer.indexOf("\x1B"); if (pos == -1) { pkt.kind = PacketKind.Text; pkt.text = this._buffer; this._buffer = ""; return pkt; } if (pos > 0) { pkt.kind = PacketKind.Text; pkt.text = this._buffer.slice(0, pos); this._buffer = this._buffer.slice(pos); return pkt; } if (pos == 0) { if (len == 1) { pkt.kind = PacketKind.Incomplete; return pkt; } var next_char = this._buffer.charAt(1); if (next_char != "[" && next_char != "]") { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } if (next_char == "[") { if (!this._csi_regex) { this._csi_regex = rgx(__makeTemplateObject2(["\n ^ # beginning of line\n #\n # First attempt\n (?: # legal sequence\n \x1B[ # CSI\n ([<-?]?) # private-mode char\n ([d;]*) # any digits or semicolons\n ([ -/]? # an intermediate modifier\n [@-~]) # the command\n )\n | # alternate (second attempt)\n (?: # illegal sequence\n \x1B[ # CSI\n [ -~]* # anything legal\n ([\0-:]) # anything illegal\n )\n "], ["\n ^ # beginning of line\n #\n # First attempt\n (?: # legal sequence\n \\x1b\\[ # CSI\n ([\\x3c-\\x3f]?) # private-mode char\n ([\\d;]*) # any digits or semicolons\n ([\\x20-\\x2f]? # an intermediate modifier\n [\\x40-\\x7e]) # the command\n )\n | # alternate (second attempt)\n (?: # illegal sequence\n \\x1b\\[ # CSI\n [\\x20-\\x7e]* # anything legal\n ([\\x00-\\x1f:]) # anything illegal\n )\n "])); } var match2 = this._buffer.match(this._csi_regex); if (match2 === null) { pkt.kind = PacketKind.Incomplete; return pkt; } if (match2[4]) { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } if (match2[1] != "" || match2[3] != "m") pkt.kind = PacketKind.Unknown; else pkt.kind = PacketKind.SGR; pkt.text = match2[2]; var rpos = match2[0].length; this._buffer = this._buffer.slice(rpos); return pkt; } if (next_char == "]") { if (len < 4) { pkt.kind = PacketKind.Incomplete; return pkt; } if (this._buffer.charAt(2) != "8" || this._buffer.charAt(3) != ";") { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } if (!this._osc_st) { this._osc_st = rgxG(__makeTemplateObject2(["\n (?: # legal sequence\n (\x1B\\) # ESC | # alternate\n (\x07) # BEL (what xterm did)\n )\n | # alternate (second attempt)\n ( # illegal sequence\n [\0-] # anything illegal\n | # alternate\n [\b-] # anything illegal\n | # alternate\n [-] # anything illegal\n )\n "], ["\n (?: # legal sequence\n (\\x1b\\\\) # ESC \\\n | # alternate\n (\\x07) # BEL (what xterm did)\n )\n | # alternate (second attempt)\n ( # illegal sequence\n [\\x00-\\x06] # anything illegal\n | # alternate\n [\\x08-\\x1a] # anything illegal\n | # alternate\n [\\x1c-\\x1f] # anything illegal\n )\n "])); } this._osc_st.lastIndex = 0; { var match_1 = this._osc_st.exec(this._buffer); if (match_1 === null) { pkt.kind = PacketKind.Incomplete; return pkt; } if (match_1[3]) { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } } { var match_2 = this._osc_st.exec(this._buffer); if (match_2 === null) { pkt.kind = PacketKind.Incomplete; return pkt; } if (match_2[3]) { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } } if (!this._osc_regex) { this._osc_regex = rgx(__makeTemplateObject2(["\n ^ # beginning of line\n #\n \x1B]8; # OSC Hyperlink\n [ -:<-~]* # params (excluding ;)\n ; # end of params\n ([!-~]{0,512}) # URL capture\n (?: # ST\n (?:\x1B\\) # ESC | # alternate\n (?:\x07) # BEL (what xterm did)\n )\n ([ -~]+) # TEXT capture\n \x1B]8;; # OSC Hyperlink End\n (?: # ST\n (?:\x1B\\) # ESC | # alternate\n (?:\x07) # BEL (what xterm did)\n )\n "], ["\n ^ # beginning of line\n #\n \\x1b\\]8; # OSC Hyperlink\n [\\x20-\\x3a\\x3c-\\x7e]* # params (excluding ;)\n ; # end of params\n ([\\x21-\\x7e]{0,512}) # URL capture\n (?: # ST\n (?:\\x1b\\\\) # ESC \\\n | # alternate\n (?:\\x07) # BEL (what xterm did)\n )\n ([\\x20-\\x7e]+) # TEXT capture\n \\x1b\\]8;; # OSC Hyperlink End\n (?: # ST\n (?:\\x1b\\\\) # ESC \\\n | # alternate\n (?:\\x07) # BEL (what xterm did)\n )\n "])); } var match2 = this._buffer.match(this._osc_regex); if (match2 === null) { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } pkt.kind = PacketKind.OSCURL; pkt.url = match2[1]; pkt.text = match2[2]; var rpos = match2[0].length; this._buffer = this._buffer.slice(rpos); return pkt; } } }; AnsiUp3.prototype.ansi_to_html = function(txt) { this.append_buffer(txt); var blocks = []; while (true) { var packet = this.get_next_packet(); if (packet.kind == PacketKind.EOS || packet.kind == PacketKind.Incomplete) break; if (packet.kind == PacketKind.ESC || packet.kind == PacketKind.Unknown) continue; if (packet.kind == PacketKind.Text) blocks.push(this.transform_to_html(this.with_state(packet))); else if (packet.kind == PacketKind.SGR) this.process_ansi(packet); else if (packet.kind == PacketKind.OSCURL) blocks.push(this.process_hyperlink(packet)); } return blocks.join(""); }; AnsiUp3.prototype.with_state = function(pkt) { return { bold: this.bold, italic: this.italic, underline: this.underline, fg: this.fg, bg: this.bg, text: pkt.text }; }; AnsiUp3.prototype.process_ansi = function(pkt) { var sgr_cmds = pkt.text.split(";"); while (sgr_cmds.length > 0) { var sgr_cmd_str = sgr_cmds.shift(); var num = parseInt(sgr_cmd_str, 10); if (isNaN(num) || num === 0) { this.fg = this.bg = null; this.bold = false; this.italic = false; this.underline = false; } else if (num === 1) { this.bold = true; } else if (num === 3) { this.italic = true; } else if (num === 4) { this.underline = true; } else if (num === 22) { this.bold = false; } else if (num === 23) { this.italic = false; } else if (num === 24) { this.underline = false; } else if (num === 39) { this.fg = null; } else if (num === 49) { this.bg = null; } else if (num >= 30 && num < 38) { this.fg = this.ansi_colors[0][num - 30]; } else if (num >= 40 && num < 48) { this.bg = this.ansi_colors[0][num - 40]; } else if (num >= 90 && num < 98) { this.fg = this.ansi_colors[1][num - 90]; } else if (num >= 100 && num < 108) { this.bg = this.ansi_colors[1][num - 100]; } else if (num === 38 || num === 48) { if (sgr_cmds.length > 0) { var is_foreground = num === 38; var mode_cmd = sgr_cmds.shift(); if (mode_cmd === "5" && sgr_cmds.length > 0) { var palette_index = parseInt(sgr_cmds.shift(), 10); if (palette_index >= 0 && palette_index <= 255) { if (is_foreground) this.fg = this.palette_256[palette_index]; else this.bg = this.palette_256[palette_index]; } } if (mode_cmd === "2" && sgr_cmds.length > 2) { var r = parseInt(sgr_cmds.shift(), 10); var g2 = parseInt(sgr_cmds.shift(), 10); var b = parseInt(sgr_cmds.shift(), 10); if (r >= 0 && r <= 255 && (g2 >= 0 && g2 <= 255) && (b >= 0 && b <= 255)) { var c2 = { rgb: [r, g2, b], class_name: "truecolor" }; if (is_foreground) this.fg = c2; else this.bg = c2; } } } } } }; AnsiUp3.prototype.transform_to_html = function(fragment) { var txt = fragment.text; if (txt.length === 0) return txt; txt = this.escape_txt_for_html(txt); if (!fragment.bold && !fragment.italic && !fragment.underline && fragment.fg === null && fragment.bg === null) return txt; var styles2 = []; var classes = []; var fg = fragment.fg; var bg = fragment.bg; if (fragment.bold) styles2.push("font-weight:bold"); if (fragment.italic) styles2.push("font-style:italic"); if (fragment.underline) styles2.push("text-decoration:underline"); if (!this._use_classes) { if (fg) styles2.push("color:rgb(" + fg.rgb.join(",") + ")"); if (bg) styles2.push("background-color:rgb(" + bg.rgb + ")"); } else { if (fg) { if (fg.class_name !== "truecolor") { classes.push(fg.class_name + "-fg"); } else { styles2.push("color:rgb(" + fg.rgb.join(",") + ")"); } } if (bg) { if (bg.class_name !== "truecolor") { classes.push(bg.class_name + "-bg"); } else { styles2.push("background-color:rgb(" + bg.rgb.join(",") + ")"); } } } var class_string = ""; var style_string = ""; if (classes.length) class_string = ' class="' + classes.join(" ") + '"'; if (styles2.length) style_string = ' style="' + styles2.join(";") + '"'; return "" + txt + ""; }; AnsiUp3.prototype.process_hyperlink = function(pkt) { var parts = pkt.url.split(":"); if (parts.length < 1) return ""; if (!this._url_whitelist[parts[0]]) return ""; var result = '' + this.escape_txt_for_html(pkt.text) + ""; return result; }; return AnsiUp3; }(); function rgx(tmplObj) { var regexText = tmplObj.raw[0]; var wsrgx = /^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm; var txt2 = regexText.replace(wsrgx, ""); return new RegExp(txt2); } function rgxG(tmplObj) { var regexText = tmplObj.raw[0]; var wsrgx = /^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm; var txt2 = regexText.replace(wsrgx, ""); return new RegExp(txt2, "g"); } Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = AnsiUp2; }); })(ansi_up); const AnsiUp = /* @__PURE__ */ getDefaultExportFromCjs(ansi_up); function nicerError(e) { if (e.code == 1070) { return "Static/public methods are not supported on traits"; } return e.messageText.toString(); } class TagNode { constructor(name, tsNode) { this.tsNode = tsNode; this.name = name; this.tags = []; this.edges = []; this.edgesOther = []; } } class TagGraph { constructor() { this.nodes = []; } addNode(name, tsNode) { let node2 = this.nodes.find((node22) => node22.name === name); if (!node2) { node2 = new TagNode(name, tsNode); this.nodes.push(node2); } } addEdge(from, to) { let fromNode = this.nodes.find((node2) => node2.name === from); if (!fromNode) { fromNode = new TagNode(from); this.nodes.push(fromNode); } let toNode = this.nodes.find((node2) => node2.name === to); if (!toNode) { toNode = new TagNode(to); this.nodes.push(toNode); } fromNode.edges.push(toNode); toNode.edgesOther.push(fromNode); } addTag(name, tag) { let node2 = this.nodes.find((node22) => node22.name === name); if (!node2) { node2 = new TagNode(name); this.nodes.push(node2); } node2.tags.push(tag); } getNode(name) { return this.nodes.find((node2) => node2.name === name); } resolveTagSourceChain(name, tag) { const node2 = this.getNode(name); if (!node2) return []; const chain = [name]; const visited = /* @__PURE__ */ new Set(); const queue = [node2]; while (queue.length > 0) { const node22 = queue.shift(); if (visited.has(node22.name)) continue; visited.add(node22.name); let nodeWithTag = null; for (const edge of node22.edgesOther) { if (edge.tags.includes(tag)) { nodeWithTag = edge; break; } } if (nodeWithTag) { chain.push(nodeWithTag.name); queue.push(nodeWithTag); } else { return chain; } } return []; } propagateTags() { let changed = true; while (changed) { changed = false; for (const node2 of this.nodes) { for (const edge of node2.edges) { for (const tag of node2.tags) { if (!edge.tags.includes(tag)) { edge.tags.push(tag); changed = true; } } } } } } } const quickCache = { "/file.ts": { outputFiles: [ { name: "/file.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/std___std_all"], function (require, exports, std___std_all_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n var globalVarGet = std___std_all_1.globalVarGet;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/std_math.ts": { outputFiles: [ { name: "/std_math.js", writeByteOrderMark: false, text: `var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; define(["require", "exports", "./static-math"], function (require, exports, static_math_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unpack2x16float = exports.unpack2x16unorm = exports.unpack2x16snorm = exports.unpack4x8unorm = exports.unpack4x8snorm = exports.pack2x16float = exports.pack2x16unorm = exports.pack2x16snorm = exports.pack4x8unorm = exports.pack4x8snorm = exports.bitcast = exports.ddyCoarse = exports.ddxCoarse = exports.ddyFine = exports.ddxFine = exports.ddy = exports.ddx = exports.discard = exports.workgroupUniformLoad = exports.storageBarrier = exports.workgroupBarrier = exports.atomic = exports.atomic_internal = exports.FM = exports.intifyVector = exports.swizzle = exports.testDocComment = exports.makeVector = exports.not = exports.or = exports.and = exports.gte = exports.gt = exports.lte = exports.lt = exports.neq = exports.eq = exports.saturate = exports.clamp = exports.max = exports.min = exports.smoothstep = exports.step = exports.radians = exports.degrees = exports.refract = exports.reflect = exports.normalize = exports.distance = exports.dist = exports.length = exports.bilerp = exports.lerp = exports.dot = exports.cross = exports.pingpong = exports.rand3 = exports.rand2 = exports.rand = exports.wrap = exports.frac = exports.inversesqrt = exports.sqrt = exports.log10 = exports.log2 = exports.log = exports.exp = exports.atanh = exports.asinh = exports.acosh = exports.tanh = exports.sinh = exports.cosh = exports.atan2 = exports.atan = exports.asin = exports.acos = exports.tan = exports.sin = exports.cos = exports.sign = exports.round = exports.ceil = exports.floor = exports.abs = exports.positive = exports.negate = exports.bitnot = exports.rshift = exports.lshift = exports.bitxor = exports.bitor = exports.bitand = exports.mod = exports.pow = exports.div = exports.mul = exports.transpose = exports.inverse = exports.sub = exports.add = exports.uint8 = exports.uint4 = exports.uint3 = exports.uint2 = exports.int4 = exports.int3 = exports.int2 = exports.float4 = exports.float3 = exports.float2 = exports.uint = exports.int = exports.float = exports.float4x4 = exports.float3x3 = exports.float2x2 = void 0; function isVector(v) { return Array.isArray(v); } function isScalar(v) { return typeof v === 'number'; } function isMatrix(v) { return !!v.__matrix; } /** @shadeup=glsl(mat2) @shadeup=wgsl(mat2x2) */ function float2x2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var arr = [0, 0, 0, 0]; if (args.length === 4) { arr = __spreadArray([], args, true); } applyMatrix2x2Methods(arr); return arr; } exports.float2x2 = float2x2; /** @shadeup=glsl(mat3) @shadeup=wgsl(mat3x3) */ function float3x3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var arr = [0, 0, 0, 0, 0, 0, 0, 0, 0]; if (args.length === 9) { arr = __spreadArray([], args, true); } applyMatrix3x3Methods(arr); return arr; } exports.float3x3 = float3x3; function applyMatrix4x4Methods(arr) { arr.__matrix = 4; arr.__index = function (index) { var out_arr = [arr[index * 4], arr[index * 4 + 1], arr[index * 4 + 2], arr[index * 4 + 3]]; out_arr.__index = function (index_inner) { return out_arr[index_inner]; }; out_arr.__index_assign = function (index_inner, value) { arr[index * 4 + index_inner] = value; }; out_arr.__index_assign_op = function (op_fn, index_inner, value) { arr[index * 4 + index_inner] = op_fn(arr[index * 4 + index_inner], value); }; return out_arr; }; arr.__index_assign = function (index, value) { arr[index * 4] = value[0]; arr[index * 4 + 1] = value[1]; arr[index * 4 + 2] = value[2]; arr[index * 4 + 3] = value[3]; }; arr.__index_assign_op = function (op_fn, index, value) { arr[index * 4] = op_fn(arr[index * 4], value[0]); arr[index * 4 + 1] = op_fn(arr[index * 4 + 1], value[1]); arr[index * 4 + 2] = op_fn(arr[index * 4 + 2], value[2]); arr[index * 4 + 3] = op_fn(arr[index * 4 + 3], value[3]); }; } window.applyMatrix4x4Methods = applyMatrix4x4Methods; function applyMatrix3x3Methods(arr) { arr.__matrix = 3; arr.__index = function (index) { var out_arr = [arr[index * 3], arr[index * 3 + 1], arr[index * 3 + 2]]; out_arr.__index = function (index_inner) { return out_arr[index_inner]; }; out_arr.__index_assign = function (index_inner, value) { arr[index * 3 + index_inner] = value; }; out_arr.__index_assign_op = function (op_fn, index_inner, value) { arr[index * 3 + index_inner] = op_fn(arr[index * 3 + index_inner], value); }; return out_arr; }; arr.__index_assign = function (index, value) { arr[index * 3] = value[0]; arr[index * 3 + 1] = value[1]; arr[index * 3 + 2] = value[2]; }; arr.__index_assign_op = function (op_fn, index, value) { arr[index * 3] = op_fn(arr[index * 3], value[0]); arr[index * 3 + 1] = op_fn(arr[index * 3 + 1], value[1]); arr[index * 3 + 2] = op_fn(arr[index * 3 + 2], value[2]); }; } window.applyMatrix3x3Methods = applyMatrix3x3Methods; function applyMatrix2x2Methods(arr) { arr.__matrix = 2; arr.__index = function (index) { var out_arr = [arr[index * 2], arr[index * 2 + 1]]; out_arr.__index = function (index_inner) { return out_arr[index_inner]; }; out_arr.__index_assign = function (index_inner, value) { arr[index * 2 + index_inner] = value; }; out_arr.__index_assign_op = function (op_fn, index_inner, value) { arr[index * 2 + index_inner] = op_fn(arr[index * 2 + index_inner], value); }; return out_arr; }; arr.__index_assign = function (index, value) { arr[index * 2] = value[0]; arr[index * 2 + 1] = value[1]; }; arr.__index_assign_op = function (op_fn, index, value) { arr[index * 2] = op_fn(arr[index * 2], value[0]); arr[index * 2 + 1] = op_fn(arr[index * 2 + 1], value[1]); }; } window.applyMatrix2x2Methods = applyMatrix2x2Methods; /** @shadeup=glsl(mat4) @shadeup=wgsl(mat4x4) */ function float4x4() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; if (args.length === 16) { arr = __spreadArray([], args, true); } applyMatrix4x4Methods(arr); return arr; } exports.float4x4 = float4x4; /** @shadeup=glsl(float) @shadeup=wgsl(f32) */ function float(x) { return x; } exports.float = float; /** @shadeup=glsl(int) @shadeup=wgsl(i32) */ function int(x) { return (x | 0); } exports.int = int; /** @shadeup=glsl(uint) @shadeup=wgsl(u32) */ function uint(x) { return (x >>> 0); } exports.uint = uint; /** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */ function float2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat(); } exports.float2 = float2; /** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */ function float3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat(); } exports.float3 = float3; /** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */ function float4() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat(); } exports.float4 = float4; /** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */ function int2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x | 0; }); } exports.int2 = int2; /** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */ function int3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x | 0; }); } exports.int3 = int3; /** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */ function int4() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x | 0; }); } exports.int4 = int4; function uint2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x >>> 0; }); } exports.uint2 = uint2; function uint3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x >>> 0; }); } exports.uint3 = uint3; function uint4() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x >>> 0; }); } exports.uint4 = uint4; function uint8(x) { return ((x >>> 0) & 0xff); } exports.uint8 = uint8; function componentMath(a, b, f) { var aIsScalar = isScalar(a); var bIsScalar = isScalar(b); if (aIsScalar && bIsScalar) { return f(a, b); } if (!aIsScalar && !bIsScalar) { if (a.length !== b.length) { throw new Error('Cannot perform component-wise math on vectors of different lengths'); } // return a.map((a, i) => f(a, b[i])) as vector; if (a.length == 2) { return [f(a[0], b[0]), f(a[1], b[1])]; } else if (a.length == 3) { return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2])]; } else if (a.length == 4) { return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2]), f(a[3], b[3])]; } } else if (!aIsScalar && bIsScalar) { if (a.length == 2) { return [f(a[0], b), f(a[1], b)]; } else if (a.length == 3) { return [f(a[0], b), f(a[1], b), f(a[2], b)]; } else if (a.length == 4) { return [f(a[0], b), f(a[1], b), f(a[2], b), f(a[3], b)]; } } else if (!bIsScalar && aIsScalar) { if (b.length == 2) { return [f(a, b[0]), f(a, b[1])]; } else if (b.length == 3) { return [f(a, b[0]), f(a, b[1]), f(a, b[2])]; } else if (b.length == 4) { return [f(a, b[0]), f(a, b[1]), f(a, b[2]), f(a, b[3])]; } } throw new Error('Cannot perform component-wise math on a scalar and a vector'); } function componentMathSingular(a, f) { if (isScalar(a)) { return f(a); } if (isVector(a)) { return a.map(function (a, i) { return f(a); }); } throw new Error('Cannot perform component-wise math on a scalar and a vector'); } function cCall(cb, a, b) { return componentMath(a, b, function (a, b) { return a + b; }); } function componentOp(cb) { return function (a, b) { return componentMath(a, b, cb); }; } function componentOpMatch(cb) { return function (a, b) { return componentMath(a, b, cb); }; } function componentOpSingular(cb) { return function (a) { return componentMathSingular(a, cb); }; } function componentOpSingularFloat(cb) { return function (a) { return componentMathSingular(a, cb); }; } /** @shadeup=univ(!$0$ + $1$)*/ var add = function (a, b) { if (typeof a === 'string' && typeof b === 'string') { return "".concat(a).concat(b); } else { var addOp = componentOp(function (a, b) { return a + b; }); var v = addOp(a, b); return v; } }; exports.add = add; /** @shadeup=univ(!$0$ - $1$)*/ exports.sub = componentOp(function (a, b) { return a - b; }); function matrixMul(a, b) { // Multiply two square matrices of the same dimension row-major var dimension = a.__matrix; var out; if (dimension === 2) { out = float2x2(); } else if (dimension === 3) { out = float3x3(); } else if (dimension === 4) { var a00 = a[0 * 4 + 0]; var a01 = a[0 * 4 + 1]; var a02 = a[0 * 4 + 2]; var a03 = a[0 * 4 + 3]; var a10 = a[1 * 4 + 0]; var a11 = a[1 * 4 + 1]; var a12 = a[1 * 4 + 2]; var a13 = a[1 * 4 + 3]; var a20 = a[2 * 4 + 0]; var a21 = a[2 * 4 + 1]; var a22 = a[2 * 4 + 2]; var a23 = a[2 * 4 + 3]; var a30 = a[3 * 4 + 0]; var a31 = a[3 * 4 + 1]; var a32 = a[3 * 4 + 2]; var a33 = a[3 * 4 + 3]; var b00 = b[0 * 4 + 0]; var b01 = b[0 * 4 + 1]; var b02 = b[0 * 4 + 2]; var b03 = b[0 * 4 + 3]; var b10 = b[1 * 4 + 0]; var b11 = b[1 * 4 + 1]; var b12 = b[1 * 4 + 2]; var b13 = b[1 * 4 + 3]; var b20 = b[2 * 4 + 0]; var b21 = b[2 * 4 + 1]; var b22 = b[2 * 4 + 2]; var b23 = b[2 * 4 + 3]; var b30 = b[3 * 4 + 0]; var b31 = b[3 * 4 + 1]; var b32 = b[3 * 4 + 2]; var b33 = b[3 * 4 + 3]; return float4x4(b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30, b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31, b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32, b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33, b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30, b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31, b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32, b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33, b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30, b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31, b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32, b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33, b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30, b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31, b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32, b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33); out = float4x4(); } for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { var sum = float(0); for (var k = 0; k < dimension; k++) { sum += float(a[i * dimension + k] * b[k * dimension + j]); } out[i * dimension + j] = sum; } } return out; if (a.__matrix === 2 && b.__matrix === 2) { var a00_1 = a[0]; var a01_1 = a[1]; var a10_1 = a[2]; var a11_1 = a[3]; var b00_1 = b[0]; var b01_1 = b[1]; var b10_1 = b[2]; var b11_1 = b[3]; var v = float2x2(a00_1 * b00_1 + a01_1 * b10_1, a00_1 * b01_1 + a01_1 * b11_1, a10_1 * b00_1 + a11_1 * b10_1, a10_1 * b01_1 + a11_1 * b11_1); return v; } else if (a.__matrix === 3 && b.__matrix === 3) { var a00_2 = a[0]; var a01_2 = a[1]; var a02_1 = a[2]; var a10_2 = a[3]; var a11_2 = a[4]; var a12_1 = a[5]; var a20_1 = a[6]; var a21_1 = a[7]; var a22_1 = a[8]; var b00_2 = b[0]; var b01_2 = b[1]; var b02_1 = b[2]; var b10_2 = b[3]; var b11_2 = b[4]; var b12_1 = b[5]; var b20_1 = b[6]; var b21_1 = b[7]; var b22_1 = b[8]; var v = float3x3(a00_2 * b00_2 + a01_2 * b10_2 + a02_1 * b20_1, a00_2 * b01_2 + a01_2 * b11_2 + a02_1 * b21_1, a00_2 * b02_1 + a01_2 * b12_1 + a02_1 * b22_1, a10_2 * b00_2 + a11_2 * b10_2 + a12_1 * b20_1, a10_2 * b01_2 + a11_2 * b11_2 + a12_1 * b21_1, a10_2 * b02_1 + a11_2 * b12_1 + a12_1 * b22_1, a20_1 * b00_2 + a21_1 * b10_2 + a22_1 * b20_1, a20_1 * b01_2 + a21_1 * b11_2 + a22_1 * b21_1, a20_1 * b02_1 + a21_1 * b12_1 + a22_1 * b22_1); return v; } else if (a.__matrix === 4 && b.__matrix === 4) { var a00_3 = a[0]; var a01_3 = a[1]; var a02_2 = a[2]; var a03_1 = a[3]; var a10_3 = a[4]; var a11_3 = a[5]; var a12_2 = a[6]; var a13_1 = a[7]; var a20_2 = a[8]; var a21_2 = a[9]; var a22_2 = a[10]; var a23_1 = a[11]; var a30_1 = a[12]; var a31_1 = a[13]; var a32_1 = a[14]; var a33_1 = a[15]; var b00_3 = b[0]; var b01_3 = b[1]; var b02_2 = b[2]; var b03_1 = b[3]; var b10_3 = b[4]; var b11_3 = b[5]; var b12_2 = b[6]; var b13_1 = b[7]; var b20_2 = b[8]; var b21_2 = b[9]; var b22_2 = b[10]; var b23_1 = b[11]; var b30_1 = b[12]; var b31_1 = b[13]; var b32_1 = b[14]; var b33_1 = b[15]; var v = float4x4(a00_3 * b00_3 + a01_3 * b10_3 + a02_2 * b20_2 + a03_1 * b30_1, a00_3 * b01_3 + a01_3 * b11_3 + a02_2 * b21_2 + a03_1 * b31_1, a00_3 * b02_2 + a01_3 * b12_2 + a02_2 * b22_2 + a03_1 * b32_1, a00_3 * b03_1 + a01_3 * b13_1 + a02_2 * b23_1 + a03_1 * b33_1, a10_3 * b00_3 + a11_3 * b10_3 + a12_2 * b20_2 + a13_1 * b30_1, a10_3 * b01_3 + a11_3 * b11_3 + a12_2 * b21_2 + a13_1 * b31_1, a10_3 * b02_2 + a11_3 * b12_2 + a12_2 * b22_2 + a13_1 * b32_1, a10_3 * b03_1 + a11_3 * b13_1 + a12_2 * b23_1 + a13_1 * b33_1, a20_2 * b00_3 + a21_2 * b10_3 + a22_2 * b20_2 + a23_1 * b30_1, a20_2 * b01_3 + a21_2 * b11_3 + a22_2 * b21_2 + a23_1 * b31_1, a20_2 * b02_2 + a21_2 * b12_2 + a22_2 * b22_2 + a23_1 * b32_1, a20_2 * b03_1 + a21_2 * b13_1 + a22_2 * b23_1 + a23_1 * b33_1, a30_1 * b00_3 + a31_1 * b10_3 + a32_1 * b20_2 + a33_1 * b30_1, a30_1 * b01_3 + a31_1 * b11_3 + a32_1 * b21_2 + a33_1 * b31_1, a30_1 * b02_2 + a31_1 * b12_2 + a32_1 * b22_2 + a33_1 * b32_1, a30_1 * b03_1 + a31_1 * b13_1 + a32_1 * b23_1 + a33_1 * b33_1); return v; } else { throw new Error('Invalid matrix multiplication'); } } function matrixInversefloat2x2(m) { var a = m.__index(0)[0], b = m.__index(1)[0], c = m.__index(0)[1], d = m.__index(1)[1]; var det = a * d - b * c; if (det === 0) { throw new Error('Matrix determinant is zero'); } var detInv = 1.0 / det; return float2x2(d * detInv, -b * detInv, -c * detInv, a * detInv); } function matrixInversefloat3x3(m) { var n11 = m.__index(0)[0], n12 = m.__index(1)[0], n13 = m.__index(2)[0]; var n21 = m.__index(0)[1], n22 = m.__index(1)[1], n23 = m.__index(2)[1]; var n31 = m.__index(0)[2], n32 = m.__index(1)[2], n33 = m.__index(2)[2]; var t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13; var det = n11 * t11 + n21 * t12 + n31 * t13; if (det === 0) { throw new Error('Invalid matrix inverse'); } var detInv = 1 / det; var v = float3x3(t11 * detInv, (n31 * n23 - n33 * n21) * detInv, (n32 * n21 - n31 * n22) * detInv, t12 * detInv, (n33 * n11 - n31 * n13) * detInv, (n31 * n12 - n32 * n11) * detInv, t13 * detInv, (n21 * n13 - n23 * n11) * detInv, (n22 * n11 - n21 * n12) * detInv); return v; } function matrixInversefloat4x4(m) { var m00 = m[0 * 4 + 0]; var m01 = m[0 * 4 + 1]; var m02 = m[0 * 4 + 2]; var m03 = m[0 * 4 + 3]; var m10 = m[1 * 4 + 0]; var m11 = m[1 * 4 + 1]; var m12 = m[1 * 4 + 2]; var m13 = m[1 * 4 + 3]; var m20 = m[2 * 4 + 0]; var m21 = m[2 * 4 + 1]; var m22 = m[2 * 4 + 2]; var m23 = m[2 * 4 + 3]; var m30 = m[3 * 4 + 0]; var m31 = m[3 * 4 + 1]; var m32 = m[3 * 4 + 2]; var m33 = m[3 * 4 + 3]; var tmp_0 = m22 * m33; var tmp_1 = m32 * m23; var tmp_2 = m12 * m33; var tmp_3 = m32 * m13; var tmp_4 = m12 * m23; var tmp_5 = m22 * m13; var tmp_6 = m02 * m33; var tmp_7 = m32 * m03; var tmp_8 = m02 * m23; var tmp_9 = m22 * m03; var tmp_10 = m02 * m13; var tmp_11 = m12 * m03; var tmp_12 = m20 * m31; var tmp_13 = m30 * m21; var tmp_14 = m10 * m31; var tmp_15 = m30 * m11; var tmp_16 = m10 * m21; var tmp_17 = m20 * m11; var tmp_18 = m00 * m31; var tmp_19 = m30 * m01; var tmp_20 = m00 * m21; var tmp_21 = m20 * m01; var tmp_22 = m00 * m11; var tmp_23 = m10 * m01; var t0 = tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31 - (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31); var t1 = tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31 - (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31); var t2 = tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31 - (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31); var t3 = tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21 - (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21); var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3); if (d === 0) { throw new Error('Invalid matrix inverse'); } return float4x4(d * t0, d * t1, d * t2, d * t3, d * (tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30 - (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30)), d * (tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30 - (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30)), d * (tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30 - (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30)), d * (tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20 - (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20)), d * (tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33 - (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33)), d * (tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33 - (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33)), d * (tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33 - (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33)), d * (tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23 - (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23)), d * (tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12 - (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22)), d * (tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22 - (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02)), d * (tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02 - (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12)), d * (tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12 - (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02))); } function matrixTransposefloat2x2(m) { return float2x2(m.__index(0)[0], m.__index(1)[0], m.__index(0)[1], m.__index(1)[1]); } function matrixTransposefloat3x3(m) { return float3x3(m.__index(0)[0], m.__index(1)[0], m.__index(2)[0], m.__index(0)[1], m.__index(1)[1], m.__index(2)[1], m.__index(0)[2], m.__index(1)[2], m.__index(2)[2]); } function matrixTransposefloat4x4(m) { return float4x4(m.__index(0)[0], m.__index(1)[0], m.__index(2)[0], m.__index(3)[0], m.__index(0)[1], m.__index(1)[1], m.__index(2)[1], m.__index(3)[1], m.__index(0)[2], m.__index(1)[2], m.__index(2)[2], m.__index(3)[2], m.__index(0)[3], m.__index(1)[3], m.__index(2)[3], m.__index(3)[3]); } function matrixMul2x2float2(a, b) { var c = [0, 0]; for (var j = 0; j < 2; j++) { for (var i = 0; i < 2; i++) { c[i] += a[j * 2 + i] * b[j]; } } return c; } function matrixMul3x3float3(a, b) { var c = [0, 0, 0]; for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { c[i] += a[j * 3 + i] * b[j]; } } return c; } function matrixMul4x4float4(a, b) { var c = [0, 0, 0, 0]; for (var j = 0; j < 4; j++) { for (var i = 0; i < 4; i++) { c[i] += a[j * 4 + i] * b[j]; } } return c; } function matrixMulfloat22x2(a, b) { var c = [0, 0]; for (var j = 0; j < 2; j++) { for (var i = 0; i < 2; i++) { c[i] += a[j] * b[i * 2 + j]; } } return c; } function matrixMulfloat33x3(a, b) { var c = [0, 0, 0]; for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { c[i] += a[j] * b[i * 3 + j]; } } return c; } function matrixMulfloat44x4(a, b) { var c = [0, 0, 0, 0]; for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { c[i] += a[j] * b[i * 4 + j]; } } return c; } var mulFunc = componentOp(function (a, b) { return a * b; }); function inverse(a) { if (a.__matrix == 2) { return matrixInversefloat2x2(a); } else if (a.__matrix == 3) { return matrixInversefloat3x3(a); } else if (a.__matrix == 4) { return matrixInversefloat4x4(a); } } exports.inverse = inverse; function transpose(a) { if (a.__matrix == 2) { return matrixTransposefloat2x2(a); } else if (a.__matrix == 3) { return matrixTransposefloat3x3(a); } else if (a.__matrix == 4) { return matrixTransposefloat4x4(a); } } exports.transpose = transpose; /** @shadeup=univ(!$0$ * $1$)*/ var mul = function (a, b) { if (isMatrix(a) || isMatrix(b)) { if (isMatrix(a) && isMatrix(b)) { return matrixMul(a, b); } else { if (isMatrix(a) && typeof b == 'number') { return componentMath(b, a, function (a, b) { return a * b; }); } else if (isMatrix(b) && typeof a == 'number') { return componentMath(a, b, function (a, b) { return a * b; }); } else { if (isMatrix(a)) { if (a.length == 4) { return matrixMul2x2float2(a, b); } else if (a.length == 9) { return matrixMul3x3float3(a, b); } else if (a.length == 16) { return matrixMul4x4float4(a, b); } } else if (isMatrix(b)) { if (b.length == 4) { return matrixMulfloat22x2(a, b); } else if (b.length == 9) { return matrixMulfloat33x3(a, b); } else if (b.length == 16) { return matrixMulfloat44x4(a, b); } } } } } else { return mulFunc(a, b); } }; exports.mul = mul; /** @shadeup=univ(!$0$ / $1$)*/ exports.div = componentOp(function (a, b) { return a / b; }); /** @shadeup=glsl(!$0$ ** $1$) @shadeup=wgsl(!pow($0$, $1$))*/ exports.pow = componentOp(function (a, b) { return Math.pow(a, b); }); /** @shadeup=wgsl(!$0$ % $1$) @shadeup=glsl(!mod($0$, $1$))*/ exports.mod = componentOpMatch(function (a, b) { return a - b * Math.floor(a / b); }); /** @shadeup=univ(!$0$ & $1$)*/ exports.bitand = componentOp(function (a, b) { return a & b; }); /** @shadeup=univ(!$0$ | $1$)*/ exports.bitor = componentOp(function (a, b) { return a | b; }); /** @shadeup=univ(!$0$ ^ $1$)*/ exports.bitxor = componentOp(function (a, b) { return a ^ b; }); /** @shadeup=glsl(!$0$ << $1$) @shadeup=wgsl(!$0$ << u32($1$))*/ exports.lshift = componentOp(function (a, b) { return a << b; }); /** @shadeup=glsl(!$0$ >> $1$) @shadeup=wgsl(!$0$ >> u32($1$))*/ exports.rshift = componentOp(function (a, b) { return a >> b; }); /** @shadeup=univ(!~$0$)*/ exports.bitnot = componentOpSingular(function (a) { return ~a; }); /** @shadeup=univ(!-($0$))*/ exports.negate = componentOpSingular(function (a) { return -a; }); /** @shadeup=univ(!+($0$))*/ exports.positive = componentOpSingular(function (a) { return Math.abs(a); }); /** @shadeup=univ(abs)*/ exports.abs = componentOpSingular(function (a) { return Math.abs(a); }); /** @shadeup=glsl(floor) @shadeup=wgsl(!floor(f32(1.0) * $0$))*/ exports.floor = componentOpSingular(Math.floor); /** @shadeup=glsl(ceil) @shadeup=wgsl(!ceil(f32(1.0) * $0$))*/ exports.ceil = componentOpSingular(Math.ceil); /** @shadeup=univ(round)*/ exports.round = componentOpSingular(Math.round); /** @shadeup=univ(sign)*/ exports.sign = componentOpSingular(Math.sign); /** @shadeup=univ(cos) */ exports.cos = componentOpSingular(Math.cos); /** @shadeup=univ(sin) */ exports.sin = componentOpSingularFloat(Math.sin); /** @shadeup=univ(tan) */ exports.tan = componentOpSingular(Math.tan); /** @shadeup=univ(acos) */ exports.acos = componentOpSingular(Math.acos); /** @shadeup=univ(asin) */ exports.asin = componentOpSingular(Math.asin); /** @shadeup=univ(atan) */ exports.atan = componentOpSingular(Math.atan); /** @shadeup=univ(atan2) */ exports.atan2 = Math.atan2; /** @shadeup=univ(cosh) */ exports.cosh = componentOpSingular(Math.cosh); /** @shadeup=univ(sinh) */ exports.sinh = componentOpSingular(Math.sinh); /** @shadeup=univ(tanh) */ exports.tanh = componentOpSingular(Math.tanh); /** @shadeup=univ(acosh) */ exports.acosh = componentOpSingular(Math.acosh); /** @shadeup=univ(asinh) */ exports.asinh = componentOpSingular(Math.asinh); /** @shadeup=univ(atanh) */ exports.atanh = componentOpSingular(Math.atanh); /** @shadeup=univ(exp) */ exports.exp = componentOpSingular(Math.exp); /** @shadeup=univ(log) */ exports.log = componentOpSingular(Math.log); /** @shadeup=univ(log2) */ exports.log2 = componentOpSingular(Math.log2); /** @shadeup=univ(log10) */ exports.log10 = componentOpSingular(Math.log10); /** @shadeup=univ(sqrt) */ exports.sqrt = componentOpSingular(Math.sqrt); /** @shadeup=univ(inversesqrt) */ exports.inversesqrt = componentOpSingular(function (a) { return 1 / Math.sqrt(a); }); /** @shadeup=univ(fract)*/ exports.frac = componentOpSingular(function (a) { return a - Math.floor(a); }); function wrap(x, low, high) { if ((0, exports.lt)(x, low)) { var rng = high - low; var s1 = low - x; var ms = s1 % rng; return high - ms; } else if ((0, exports.gte)(x, high)) { var rng = high - low; var s1 = x - high; var ms = s1 % rng; return low + ms; } else { return x; } // return add(mod(sub(x, low), sub(high, low)), low) as T; } exports.wrap = wrap; /** * Returns a deterministic (same seed = same output) random float between 0-1 * * **Note:** See the noise package for more advanced random functions */ function rand(seed) { if (typeof seed === 'number') { return (0, exports.frac)(Math.sin(seed * float(91.3458)) * float(47453.5453)); } else { return Math.random(); } } exports.rand = rand; /** * Returns a deterministic (same seed = same output) random float between 0-1 * * **Note:** See the noise package for more advanced random functions */ function rand2(seed) { return (0, exports.frac)(Math.sin((0, exports.dot)(seed, float2(12.9898, 4.1414))) * float(43758.5453)); } exports.rand2 = rand2; /** * Returns a deterministic (same seed = same output) random float between 0-1 * * **Note:** See the noise package for more advanced random functions */ function rand3(seed) { var _a, _b; return rand2((_a = swizzle(seed, 'xy'), _b = rand(swizzle(seed, 'z')), [_a[0] + _b, _a[1] + _b])); } exports.rand3 = rand3; // export function remap(x: float, low1: float, high1: float, low2: float, high2: float): float { // return add(low2, mul(div(sub(x, low1), sub(high1, low1)), sub(high2, low2))); // } function pingpong(x, length) { var t = x % (length * float(2)); return length - Math.abs(t - length); } exports.pingpong = pingpong; function vectorMath_2to1_3to3(cb2, cb3) { return function (a, b) { if (a.length === 2 && b.length === 2) { return cb2(a, b); } else if (a.length === 3 && b.length === 3) { return cb3(a, b); } else { throw new Error('Invalid vector length'); } }; } function vectorMath_2to1_3to3_4to4(cb2, cb3, cb4) { return function (a, b) { if (a.length === 2 && b.length === 2) { return cb2(a, b); } else if (a.length === 3 && b.length === 3) { return cb3(a, b); } else if (a.length === 4 && b.length === 4) { return cb4(a, b); } else { throw new Error('Invalid vector length'); } }; } function vectorMath_2to1_3to1_4to1(cb2, cb3, cb4) { return function (a, b) { if (a.length === 2 && b.length === 2) { return cb2(a, b); } else if (a.length === 3 && b.length === 3) { return cb3(a, b); } else if (a.length === 4 && b.length === 4) { return cb4(a, b); } else { throw new Error('Invalid vector length'); } }; } function cross2(a, b) { return a[0] * b[1] - a[1] * b[0]; } function cross3(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; } exports.cross = vectorMath_2to1_3to3(cross2, cross3); function dot2(a, b) { return a[0] * b[0] + a[1] * b[1]; } function dot3(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } function dot4(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } /** @shadeup=univ(dot)*/ exports.dot = vectorMath_2to1_3to1_4to1(dot2, dot3, dot4); function lerp1(a, b, t) { return (a + (b - a) * t); } function lerp2(a, b, t) { return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t)]; } function lerp3(a, b, t) { return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t)]; } function lerp4(a, b, t) { return [ lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t), lerp1(a[3], b[3], t) ]; } function lerp2x2(a, b, t) { return float2x2(lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t), lerp1(a[3], b[3], t)); } function lerp3x3(a, b, t) { return float3x3(lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t), lerp1(a[3], b[3], t), lerp1(a[4], b[4], t), lerp1(a[5], b[5], t), lerp1(a[6], b[6], t), lerp1(a[7], b[7], t), lerp1(a[8], b[8], t)); } function lerp4x4(a, b, t) { return float4x4(lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t), lerp1(a[3], b[3], t), lerp1(a[4], b[4], t), lerp1(a[5], b[5], t), lerp1(a[6], b[6], t), lerp1(a[7], b[7], t), lerp1(a[8], b[8], t), lerp1(a[9], b[9], t), lerp1(a[10], b[10], t), lerp1(a[11], b[11], t), lerp1(a[12], b[12], t), lerp1(a[13], b[13], t), lerp1(a[14], b[14], t), lerp1(a[15], b[15], t)); } /** @shadeup=univ(mix)*/ function lerp(a, b, t) { if (typeof a === 'number' && typeof b === 'number' && typeof t === 'number') { return lerp1(a, b, t); } else if (isMatrix(a) && isMatrix(b)) { if (a.length === 4 && b.length === 4) { return lerp2x2(a, b, t); } else if (a.length === 9 && b.length === 9) { return lerp3x3(a, b, t); } else if (a.length === 16 && b.length === 16) { return lerp4x4(a, b, t); } else { throw new Error('Invalid matrix length'); } } else if (a.length === 2 && b.length === 2 && typeof t === 'number') { return lerp2(a, b, t); } else if (a.length === 3 && b.length === 3 && typeof t === 'number') { return lerp3(a, b, t); } else if (a.length === 4 && b.length === 4 && typeof t === 'number') { return lerp4(a, b, t); } else { throw new Error('Invalid vector length'); } } exports.lerp = lerp; /** @shadeup=univ(!bilerp_\`0\`($0$, $1$, $2$, $3$, $4$, $5$)) */ function bilerp(a, b, c, d, u, v) { return lerp(lerp(a, b, u), lerp(c, d, u), v); } exports.bilerp = bilerp; /** @shadeup=univ(length)*/ function length(a) { if (typeof a === 'number') { return Math.abs(a); } else if (a.length === 2) { return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2)); } else if (a.length === 3) { return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2)); } else if (a.length === 4) { return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2)); } else { throw new Error('Invalid vector length'); } } exports.length = length; function dist(a, b) { return length((0, exports.sub)(a, b)); } exports.dist = dist; /** @shadeup=univ(distance)*/ exports.distance = dist; /** @shadeup=univ(normalize)*/ function normalize(a) { if (a.length === 2) { var l = length(a); return [a[0] / l, a[1] / l]; } else if (a.length === 3) { var l = length(a); return [a[0] / l, a[1] / l, a[2] / l]; } else if (a.length === 4) { var l = length(a); return [a[0] / l, a[1] / l, a[2] / l, a[3] / l]; } else { throw new Error('Invalid vector length'); } } exports.normalize = normalize; /** @shadeup=univ(reflect)*/ function reflect(a, b) { if (a.length === 2 && b.length === 2) { return reflect2(a, b); } else if (a.length === 3 && b.length === 3) { return reflect3(a, b); } else if (a.length === 4 && b.length === 4) { return reflect4(a, b); } else { throw new Error('Invalid vector length'); } } exports.reflect = reflect; function reflect2(b, a) { var dot = dot2(a, b); return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1]]; } function reflect3(b, a) { var dot = dot3(a, b); return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1], b[2] - 2 * dot * a[2]]; } function reflect4(b, a) { var dot = dot4(a, b); return [ b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1], b[2] - 2 * dot * a[2], b[3] - 2 * dot * a[3] ]; } /** @shadeup=univ(refract)*/ function refract(a, b, eta) { if (a.length === 2 && b.length === 2) { return refract2(a, b, eta); } else if (a.length === 3 && b.length === 3) { return refract3(a, b, eta); } else if (a.length === 4 && b.length === 4) { return refract4(a, b, eta); } else { throw new Error('Invalid vector length'); } } exports.refract = refract; function refract2(b, a, eta) { var dot = dot2(a, b); var k = 1 - eta * eta * (1 - dot * dot); return k < 0 ? [0, 0] : [ eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0], eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1] ]; } function refract3(b, a, eta) { var dot = dot3(a, b); var k = 1 - eta * eta * (1 - dot * dot); return k < 0 ? [0, 0, 0] : [ eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0], eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1], eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2] ]; } function refract4(b, a, eta) { var dot = dot4(a, b); var k = 1 - eta * eta * (1 - dot * dot); return k < 0 ? [0, 0, 0, 0] : [ eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0], eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1], eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2], eta * b[3] - (eta * dot + Math.sqrt(k)) * a[3] ]; } /** @shadeup=univ(degrees)*/ function degrees(a) { return float((a * 180) / Math.PI); } exports.degrees = degrees; /** @shadeup=univ(radians)*/ function radians(a) { return float((a * Math.PI) / 180); } exports.radians = radians; /** @shadeup=univ(step)*/ function step(edge, x) { if (typeof edge === 'number') { if (typeof x === 'number') { return x < edge ? 0 : 1; } else { return x.map(function (v) { return (v < edge ? 0 : 1); }); } } else { if (typeof x === 'number') { return edge.map(function (v) { return (x < v ? 0 : 1); }); } else { return edge.map(function (v, i) { return (x[i] < v ? 0 : 1); }); } } } exports.step = step; function _smoothstep(a, b, x) { var t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); } /** @shadeup=univ(smoothstep)*/ function smoothstep(a, b, x) { if (typeof a === 'number' && typeof b === 'number' && typeof x === 'number') { return _smoothstep(a, b, x); } else if (typeof a === 'number' && typeof b === 'number') { return x.map(function (v) { return _smoothstep(a, b, v); }); } else { return a.map(function (v, i) { return _smoothstep(v, b[i], x[i]); }); } } exports.smoothstep = smoothstep; function componentReduce(vectors, cb) { var result = []; var _loop_1 = function (i) { result.push(cb(vectors.map(function (v) { return v[i]; }))); }; for (var i = 0; i < vectors[0].length; i++) { _loop_1(i); } return result; } /** @shadeup=univ(min)*/ function min() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (args.length == 1) { if (Array.isArray(args[0])) { return Math.min.apply(Math, args[0]); } else { return args[0]; } } else { if (Array.isArray(args[0]) && !Array.isArray(args[1])) { var minTo_1 = args[1]; return args[0].map(function (v) { return Math.min(v, minTo_1); }); } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) { var minFrom_1 = args[0]; return args[1].map(function (v) { return Math.min(minFrom_1, v); }); } else if (Array.isArray(args[0])) { return componentReduce(args, function (a) { return Math.min.apply(Math, a); }); } else { return Math.min.apply(Math, args); } } } exports.min = min; /** @shadeup=univ(max)*/ function max() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (args.length == 1) { if (Array.isArray(args[0])) { return Math.max.apply(Math, args[0]); } else { return args[0]; } } else { if (Array.isArray(args[0]) && !Array.isArray(args[1])) { var maxTo_1 = args[1]; return args[0].map(function (v) { return Math.max(v, maxTo_1); }); } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) { var maxFrom_1 = args[0]; return args[1].map(function (v) { return Math.max(maxFrom_1, v); }); } else if (Array.isArray(args[0])) { return componentReduce(args, function (a) { return Math.max.apply(Math, a); }); } else { return Math.max.apply(Math, args); } } } exports.max = max; /** @shadeup=univ(clamp)*/ function clamp(arg, min, max) { if (Array.isArray(arg)) { if (Array.isArray(min) && Array.isArray(max)) { return arg.map(function (a, i) { return Math.min(Math.max(a, min[i]), max[i]); }); } else { return arg.map(function (a) { return Math.min(Math.max(a, min), max); }); } } else { return Math.min(Math.max(arg, min), max); } } exports.clamp = clamp; /** @shadeup=glsl(!clamp($0$, 0.0, 1.0)) @shadeup=wgsl(saturate) */ function saturate(arg) { return clamp(arg, float(0), float(1)); } exports.saturate = saturate; function eq(a, b) { var ta = typeof a; var tb = typeof b; if (ta != tb) { return false; } else if ((ta == 'number' && tb == 'number') || (ta == 'string' && tb == 'string') || (ta == 'boolean' && tb == 'boolean') || (ta == 'undefined' && tb == 'undefined')) { return a == b; } else if (ta == 'object' && tb == 'object') { if (Array.isArray(a) && Array.isArray(b)) { if (a.length != b.length) { return false; } for (var i = 0; i < a.length; i++) { if (!eq(a[i], b[i])) { return false; } } return true; } else { return a == b; } } } exports.eq = eq; /** @shadeup=univ(!($0$ != $1$))*/ var neq = function (a, b) { return !eq(a, b); }; exports.neq = neq; /** @shadeup=univ(!($0$ < $1$))*/ var lt = function (a, b) { return a < b; }; exports.lt = lt; /** @shadeup=univ(!($0$ <= $1$))*/ var lte = function (a, b) { return a <= b; }; exports.lte = lte; /** @shadeup=univ(!($0$ > $1$))*/ var gt = function (a, b) { return a > b; }; exports.gt = gt; /** @shadeup=univ(!($0$ >= $1$))*/ var gte = function (a, b) { return a >= b; }; exports.gte = gte; /** @shadeup=univ(!($0$ && $1$))*/ var and = function (a, b) { return a && b; }; exports.and = and; /** @shadeup=univ(!($0$ || $1$))*/ var or = function (a, b) { return a || b; }; exports.or = or; /** @shadeup=univ(!(!$0$))*/ var not = function (a) { return !a; }; exports.not = not; /** @shadeup=univ()*/ function makeVector() { var out = []; for (var i = 0; i < arguments.length; i++) { var a = arguments[i]; if (typeof a === 'number') { out.push(a); } else { for (var j = 0; j < a.length; j++) { out.push(a[j]); } } } return out; throw new Error('Invalid vector length'); } exports.makeVector = makeVector; var swizIndex = { x: 0, y: 1, z: 2, w: 3, r: 0, g: 1, b: 2, a: 3 }; var getSwizIndexFast = function (swiz) { switch (swiz) { case 'x': return 0; case 'y': return 1; case 'z': return 2; case 'w': return 3; case 'r': return 0; case 'g': return 1; case 'b': return 2; case 'a': return 3; } }; /** @shadeup=shader */ function testDocComment() { return 1; } exports.testDocComment = testDocComment; function swizzle(v, swiz, assign) { var _a; if (typeof v === 'number') { if (swiz.length === 1) { return v; } else if (swiz.length === 2) { return [v, v]; } else if (swiz.length === 3) { return [v, v, v]; } else if (swiz.length === 4) { return [v, v, v, v]; } } else if (Array.isArray(v)) { if (typeof assign !== 'undefined') { for (var i = 0; i < swiz.length; i++) { v[getSwizIndexFast(swiz[i])] = (_a = assign[i]) !== null && _a !== void 0 ? _a : assign; } return v; } if (swiz.length === 1) { return v[getSwizIndexFast(swiz)]; } else if (swiz.length === 2) { return [v[getSwizIndexFast(swiz[0])], v[getSwizIndexFast(swiz[1])]]; } else if (swiz.length === 3) { return [ v[getSwizIndexFast(swiz[0])], v[getSwizIndexFast(swiz[1])], v[getSwizIndexFast(swiz[2])] ]; } else if (swiz.length === 4) { return [ v[getSwizIndexFast(swiz[0])], v[getSwizIndexFast(swiz[1])], v[getSwizIndexFast(swiz[2])], v[getSwizIndexFast(swiz[3])] ]; } } else { return v[swiz]; } } exports.swizzle = swizzle; function intifyVector(v) { if (typeof v === 'number') { return v; } else if (Array.isArray(v)) { return v.map(function (v) { return v | 0; }); } else { return v; } } exports.intifyVector = intifyVector; exports.FM = static_math_1.FM; // type f32 = number & { __float: never }; // type i32 = number & { __int: never }; // type num = f32 | i32; // function f32(a: number): f32 { // return a as f32; // } // function i32(a: number): i32 { // return a as i32; // } // type numeric2 = (a: A, b: B) => (A extends f32 ? f32 : (B extends f32 ? f32 : i32)); // type numeric3 = (a: A, b: B, c: C) => (A extends f32 ? f32 : (B extends f32 ? f32 : (C extends f32 ? f32 : i32))); // export const abc: numeric2 = (a, b, c) => a + b + c; // abc(f32(1), i32(2)); var atomic_internal = /** @class */ (function () { function atomic_internal(value) { this.__value = value; } /** @shadeup=univ(!atomicLoad(&$self$))*/ atomic_internal.prototype.load = function () { return this.__value; }; /** @shadeup=univ(!atomicStore(&$self$, $0$))*/ atomic_internal.prototype.store = function (value) { this.__value = value; if (this.$mutate) this.$mutate(this.__value); }; /** @shadeup=univ(!atomicAdd(&$self$, $0$))*/ atomic_internal.prototype.add = function (value) { var old = this.__value; this.__value += value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicSub(&$self$, $0$))*/ atomic_internal.prototype.sub = function (value) { var old = this.__value; this.__value -= value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicMax(&$self$, $0$))*/ atomic_internal.prototype.max = function (value) { var old = this.__value; this.__value = Math.max(value, this.__value); if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicMin(&$self$, $0$))*/ atomic_internal.prototype.min = function (value) { var old = this.__value; this.__value = Math.min(value, this.__value); if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicAnd(&$self$, $0$))*/ atomic_internal.prototype.and = function (value) { var old = this.__value; this.__value = value & this.__value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicOr(&$self$, $0$))*/ atomic_internal.prototype.or = function (value) { var old = this.__value; this.__value = value | this.__value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicXor(&$self$, $0$))*/ atomic_internal.prototype.xor = function (value) { var old = this.__value; this.__value = value ^ this.__value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicExchange(&$self$, $0$))*/ atomic_internal.prototype.exchange = function (value) { var old = this.__value; this.__value = value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicCompareExchangeWeak(&$self$, $0$, $1$))*/ atomic_internal.prototype.compareExchangeWeak = function (compare, value) { var old = this.__value; if (old == compare) { this.__value = value; } if (this.$mutate) this.$mutate(this.__value); return { old_value: old, exchanged: old == compare }; }; atomic_internal.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_math_ts_71052_atomic_internal\\",\\"fields\\":[[\\"__type\\",{\\"type\\":\\"unknown\\"}],[\\"__value\\",null],[\\"$mutate\\",{\\"type\\":\\"unknown\\"}]]}"); }; return atomic_internal; }()); exports.atomic_internal = atomic_internal; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_math_ts_71052_atomic_internal\\",\\"fields\\":[[\\"__type\\",{\\"type\\":\\"unknown\\"}],[\\"__value\\",null],[\\"$mutate\\",{\\"type\\":\\"unknown\\"}]]}"), atomic_internal) function atomic(value) { return new atomic_internal(value); } exports.atomic = atomic; window.makeAtomic = atomic; /** * Executes a control barrier synchronization function that affects memory and atomic operations in the workgroup address space. * * See: https://www.w3.org/TR/WGSL/#workgroupBarrier-builtin * * @shadeup=univ(!workgroupBarrier()) */ function workgroupBarrier() { } exports.workgroupBarrier = workgroupBarrier; /** * Executes a storage barrier synchronization function that affects memory and atomic operations in the workgroup address space. * * See: https://www.w3.org/TR/WGSL/#storageBarrier-builtin * * @shadeup=univ(!storageBarrier()) */ function storageBarrier() { } exports.storageBarrier = storageBarrier; /** * See: https://www.w3.org/TR/WGSL/#workgroupUniformLoad-builtin * * @shadeup=univ(!workgroupUniformLoad(&$0$)) */ function workgroupUniformLoad(p) { return p; } exports.workgroupUniformLoad = workgroupUniformLoad; /** * Discards the current fragment. * * A discard statement converts the invocation into a helper invocation and throws away the fragment. The discard statement must only be used in a fragment shader stage. * * See: https://www.w3.org/TR/WGSL/#discard-statement * * @shadeup=univ(!discard;) */ function discard() { } exports.discard = discard; /** * Returns the derivative of the input value with respect to the window-space x coordinate. * @param value - The input value. * @returns The derivative of the input value with respect to the window-space x coordinate. * @shadeup=glsl(!dFdx($0$)) * @shadeup=wgsl(!dpdx($0$)) */ function ddx(value) { return 0; } exports.ddx = ddx; /** * Returns the derivative of the input value with respect to the window-space y coordinate. * @param value - The input value. * * @returns The derivative of the input value with respect to the window-space y coordinate. * @shadeup=glsl(!dFdy($0$)) * @shadeup=wgsl(!dpdy($0$)) */ function ddy(value) { return 0; } exports.ddy = ddy; /** * @shadeup=glsl(!dFdxFine($0$)) * @shadeup=wgsl(!dpdxFine($0$)) */ function ddxFine(value) { return 0; } exports.ddxFine = ddxFine; /** * @shadeup=glsl(!dFdyFine($0$)) * @shadeup=wgsl(!dpdyFine($0$)) */ function ddyFine(value) { return 0; } exports.ddyFine = ddyFine; /** * @shadeup=glsl(!dFdxCoarse($0$)) * @shadeup=wgsl(!dpdxCoarse($0$)) */ function ddxCoarse(value) { return 0; } exports.ddxCoarse = ddxCoarse; /** * @shadeup=glsl(!dFdyCoarse($0$)) * @shadeup=wgsl(!dpdyCoarse($0$)) */ function ddyCoarse(value) { return 0; } exports.ddyCoarse = ddyCoarse; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!bitcast<$[0]$>($0$)) */ function bitcast(value) { return 0; } exports.bitcast = bitcast; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack4x8snorm($0$)) */ function pack4x8snorm(value) { return uint(0); } exports.pack4x8snorm = pack4x8snorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack4x8unorm($0$)) */ function pack4x8unorm(value) { return uint(0); } exports.pack4x8unorm = pack4x8unorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack2x16snorm($0$)) */ function pack2x16snorm(value) { return uint(0); } exports.pack2x16snorm = pack2x16snorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack2x16unorm($0$)) */ function pack2x16unorm(value) { return uint(0); } exports.pack2x16unorm = pack2x16unorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack2x16float($0$)) */ function pack2x16float(value) { return uint(0); } exports.pack2x16float = pack2x16float; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack4x8snorm($0$)) */ function unpack4x8snorm(value) { return float4(0, 0, 0, 0); } exports.unpack4x8snorm = unpack4x8snorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack4x8unorm($0$)) */ function unpack4x8unorm(value) { return float4(0, 0, 0, 0); } exports.unpack4x8unorm = unpack4x8unorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack2x16snorm($0$)) */ function unpack2x16snorm(value) { return float2(0, 0); } exports.unpack2x16snorm = unpack2x16snorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack2x16unorm($0$)) */ function unpack2x16unorm(value) { return float2(0, 0); } exports.unpack2x16unorm = unpack2x16unorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack2x16float($0$)) */ function unpack2x16float(value) { return float2(0, 0); } exports.unpack2x16float = unpack2x16float; }); ` } ], emitSkipped: false, diagnostics: [] }, "/static-math.ts": { outputFiles: [ { name: "/static-math.js", writeByteOrderMark: false, text: 'define(["require", "exports"], function (require, exports) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.FM = void 0;\n ///\n /// GENERATED\n /// DO NOT EDIT THIS FILE\n /// see generate-static-math.ts\n ///\n exports.FM = {\n add_1_1: function (a, b) { return a + b; },\n add_2_1: function (a, b) { return [a[0] + b, a[1] + b]; },\n add_1_2: function (a, b) { return [a + b[0], a + b[1]]; },\n add_2_2: function (a, b) { return [a[0] + b[0], a[1] + b[1]]; },\n add_3_1: function (a, b) { return [a[0] + b, a[1] + b, a[2] + b]; },\n add_1_3: function (a, b) { return [a + b[0], a + b[1], a + b[2]]; },\n add_3_3: function (a, b) { return [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; },\n add_4_1: function (a, b) { return [a[0] + b, a[1] + b, a[2] + b, a[3] + b]; },\n add_1_4: function (a, b) { return [a + b[0], a + b[1], a + b[2], a + b[3]]; },\n add_4_4: function (a, b) { return [a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]]; },\n sub_1_1: function (a, b) { return a - b; },\n sub_2_1: function (a, b) { return [a[0] - b, a[1] - b]; },\n sub_1_2: function (a, b) { return [a - b[0], a - b[1]]; },\n sub_2_2: function (a, b) { return [a[0] - b[0], a[1] - b[1]]; },\n sub_3_1: function (a, b) { return [a[0] - b, a[1] - b, a[2] - b]; },\n sub_1_3: function (a, b) { return [a - b[0], a - b[1], a - b[2]]; },\n sub_3_3: function (a, b) { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; },\n sub_4_1: function (a, b) { return [a[0] - b, a[1] - b, a[2] - b, a[3] - b]; },\n sub_1_4: function (a, b) { return [a - b[0], a - b[1], a - b[2], a - b[3]]; },\n sub_4_4: function (a, b) { return [a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]]; },\n div_1_1: function (a, b) { return a / b; },\n div_2_1: function (a, b) { return [a[0] / b, a[1] / b]; },\n div_1_2: function (a, b) { return [a / b[0], a / b[1]]; },\n div_2_2: function (a, b) { return [a[0] / b[0], a[1] / b[1]]; },\n div_3_1: function (a, b) { return [a[0] / b, a[1] / b, a[2] / b]; },\n div_1_3: function (a, b) { return [a / b[0], a / b[1], a / b[2]]; },\n div_3_3: function (a, b) { return [a[0] / b[0], a[1] / b[1], a[2] / b[2]]; },\n div_4_1: function (a, b) { return [a[0] / b, a[1] / b, a[2] / b, a[3] / b]; },\n div_1_4: function (a, b) { return [a / b[0], a / b[1], a / b[2], a / b[3]]; },\n div_4_4: function (a, b) { return [a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]]; },\n mul_1_1: function (a, b) { return a * b; },\n mul_2_1: function (a, b) { return [a[0] * b, a[1] * b]; },\n mul_1_2: function (a, b) { return [a * b[0], a * b[1]]; },\n mul_2_2: function (a, b) { return [a[0] * b[0], a[1] * b[1]]; },\n mul_3_1: function (a, b) { return [a[0] * b, a[1] * b, a[2] * b]; },\n mul_1_3: function (a, b) { return [a * b[0], a * b[1], a * b[2]]; },\n mul_3_3: function (a, b) { return [a[0] * b[0], a[1] * b[1], a[2] * b[2]]; },\n mul_4_1: function (a, b) { return [a[0] * b, a[1] * b, a[2] * b, a[3] * b]; },\n mul_1_4: function (a, b) { return [a * b[0], a * b[1], a * b[2], a * b[3]]; },\n mul_4_4: function (a, b) { return [a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]]; },\n mod_1_1: function (a, b) { return a % b; },\n mod_2_1: function (a, b) { return [a[0] % b, a[1] % b]; },\n mod_1_2: function (a, b) { return [a % b[0], a % b[1]]; },\n mod_2_2: function (a, b) { return [a[0] % b[0], a[1] % b[1]]; },\n mod_3_1: function (a, b) { return [a[0] % b, a[1] % b, a[2] % b]; },\n mod_1_3: function (a, b) { return [a % b[0], a % b[1], a % b[2]]; },\n mod_3_3: function (a, b) { return [a[0] % b[0], a[1] % b[1], a[2] % b[2]]; },\n mod_4_1: function (a, b) { return [a[0] % b, a[1] % b, a[2] % b, a[3] % b]; },\n mod_1_4: function (a, b) { return [a % b[0], a % b[1], a % b[2], a % b[3]]; },\n mod_4_4: function (a, b) { return [a[0] % b[0], a[1] % b[1], a[2] % b[2], a[3] % b[3]]; },\n bitand_1_1: function (a, b) { return a & b; },\n bitand_2_1: function (a, b) { return [a[0] & b, a[1] & b]; },\n bitand_1_2: function (a, b) { return [a & b[0], a & b[1]]; },\n bitand_2_2: function (a, b) { return [a[0] & b[0], a[1] & b[1]]; },\n bitand_3_1: function (a, b) { return [a[0] & b, a[1] & b, a[2] & b]; },\n bitand_1_3: function (a, b) { return [a & b[0], a & b[1], a & b[2]]; },\n bitand_3_3: function (a, b) { return [a[0] & b[0], a[1] & b[1], a[2] & b[2]]; },\n bitand_4_1: function (a, b) { return [a[0] & b, a[1] & b, a[2] & b, a[3] & b]; },\n bitand_1_4: function (a, b) { return [a & b[0], a & b[1], a & b[2], a & b[3]]; },\n bitand_4_4: function (a, b) { return [a[0] & b[0], a[1] & b[1], a[2] & b[2], a[3] & b[3]]; },\n bitor_1_1: function (a, b) { return a | b; },\n bitor_2_1: function (a, b) { return [a[0] | b, a[1] | b]; },\n bitor_1_2: function (a, b) { return [a | b[0], a | b[1]]; },\n bitor_2_2: function (a, b) { return [a[0] | b[0], a[1] | b[1]]; },\n bitor_3_1: function (a, b) { return [a[0] | b, a[1] | b, a[2] | b]; },\n bitor_1_3: function (a, b) { return [a | b[0], a | b[1], a | b[2]]; },\n bitor_3_3: function (a, b) { return [a[0] | b[0], a[1] | b[1], a[2] | b[2]]; },\n bitor_4_1: function (a, b) { return [a[0] | b, a[1] | b, a[2] | b, a[3] | b]; },\n bitor_1_4: function (a, b) { return [a | b[0], a | b[1], a | b[2], a | b[3]]; },\n bitor_4_4: function (a, b) { return [a[0] | b[0], a[1] | b[1], a[2] | b[2], a[3] | b[3]]; },\n bitxor_1_1: function (a, b) { return a ^ b; },\n bitxor_2_1: function (a, b) { return [a[0] ^ b, a[1] ^ b]; },\n bitxor_1_2: function (a, b) { return [a ^ b[0], a ^ b[1]]; },\n bitxor_2_2: function (a, b) { return [a[0] ^ b[0], a[1] ^ b[1]]; },\n bitxor_3_1: function (a, b) { return [a[0] ^ b, a[1] ^ b, a[2] ^ b]; },\n bitxor_1_3: function (a, b) { return [a ^ b[0], a ^ b[1], a ^ b[2]]; },\n bitxor_3_3: function (a, b) { return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2]]; },\n bitxor_4_1: function (a, b) { return [a[0] ^ b, a[1] ^ b, a[2] ^ b, a[3] ^ b]; },\n bitxor_1_4: function (a, b) { return [a ^ b[0], a ^ b[1], a ^ b[2], a ^ b[3]]; },\n bitxor_4_4: function (a, b) { return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]; },\n lshift_1_1: function (a, b) { return a << b; },\n lshift_2_1: function (a, b) { return [a[0] << b, a[1] << b]; },\n lshift_1_2: function (a, b) { return [a << b[0], a << b[1]]; },\n lshift_2_2: function (a, b) { return [a[0] << b[0], a[1] << b[1]]; },\n lshift_3_1: function (a, b) { return [a[0] << b, a[1] << b, a[2] << b]; },\n lshift_1_3: function (a, b) { return [a << b[0], a << b[1], a << b[2]]; },\n lshift_3_3: function (a, b) { return [a[0] << b[0], a[1] << b[1], a[2] << b[2]]; },\n lshift_4_1: function (a, b) { return [a[0] << b, a[1] << b, a[2] << b, a[3] << b]; },\n lshift_1_4: function (a, b) { return [a << b[0], a << b[1], a << b[2], a << b[3]]; },\n lshift_4_4: function (a, b) { return [a[0] << b[0], a[1] << b[1], a[2] << b[2], a[3] << b[3]]; },\n rshift_1_1: function (a, b) { return a >> b; },\n rshift_2_1: function (a, b) { return [a[0] >> b, a[1] >> b]; },\n rshift_1_2: function (a, b) { return [a >> b[0], a >> b[1]]; },\n rshift_2_2: function (a, b) { return [a[0] >> b[0], a[1] >> b[1]]; },\n rshift_3_1: function (a, b) { return [a[0] >> b, a[1] >> b, a[2] >> b]; },\n rshift_1_3: function (a, b) { return [a >> b[0], a >> b[1], a >> b[2]]; },\n rshift_3_3: function (a, b) { return [a[0] >> b[0], a[1] >> b[1], a[2] >> b[2]]; },\n rshift_4_1: function (a, b) { return [a[0] >> b, a[1] >> b, a[2] >> b, a[3] >> b]; },\n rshift_1_4: function (a, b) { return [a >> b[0], a >> b[1], a >> b[2], a >> b[3]]; },\n rshift_4_4: function (a, b) { return [a[0] >> b[0], a[1] >> b[1], a[2] >> b[2], a[3] >> b[3]]; },\n bitnot_1: function (a) { return ~a; },\n bitnot_2: function (a) { return [~a[0], ~a[1]]; },\n bitnot_3: function (a) { return [~a[0], ~a[1], ~a[2]]; },\n bitnot_4: function (a) { return [~a[0], ~a[1], ~a[2], ~a[3]]; },\n negate_1: function (a) { return -a; },\n negate_2: function (a) { return [-a[0], -a[1]]; },\n negate_3: function (a) { return [-a[0], -a[1], -a[2]]; },\n negate_4: function (a) { return [-a[0], -a[1], -a[2], -a[3]]; },\n positive_1: function (a) { return Math.abs(a); },\n positive_2: function (a) { return [Math.abs(a[0]), Math.abs(a[1])]; },\n positive_3: function (a) { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])]; },\n positive_4: function (a) { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2]), Math.abs(a[3])]; },\n abs_1: function (a) { return Math.abs(a); },\n abs_2: function (a) { return [Math.abs(a[0]), Math.abs(a[1])]; },\n abs_3: function (a) { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])]; },\n abs_4: function (a) { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2]), Math.abs(a[3])]; },\n floor_1: function (a) { return Math.floor(a); },\n floor_2: function (a) { return [Math.floor(a[0]), Math.floor(a[1])]; },\n floor_3: function (a) { return [Math.floor(a[0]), Math.floor(a[1]), Math.floor(a[2])]; },\n floor_4: function (a) { return [Math.floor(a[0]), Math.floor(a[1]), Math.floor(a[2]), Math.floor(a[3])]; },\n ceil_1: function (a) { return Math.ceil(a); },\n ceil_2: function (a) { return [Math.ceil(a[0]), Math.ceil(a[1])]; },\n ceil_3: function (a) { return [Math.ceil(a[0]), Math.ceil(a[1]), Math.ceil(a[2])]; },\n ceil_4: function (a) { return [Math.ceil(a[0]), Math.ceil(a[1]), Math.ceil(a[2]), Math.ceil(a[3])]; },\n round_1: function (a) { return Math.round(a); },\n round_2: function (a) { return [Math.round(a[0]), Math.round(a[1])]; },\n round_3: function (a) { return [Math.round(a[0]), Math.round(a[1]), Math.round(a[2])]; },\n round_4: function (a) { return [Math.round(a[0]), Math.round(a[1]), Math.round(a[2]), Math.round(a[3])]; },\n sign_1: function (a) { return Math.sign(a); },\n sign_2: function (a) { return [Math.sign(a[0]), Math.sign(a[1])]; },\n sign_3: function (a) { return [Math.sign(a[0]), Math.sign(a[1]), Math.sign(a[2])]; },\n sign_4: function (a) { return [Math.sign(a[0]), Math.sign(a[1]), Math.sign(a[2]), Math.sign(a[3])]; },\n cos_1: function (a) { return Math.cos(a); },\n cos_2: function (a) { return [Math.cos(a[0]), Math.cos(a[1])]; },\n cos_3: function (a) { return [Math.cos(a[0]), Math.cos(a[1]), Math.cos(a[2])]; },\n cos_4: function (a) { return [Math.cos(a[0]), Math.cos(a[1]), Math.cos(a[2]), Math.cos(a[3])]; },\n sin_1: function (a) { return Math.sin(a); },\n sin_2: function (a) { return [Math.sin(a[0]), Math.sin(a[1])]; },\n sin_3: function (a) { return [Math.sin(a[0]), Math.sin(a[1]), Math.sin(a[2])]; },\n sin_4: function (a) { return [Math.sin(a[0]), Math.sin(a[1]), Math.sin(a[2]), Math.sin(a[3])]; },\n tan_1: function (a) { return Math.tan(a); },\n tan_2: function (a) { return [Math.tan(a[0]), Math.tan(a[1])]; },\n tan_3: function (a) { return [Math.tan(a[0]), Math.tan(a[1]), Math.tan(a[2])]; },\n tan_4: function (a) { return [Math.tan(a[0]), Math.tan(a[1]), Math.tan(a[2]), Math.tan(a[3])]; },\n acos_1: function (a) { return Math.acos(a); },\n acos_2: function (a) { return [Math.acos(a[0]), Math.acos(a[1])]; },\n acos_3: function (a) { return [Math.acos(a[0]), Math.acos(a[1]), Math.acos(a[2])]; },\n acos_4: function (a) { return [Math.acos(a[0]), Math.acos(a[1]), Math.acos(a[2]), Math.acos(a[3])]; },\n asin_1: function (a) { return Math.asin(a); },\n asin_2: function (a) { return [Math.asin(a[0]), Math.asin(a[1])]; },\n asin_3: function (a) { return [Math.asin(a[0]), Math.asin(a[1]), Math.asin(a[2])]; },\n asin_4: function (a) { return [Math.asin(a[0]), Math.asin(a[1]), Math.asin(a[2]), Math.asin(a[3])]; },\n atan_1: function (a) { return Math.atan(a); },\n atan_2: function (a) { return [Math.atan(a[0]), Math.atan(a[1])]; },\n atan_3: function (a) { return [Math.atan(a[0]), Math.atan(a[1]), Math.atan(a[2])]; },\n atan_4: function (a) { return [Math.atan(a[0]), Math.atan(a[1]), Math.atan(a[2]), Math.atan(a[3])]; },\n cosh_1: function (a) { return Math.cosh(a); },\n cosh_2: function (a) { return [Math.cosh(a[0]), Math.cosh(a[1])]; },\n cosh_3: function (a) { return [Math.cosh(a[0]), Math.cosh(a[1]), Math.cosh(a[2])]; },\n cosh_4: function (a) { return [Math.cosh(a[0]), Math.cosh(a[1]), Math.cosh(a[2]), Math.cosh(a[3])]; },\n sinh_1: function (a) { return Math.sinh(a); },\n sinh_2: function (a) { return [Math.sinh(a[0]), Math.sinh(a[1])]; },\n sinh_3: function (a) { return [Math.sinh(a[0]), Math.sinh(a[1]), Math.sinh(a[2])]; },\n sinh_4: function (a) { return [Math.sinh(a[0]), Math.sinh(a[1]), Math.sinh(a[2]), Math.sinh(a[3])]; },\n tanh_1: function (a) { return Math.tanh(a); },\n tanh_2: function (a) { return [Math.tanh(a[0]), Math.tanh(a[1])]; },\n tanh_3: function (a) { return [Math.tanh(a[0]), Math.tanh(a[1]), Math.tanh(a[2])]; },\n tanh_4: function (a) { return [Math.tanh(a[0]), Math.tanh(a[1]), Math.tanh(a[2]), Math.tanh(a[3])]; },\n acosh_1: function (a) { return Math.acosh(a); },\n acosh_2: function (a) { return [Math.acosh(a[0]), Math.acosh(a[1])]; },\n acosh_3: function (a) { return [Math.acosh(a[0]), Math.acosh(a[1]), Math.acosh(a[2])]; },\n acosh_4: function (a) { return [Math.acosh(a[0]), Math.acosh(a[1]), Math.acosh(a[2]), Math.acosh(a[3])]; },\n asinh_1: function (a) { return Math.asinh(a); },\n asinh_2: function (a) { return [Math.asinh(a[0]), Math.asinh(a[1])]; },\n asinh_3: function (a) { return [Math.asinh(a[0]), Math.asinh(a[1]), Math.asinh(a[2])]; },\n asinh_4: function (a) { return [Math.asinh(a[0]), Math.asinh(a[1]), Math.asinh(a[2]), Math.asinh(a[3])]; },\n atanh_1: function (a) { return Math.atanh(a); },\n atanh_2: function (a) { return [Math.atanh(a[0]), Math.atanh(a[1])]; },\n atanh_3: function (a) { return [Math.atanh(a[0]), Math.atanh(a[1]), Math.atanh(a[2])]; },\n atanh_4: function (a) { return [Math.atanh(a[0]), Math.atanh(a[1]), Math.atanh(a[2]), Math.atanh(a[3])]; },\n exp_1: function (a) { return Math.exp(a); },\n exp_2: function (a) { return [Math.exp(a[0]), Math.exp(a[1])]; },\n exp_3: function (a) { return [Math.exp(a[0]), Math.exp(a[1]), Math.exp(a[2])]; },\n exp_4: function (a) { return [Math.exp(a[0]), Math.exp(a[1]), Math.exp(a[2]), Math.exp(a[3])]; },\n log_1: function (a) { return Math.log(a); },\n log_2: function (a) { return [Math.log(a[0]), Math.log(a[1])]; },\n log_3: function (a) { return [Math.log(a[0]), Math.log(a[1]), Math.log(a[2])]; },\n log_4: function (a) { return [Math.log(a[0]), Math.log(a[1]), Math.log(a[2]), Math.log(a[3])]; },\n log2_1: function (a) { return Math.log2(a); },\n log2_2: function (a) { return [Math.log2(a[0]), Math.log2(a[1])]; },\n log2_3: function (a) { return [Math.log2(a[0]), Math.log2(a[1]), Math.log2(a[2])]; },\n log2_4: function (a) { return [Math.log2(a[0]), Math.log2(a[1]), Math.log2(a[2]), Math.log2(a[3])]; },\n log10_1: function (a) { return Math.log10(a); },\n log10_2: function (a) { return [Math.log10(a[0]), Math.log10(a[1])]; },\n log10_3: function (a) { return [Math.log10(a[0]), Math.log10(a[1]), Math.log10(a[2])]; },\n log10_4: function (a) { return [Math.log10(a[0]), Math.log10(a[1]), Math.log10(a[2]), Math.log10(a[3])]; },\n sqrt_1: function (a) { return Math.sqrt(a); },\n sqrt_2: function (a) { return [Math.sqrt(a[0]), Math.sqrt(a[1])]; },\n sqrt_3: function (a) { return [Math.sqrt(a[0]), Math.sqrt(a[1]), Math.sqrt(a[2])]; },\n sqrt_4: function (a) { return [Math.sqrt(a[0]), Math.sqrt(a[1]), Math.sqrt(a[2]), Math.sqrt(a[3])]; },\n int_2_1_1: function (a, b) { return [a | 0, b | 0]; },\n int_2_2: function (a) { return [a[0] | 0, a[1] | 0]; },\n int_3_1_1_1: function (a, b, c) { return [a | 0, b | 0, c | 0]; },\n int_3_2_1: function (a, b) { return [a[0] | 0, a[1] | 0, b | 0]; },\n int_3_1_2: function (a, b) { return [a | 0, b[0] | 0, b[1] | 0]; },\n int_3_3: function (a) { return [a[0] | 0, a[1] | 0, a[2] | 0]; },\n int_4_1_1_1_1: function (a, b, c, d) { return [a | 0, b | 0, c | 0, d | 0]; },\n int_4_2_1_1: function (a, b, c) { return [a[0] | 0, a[1] | 0, b | 0, c | 0]; },\n int_4_1_2_1: function (a, b, c) { return [a | 0, b[0] | 0, b[1] | 0, c | 0]; },\n int_4_1_1_2: function (a, b, c) { return [a | 0, b | 0, c[0] | 0, c[1] | 0]; },\n int_4_3_1: function (a, b) { return [a[0] | 0, a[1] | 0, a[2] | 0, b | 0]; },\n int_4_1_3: function (a, b) { return [a | 0, b[0] | 0, b[1] | 0, b[2] | 0]; },\n int_4_2_2: function (a, b) { return [a[0] | 0, a[1] | 0, b[0] | 0, b[1] | 0]; },\n int_4_4: function (a) { return [a[0] | 0, a[1] | 0, a[2] | 0, a[3] | 0]; },\n float_2_1_1: function (a, b) { return [a, b]; },\n float_2_2: function (a) { return [a[0], a[1]]; },\n float_3_1_1_1: function (a, b, c) { return [a, b, c]; },\n float_3_2_1: function (a, b) { return [a[0], a[1], b]; },\n float_3_1_2: function (a, b) { return [a, b[0], b[1]]; },\n float_3_3: function (a) { return [a[0], a[1], a[2]]; },\n float_4_1_1_1_1: function (a, b, c, d) { return [a, b, c, d]; },\n float_4_2_1_1: function (a, b, c) { return [a[0], a[1], b, c]; },\n float_4_1_2_1: function (a, b, c) { return [a, b[0], b[1], c]; },\n float_4_1_1_2: function (a, b, c) { return [a, b, c[0], c[1]]; },\n float_4_3_1: function (a, b) { return [a[0], a[1], a[2], b]; },\n float_4_1_3: function (a, b) { return [a, b[0], b[1], b[2]]; },\n float_4_2_2: function (a, b) { return [a[0], a[1], b[0], b[1]]; },\n float_4_4: function (a) { return [a[0], a[1], a[2], a[3]]; },\n uint_2_1_1: function (a, b) { return [a >>> 0, b >>> 0]; },\n uint_2_2: function (a) { return [a[0] >>> 0, a[1] >>> 0]; },\n uint_3_1_1_1: function (a, b, c) { return [a >>> 0, b >>> 0, c >>> 0]; },\n uint_3_2_1: function (a, b) { return [a[0] >>> 0, a[1] >>> 0, b >>> 0]; },\n uint_3_1_2: function (a, b) { return [a >>> 0, b[0] >>> 0, b[1] >>> 0]; },\n uint_3_3: function (a) { return [a[0] >>> 0, a[1] >>> 0, a[2] >>> 0]; },\n uint_4_1_1_1_1: function (a, b, c, d) { return [a >>> 0, b >>> 0, c >>> 0, d >>> 0]; },\n uint_4_2_1_1: function (a, b, c) { return [a[0] >>> 0, a[1] >>> 0, b >>> 0, c >>> 0]; },\n uint_4_1_2_1: function (a, b, c) { return [a >>> 0, b[0] >>> 0, b[1] >>> 0, c >>> 0]; },\n uint_4_1_1_2: function (a, b, c) { return [a >>> 0, b >>> 0, c[0] >>> 0, c[1] >>> 0]; },\n uint_4_3_1: function (a, b) { return [a[0] >>> 0, a[1] >>> 0, a[2] >>> 0, b >>> 0]; },\n uint_4_1_3: function (a, b) { return [a >>> 0, b[0] >>> 0, b[1] >>> 0, b[2] >>> 0]; },\n uint_4_2_2: function (a, b) { return [a[0] >>> 0, a[1] >>> 0, b[0] >>> 0, b[1] >>> 0]; },\n uint_4_4: function (a) { return [a[0] >>> 0, a[1] >>> 0, a[2] >>> 0, a[3] >>> 0]; },\n };\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/std___std_all.ts": { outputFiles: [ { name: "/std___std_all.js", writeByteOrderMark: false, text: `var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.time = exports.__deepClone = exports.__makeMap = exports.map = exports.array = exports.sleep = exports.hashableTypeToString = exports.globalVarGet = exports.globalVarInit = exports.compute = exports.statGraph = exports.stat = exports.flush = exports.print = exports.getShadeupLocalContext = exports.Mesh = exports.__dummy = void 0; /**__SHADEUP_STRUCT_INJECTION_HOOK__*/ exports.__dummy = 1; // import { Mesh } from '/_std/mesh'; var Mesh = /** @class */ (function () { function Mesh(prefils) { this.vertices = []; this.triangles = []; this.normals = []; this.tangents = []; this.bitangents = []; this.uvs = []; this.colors = []; this.symbol = Symbol(); if (prefils.vertices) this.vertices = prefils.vertices; if (prefils.triangles) this.triangles = prefils.triangles; if (prefils.normals) this.normals = prefils.normals; if (prefils.tangents) this.tangents = prefils.tangents; if (prefils.bitangents) this.bitangents = prefils.bitangents; if (prefils.uvs) this.uvs = prefils.uvs; if (prefils.colors) this.colors = prefils.colors; } Mesh.prototype.getVertices = function () { return this.vertices; }; Mesh.prototype.getTriangles = function () { return this.triangles; }; Mesh.prototype.getNormals = function () { return this.normals; }; Mesh.prototype.getTangents = function () { return this.tangents; }; Mesh.prototype.getBitangents = function () { return this.bitangents; }; Mesh.prototype.getUVs = function () { return this.uvs; }; Mesh.prototype.getColors = function () { return this.colors; }; Mesh.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_245_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",{\\"type\\":\\"unknown\\"}]]}"); }; return Mesh; }()); exports.Mesh = Mesh; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_245_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",{\\"type\\":\\"unknown\\"}]]}"), Mesh) var getShadeupLocalContext = function () { if (typeof localEngineContext !== 'undefined') { return localEngineContext; } else { return window; } }; exports.getShadeupLocalContext = getShadeupLocalContext; /** * Prints a set of value(s) to the console. Values will be converted to strings before printing. * * @param args Any number of values to print to the console */ function print() { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } console.log.apply(console, args); if (typeof (0, exports.getShadeupLocalContext)()['__shadeup_print'] === 'function') { (_a = (0, exports.getShadeupLocalContext)())['__shadeup_print'].apply(_a, args); } } exports.print = print; /** * Flushes (executes) all queued compute or draw calls * @shadeup=tag(async) @shadeup=noemit_gpu */ function flush() { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(typeof (0, exports.getShadeupLocalContext)()['flushAdapter'] === 'function')) return [3 /*break*/, 2]; return [4 /*yield*/, (0, exports.getShadeupLocalContext)()['flushAdapter']()]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [2 /*return*/]; } }); }); } exports.flush = flush; /** * Displays a single value in the stats panel at the top right * * @param name key for this stat (e.g. "fps") * @param value any value */ function stat(name, value) { if (typeof (0, exports.getShadeupLocalContext)()['__shadeup_stat'] === 'function') { (0, exports.getShadeupLocalContext)()['__shadeup_stat'](name, value); } } exports.stat = stat; /** * Display a graph of a numeric value over time * * @param name key for this stat (e.g. "fps") * @param value any numeric value * @param sampleRate how often should the graph be updated (e.g. 1 = every call, 2 = every second call, etc.) */ function statGraph(name, value, sampleRate) { if (sampleRate === void 0) { sampleRate = 1; } if (typeof (0, exports.getShadeupLocalContext)()['__shadeup_statGraph'] === 'function') { (0, exports.getShadeupLocalContext)()['__shadeup_statGraph'](name, value); } } exports.statGraph = statGraph; function infer(fn) { return fn; } // export function drawAlt(keys: shader) {} // export function draw(fullScreenPixelShader: shader): void; // export function draw( // first: Mesh | any | shader, // second?: shader, // third?: shader // ) { // if ('vertices' in first && second && third) { // __shadeup_dispatch_draw_geometry(first, second, third); // } else if (first && !second && !third) { // __shadeup_dispatch_draw(first as shader); // } // } // draw(makeShader('', (a, b) => {})); // drawAlt( // makeShader( // '000004808000091289258019303699031390005438610', // /**@shadeup=shader*/ (__in, __out) => { // __out.color; // } // ) // ); // /** // * // */ function compute(workgroups, computeShader) { (0, exports.getShadeupLocalContext)().__shadeup_dispatch_compute(workgroups, computeShader); } exports.compute = compute; // function draww(s: shader<{ abc: 123 }, { test: 123 }>) {} // type x = { x: T }; // function makeTex(a: T): x { // return { x: a }; // } // draw({ // vertex: shader('abc', (__in, __out) => {}), // attachments: [ // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }) // ], // mesh: new Mesh(), // fragment: shader('abc', (__in, __out) => { // //__out.attachment0 // }) // }); function globalVarInit(fileName, varName, initFn, getterFn) { if (!(0, exports.getShadeupLocalContext)()['shadeup_globals']) { (0, exports.getShadeupLocalContext)()['shadeup_globals'] = {}; } if (!(0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName]) { (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName] = {}; } // Disable caching for now var cache = false; if (!(varName in (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName]) || !cache) { (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName][varName] = initFn(); } (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName]['$getter_' + varName] = getterFn; return (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName][varName]; } exports.globalVarInit = globalVarInit; function globalVarGet(fileName, varName) { if (varName == 'env' || varName == 'PLATFORM_WEBGPU' || varName == 'PLATFORM_WEBGL') { return (0, exports.getShadeupLocalContext)()[varName]; } return (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName]['$getter_' + varName](); } exports.globalVarGet = globalVarGet; function hashableTypeToString(k) { if (typeof k == 'number') { return k.toString(); } else if (typeof k == 'object') { if (Array.isArray(k)) { return k.map(hashableTypeToString).join(','); } else { return k.toString(); } } else { return k.toString(); } } exports.hashableTypeToString = hashableTypeToString; Array.prototype.len = function () { return this.length; }; Array.prototype.last = function () { return this[this.length - 1]; }; Array.prototype.first = function () { return this[0]; }; Array.prototype.append = function (items) { for (var i = 0; i < items.length; i++) { this.push(items[i]); } }; Array.prototype.remove = function (index) { this.splice(index, 1); }; Array.prototype.__index = function (index) { return this[index]; }; Array.prototype.__index_assign = function (index, value) { this[index] = value; }; Array.prototype.__index_assign_op = function (op_fn, index, value) { this[index] = op_fn(this[index], value); }; /** @shadeup=tag(async) */ function sleep(seconds) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, new Promise(function (resolve) { return setTimeout(resolve, seconds * 1000); })]; }); }); } exports.sleep = sleep; function array(count, initializer) { if (initializer === void 0) { initializer = null; } var arr = new Array(count); if (initializer) { for (var i = 0; i < count; i++) { arr[i] = initializer; } } return arr; } exports.array = array; var map = /** @class */ (function () { function map(entries) { this.pairs = new Map(); if (entries) for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { var e = entries_1[_i]; this.__index_assign(e[0], e[1]); } } map.prototype.__index = function (key) { if (!this.pairs.has(hashableTypeToString(key))) { throw new Error('Key not found: ' + hashableTypeToString(key)); } return this.pairs.get(hashableTypeToString(key))[1]; }; map.prototype.__index_assign = function (key, value) { this.pairs.set(hashableTypeToString(key), [key, value]); }; map.prototype.__index_assign_op = function (op_fn, key, value) { this.pairs.set(hashableTypeToString(key), [key, op_fn(this.__index(key), value)]); }; map.prototype.delete = function (key) { this.pairs.delete(hashableTypeToString(key)); }; map.prototype.has = function (key) { return this.pairs.has(hashableTypeToString(key)); }; map.prototype.keys = function () { return Array.from(this.pairs.values()).map(function (k) { return k[0]; }); }; map.prototype.values = function () { return Array.from(this.pairs.values()).map(function (k) { return k[1]; }); }; map.new = function (entries) { return new map(entries); }; map.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_8545_map\\",\\"fields\\":[[\\"pairs\\",null]]}"); }; return map; }()); exports.map = map; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_8545_map\\",\\"fields\\":[[\\"pairs\\",null]]}"), map) function __makeMap(initial) { return new map(Object.entries(initial)); } exports.__makeMap = __makeMap; function __deepClone(value) { if (typeof value == 'object') { if (Array.isArray(value)) { var res = new Array(value.length); for (var i = 0; i < value.length; i++) { res[i] = __deepClone(value[i]); } return res; } else { if (value && typeof value.clone == 'function') { return value.clone(); } else { return value; } } } else { return value; } } exports.__deepClone = __deepClone; var time = /** @class */ (function () { function time() { } /** Saves the current time with a key of name */ time.start = function (name) { performance.mark((name !== null && name !== void 0 ? name : '_default') + '_start'); }; /** Returns the difference in milliseconds between a start with the same key */ time.stop = function (name) { performance.mark((name !== null && name !== void 0 ? name : '_default') + '_end'); var res = performance.measure((name !== null && name !== void 0 ? name : '_default') + '_diff', (name !== null && name !== void 0 ? name : '_default') + '_start', (name !== null && name !== void 0 ? name : '_default') + '_end'); return res.duration; }; /** * This returns a decimal resolution time in milliseconds since the page started. Useful for measuring time differences * * This uses performance.now() under the hood: * The performance.now() method returns a high resolution timestamp in milliseconds. It represents the time elapsed since Performance.timeOrigin */ time.now = function () { return performance.now(); }; time.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_10778_time\\",\\"fields\\":[]}"); }; return time; }()); exports.time = time; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_10778_time\\",\\"fields\\":[]}"), time) }); ` } ], emitSkipped: false, diagnostics: [] }, "/std.ts": { outputFiles: [ { name: "/std.js", writeByteOrderMark: false, text: 'var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\ndefine(["require", "exports", "/_std/ui", "/_std/mesh", "/_std/sdf", "/_std/geo", "/_std/native"], function (require, exports, ui_1, mesh_1, sdf_1, geo_1, native_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.geo = exports.sdf = exports.Mesh = exports.mesh = exports.ui = void 0;\n Object.defineProperty(exports, "ui", { enumerable: true, get: function () { return ui_1.ui; } });\n Object.defineProperty(exports, "mesh", { enumerable: true, get: function () { return mesh_1.mesh; } });\n Object.defineProperty(exports, "Mesh", { enumerable: true, get: function () { return mesh_1.Mesh; } });\n Object.defineProperty(exports, "sdf", { enumerable: true, get: function () { return sdf_1.sdf; } });\n Object.defineProperty(exports, "geo", { enumerable: true, get: function () { return geo_1.geo; } });\n __exportStar(native_1, exports);\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/ui.ts": { outputFiles: [ { name: "/_std/ui.js", writeByteOrderMark: false, text: `define(["require", "exports", "/_std/context"], function (require, exports, context_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ui = void 0; var ui; (function (ui) { function puck(position) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_PUCK(position); } ui.puck = puck; function draggable(position, radius) { if (radius === void 0) { radius = 10; } return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_PUCK(position, radius, true); } ui.draggable = draggable; function textbox(value) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('textbox', value); } ui.textbox = textbox; function slider(value, min, max) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_SLIDER(value, { min: min, max: max }); } ui.slider = slider; function label(text) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('label', text); } ui.label = label; function checkbox(value) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('checkbox', value); } ui.checkbox = checkbox; function combo(value, options) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('combo', value, { options: options }); } ui.combo = combo; function group(text) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('group', text); } ui.group = group; function button(text) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('button', false, { text: text }); } ui.button = button; function pop() { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('pop'); } ui.pop = pop; })(ui = exports.ui || (exports.ui = {})); }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/native.ts": { outputFiles: [ { name: "/_std/native.js", writeByteOrderMark: false, text: `define(["require", "exports", "/_std/common", "/_std/context"], function (require, exports, common_1, context_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.KeyboardInputState = exports.MouseInputState = exports.FrameContext = exports.shadeupMakeTextureFromUrl = void 0; function shadeupMakeTextureFromUrl(url) { return (0, context_1.getShadeupLocalContext)()['shadeupMakeTextureFromUrlNative'](url); } exports.shadeupMakeTextureFromUrl = shadeupMakeTextureFromUrl; var FrameContext = /** @class */ (function () { function FrameContext() { /** Mouse/touch screen input state for this frame */ this.mouse = new MouseInputState(); /** Keyboard input state for this frame */ this.keyboard = new KeyboardInputState(); /** Controllable camera (Hold right click and use WASD to move) */ this.camera = new common_1.Camera(); this.camera2d = new common_1.Camera2d(); } FrameContext.prototype.configureCamera = function (options) { }; /** * Use external values from the host JavaScript environment. */ FrameContext.prototype.input = function (key, defaultValue) { return defaultValue; }; /** * Send values to the host JavaScript environment. */ FrameContext.prototype.output = function (key, value) { }; FrameContext.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_387_FrameContext\\",\\"fields\\":[[\\"deltaTime\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"time\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"screenSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frame\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"mouse\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_1719_MouseInputState\\",\\"fields\\":[[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"button\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"clicked\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"dragging\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"wheel\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"velocity\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"focused\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}]]}],[\\"keyboard\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_3334_KeyboardInputState\\",\\"fields\\":[[\\"backspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"tab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"enter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"capsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"escape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"space\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"home\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"printScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"insert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"delete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"contextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"scrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"semicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"equal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"comma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"minus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"period\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"slash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"quote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedTab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedCapsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEscape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSpace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedHome\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPrintScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedInsert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDelete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedContextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedScrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSemicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEqual\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedComma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMinus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPeriod\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSlash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedQuote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowVector\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}]]}],[\\"camera\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_10837_Camera\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"rotation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"width\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"height\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"fov\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"near\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"far\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}],[\\"camera2d\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_9812_Camera2d\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"zoom\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}]]}"); }; return FrameContext; }()); exports.FrameContext = FrameContext; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_387_FrameContext\\",\\"fields\\":[[\\"deltaTime\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"time\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"screenSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frame\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"mouse\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_1719_MouseInputState\\",\\"fields\\":[[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"button\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"clicked\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"dragging\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"wheel\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"velocity\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"focused\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}]]}],[\\"keyboard\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_3334_KeyboardInputState\\",\\"fields\\":[[\\"backspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"tab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"enter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"capsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"escape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"space\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"home\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"printScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"insert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"delete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"contextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"scrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"semicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"equal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"comma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"minus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"period\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"slash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"quote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedTab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedCapsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEscape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSpace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedHome\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPrintScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedInsert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDelete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedContextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedScrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSemicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEqual\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedComma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMinus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPeriod\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSlash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedQuote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowVector\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}]]}],[\\"camera\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_10837_Camera\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"rotation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"width\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"height\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"fov\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"near\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"far\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}],[\\"camera2d\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_9812_Camera2d\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"zoom\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}]]}"), FrameContext) var MouseInputState = /** @class */ (function () { function MouseInputState() { /** , Some("Mouse button down state for buttons 0-3 (left, middle, right */ this.button = [false, false, false]; /** Mouse button pressed state for buttons 0-3 (left, middle, right) */ this.clicked = [false, false, false]; } MouseInputState.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_1719_MouseInputState\\",\\"fields\\":[[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"button\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"clicked\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"dragging\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"wheel\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"velocity\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"focused\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}]]}"); }; return MouseInputState; }()); exports.MouseInputState = MouseInputState; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_1719_MouseInputState\\",\\"fields\\":[[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"button\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"clicked\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"dragging\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"wheel\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"velocity\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"focused\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}]]}"), MouseInputState) var KeyboardInputState = /** @class */ (function () { function KeyboardInputState() { } KeyboardInputState.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_3334_KeyboardInputState\\",\\"fields\\":[[\\"backspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"tab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"enter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"capsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"escape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"space\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"home\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"printScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"insert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"delete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"contextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"scrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"semicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"equal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"comma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"minus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"period\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"slash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"quote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedTab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedCapsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEscape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSpace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedHome\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPrintScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedInsert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDelete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedContextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedScrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSemicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEqual\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedComma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMinus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPeriod\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSlash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedQuote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowVector\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}]]}"); }; return KeyboardInputState; }()); exports.KeyboardInputState = KeyboardInputState; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_3334_KeyboardInputState\\",\\"fields\\":[[\\"backspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"tab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"enter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"capsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"escape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"space\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"home\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"printScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"insert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"delete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"contextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"scrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"semicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"equal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"comma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"minus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"period\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"slash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"quote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedTab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedCapsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEscape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSpace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedHome\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPrintScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedInsert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDelete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedContextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedScrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSemicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEqual\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedComma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMinus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPeriod\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSlash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedQuote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowVector\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}]]}"), KeyboardInputState) }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/paint.ts": { outputFiles: [ { name: "/_std/paint.js", writeByteOrderMark: false, text: `define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PaintingContext = void 0; var PaintingContext = /** @class */ (function () { function PaintingContext(canvas, gl) { var _this = this; this.markDirtyCallback = function () { }; this.__ctx = null; this.__gl = null; this.__offscreen_canvas = null; this.__program = null; this.stagedChanges = false; this.dirty = false; this.fastPoints = false; this.fastPointsBuffer = null; this.__currentColor = null; this.pointsCounter = 0; this.cacheSize = [0, 0]; if (!gl) return; this.__gl = gl; this.__canvas = canvas; this.__offscreen_canvas = document.createElement('canvas'); this.__offscreen_canvas.width = canvas.width; this.__offscreen_canvas.height = canvas.height; // document.body.appendChild(this.__offscreen_canvas); this.__ctx = this.__offscreen_canvas.getContext('2d', { willReadFrequently: true }); this.__offscreen_canvas.style.position = 'absolute'; this.__offscreen_canvas.style.zIndex = '10'; // document.body.appendChild(this.__offscreen_canvas); this.__setColor([0, 0, 0, 1]); gl.addEventListener('context', function (toContext) { if (toContext == 'draw') { _this.flush(); } }); gl.addEventListener('flush', function () { _this.flush(); }); } PaintingContext.prototype.flush = function () { if (!this.__gl) return; if (!this.__canvas) return; if (!this.__offscreen_canvas) return; if (!this.stagedChanges) return; if (this.fastPoints) this.flushPoints(); this.__gl.drawImage(this.__offscreen_canvas); this.stagedChanges = false; if (this.__offscreen_canvas.width != this.__canvas.width || this.__offscreen_canvas.height != this.__canvas.height) { this.__offscreen_canvas.width = this.__canvas.width; this.__offscreen_canvas.height = this.__canvas.height; } this.pointsCounter = 0; }; PaintingContext.prototype.__beforeDraw = function () { var _a; if (!this.__offscreen_canvas) return; if (!this.__ctx) return; if (!this.__canvas) return; this.markDirtyCallback(); (_a = this.__gl) === null || _a === void 0 ? void 0 : _a.activatePaintContext(); if (!this.stagedChanges) { this.__ctx.clearRect(0, 0, this.__canvas.width, this.__canvas.height); this.__ctx.drawImage(this.__canvas, 0, 0); var color = this.__currentColor; this.__ctx.fillStyle = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); this.__ctx.strokeStyle = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); } }; PaintingContext.prototype.__afterDraw = function () { var gl = this.__gl; this.dirty = true; this.stagedChanges = true; }; PaintingContext.prototype.__setColor = function (color) { if (!this.__ctx || !color) return; if (this.__currentColor && this.__currentColor[0] == color[0] && this.__currentColor[1] == color[1] && this.__currentColor[2] == color[2] && this.__currentColor[3] == color[3]) return; this.__ctx.strokeStyle = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); this.__ctx.fillStyle = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); this.__currentColor = [color[0], color[1], color[2], color[3]]; }; PaintingContext.prototype.fillRect = function (pos, size, color) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.fillRect(pos[0], pos[1], size[0], size[1]); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.fillCircle = function (pos, radius, color) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.fillArc = function (pos, radius, startAngle, endAngle, color) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.line = function (pos1, pos2, color, width) { if (width === void 0) { width = 1; } if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.moveTo(pos1[0], pos1[1]); this.__ctx.lineTo(pos2[0], pos2[1]); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.circle = function (pos, radius, color, width) { if (width === void 0) { width = 1; } if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.arc = function (pos, radius, startAngle, endAngle, color, width) { if (width === void 0) { width = 1; } if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.text = function (pos, text, color) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.fillText(text, pos[0], pos[1]); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.startPath = function (pos) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__ctx.beginPath(); this.__ctx.moveTo(pos[0], pos[1]); }; PaintingContext.prototype.lineTo = function (pos) { if (!this.__ctx) return; this.__ctx.lineTo(pos[0], pos[1]); }; PaintingContext.prototype.strokePath = function (color, width) { if (width === void 0) { width = 1; } if (!this.__ctx) return; this.__ctx.lineWidth = width; this.__setColor(color); this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.fillPath = function (color) { if (!this.__ctx) return; this.__setColor(color); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.setStrokeWidth = function (width) { if (!this.__ctx) return; this.__ctx.lineWidth = width; }; PaintingContext.prototype.setFont = function (font) { if (!this.__ctx) return; this.__ctx.font = font; }; PaintingContext.prototype.setFontSize = function (size) { if (!this.__ctx) return; this.__ctx.font = "".concat(size, "px ").concat(this.__ctx.font.split(' ').slice(1).join(' ')); }; PaintingContext.prototype.setTextAlign = function (align) { if (!this.__ctx) return; this.__ctx.textAlign = align; }; PaintingContext.prototype.setTextBaseline = function (baseline) { if (!this.__ctx) return; this.__ctx.textBaseline = baseline; }; PaintingContext.prototype.setLineCap = function (cap) { if (!this.__ctx) return; this.__ctx.lineCap = cap; }; PaintingContext.prototype.setLineJoin = function (join) { if (!this.__ctx) return; this.__ctx.lineJoin = join; }; PaintingContext.prototype.setMiterLimit = function (limit) { if (!this.__ctx) return; this.__ctx.miterLimit = limit; }; PaintingContext.prototype.setShadowColor = function (color) { if (!this.__ctx) return; this.__ctx.shadowColor = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); }; PaintingContext.prototype.setShadowBlur = function (blur) { if (!this.__ctx) return; this.__ctx.shadowBlur = blur; }; PaintingContext.prototype.setShadowOffset = function (offset) { if (!this.__ctx) return; this.__ctx.shadowOffsetX = offset[0]; this.__ctx.shadowOffsetY = offset[1]; }; PaintingContext.prototype.setGlobalAlpha = function (alpha) { if (!this.__ctx) return; this.__ctx.globalAlpha = alpha; }; PaintingContext.prototype.setGlobalCompositeOperation = function (op) { if (!this.__ctx) return; this.__ctx.globalCompositeOperation = op; }; PaintingContext.prototype.setImageSmoothingEnabled = function (enabled) { if (!this.__ctx) return; this.__ctx.imageSmoothingEnabled = enabled; }; PaintingContext.prototype.setImageSmoothingQuality = function (quality) { if (!this.__ctx) return; this.__ctx.imageSmoothingQuality = quality; }; PaintingContext.prototype.setLineDash = function (dash) { if (!this.__ctx) return; this.__ctx.setLineDash(dash); }; PaintingContext.prototype.setLineDashOffset = function (offset) { if (!this.__ctx) return; this.__ctx.lineDashOffset = offset; }; PaintingContext.prototype.setTransform = function (a, b, c, d, e, f) { if (!this.__ctx) return; this.__ctx.setTransform(a, b, c, d, e, f); }; PaintingContext.prototype.resetTransform = function () { if (!this.__ctx) return; this.__ctx.resetTransform(); }; PaintingContext.prototype.scale = function (v) { if (!this.__ctx) return; this.__ctx.scale(v[0], v[1]); }; PaintingContext.prototype.rotate = function (angle) { if (!this.__ctx) return; this.__ctx.rotate(angle); }; PaintingContext.prototype.translate = function (v) { if (!this.__ctx) return; this.__ctx.translate(v[0], v[1]); }; PaintingContext.prototype.flushPoints = function () { if (!this.__ctx) return; if (!this.fastPoints) return; if (!this.fastPointsBuffer) return; this.__ctx.putImageData(this.fastPointsBuffer, 0, 0); this.fastPoints = false; this.fastPointsBuffer = null; this.pointsCounter = 0; }; PaintingContext.prototype.point = function (pos, color) { if (!this.__ctx) return; this.pointsCounter++; this.__beforeDraw(); if (this.pointsCounter > 10) { if (!this.fastPoints) { this.fastPoints = true; this.cacheSize = [this.__offscreen_canvas.width, this.__offscreen_canvas.height]; this.fastPointsBuffer = this.__ctx.getImageData(0, 0, this.cacheSize[0], this.cacheSize[1]); } if (!this.fastPointsBuffer) return; var x = Math.floor(pos[0]); var y = Math.floor(pos[1]); var index = (y * this.cacheSize[0] + x) * 4; if (!color) { color = this.__currentColor; } var oldColorx = this.fastPointsBuffer.data[index] / 255; var oldColory = this.fastPointsBuffer.data[index + 1] / 255; var oldColorz = this.fastPointsBuffer.data[index + 2] / 255; var oldColora = this.fastPointsBuffer.data[index + 3] / 255; this.fastPointsBuffer.data[index] = color[0] * 255 * color[3] + oldColorx * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 1] = color[1] * 255 * color[3] + oldColory * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 2] = color[2] * 255 * color[3] + oldColorz * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 3] = color[3] * 255 + oldColora * 255 * (1 - color[3]); } else { this.__setColor(color); this.__ctx.fillRect(pos[0], pos[1], 1, 1); } this.__afterDraw(); }; PaintingContext.prototype.vector = function (pos, dir, color, width) { if (color === void 0) { color = [0.9803921568627451, 0.8, 0.08235294117647059, 1]; } if (width === void 0) { width = 4; } if (!this.__ctx || (dir[0] == 0 && dir[1] == 0)) return; this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.setStrokeWidth(width); this.__ctx.moveTo(pos[0], pos[1]); this.__ctx.lineCap = 'round'; this.__ctx.lineTo(pos[0] + dir[0], pos[1] + dir[1]); this.__ctx.stroke(); this.__ctx.beginPath(); this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]); // Arrows var arrowSize = 20; var arrowAngle = Math.PI / 5; var dirAngle = Math.atan2(dir[1], dir[0]) + Math.PI; var arrow1 = [ Math.cos(dirAngle + arrowAngle) * arrowSize, Math.sin(dirAngle + arrowAngle) * arrowSize ]; var arrow2 = [ Math.cos(dirAngle - arrowAngle) * arrowSize, Math.sin(dirAngle - arrowAngle) * arrowSize ]; this.__ctx.lineTo(pos[0] + dir[0] + arrow1[0], pos[1] + dir[1] + arrow1[1]); this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]); this.__ctx.lineTo(pos[0] + dir[0] + arrow2[0], pos[1] + dir[1] + arrow2[1]); this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.grid = function (center, count, gap, color, width) { if (color === void 0) { color = [0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1]; } if (width === void 0) { width = 2; } if (!this.__ctx) return; this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.setStrokeWidth(width); var start = [ center[0] - (count[0] / 2) * gap[0], center[1] - (count[1] / 2) * gap[1] ]; for (var i = 0; i <= count[0]; i++) { this.__ctx.moveTo(start[0] + i * gap[0], start[1]); this.__ctx.lineTo(start[0] + i * gap[0], start[1] + count[1] * gap[1]); } for (var i = 0; i <= count[1]; i++) { this.__ctx.moveTo(start[0], start[1] + i * gap[1]); this.__ctx.lineTo(start[0] + count[0] * gap[0], start[1] + i * gap[1]); } this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_paint_ts_225_PaintingContext\\",\\"fields\\":[[\\"markDirtyCallback\\",{\\"type\\":\\"unknown\\"}],[\\"__ctx\\",null],[\\"__gl\\",null],[\\"__offscreen_canvas\\",null],[\\"__program\\",null],[\\"stagedChanges\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPoints\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPointsBuffer\\",null],[\\"__currentColor\\",null],[\\"pointsCounter\\",null],[\\"cacheSize\\",{\\"type\\":\\"array\\",\\"staticSize\\":2}]]}"); }; return PaintingContext; }()); exports.PaintingContext = PaintingContext; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_paint_ts_225_PaintingContext\\",\\"fields\\":[[\\"markDirtyCallback\\",{\\"type\\":\\"unknown\\"}],[\\"__ctx\\",null],[\\"__gl\\",null],[\\"__offscreen_canvas\\",null],[\\"__program\\",null],[\\"stagedChanges\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPoints\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPointsBuffer\\",null],[\\"__currentColor\\",null],[\\"pointsCounter\\",null],[\\"cacheSize\\",{\\"type\\":\\"array\\",\\"staticSize\\":2}]]}"), PaintingContext) }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/buffer.ts": { outputFiles: [ { name: "/_std/buffer.js", writeByteOrderMark: false, text: `var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; define(["require", "exports", "/_std/context", "/std_math"], function (require, exports, context_1, std_math_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buffer = exports.buffer_internal = void 0; var __ = { intifyVector: std_math_1.intifyVector }; var buffer_internal = /** @class */ (function () { function buffer_internal(size, typeName, structure) { var _this = this; this.__opaque_buffer = true; this.structArray = null; this.floatArray = null; this.intArray = null; this.uintArray = null; this.arrayBuffer = null; this.vectorSize = 0; this.platformPayload = null; this.adapter = null; this.dirty = false; this.pendingWrites = 0; this.cpuReadDirty = false; this.cpuWriteDirty = false; this.elementCount = 0; this.elementBytes = 0; this.structured = false; this.watchMutation = false; this.symbol = Symbol(); this.adapter = (0, context_1.getShadeupLocalContext)().shadeupGetGraphicsAdapter(); this.typeName = typeName; if (structure) { if (structure.name && !structure.name.startsWith('atomic')) { this.typeName = structure.name; } } this.elementCount = size; this.elementBytes = 4; if (typeName == 'float4' || typeName == 'float3' || typeName == 'float2' || typeName == 'float') { this.vectorSize = 1; this.fastIndex = function (index) { return _this.floatArray[index]; }; this.fastIndexAssign = function (index, value) { _this.floatArray[index] = value; }; if (typeName == 'float4') { this.vectorSize = 4; this.fastIndex = function (index) { return (0, std_math_1.float4)(_this.floatArray[index * 4], _this.floatArray[index * 4 + 1], _this.floatArray[index * 4 + 2], _this.floatArray[index * 4 + 3]); }; this.fastIndexAssign = function (index, value) { _this.floatArray[index * 4] = value[0]; _this.floatArray[index * 4 + 1] = value[1]; _this.floatArray[index * 4 + 2] = value[2]; _this.floatArray[index * 4 + 3] = value[3]; }; } if (typeName == 'float3') { this.vectorSize = 3; this.fastIndex = function (index) { return (0, std_math_1.float3)(_this.floatArray[index * 3], _this.floatArray[index * 3 + 1], _this.floatArray[index * 3 + 2]); }; this.fastIndexAssign = function (index, value) { _this.floatArray[index * 3] = value[0]; _this.floatArray[index * 3 + 1] = value[1]; _this.floatArray[index * 3 + 2] = value[2]; }; } if (typeName == 'float2') { this.vectorSize = 2; this.fastIndex = function (index) { return (0, std_math_1.float2)(_this.floatArray[index * 2], _this.floatArray[index * 2 + 1]); }; this.fastIndexAssign = function (index, value) { _this.floatArray[index * 2] = value[0]; _this.floatArray[index * 2 + 1] = value[1]; }; } this.floatArray = new Float32Array(size * this.vectorSize); this.arrayBuffer = this.floatArray.buffer; } else if (typeName == 'int4' || typeName == 'int3' || typeName == 'int2' || typeName == 'int') { this.vectorSize = 1; this.fastIndex = function (index) { return _this.intArray[index]; }; this.fastIndexAssign = function (index, value) { _this.intArray[index] = value; }; if (typeName == 'int4') { this.vectorSize = 4; this.fastIndex = function (index) { return __.intifyVector((0, std_math_1.int4)(_this.intArray[index * 4], _this.intArray[index * 4 + 1], _this.intArray[index * 4 + 2], _this.intArray[index * 4 + 3])); }; this.fastIndexAssign = function (index, value) { _this.intArray[index * 4] = value[0]; _this.intArray[index * 4 + 1] = value[1]; _this.intArray[index * 4 + 2] = value[2]; _this.intArray[index * 4 + 3] = value[3]; }; } if (typeName == 'int3') { this.vectorSize = 3; this.fastIndex = function (index) { return __.intifyVector((0, std_math_1.int3)(_this.intArray[index * 3], _this.intArray[index * 3 + 1], _this.intArray[index * 3 + 2])); }; this.fastIndexAssign = function (index, value) { _this.intArray[index * 3] = value[0]; _this.intArray[index * 3 + 1] = value[1]; _this.intArray[index * 3 + 2] = value[2]; }; } if (typeName == 'int2') { this.vectorSize = 2; this.fastIndex = function (index) { return __.intifyVector((0, std_math_1.int2)(_this.intArray[index * 2], _this.intArray[index * 2 + 1])); }; this.fastIndexAssign = function (index, value) { _this.intArray[index * 2] = value[0]; _this.intArray[index * 2 + 1] = value[1]; }; } this.intArray = new Int32Array(size * this.vectorSize); this.arrayBuffer = this.intArray.buffer; } else if (typeName == 'uint4' || typeName == 'uint3' || typeName == 'uint2' || typeName == 'uint') { this.vectorSize = 1; this.fastIndex = function (index) { return _this.uintArray[index]; }; this.fastIndexAssign = function (index, value) { _this.uintArray[index] = value; }; if (typeName == 'uint4') { this.vectorSize = 4; this.fastIndex = function (index) { return (0, std_math_1.uint4)(_this.uintArray[index * 4], _this.uintArray[index * 4 + 1], _this.uintArray[index * 4 + 2], _this.uintArray[index * 4 + 3]); }; this.fastIndexAssign = function (index, value) { _this.uintArray[index * 4] = value[0]; _this.uintArray[index * 4 + 1] = value[1]; _this.uintArray[index * 4 + 2] = value[2]; _this.uintArray[index * 4 + 3] = value[3]; }; } if (typeName == 'uint3') { this.vectorSize = 3; this.fastIndex = function (index) { return (0, std_math_1.uint3)(_this.uintArray[index * 3], _this.uintArray[index * 3 + 1], _this.uintArray[index * 3 + 2]); }; this.fastIndexAssign = function (index, value) { _this.uintArray[index * 3] = value[0]; _this.uintArray[index * 3 + 1] = value[1]; _this.uintArray[index * 3 + 2] = value[2]; }; } if (typeName == 'uint2') { this.vectorSize = 2; this.fastIndex = function (index) { return (0, std_math_1.uint2)(_this.uintArray[index * 2], _this.uintArray[index * 2 + 1]); }; this.fastIndexAssign = function (index, value) { _this.uintArray[index * 2] = value[0]; _this.uintArray[index * 2 + 1] = value[1]; }; } this.uintArray = new Uint32Array(size * this.vectorSize); this.arrayBuffer = this.uintArray.buffer; } else { this.structured = true; if (typeName.startsWith('atomic<')) { // this.structArray = new Array(size); this.arrayBuffer = new ArrayBuffer(size * 4); this.watchMutation = true; this.vectorSize = 1; this.elementBytes = 4; this.elementCount = size; for (var i = 0; i < size; i++) { // this.structArray[i] = atomic(0) as T; } if (typeName == 'atomic') { this.uintArray = new Uint32Array(this.arrayBuffer); this.fastIndex = function (index) { return (0, std_math_1.atomic)(_this.uintArray[index]); }; this.fastIndexAssign = function (index, value) { _this.uintArray[index] = value.__value; }; } else { this.intArray = new Int32Array(this.arrayBuffer); this.fastIndex = function (index) { return (0, std_math_1.atomic)(_this.intArray[index]); }; this.fastIndexAssign = function (index, value) { _this.intArray[index] = value.__value; }; } } else { var elementSize_1 = this.adapter.getValueSize(structure); var realSize = elementSize_1 * size; this.elementCount = size; this.elementBytes = elementSize_1; this.arrayBuffer = new ArrayBuffer(realSize); this.fastIndex = function (index) { return _this.adapter.readStructuredBuffer(structure, _this.arrayBuffer, index * elementSize_1); }; this.fastIndexAssign = function (index, value) { _this.cpuWriteDirty = true; _this.adapter.writeStructuredBuffer(structure, value, _this.arrayBuffer, index * (elementSize_1 / 4)); }; } } this.__index = function (index) { // await this.download(); if (_this.watchMutation) { var data = _this.fastIndex(index); data.$mutate = function (to) { _this.cpuWriteDirty = true; if (to !== undefined) { if (_this.intArray) { _this.intArray[index] = to; } else { _this.uintArray[index] = to; } } }; return data; } else { return _this.fastIndex(index); } }; this.__index_assign = function (index, value) { // await this.download(); _this.cpuWriteDirty = true; _this.fastIndexAssign(index, value); }; this.__index_assign_op = function (op_fn, index, value) { // await this.download(); _this.cpuWriteDirty = true; _this.fastIndexAssign(index, op_fn(_this.fastIndex(index), value)); }; } buffer_internal.prototype.destroy = function () { this.adapter.destroyBuffer(this); }; buffer_internal.prototype.__index = function (index) { // this.download(); // return this.fastIndex(index); return null; }; buffer_internal.prototype.__index_assign = function (index, value) { // this.download(); // this.cpuWriteDirty = true; // this.fastIndexAssign(index, value); }; buffer_internal.prototype.__index_assign_op = function (op_fn, index, value) { // this.download(); // this.cpuWriteDirty = true; // this.fastIndexAssign(index, op_fn(this.fastIndex(index), value)); }; buffer_internal.prototype.len = function () { return this.elementCount; }; /** * Returns the underlying cpu buffer as a typed array. * * > [!NOTE] * > This is considerably faster than using the raw index [] operator. * * > [!NOTE] * > If the buffer contents are structured (atomic, or a struct), this will return a normal array * * \`\`\`shadeup * let buf = buffer(); * let data = buf.getData(); * * for (let i = 0; i < data.length; i += 4) { * // Do something with data[i] * } * \`\`\` */ buffer_internal.prototype.getData = function () { var _a, _b, _c; if (this.structured) { return this.structArray; } else { return (_c = (_b = (_a = this.floatArray) !== null && _a !== void 0 ? _a : this.intArray) !== null && _b !== void 0 ? _b : this.uintArray) !== null && _c !== void 0 ? _c : new Uint8Array(0); } }; buffer_internal.prototype.write = function (other) { if (!this.adapter) return; this.adapter.copyBufferToBuffer(other, this); }; /** @shadeup=tag(async) @shadeup=noemit_gpu */ buffer_internal.prototype.download = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.adapter) return [2 /*return*/]; if (this.pendingWrites > 0) { (0, context_1.getShadeupLocalContext)().flushAdapter(); } if (!this.cpuReadDirty) return [3 /*break*/, 2]; this.cpuReadDirty = false; return [4 /*yield*/, this.adapter.downloadBuffer(this)]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); }; buffer_internal.prototype.downloadAsync = function () { return this['download'](); }; /** @shadeup=noemit_gpu */ buffer_internal.prototype.upload = function () { if (!this.adapter) return; if (this.cpuWriteDirty) { this.cpuWriteDirty = false; this.adapter.uploadBuffer(this); } }; buffer_internal.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_buffer_ts_317_buffer_internal\\",\\"fields\\":[[\\"__opaque_buffer\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"structArray\\",null],[\\"floatArray\\",null],[\\"intArray\\",null],[\\"uintArray\\",null],[\\"arrayBuffer\\",null],[\\"vectorSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"typeName\\",null],[\\"platformPayload\\",null],[\\"adapter\\",null],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pendingWrites\\",null],[\\"cpuReadDirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"cpuWriteDirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"elementCount\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"elementBytes\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"structured\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastIndex\\",{\\"type\\":\\"unknown\\"}],[\\"fastIndexAssign\\",{\\"type\\":\\"unknown\\"}],[\\"watchMutation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"symbol\\",{\\"type\\":\\"unknown\\"}]]}"); }; return buffer_internal; }()); exports.buffer_internal = buffer_internal; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_buffer_ts_317_buffer_internal\\",\\"fields\\":[[\\"__opaque_buffer\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"structArray\\",null],[\\"floatArray\\",null],[\\"intArray\\",null],[\\"uintArray\\",null],[\\"arrayBuffer\\",null],[\\"vectorSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"typeName\\",null],[\\"platformPayload\\",null],[\\"adapter\\",null],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pendingWrites\\",null],[\\"cpuReadDirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"cpuWriteDirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"elementCount\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"elementBytes\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"structured\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastIndex\\",{\\"type\\":\\"unknown\\"}],[\\"fastIndexAssign\\",{\\"type\\":\\"unknown\\"}],[\\"watchMutation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"symbol\\",{\\"type\\":\\"unknown\\"}]]}"), buffer_internal) function buffer(e1, typeName, structure) { if (typeof e1 === 'number') { var size = e1; var buf = new buffer_internal(size, typeName, structure); return buf; } else { var data = e1; var buf = new buffer_internal(data.length, typeName, structure); for (var i = 0; i < data.length; i++) { buf.fastIndexAssign(i, data[i]); } return buf; } } exports.buffer = buffer; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/texture.ts": { outputFiles: [ { name: "/_std/texture.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/_std/context"], function (require, exports, context_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.texture3d = exports.texture3d_internal_empty = exports.texture2d = exports.texture2d_internal_empty = void 0;\n var texture2d_internal_empty = /** @class */ (function () {\n function texture2d_internal_empty() {\n this.__opaque_texture2d = true;\n this.size = [0, 0];\n this.paint = null;\n }\n /** @shadeup=glsl(!texture($self$, $0$)) */\n texture2d_internal_empty.prototype.__index = function (index) {\n return null;\n };\n texture2d_internal_empty.prototype.__index_assign = function (index, value) {\n return null;\n };\n texture2d_internal_empty.prototype.getFast = function (index) {\n return null;\n };\n texture2d_internal_empty.prototype.setFast = function (index, value) {\n return null;\n };\n /** @shadeup=tag(async) */\n texture2d_internal_empty.prototype.download = function () { };\n texture2d_internal_empty.prototype.downloadAsync = function () {\n return null;\n };\n /**\n * Returns the underlying cpu buffer as a typed array.\n *\n * Note that this is considerably faster than using the raw index [] operator.\n *\n * ```shadeup\n * let tex = texture2d();\n * let data = tex.getData();\n *\n * for (let i = 0; i < data.length; i += 4) {\n * let r = data[i];\n * let g = data[i + 1];\n * let b = data[i + 2];\n * let a = data[i + 3];\n *\n * // Do something with the pixel\n * }\n * ```\n */\n texture2d_internal_empty.prototype.getData = function () {\n return new Uint32Array(0);\n };\n texture2d_internal_empty.prototype.upload = function () { };\n texture2d_internal_empty.prototype.sample = function (position) { };\n texture2d_internal_empty.prototype.clear = function (color) {\n if (color === void 0) { color = \'auto\'; }\n };\n texture2d_internal_empty.prototype.flush = function () { };\n /** Release the texture */\n texture2d_internal_empty.prototype.destroy = function () { };\n texture2d_internal_empty.prototype._getStructure = function () {\n return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_texture_ts_434_texture2d_internal_empty\\",\\"fields\\":[[\\"__opaque_texture2d\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"size\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"paint\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_paint_ts_225_PaintingContext\\",\\"fields\\":[[\\"markDirtyCallback\\",{\\"type\\":\\"unknown\\"}],[\\"__ctx\\",null],[\\"__gl\\",null],[\\"__offscreen_canvas\\",null],[\\"__program\\",null],[\\"stagedChanges\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPoints\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPointsBuffer\\",null],[\\"__currentColor\\",null],[\\"pointsCounter\\",null],[\\"cacheSize\\",{\\"type\\":\\"array\\",\\"staticSize\\":2}]]}],[\\"draw\\",{\\"type\\":\\"unknown\\"}],[\\"drawIndexed\\",{\\"type\\":\\"unknown\\"}],[\\"drawAdvanced\\",{\\"type\\":\\"unknown\\"}],[\\"drawInstanced\\",{\\"type\\":\\"unknown\\"}]]}");\n };\n return texture2d_internal_empty;\n }());\n exports.texture2d_internal_empty = texture2d_internal_empty;\n __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_texture_ts_434_texture2d_internal_empty\\",\\"fields\\":[[\\"__opaque_texture2d\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"size\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"paint\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_paint_ts_225_PaintingContext\\",\\"fields\\":[[\\"markDirtyCallback\\",{\\"type\\":\\"unknown\\"}],[\\"__ctx\\",null],[\\"__gl\\",null],[\\"__offscreen_canvas\\",null],[\\"__program\\",null],[\\"stagedChanges\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPoints\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPointsBuffer\\",null],[\\"__currentColor\\",null],[\\"pointsCounter\\",null],[\\"cacheSize\\",{\\"type\\":\\"array\\",\\"staticSize\\":2}]]}],[\\"draw\\",{\\"type\\":\\"unknown\\"}],[\\"drawIndexed\\",{\\"type\\":\\"unknown\\"}],[\\"drawAdvanced\\",{\\"type\\":\\"unknown\\"}],[\\"drawInstanced\\",{\\"type\\":\\"unknown\\"}]]}"), texture2d_internal_empty)\n function texture2d(size, format, type) {\n return (0, context_1.getShadeupLocalContext)().shadeupMakeTextureInternal(size, format, type);\n }\n exports.texture2d = texture2d;\n var texture3d_internal_empty = /** @class */ (function () {\n function texture3d_internal_empty() {\n this.__opaque_texture3d = true;\n this.size = [0, 0, 0];\n }\n /** @shadeup=glsl(!texture($self$, $0$)) */\n texture3d_internal_empty.prototype.__index = function (index) {\n return null;\n };\n texture3d_internal_empty.prototype.__index_assign = function (index, value) { };\n texture3d_internal_empty.prototype.sample = function (position) { };\n texture3d_internal_empty.prototype._getStructure = function () {\n return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_texture_ts_2584_texture3d_internal_empty\\",\\"fields\\":[[\\"__opaque_texture3d\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"size\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}]]}");\n };\n return texture3d_internal_empty;\n }());\n exports.texture3d_internal_empty = texture3d_internal_empty;\n __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_texture_ts_2584_texture3d_internal_empty\\",\\"fields\\":[[\\"__opaque_texture3d\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"size\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}]]}"), texture3d_internal_empty)\n function texture3d(size, type) {\n return (0, context_1.getShadeupLocalContext)().shadeupMakeTextureInternal(size, type);\n }\n exports.texture3d = texture3d;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/drawIndexed.ts": { outputFiles: [ { name: "/_std/drawIndexed.js", writeByteOrderMark: false, text: `define(["require", "exports", "/_std/context", "/_std/buffer", "/std_math"], function (require, exports, context_1, buffer_1, std_math_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.computeIndirect = exports.drawAttributes = exports.drawCount = exports.drawAlt2 = exports.drawFullscreen = exports.draw = exports.drawAdvanced = exports.makeShader = exports.ShaderOutput = exports.ShaderInput = exports.shader_start_shd_ = exports.drawIndirect = exports.drawIndexedIndirect = exports.drawInstancedIndexed = exports.drawInstanced = exports.drawIndexed = void 0; function drawIndexed(indexBuffer, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_indexed(indexBuffer, vertexShader, pixelShader); } exports.drawIndexed = drawIndexed; function drawInstanced(mesh, instanceCount, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_instanced(mesh, instanceCount, vertexShader, pixelShader); } exports.drawInstanced = drawInstanced; function drawInstancedIndexed(indexBuffer, instanceCount, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_instanced_indexed(indexBuffer, instanceCount, vertexShader, pixelShader); } exports.drawInstancedIndexed = drawInstancedIndexed; function drawIndexedIndirect(indirectBuffer, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_indexed_indirect(indirectBuffer, vertexShader, pixelShader); } exports.drawIndexedIndirect = drawIndexedIndirect; function drawIndirect(mesh, indirectBuffer, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_indirect(mesh, indirectBuffer, vertexShader, pixelShader); } exports.drawIndirect = drawIndirect; function shader_start_shd_(s, groupSize) { return s; } exports.shader_start_shd_ = shader_start_shd_; /**@shadeup=struct*/ var ShaderInput = /** @class */ (function () { function ShaderInput() { /** Interpolated world position (available in fragment, and vertex) */ this.position = (0, std_math_1.float3)(0, 0, 0); /** Interpolated normal (fragment), Source mesh normal (vertex) */ this.normal = (0, std_math_1.float3)(0, 0, 0); /** Interpolated tangent (fragment), Source mesh tangent (vertex) */ this.tangent = (0, std_math_1.float3)(0, 0, 0); /** Interpolated bitangent (fragment), Source mesh bitangent (vertex) */ this.bitangent = (0, std_math_1.float3)(0, 0, 0); /** Vertex shader output position */ this.clipPosition = (0, std_math_1.float4)(0, 0, 0, 0); this.realPosition = (0, std_math_1.float4)(0, 0, 0, 0); /** UV channel 0 input (available in fragment, and vertex) */ this.uv = (0, std_math_1.float2)(0, 0); /** Screen position in pixels (available in fragment, and vertex) */ this.screen = (0, std_math_1.float2)(0, 0); /** Interpolated vertex color (available in fragment, and vertex) */ this.color = (0, std_math_1.float4)(0, 0, 0, 0); /** Group ID (available in compute) */ this.groupId = __.intifyVector((0, std_math_1.int3)(0, 0, 0)); /** Group size (available in compute) */ this.groupSize = __.intifyVector((0, std_math_1.int3)(0, 0, 0)); /** Global id (groupId * groupSize + localId) (available in compute) */ this.globalId = __.intifyVector((0, std_math_1.int3)(0, 0, 0)); /** Local id (available in compute) */ this.localId = __.intifyVector((0, std_math_1.int3)(0, 0, 0)); /** Instance index (available in fragment, and vertex) */ this.instanceIndex = 0; /** Vertex index (available in vertex) */ this.vertexIndex = 0; } /** @shadeup=noemit_gpu */ ShaderInput.prototype.attr = function (index, interpolation) { return null; }; ShaderInput.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"ShaderInput\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"tangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"bitangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"clipPosition\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"realPosition\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"groupId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"groupSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"globalId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"localId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"instanceIndex\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"vertexIndex\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}]]}"); }; return ShaderInput; }()); exports.ShaderInput = ShaderInput; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"ShaderInput\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"tangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"bitangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"clipPosition\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"realPosition\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"groupId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"groupSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"globalId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"localId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"instanceIndex\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"vertexIndex\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}]]}"), ShaderInput) /**@shadeup=struct*/ var ShaderOutput = /** @class */ (function () { function ShaderOutput() { /** Vertex output position */ this.position = (0, std_math_1.float4)(0, 0, 0, 0); /** Vertex output normal */ this.normal = (0, std_math_1.float3)(0, 0, 0); /** Vertex output tangent */ this.tangent = (0, std_math_1.float3)(0, 0, 0); /** Vertex output bitangent */ this.bitangent = (0, std_math_1.float3)(0, 0, 0); /** UV channel 0 output */ this.uv = (0, std_math_1.float2)(0, 0); /** Pixel color output */ this.color = (0, std_math_1.float4)(0, 0, 0, 0); } /** @shadeup=noemit_gpu */ ShaderOutput.prototype.attr = function (index, value, interpolation) { }; ShaderOutput.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"ShaderOutput\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"tangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"bitangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}]]}"); }; return ShaderOutput; }()); exports.ShaderOutput = ShaderOutput; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"ShaderOutput\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"tangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"bitangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}]]}"), ShaderOutput) /** @shadeup=shader */ function makeShader(key, fn) { return fn; } exports.makeShader = makeShader; function drawAdvanced(descriptor) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_advanced(descriptor); } exports.drawAdvanced = drawAdvanced; function draw(first, second, third) { if ('vertices' in first && second && third) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_geometry(first, second, third); } else if (first && !second && !third) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw(first); } } exports.draw = draw; function drawFullscreen(first, second, third) { if ('vertices' in first && second && third) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_geometry(first, second, third); } else if (first && !second && !third) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw(first); } } exports.drawFullscreen = drawFullscreen; function drawAlt2(fullScreenPixelShader) { } exports.drawAlt2 = drawAlt2; function drawCount(triCount, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader); } exports.drawCount = drawCount; function drawAttributes(indexBuffer, buffers, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_attributes(indexBuffer, buffer_1.buffer, vertexShader, pixelShader); } exports.drawAttributes = drawAttributes; function computeIndirect(indirectBuffer, indirectOffset, computeShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_compute_indirect(indirectBuffer, indirectOffset, computeShader); } exports.computeIndirect = computeIndirect; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/drawAttributes.ts": { outputFiles: [ { name: "/_std/drawAttributes.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/_std/context", "/_std/buffer"], function (require, exports, context_1, buffer_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.drawAttributes = void 0;\n function drawAttributes(indexBuffer, buffers, vertexShader, pixelShader) {\n (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_attributes(indexBuffer, buffer_1.buffer, vertexShader, pixelShader);\n }\n exports.drawAttributes = drawAttributes;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/drawCount.ts": { outputFiles: [ { name: "/_std/drawCount.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/_std/context"], function (require, exports, context_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.drawCount = void 0;\n function drawCount(triCount, vertexShader, pixelShader) {\n (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader);\n }\n exports.drawCount = drawCount;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/physics.ts": { outputFiles: [ { name: "/_std/physics.js", writeByteOrderMark: false, text: `define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.physics = exports.PhysicsEngine3d = exports.PhysicsEngine2d = exports.PhysicsRigidBody2d = exports.PhysicsRayCastResult2d = exports.PhysicsCollider2d = void 0; var PhysicsCollider2d = /** @class */ (function () { function PhysicsCollider2d(rapier, world, collider) { this.rapier = rapier; this.world = world; this.collider = collider; } PhysicsCollider2d.prototype.setTranslation = function (position) { this.collider.setTranslation(toVec2(position)); }; PhysicsCollider2d.prototype.setRotation = function (rotation) { this.collider.setRotation(rotation); }; PhysicsCollider2d.prototype.setSensor = function (isSensor) { this.collider.setSensor(isSensor); }; PhysicsCollider2d.prototype.setCollisionGroups = function (groups) { this.collider.setCollisionGroups(groups); }; PhysicsCollider2d.prototype.setCollidesWith = function (groups) { this.collider.setActiveCollisionTypes(groups); }; PhysicsCollider2d.prototype.setFriction = function (friction) { this.collider.setFriction(friction); }; PhysicsCollider2d.prototype.setRestitution = function (restitution) { this.collider.setRestitution(restitution); }; PhysicsCollider2d.prototype.setDensity = function (density) { this.collider.setDensity(density); }; PhysicsCollider2d.prototype.setMass = function (mass) { this.collider.setMass(mass); }; PhysicsCollider2d.prototype.setRadius = function (radius) { this.collider.setRadius(radius); }; PhysicsCollider2d.prototype.setHalfExtents = function (halfExtents) { this.collider.setHalfExtents(toVec2(halfExtents)); }; PhysicsCollider2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_232_PhysicsCollider2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null],[\\"collider\\",null]]}"); }; return PhysicsCollider2d; }()); exports.PhysicsCollider2d = PhysicsCollider2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_232_PhysicsCollider2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null],[\\"collider\\",null]]}"), PhysicsCollider2d) function toVec2(v) { return { x: v[0], y: v[1] }; } function toVec3(v) { return { x: v[0], y: v[1], z: v[2] }; } var PhysicsRayCastResult2d = /** @class */ (function () { function PhysicsRayCastResult2d(rapier, result) { this.rapier = rapier; this.result = result; } PhysicsRayCastResult2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_1662_PhysicsRayCastResult2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"result\\",null]]}"); }; return PhysicsRayCastResult2d; }()); exports.PhysicsRayCastResult2d = PhysicsRayCastResult2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_1662_PhysicsRayCastResult2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"result\\",null]]}"), PhysicsRayCastResult2d) var PhysicsRigidBody2d = /** @class */ (function () { function PhysicsRigidBody2d(rapier, world, body) { this.rapier = rapier; this.world = world; this.body = body; } PhysicsRigidBody2d.prototype.addBallCollider = function (radius) { var colDesc = this.rapier.ColliderDesc.ball(radius); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addBoxCollider = function (halfExtents) { var colDesc = this.rapier.ColliderDesc.cuboid(halfExtents[0], halfExtents[1]); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addCapsuleCollider = function (radius, halfHeight) { var colDesc = this.rapier.ColliderDesc.capsule(radius, halfHeight); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addTriangleCollider = function (a, b, c) { var colDesc = this.rapier.ColliderDesc.triangle(toVec2(a), toVec2(b), toVec2(c)); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addConvexCollider = function (points) { var floatarr = new Float32Array(points.length * 2); for (var i = 0; i < points.length; i++) { floatarr[i * 2 + 0] = points[i][0]; floatarr[i * 2 + 1] = points[i][1]; } var colDesc = this.rapier.ColliderDesc.convexHull(floatarr); if (!colDesc) throw new Error('Failed to create convex hull collider'); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addHeightfieldCollider = function (heights, scale) { var arr = new Float32Array(heights.length); for (var i = 0; i < heights.length; i++) { arr[i] = heights[i]; } var colDesc = this.rapier.ColliderDesc.heightfield(arr, toVec2(scale)); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.setTranslation = function (position) { this.body.setTranslation(toVec2(position), true); }; PhysicsRigidBody2d.prototype.setRotation = function (rotation) { this.body.setRotation(rotation, true); }; PhysicsRigidBody2d.prototype.setVelocity = function (velocity) { this.body.setLinvel(toVec2(velocity), true); }; PhysicsRigidBody2d.prototype.setAngularVelocity = function (velocity) { this.body.setAngvel(velocity, true); }; PhysicsRigidBody2d.prototype.addForce = function (force) { this.body.addForce(toVec2(force), true); }; PhysicsRigidBody2d.prototype.addForceAtPoint = function (force, point) { this.body.addForceAtPoint(toVec2(force), toVec2(point), true); }; PhysicsRigidBody2d.prototype.addTorque = function (torque) { this.body.addTorque(torque, true); }; PhysicsRigidBody2d.prototype.setAdditionalMass = function (mass) { this.body.setAdditionalMass(mass, true); }; PhysicsRigidBody2d.prototype.setEnabled = function (enabled) { this.body.setEnabled(enabled); }; PhysicsRigidBody2d.prototype.sleep = function () { this.body.sleep(); }; PhysicsRigidBody2d.prototype.wakeUp = function () { this.body.wakeUp(); }; PhysicsRigidBody2d.prototype.setGravityScale = function (scale) { this.body.setGravityScale(scale, true); }; PhysicsRigidBody2d.prototype.setLinearDamping = function (damping) { this.body.setLinearDamping(damping); }; PhysicsRigidBody2d.prototype.setAngularDamping = function (damping) { this.body.setAngularDamping(damping); }; PhysicsRigidBody2d.prototype.isSleeping = function () { return this.body.isSleeping(); }; PhysicsRigidBody2d.prototype.mass = function () { return this.body.mass(); }; PhysicsRigidBody2d.prototype.translation = function () { var t = this.body.translation(); return [t.x, t.y]; }; PhysicsRigidBody2d.prototype.rotation = function () { return this.body.rotation(); }; PhysicsRigidBody2d.prototype.velocity = function () { var t = this.body.linvel(); return [t.x, t.y]; }; PhysicsRigidBody2d.prototype.angularVelocity = function () { return this.body.angvel(); }; PhysicsRigidBody2d.prototype.isMoving = function () { return this.body.isMoving(); }; PhysicsRigidBody2d.prototype.collider = function (index) { var collider = this.body.collider(index); if (!collider) throw new Error('Failed to get collider'); return new PhysicsCollider2d(this.rapier, this.world, collider); }; PhysicsRigidBody2d.prototype.applyImpulse = function (impulse) { this.body.applyImpulse(toVec2(impulse), true); }; PhysicsRigidBody2d.prototype.applyTorqueImpulse = function (impulse) { this.body.applyTorqueImpulse(impulse, true); }; PhysicsRigidBody2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_1904_PhysicsRigidBody2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null],[\\"body\\",null]]}"); }; return PhysicsRigidBody2d; }()); exports.PhysicsRigidBody2d = PhysicsRigidBody2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_1904_PhysicsRigidBody2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null],[\\"body\\",null]]}"), PhysicsRigidBody2d) var PhysicsEngine2d = /** @class */ (function () { function PhysicsEngine2d(rapier) { this.rapier = rapier; this.world = new rapier.World(new rapier.Vector2(0.0, -9.81)); } PhysicsEngine2d.prototype.step = function () { this.world.step(); }; PhysicsEngine2d.prototype.createRigidBody = function (position, rotation, mode) { var rbDesc = mode == 'dynamic' ? this.rapier.RigidBodyDesc.dynamic() : mode == 'fixed' ? this.rapier.RigidBodyDesc.fixed() : this.rapier.RigidBodyDesc.dynamic(); rbDesc.setTranslation(position[0], position[1]); rbDesc.setRotation(rotation); var rb = this.world.createRigidBody(rbDesc); return new PhysicsRigidBody2d(this.rapier, this.world, rb); }; PhysicsEngine2d.prototype.bodies = function () { var bodies = this.world.bodies; var result = []; for (var i = 0; i < bodies.len(); i++) { result.push(new PhysicsRigidBody2d(this.rapier, this.world, bodies.get(i))); } return result; }; PhysicsEngine2d.prototype.castRay = function (start, end, maxi) { var result = this.world.castRay(new this.rapier.Ray(toVec2(start), toVec2(end)), maxi, true); if (!result) return null; return new PhysicsRigidBody2d(this.rapier, this.world, result.collider.parent()); }; PhysicsEngine2d.prototype.setGravity = function (gravity) { this.world.gravity = toVec2(gravity); }; PhysicsEngine2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_6278_PhysicsEngine2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null]]}"); }; return PhysicsEngine2d; }()); exports.PhysicsEngine2d = PhysicsEngine2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_6278_PhysicsEngine2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null]]}"), PhysicsEngine2d) var PhysicsEngine3d = /** @class */ (function () { function PhysicsEngine3d() { } PhysicsEngine3d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_7687_PhysicsEngine3d\\",\\"fields\\":[]}"); }; return PhysicsEngine3d; }()); exports.PhysicsEngine3d = PhysicsEngine3d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_7687_PhysicsEngine3d\\",\\"fields\\":[]}"), PhysicsEngine3d) var physics; (function (physics) { function engine2d() { return new PhysicsEngine2d(window.RAPIER_2D); } physics.engine2d = engine2d; })(physics = exports.physics || (exports.physics = {})); }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/context.ts": { outputFiles: [ { name: "/_std/context.js", writeByteOrderMark: false, text: `define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getShadeupLocalContext = void 0; var getShadeupLocalContext = function () { if (typeof localEngineContext !== 'undefined') { return localEngineContext; } else { return window; } }; exports.getShadeupLocalContext = getShadeupLocalContext; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/mesh.ts": { outputFiles: [ { name: "/_std/mesh.js", writeByteOrderMark: false, text: `var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; define(["require", "exports", "/std_math", "/std_math", "/std___std_all", "/_std/common"], function (require, exports, __, std_math_1, std___std_all_1, common_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Model = exports.ModelPart = exports.Material = exports.mesh = exports.Mesh = void 0; __ = __importStar(__); var globalVarGet = std___std_all_1.globalVarGet; var Mesh = /** @class */ (function () { function Mesh(data) { var _a, _b, _c, _d, _e, _f, _g, _h; this.vertices = ((_a = data.vertices) !== null && _a !== void 0 ? _a : []); this.triangles = ((_b = data.triangles) !== null && _b !== void 0 ? _b : []); this.normals = ((_c = data.normals) !== null && _c !== void 0 ? _c : []); this.tangents = ((_d = data.tangents) !== null && _d !== void 0 ? _d : []); this.bitangents = ((_e = data.bitangents) !== null && _e !== void 0 ? _e : []); this.uvs = ((_f = data.uvs) !== null && _f !== void 0 ? _f : []); this.colors = ((_g = data.colors) !== null && _g !== void 0 ? _g : []); this.symbol = ((_h = data.symbol) !== null && _h !== void 0 ? _h : null); } Mesh.prototype.rect = function (size) { var shader_self_temp = this; var index = (this.vertices.len() | 0); this.vertices.push(__.makeVector((__.FM.negate_1(size[0])) / (2 | 0), (__.FM.negate_1(size[1])) / (2 | 0), (0 | 0))); this.vertices.push(__.makeVector(size[0] / (2 | 0), (__.FM.negate_1(size[1])) / (2 | 0), (0 | 0))); this.vertices.push(__.makeVector(size[0] / (2 | 0), size[1] / (2 | 0), (0 | 0))); this.vertices.push(__.makeVector((__.FM.negate_1(size[0])) / (2 | 0), size[1] / (2 | 0), (0 | 0))); this.triangles.push(index + (2 | 0)); this.triangles.push(index + (1 | 0)); this.triangles.push(index + (0 | 0)); this.triangles.push(index + (0 | 0)); this.triangles.push(index + (3 | 0)); this.triangles.push(index + (2 | 0)); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((1 | 0), (1 | 0)))); }; Mesh.prototype.quad = function (position, direction, right, size) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9; var shader_self_temp = this; var up = (0, std_math_1.normalize)((0, std_math_1.cross)(right, direction)); var halfSize = (_a = size, _b = 2.0, [_a[0] / _b, _a[1] / _b]); var index = (this.vertices.len() | 0); this.vertices.push((_c = (_e = position, _f = (_g = right, _h = (__.FM.negate_1(halfSize[0])), [_g[0] * _h, _g[1] * _h, _g[2] * _h]), [_e[0] + _f[0], _e[1] + _f[1], _e[2] + _f[2]]), _d = (_j = up, _k = halfSize[1], [_j[0] * _k, _j[1] * _k, _j[2] * _k]), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]])); this.vertices.push((_l = (_o = position, _p = (_q = right, _r = halfSize[0], [_q[0] * _r, _q[1] * _r, _q[2] * _r]), [_o[0] + _p[0], _o[1] + _p[1], _o[2] + _p[2]]), _m = (_s = up, _t = halfSize[1], [_s[0] * _t, _s[1] * _t, _s[2] * _t]), [_l[0] + _m[0], _l[1] + _m[1], _l[2] + _m[2]])); this.vertices.push((_u = (_w = position, _x = (_y = right, _z = halfSize[0], [_y[0] * _z, _y[1] * _z, _y[2] * _z]), [_w[0] + _x[0], _w[1] + _x[1], _w[2] + _x[2]]), _v = (_0 = up, _1 = (__.FM.negate_1(halfSize[1])), [_0[0] * _1, _0[1] * _1, _0[2] * _1]), [_u[0] + _v[0], _u[1] + _v[1], _u[2] + _v[2]])); this.vertices.push((_2 = (_4 = position, _5 = (_6 = right, _7 = (__.FM.negate_1(halfSize[0])), [_6[0] * _7, _6[1] * _7, _6[2] * _7]), [_4[0] + _5[0], _4[1] + _5[1], _4[2] + _5[2]]), _3 = (_8 = up, _9 = (__.FM.negate_1(halfSize[1])), [_8[0] * _9, _8[1] * _9, _8[2] * _9]), [_2[0] + _3[0], _2[1] + _3[1], _2[2] + _3[2]])); this.triangles.push(index + (0 | 0)); this.triangles.push(index + (1 | 0)); this.triangles.push(index + (2 | 0)); this.triangles.push(index + (2 | 0)); this.triangles.push(index + (3 | 0)); this.triangles.push(index + (0 | 0)); this.normals.push(direction); this.normals.push(direction); this.normals.push(direction); this.normals.push(direction); this.tangents.push(right); this.tangents.push(right); this.tangents.push(right); this.tangents.push(right); this.bitangents.push(up); this.bitangents.push(up); this.bitangents.push(up); this.bitangents.push(up); this.uvs.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((1 | 0), (1 | 0)))); }; Mesh.prototype.box = function (size) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; var shader_self_temp = this; var halfSize = (_a = size, _b = 2.0, [_a[0] / _b, _a[1] / _b, _a[2] / _b]); var UP = __.makeVector((0 | 0), 1.0, (0 | 0)); var DOWN = __.makeVector((0 | 0), (__.FM.negate_1(1.0)), (0 | 0)); var LEFT = __.makeVector((__.FM.negate_1(1.0)), (0 | 0), (0 | 0)); var RIGHT = __.makeVector(1.0, (0 | 0), (0 | 0)); var FORWARD = __.makeVector((0 | 0), (0 | 0), 1.0); var BACK = __.makeVector((0 | 0), (0 | 0), (__.FM.negate_1(1.0))); // Up this.quad((_c = UP, _d = halfSize[1], [_c[0] * _d, _c[1] * _d, _c[2] * _d]), UP, LEFT, __.makeVector(size[0], size[2])); // Down this.quad((_e = DOWN, _f = halfSize[1], [_e[0] * _f, _e[1] * _f, _e[2] * _f]), DOWN, RIGHT, __.makeVector(size[0], size[2])); // Left this.quad((_g = LEFT, _h = halfSize[0], [_g[0] * _h, _g[1] * _h, _g[2] * _h]), LEFT, BACK, __.makeVector(size[2], size[1])); // Right this.quad((_j = RIGHT, _k = halfSize[0], [_j[0] * _k, _j[1] * _k, _j[2] * _k]), RIGHT, FORWARD, __.makeVector(size[2], size[1])); // Forward this.quad((_l = FORWARD, _m = halfSize[2], [_l[0] * _m, _l[1] * _m, _l[2] * _m]), FORWARD, LEFT, __.makeVector(size[0], size[1])); // Back this.quad((_o = BACK, _p = halfSize[2], [_o[0] * _p, _o[1] * _p, _o[2] * _p]), BACK, RIGHT, __.makeVector(size[0], size[1])); }; Mesh.prototype.rectAt = function (minPos, maxPos) { var _a, _b; var shader_self_temp = this; this.rect((_a = maxPos, _b = minPos, [_a[0] - _b[0], _a[1] - _b[1]])); this.translate(__.makeVector(minPos, (0 | 0))); }; Mesh.prototype.circle = function (pos, radius, vertices) { if (vertices === void 0) { vertices = (32 | 0); } }; Mesh.prototype.uvSphere = function (pos, radius, vertices, rings) { if (vertices === void 0) { vertices = (32 | 0); } if (rings === void 0) { rings = (16 | 0); } var shader_self_temp = this; var index = (this.vertices.len() | 0); var verticesPerRing = vertices + (1 | 0); for (var i = (0 | 0); i <= rings; i++) { var y = i / rings; var angleY = y * common_1.PI; var posY = Math.cos(angleY); var radiusY = Math.sin(angleY); for (var j = (0 | 0); j <= vertices; j++) { var x = j / vertices; var angleX = x * common_1.PI * (2 | 0); var posX = Math.cos(angleX); var posZ = Math.sin(angleX); this.vertices.push(__.makeVector(posX * radiusY * radius, posY * radius, posZ * radiusY * radius)); this.normals.push((0, std_math_1.normalize)(__.makeVector(posX * radiusY, posY, posZ * radiusY))); var tangent = (0, std_math_1.normalize)(__.makeVector(posZ, (0 | 0), (__.FM.negate_1(posX)))); var bitangent = (0, std_math_1.normalize)((0, std_math_1.cross)(this.normals[(this.normals.len() | 0) - (1 | 0)], tangent)); this.tangents.push(tangent); this.bitangents.push(bitangent); this.uvs.push(__.makeVector(x, y)); } } for (var i = (0 | 0); i < rings; i++) { for (var j = (0 | 0); j < vertices; j++) { var i0 = i * verticesPerRing + j; var i1 = i0 + (1 | 0); var i2 = i0 + verticesPerRing; var i3 = i2 + (1 | 0); this.triangles.push(index + i0); this.triangles.push(index + i1); this.triangles.push(index + i2); this.triangles.push(index + i2); this.triangles.push(index + i1); this.triangles.push(index + i3); } } this.translate(pos); }; Mesh.prototype.icoSphere = function (pos, radius, subdivisions) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v; if (subdivisions === void 0) { subdivisions = (1 | 0); } var shader_self_temp = this; var index = (this.vertices.len() | 0); var t = (1.0 + Math.sqrt(5.0)) / 2.0; var vertices = [__.makeVector((__.FM.negate_1((1 | 0))), t, (0 | 0)), __.makeVector((1 | 0), t, (0 | 0)), __.makeVector((__.FM.negate_1((1 | 0))), (__.FM.negate_1(t)), (0 | 0)), __.makeVector((1 | 0), (__.FM.negate_1(t)), (0 | 0)), __.makeVector((0 | 0), (__.FM.negate_1((1 | 0))), t), __.makeVector((0 | 0), (1 | 0), t), __.makeVector((0 | 0), (__.FM.negate_1((1 | 0))), (__.FM.negate_1(t))), __.makeVector((0 | 0), (1 | 0), (__.FM.negate_1(t))), __.makeVector(t, (0 | 0), (__.FM.negate_1((1 | 0)))), __.makeVector(t, (0 | 0), (1 | 0)), __.makeVector((__.FM.negate_1(t)), (0 | 0), (__.FM.negate_1((1 | 0)))), __.makeVector((__.FM.negate_1(t)), (0 | 0), (1 | 0))]; var triangles = [__.intifyVector(__.makeVector((0 | 0), (11 | 0), (5 | 0))), __.intifyVector(__.makeVector((0 | 0), (5 | 0), (1 | 0))), __.intifyVector(__.makeVector((0 | 0), (1 | 0), (7 | 0))), __.intifyVector(__.makeVector((0 | 0), (7 | 0), (10 | 0))), __.intifyVector(__.makeVector((0 | 0), (10 | 0), (11 | 0))), __.intifyVector(__.makeVector((1 | 0), (5 | 0), (9 | 0))), __.intifyVector(__.makeVector((5 | 0), (11 | 0), (4 | 0))), __.intifyVector(__.makeVector((11 | 0), (10 | 0), (2 | 0))), __.intifyVector(__.makeVector((10 | 0), (7 | 0), (6 | 0))), __.intifyVector(__.makeVector((7 | 0), (1 | 0), (8 | 0))), __.intifyVector(__.makeVector((3 | 0), (9 | 0), (4 | 0))), __.intifyVector(__.makeVector((3 | 0), (4 | 0), (2 | 0))), __.intifyVector(__.makeVector((3 | 0), (2 | 0), (6 | 0))), __.intifyVector(__.makeVector((3 | 0), (6 | 0), (8 | 0))), __.intifyVector(__.makeVector((3 | 0), (8 | 0), (9 | 0))), __.intifyVector(__.makeVector((4 | 0), (9 | 0), (5 | 0))), __.intifyVector(__.makeVector((2 | 0), (4 | 0), (11 | 0))), __.intifyVector(__.makeVector((6 | 0), (2 | 0), (10 | 0))), __.intifyVector(__.makeVector((8 | 0), (6 | 0), (7 | 0))), __.intifyVector(__.makeVector((9 | 0), (8 | 0), (1 | 0)))]; for (var i = (0 | 0); i < (vertices.len() | 0); i++) { this.vertices.push((_a = (0, std_math_1.normalize)(vertices[i]), _b = radius, [_a[0] * _b, _a[1] * _b, _a[2] * _b])); } for (var i = (0 | 0); i < (triangles.len() | 0); i++) { this.triangles.push(index + triangles[i][0]); this.triangles.push(index + triangles[i][1]); this.triangles.push(index + triangles[i][2]); } for (var i = (0 | 0); i < subdivisions; i++) { var newTriangles = []; for (var j = (0 | 0); j < (this.triangles.len() | 0); j = j + (3 | 0)) { var i0 = this.triangles[j + (0 | 0)]; var i1 = this.triangles[j + (1 | 0)]; var i2 = this.triangles[j + (2 | 0)]; var v0 = this.vertices[i0]; var v1 = this.vertices[i1]; var v2 = this.vertices[i2]; var v3 = (0, std_math_1.normalize)((_c = (_e = v0, _f = v1, [_e[0] + _f[0], _e[1] + _f[1], _e[2] + _f[2]]), _d = 2.0, [_c[0] / _d, _c[1] / _d, _c[2] / _d])); var v4 = (0, std_math_1.normalize)((_g = (_j = v1, _k = v2, [_j[0] + _k[0], _j[1] + _k[1], _j[2] + _k[2]]), _h = 2.0, [_g[0] / _h, _g[1] / _h, _g[2] / _h])); var v5 = (0, std_math_1.normalize)((_l = (_o = v2, _p = v0, [_o[0] + _p[0], _o[1] + _p[1], _o[2] + _p[2]]), _m = 2.0, [_l[0] / _m, _l[1] / _m, _l[2] / _m])); var i3 = (this.vertices.len() | 0); var i4 = i3 + (1 | 0); var i5 = i3 + (2 | 0); this.vertices.push((_q = v3, _r = radius, [_q[0] * _r, _q[1] * _r, _q[2] * _r])); this.vertices.push((_s = v4, _t = radius, [_s[0] * _t, _s[1] * _t, _s[2] * _t])); this.vertices.push((_u = v5, _v = radius, [_u[0] * _v, _u[1] * _v, _u[2] * _v])); newTriangles.push(i0, i3, i5); newTriangles.push(i3, i1, i4); newTriangles.push(i3, i4, i5); newTriangles.push(i5, i4, i2); } this.triangles = newTriangles; } for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { var normal = (0, std_math_1.normalize)(this.vertices[i]); var tangent = (0, std_math_1.normalize)(__.makeVector(normal[2], (0 | 0), (__.FM.negate_1(normal[0])))); var bitangent = (0, std_math_1.normalize)((0, std_math_1.cross)(normal, tangent)); this.normals.push(normal); this.tangents.push(tangent); this.bitangents.push(bitangent); } for (var i = (0 | 0); i < (this.triangles.len() | 0); i = i + (3 | 0)) { var i0 = this.triangles[i + (0 | 0)]; var i1 = this.triangles[i + (1 | 0)]; var i2 = this.triangles[i + (2 | 0)]; var v0 = this.vertices[i0]; var v1 = this.vertices[i1]; var v2 = this.vertices[i2]; var uv0 = __.FM.float_2_1_1(__.add((0, std_math_1.atan2)(v0[2], v0[0]) / common_1.PI / 2.0, 0.5), __.add(Math.asin(v0[1]) / common_1.PI, 0.5)); var uv1 = __.FM.float_2_1_1(__.add((0, std_math_1.atan2)(v1[2], v1[0]) / common_1.PI / 2.0, 0.5), __.add(Math.asin(v1[1]) / common_1.PI, 0.5)); var uv2 = __.FM.float_2_1_1(__.add((0, std_math_1.atan2)(v2[2], v2[0]) / common_1.PI / 2.0, 0.5), __.add(Math.asin(v2[1]) / common_1.PI, 0.5)); this.uvs.push(uv0); this.uvs.push(uv1); this.uvs.push(uv2); } this.translate(pos); }; Mesh.prototype.cylinder = function (pos, radius, height, vertices) { if (vertices === void 0) { vertices = (32 | 0); } var shader_self_temp = this; this.translate(pos); }; Mesh.prototype.capsule = function (pos, radius, height, vertices) { if (vertices === void 0) { vertices = (32 | 0); } var shader_self_temp = this; this.translate(pos); }; Mesh.prototype.cone = function (pos, radius, height, vertices) { if (vertices === void 0) { vertices = (32 | 0); } var shader_self_temp = this; var index = (this.vertices.len() | 0); this.translate(pos); }; Mesh.prototype.plane = function (pos, size, subdivisions) { var _a, _b; if (subdivisions === void 0) { subdivisions = __.intifyVector(__.makeVector((2 | 0), (2 | 0))); } var shader_self_temp = this; var index = (this.vertices.len() | 0); var halfSize = (_a = size, _b = 2.0, [_a[0] / _b, _a[1] / _b]); for (var i = (0 | 0); i <= subdivisions[0]; i++) { var x = i / __.swizzle(subdivisions, 'x'); var posX = x * size[0] - halfSize[0]; for (var j = (0 | 0); j <= subdivisions[1]; j++) { var y = j / __.swizzle(subdivisions, 'y'); var posY = y * size[1] - halfSize[1]; this.vertices.push(__.makeVector(posX, (0 | 0), posY)); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.uvs.push(__.makeVector(x, y)); } } for (var i = (0 | 0); i < subdivisions[0]; i++) { for (var j = (0 | 0); j < subdivisions[1]; j++) { var i0 = i * (subdivisions[1] + (1 | 0)) + j; var i1 = i0 + (1 | 0); var i2 = i0 + subdivisions[1] + (1 | 0); var i3 = i2 + (1 | 0); this.triangles.push(index + i0); this.triangles.push(index + i1); this.triangles.push(index + i2); this.triangles.push(index + i2); this.triangles.push(index + i1); this.triangles.push(index + i3); } } this.translate(pos); }; Mesh.prototype.translate = function (pos) { var shader_self_temp = this; for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { this.vertices.__index_assign_op(__.add, i, pos); } return this; }; Mesh.prototype.rotate = function (quaternion) { var shader_self_temp = this; for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { this.vertices.__index_assign(i, common_1.quat.rotate(quaternion, this.vertices[i])); } for (var i = (0 | 0); i < (this.normals.len() | 0); i++) { this.normals.__index_assign(i, common_1.quat.rotate(quaternion, this.normals[i])); } return this; }; Mesh.prototype.transform = function (matrix) { var _a, _b; var shader_self_temp = this; for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { this.vertices.__index_assign(i, (_a = (__.mul(__.makeVector(this.vertices[i], (1 | 0)), matrix)), [_a[0], _a[1], _a[2]])); } for (var i = (0 | 0); i < (this.normals.len() | 0); i++) { this.normals.__index_assign(i, (_b = (__.mul(__.makeVector(this.normals[i], (1 | 0)), matrix)), [_b[0], _b[1], _b[2]])); } return this; }; Mesh.prototype.scale = function (scale) { var shader_self_temp = this; for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { this.vertices.__index_assign_op(__.mul, i, scale); } return this; }; Mesh.prototype.bounds = function () { var _a, _b, _c, _d; var shader_self_temp = this; var mn = (_a = 0.0, [_a, _a, _a]); var mx = (_b = 0.0, [_b, _b, _b]); for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { mn = (0, std_math_1.min)(mn, this.vertices[i]); mx = (0, std_math_1.max)(mx, this.vertices[i]); } return _c = mx, _d = mn, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]; }; Mesh.prototype.center = function () { var _a, _b; var shader_self_temp = this; var bounds = this.bounds(); return _a = bounds, _b = 2.0, [_a[0] / _b, _a[1] / _b, _a[2] / _b]; }; Mesh.new = function () { return new Mesh({ vertices: [], triangles: [], tangents: [], bitangents: [], normals: [], uvs: [], colors: [] }); }; Mesh.prototype.append = function (other) { var shader_self_temp = this; var oldVertices = (this.vertices.len() | 0); var oldTriangles = (this.triangles.len() | 0); this.vertices.append(other.vertices); this.triangles.append(other.triangles); this.normals.append(other.normals); this.tangents.append(other.tangents); this.bitangents.append(other.bitangents); this.uvs.append(other.uvs); this.colors.append(other.colors); for (var i = oldTriangles; i < (this.triangles.len() | 0); i++) { this.triangles.__index_assign_op(__.add, i, oldVertices); } }; Mesh.prototype.getVertices = function () { var shader_self_temp = this; return this.vertices; }; Mesh.prototype.getTriangles = function () { var shader_self_temp = this; return this.triangles; }; Mesh.prototype.getNormals = function () { var shader_self_temp = this; return this.normals; }; Mesh.prototype.getTangents = function () { var shader_self_temp = this; return this.tangents; }; Mesh.prototype.getBitangents = function () { var shader_self_temp = this; return this.bitangents; }; Mesh.prototype.getUVs = function () { var shader_self_temp = this; return this.uvs; }; Mesh.prototype.getColors = function () { var shader_self_temp = this; return this.colors; }; Mesh.prototype.setVertices = function (vertices) { var shader_self_temp = this; this.vertices = vertices; }; Mesh.prototype.setTriangles = function (triangles) { var shader_self_temp = this; this.triangles = triangles; }; Mesh.prototype.setNormals = function (normals) { var shader_self_temp = this; this.normals = normals; }; Mesh.prototype.setTangents = function (tangents) { var shader_self_temp = this; this.tangents = tangents; }; Mesh.prototype.setBitangents = function (bitangents) { var shader_self_temp = this; this.bitangents = bitangents; }; Mesh.prototype.setUVs = function (uvs) { var shader_self_temp = this; this.uvs = uvs; }; Mesh.prototype.setColors = function (colors) { var shader_self_temp = this; this.colors = colors; }; Mesh.prototype.clone = function () { return new Mesh({ vertices: (0, std___std_all_1.__deepClone)(this.vertices), triangles: (0, std___std_all_1.__deepClone)(this.triangles), normals: (0, std___std_all_1.__deepClone)(this.normals), tangents: (0, std___std_all_1.__deepClone)(this.tangents), bitangents: (0, std___std_all_1.__deepClone)(this.bitangents), uvs: (0, std___std_all_1.__deepClone)(this.uvs), colors: (0, std___std_all_1.__deepClone)(this.colors), symbol: (0, std___std_all_1.__deepClone)(this.symbol), }); }; Mesh.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}"); }; return Mesh; }()); exports.Mesh = Mesh; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}"), Mesh) ; /* impl Mesh */ var mesh = /** @class */ (function () { function mesh(data) { } mesh.rect = function (pos, size) { var _a, _b; var g = Mesh.new(); g.rectAt(pos, (_a = pos, _b = size, [_a[0] + _b[0], _a[1] + _b[1]])); return g; }; mesh.box = function (pos, size) { var g = Mesh.new(); g.box(size); g.translate(pos); return g; }; mesh.uvSphere = function (pos, radius, vertices, rings) { if (vertices === void 0) { vertices = (32 | 0); } if (rings === void 0) { rings = (16 | 0); } var g = Mesh.new(); g.uvSphere(pos, radius, vertices, rings); return g; }; mesh.icoSphere = function (pos, radius, subdivisions) { if (subdivisions === void 0) { subdivisions = (1 | 0); } var g = Mesh.new(); g.icoSphere(pos, radius, subdivisions); return g; }; mesh.plane = function (pos, size, subdivisions) { if (subdivisions === void 0) { subdivisions = __.intifyVector(__.makeVector((2 | 0), (2 | 0))); } var g = Mesh.new(); g.plane(pos, size, subdivisions); return g; }; /** * Returns a [-1, 1] position for a given index. */ mesh.triangleFromIndex = function (index) { if (index == (0 | 0)) { return __.FM.float_2_1_1(__.negate((1 | 0)), __.int(1)); } else if (index == (1 | 0)) { return __.FM.float_2_1_1(__.int(1), __.int(1)); } else if (index == (2 | 0)) { return __.FM.float_2_1_1(__.int(0), __.negate((1 | 0))); } else { return __.FM.float_2_1_1(__.int(0), __.int(0)); } }; mesh.circleFromIndex = function (vertexIndex, vertices) { vertexIndex = vertices - vertexIndex; var numSlices = vertices / (3 | 0); var sliceIndex = Math.floor(vertexIndex / vertices * numSlices); var incAngle = common_1.PI * 2.0 / numSlices; var baseAngle = incAngle * sliceIndex; if (vertexIndex % (3 | 0) == (0 | 0)) { return __.FM.float_2_1_1(__.int(0), __.int(0)); } else if (vertexIndex % (3 | 0) == (1 | 0)) { return __.FM.float_2_1_1((0, std_math_1.cos)(baseAngle), (0, std_math_1.sin)(baseAngle)); } else { return __.FM.float_2_1_1((0, std_math_1.cos)(baseAngle + incAngle), (0, std_math_1.sin)(baseAngle + incAngle)); } }; mesh.rectFromIndex = function (index, vertices) { var _a, _b, _c, _d, _e, _f; var x = index % vertices; var y = index / vertices; return _a = (_c = (_e = __.FM.float_2_1_1(x, y), _f = vertices, [_e[0] / _f, _e[1] / _f]), _d = 2.0, [_c[0] * _d, _c[1] * _d]), _b = 1.0, [_a[0] - _b, _a[1] - _b]; }; mesh.empty = function (numVerts) { var _a, _b, _c, _d, _e, _f; if (numVerts === void 0) { numVerts = (0 | 0); } var g = Mesh.new(); if (numVerts > (0 | 0)) { g.setVertices((0, std___std_all_1.array)(numVerts, (_a = (0 | 0), [_a, _a, _a]))); g.setNormals((0, std___std_all_1.array)(numVerts, (_b = (0 | 0), [_b, _b, _b]))); g.setTangents((0, std___std_all_1.array)(numVerts, (_c = (0 | 0), [_c, _c, _c]))); g.setBitangents((0, std___std_all_1.array)(numVerts, (_d = (0 | 0), [_d, _d, _d]))); g.setUVs((0, std___std_all_1.array)(numVerts, (_e = (0 | 0), [_e, _e]))); g.setColors((0, std___std_all_1.array)(numVerts, (_f = (0 | 0), [_f, _f, _f, _f]))); var tris = (0, std___std_all_1.array)(numVerts, (0 | 0)); for (var i = (0 | 0); i < numVerts; i++) { tris.__index_assign(i, i); } g.setTriangles(tris); } return g; }; mesh.join = function (mesh1, mesh2) { var g = Mesh.new(); g.append(mesh1); g.append(mesh2); return g; }; // pub fn cylinder(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.cylinder(pos, radius, height, vertices); // return g; // } // pub fn capsule(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.capsule(pos, radius, height, vertices); // return g; // } // pub fn cone(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.cone(pos, radius, height, vertices); // return g; // } mesh.prototype.clone = function () { return new mesh({}); }; mesh.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_19895_mesh\\",\\"fields\\":[]}"); }; return mesh; }()); exports.mesh = mesh; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_19895_mesh\\",\\"fields\\":[]}"), mesh) ; /* impl mesh */ var Material = /** @class */ (function () { function Material(data) { var _a, _b, _c, _d, _e, _f, _g; this.baseColor = ((_a = data.baseColor) !== null && _a !== void 0 ? _a : __.FM.float_4_1_1_1_1(0.0, 0.0, 0.0, 0.0)); this.color = ((_b = data.color) !== null && _b !== void 0 ? _b : null); this.normal = ((_c = data.normal) !== null && _c !== void 0 ? _c : null); this.normalScale = ((_d = data.normalScale) !== null && _d !== void 0 ? _d : __.FM.float_2_1_1(0.0, 0.0)); this.roughness = ((_e = data.roughness) !== null && _e !== void 0 ? _e : null); this.emissive = ((_f = data.emissive) !== null && _f !== void 0 ? _f : null); this.metallic = ((_g = data.metallic) !== null && _g !== void 0 ? _g : null); } Material.prototype.clone = function () { return new Material({ baseColor: (0, std___std_all_1.__deepClone)(this.baseColor), color: (0, std___std_all_1.__deepClone)(this.color), normal: (0, std___std_all_1.__deepClone)(this.normal), normalScale: (0, std___std_all_1.__deepClone)(this.normalScale), roughness: (0, std___std_all_1.__deepClone)(this.roughness), emissive: (0, std___std_all_1.__deepClone)(this.emissive), metallic: (0, std___std_all_1.__deepClone)(this.metallic), }); }; Material.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}"); }; return Material; }()); exports.Material = Material; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}"), Material) ; var ModelPart = /** @class */ (function () { function ModelPart(data) { var _a, _b, _c; this.mesh = ((_a = data.mesh) !== null && _a !== void 0 ? _a : new Mesh({})); this.material = ((_b = data.material) !== null && _b !== void 0 ? _b : new Material({})); this.transform = ((_c = data.transform) !== null && _c !== void 0 ? _c : __.float4x4(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)); } ModelPart.prototype.clone = function () { return new ModelPart({ mesh: (0, std___std_all_1.__deepClone)(this.mesh), material: (0, std___std_all_1.__deepClone)(this.material), transform: (0, std___std_all_1.__deepClone)(this.transform), }); }; ModelPart.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_24666_ModelPart\\",\\"fields\\":[[\\"mesh\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}],[\\"material\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}],[\\"transform\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4x4\\"}]]}"); }; return ModelPart; }()); exports.ModelPart = ModelPart; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_24666_ModelPart\\",\\"fields\\":[[\\"mesh\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}],[\\"material\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}],[\\"transform\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4x4\\"}]]}"), ModelPart) ; var Model = /** @class */ (function () { function Model(data) { var _a; this.parts = ((_a = data.parts) !== null && _a !== void 0 ? _a : []); } Model.prototype.clone = function () { return new Model({ parts: (0, std___std_all_1.__deepClone)(this.parts), }); }; Model.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_25266_Model\\",\\"fields\\":[[\\"parts\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_24666_ModelPart\\",\\"fields\\":[[\\"mesh\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}],[\\"material\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}],[\\"transform\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4x4\\"}]]},\\"staticSize\\":1}]]}"); }; return Model; }()); exports.Model = Model; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_25266_Model\\",\\"fields\\":[[\\"parts\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_24666_ModelPart\\",\\"fields\\":[[\\"mesh\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}],[\\"material\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}],[\\"transform\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4x4\\"}]]},\\"staticSize\\":1}]]}"), Model) ; window.SHD_Mesh = Mesh; window.SHD_Model = Model; window.SHD_ModelPart = ModelPart; window.SHD_Material = Material; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/textures.ts": { outputFiles: [ { name: "/_std/textures.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/std___std_all"], function (require, exports, std___std_all_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n var globalVarGet = std___std_all_1.globalVarGet;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/common.ts": { outputFiles: [ { name: "/_std/common.js", writeByteOrderMark: false, text: `var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; define(["require", "exports", "/std_math", "/std_math", "/std___std_all", "/_std/buffer", "/_std/ui", "/_std/texture"], function (require, exports, __, std_math_1, std___std_all_1, buffer_1, ui_1, texture_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.wrap4 = exports.wrap3 = exports.wrap2 = exports.color = exports.remap1 = exports.remap = exports.tan1 = exports.cos1 = exports.sin1 = exports.hexFromColor = exports.hex = exports.cmykFromColor = exports.cmyk = exports.rgbaFromColor = exports.rgbFromColor = exports.rgba = exports.rgb = exports.hsvaFromColor = exports.hsvFromColor = exports.hsva = exports.hsv = exports.hslaFromColor = exports.hslFromColor = exports.hsla = exports.hsl = exports.screenAA = exports.matrix = exports.noise = exports.reverseMortonCode2 = exports.randColor2 = exports.randColor = exports.mortonCode2 = exports.spatial = exports.bezier = exports.Camera = exports.Camera2d = exports.quat = exports.ui = exports.texture3d = exports.texture2d = exports.buffer = exports.PI = exports.pixelToClip = void 0; __ = __importStar(__); var globalVarGet = std___std_all_1.globalVarGet; Object.defineProperty(exports, "buffer", { enumerable: true, get: function () { return buffer_1.buffer; } }); Object.defineProperty(exports, "ui", { enumerable: true, get: function () { return ui_1.ui; } }); Object.defineProperty(exports, "texture2d", { enumerable: true, get: function () { return texture_1.texture2d; } }); Object.defineProperty(exports, "texture3d", { enumerable: true, get: function () { return texture_1.texture3d; } }); function pixelToClip(pixelPosition) { var _a, _b, _c, _d, _e, _f, _g; var zeroToOne = (_a = pixelPosition, _b = env.screenSize, [_a[0] / _b[0], _a[1] / _b[1]]); var zeroToTwo = (_c = zeroToOne, _d = 2.0, [_c[0] * _d, _c[1] * _d]); var clipSpace = (_e = zeroToTwo, _f = (_g = 1.0, [_g, _g]), [_e[0] - _f[0], _e[1] - _f[1]]); return __.makeVector(clipSpace[0], clipSpace[1] * (__.FM.negate_1(1.0))); } exports.pixelToClip = pixelToClip; ; /** * Value of PI to 35 decimal places. */ var PI = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PI", function () { return 3.14159265358979323846264338327950288; }, function () { return PI; }); exports.PI = PI; var quat = /** @class */ (function () { function quat(data) { } /** * Creates a quaternion from an angle and axis. */ quat.fromAngleAxis = function (angle, axis) { return __.FM.float_4_3_1(__.mul(axis, Math.sin(angle * 0.5)), (0, std_math_1.cos)(angle * 0.5)); }; /** * Multiplies two quaternions and returns the result. */ quat.mul = function (a, b) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; return __.FM.float_4_3_1(__.add((_a = (_c = (_e = b, [_e[0], _e[1], _e[2]]), _d = a[3], [_c[0] * _d, _c[1] * _d, _c[2] * _d]), _b = (_f = (_h = a, [_h[0], _h[1], _h[2]]), _g = b[3], [_f[0] * _g, _f[1] * _g, _f[2] * _g]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]), (0, std_math_1.cross)((_j = a, [_j[0], _j[1], _j[2]]), (_k = b, [_k[0], _k[1], _k[2]]))), __.sub(a[3] * b[3], (0, std_math_1.dot)((_l = a, [_l[0], _l[1], _l[2]]), (_m = b, [_m[0], _m[1], _m[2]])))); }; /** * Rotates a vector by a quaternion and returns the rotated vector. */ quat.rotate = function (quaternion, vector) { var _a; var q = quat.mul(quat.mul(quaternion, __.FM.float_4_3_1(vector, __.int(0))), quat.conjugate(quaternion)); return _a = q, [_a[0], _a[1], _a[2]]; }; /** * Returns the conjugate of the input quaternion. * * The conjugate of a quaternion number is a quaternion with the same magnitudes but with the sign of the imaginary parts changed */ quat.conjugate = function (quaternion) { var _a; return __.FM.float_4_3_1(__.negate((_a = quaternion, [_a[0], _a[1], _a[2]])), __.swizzle(quaternion, 'w')); }; /** * Returns the inverse of the input quaternion. */ quat.inverse = function (quaternion) { var _a, _b; return _a = quat.conjugate(quaternion), _b = (0, std_math_1.dot)(quaternion, quaternion), [_a[0] / _b, _a[1] / _b, _a[2] / _b, _a[3] / _b]; }; /** * Generates a quaternion that rotates from one direction to another via the shortest path. */ quat.fromToRotation = function (from, to) { var _a; var q = (_a = 0.0, [_a, _a, _a, _a]); var d = (0, std_math_1.dot)(from, to); if (d < (__.FM.negate_1(0.999999))) { var right = __.FM.float_3_1_1_1(__.int(1), __.int(0), __.int(0)); var up = __.FM.float_3_1_1_1(__.int(0), __.int(1), __.int(0)); var tmp = (0, std_math_1.cross)(right, from); if ((0, std_math_1.length)(tmp) < 0.000001) { tmp = (0, std_math_1.cross)(up, from); } tmp = (0, std_math_1.normalize)(tmp); q = quat.fromAngleAxis(PI, tmp); } else if (d > 0.999999) { q = __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(1)); } else { q = __.FM.float_4_3_1((0, std_math_1.cross)(from, to), __.add((1 | 0), d)); q = (0, std_math_1.normalize)(q); } return q; }; quat.diff = function (a, b) { var _a, _b; return _a = a, _b = quat.inverse(b), [_a[0] * _b[0], _a[1] * _b[1], _a[2] * _b[2], _a[3] * _b[3]]; }; /** * Generates lookAt quaternion. */ quat.lookAt = function (forward, up) { var right = (0, std_math_1.normalize)((0, std_math_1.cross)(forward, up)); up = (0, std_math_1.normalize)((0, std_math_1.cross)(forward, right)); var m00 = right[0]; var m01 = right[1]; var m02 = right[2]; var m10 = up[0]; var m11 = up[1]; var m12 = up[2]; var m20 = forward[0]; var m21 = forward[1]; var m22 = forward[2]; var num8 = (m00 + m11) + m22; var q = __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(1)); if (num8 > 0.0) { var num = Math.sqrt(num8 + 1.0); var w_1 = num * 0.5; num = 0.5 / num; var x_1 = (m12 - m21) * num; var y_1 = (m20 - m02) * num; var z_1 = (m01 - m10) * num; return __.FM.float_4_1_1_1_1(x_1, y_1, z_1, w_1); } if (__.and((m00 >= m11), (m00 >= m22))) { var num7 = Math.sqrt(((1.0 + m00) - m11) - m22); var num4 = 0.5 / num7; var x_2 = 0.5 * num7; var y_2 = (m01 + m10) * num4; var z_2 = (m02 + m20) * num4; var w_2 = (m12 - m21) * num4; return __.FM.float_4_1_1_1_1(x_2, y_2, z_2, w_2); } if (m11 > m22) { var num6 = Math.sqrt(((1.0 + m11) - m00) - m22); var num3 = 0.5 / num6; var x_3 = (m10 + m01) * num3; var y_3 = 0.5 * num6; var z_3 = (m21 + m12) * num3; var w_3 = (m20 - m02) * num3; return __.FM.float_4_1_1_1_1(x_3, y_3, z_3, w_3); } var num5 = Math.sqrt(((1.0 + m22) - m00) - m11); var num2 = 0.5 / num5; var x = (m20 + m02) * num2; var y = (m21 + m12) * num2; var z = 0.5 * num5; var w = (m01 - m10) * num2; return __.FM.float_4_1_1_1_1(x, y, z, w); }; /** * Smooth interpolation between two quaternions. */ quat.slerp = function (a, b, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; if ((0, std_math_1.length)(a) == 0.0) { if ((0, std_math_1.length)(b) == 0.0) { return __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(1)); } return b; } else if ((0, std_math_1.length)(b) == 0.0) { return a; } var cosHalfAngle = a[3] * b[3] + (0, std_math_1.dot)((_a = a, [_a[0], _a[1], _a[2]]), (_b = b, [_b[0], _b[1], _b[2]])); if (__.or(cosHalfAngle >= 1.0, cosHalfAngle <= (__.FM.negate_1(1.0)))) { return a; } else if (cosHalfAngle < 0.0) { b = (_c = b, _d = (__.FM.negate_1(1.0)), [_c[0] * _d, _c[1] * _d, _c[2] * _d, _c[3] * _d]); cosHalfAngle = (__.FM.negate_1(cosHalfAngle)); } var blendA = 0.0; var blendB = 0.0; if (cosHalfAngle < 0.99) { var halfAngle = Math.acos(cosHalfAngle); var sinHalfAngle = Math.sin(halfAngle); var oneOverSinHalfAngle = 1.0 / sinHalfAngle; blendA = Math.sin(halfAngle * (1.0 - t)) * oneOverSinHalfAngle; blendB = Math.sin(halfAngle * t) * oneOverSinHalfAngle; } else { blendA = 1.0 - t; blendB = t; } var result = __.FM.float_4_3_1(__.add((_e = blendA, _f = (_g = a, [_g[0], _g[1], _g[2]]), [_e * _f[0], _e * _f[1], _e * _f[2]]), (_h = blendB, _j = (_k = b, [_k[0], _k[1], _k[2]]), [_h * _j[0], _h * _j[1], _h * _j[2]])), __.add(blendA * a[3], blendB * b[3])); if ((0, std_math_1.length)(result) > 0.0) { return (0, std_math_1.normalize)(result); } return __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(1)); }; /** * Converts quaternion to matrix. */ quat.toMatrix = function (quaternion) { var x = quaternion[0]; var y = quaternion[1]; var z = quaternion[2]; var w = quaternion[3]; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var xy = x * y2; var xz = x * z2; var yy = y * y2; var yz = y * z2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; var m = __.float4x4(1.0 - (yy + zz), xy + wz, xz - wy, (0 | 0), xy - wz, 1.0 - (xx + zz), yz + wx, (0 | 0), xz + wy, yz - wx, 1.0 - (xx + yy), (0 | 0), (0 | 0), (0 | 0), (0 | 0), 1.0); return m; }; quat.fromEulerAngles = function (angles) { var cr = Math.cos(angles[0] * 0.5); var sr = Math.sin(angles[0] * 0.5); var cp = Math.cos(angles[1] * 0.5); var sp = Math.sin(angles[1] * 0.5); var cy = Math.cos(angles[2] * 0.5); var sy = Math.sin(angles[2] * 0.5); return __.FM.float_4_1_1_1_1(__.sub(sr * cp * cy, cr * sp * sy), __.add(cr * sp * cy, sr * cp * sy), __.sub(cr * cp * sy, sr * sp * cy), __.add(cr * cp * cy, sr * sp * sy)); }; quat.prototype.clone = function () { return new quat({}); }; quat.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_2304_quat\\",\\"fields\\":[]}"); }; return quat; }()); exports.quat = quat; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_2304_quat\\",\\"fields\\":[]}"), quat) ; /* impl quat */ window.shadeupQuat = quat; var Camera2d = /** @class */ (function () { function Camera2d(data) { var _a, _b; this.position = ((_a = data.position) !== null && _a !== void 0 ? _a : __.FM.float_2_1_1(__.int(0), __.int(0))); this.zoom = ((_b = data.zoom) !== null && _b !== void 0 ? _b : (1 | 0)); } Camera2d.prototype.transform = function (position) { var _a, _b, _c, _d; var shader_self_temp = this; return _a = (_c = position, _d = this.position, [_c[0] - _d[0], _c[1] - _d[1]]), _b = this.zoom, [_a[0] * _b, _a[1] * _b]; }; /** * Moves and zooms the camera to fit the given size. (centers the camera in the viewport) */ Camera2d.prototype.fit = function (size) { var _a, _b, _c, _d, _e, _f; var shader_self_temp = this; var zoom = (1 | 0) / (0, std_math_1.min)(env.screenSize[0] / size[0], env.screenSize[1] / size[1]); var position = (_a = (_c = env.screenSize, _d = (_e = size, _f = ((1 | 0) / zoom), [_e[0] * _f, _e[1] * _f]), [_c[0] - _d[0], _c[1] - _d[1]]), _b = (2 | 0), [_a[0] / _b, _a[1] / _b]); this.position = position; this.zoom = zoom; }; Camera2d.prototype.clone = function () { return new Camera2d({ position: (0, std___std_all_1.__deepClone)(this.position), zoom: (0, std___std_all_1.__deepClone)(this.zoom), }); }; Camera2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_9812_Camera2d\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"zoom\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"); }; return Camera2d; }()); exports.Camera2d = Camera2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_9812_Camera2d\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"zoom\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"), Camera2d) ; /* impl Camera2d */ var Camera = /** @class */ (function () { function Camera(data) { var _a, _b, _c, _d, _e, _f, _g; this.position = ((_a = data.position) !== null && _a !== void 0 ? _a : __.FM.float_3_1_1_1(__.int(0), __.int(0), __.int(0))); this.rotation = ((_b = data.rotation) !== null && _b !== void 0 ? _b : __.FM.float_4_1_1_1_1(__.int(1), __.int(0), __.int(0), __.int(0))); this.width = ((_c = data.width) !== null && _c !== void 0 ? _c : (1920 | 0)); this.height = ((_d = data.height) !== null && _d !== void 0 ? _d : (1080 | 0)); this.fov = ((_e = data.fov) !== null && _e !== void 0 ? _e : (90 | 0)); this.near = ((_f = data.near) !== null && _f !== void 0 ? _f : (1 | 0)); this.far = ((_g = data.far) !== null && _g !== void 0 ? _g : (100000 | 0)); } Camera.prototype.getRay = function (screen) { var shader_self_temp = this; var aspect = this.width / this.height; var x = screen[0]; var y = screen[1]; var Px = ((2 | 0) * ((x + 0.5) / this.width) - (1 | 0)) * Math.tan(this.fov / (2 | 0) * PI / (180 | 0)) * aspect; var Py = ((1 | 0) - (2 | 0) * ((y + 0.5) / this.height)) * Math.tan(this.fov / (2 | 0) * PI / (180 | 0)); return quat.rotate(this.rotation, (0, std_math_1.normalize)(__.makeVector(Px, Py, (__.FM.negate_1((1 | 0)))))); }; Camera.prototype.getTransformToViewMatrix = function (position, scale, rotation) { var shader_self_temp = this; var rotationMatrix = quat.toMatrix(rotation); var translationMatrix = __.float4x4(scale[0], (0 | 0), (0 | 0), (0 | 0), (0 | 0), scale[1], (0 | 0), (0 | 0), (0 | 0), (0 | 0), scale[2], (0 | 0), position[0], position[1], position[2], (1 | 0)); return __.mul(__.mul(__.mul(this.getPerspectiveMatrix(), this.getWorldToViewMatrix()), translationMatrix), rotationMatrix); }; Camera.prototype.getCombinedMatrix = function () { var shader_self_temp = this; return __.mul(this.getPerspectiveMatrix(), this.getWorldToViewMatrix()); }; Camera.prototype.getCombinedMatrixReverseZ = function () { var shader_self_temp = this; return __.mul(this.getPerspectiveMatrixReverseZ(), this.getWorldToViewMatrix()); }; Camera.prototype.getWorldToViewMatrix = function () { var shader_self_temp = this; var rotationMatrix = quat.toMatrix(this.rotation); var translationMatrix = __.float4x4((1 | 0), (0 | 0), (0 | 0), (0 | 0), (0 | 0), (1 | 0), (0 | 0), (0 | 0), (0 | 0), (0 | 0), (1 | 0), (0 | 0), this.position[0], this.position[1], this.position[2], (1 | 0)); return (0, std_math_1.inverse)(__.mul(translationMatrix, rotationMatrix)); }; Camera.prototype.getPerspectiveMatrixReverseZ = function () { var shader_self_temp = this; return matrix.perspectiveReverseZ(this.fov, this.width / this.height, this.near); }; Camera.prototype.getPerspectiveMatrix = function () { var shader_self_temp = this; return matrix.perspective(this.fov, this.width / this.height, this.near, this.far); // // let matrix = float4x4(); // let far = self.far; // let near = self.near; // let aspect = self.width / self.height; // let fovRad = radians(self.fov); // let tanFov = tan( fovRad * 0.5 ); // // matrix[0][0] = ; // // matrix[1][1] = 1.0 / tanFov; // // matrix[2][2] = -((far + near)/(far - near)); // // matrix[3][2] = -((2*(near*far))/(far - near)); // // matrix[2][3] = -1; // // matrix[3][3] = 0; // let matrix = float4x4( // 1.0 / (tanFov * aspect), 0, 0, 0, // 0, 1.0 / tanFov, 0, 0, // 0, 0, -((far + near)/(far - near)), -1, // 0, 0, -((2*(near*far))/(far - near)), 0 // ); // return matrix; }; Camera.prototype.getOrthographicMatrix = function () { var shader_self_temp = this; var matrix = __.float4x4(); var far = this.far; var near = this.near; var w = 1.0 / this.width; var h = 1.0 / this.height; matrix.__index((0 | 0)).__index_assign((0 | 0), w); matrix.__index((1 | 0)).__index_assign((1 | 0), h); matrix.__index((2 | 0)).__index_assign((2 | 0), (__.FM.negate_1((2.0 / (far - near))))); matrix.__index((2 | 0)).__index_assign((3 | 0), ((far + near) / (far - near))); //matrix[2][2] = -((far + near)/(far - near)); //matrix[3][2] = -((2*(near*far))/(far - near)); matrix.__index((3 | 0)).__index_assign((3 | 0), 1.0); return matrix; }; Camera.prototype.clone = function () { return new Camera({ position: (0, std___std_all_1.__deepClone)(this.position), rotation: (0, std___std_all_1.__deepClone)(this.rotation), width: (0, std___std_all_1.__deepClone)(this.width), height: (0, std___std_all_1.__deepClone)(this.height), fov: (0, std___std_all_1.__deepClone)(this.fov), near: (0, std___std_all_1.__deepClone)(this.near), far: (0, std___std_all_1.__deepClone)(this.far), }); }; Camera.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_10837_Camera\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"rotation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"width\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"height\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"fov\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"near\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"far\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"); }; return Camera; }()); exports.Camera = Camera; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_10837_Camera\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"rotation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"width\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"height\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"fov\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"near\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"far\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"), Camera) ; /* impl Camera */ window._makeCamera = Camera; window._makeCamera2d = Camera2d; function easeA(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; } function easeB(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; } function easeC(aA1) { return 3.0 * aA1; } function calcBezier(aT, aA1, aA2) { return ((easeA(aA1, aA2) * aT + easeB(aA1, aA2)) * aT + easeC(aA1)) * aT; } function getSlope(aT, aA1, aA2) { return 3.0 * easeA(aA1, aA2) * aT * aT + 2.0 * easeB(aA1, aA2) * aT + easeC(aA1); } // fn getTForX(aX: float, aA1: float, aA2: float) -> float { // let aGuessT = aX; // for (let i = 0; i <= 10; i++) { // let currentSlope = bezSlope(aGuessT, aA1, aA2); // if (currentSlope == 0.0) { // return aGuessT; // } // let currentX = calcBezier(aGuessT, aA1, aA2) - aX; // aGuessT -= currentX / currentSlope; // } // return aGuessT; // } var NEWTON_ITERATIONS = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "NEWTON_ITERATIONS", function () { return (4 | 0); }, function () { return NEWTON_ITERATIONS; }) | 0); var NEWTON_MIN_SLOPE = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "NEWTON_MIN_SLOPE", function () { return 0.02; }, function () { return NEWTON_MIN_SLOPE; }); var SUBDIVISION_PRECISION = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "SUBDIVISION_PRECISION", function () { return 0.0000001; }, function () { return SUBDIVISION_PRECISION; }); var SUBDIVISION_MAX_ITERATIONS = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "SUBDIVISION_MAX_ITERATIONS", function () { return (10 | 0); }, function () { return SUBDIVISION_MAX_ITERATIONS; }) | 0); var kSplineTableSize = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "kSplineTableSize", function () { return (11 | 0); }, function () { return kSplineTableSize; }) | 0); var kSampleStepSize = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "kSampleStepSize", function () { return 1.0 / __.sub(kSplineTableSize, (1 | 0)); }, function () { return kSampleStepSize; }); function getTForX(aX, mX1, mX2) { var mSampleValues = (0, std___std_all_1.array)((11 | 0), (0 | 0)); for (var i = (0 | 0); i < kSplineTableSize; i++) { mSampleValues.__index_assign(i, calcBezier(i * kSampleStepSize, mX1, mX2)); } // Find interval where t lies var intervalStart = 0.0; var currentSample = (1 | 0); var lastSample = kSplineTableSize - (1 | 0); for (var dummy = (0 | 0); __.and(currentSample != lastSample, mSampleValues[currentSample] <= aX); currentSample++) { intervalStart = intervalStart + kSampleStepSize; } currentSample--; // t now lies between *currentSample and *currentSample+1 // Interpolate to provide an initial guess for t var csamp = mSampleValues[currentSample]; var dst = (aX - csamp) / (mSampleValues[currentSample + (1 | 0)] - csamp); var guessForT = intervalStart + dst * kSampleStepSize; // Check the slope to see what strategy to use. If the slope is too small // Newton-Raphson iteration won't converge on a root so we use bisection // instead. var initialSlope = getSlope(guessForT, mX1, mX2); if (initialSlope >= NEWTON_MIN_SLOPE) { return newtonRaphsonIterate(aX, guessForT, mX1, mX2); } else if (initialSlope == 0.0) { return guessForT; } else { return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize); } } function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { for (var i = (0 | 0); i < NEWTON_ITERATIONS; i++) { // We're trying to find where f(t) = aX, // so we're actually looking for a root for: CalcBezier(t) - aX var currentX = calcBezier(aGuessT, mX1, mX2) - aX; var currentSlope = getSlope(aGuessT, mX1, mX2); if (currentSlope == 0.0) return aGuessT; aGuessT = aGuessT - currentX / currentSlope; } return aGuessT; } function binarySubdivide(aX, aA, aB) { var currentX = 0.0; var currentT = 0.0; var i = (0 | 0); var mX1 = aA; var mX2 = aB; while ((true)) { i++; if (__.and(Math.abs(currentX) > SUBDIVISION_PRECISION, i < SUBDIVISION_MAX_ITERATIONS)) { currentT = aA + (aB - aA) / 2.0; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0.0) { aB = currentT; } else { aA = currentT; } } else { break; } } return currentT; } var bezier = /** @class */ (function () { function bezier(data) { } bezier.cubic2 = function (a, b, c, d, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; return _a = (_c = (_e = (_g = __.pow((1.0 - t), (3 | 0)), _h = a, [_g * _h[0], _g * _h[1]]), _f = (_j = 3.0 * __.pow((1.0 - t), (2 | 0)) * t, _k = b, [_j * _k[0], _j * _k[1]]), [_e[0] + _f[0], _e[1] + _f[1]]), _d = (_l = 3.0 * (1.0 - t) * __.pow(t, (2 | 0)), _m = c, [_l * _m[0], _l * _m[1]]), [_c[0] + _d[0], _c[1] + _d[1]]), _b = (_o = __.pow(t, (3 | 0)), _p = d, [_o * _p[0], _o * _p[1]]), [_a[0] + _b[0], _a[1] + _b[1]]; }; bezier.cubic3 = function (a, b, c, d, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; return _a = (_c = (_e = (_g = __.pow((1.0 - t), (3 | 0)), _h = a, [_g * _h[0], _g * _h[1], _g * _h[2]]), _f = (_j = 3.0 * __.pow((1.0 - t), (2 | 0)) * t, _k = b, [_j * _k[0], _j * _k[1], _j * _k[2]]), [_e[0] + _f[0], _e[1] + _f[1], _e[2] + _f[2]]), _d = (_l = 3.0 * (1.0 - t) * __.pow(t, (2 | 0)), _m = c, [_l * _m[0], _l * _m[1], _l * _m[2]]), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]]), _b = (_o = __.pow(t, (3 | 0)), _p = d, [_o * _p[0], _o * _p[1], _o * _p[2]]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]; }; bezier.quadratic2 = function (a, b, c, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; return _a = (_c = (_e = __.pow((1.0 - t), (2 | 0)), _f = a, [_e * _f[0], _e * _f[1]]), _d = (_g = 2.0 * (1.0 - t) * t, _h = b, [_g * _h[0], _g * _h[1]]), [_c[0] + _d[0], _c[1] + _d[1]]), _b = (_j = __.pow(t, (2 | 0)), _k = c, [_j * _k[0], _j * _k[1]]), [_a[0] + _b[0], _a[1] + _b[1]]; }; bezier.quadratic3 = function (a, b, c, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; return _a = (_c = (_e = __.pow((1.0 - t), (2 | 0)), _f = a, [_e * _f[0], _e * _f[1], _e * _f[2]]), _d = (_g = 2.0 * (1.0 - t) * t, _h = b, [_g * _h[0], _g * _h[1], _g * _h[2]]), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]]), _b = (_j = __.pow(t, (2 | 0)), _k = c, [_j * _k[0], _j * _k[1], _j * _k[2]]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]; }; /** * 3d triangle patch evaulation with barycentric coordinates. */ bezier.patch = function (a, ab, b, bc, c, ca, barycentricT) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15; var s = barycentricT[0]; var t = barycentricT[1]; var u = barycentricT[2]; return _a = (_c = (_e = (_g = (_j = (_l = (_o = 1.0, _p = c, [_o * _p[0], _o * _p[1], _o * _p[2]]), _m = (s * s), [_l[0] * _m, _l[1] * _m, _l[2] * _m]), _k = (_q = (_s = (_u = 2.0, _v = bc, [_u * _v[0], _u * _v[1], _u * _v[2]]), _t = s, [_s[0] * _t, _s[1] * _t, _s[2] * _t]), _r = t, [_q[0] * _r, _q[1] * _r, _q[2] * _r]), [_j[0] + _k[0], _j[1] + _k[1], _j[2] + _k[2]]), _h = (_w = (_y = (_0 = 2.0, _1 = ca, [_0 * _1[0], _0 * _1[1], _0 * _1[2]]), _z = s, [_y[0] * _z, _y[1] * _z, _y[2] * _z]), _x = u, [_w[0] * _x, _w[1] * _x, _w[2] * _x]), [_g[0] + _h[0], _g[1] + _h[1], _g[2] + _h[2]]), _f = (_2 = (_4 = 1.0, _5 = b, [_4 * _5[0], _4 * _5[1], _4 * _5[2]]), _3 = (t * t), [_2[0] * _3, _2[1] * _3, _2[2] * _3]), [_e[0] + _f[0], _e[1] + _f[1], _e[2] + _f[2]]), _d = (_6 = (_8 = (_10 = 2.0, _11 = ab, [_10 * _11[0], _10 * _11[1], _10 * _11[2]]), _9 = t, [_8[0] * _9, _8[1] * _9, _8[2] * _9]), _7 = u, [_6[0] * _7, _6[1] * _7, _6[2] * _7]), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]]), _b = (_12 = (_14 = 1.0, _15 = a, [_14 * _15[0], _14 * _15[1], _14 * _15[2]]), _13 = (u * u), [_12[0] * _13, _12[1] * _13, _12[2] * _13]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]; }; bezier.easing = function (controlA, controlB, t) { return calcBezier(getTForX(t, controlA[0], controlB[0]), controlA[1], controlB[1]); }; bezier.prototype.clone = function () { return new bezier({}); }; bezier.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_20500_bezier\\",\\"fields\\":[]}"); }; return bezier; }()); exports.bezier = bezier; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_20500_bezier\\",\\"fields\\":[]}"), bezier) ; /* impl bezier */ /** * Provides space related utilities like z-order curves and quadtrees. */ var spatial = /** @class */ (function () { function spatial(data) { } spatial.cantorPair = function (v) { return ((v[0] + v[1]) * (v[0] + v[1] + (1 | 0))) / (2 | 0) + v[1]; }; spatial.cantorUnpair = function (v) { var w = Math.floor((Math.sqrt(8.0 * v + 1.0) - 1.0) / 2.0); var t = (w * w + w) / 2.0; var y = v - t; var x = w - y; return __.FM.int_2_1_1(x, y); }; spatial.hilbertRotate = function (n, b, r) { var x = b[0]; var y = b[1]; if (r[1] == (0 | 0)) { if (r[0] == (1 | 0)) { x = n - (1 | 0) - x; y = n - (1 | 0) - y; } var t = x; x = y; y = t; } return __.FM.int_2_1_1(x, y); }; spatial.hilbertUncurve = function (n, v) { var x = v[0]; var y = v[1]; var rx = (0 | 0); var ry = (0 | 0); var s = (0 | 0); var d = (0 | 0); for (s = n / (2 | 0); s > (0 | 0); s = s / (2 | 0)) { rx = ((x & s) > (0 | 0)) ? (1 | 0) : (0 | 0); ry = ((y & s) > (0 | 0)) ? (1 | 0) : (0 | 0); d = d + s * s * (((3 | 0) * rx) ^ ry); var o = __.intifyVector(spatial.hilbertRotate(n, __.intifyVector(__.makeVector(x, y)), __.intifyVector(__.makeVector(rx, ry)))); x = o[0]; y = o[1]; } return d; }; spatial.hilbertCurve = function (n, v) { var rx = (0 | 0); var ry = (0 | 0); var t = v; var x = (0 | 0); var y = (0 | 0); for (var s = (1 | 0); s < n; s = s * (2 | 0)) { rx = (1 | 0) & (t / (2 | 0)); ry = (1 | 0) & (t ^ rx); var o = __.intifyVector(spatial.hilbertRotate(s, __.intifyVector(__.makeVector(x, y)), __.intifyVector(__.makeVector(rx, ry)))); x = o[0]; y = o[1]; x = x + s * rx; y = y + s * ry; t = t / (4 | 0); } return __.FM.int_2_1_1(x, y); }; spatial.mortonDecode = function (p) { return __.FM.uint_2_1_1(reverseMortonCode2(p), reverseMortonCode2(p >> (1 >>> 0))); }; spatial.mortonEncode = function (p) { return (__.bitor(mortonCode2(p[0]), (mortonCode2(p[1]) << (1 >>> 0))) >>> 0); }; spatial.prototype.clone = function () { return new spatial({}); }; spatial.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_23054_spatial\\",\\"fields\\":[]}"); }; return spatial; }()); exports.spatial = spatial; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_23054_spatial\\",\\"fields\\":[]}"), spatial) ; /* impl spatial */ function mortonCode2(x) { x = x & (0x0000ffff >>> 0); var n8 = (8 >>> 0); var n4 = (4 >>> 0); var n2 = (2 >>> 0); var n1 = (1 >>> 0); x = (x ^ (x << n8)) & (0x00ff00ff >>> 0); x = (x ^ (x << n4)) & (0x0f0f0f0f >>> 0); x = (x ^ (x << n2)) & (0x33333333 >>> 0); x = (x ^ (x << n1)) & (0x55555555 >>> 0); return x; } exports.mortonCode2 = mortonCode2; ; function randColor(seed) { return __.FM.float_4_1_1_1_1((0, std_math_1.rand2)(__.makeVector(seed, (5 | 0))), (0, std_math_1.rand2)(__.makeVector(seed, (1 | 0))), (0, std_math_1.rand2)(__.makeVector(seed, (4 | 0))), __.int(1)); } exports.randColor = randColor; ; function randColor2(seed) { return __.FM.float_4_1_1_1_1((0, std_math_1.rand3)(__.makeVector(seed, (5 | 0))), (0, std_math_1.rand3)(__.makeVector(seed, (1 | 0))), (0, std_math_1.rand3)(__.makeVector(seed, (4 | 0))), __.int(1)); } exports.randColor2 = randColor2; ; function reverseMortonCode2(x) { x = x & (0x55555555 >>> 0); x = (x ^ (x >> (1 >>> 0))) & (0x33333333 >>> 0); x = (x ^ (x >> (2 >>> 0))) & (0x0f0f0f0f >>> 0); x = (x ^ (x >> (4 >>> 0))) & (0x00ff00ff >>> 0); x = (x ^ (x >> (8 >>> 0))) & (0x0000ffff >>> 0); return x; } exports.reverseMortonCode2 = reverseMortonCode2; ; var noise = /** @class */ (function () { function noise(data) { } noise.gaussian3 = function (v) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17; var p = v; var a = (_a = p, [Math.floor(_a[0]), Math.floor(_a[1]), Math.floor(_a[2])]); var d = (_b = p, _c = a, [_b[0] - _c[0], _b[1] - _c[1], _b[2] - _c[2]]); d = (_d = (_f = d, _g = d, [_f[0] * _g[0], _f[1] * _g[1], _f[2] * _g[2]]), _e = (_h = 3.0, _j = (_k = 2.0, _l = d, [_k * _l[0], _k * _l[1], _k * _l[2]]), [_h - _j[0], _h - _j[1], _h - _j[2]]), [_d[0] * _e[0], _d[1] * _e[1], _d[2] * _e[2]]); var b = (_m = (_p = a, [_p[0], _p[0], _p[1], _p[1]]), _o = __.FM.float_4_1_1_1_1(__.float(0.0), __.float(1.0), __.float(0.0), __.float(1.0)), [_m[0] + _o[0], _m[1] + _o[1], _m[2] + _o[2], _m[3] + _o[3]]); var k1 = perm((_q = b, [_q[0], _q[1], _q[0], _q[1]])); var k2 = perm((_r = (_t = k1, [_t[0], _t[1], _t[0], _t[1]]), _s = (_u = b, [_u[2], _u[2], _u[3], _u[3]]), [_r[0] + _s[0], _r[1] + _s[1], _r[2] + _s[2], _r[3] + _s[3]])); var c = (_v = k2, _w = (_x = a, [_x[2], _x[2], _x[2], _x[2]]), [_v[0] + _w[0], _v[1] + _w[1], _v[2] + _w[2], _v[3] + _w[3]]); var k3 = perm(c); var k4 = perm((_y = c, _z = 1.0, [_y[0] + _z, _y[1] + _z, _y[2] + _z, _y[3] + _z])); var o1 = (0, std_math_1.frac)((_0 = k3, _1 = (1.0 / 41.0), [_0[0] * _1, _0[1] * _1, _0[2] * _1, _0[3] * _1])); var o2 = (0, std_math_1.frac)((_2 = k4, _3 = (1.0 / 41.0), [_2[0] * _3, _2[1] * _3, _2[2] * _3, _2[3] * _3])); var o3 = (_4 = (_6 = o2, _7 = d[2], [_6[0] * _7, _6[1] * _7, _6[2] * _7, _6[3] * _7]), _5 = (_8 = o1, _9 = (1.0 - d[2]), [_8[0] * _9, _8[1] * _9, _8[2] * _9, _8[3] * _9]), [_4[0] + _5[0], _4[1] + _5[1], _4[2] + _5[2], _4[3] + _5[3]]); var o4 = (_10 = (_12 = (_14 = o3, [_14[1], _14[3]]), _13 = d[0], [_12[0] * _13, _12[1] * _13]), _11 = (_15 = (_17 = o3, [_17[0], _17[2]]), _16 = (1.0 - d[0]), [_15[0] * _16, _15[1] * _16]), [_10[0] + _11[0], _10[1] + _11[1]]); return o4[1] * d[1] + o4[0] * (1.0 - d[1]); }; noise.gaussian2 = function (v) { return noise.gaussian3(__.makeVector(v, (0 | 0))); }; noise.noise1 = function (x) { var i = Math.floor(x); var f = (0, std_math_1.frac)(x); var u = f * f * (3.0 - 2.0 * f); return (0, std_math_1.lerp)(hash(i), hash(i + 1.0), u); }; noise.noise2 = function (x) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; var i = (_a = x, [Math.floor(_a[0]), Math.floor(_a[1])]); var f = (0, std_math_1.frac)(x); // Four corners in 2D of a tile var a = hash2(i); var b = hash2((_b = i, _c = __.FM.float_2_1_1(__.float(1.0), __.float(0.0)), [_b[0] + _c[0], _b[1] + _c[1]])); var c = hash2((_d = i, _e = __.FM.float_2_1_1(__.float(0.0), __.float(1.0)), [_d[0] + _e[0], _d[1] + _e[1]])); var d = hash2((_f = i, _g = __.FM.float_2_1_1(__.float(1.0), __.float(1.0)), [_f[0] + _g[0], _f[1] + _g[1]])); // Simple 2D lerp using smoothstep envelope between the values. // return float3(lerp(lerp(a, b, smoothstep(0.0, 1.0, f.x)), // lerp(c, d, smoothstep(0.0, 1.0, f.x)), // smoothstep(0.0, 1.0, f.y))); // Same code, with the clamps in smoothstep and common subexpressions // optimized away. var u = (_h = (_k = f, _l = f, [_k[0] * _l[0], _k[1] * _l[1]]), _j = (_m = 3.0, _o = (_p = 2.0, _q = f, [_p * _q[0], _p * _q[1]]), [_m - _o[0], _m - _o[1]]), [_h[0] * _j[0], _h[1] * _j[1]]); return (0, std_math_1.lerp)(a, b, u[0]) + (c - a) * u[1] * (1.0 - u[0]) + (d - b) * u[0] * u[1]; }; noise.fmb1 = function (x) { var v = 0.0; var a = 0.5; var shift = __.int(100); for (var i = (0 | 0); i < (5 | 0); i++) { v = v + a * noise.noise1(x); x = x * 2.0 + shift; a = a * 0.5; } return v; }; noise.fbm2 = function (x) { var _a, _b, _c, _d; var v = 0.0; var a = 0.5; var shift = __.FM.float_2_2(__.swizzle((100 | 0), "xy")); // Rotate to reduce axial bias var rot = __.float2x2(Math.cos(0.5), Math.sin(0.5), (__.FM.negate_1(Math.sin(0.5))), Math.cos(0.50)); for (var i = (0 | 0); i < (5 | 0); i++) { v = v + a * noise.noise2(x); x = (_a = (_c = __.mul(rot, x), _d = 2.0, [_c[0] * _d, _c[1] * _d]), _b = shift, [_a[0] + _b[0], _a[1] + _b[1]]); a = a * 0.5; } return v; }; noise.fbm3 = function (x) { var _a, _b, _c, _d; var v = 0.0; var a = 0.5; var shift = __.FM.float_3_3(__.swizzle((100 | 0), "xyz")); for (var i = (0 | 0); i < (5 | 0); i++) { v = v + a * noise.noise3(x); x = (_a = (_c = x, _d = 2.0, [_c[0] * _d, _c[1] * _d, _c[2] * _d]), _b = shift, [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]); a = a * 0.5; } return v; }; noise.noise3 = function (x) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; var step = __.FM.float_3_1_1_1(__.int(110), __.int(241), __.int(171)); var i = (_a = x, [Math.floor(_a[0]), Math.floor(_a[1]), Math.floor(_a[2])]); var f = (0, std_math_1.frac)(x); // For performance, compute the base input to a 1D hash from the integer part of the argument and the // incremental change to the 1D based on the 3D -> 1D wrapping var n = (0, std_math_1.dot)(i, step); var u = (_b = (_d = f, _e = f, [_d[0] * _e[0], _d[1] * _e[1], _d[2] * _e[2]]), _c = (_f = 3.0, _g = (_h = 2.0, _j = f, [_h * _j[0], _h * _j[1], _h * _j[2]]), [_f - _g[0], _f - _g[1], _f - _g[2]]), [_b[0] * _c[0], _b[1] * _c[1], _b[2] * _c[2]]); return (0, std_math_1.lerp)((0, std_math_1.lerp)((0, std_math_1.lerp)(hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(0), __.int(0), __.int(0)))), hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(1), __.int(0), __.int(0)))), u[0]), (0, std_math_1.lerp)(hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(0), __.int(1), __.int(0)))), hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(1), __.int(1), __.int(0)))), u[0]), u[1]), (0, std_math_1.lerp)((0, std_math_1.lerp)(hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(0), __.int(0), __.int(1)))), hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(1), __.int(0), __.int(1)))), u[0]), (0, std_math_1.lerp)(hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(0), __.int(1), __.int(1)))), hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(1), __.int(1), __.int(1)))), u[0]), u[1]), u[2]); }; noise.simplex2 = function (v) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28; var C = __.FM.float_4_1_1_1_1(__.float(0.211324865405187), __.float(0.366025403784439), __.negate(0.577350269189626), __.float(0.024390243902439)); var i = (_a = (_b = v, _c = (0, std_math_1.dot)(v, (_d = C, [_d[1], _d[1]])), [_b[0] + _c, _b[1] + _c]), [Math.floor(_a[0]), Math.floor(_a[1])]); var x0 = (_e = (_g = v, _h = i, [_g[0] - _h[0], _g[1] - _h[1]]), _f = (0, std_math_1.dot)(i, (_j = C, [_j[0], _j[0]])), [_e[0] + _f, _e[1] + _f]); var xv = (0, std_math_1.step)(x0[1], x0[0]); var i1 = __.FM.float_2_1_1(xv, __.sub(1.0, xv)); var x1 = (_k = (_m = x0, _o = (_p = C, [_p[0], _p[0]]), [_m[0] + _o[0], _m[1] + _o[1]]), _l = i1, [_k[0] - _l[0], _k[1] - _l[1]]); var x2 = (_q = x0, _r = (_s = C, [_s[2], _s[2]]), [_q[0] + _r[0], _q[1] + _r[1]]); i = mod289_2(i); var p = permute((_t = (_v = permute((_x = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'y'), __.float(1.0)), _y = i[1], [_x[0] + _y, _x[1] + _y, _x[2] + _y])), _w = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'x'), __.float(1.0)), [_v[0] + _w[0], _v[1] + _w[1], _v[2] + _w[2]]), _u = i[0], [_t[0] + _u, _t[1] + _u, _t[2] + _u])); var m = (0, std_math_1.max)((_z = (_1 = 0.5, [_1, _1, _1]), _0 = __.FM.float_3_1_1_1((0, std_math_1.dot)(x0, x0), (0, std_math_1.dot)(x1, x1), (0, std_math_1.dot)(x2, x2)), [_z[0] - _0[0], _z[1] - _0[1], _z[2] - _0[2]]), 0.0); m = (_2 = m, _3 = m, [_2[0] * _3[0], _2[1] * _3[1], _2[2] * _3[2]]); m = (_4 = m, _5 = m, [_4[0] * _5[0], _4[1] * _5[1], _4[2] * _5[2]]); var x = (_6 = (_8 = 2.0, _9 = (0, std_math_1.frac)((_10 = p, _11 = (_12 = C, [_12[3], _12[3], _12[3]]), [_10[0] * _11[0], _10[1] * _11[1], _10[2] * _11[2]])), [_8 * _9[0], _8 * _9[1], _8 * _9[2]]), _7 = 1.0, [_6[0] - _7, _6[1] - _7, _6[2] - _7]); var h = (_13 = (_15 = x, [Math.abs(_15[0]), Math.abs(_15[1]), Math.abs(_15[2])]), _14 = 0.5, [_13[0] - _14, _13[1] - _14, _13[2] - _14]); var ox = (_16 = (_17 = x, _18 = 0.5, [_17[0] + _18, _17[1] + _18, _17[2] + _18]), [Math.floor(_16[0]), Math.floor(_16[1]), Math.floor(_16[2])]); var a0 = (_19 = x, _20 = ox, [_19[0] - _20[0], _19[1] - _20[1], _19[2] - _20[2]]); // Normalise gradients implicitly by scaling m m = (_21 = m, _22 = taylorInvSqrt((_23 = (_25 = a0, _26 = a0, [_25[0] * _26[0], _25[1] * _26[1], _25[2] * _26[2]]), _24 = (_27 = h, _28 = h, [_27[0] * _28[0], _27[1] * _28[1], _27[2] * _28[2]]), [_23[0] + _24[0], _23[1] + _24[1], _23[2] + _24[2]])), [_21[0] * _22[0], _21[1] * _22[1], _21[2] * _22[2]]); // Compute final noise value at P var g = __.FM.float_3_1_1_1(__.add(a0[0] * x0[0], h[0] * x0[1]), __.add(a0[1] * x1[0], h[1] * x1[1]), __.add(a0[2] * x2[0], h[2] * x2[1])); return 130.0 * (0, std_math_1.dot)(m, g); }; noise.perlin2 = function (v) { var x = v[0]; var y = v[1]; var z = 0.0; if (x < (0 | 0)) { x = (__.FM.negate_1(x)); } if (y < (0 | 0)) { y = (__.FM.negate_1(y)); } if (z < (0 | 0)) { z = (__.FM.negate_1(z)); } var xi = ((0, std_math_1.floor)(x) | 0); var yi = ((0, std_math_1.floor)(y) | 0); var zi = ((0, std_math_1.floor)(z) | 0); var xf = x - xi; var yf = y - yi; var zf = z - zi; var rxf = 0.0; var ryf = 0.0; var r = 0.0; var ampl = 0.5; var n1 = 0.0; var n2 = 0.0; var n3 = 0.0; for (var o = (0 | 0); o < perlin_octaves; o++) { var of1 = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); rxf = scaled_cosine(xf); ryf = scaled_cosine(yf); n1 = perlin.floatArray[of1 & PERLIN_SIZE]; n1 = n1 + rxf * (perlin.floatArray[(of1 + (1 | 0)) & PERLIN_SIZE] - n1); n2 = perlin.floatArray[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n2 = n2 + rxf * (perlin.floatArray[(of1 + PERLIN_YWRAP + (1 | 0)) & PERLIN_SIZE] - n2); n1 = n1 + ryf * (n2 - n1); of1 = of1 + PERLIN_ZWRAP; n2 = perlin.floatArray[of1 & PERLIN_SIZE]; n2 = n2 + rxf * (perlin.floatArray[(of1 + (1 | 0)) & PERLIN_SIZE] - n2); n3 = perlin.floatArray[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n3 = n3 + rxf * (perlin.floatArray[(of1 + PERLIN_YWRAP + (1 | 0)) & PERLIN_SIZE] - n3); n2 = n2 + ryf * (n3 - n2); n1 = n1 + scaled_cosine(zf) * (n2 - n1); r = r + n1 * ampl; ampl = ampl * perlin_amp_falloff; xi = xi << (1 | 0); xf = xf * 2.0; yi = yi << (1 | 0); yf = yf * 2.0; zi = zi << (1 | 0); zf = zf * 2.0; if (xf >= 1.0) { xi++; xf = xf - 1.0; } if (yf >= 1.0) { yi++; yf = yf - 1.0; } if (zf >= 1.0) { zi++; zf = zf - 1.0; } } return r; }; noise.perlin3 = function (v) { var x = v[0]; var y = v[1]; var z = v[2]; if (x < (0 | 0)) { x = (__.FM.negate_1(x)); } if (y < (0 | 0)) { y = (__.FM.negate_1(y)); } if (z < (0 | 0)) { z = (__.FM.negate_1(z)); } var xi = ((0, std_math_1.floor)(x) | 0); var yi = ((0, std_math_1.floor)(y) | 0); var zi = ((0, std_math_1.floor)(z) | 0); var xf = x - xi; var yf = y - yi; var zf = z - zi; var rxf = 0.0; var ryf = 0.0; var r = 0.0; var ampl = 0.5; var n1 = 0.0; var n2 = 0.0; var n3 = 0.0; for (var o = (0 | 0); o < perlin_octaves; o++) { var of1 = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); rxf = scaled_cosine(xf); ryf = scaled_cosine(yf); n1 = perlin.floatArray[of1 & PERLIN_SIZE]; n1 = n1 + rxf * (perlin.floatArray[(of1 + (1 | 0)) & PERLIN_SIZE] - n1); n2 = perlin.floatArray[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n2 = n2 + rxf * (perlin.floatArray[(of1 + PERLIN_YWRAP + (1 | 0)) & PERLIN_SIZE] - n2); n1 = n1 + ryf * (n2 - n1); of1 = of1 + PERLIN_ZWRAP; n2 = perlin.floatArray[of1 & PERLIN_SIZE]; n2 = n2 + rxf * (perlin.floatArray[(of1 + (1 | 0)) & PERLIN_SIZE] - n2); n3 = perlin.floatArray[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n3 = n3 + rxf * (perlin.floatArray[(of1 + PERLIN_YWRAP + (1 | 0)) & PERLIN_SIZE] - n3); n2 = n2 + ryf * (n3 - n2); n1 = n1 + scaled_cosine(zf) * (n2 - n1); r = r + n1 * ampl; ampl = ampl * perlin_amp_falloff; xi = xi << (1 | 0); xf = xf * 2.0; yi = yi << (1 | 0); yf = yf * 2.0; zi = zi << (1 | 0); zf = zf * 2.0; if (xf >= 1.0) { xi++; xf = xf - 1.0; } if (yf >= 1.0) { yi++; yf = yf - 1.0; } if (zf >= 1.0) { zi++; zf = zf - 1.0; } } return r; }; /** * Returns 3 values: distance to closest cell, random value of closest cell, distance to closest edge. */ noise.voronoi2 = function (v) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z; var n = (_a = v, [Math.floor(_a[0]), Math.floor(_a[1])]); var minDist = 10.0; var toClose = (_b = 0.0, [_b, _b]); var closestCell = (_c = 0.0, [_c, _c]); for (var j = (__.FM.negate_1((1 | 0))); j <= (1 | 0); j++) { for (var i = (__.FM.negate_1((1 | 0))); i <= (1 | 0); i++) { var cell = (_d = n, _e = __.FM.float_2_1_1(i, j), [_d[0] + _e[0], _d[1] + _e[1]]); var cellPos = (_f = cell, _g = hash2(cell), [_f[0] + _g, _f[1] + _g]); var toCell = (_h = cellPos, _j = v, [_h[0] - _j[0], _h[1] - _j[1]]); var dst = (0, std_math_1.length)(toCell); if (dst < minDist) { minDist = dst; toClose = toCell; closestCell = cell; } } } var minEdge = 10.0; for (var j = (__.FM.negate_1((1 | 0))); j <= (1 | 0); j++) { for (var i = (__.FM.negate_1((1 | 0))); i <= (1 | 0); i++) { var cell = (_k = n, _l = __.FM.float_2_1_1(i, j), [_k[0] + _l[0], _k[1] + _l[1]]); var cellPos = (_m = cell, _o = hash2(cell), [_m[0] + _o, _m[1] + _o]); var toCell = (_p = cellPos, _q = v, [_p[0] - _q[0], _p[1] - _q[1]]); var diff = (_r = (_s = closestCell, _t = cell, [_s[0] - _t[0], _s[1] - _t[1]]), [Math.abs(_r[0]), Math.abs(_r[1])]); var isClosest = diff[0] + diff[1] < 0.1; if (__.not(isClosest)) { var toCenter = (_u = (_w = toClose, _x = toCell, [_w[0] + _x[0], _w[1] + _x[1]]), _v = 0.5, [_u[0] * _v, _u[1] * _v]); var cellDiff = (0, std_math_1.normalize)((_y = toCell, _z = toClose, [_y[0] - _z[0], _y[1] - _z[1]])); var edge = (0, std_math_1.dot)(toCenter, cellDiff); minEdge = (0, std_math_1.min)(minEdge, edge); } } } var random = hash2(closestCell); return __.FM.float_3_1_1_1(minDist, random, minEdge); }; noise.simplex3 = function (v) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56; var C = __.FM.float_4_1_1_1_1(__.float(0.138196601125011), __.float(0.276393202250021), __.float(0.414589803375032), __.negate(0.447213595499958)); var i = (_a = (_b = v, _c = (0, std_math_1.dot)(v, (_d = C, [_d[1], _d[1], _d[1]])), [_b[0] + _c, _b[1] + _c, _b[2] + _c]), [Math.floor(_a[0]), Math.floor(_a[1]), Math.floor(_a[2])]); var x0 = (_e = (_g = v, _h = i, [_g[0] - _h[0], _g[1] - _h[1], _g[2] - _h[2]]), _f = (0, std_math_1.dot)(i, (_j = C, [_j[0], _j[0], _j[0]])), [_e[0] + _f, _e[1] + _f, _e[2] + _f]); var g = (0, std_math_1.step)((_k = x0, [_k[1], _k[2], _k[0]]), (_l = x0, [_l[0], _l[1], _l[2]])); var l = (_m = 1.0, _o = g, [_m - _o[0], _m - _o[1], _m - _o[2]]); var i1 = (0, std_math_1.min)((_p = g, [_p[0], _p[1], _p[2]]), (_q = l, [_q[2], _q[0], _q[1]])); var i2 = (0, std_math_1.max)((_r = g, [_r[0], _r[1], _r[2]]), (_s = l, [_s[2], _s[0], _s[1]])); var x1 = (_t = (_v = x0, _w = i1, [_v[0] - _w[0], _v[1] - _w[1], _v[2] - _w[2]]), _u = (_x = 1.0, _y = (_z = C, [_z[0], _z[0], _z[0]]), [_x * _y[0], _x * _y[1], _x * _y[2]]), [_t[0] + _u[0], _t[1] + _u[1], _t[2] + _u[2]]); var x2 = (_0 = (_2 = x0, _3 = i2, [_2[0] - _3[0], _2[1] - _3[1], _2[2] - _3[2]]), _1 = (_4 = 2.0, _5 = (_6 = C, [_6[0], _6[0], _6[0]]), [_4 * _5[0], _4 * _5[1], _4 * _5[2]]), [_0[0] + _1[0], _0[1] + _1[1], _0[2] + _1[2]]); var x3 = (_7 = (_9 = x0, _10 = 1., [_9[0] - _10, _9[1] - _10, _9[2] - _10]), _8 = (_11 = 3.0, _12 = (_13 = C, [_13[0], _13[0], _13[0]]), [_11 * _12[0], _11 * _12[1], _11 * _12[2]]), [_7[0] + _8[0], _7[1] + _8[1], _7[2] + _8[2]]); i = mod289_3(i); var p = permute((_14 = (_16 = permute((_18 = (_20 = permute((_22 = i[2], _23 = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'z'), __.swizzle(i2, 'z')), [_22 + _23[0], _22 + _23[1], _22 + _23[2]])), _21 = i[1], [_20[0] + _21, _20[1] + _21, _20[2] + _21]), _19 = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'y'), __.swizzle(i2, 'y')), [_18[0] + _19[0], _18[1] + _19[1], _18[2] + _19[2]])), _17 = i[0], [_16[0] + _17, _16[1] + _17, _16[2] + _17]), _15 = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'x'), __.swizzle(i2, 'x')), [_14[0] + _15[0], _14[1] + _15[1], _14[2] + _15[2]])); var m = (0, std_math_1.max)((_24 = 0.5, _25 = __.FM.float_3_1_1_1((0, std_math_1.dot)(x0, x0), (0, std_math_1.dot)(x1, x1), (0, std_math_1.dot)(x2, x2)), [_24 - _25[0], _24 - _25[1], _24 - _25[2]]), 0.0); m = (_26 = m, _27 = m, [_26[0] * _27[0], _26[1] * _27[1], _26[2] * _27[2]]); m = (_28 = m, _29 = m, [_28[0] * _29[0], _28[1] * _29[1], _28[2] * _29[2]]); var x = (_30 = (_32 = 2.0, _33 = (0, std_math_1.frac)((_34 = p, _35 = (_36 = C, [_36[3], _36[3], _36[3]]), [_34[0] * _35[0], _34[1] * _35[1], _34[2] * _35[2]])), [_32 * _33[0], _32 * _33[1], _32 * _33[2]]), _31 = 1.0, [_30[0] - _31, _30[1] - _31, _30[2] - _31]); var h = (_37 = (_39 = x, [Math.abs(_39[0]), Math.abs(_39[1]), Math.abs(_39[2])]), _38 = 0.5, [_37[0] - _38, _37[1] - _38, _37[2] - _38]); var ox = (_40 = (_41 = x, _42 = 0.5, [_41[0] + _42, _41[1] + _42, _41[2] + _42]), [Math.floor(_40[0]), Math.floor(_40[1]), Math.floor(_40[2])]); var a0 = (_43 = x, _44 = ox, [_43[0] - _44[0], _43[1] - _44[1], _43[2] - _44[2]]); // Normalise gradients implicitly by scaling m // Approximation of: m *= inversesqrt(a0 * a0 + h * h); m = (_45 = m, _46 = (_47 = 1.79284291400159, _48 = (_49 = 0.85373472095314, _50 = (_51 = (_53 = a0, _54 = a0, [_53[0] * _54[0], _53[1] * _54[1], _53[2] * _54[2]]), _52 = (_55 = h, _56 = h, [_55[0] * _56[0], _55[1] * _56[1], _55[2] * _56[2]]), [_51[0] + _52[0], _51[1] + _52[1], _51[2] + _52[2]]), [_49 * _50[0], _49 * _50[1], _49 * _50[2]]), [_47 - _48[0], _47 - _48[1], _47 - _48[2]]), [_45[0] * _46[0], _45[1] * _46[1], _45[2] * _46[2]]); // Compute final noise value at P var g2 = __.FM.float_3_1_1_1(__.add(a0[0] * x0[0], h[0] * x0[1]), __.add(a0[1] * x1[0], h[1] * x1[1]), __.add(a0[2] * x2[0], h[2] * x2[1])); return 130.0 * (0, std_math_1.dot)(m, g2); }; noise.prototype.clone = function () { return new noise({}); }; noise.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_26913_noise\\",\\"fields\\":[]}"); }; return noise; }()); exports.noise = noise; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_26913_noise\\",\\"fields\\":[]}"), noise) ; var PERLIN_YWRAPB = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_YWRAPB", function () { return (4 | 0); }, function () { return PERLIN_YWRAPB; }) | 0); var PERLIN_YWRAP = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_YWRAP", function () { return (1 | 0) << PERLIN_YWRAPB; }, function () { return PERLIN_YWRAP; }) | 0); var PERLIN_ZWRAPB = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_ZWRAPB", function () { return (8 | 0); }, function () { return PERLIN_ZWRAPB; }) | 0); var PERLIN_ZWRAP = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_ZWRAP", function () { return (1 | 0) << PERLIN_ZWRAPB; }, function () { return PERLIN_ZWRAP; }) | 0); var PERLIN_SIZE = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_SIZE", function () { return (4095 | 0); }, function () { return PERLIN_SIZE; }) | 0); var perlin_octaves = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "perlin_octaves", function () { return (4 | 0); }, function () { return perlin_octaves; }) | 0); // default to medium smooth var perlin_amp_falloff = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "perlin_amp_falloff", function () { return 0.5; }, function () { return perlin_amp_falloff; }); // 50% reduction/octave function scaled_cosine(i) { return 0.5 * (1.0 - Math.cos(i * PI)); } var perlin = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "perlin", function () { return (0, buffer_1.buffer)(PERLIN_SIZE + (1 | 0), "float", __assign({}, JSON.parse("{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}"))); }, function () { return perlin; }); for (var i = (0 | 0); i < PERLIN_SIZE + (1 | 0); i++) { perlin.__index_assign(i, (0, std_math_1.rand)(i)); } // // By Morgan McGuire @morgan3d, http://graphicscodex.com // function hash(n) { return (0, std_math_1.frac)(Math.sin(n) * (1e4 | 0)); } function hash2(p) { return (0, std_math_1.frac)((1e4 | 0) * Math.sin(17.0 * p[0] + p[1] * 0.1) * (0.1 + Math.abs(Math.sin(p[1] * 13.0 + p[0])))); } function hash3(p) { var h = (0, std_math_1.dot)(p, __.FM.float_3_1_1_1(__.float(127.1), __.float(311.7), __.float(74.7))); return (0, std_math_1.frac)(Math.sin(h) * 43758.5453123); } /* impl noise */ function mod289_1(x) { return x - Math.floor(x * (1.0 / 289.0)) * 289.0; } function mod289_4(x) { var _a, _b, _c, _d, _e, _f, _g; return _a = x, _b = (_c = (_e = (_f = x, _g = (1.0 / 289.0), [_f[0] * _g, _f[1] * _g, _f[2] * _g, _f[3] * _g]), [Math.floor(_e[0]), Math.floor(_e[1]), Math.floor(_e[2]), Math.floor(_e[3])]), _d = 289.0, [_c[0] * _d, _c[1] * _d, _c[2] * _d, _c[3] * _d]), [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2], _a[3] - _b[3]]; } function perm(x) { var _a, _b, _c, _d, _e, _f; return mod289_4((_a = (_c = (_e = x, _f = 34.0, [_e[0] * _f, _e[1] * _f, _e[2] * _f, _e[3] * _f]), _d = 1.0, [_c[0] + _d, _c[1] + _d, _c[2] + _d, _c[3] + _d]), _b = x, [_a[0] * _b[0], _a[1] * _b[1], _a[2] * _b[2], _a[3] * _b[3]])); } function mod289_3(x) { var _a, _b, _c, _d, _e, _f, _g; return _a = x, _b = (_c = (_e = (_f = x, _g = (1.0 / 289.0), [_f[0] * _g, _f[1] * _g, _f[2] * _g]), [Math.floor(_e[0]), Math.floor(_e[1]), Math.floor(_e[2])]), _d = 289.0, [_c[0] * _d, _c[1] * _d, _c[2] * _d]), [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]; } function mod289_2(x) { var _a, _b, _c, _d, _e, _f, _g; return _a = x, _b = (_c = (_e = (_f = x, _g = (1.0 / 289.0), [_f[0] * _g, _f[1] * _g]), [Math.floor(_e[0]), Math.floor(_e[1])]), _d = 289.0, [_c[0] * _d, _c[1] * _d]), [_a[0] - _b[0], _a[1] - _b[1]]; } function permute(x) { var _a, _b, _c, _d, _e, _f; return mod289_3((_a = (_c = (_e = x, _f = 34.0, [_e[0] * _f, _e[1] * _f, _e[2] * _f]), _d = 1.0, [_c[0] + _d, _c[1] + _d, _c[2] + _d]), _b = x, [_a[0] * _b[0], _a[1] * _b[1], _a[2] * _b[2]])); } function taylorInvSqrt(r) { var _a, _b, _c, _d; return _a = 1.79284291400159, _b = (_c = 0.85373472095314, _d = r, [_c * _d[0], _c * _d[1], _c * _d[2]]), [_a - _b[0], _a - _b[1], _a - _b[2]]; } var matrix = /** @class */ (function () { function matrix(data) { } matrix.lookAt = function (from, to, up) { var _a, _b, _c, _d; var zAxis = (0, std_math_1.normalize)((_a = from, _b = to, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]])); var xAxis = (0, std_math_1.normalize)((0, std_math_1.cross)(up, zAxis)); var yAxis = (0, std_math_1.normalize)((0, std_math_1.cross)(zAxis, xAxis)); var dst = __.float4x4(); dst.__index((0 | 0)).__index_assign((0 | 0), xAxis[0]); dst.__index((0 | 0)).__index_assign((1 | 0), yAxis[0]); dst.__index((0 | 0)).__index_assign((2 | 0), zAxis[0]); dst.__index((0 | 0)).__index_assign((3 | 0), (0 | 0)); dst.__index((1 | 0)).__index_assign((0 | 0), xAxis[1]); dst.__index((1 | 0)).__index_assign((1 | 0), yAxis[1]); dst.__index((1 | 0)).__index_assign((2 | 0), zAxis[1]); dst.__index((1 | 0)).__index_assign((3 | 0), (0 | 0)); dst.__index((2 | 0)).__index_assign((0 | 0), xAxis[2]); dst.__index((2 | 0)).__index_assign((1 | 0), yAxis[2]); dst.__index((2 | 0)).__index_assign((2 | 0), zAxis[2]); dst.__index((2 | 0)).__index_assign((3 | 0), (0 | 0)); dst.__index((3 | 0)).__index_assign((0 | 0), (__.FM.negate_1((xAxis[0] * from[0] + xAxis[1] * from[1] + xAxis[2] * from[2])))); dst.__index((3 | 0)).__index_assign((1 | 0), (__.FM.negate_1((yAxis[0] * from[0] + yAxis[1] * from[1] + yAxis[2] * from[2])))); dst.__index((3 | 0)).__index_assign((2 | 0), (__.FM.negate_1((zAxis[0] * from[0] + zAxis[1] * from[1] + zAxis[2] * from[2])))); dst.__index((3 | 0)).__index_assign((3 | 0), (1 | 0)); return dst; var forward = (0, std_math_1.normalize)((_c = from, _d = to, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]])); var right = (0, std_math_1.normalize)((0, std_math_1.cross)(up, forward)); var newup = (0, std_math_1.cross)(forward, right); var m = __.float4x4(); m.__index((0 | 0)).__index_assign((0 | 0), right[0]), m.__index((0 | 0)).__index_assign((1 | 0), right[1]), m.__index((0 | 0)).__index_assign((2 | 0), right[2]); m.__index((1 | 0)).__index_assign((0 | 0), newup[0]), m.__index((1 | 0)).__index_assign((1 | 0), newup[1]), m.__index((1 | 0)).__index_assign((2 | 0), newup[2]); m.__index((2 | 0)).__index_assign((0 | 0), forward[0]), m.__index((2 | 0)).__index_assign((1 | 0), forward[1]), m.__index((2 | 0)).__index_assign((2 | 0), forward[2]); m.__index((3 | 0)).__index_assign((0 | 0), from[0]), m.__index((3 | 0)).__index_assign((1 | 0), from[1]), m.__index((3 | 0)).__index_assign((2 | 0), from[2]); return m; }; matrix.perspective = function (fov, aspect, near, far) { // let scale = 1.0 / tan(fov * 0.5 * PI / 180); // let M = float4x4(); // M[0][0] = scale; //scale the x coordinates of the projected point // M[1][1] = scale * aspect; //scale the y coordinates of the projected point // M[2][2] = -far / (far - near); //used to remap z to [0,1] // M[3][2] = -far * near / (far - near); //used to remap z [0,1] // M[2][3] = -1; //set w = -z // M[3][3] = 0; //return M; var fovRad = (0, std_math_1.radians)(fov); var tanFov = Math.tan(fovRad * 0.5); var matrx = __.float4x4(1.0 / (tanFov * aspect), (0 | 0), (0 | 0), (0 | 0), (0 | 0), 1.0 / tanFov, (0 | 0), (0 | 0), (0 | 0), (0 | 0), (__.FM.negate_1(((far + near) / (far - near)))), (__.FM.negate_1((1 | 0))), (0 | 0), (0 | 0), (__.FM.negate_1((((2 | 0) * (near * far)) / (far - near)))), (0 | 0)); return matrx; }; matrix.perspectiveReverseZ = function (fov, aspect, near) { // let far = 10000000.0; // let M = float4x4(); // M[0][0] = scale; //scale the x coordinates of the projected point // M[1][1] = scale * aspect; //scale the y coordinates of the projected point // M[2][2] = (-far / (far - near)) * -1; //used to remap z to [0,1] // M[3][2] = -far * near / (far - near); //used to remap z [0,1] // M[2][3] = 0; //set w = -z // M[3][3] = 0; // return M; var matrx = __.mul(__.float4x4((1 | 0), (0 | 0), (0 | 0), (0 | 0), (0 | 0), (1 | 0), (0 | 0), (0 | 0), (0 | 0), (0 | 0), (__.FM.negate_1((1 | 0))), (0 | 0), (0 | 0), (0 | 0), (1 | 0), (1 | 0)), matrix.perspective(fov, aspect, near, 10000000.0)); return matrx; }; matrix.prototype.clone = function () { return new matrix({}); }; matrix.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_44684_matrix\\",\\"fields\\":[]}"); }; return matrix; }()); exports.matrix = matrix; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_44684_matrix\\",\\"fields\\":[]}"), matrix) ; /* impl matrix */ /** * Uses Super Sampling Anti Aliasing to smooth out the image. */ function screenAA(inScreenPos, gridSize, func) { var _a, _b, _c, _d, _e, _f, _g, _h; var weightSum = 0.0; var accumulatedColor = __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(0)); for (var y = (0 | 0); y < gridSize; y++) { for (var x = (0 | 0); x < gridSize; x++) { var offset = __.FM.float_2_1_1(__.div((x + 0.5 - gridSize * 0.5), gridSize), __.div((y + 0.5 - gridSize * 0.5), gridSize)); var weight = Math.exp((__.FM.negate_1((0, std_math_1.dot)(offset, offset))) * (5 | 0)); // Gaussian weight accumulatedColor = (_a = accumulatedColor, _b = (_c = func((_e = inScreenPos, _f = offset, [_e[0] + _f[0], _e[1] + _f[1]])), _d = weight, [_c[0] * _d, _c[1] * _d, _c[2] * _d, _c[3] * _d]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2], _a[3] + _b[3]]); weightSum = weightSum + weight; } } return _g = accumulatedColor, _h = weightSum, [_g[0] / _h, _g[1] / _h, _g[2] / _h, _g[3] / _h]; } exports.screenAA = screenAA; ; // Color conversion helpers // A color = float4 containing rgba values in the range [0, 1] // All functions have an extra alpha functon and a reverse // i.e. hsl, hsla, hslFromColor, hslaFromColor // fn hsl(v: float3) -> float4 function hsl(v) { return hsla(__.makeVector(v, (1 | 0))); } exports.hsl = hsl; ; function hsla(v) { var h = v[0]; var s = v[1]; var l = v[2]; var a = v[3]; var c = ((1 | 0) - Math.abs((2 | 0) * l - (1 | 0))) * s; var x = c * ((1 | 0) - Math.abs(((h / (60 | 0)) % (2 | 0)) - (1 | 0))); var m = l - c / (2 | 0); var r = 0.0; var g = 0.0; var b = 0.0; if (h < (60 | 0)) { r = c; g = x; b = (0 | 0); } else if (h < (120 | 0)) { r = x; g = c; b = (0 | 0); } else if (h < (180 | 0)) { r = (0 | 0); g = c; b = x; } else if (h < (240 | 0)) { r = (0 | 0); g = x; b = c; } else if (h < (300 | 0)) { r = x; g = (0 | 0); b = c; } else { r = c; g = (0 | 0); b = x; } return __.FM.float_4_1_1_1_1(__.add(r, m), __.add(g, m), __.add(b, m), a); } exports.hsla = hsla; ; function hslFromColor(c) { var r = c[0]; var g = c[1]; var b = c[2]; var a = c[3]; var mx = (0, std_math_1.max)(r, (0, std_math_1.max)(g, b)); var mn = (0, std_math_1.min)(r, (0, std_math_1.min)(g, b)); var h = 0.0; var s = 0.0; var l = (mx + mn) / (2 | 0); if (mx == mn) { h = (0 | 0); s = (0 | 0); } else { var d = mx - mn; s = (l > 0.5) ? d / ((2 | 0) - mx - mn) : d / (mx + mn); if (mx == r) { h = (g - b) / d + ((g < b) ? (6 | 0) : (0 | 0)); } else if (mx == g) { h = (b - r) / d + (2 | 0); } else if (mx == b) { h = (r - g) / d + (4 | 0); } h = h / (6 | 0); } return __.FM.float_3_1_1_1(__.mul(h, (360 | 0)), s, l); } exports.hslFromColor = hslFromColor; ; function hslaFromColor(c) { var hsl = hslFromColor(c); return __.FM.float_4_3_1(hsl, __.swizzle(c, 'a')); } exports.hslaFromColor = hslaFromColor; ; function hsv(v) { return hsva(__.makeVector(v, (1 | 0))); } exports.hsv = hsv; ; function hsva(val) { var h = val[0]; var s = val[1]; var v = val[2]; var a = val[3]; var c = v * s; var x = c * ((1 | 0) - Math.abs(h / (60 | 0) % (2 | 0) - (1 | 0))); var m = v - c; var r = 0.0; var g = 0.0; var b = 0.0; if (h < (60 | 0)) { r = c; g = x; b = (0 | 0); } else if (h < (120 | 0)) { r = x; g = c; b = (0 | 0); } else if (h < (180 | 0)) { r = (0 | 0); g = c; b = x; } else if (h < (240 | 0)) { r = (0 | 0); g = x; b = c; } else if (h < (300 | 0)) { r = x; g = (0 | 0); b = c; } else { r = c; g = (0 | 0); b = x; } return __.FM.float_4_1_1_1_1(__.add(r, m), __.add(g, m), __.add(b, m), a); } exports.hsva = hsva; ; function hsvFromColor(c) { var r = c[0]; var g = c[1]; var b = c[2]; var mx = (0, std_math_1.max)(r, (0, std_math_1.max)(g, b)); var mn = (0, std_math_1.min)(r, (0, std_math_1.min)(g, b)); var h = 0.0; var s = 0.0; var v = mx; var d = mx - mn; s = (mx == (0 | 0)) ? (0 | 0) : d / mx; if (mx == mn) { h = (0 | 0); } else { if (mx == r) { h = (g - b) / d + ((g < b) ? (6 | 0) : (0 | 0)); } else if (mx == g) { h = (b - r) / d + (2 | 0); } else if (mx == b) { h = (r - g) / d + (4 | 0); } h = h / (6 | 0); } return __.FM.float_3_1_1_1(__.mul(h, (360 | 0)), s, v); } exports.hsvFromColor = hsvFromColor; ; function hsvaFromColor(c) { var hsv = hsvFromColor(c); return __.FM.float_4_3_1(hsv, __.swizzle(c, 'a')); } exports.hsvaFromColor = hsvaFromColor; ; function rgb(v) { return __.FM.float_4_3_1(__.div(v, 255.0), __.int(1)); } exports.rgb = rgb; ; function rgba(v) { return __.FM.float_4_4(__.div(v, 255.0)); } exports.rgba = rgba; ; function rgbFromColor(c) { var _a, _b, _c; return _a = (_c = c, [_c[0], _c[1], _c[2]]), _b = 255.0, [_a[0] * _b, _a[1] * _b, _a[2] * _b]; } exports.rgbFromColor = rgbFromColor; ; function rgbaFromColor(c) { var _a, _b; return _a = c, _b = 255.0, [_a[0] * _b, _a[1] * _b, _a[2] * _b, _a[3] * _b]; } exports.rgbaFromColor = rgbaFromColor; ; function cmyk(v) { var c = v[0]; var m = v[1]; var y = v[2]; var k = v[3]; var r = (1 | 0) - (0, std_math_1.min)((1 | 0), c * ((1 | 0) - k) + k); var g = (1 | 0) - (0, std_math_1.min)((1 | 0), m * ((1 | 0) - k) + k); var b = (1 | 0) - (0, std_math_1.min)((1 | 0), y * ((1 | 0) - k) + k); return __.FM.float_4_1_1_1_1(r, g, b, __.int(1)); } exports.cmyk = cmyk; ; function cmykFromColor(c) { var r = c[0]; var g = c[1]; var b = c[2]; var k = (1 | 0) - (0, std_math_1.max)(r, (0, std_math_1.max)(g, b)); var c1 = ((1 | 0) - r - k) / ((1 | 0) - k); var m = ((1 | 0) - g - k) / ((1 | 0) - k); var y = ((1 | 0) - b - k) / ((1 | 0) - k); return __.FM.float_4_1_1_1_1(c1, m, y, k); } exports.cmykFromColor = cmykFromColor; ; function hex(v) { var r = (v >> (16 | 0)) & (0xFF | 0); var g = (v >> (8 | 0)) & (0xFF | 0); var b = v & (0xFF | 0); return __.FM.float_4_1_1_1_1(__.div(r, 255.0), __.div(g, 255.0), __.div(b, 255.0), __.float(1.0)); } exports.hex = hex; ; function hexFromColor(c) { var r = (__.mul(c[0], 255.0) | 0); var g = (__.mul(c[1], 255.0) | 0); var b = (__.mul(c[2], 255.0) | 0); return (r << (16 | 0)) | (g << (8 | 0)) | b; } exports.hexFromColor = hexFromColor; ; /** * Returns sin remapped to [0, 1] */ function sin1(v) { return (Math.sin(v) + (1 | 0)) * 0.5; } exports.sin1 = sin1; ; /** * Returns cos remapped to [0, 1] */ function cos1(v) { return (Math.cos(v) + (1 | 0)) * 0.5; } exports.cos1 = cos1; ; /** * Returns tan remapped to [0, 1] */ function tan1(v) { return (Math.tan(v) + (1 | 0)) * 0.5; } exports.tan1 = tan1; ; function remap(v, low1, high1, low2, high2) { return low2 + (v - low1) * (high2 - low2) / (high1 - low1); } exports.remap = remap; ; function remap1(v, low, high) { return remap(v, low, high, (0 | 0), (1 | 0)); } exports.remap1 = remap1; ; var color = /** @class */ (function () { function color(data) { } color.prototype.clone = function () { return new color({}); }; color.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_57436_color\\",\\"fields\\":[[\\"slate50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}]]}"); }; color.slate50 = __.FM.float_4_1_1_1_1(__.float(0.9725490196078431), __.float(0.9803921568627451), __.float(0.9882352941176471), __.int(1)); color.slate100 = __.FM.float_4_1_1_1_1(__.float(0.9450980392156862), __.float(0.9607843137254902), __.float(0.9764705882352941), __.int(1)); color.slate200 = __.FM.float_4_1_1_1_1(__.float(0.8862745098039215), __.float(0.9098039215686274), __.float(0.9411764705882353), __.int(1)); color.slate300 = __.FM.float_4_1_1_1_1(__.float(0.796078431372549), __.float(0.8352941176470589), __.float(0.8823529411764706), __.int(1)); color.slate400 = __.FM.float_4_1_1_1_1(__.float(0.5803921568627451), __.float(0.6392156862745098), __.float(0.7215686274509804), __.int(1)); color.slate500 = __.FM.float_4_1_1_1_1(__.float(0.39215686274509803), __.float(0.4549019607843137), __.float(0.5450980392156862), __.int(1)); color.slate600 = __.FM.float_4_1_1_1_1(__.float(0.2784313725490196), __.float(0.3333333333333333), __.float(0.4117647058823529), __.int(1)); color.slate700 = __.FM.float_4_1_1_1_1(__.float(0.2), __.float(0.2549019607843137), __.float(0.3333333333333333), __.int(1)); color.slate800 = __.FM.float_4_1_1_1_1(__.float(0.11764705882352941), __.float(0.1607843137254902), __.float(0.23137254901960785), __.int(1)); color.slate900 = __.FM.float_4_1_1_1_1(__.float(0.058823529411764705), __.float(0.09019607843137255), __.float(0.16470588235294117), __.int(1)); color.slate950 = __.FM.float_4_1_1_1_1(__.float(0.00784313725490196), __.float(0.023529411764705882), __.float(0.09019607843137255), __.int(1)); color.gray50 = __.FM.float_4_1_1_1_1(__.float(0.9764705882352941), __.float(0.9803921568627451), __.float(0.984313725490196), __.int(1)); color.gray100 = __.FM.float_4_1_1_1_1(__.float(0.9529411764705882), __.float(0.9568627450980393), __.float(0.9647058823529412), __.int(1)); color.gray200 = __.FM.float_4_1_1_1_1(__.float(0.8980392156862745), __.float(0.9058823529411765), __.float(0.9215686274509803), __.int(1)); color.gray300 = __.FM.float_4_1_1_1_1(__.float(0.8196078431372549), __.float(0.8352941176470589), __.float(0.8588235294117647), __.int(1)); color.gray400 = __.FM.float_4_1_1_1_1(__.float(0.611764705882353), __.float(0.6392156862745098), __.float(0.6862745098039216), __.int(1)); color.gray500 = __.FM.float_4_1_1_1_1(__.float(0.4196078431372549), __.float(0.4470588235294118), __.float(0.5019607843137255), __.int(1)); color.gray600 = __.FM.float_4_1_1_1_1(__.float(0.29411764705882354), __.float(0.3333333333333333), __.float(0.38823529411764707), __.int(1)); color.gray700 = __.FM.float_4_1_1_1_1(__.float(0.21568627450980393), __.float(0.2549019607843137), __.float(0.3176470588235294), __.int(1)); color.gray800 = __.FM.float_4_1_1_1_1(__.float(0.12156862745098039), __.float(0.1607843137254902), __.float(0.21568627450980393), __.int(1)); color.gray900 = __.FM.float_4_1_1_1_1(__.float(0.06666666666666667), __.float(0.09411764705882353), __.float(0.15294117647058825), __.int(1)); color.gray950 = __.FM.float_4_1_1_1_1(__.float(0.011764705882352941), __.float(0.027450980392156862), __.float(0.07058823529411765), __.int(1)); color.zinc50 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9803921568627451), __.float(0.9803921568627451), __.int(1)); color.zinc100 = __.FM.float_4_1_1_1_1(__.float(0.9568627450980393), __.float(0.9568627450980393), __.float(0.9607843137254902), __.int(1)); color.zinc200 = __.FM.float_4_1_1_1_1(__.float(0.8941176470588236), __.float(0.8941176470588236), __.float(0.9058823529411765), __.int(1)); color.zinc300 = __.FM.float_4_1_1_1_1(__.float(0.8313725490196079), __.float(0.8313725490196079), __.float(0.8470588235294118), __.int(1)); color.zinc400 = __.FM.float_4_1_1_1_1(__.float(0.6313725490196078), __.float(0.6313725490196078), __.float(0.6666666666666666), __.int(1)); color.zinc500 = __.FM.float_4_1_1_1_1(__.float(0.44313725490196076), __.float(0.44313725490196076), __.float(0.47843137254901963), __.int(1)); color.zinc600 = __.FM.float_4_1_1_1_1(__.float(0.3215686274509804), __.float(0.3215686274509804), __.float(0.3568627450980392), __.int(1)); color.zinc700 = __.FM.float_4_1_1_1_1(__.float(0.24705882352941178), __.float(0.24705882352941178), __.float(0.27450980392156865), __.int(1)); color.zinc800 = __.FM.float_4_1_1_1_1(__.float(0.15294117647058825), __.float(0.15294117647058825), __.float(0.16470588235294117), __.int(1)); color.zinc900 = __.FM.float_4_1_1_1_1(__.float(0.09411764705882353), __.float(0.09411764705882353), __.float(0.10588235294117647), __.int(1)); color.zinc950 = __.FM.float_4_1_1_1_1(__.float(0.03529411764705882), __.float(0.03529411764705882), __.float(0.043137254901960784), __.int(1)); color.neutral50 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9803921568627451), __.float(0.9803921568627451), __.int(1)); color.neutral100 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.9607843137254902), __.float(0.9607843137254902), __.int(1)); color.neutral200 = __.FM.float_4_1_1_1_1(__.float(0.8980392156862745), __.float(0.8980392156862745), __.float(0.8980392156862745), __.int(1)); color.neutral300 = __.FM.float_4_1_1_1_1(__.float(0.8313725490196079), __.float(0.8313725490196079), __.float(0.8313725490196079), __.int(1)); color.neutral400 = __.FM.float_4_1_1_1_1(__.float(0.6392156862745098), __.float(0.6392156862745098), __.float(0.6392156862745098), __.int(1)); color.neutral500 = __.FM.float_4_1_1_1_1(__.float(0.45098039215686275), __.float(0.45098039215686275), __.float(0.45098039215686275), __.int(1)); color.neutral600 = __.FM.float_4_1_1_1_1(__.float(0.3215686274509804), __.float(0.3215686274509804), __.float(0.3215686274509804), __.int(1)); color.neutral700 = __.FM.float_4_1_1_1_1(__.float(0.25098039215686274), __.float(0.25098039215686274), __.float(0.25098039215686274), __.int(1)); color.neutral800 = __.FM.float_4_1_1_1_1(__.float(0.14901960784313725), __.float(0.14901960784313725), __.float(0.14901960784313725), __.int(1)); color.neutral900 = __.FM.float_4_1_1_1_1(__.float(0.09019607843137255), __.float(0.09019607843137255), __.float(0.09019607843137255), __.int(1)); color.neutral950 = __.FM.float_4_1_1_1_1(__.float(0.0392156862745098), __.float(0.0392156862745098), __.float(0.0392156862745098), __.int(1)); color.stone50 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9803921568627451), __.float(0.9764705882352941), __.int(1)); color.stone100 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.9607843137254902), __.float(0.9568627450980393), __.int(1)); color.stone200 = __.FM.float_4_1_1_1_1(__.float(0.9058823529411765), __.float(0.8980392156862745), __.float(0.8941176470588236), __.int(1)); color.stone300 = __.FM.float_4_1_1_1_1(__.float(0.8392156862745098), __.float(0.8274509803921568), __.float(0.8196078431372549), __.int(1)); color.stone400 = __.FM.float_4_1_1_1_1(__.float(0.6588235294117647), __.float(0.6352941176470588), __.float(0.6196078431372549), __.int(1)); color.stone500 = __.FM.float_4_1_1_1_1(__.float(0.47058823529411764), __.float(0.44313725490196076), __.float(0.4235294117647059), __.int(1)); color.stone600 = __.FM.float_4_1_1_1_1(__.float(0.3411764705882353), __.float(0.3254901960784314), __.float(0.3058823529411765), __.int(1)); color.stone700 = __.FM.float_4_1_1_1_1(__.float(0.26666666666666666), __.float(0.25098039215686274), __.float(0.23529411764705882), __.int(1)); color.stone800 = __.FM.float_4_1_1_1_1(__.float(0.1607843137254902), __.float(0.1450980392156863), __.float(0.1411764705882353), __.int(1)); color.stone900 = __.FM.float_4_1_1_1_1(__.float(0.10980392156862745), __.float(0.09803921568627451), __.float(0.09019607843137255), __.int(1)); color.stone950 = __.FM.float_4_1_1_1_1(__.float(0.047058823529411764), __.float(0.0392156862745098), __.float(0.03529411764705882), __.int(1)); color.red50 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9490196078431372), __.float(0.9490196078431372), __.int(1)); color.red100 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.8862745098039215), __.float(0.8862745098039215), __.int(1)); color.red200 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.792156862745098), __.float(0.792156862745098), __.int(1)); color.red300 = __.FM.float_4_1_1_1_1(__.float(0.9882352941176471), __.float(0.6470588235294118), __.float(0.6470588235294118), __.int(1)); color.red400 = __.FM.float_4_1_1_1_1(__.float(0.9725490196078431), __.float(0.44313725490196076), __.float(0.44313725490196076), __.int(1)); color.red500 = __.FM.float_4_1_1_1_1(__.float(0.9372549019607843), __.float(0.26666666666666666), __.float(0.26666666666666666), __.int(1)); color.red600 = __.FM.float_4_1_1_1_1(__.float(0.8627450980392157), __.float(0.14901960784313725), __.float(0.14901960784313725), __.int(1)); color.red700 = __.FM.float_4_1_1_1_1(__.float(0.7254901960784313), __.float(0.10980392156862745), __.float(0.10980392156862745), __.int(1)); color.red800 = __.FM.float_4_1_1_1_1(__.float(0.6), __.float(0.10588235294117647), __.float(0.10588235294117647), __.int(1)); color.red900 = __.FM.float_4_1_1_1_1(__.float(0.4980392156862745), __.float(0.11372549019607843), __.float(0.11372549019607843), __.int(1)); color.red950 = __.FM.float_4_1_1_1_1(__.float(0.27058823529411763), __.float(0.0392156862745098), __.float(0.0392156862745098), __.int(1)); color.orange50 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.9686274509803922), __.float(0.9294117647058824), __.int(1)); color.orange100 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.9294117647058824), __.float(0.8352941176470589), __.int(1)); color.orange200 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.8431372549019608), __.float(0.6666666666666666), __.int(1)); color.orange300 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.7294117647058823), __.float(0.4549019607843137), __.int(1)); color.orange400 = __.FM.float_4_1_1_1_1(__.float(0.984313725490196), __.float(0.5725490196078431), __.float(0.23529411764705882), __.int(1)); color.orange500 = __.FM.float_4_1_1_1_1(__.float(0.9764705882352941), __.float(0.45098039215686275), __.float(0.08627450980392157), __.int(1)); color.orange600 = __.FM.float_4_1_1_1_1(__.float(0.9176470588235294), __.float(0.34509803921568627), __.float(0.047058823529411764), __.int(1)); color.orange700 = __.FM.float_4_1_1_1_1(__.float(0.7607843137254902), __.float(0.2549019607843137), __.float(0.047058823529411764), __.int(1)); color.orange800 = __.FM.float_4_1_1_1_1(__.float(0.6039215686274509), __.float(0.20392156862745098), __.float(0.07058823529411765), __.int(1)); color.orange900 = __.FM.float_4_1_1_1_1(__.float(0.48627450980392156), __.float(0.17647058823529413), __.float(0.07058823529411765), __.int(1)); color.orange950 = __.FM.float_4_1_1_1_1(__.float(0.2627450980392157), __.float(0.0784313725490196), __.float(0.027450980392156862), __.int(1)); color.amber50 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.984313725490196), __.float(0.9215686274509803), __.int(1)); color.amber100 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9529411764705882), __.float(0.7803921568627451), __.int(1)); color.amber200 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.9019607843137255), __.float(0.5411764705882353), __.int(1)); color.amber300 = __.FM.float_4_1_1_1_1(__.float(0.9882352941176471), __.float(0.8274509803921568), __.float(0.30196078431372547), __.int(1)); color.amber400 = __.FM.float_4_1_1_1_1(__.float(0.984313725490196), __.float(0.7490196078431373), __.float(0.1411764705882353), __.int(1)); color.amber500 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.6196078431372549), __.float(0.043137254901960784), __.int(1)); color.amber600 = __.FM.float_4_1_1_1_1(__.float(0.8509803921568627), __.float(0.4666666666666667), __.float(0.023529411764705882), __.int(1)); color.amber700 = __.FM.float_4_1_1_1_1(__.float(0.7058823529411765), __.float(0.3254901960784314), __.float(0.03529411764705882), __.int(1)); color.amber800 = __.FM.float_4_1_1_1_1(__.float(0.5725490196078431), __.float(0.25098039215686274), __.float(0.054901960784313725), __.int(1)); color.amber900 = __.FM.float_4_1_1_1_1(__.float(0.47058823529411764), __.float(0.20784313725490197), __.float(0.058823529411764705), __.int(1)); color.amber950 = __.FM.float_4_1_1_1_1(__.float(0.27058823529411763), __.float(0.10196078431372549), __.float(0.011764705882352941), __.int(1)); color.yellow50 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9882352941176471), __.float(0.9098039215686274), __.int(1)); color.yellow100 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9764705882352941), __.float(0.7647058823529411), __.int(1)); color.yellow200 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9411764705882353), __.float(0.5411764705882353), __.int(1)); color.yellow300 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.8784313725490196), __.float(0.2784313725490196), __.int(1)); color.yellow400 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.8), __.float(0.08235294117647059), __.int(1)); color.yellow500 = __.FM.float_4_1_1_1_1(__.float(0.9176470588235294), __.float(0.7019607843137254), __.float(0.03137254901960784), __.int(1)); color.yellow600 = __.FM.float_4_1_1_1_1(__.float(0.792156862745098), __.float(0.5411764705882353), __.float(0.01568627450980392), __.int(1)); color.yellow700 = __.FM.float_4_1_1_1_1(__.float(0.6313725490196078), __.float(0.3843137254901961), __.float(0.027450980392156862), __.int(1)); color.yellow800 = __.FM.float_4_1_1_1_1(__.float(0.5215686274509804), __.float(0.30196078431372547), __.float(0.054901960784313725), __.int(1)); color.yellow900 = __.FM.float_4_1_1_1_1(__.float(0.44313725490196076), __.float(0.24705882352941178), __.float(0.07058823529411765), __.int(1)); color.yellow950 = __.FM.float_4_1_1_1_1(__.float(0.25882352941176473), __.float(0.12549019607843137), __.float(0.023529411764705882), __.int(1)); color.lime50 = __.FM.float_4_1_1_1_1(__.float(0.9686274509803922), __.float(0.996078431372549), __.float(0.9058823529411765), __.int(1)); color.lime100 = __.FM.float_4_1_1_1_1(__.float(0.9254901960784314), __.float(0.9882352941176471), __.float(0.796078431372549), __.int(1)); color.lime200 = __.FM.float_4_1_1_1_1(__.float(0.8509803921568627), __.float(0.9764705882352941), __.float(0.615686274509804), __.int(1)); color.lime300 = __.FM.float_4_1_1_1_1(__.float(0.7450980392156863), __.float(0.9490196078431372), __.float(0.39215686274509803), __.int(1)); color.lime400 = __.FM.float_4_1_1_1_1(__.float(0.6392156862745098), __.float(0.9019607843137255), __.float(0.20784313725490197), __.int(1)); color.lime500 = __.FM.float_4_1_1_1_1(__.float(0.5176470588235295), __.float(0.8), __.float(0.08627450980392157), __.int(1)); color.lime600 = __.FM.float_4_1_1_1_1(__.float(0.396078431372549), __.float(0.6392156862745098), __.float(0.050980392156862744), __.int(1)); color.lime700 = __.FM.float_4_1_1_1_1(__.float(0.30196078431372547), __.float(0.48627450980392156), __.float(0.058823529411764705), __.int(1)); color.lime800 = __.FM.float_4_1_1_1_1(__.float(0.24705882352941178), __.float(0.3843137254901961), __.float(0.07058823529411765), __.int(1)); color.lime900 = __.FM.float_4_1_1_1_1(__.float(0.21176470588235294), __.float(0.3254901960784314), __.float(0.0784313725490196), __.int(1)); color.lime950 = __.FM.float_4_1_1_1_1(__.float(0.10196078431372549), __.float(0.1803921568627451), __.float(0.0196078431372549), __.int(1)); color.green50 = __.FM.float_4_1_1_1_1(__.float(0.9411764705882353), __.float(0.9921568627450981), __.float(0.9568627450980393), __.int(1)); color.green100 = __.FM.float_4_1_1_1_1(__.float(0.8627450980392157), __.float(0.9882352941176471), __.float(0.9058823529411765), __.int(1)); color.green200 = __.FM.float_4_1_1_1_1(__.float(0.7333333333333333), __.float(0.9686274509803922), __.float(0.8156862745098039), __.int(1)); color.green300 = __.FM.float_4_1_1_1_1(__.float(0.5254901960784314), __.float(0.9372549019607843), __.float(0.6745098039215687), __.int(1)); color.green400 = __.FM.float_4_1_1_1_1(__.float(0.2901960784313726), __.float(0.8705882352941177), __.float(0.5019607843137255), __.int(1)); color.green500 = __.FM.float_4_1_1_1_1(__.float(0.13333333333333333), __.float(0.7725490196078432), __.float(0.3686274509803922), __.int(1)); color.green600 = __.FM.float_4_1_1_1_1(__.float(0.08627450980392157), __.float(0.6392156862745098), __.float(0.2901960784313726), __.int(1)); color.green700 = __.FM.float_4_1_1_1_1(__.float(0.08235294117647059), __.float(0.5019607843137255), __.float(0.23921568627450981), __.int(1)); color.green800 = __.FM.float_4_1_1_1_1(__.float(0.08627450980392157), __.float(0.396078431372549), __.float(0.20392156862745098), __.int(1)); color.green900 = __.FM.float_4_1_1_1_1(__.float(0.0784313725490196), __.float(0.3254901960784314), __.float(0.17647058823529413), __.int(1)); color.green950 = __.FM.float_4_1_1_1_1(__.float(0.0196078431372549), __.float(0.1803921568627451), __.float(0.08627450980392157), __.int(1)); color.emerald50 = __.FM.float_4_1_1_1_1(__.float(0.9254901960784314), __.float(0.9921568627450981), __.float(0.9607843137254902), __.int(1)); color.emerald100 = __.FM.float_4_1_1_1_1(__.float(0.8196078431372549), __.float(0.9803921568627451), __.float(0.8980392156862745), __.int(1)); color.emerald200 = __.FM.float_4_1_1_1_1(__.float(0.6549019607843137), __.float(0.9529411764705882), __.float(0.8156862745098039), __.int(1)); color.emerald300 = __.FM.float_4_1_1_1_1(__.float(0.43137254901960786), __.float(0.9058823529411765), __.float(0.7176470588235294), __.int(1)); color.emerald400 = __.FM.float_4_1_1_1_1(__.float(0.20392156862745098), __.float(0.8274509803921568), __.float(0.6), __.int(1)); color.emerald500 = __.FM.float_4_1_1_1_1(__.float(0.06274509803921569), __.float(0.7254901960784313), __.float(0.5058823529411764), __.int(1)); color.emerald600 = __.FM.float_4_1_1_1_1(__.float(0.0196078431372549), __.float(0.5882352941176471), __.float(0.4117647058823529), __.int(1)); color.emerald700 = __.FM.float_4_1_1_1_1(__.float(0.01568627450980392), __.float(0.47058823529411764), __.float(0.3411764705882353), __.int(1)); color.emerald800 = __.FM.float_4_1_1_1_1(__.float(0.023529411764705882), __.float(0.37254901960784315), __.float(0.27450980392156865), __.int(1)); color.emerald900 = __.FM.float_4_1_1_1_1(__.float(0.023529411764705882), __.float(0.3058823529411765), __.float(0.23137254901960785), __.int(1)); color.emerald950 = __.FM.float_4_1_1_1_1(__.float(0.00784313725490196), __.float(0.17254901960784313), __.float(0.13333333333333333), __.int(1)); color.teal50 = __.FM.float_4_1_1_1_1(__.float(0.9411764705882353), __.float(0.9921568627450981), __.float(0.9803921568627451), __.int(1)); color.teal100 = __.FM.float_4_1_1_1_1(__.float(0.8), __.float(0.984313725490196), __.float(0.9450980392156862), __.int(1)); color.teal200 = __.FM.float_4_1_1_1_1(__.float(0.6), __.float(0.9647058823529412), __.float(0.8941176470588236), __.int(1)); color.teal300 = __.FM.float_4_1_1_1_1(__.float(0.3686274509803922), __.float(0.9176470588235294), __.float(0.8313725490196079), __.int(1)); color.teal400 = __.FM.float_4_1_1_1_1(__.float(0.17647058823529413), __.float(0.8313725490196079), __.float(0.7490196078431373), __.int(1)); color.teal500 = __.FM.float_4_1_1_1_1(__.float(0.0784313725490196), __.float(0.7215686274509804), __.float(0.6509803921568628), __.int(1)); color.teal600 = __.FM.float_4_1_1_1_1(__.float(0.050980392156862744), __.float(0.5803921568627451), __.float(0.5333333333333333), __.int(1)); color.teal700 = __.FM.float_4_1_1_1_1(__.float(0.058823529411764705), __.float(0.4627450980392157), __.float(0.43137254901960786), __.int(1)); color.teal800 = __.FM.float_4_1_1_1_1(__.float(0.06666666666666667), __.float(0.3686274509803922), __.float(0.34901960784313724), __.int(1)); color.teal900 = __.FM.float_4_1_1_1_1(__.float(0.07450980392156863), __.float(0.3058823529411765), __.float(0.2901960784313726), __.int(1)); color.teal950 = __.FM.float_4_1_1_1_1(__.float(0.01568627450980392), __.float(0.1843137254901961), __.float(0.1803921568627451), __.int(1)); color.cyan50 = __.FM.float_4_1_1_1_1(__.float(0.9254901960784314), __.float(0.996078431372549), __.int(1), __.int(1)); color.cyan100 = __.FM.float_4_1_1_1_1(__.float(0.8117647058823529), __.float(0.9803921568627451), __.float(0.996078431372549), __.int(1)); color.cyan200 = __.FM.float_4_1_1_1_1(__.float(0.6470588235294118), __.float(0.9529411764705882), __.float(0.9882352941176471), __.int(1)); color.cyan300 = __.FM.float_4_1_1_1_1(__.float(0.403921568627451), __.float(0.9098039215686274), __.float(0.9764705882352941), __.int(1)); color.cyan400 = __.FM.float_4_1_1_1_1(__.float(0.13333333333333333), __.float(0.8274509803921568), __.float(0.9333333333333333), __.int(1)); color.cyan500 = __.FM.float_4_1_1_1_1(__.float(0.023529411764705882), __.float(0.7137254901960784), __.float(0.8313725490196079), __.int(1)); color.cyan600 = __.FM.float_4_1_1_1_1(__.float(0.03137254901960784), __.float(0.5686274509803921), __.float(0.6980392156862745), __.int(1)); color.cyan700 = __.FM.float_4_1_1_1_1(__.float(0.054901960784313725), __.float(0.4549019607843137), __.float(0.5647058823529412), __.int(1)); color.cyan800 = __.FM.float_4_1_1_1_1(__.float(0.08235294117647059), __.float(0.3686274509803922), __.float(0.4588235294117647), __.int(1)); color.cyan900 = __.FM.float_4_1_1_1_1(__.float(0.08627450980392157), __.float(0.3058823529411765), __.float(0.38823529411764707), __.int(1)); color.cyan950 = __.FM.float_4_1_1_1_1(__.float(0.03137254901960784), __.float(0.2), __.float(0.26666666666666666), __.int(1)); color.sky50 = __.FM.float_4_1_1_1_1(__.float(0.9411764705882353), __.float(0.9764705882352941), __.int(1), __.int(1)); color.sky100 = __.FM.float_4_1_1_1_1(__.float(0.8784313725490196), __.float(0.9490196078431372), __.float(0.996078431372549), __.int(1)); color.sky200 = __.FM.float_4_1_1_1_1(__.float(0.7294117647058823), __.float(0.9019607843137255), __.float(0.9921568627450981), __.int(1)); color.sky300 = __.FM.float_4_1_1_1_1(__.float(0.49019607843137253), __.float(0.8274509803921568), __.float(0.9882352941176471), __.int(1)); color.sky400 = __.FM.float_4_1_1_1_1(__.float(0.2196078431372549), __.float(0.7411764705882353), __.float(0.9725490196078431), __.int(1)); color.sky500 = __.FM.float_4_1_1_1_1(__.float(0.054901960784313725), __.float(0.6470588235294118), __.float(0.9137254901960784), __.int(1)); color.sky600 = __.FM.float_4_1_1_1_1(__.float(0.00784313725490196), __.float(0.5176470588235295), __.float(0.7803921568627451), __.int(1)); color.sky700 = __.FM.float_4_1_1_1_1(__.float(0.011764705882352941), __.float(0.4117647058823529), __.float(0.6313725490196078), __.int(1)); color.sky800 = __.FM.float_4_1_1_1_1(__.float(0.027450980392156862), __.float(0.34901960784313724), __.float(0.5215686274509804), __.int(1)); color.sky900 = __.FM.float_4_1_1_1_1(__.float(0.047058823529411764), __.float(0.2901960784313726), __.float(0.43137254901960786), __.int(1)); color.sky950 = __.FM.float_4_1_1_1_1(__.float(0.03137254901960784), __.float(0.1843137254901961), __.float(0.28627450980392155), __.int(1)); color.blue50 = __.FM.float_4_1_1_1_1(__.float(0.9372549019607843), __.float(0.9647058823529412), __.int(1), __.int(1)); color.blue100 = __.FM.float_4_1_1_1_1(__.float(0.8588235294117647), __.float(0.9176470588235294), __.float(0.996078431372549), __.int(1)); color.blue200 = __.FM.float_4_1_1_1_1(__.float(0.7490196078431373), __.float(0.8588235294117647), __.float(0.996078431372549), __.int(1)); color.blue300 = __.FM.float_4_1_1_1_1(__.float(0.5764705882352941), __.float(0.7725490196078432), __.float(0.9921568627450981), __.int(1)); color.blue400 = __.FM.float_4_1_1_1_1(__.float(0.3764705882352941), __.float(0.6470588235294118), __.float(0.9803921568627451), __.int(1)); color.blue500 = __.FM.float_4_1_1_1_1(__.float(0.23137254901960785), __.float(0.5098039215686274), __.float(0.9647058823529412), __.int(1)); color.blue600 = __.FM.float_4_1_1_1_1(__.float(0.1450980392156863), __.float(0.38823529411764707), __.float(0.9215686274509803), __.int(1)); color.blue700 = __.FM.float_4_1_1_1_1(__.float(0.11372549019607843), __.float(0.3058823529411765), __.float(0.8470588235294118), __.int(1)); color.blue800 = __.FM.float_4_1_1_1_1(__.float(0.11764705882352941), __.float(0.25098039215686274), __.float(0.6862745098039216), __.int(1)); color.blue900 = __.FM.float_4_1_1_1_1(__.float(0.11764705882352941), __.float(0.22745098039215686), __.float(0.5411764705882353), __.int(1)); color.blue950 = __.FM.float_4_1_1_1_1(__.float(0.09019607843137255), __.float(0.1450980392156863), __.float(0.32941176470588235), __.int(1)); color.indigo50 = __.FM.float_4_1_1_1_1(__.float(0.9333333333333333), __.float(0.9490196078431372), __.int(1), __.int(1)); color.indigo100 = __.FM.float_4_1_1_1_1(__.float(0.8784313725490196), __.float(0.9058823529411765), __.int(1), __.int(1)); color.indigo200 = __.FM.float_4_1_1_1_1(__.float(0.7803921568627451), __.float(0.8235294117647058), __.float(0.996078431372549), __.int(1)); color.indigo300 = __.FM.float_4_1_1_1_1(__.float(0.6470588235294118), __.float(0.7058823529411765), __.float(0.9882352941176471), __.int(1)); color.indigo400 = __.FM.float_4_1_1_1_1(__.float(0.5058823529411764), __.float(0.5490196078431373), __.float(0.9725490196078431), __.int(1)); color.indigo500 = __.FM.float_4_1_1_1_1(__.float(0.38823529411764707), __.float(0.4), __.float(0.9450980392156862), __.int(1)); color.indigo600 = __.FM.float_4_1_1_1_1(__.float(0.30980392156862746), __.float(0.27450980392156865), __.float(0.8980392156862745), __.int(1)); color.indigo700 = __.FM.float_4_1_1_1_1(__.float(0.2627450980392157), __.float(0.2196078431372549), __.float(0.792156862745098), __.int(1)); color.indigo800 = __.FM.float_4_1_1_1_1(__.float(0.21568627450980393), __.float(0.18823529411764706), __.float(0.6392156862745098), __.int(1)); color.indigo900 = __.FM.float_4_1_1_1_1(__.float(0.19215686274509805), __.float(0.1803921568627451), __.float(0.5058823529411764), __.int(1)); color.indigo950 = __.FM.float_4_1_1_1_1(__.float(0.11764705882352941), __.float(0.10588235294117647), __.float(0.29411764705882354), __.int(1)); color.violet50 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.9529411764705882), __.int(1), __.int(1)); color.violet100 = __.FM.float_4_1_1_1_1(__.float(0.9294117647058824), __.float(0.9137254901960784), __.float(0.996078431372549), __.int(1)); color.violet200 = __.FM.float_4_1_1_1_1(__.float(0.8666666666666667), __.float(0.8392156862745098), __.float(0.996078431372549), __.int(1)); color.violet300 = __.FM.float_4_1_1_1_1(__.float(0.7686274509803922), __.float(0.7098039215686275), __.float(0.9921568627450981), __.int(1)); color.violet400 = __.FM.float_4_1_1_1_1(__.float(0.6549019607843137), __.float(0.5450980392156862), __.float(0.9803921568627451), __.int(1)); color.violet500 = __.FM.float_4_1_1_1_1(__.float(0.5450980392156862), __.float(0.3607843137254902), __.float(0.9647058823529412), __.int(1)); color.violet600 = __.FM.float_4_1_1_1_1(__.float(0.48627450980392156), __.float(0.22745098039215686), __.float(0.9294117647058824), __.int(1)); color.violet700 = __.FM.float_4_1_1_1_1(__.float(0.42745098039215684), __.float(0.1568627450980392), __.float(0.8509803921568627), __.int(1)); color.violet800 = __.FM.float_4_1_1_1_1(__.float(0.3568627450980392), __.float(0.12941176470588237), __.float(0.7137254901960784), __.int(1)); color.violet900 = __.FM.float_4_1_1_1_1(__.float(0.2980392156862745), __.float(0.11372549019607843), __.float(0.5843137254901961), __.int(1)); color.violet950 = __.FM.float_4_1_1_1_1(__.float(0.1803921568627451), __.float(0.06274509803921569), __.float(0.396078431372549), __.int(1)); color.purple50 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9607843137254902), __.int(1), __.int(1)); color.purple100 = __.FM.float_4_1_1_1_1(__.float(0.9529411764705882), __.float(0.9098039215686274), __.int(1), __.int(1)); color.purple200 = __.FM.float_4_1_1_1_1(__.float(0.9137254901960784), __.float(0.8352941176470589), __.int(1), __.int(1)); color.purple300 = __.FM.float_4_1_1_1_1(__.float(0.8470588235294118), __.float(0.7058823529411765), __.float(0.996078431372549), __.int(1)); color.purple400 = __.FM.float_4_1_1_1_1(__.float(0.7529411764705882), __.float(0.5176470588235295), __.float(0.9882352941176471), __.int(1)); color.purple500 = __.FM.float_4_1_1_1_1(__.float(0.6588235294117647), __.float(0.3333333333333333), __.float(0.9686274509803922), __.int(1)); color.purple600 = __.FM.float_4_1_1_1_1(__.float(0.5764705882352941), __.float(0.2), __.float(0.9176470588235294), __.int(1)); color.purple700 = __.FM.float_4_1_1_1_1(__.float(0.49411764705882355), __.float(0.13333333333333333), __.float(0.807843137254902), __.int(1)); color.purple800 = __.FM.float_4_1_1_1_1(__.float(0.4196078431372549), __.float(0.12941176470588237), __.float(0.6588235294117647), __.int(1)); color.purple900 = __.FM.float_4_1_1_1_1(__.float(0.34509803921568627), __.float(0.10980392156862745), __.float(0.5294117647058824), __.int(1)); color.purple950 = __.FM.float_4_1_1_1_1(__.float(0.23137254901960785), __.float(0.027450980392156862), __.float(0.39215686274509803), __.int(1)); color.fuchsia50 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.9568627450980393), __.int(1), __.int(1)); color.fuchsia100 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9098039215686274), __.int(1), __.int(1)); color.fuchsia200 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.8156862745098039), __.float(0.996078431372549), __.int(1)); color.fuchsia300 = __.FM.float_4_1_1_1_1(__.float(0.9411764705882353), __.float(0.6705882352941176), __.float(0.9882352941176471), __.int(1)); color.fuchsia400 = __.FM.float_4_1_1_1_1(__.float(0.9098039215686274), __.float(0.4745098039215686), __.float(0.9764705882352941), __.int(1)); color.fuchsia500 = __.FM.float_4_1_1_1_1(__.float(0.8509803921568627), __.float(0.27450980392156865), __.float(0.9372549019607843), __.int(1)); color.fuchsia600 = __.FM.float_4_1_1_1_1(__.float(0.7529411764705882), __.float(0.14901960784313725), __.float(0.8274509803921568), __.int(1)); color.fuchsia700 = __.FM.float_4_1_1_1_1(__.float(0.6352941176470588), __.float(0.10980392156862745), __.float(0.6862745098039216), __.int(1)); color.fuchsia800 = __.FM.float_4_1_1_1_1(__.float(0.5254901960784314), __.float(0.09803921568627451), __.float(0.5607843137254902), __.int(1)); color.fuchsia900 = __.FM.float_4_1_1_1_1(__.float(0.4392156862745098), __.float(0.10196078431372549), __.float(0.4588235294117647), __.int(1)); color.fuchsia950 = __.FM.float_4_1_1_1_1(__.float(0.2901960784313726), __.float(0.01568627450980392), __.float(0.3058823529411765), __.int(1)); color.pink50 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.9490196078431372), __.float(0.9725490196078431), __.int(1)); color.pink100 = __.FM.float_4_1_1_1_1(__.float(0.9882352941176471), __.float(0.9058823529411765), __.float(0.9529411764705882), __.int(1)); color.pink200 = __.FM.float_4_1_1_1_1(__.float(0.984313725490196), __.float(0.8117647058823529), __.float(0.9098039215686274), __.int(1)); color.pink300 = __.FM.float_4_1_1_1_1(__.float(0.9764705882352941), __.float(0.6588235294117647), __.float(0.8313725490196079), __.int(1)); color.pink400 = __.FM.float_4_1_1_1_1(__.float(0.9568627450980393), __.float(0.4470588235294118), __.float(0.7137254901960784), __.int(1)); color.pink500 = __.FM.float_4_1_1_1_1(__.float(0.9254901960784314), __.float(0.2823529411764706), __.float(0.6), __.int(1)); color.pink600 = __.FM.float_4_1_1_1_1(__.float(0.8588235294117647), __.float(0.15294117647058825), __.float(0.4666666666666667), __.int(1)); color.pink700 = __.FM.float_4_1_1_1_1(__.float(0.7450980392156863), __.float(0.09411764705882353), __.float(0.36470588235294116), __.int(1)); color.pink800 = __.FM.float_4_1_1_1_1(__.float(0.615686274509804), __.float(0.09019607843137255), __.float(0.30196078431372547), __.int(1)); color.pink900 = __.FM.float_4_1_1_1_1(__.float(0.5137254901960784), __.float(0.09411764705882353), __.float(0.2627450980392157), __.int(1)); color.pink950 = __.FM.float_4_1_1_1_1(__.float(0.3137254901960784), __.float(0.027450980392156862), __.float(0.1411764705882353), __.int(1)); color.rose50 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.9450980392156862), __.float(0.9490196078431372), __.int(1)); color.rose100 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.8941176470588236), __.float(0.9019607843137255), __.int(1)); color.rose200 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.803921568627451), __.float(0.8274509803921568), __.int(1)); color.rose300 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.6431372549019608), __.float(0.6862745098039216), __.int(1)); color.rose400 = __.FM.float_4_1_1_1_1(__.float(0.984313725490196), __.float(0.44313725490196076), __.float(0.5215686274509804), __.int(1)); color.rose500 = __.FM.float_4_1_1_1_1(__.float(0.9568627450980393), __.float(0.24705882352941178), __.float(0.3686274509803922), __.int(1)); color.rose600 = __.FM.float_4_1_1_1_1(__.float(0.8823529411764706), __.float(0.11372549019607843), __.float(0.2823529411764706), __.int(1)); color.rose700 = __.FM.float_4_1_1_1_1(__.float(0.7450980392156863), __.float(0.07058823529411765), __.float(0.23529411764705882), __.int(1)); color.rose800 = __.FM.float_4_1_1_1_1(__.float(0.6235294117647059), __.float(0.07058823529411765), __.float(0.2235294117647059), __.int(1)); color.rose900 = __.FM.float_4_1_1_1_1(__.float(0.5333333333333333), __.float(0.07450980392156863), __.float(0.21568627450980393), __.int(1)); color.rose950 = __.FM.float_4_1_1_1_1(__.float(0.2980392156862745), __.float(0.0196078431372549), __.float(0.09803921568627451), __.int(1)); return color; }()); exports.color = color; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_57436_color\\",\\"fields\\":[[\\"slate50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}]]}"), color) ; function wrap2(value, low, high) { return __.makeVector((0, std_math_1.wrap)(value[0], low, high), (0, std_math_1.wrap)(value[1], low, high)); } exports.wrap2 = wrap2; ; function wrap3(value, low, high) { return __.makeVector((0, std_math_1.wrap)(value[0], low, high), (0, std_math_1.wrap)(value[1], low, high), (0, std_math_1.wrap)(value[2], low, high)); } exports.wrap3 = wrap3; ; function wrap4(value, low, high) { return __.makeVector((0, std_math_1.wrap)(value[0], low, high), (0, std_math_1.wrap)(value[1], low, high), (0, std_math_1.wrap)(value[2], low, high), (0, std_math_1.wrap)(value[3], low, high)); } exports.wrap4 = wrap4; ; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/sdf.ts": { outputFiles: [ { name: "/_std/sdf.js", writeByteOrderMark: false, text: `var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; define(["require", "exports", "/std_math", "/std_math", "/std___std_all"], function (require, exports, __, std_math_1, std___std_all_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sdf = void 0; __ = __importStar(__); var globalVarGet = std___std_all_1.globalVarGet; var sdf = /** @class */ (function () { function sdf(data) { } sdf.sphere = function (samplePosition, sphereCenter, radius) { var _a, _b; var p = (_a = samplePosition, _b = sphereCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var r = radius; return (0, std_math_1.length)(p) - r; }; sdf.box = function (samplePosition, boxCenter, boxSize) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = boxCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var s = boxSize; var q = (_c = (_e = p, [Math.abs(_e[0]), Math.abs(_e[1]), Math.abs(_e[2])]), _d = s, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); return (0, std_math_1.length)((0, std_math_1.max)(q, 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(q[0], (0, std_math_1.max)(q[1], q[2])), 0.0); }; sdf.roundBox = function (samplePosition, boxCenter, boxSize, cornerRadius) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = boxCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var s = boxSize; var r = cornerRadius; var q = (_c = (_e = p, [Math.abs(_e[0]), Math.abs(_e[1]), Math.abs(_e[2])]), _d = s, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); return (0, std_math_1.length)((0, std_math_1.max)(q, 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(q[0], (0, std_math_1.max)(q[1], q[2])), 0.0) - r; }; sdf.boxFrame = function (samplePosition, boxCenter, boxSize, frameThickness) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; var p = (_a = samplePosition, _b = boxCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var b = boxSize; var e = frameThickness; p = (_c = (_e = p, [Math.abs(_e[0]), Math.abs(_e[1]), Math.abs(_e[2])]), _d = b, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var q = (_f = (_h = (_j = p, _k = e, [_j[0] + _k, _j[1] + _k, _j[2] + _k]), [Math.abs(_h[0]), Math.abs(_h[1]), Math.abs(_h[2])]), _g = e, [_f[0] - _g, _f[1] - _g, _f[2] - _g]); return (0, std_math_1.min)((0, std_math_1.min)((0, std_math_1.length)((0, std_math_1.max)(__.FM.float_3_1_1_1(__.swizzle(p, 'x'), __.swizzle(q, 'y'), __.swizzle(q, 'z')), 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(p[0], (0, std_math_1.max)(q[1], q[2])), 0.0), (0, std_math_1.length)((0, std_math_1.max)(__.FM.float_3_1_1_1(__.swizzle(q, 'x'), __.swizzle(p, 'y'), __.swizzle(q, 'z')), 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(q[0], (0, std_math_1.max)(p[1], q[2])), 0.0)), (0, std_math_1.length)((0, std_math_1.max)(__.FM.float_3_1_1_1(__.swizzle(q, 'x'), __.swizzle(q, 'y'), __.swizzle(p, 'z')), 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(q[0], (0, std_math_1.max)(q[1], p[2])), 0.0)); }; sdf.torus = function (samplePosition, torusCenter, torusSize) { var _a, _b, _c; var p = (_a = samplePosition, _b = torusCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var t = torusSize; var q = __.FM.float_2_1_1(__.sub((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), t[0]), __.swizzle(p, 'y')); return (0, std_math_1.length)(q) - t[1]; }; sdf.cappedTorus = function (samplePosition, torusCenter, torusSize, ra, rb) { var _a, _b, _c, _d, _e; var p1 = (_a = samplePosition, _b = torusCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var p = __.makeVector(Math.abs(p1[0]), (_c = p1, [_c[1], _c[2]])); var sc = torusSize; var k = (sc[1] * p[0] > sc[0] * p[1]) ? (0, std_math_1.dot)((_d = p, [_d[0], _d[1]]), sc) : (0, std_math_1.length)((_e = p, [_e[0], _e[1]])); return Math.sqrt((0, std_math_1.dot)(p, p) + ra * ra - 2.0 * ra * k) - rb; }; sdf.link = function (samplePosition, linkCenter, linkLength, r1, r2) { var _a, _b, _c; var p = (_a = samplePosition, _b = linkCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var le = linkLength; var q = __.FM.float_3_1_1_1(__.swizzle(p, 'x'), (0, std_math_1.max)(Math.abs(p[1]) - le, 0.0), __.swizzle(p, 'z')); return (0, std_math_1.length)(__.FM.float_2_1_1(__.sub((0, std_math_1.length)((_c = q, [_c[0], _c[1]])), r1), __.swizzle(q, 'z'))) - r2; }; sdf.infinteCylinder = function (samplePosition, cylinderCenter, cylinderSize) { var _a, _b, _c, _d, _e, _f; var p = (_a = samplePosition, _b = cylinderCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var c = cylinderSize; return (0, std_math_1.length)((_c = (_e = p, [_e[0], _e[2]]), _d = (_f = c, [_f[0], _f[1]]), [_c[0] - _d[0], _c[1] - _d[1]])) - c[2]; }; sdf.cone = function (samplePosition, coneCenter, c, coneHeight) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; var p = (_a = samplePosition, _b = coneCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = coneHeight; // c is the sin/cos of the angle, h is height // Alternatively pass q instead of (c,h), // which is the point at the base in 2D var q = (_c = h, _d = __.FM.float_2_1_1(__.div(c[0], c[1]), __.negate(1.0)), [_c * _d[0], _c * _d[1]]); var w = __.FM.float_2_1_1((0, std_math_1.length)((_e = p, [_e[0], _e[2]])), __.swizzle(p, 'y')); var a = (_f = w, _g = (_h = q, _j = (0, std_math_1.clamp)((0, std_math_1.dot)(w, q) / (0, std_math_1.dot)(q, q), 0.0, 1.0), [_h[0] * _j, _h[1] * _j]), [_f[0] - _g[0], _f[1] - _g[1]]); var b = (_k = w, _l = (_m = q, _o = __.FM.float_2_1_1((0, std_math_1.clamp)(w[0] / q[0], 0.0, 1.0), __.float(1.0)), [_m[0] * _o[0], _m[1] * _o[1]]), [_k[0] - _l[0], _k[1] - _l[1]]); var k = Math.sign(q[1]); var d = (0, std_math_1.min)((0, std_math_1.dot)(a, a), (0, std_math_1.dot)(b, b)); var s = (0, std_math_1.max)(k * (w[0] * q[1] - w[1] * q[0]), k * (w[1] - q[1])); return Math.sqrt(d) * Math.sign(s); }; sdf.plane = function (samplePosition, planeCenter, planeNormal, planeHeight) { var _a, _b; var p = (_a = samplePosition, _b = planeCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var n = planeNormal; var h = planeHeight; // n must be normalized return (0, std_math_1.dot)(p, n) + h; }; sdf.hexPrism = function (samplePosition, hexCenter, hexSize) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; var p = (_a = samplePosition, _b = hexCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = hexSize; var k = __.FM.float_3_1_1_1(__.negate(0.8660254), __.float(0.5), __.float(0.57735)); p = (_c = p, [Math.abs(_c[0]), Math.abs(_c[1]), Math.abs(_c[2])]); var dddd = (0, std_math_1.min)((0, std_math_1.dot)((_d = k, [_d[0], _d[1]]), (_e = p, [_e[0], _e[1]])), 0.0) * 2.0; p = (_f = p, _g = __.FM.float_3_2_1(__.mul(dddd, (_h = k, [_h[0], _h[1]])), __.float(0.0)), [_f[0] - _g[0], _f[1] - _g[1], _f[2] - _g[2]]); var d = __.FM.float_2_1_1(__.mul((0, std_math_1.length)((_j = (_l = p, [_l[0], _l[1]]), _k = __.FM.float_2_1_1((0, std_math_1.clamp)(p[0], (__.FM.negate_1(k[2])) * h[0], k[2] * h[0]), __.swizzle(h, 'x')), [_j[0] - _k[0], _j[1] - _k[1]])), Math.sign(p[1] - h[0])), __.sub(p[2], h[1])); return (0, std_math_1.min)((0, std_math_1.max)(d[0], d[1]), 0.0) + (0, std_math_1.length)((0, std_math_1.max)(d, 0.0)); }; sdf.triPrism = function (samplePosition, triCenter, triSize) { var _a, _b, _c; var p = (_a = samplePosition, _b = triCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = triSize; var q = (_c = p, [Math.abs(_c[0]), Math.abs(_c[1]), Math.abs(_c[2])]); return (0, std_math_1.max)(q[2] - h[1], (0, std_math_1.max)(q[0] * 0.866025 + p[1] * 0.5, (__.FM.negate_1(p[1]))) - h[0] * 0.5); }; sdf.capsuleLine = function (samplePosition, lineStart, lineEnd, capsuleRadius) { var _a, _b, _c, _d, _e, _f, _g, _h; var p = samplePosition; var a = lineStart; var b = lineEnd; var r = capsuleRadius; var pa = (_a = p, _b = a, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var ba = (_c = b, _d = a, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var h = (0, std_math_1.clamp)((0, std_math_1.dot)(pa, ba) / (0, std_math_1.dot)(ba, ba), 0.0, 1.0); return (0, std_math_1.length)((_e = pa, _f = (_g = ba, _h = h, [_g[0] * _h, _g[1] * _h, _g[2] * _h]), [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]])) - r; }; sdf.capsule = function (samplePosition, capsuleCenter, height, radius) { var _a, _b; var p1 = (_a = samplePosition, _b = capsuleCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var r = radius; var p = __.makeVector(p1[0], p1[1] - (0, std_math_1.clamp)(p1[1], 0.0, h), p1[2]); return (0, std_math_1.length)(p) - r; }; sdf.cylinder = function (samplePosition, cylinderCenter, height, radius) { var _a, _b, _c, _d, _e, _f; var p = (_a = samplePosition, _b = cylinderCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var r = radius; var d = (_c = (_e = __.FM.float_2_1_1((0, std_math_1.length)((_f = p, [_f[0], _f[2]])), __.swizzle(p, 'y')), [Math.abs(_e[0]), Math.abs(_e[1])]), _d = __.FM.float_2_1_1(r, h), [_c[0] - _d[0], _c[1] - _d[1]]); return (0, std_math_1.min)((0, std_math_1.max)(d[0], d[1]), 0.0) + (0, std_math_1.length)((0, std_math_1.max)(d, 0.0)); }; sdf.cylinderLine = function (samplePosition, lineStart, lineEnd, radius) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; var p = samplePosition; var a = lineStart; var b = lineEnd; var r = radius; var ba = (_a = b, _b = a, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var pa = (_c = p, _d = a, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var baba = (0, std_math_1.dot)(ba, ba); var paba = (0, std_math_1.dot)(pa, ba); var x = (0, std_math_1.length)((_e = (_g = pa, _h = baba, [_g[0] * _h, _g[1] * _h, _g[2] * _h]), _f = (_j = ba, _k = paba, [_j[0] * _k, _j[1] * _k, _j[2] * _k]), [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]])) - r * baba; var y = Math.abs(paba - baba * 0.5) - baba * 0.5; var x2 = x * x; var y2 = y * y * baba; var mxxy = (0, std_math_1.max)(x, y); var d = (mxxy < 0.0) ? (__.FM.negate_1((0, std_math_1.min)(x2, y2))) : (((x > 0.0) ? x2 : 0.0) + ((y > 0.0) ? y2 : 0.0)); return Math.sign(d) * Math.sqrt(Math.abs(d)) / baba; }; sdf.roundedCylinder = function (samplePosition, cylinderCenter, cylinderRadius, cornerRadius, height) { var _a, _b, _c; var p = (_a = samplePosition, _b = cylinderCenter, [_a[0] - _b, _a[1] - _b, _a[2] - _b]); var h = height; var ra = cylinderRadius; var rb = cornerRadius; var d = __.FM.float_2_1_1(__.add((0, std_math_1.length)((_c = p, [_c[0], _c[2]])) - 2.0 * ra, rb), __.sub(Math.abs(p[1]), h)); return (0, std_math_1.min)((0, std_math_1.max)(d[0], d[1]), 0.0) + (0, std_math_1.length)((0, std_math_1.max)(d, 0.0)) - rb; }; sdf.cappedCone = function (samplePosition, coneCenter, height, r1, r2) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; var p = (_a = samplePosition, _b = coneCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); var k1 = __.FM.float_2_1_1(r2, h); var k2 = __.FM.float_2_1_1(__.sub(r2, r1), __.mul(2.0, h)); var ca = __.FM.float_2_1_1(__.sub(q[0], (0, std_math_1.min)(q[0], (q[1] < 0.0) ? r1 : r2)), __.sub(Math.abs(q[1]), h)); var cb = (_d = (_f = q, _g = k1, [_f[0] - _g[0], _f[1] - _g[1]]), _e = (_h = k2, _j = (0, std_math_1.clamp)((0, std_math_1.dot)((_k = k1, _l = q, [_k[0] - _l[0], _k[1] - _l[1]]), k2) / dot2(k2), 0.0, 1.0), [_h[0] * _j, _h[1] * _j]), [_d[0] + _e[0], _d[1] + _e[1]]); var s = (__.and(cb[0] < 0.0, ca[1] < 0.0)) ? (__.FM.negate_1(1.0)) : 1.0; return s * Math.sqrt((0, std_math_1.min)(dot2(ca), dot2(cb))); }; sdf.solidAngle = function (samplePosition, solidCenter, size, radius) { var _a, _b, _c, _d, _e, _f, _g; var p = (_a = samplePosition, _b = solidCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var c = size; var ra = radius; // c is the sin/cos of the angle var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); var l = (0, std_math_1.length)(q) - ra; var m = (0, std_math_1.length)((_d = q, _e = (_f = c, _g = (0, std_math_1.clamp)((0, std_math_1.dot)(q, c), 0.0, ra), [_f[0] * _g, _f[1] * _g]), [_d[0] - _e[0], _d[1] - _e[1]])); return (0, std_math_1.max)(l, m * Math.sign(c[1] * q[0] - c[0] * q[1])); }; sdf.cutSphere = function (samplePosition, sphereCenter, radius, height) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = sphereCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var r = radius; // sampling independent computations (only depend on shape) var w = Math.sqrt(r * r - h * h); // sampling dependant computations var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); var s = (0, std_math_1.max)((h - r) * q[0] * q[0] + w * w * (h + r - 2.0 * q[1]), h * q[0] - w * q[1]); return (s < 0.0) ? (0, std_math_1.length)(q) - r : (q[0] < w) ? h - q[1] : (0, std_math_1.length)((_d = q, _e = __.FM.float_2_1_1(w, h), [_d[0] - _e[0], _d[1] - _e[1]])); }; sdf.cutHollowSphere = function (samplePosition, sphereCenter, radius, height, thickness) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = sphereCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var r = radius; var h = height; var t = thickness; // sampling independent computations (only depend on shape) var w = Math.sqrt(r * r - h * h); // sampling dependant computations var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); return ((h * q[0] < w * q[1]) ? (0, std_math_1.length)((_d = q, _e = __.FM.float_2_1_1(w, h), [_d[0] - _e[0], _d[1] - _e[1]])) : Math.abs((0, std_math_1.length)(q) - r)) - t; }; sdf.roundCone = function (samplePosition, coneCenter, coneRadius, cornerRadius, height) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = coneCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var r1 = coneRadius; var r2 = cornerRadius; // sampling independent computations (only depend on shape) var b = (r1 - r2) / h; var a = Math.sqrt(1.0 - b * b); // sampling dependant computations var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); var k = (0, std_math_1.dot)(q, __.FM.float_2_1_1(__.negate(b), a)); if (k < 0.0) return (0, std_math_1.length)(q) - r1; if (k > a * h) return (0, std_math_1.length)((_d = q, _e = __.FM.float_2_1_1(__.float(0.0), h), [_d[0] - _e[0], _d[1] - _e[1]])) - r2; return (0, std_math_1.dot)(q, __.FM.float_2_1_1(a, b)) - r1; }; sdf.ellipsoid = function (samplePosition, center, radius) { var _a, _b, _c, _d, _e, _f, _g, _h; var p = (_a = samplePosition, _b = center, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var r = radius; var k0 = (0, std_math_1.length)((_c = p, _d = r, [_c[0] / _d[0], _c[1] / _d[1], _c[2] / _d[2]])); var k1 = (0, std_math_1.length)((_e = p, _f = (_g = r, _h = r, [_g[0] * _h[0], _g[1] * _h[1], _g[2] * _h[2]]), [_e[0] / _f[0], _e[1] / _f[1], _e[2] / _f[2]])); return k0 * (k0 - 1.0) / k1; }; sdf.rhombus = function (samplePosition, rhombusCenter, la, lb, height, ra) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; var p = (_a = samplePosition, _b = rhombusCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; p = (_c = p, [Math.abs(_c[0]), Math.abs(_c[1]), Math.abs(_c[2])]); var b = __.FM.float_2_1_1(la, lb); var f = (0, std_math_1.clamp)((ndot(b, (_d = b, _e = (_f = 2.0, _g = (_h = p, [_h[0], _h[2]]), [_f * _g[0], _f * _g[1]]), [_d[0] - _e[0], _d[1] - _e[1]]))) / (0, std_math_1.dot)(b, b), (__.FM.negate_1(1.0)), 1.0); var q = __.FM.float_2_1_1(__.sub((0, std_math_1.length)((_j = (_l = p, [_l[0], _l[2]]), _k = (_m = (_p = 0.5, _q = b, [_p * _q[0], _p * _q[1]]), _o = __.FM.float_2_1_1(__.sub(1.0, f), __.add(1.0, f)), [_m[0] * _o[0], _m[1] * _o[1]]), [_j[0] - _k[0], _j[1] - _k[1]])) * Math.sign(p[0] * b[1] + p[2] * b[0] - b[0] * b[1]), ra), __.sub(p[1], h)); return (0, std_math_1.min)((0, std_math_1.max)(q[0], q[1]), 0.0) + (0, std_math_1.length)((0, std_math_1.max)(q, 0.0)); }; sdf.octahedron = function (samplePosition, center, size) { var _a, _b, _c, _d, _e, _f, _g; var p = (_a = samplePosition, _b = center, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var s = size; p = (_c = p, [Math.abs(_c[0]), Math.abs(_c[1]), Math.abs(_c[2])]); var m = p[0] + p[1] + p[2] - s; var q = (_d = 0.0, [_d, _d, _d]); if (3.0 * p[0] < m) q = (_e = p, [_e[0], _e[1], _e[2]]); else if (3.0 * p[1] < m) q = (_f = p, [_f[1], _f[2], _f[0]]); else if (3.0 * p[2] < m) q = (_g = p, [_g[2], _g[0], _g[1]]); else return m * 0.57735027; var k = (0, std_math_1.clamp)(0.5 * (q[2] - q[1] + s), 0.0, s); return (0, std_math_1.length)(__.FM.float_3_1_1_1(__.swizzle(q, 'x'), __.add(q[1] - s, k), __.sub(q[2], k))); }; sdf.pyramid = function (samplePosition, pyramidCenter, height) { var _a, _b; var p1 = (_a = samplePosition, _b = pyramidCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var m2 = h * h + 0.25; var p2 = __.makeVector(Math.abs(p1[0]), p1[1], Math.abs(p1[2])); if (p1[2] > p1[0]) { p2 = __.makeVector(p2[2], p2[1], p2[0]); } p2 = __.makeVector(p2[0] - 0.5, p2[1], p2[2] - 0.5); var p = p2; var q = __.FM.float_3_1_1_1(__.swizzle(p, 'z'), __.sub(h * p[1], 0.5 * p[0]), __.add(h * p[0], 0.5 * p[1])); var s = (0, std_math_1.max)((__.FM.negate_1(q[0])), 0.0); var t = (0, std_math_1.clamp)((q[1] - 0.5 * p[2]) / (m2 + 0.25), 0.0, 1.0); var a = m2 * (q[0] + s) * (q[0] + s) + q[1] * q[1]; var b = m2 * (q[0] + 0.5 * t) * (q[0] + 0.5 * t) + (q[1] - m2 * t) * (q[1] - m2 * t); var d2 = (0, std_math_1.min)(q[1], (__.FM.negate_1(q[0])) * m2 - q[1] * 0.5) > 0.0 ? 0.0 : (0, std_math_1.min)(a, b); return Math.sqrt((d2 + q[2] * q[2]) / m2) * Math.sign((0, std_math_1.max)(q[2], (__.FM.negate_1(p[1])))); }; sdf.udTriangle = function (samplePosition, a, b, c) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z; var p = samplePosition; var ba = (_a = b, _b = a, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var pa = (_c = p, _d = a, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var cb = (_e = c, _f = b, [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]]); var pb = (_g = p, _h = b, [_g[0] - _h[0], _g[1] - _h[1], _g[2] - _h[2]]); var ac = (_j = a, _k = c, [_j[0] - _k[0], _j[1] - _k[1], _j[2] - _k[2]]); var pc = (_l = p, _m = c, [_l[0] - _m[0], _l[1] - _m[1], _l[2] - _m[2]]); var nor = (0, std_math_1.cross)(ba, ac); return Math.sqrt((Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(ba, nor), pa)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(cb, nor), pb)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(ac, nor), pc)) < 2.0) ? (0, std_math_1.min)((0, std_math_1.min)(dot3((_o = (_q = ba, _r = (0, std_math_1.clamp)((0, std_math_1.dot)(ba, pa) / dot3(ba), 0.0, 1.0), [_q[0] * _r, _q[1] * _r, _q[2] * _r]), _p = pa, [_o[0] - _p[0], _o[1] - _p[1], _o[2] - _p[2]])), dot3((_s = (_u = cb, _v = (0, std_math_1.clamp)((0, std_math_1.dot)(cb, pb) / dot3(cb), 0.0, 1.0), [_u[0] * _v, _u[1] * _v, _u[2] * _v]), _t = pb, [_s[0] - _t[0], _s[1] - _t[1], _s[2] - _t[2]]))), dot3((_w = (_y = ac, _z = (0, std_math_1.clamp)((0, std_math_1.dot)(ac, pc) / dot3(ac), 0.0, 1.0), [_y[0] * _z, _y[1] * _z, _y[2] * _z]), _x = pc, [_w[0] - _x[0], _w[1] - _x[1], _w[2] - _x[2]]))) : (0, std_math_1.dot)(nor, pa) * (0, std_math_1.dot)(nor, pa) / dot3(nor)); }; sdf.udQuad = function (samplePosition, a, b, c, d) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7; var p = samplePosition; var ba = (_a = b, _b = a, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var pa = (_c = p, _d = a, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var cb = (_e = c, _f = b, [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]]); var pb = (_g = p, _h = b, [_g[0] - _h[0], _g[1] - _h[1], _g[2] - _h[2]]); var dc = (_j = d, _k = c, [_j[0] - _k[0], _j[1] - _k[1], _j[2] - _k[2]]); var pc = (_l = p, _m = c, [_l[0] - _m[0], _l[1] - _m[1], _l[2] - _m[2]]); var ad = (_o = a, _p = d, [_o[0] - _p[0], _o[1] - _p[1], _o[2] - _p[2]]); var pd = (_q = p, _r = d, [_q[0] - _r[0], _q[1] - _r[1], _q[2] - _r[2]]); var nor = (0, std_math_1.cross)(ba, ad); return Math.sqrt((Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(ba, nor), pa)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(cb, nor), pb)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(dc, nor), pc)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(ad, nor), pd)) < 3.0) ? (0, std_math_1.min)((0, std_math_1.min)((0, std_math_1.min)(dot3((_s = (_u = ba, _v = (0, std_math_1.clamp)((0, std_math_1.dot)(ba, pa) / dot3(ba), 0.0, 1.0), [_u[0] * _v, _u[1] * _v, _u[2] * _v]), _t = pa, [_s[0] - _t[0], _s[1] - _t[1], _s[2] - _t[2]])), dot3((_w = (_y = cb, _z = (0, std_math_1.clamp)((0, std_math_1.dot)(cb, pb) / dot3(cb), 0.0, 1.0), [_y[0] * _z, _y[1] * _z, _y[2] * _z]), _x = pb, [_w[0] - _x[0], _w[1] - _x[1], _w[2] - _x[2]]))), dot3((_0 = (_2 = dc, _3 = (0, std_math_1.clamp)((0, std_math_1.dot)(dc, pc) / dot3(dc), 0.0, 1.0), [_2[0] * _3, _2[1] * _3, _2[2] * _3]), _1 = pc, [_0[0] - _1[0], _0[1] - _1[1], _0[2] - _1[2]]))), dot3((_4 = (_6 = ad, _7 = (0, std_math_1.clamp)((0, std_math_1.dot)(ad, pd) / dot3(ad), 0.0, 1.0), [_6[0] * _7, _6[1] * _7, _6[2] * _7]), _5 = pd, [_4[0] - _5[0], _4[1] - _5[1], _4[2] - _5[2]]))) : (0, std_math_1.dot)(nor, pa) * (0, std_math_1.dot)(nor, pa) / dot3(nor)); }; /** * Returns the intersection of two SDFs * = max(a, b) */ sdf.intersect = function (a, b) { return (0, std_math_1.max)(a, b); }; /** * Returns the union of two SDFs * = min(a, b) */ sdf.union = function (a, b) { return (0, std_math_1.min)(a, b); }; sdf.subtract = function (a, b) { return (0, std_math_1.max)((__.FM.negate_1(a)), b); }; sdf.smoothIntersect = function (a, b, k) { var h = (0, std_math_1.clamp)(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return (0, std_math_1.lerp)(b, a, h) - k * h * (1.0 - h); }; /** * Smoothly joins two SDFs using blending distance k */ sdf.smoothUnion = function (a, b, k) { var d1 = a; var d2 = b; var h = (0, std_math_1.clamp)(0.5 + 0.5 * (d2 - d1) / k, 0.0, 1.0); return (0, std_math_1.lerp)(d2, d1, h) - k * h * (1.0 - h); }; sdf.smoothSubtract = function (a, b, k) { var d1 = a; var d2 = b; var h = (0, std_math_1.clamp)(0.5 - 0.5 * (d2 + d1) / k, 0.0, 1.0); return (0, std_math_1.lerp)(d2, (__.FM.negate_1(d1)), h) + k * h * (1.0 - h); }; /** * Blends between two SDFs using interpolation */ sdf.blend = function (a, b, t) { return t * a + ((1 | 0) - t) * b; }; sdf.round = function (a, r) { return a - r; }; /** * Carve out the interior of an SDF */ sdf.onion = function (a, thickness) { return Math.abs(a) - thickness; }; sdf.grad = function (p, sampler) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; var DELTA = 0.0001; return _a = __.FM.float_3_1_1_1(__.sub(sampler((_c = p, _d = __.FM.float_3_1_1_1(DELTA, __.float(0.0), __.float(0.0)), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]])), sampler((_e = p, _f = __.FM.float_3_1_1_1(DELTA, __.float(0.0), __.float(0.0)), [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]]))), __.sub(sampler((_g = p, _h = __.FM.float_3_1_1_1(__.float(0.0), DELTA, __.float(0.0)), [_g[0] + _h[0], _g[1] + _h[1], _g[2] + _h[2]])), sampler((_j = p, _k = __.FM.float_3_1_1_1(__.float(0.0), DELTA, __.float(0.0)), [_j[0] - _k[0], _j[1] - _k[1], _j[2] - _k[2]]))), __.sub(sampler((_l = p, _m = __.FM.float_3_1_1_1(__.float(0.0), __.float(0.0), DELTA), [_l[0] + _m[0], _l[1] + _m[1], _l[2] + _m[2]])), sampler((_o = p, _p = __.FM.float_3_1_1_1(__.float(0.0), __.float(0.0), DELTA), [_o[0] - _p[0], _o[1] - _p[1], _o[2] - _p[2]])))), _b = (2.0 * DELTA), [_a[0] / _b, _a[1] / _b, _a[2] / _b]; }; /** * Poorly returns the closest point on the surface of an SDF * This is an inaccurate method */ sdf.closest = function (position, sampler) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y; var sep = 0.0001; var zero = ((0, std_math_1.min)(env.frame, (0 | 0)) | 0); var closest = position; var initialDist = sampler(position); var seed = (0 | 0); for (var j = (0 | 0); j < (200 | 0); j++) { var n = (_a = 0.0, [_a, _a, _a]); var distSum = 0.0; for (var i = zero; i < (4 | 0); i++) { var e = (_b = 0.5773, _c = (_d = (_f = 2.0, _g = __.FM.float_3_1_1_1((((i + (3 | 0)) >> (1 | 0)) & (1 | 0)), ((i >> (1 | 0)) & (1 | 0)), (i & (1 | 0))), [_f * _g[0], _f * _g[1], _f * _g[2]]), _e = 1.0, [_d[0] - _e, _d[1] - _e, _d[2] - _e]), [_b * _c[0], _b * _c[1], _b * _c[2]]); var d = sampler((_h = closest, _j = (_k = e, _l = sep, [_k[0] * _l, _k[1] * _l, _k[2] * _l]), [_h[0] + _j[0], _h[1] + _j[1], _h[2] + _j[2]])); distSum = distSum + d; n = (_m = n, _o = (_p = e, _q = d, [_p[0] * _q, _p[1] * _q, _p[2] * _q]), [_m[0] + _o[0], _m[1] + _o[1], _m[2] + _o[2]]); } closest = (_r = (_t = (_v = (_x = (0, std_math_1.normalize)(n), _y = distSum, [_x[0] * _y, _x[1] * _y, _x[2] * _y]), _w = (__.FM.negate_1((1 | 0))), [_v[0] * _w, _v[1] * _w, _v[2] * _w]), _u = 4.0, [_t[0] / _u, _t[1] / _u, _t[2] / _u]), _s = closest, [_r[0] + _s[0], _r[1] + _s[1], _r[2] + _s[2]]); if (distSum < 0.0001) { break; } } return closest; }; sdf.normal = function (position, sampler) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; var h = 0.1; var zero = ((0, std_math_1.min)(env.frame, (0 | 0)) | 0); var n = (_a = 0.0, [_a, _a, _a]); var distSum = 0.0; for (var i = zero; i < (4 | 0); i++) { var e = (_b = 0.5773, _c = (_d = (_f = 2.0, _g = __.FM.float_3_1_1_1((((i + (3 | 0)) >> (1 | 0)) & (1 | 0)), ((i >> (1 | 0)) & (1 | 0)), (i & (1 | 0))), [_f * _g[0], _f * _g[1], _f * _g[2]]), _e = 1.0, [_d[0] - _e, _d[1] - _e, _d[2] - _e]), [_b * _c[0], _b * _c[1], _b * _c[2]]); var d = sampler((_h = position, _j = (_k = e, _l = h, [_k[0] * _l, _k[1] * _l, _k[2] * _l]), [_h[0] + _j[0], _h[1] + _j[1], _h[2] + _j[2]])); distSum = distSum + d; n = (_m = n, _o = (_p = e, _q = d, [_p[0] * _q, _p[1] * _q, _p[2] * _q]), [_m[0] + _o[0], _m[1] + _o[1], _m[2] + _o[2]]); } return (0, std_math_1.normalize)(n); }; sdf.vizRings = function (d) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; if (false) { var color_1 = (_a = 1.0, _b = (_c = Math.sign(d), _d = __.FM.float_3_1_1_1(__.float(0.1), __.float(0.4), __.float(0.7)), [_c * _d[0], _c * _d[1], _c * _d[2]]), [_a - _b[0], _a - _b[1], _a - _b[2]]); color_1 = (_e = color_1, _f = 1.0 - Math.exp((__.FM.negate_1(4.0)) * Math.abs(d)), [_e[0] * _f, _e[1] * _f, _e[2] * _f]); color_1 = (_g = color_1, _h = 0.8 + 0.2 * Math.cos(140.0 * d), [_g[0] * _h, _g[1] * _h, _g[2] * _h]); color_1 = (0, std_math_1.lerp)(color_1, (_j = 1.0, [_j, _j, _j]), 1.0 - (0, std_math_1.smoothstep)(0.0, 0.015, Math.abs(d))); return __.makeVector(color_1, 1.0); } else { var size = (2 | 0); var fadeDist = (100 | 0); var v = (1 | 0) - (0, std_math_1.clamp)(d / fadeDist, (0 | 0), (1 | 0)); var color_2 = __.makeVector(0.4 * v, 0.6 * v, (1 | 0), (1 | 0)); var s = Math.sin(d / size); if (Math.abs(d) < (1 | 0)) { return __.FM.float_4_4(__.swizzle((1 | 0), "xyzw")); } else { return d > (0 | 0) ? (_k = color_2, _l = Math.ceil((1 | 0) - s), [_k[0] * _l, _k[1] * _l, _k[2] * _l, _k[3] * _l]) : (_m = color_2, _o = Math.ceil(s), [_m[0] * _o, _m[1] * _o, _m[2] * _o, _m[3] * _o]); } } }; sdf.march = function (position, direction, sampler) { var _a, _b, _c, _d; var maxDist = 100000.0; var minDist = 1.0; var dist = minDist; for (var i = (0 | 0); __.and(i < (256 | 0), dist < maxDist); i++) { var samp = sampler((_a = position, _b = (_c = direction, _d = dist, [_c[0] * _d, _c[1] * _d, _c[2] * _d]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]])); dist = dist + samp; if (Math.abs(samp) < (0.00005 * dist)) { break; } } if (dist > maxDist) { dist = (__.FM.negate_1(1.0)); } return dist; }; /** * See: https://iquilezles.org/articles/distfunctions/ * Infinitely repeats an SDF with space in between. This returns an updated position * * Example: * \`\`\`shadeup * sdf::sphere(sdf::repeat(p, 100.xyz), 0.xyz, 50.0); * \`\`\` */ sdf.repeat = function (position, space) { var _a, _b, _c, _d, _e, _f, _g; var p = position; var s = space; return _a = p, _b = (_c = s, _d = (_e = (_f = p, _g = s, [_f[0] / _g[0], _f[1] / _g[1], _f[2] / _g[2]]), [Math.round(_e[0]), Math.round(_e[1]), Math.round(_e[2])]), [_c[0] * _d[0], _c[1] * _d[1], _c[2] * _d[2]]), [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]; }; /** * See: https://iquilezles.org/articles/distfunctions/ * Repeats an SDF with space in between upto the limit. This returns an updated position * * Example: * \`\`\`shadeup * sdf::sphere(sdf::repeatLimited(p, 100, 10.xyz), 0.xyz, 50.0); * \`\`\` */ sdf.repeatLimited = function (position, space, limit) { var _a, _b, _c, _d, _e, _f, _g; var p = position; var s = space; return _a = p, _b = (_c = s, _d = (0, std_math_1.clamp)((_e = (_f = p, _g = s, [_f[0] / _g, _f[1] / _g, _f[2] / _g]), [Math.round(_e[0]), Math.round(_e[1]), Math.round(_e[2])]), (__.FM.negate_3(limit)), limit), [_c * _d[0], _c * _d[1], _c * _d[2]]), [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]; }; sdf.prototype.clone = function () { return new sdf({}); }; sdf.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_sdf_ts_1953_sdf\\",\\"fields\\":[]}"); }; return sdf; }()); exports.sdf = sdf; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_sdf_ts_1953_sdf\\",\\"fields\\":[]}"), sdf) ; function dot2(v) { return (0, std_math_1.dot)(v, v); } function dot3(v) { return (0, std_math_1.dot)(v, v); } function ndot(a, b) { return a[0] * b[0] - a[1] * b[1]; } }); /* impl sdf */ ` } ], emitSkipped: false, diagnostics: [] }, "/_std/geo.ts": { outputFiles: [ { name: "/_std/geo.js", writeByteOrderMark: false, text: 'var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, "default", { enumerable: true, value: v });\n}) : function(o, v) {\n o["default"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\ndefine(["require", "exports", "/std_math", "/std___std_all"], function (require, exports, __, std___std_all_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n __ = __importStar(__);\n var globalVarGet = std___std_all_1.globalVarGet;\n var GeoSegment = /** @class */ (function () {\n function GeoSegment(data) {\n var _a, _b, _c, _d, _e, _f;\n this.start = ((_a = data.start) !== null && _a !== void 0 ? _a : __.FM.float_2_1_1(0.0, 0.0));\n this.end = ((_b = data.end) !== null && _b !== void 0 ? _b : __.FM.float_2_1_1(0.0, 0.0));\n this.kind = ((_c = data.kind) !== null && _c !== void 0 ? _c : (0 | 0));\n this.arcRadius = ((_d = data.arcRadius) !== null && _d !== void 0 ? _d : 0.0);\n this.arcStart = ((_e = data.arcStart) !== null && _e !== void 0 ? _e : 0.0);\n this.arcEnd = ((_f = data.arcEnd) !== null && _f !== void 0 ? _f : 0.0);\n }\n GeoSegment.prototype.clone = function () {\n return new GeoSegment({\n start: (0, std___std_all_1.__deepClone)(this.start),\n end: (0, std___std_all_1.__deepClone)(this.end),\n kind: (0, std___std_all_1.__deepClone)(this.kind),\n arcRadius: (0, std___std_all_1.__deepClone)(this.arcRadius),\n arcStart: (0, std___std_all_1.__deepClone)(this.arcStart),\n arcEnd: (0, std___std_all_1.__deepClone)(this.arcEnd),\n });\n };\n GeoSegment.prototype._getStructure = function () {\n return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_1845_GeoSegment\\",\\"fields\\":[[\\"start\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"kind\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"arcRadius\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcStart\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}");\n };\n return GeoSegment;\n }());\n __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_1845_GeoSegment\\",\\"fields\\":[[\\"start\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"kind\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"arcRadius\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcStart\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"), GeoSegment)\n /**@shadeup=struct*/ var GeoPoly = /** @class */ (function () {\n function GeoPoly(data) {\n var _a;\n this.segments = ((_a = data.segments) !== null && _a !== void 0 ? _a : []);\n }\n GeoPoly.prototype.area = function () { return 0.0; };\n GeoPoly.prototype.perimeter = function () { return 0.0; };\n GeoPoly.prototype.discretize = function () { var shader_self_temp = this; return this.clone(); };\n GeoPoly.prototype.clone = function () {\n return new GeoPoly({\n segments: (0, std___std_all_1.__deepClone)(this.segments),\n });\n };\n GeoPoly.prototype._getStructure = function () {\n return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_2763_GeoPoly\\",\\"fields\\":[[\\"segments\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_1845_GeoSegment\\",\\"fields\\":[[\\"start\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"kind\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"arcRadius\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcStart\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]},\\"staticSize\\":1}]]}");\n };\n return GeoPoly;\n }());\n __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_2763_GeoPoly\\",\\"fields\\":[[\\"segments\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_1845_GeoSegment\\",\\"fields\\":[[\\"start\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"kind\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"arcRadius\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcStart\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]},\\"staticSize\\":1}]]}"), GeoPoly)\n});\n/* impl GeoPoly */\n' } ], emitSkipped: false, diagnostics: [] } }; function countLines(str) { let count2 = 0; for (let i = 0; i < str.length; i++) { if (str[i] === "\n") { count2++; } } return count2; } function indexToRowColumn(str, index) { let row = 0; let column = 0; for (let i = 0; i < index; i++) { if (str[i] === "\n") { row++; column = 0; } else { column++; } } return { row, column }; } function rowColumnToIndex(str, row, column) { let index = 0; let currentRow = 0; let currentColumn = 0; while (currentRow < row || currentColumn < column) { if (str[index] === "\n") { currentRow++; currentColumn = 0; } else { currentColumn++; } index++; } return index; } function getDiffRange(a, b) { let diffs = diff(a, b); if (diffs.length === 1) { return null; } let startIndex = 0; let oldEndIndex = a.length; let newEndIndex = b.length; let insertions = 0; let deletions = 0; let neutrals = 0; for (let i = 0; i < diffs.length; i++) { let diff2 = diffs[i]; if (diff2[0] === 1) { insertions++; } else if (diff2[0] === -1) { deletions++; } else if (diff2[0] === 0) { neutrals++; } if (insertions > 1 || deletions > 1 || neutrals > 1) { return null; } } for (let i = 0; i < diffs.length; i++) { let diff2 = diffs[i]; if (diff2[0] === 0) { startIndex += diff2[1].length; } else if (diff2[0] === -1) { oldEndIndex = startIndex + diff2[1].length; newEndIndex = startIndex; break; } else if (diff2[0] === 1) { newEndIndex = startIndex + diff2[1].length; oldEndIndex = startIndex; break; } } return { startIndex, oldEndIndex, newEndIndex, startPosition: indexToRowColumn(a, startIndex), oldEndPosition: indexToRowColumn(a, oldEndIndex), newEndPosition: indexToRowColumn(b, newEndIndex) }; } function getReplaceRange(a, b) { let diffs = diff(a, b); if (diffs.length === 1) { return { content: b, range: { start: 0, length: a.length } }; } let insertions = 0; let deletions = 0; let neutrals = 0; for (let i = 0; i < diffs.length; i++) { let diff2 = diffs[i]; if (diff2[0] === 1) { insertions++; } else if (diff2[0] === -1) { deletions++; } else if (diff2[0] === 0) { neutrals++; } if (insertions > 1 || deletions > 1 || neutrals > 1) { return { content: b, range: { start: 0, length: a.length } }; } } let startIndex = 0; let oldEndIndex = a.length; let newEndIndex = b.length; for (let i = 0; i < diffs.length; i++) { let diff2 = diffs[i]; if (diff2[0] === 0) { startIndex += diff2[1].length; } else if (diff2[0] === -1) { oldEndIndex = startIndex + diff2[1].length; newEndIndex = startIndex; } else if (diff2[0] === 1) { newEndIndex = startIndex + diff2[1].length; break; } } return { content: b.substring(startIndex, newEndIndex), range: { start: startIndex, length: oldEndIndex - startIndex } }; } function getFunctionNodeName(node2, sourceFile) { if (!sourceFile) { sourceFile = node2.getSourceFile(); } if (ts.isMethodDeclaration(node2)) { let parentName = node2.parent && ts.isClassDeclaration(node2.parent) ? node2.parent.name?.getText() : "not_class"; return sourceFile.fileName + ":" + parentName + ":" + node2.name?.getText(); } return sourceFile.fileName + ":" + node2.name?.getText(); } function canTypesBeCasted(a, b) { if (a === b) { return true; } if (a.startsWith("float") && b.startsWith("int") || a.startsWith("int") && b.startsWith("float")) { let aSize = parseInt(a[a.length - 1]); let bSize = parseInt(b[b.length - 1]); if (aSize == bSize) { return true; } } return false; } class ShadeupEnvironment { constructor(opts) { this.files = []; this.parser = null; this.tsEnv = null; this.loads = /* @__PURE__ */ new Map(); this.libraries = /* @__PURE__ */ new Set(); this.assetMappings = /* @__PURE__ */ new Map(); this.validationDiagnostics = /* @__PURE__ */ new Map(); this.graphValidationDiagnostics = /* @__PURE__ */ new Map(); this.options = { esnext: false }; this.emitLogs = true; this.stdEmitCache = /* @__PURE__ */ new Map(); if (opts) { this.options = opts; } } async init() { this.parser = await getShadeupParser(); this.tsEnv = await makeTypescriptEnvironment(this); { for (let k of Object.keys(quickCache)) { this.stdEmitCache.set(k, quickCache[k]); } } } setAssetMapping(assets) { console.log("Set asset mapping", assets); this.assetMappings = new Map(assets); } print(...args) { if (this.emitLogs) { console.log(...args); } } reset() { this.tagGraph = new TagGraph(); for (let f of this.files) { if (f.path == "/file.ts" || f.path.startsWith("/_std/")) continue; this.tsEnv.system.$fsMap.delete(f.path); } this.files = []; this.validationDiagnostics.clear(); this.graphValidationDiagnostics.clear(); } /** * Wipes out the tagGraph and rebuilds all and tags */ applyTags() { let checker = this.tsEnv?.env.languageService.getProgram().getTypeChecker(); let files2 = this.tsEnv.env.languageService.getProgram().getSourceFiles(); this.tagGraph = new TagGraph(); for (let file of files2) { ts.forEachChild(file, (node2) => { if (ts.isFunctionDeclaration(node2) || ts.isMethodDeclaration(node2)) { let name = getFunctionNodeName(node2); this.tagGraph.addNode(name, node2); let tags = findShadeupTags(node2); for (let tag of tags) { this.tagGraph.addTag(name, tag); } } if (ts.isClassDeclaration(node2)) { ts.forEachChild(node2, (child) => { if (ts.isMethodDeclaration(child)) { let name = getFunctionNodeName(child); this.tagGraph.addNode(name, child); let tags = findShadeupTags(child); for (let tag of tags) { this.tagGraph.addTag(name, tag); } } }); } }); } const visitNode = (node2) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let referencedFunctionName = getFunctionNodeName(funcDeclar); let callingFunction = closest( node2, (n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) ); if (callingFunction && (ts.isFunctionDeclaration(callingFunction) || ts.isMethodDeclaration(callingFunction))) { let callingFunctionName = getFunctionNodeName(callingFunction); this.tagGraph.addEdge(referencedFunctionName, callingFunctionName); } } } } ts.forEachChild(node2, visitNode); }; for (let file of files2) { ts.forEachChild(file, (node2) => { if (ts.isFunctionDeclaration(node2) || ts.isMethodDeclaration(node2)) { ts.forEachChild(node2, visitNode); } if (ts.isClassDeclaration(node2)) { ts.forEachChild(node2, (child) => { if (ts.isMethodDeclaration(child)) { ts.forEachChild(child, visitNode); } }); } }); } this.tagGraph.propagateTags(); } async regenerate(filePath) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let addedFiles = /* @__PURE__ */ new Set(); this.graphValidationDiagnostics.clear(); let now = performance.now(); let outputs = []; this.applyTags(); this.print("Tagged in ", performance.now() - now, "ms"); now = performance.now(); let checker = this.tsEnv.env.languageService.getProgram().getTypeChecker(); const addFile = (path) => { if (this.stdEmitCache.has(path)) { outputs.push(this.stdEmitCache.get(path)); return; } if (addedFiles.has(path)) { return; } console.log("Adding file ", path); addedFiles.add(path); let sourceFile = this.files.find((f) => f.path === path); let shaders = this.renderShaders(path); if (sourceFile) { sourceFile.shaders = shaders; } let out = this.tsEnv?.env.languageService.getEmitOutput(path); if (out) { let sf = this.tsEnv.env.getSourceFile(path); if (sourceFile) { this.graphValidationDiagnostics.set(path, validateGraph(this, sourceFile, sf, checker)); let outputCode = this.mixInShaders(sourceFile, out?.outputFiles[0].text); out.outputFiles[0].text = outputCode; } if (sf) { out.outputFiles[0].text = this.mixInStructs(sf, out.outputFiles[0].text); } if (this.loads.has(path)) { let jsOut = `__shadeup_register_loads(${JSON.stringify( this.loads.get(path).map((p) => { return this.assetMappings.get(p) || p; }) )});`; out.outputFiles[0].text = jsOut + out.outputFiles[0].text; } if (this.libraries.size > 0) { let jsOut = `__shadeup_register_libs(${JSON.stringify(Array.from(this.libraries))});`; out.outputFiles[0].text = jsOut + out.outputFiles[0].text; } if (path.startsWith("/_std/") || path == "/file.ts" || path == "/std_math.ts" || path == "/static-math.ts" || path == "/std___std_all.ts" || path == "/std.ts") { this.stdEmitCache.set(path, out); } outputs.push(out); } }; const addDir = (path) => { let files2 = this.tsEnv?.system.readDirectory(path); if (files2) { for (let f of files2) { let dirExists = this.tsEnv?.system.directoryExists(path + f); if (dirExists) { addDir(path + f.replace(/^\//, "") + "/"); } else { if (f.endsWith(".d.ts")) continue; let p = path + f.replace(/^\//, ""); try { addFile(p); } catch (e) { console.error(e); } } } } }; if (filePath) { await Promise.all( filePath.map(async (f) => { let sourceFile = this.tsEnv.env.getSourceFile(f); if (sourceFile) { let refs = this.tsEnv.env.languageService.getFileReferences(f); for (let dep of refs) { let shadeupFile = this.files.find((f2) => f2.path === dep.fileName); if (shadeupFile) { await this.writeFile( shadeupFile.path, shadeupFile.content, this.stdEmitCache.has(shadeupFile.path) ); try { addFile(dep.fileName); } catch (e) { console.error(e); } } } try { addFile(f); } catch (e) { console.error(e); } } }) ); } else { addDir("/"); } let s = outputs.map( (o) => o.outputFiles.map((oo) => ({ path: oo.name, contents: oo.text })) ).flat(); this.print("Regenerated in", performance.now() - now, "ms"); return s; } mixInShaders(file, code) { let finalPass = code; for (let pair of file.shaders) { let shader = pair.glsl; let params = []; let paramsTyped = []; for (let param of Object.keys(shader.locals)) { let u = shader.locals[param]; params.push(`_ext_uniform_local_${param}: ${param}`); paramsTyped.push(`_ext_uniform_local_${param}: ${JSON.stringify(u)}`); } for (let param of Object.keys(shader.globals)) { let u = shader.globals[param]; params.push( `_ext_uniform_global_${param}: globalVarGet("${cleanName(u.fileName)}", "${param}")` ); paramsTyped.push(`_ext_uniform_global_${param}: ${JSON.stringify(u.structure)}`); } finalPass = `__shadeup_gen_shader("${shader.key}", { webgl: {${paramsTyped.join(", ")}}, webgpu: ${JSON.stringify({ attributeInput: pair.wgsl.attributeInput, attributeOutput: pair.wgsl.attributeOutput, locals: pair.wgsl.locals, globals: pair.wgsl.globals })} }, {webgpu: \`${pair.wgsl.source}\`,webgl:\`${pair.glsl.source}\`, software: () => {}}, ${JSON.stringify(shader.sourceMapping)}); ` + finalPass; } if (file.path === "/main.ts") { this.print("Final pass", finalPass); } return finalPass; } mixInStructs(root, code) { let finalPass = code; let structs = []; walkNodes(root, (node2) => { if (ts.isClassDeclaration(node2)) { if (hasShadeupDocTag(node2, "struct")) { let structName = node2.name?.getText() ?? "Unknown"; let struct = { name: structName, fields: [] }; for (let member of node2.members) { if (ts.isPropertyDeclaration(member)) { let name = member.name.getText(); let type2 = member.type?.getText() ?? "any"; struct.fields.push({ name, type: type2 }); } } structs.push(struct); } } }); let sBlocks = []; for (let struct of structs) { sBlocks.push( `__shadeup_register_struct("${struct.name}", {${JSON.stringify(struct.fields)}});` ); } return finalPass; } errors(files2) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let now = performance.now(); let all = []; for (let f of this.files) { if (files2) { if (!files2.includes(f.path)) { continue; } } let errors2 = this.tsEnv.env.languageService.getSemanticDiagnostics(f.path); let syntacticErrors = this.tsEnv.env.languageService.getSyntacticDiagnostics(f.path); all.push( ...[...errors2, ...syntacticErrors].filter((e) => { if (e.code == 2345) { let parsed = /Argument of type '(.*)' is not assignable to parameter of type '(.*).*'/.exec( typeof e.messageText == "string" ? e.messageText : e.messageText.messageText ); if (parsed) { let [_, from, to] = parsed; if (canTypesBeCasted(from, to)) { return false; } } } else if (e.code == 2339) { let msgText = typeof e.messageText == "string" ? e.messageText : e.messageText.messageText; if (msgText.startsWith("Property '__index' does not exist on type '")) { return false; } } else if (e.code == 2705) { let msgText = typeof e.messageText == "string" ? e.messageText : e.messageText.messageText; if (msgText.startsWith( "An async function or method in ES5/ES3 requires the 'Promise' constructor." )) { return false; } } return true; }).map((e) => this.transformTSError(f, e)) ); let validationDiagnostics = this.validationDiagnostics.get(f.path) ?? []; all.push(...validationDiagnostics.map((e) => this.transformTSError(f, e))); let graphValidationDiagnostics = this.graphValidationDiagnostics.get(f.path) ?? []; all.push(...graphValidationDiagnostics.map((e) => this.transformTSError(f, e))); } this.print("Got errors in", performance.now() - now, "ms"); return all; } completions(path, pos) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let file = this.files.find((f) => f.path === path); if (!file) { throw new Error("File not found"); } let source = file.transpiled; indexToRowColumn(source, pos); let backTransform = reverseLookupIndexMappingCursor(file.mapping, pos); let fp = this.tsEnv.env.getSourceFile(path); console.log(fp.getFullText()); console.log( fp.getFullText().substring(0, backTransform) + "^" + fp.getFullText().substring(backTransform) ); let completions = this.tsEnv.env.languageService.getCompletionsAtPosition( path, backTransform, { includeExternalModuleExports: true, includeInsertTextCompletions: true, includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true, includeInlayVariableTypeHints: true, includeCompletionsWithClassMemberSnippets: true, includeCompletionsWithSnippetText: true, includeAutomaticOptionalChainCompletions: true, includeCompletionsForImportStatements: true, useLabelDetailsInCompletionEntries: true, includeInlayPropertyDeclarationTypeHints: true }, {} ); if (!completions) { return []; } let entries = []; let maxCompletions = 100; for (let c2 of completions.entries) { if (entries.length >= maxCompletions) { break; } let range2 = null; if (c2.replacementSpan) { let startOffset = c2.replacementSpan.start; let endOffset = c2.replacementSpan.start + c2.replacementSpan.length; let offsetRangeReal = lookupIndexMappingRange(file.mapping, startOffset, endOffset); let start = indexToRowColumn(file.content, offsetRangeReal.start); let end = indexToRowColumn(file.content, offsetRangeReal.end); range2 = { startLineNumber: start.row + 1, startColumn: start.column + 1, endLineNumber: end.row + 1, endColumn: end.column + 1 }; } entries.push({ range: range2, completion: c2, details: this.tsEnv.env.languageService.getCompletionEntryDetails( path, backTransform, c2.name, {}, c2.source, {}, c2.data ) }); } console.log(entries); return entries; } classifications(path) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let file = this.files.find((f) => f.path === path); if (!file) { throw new Error("File not found"); } this.tsEnv.env.getSourceFile(path); this.tsEnv.env.languageService.getProgram().getTypeChecker(); let ranges = []; for (let symbolRange of file.parsedFlatSymbolMap) { let offsetRangeReal = reverseLookupIndexMappingRange( file.mapping, symbolRange.startIndex, symbolRange.endIndex ); if (offsetRangeReal.start != 0 && offsetRangeReal.end < file.transpiled.length - 1 && isFinite(offsetRangeReal.start) && isFinite(offsetRangeReal.end)) { let info = this.tsEnv.env.languageService.getQuickInfoAtPosition( path, offsetRangeReal.start ); if (info) { let backRange = lookupIndexMappingRange( file.mapping, info.textSpan.start, info.textSpan.start + info.textSpan.length ); let kind = info.kind; const funcMatch = /^\(alias\)\s+[^(]+\(/i; if (kind == "alias") { let fullStr = ""; let isNew = false; for (let p of info.displayParts) { fullStr += p.text; if (p.kind == "keyword" && (p.text == "class" || p.text == "new")) { kind = ts.ScriptElementKind.classElement; if (p.text == "new") { isNew = true; } } if (p.kind == "keyword" && p.text == "namespace") { kind = ts.ScriptElementKind.classElement; } if (p.kind == "keyword" && p.text == "type") { kind = ts.ScriptElementKind.classElement; } } if (!isNew && funcMatch.test(fullStr)) { kind = ts.ScriptElementKind.functionElement; } } ranges.push([backRange.start, backRange.end, kind]); } } } return { ranges }; } hover(path, pos) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let file = this.files.find((f) => f.path === path); if (!file) { throw new Error("File not found"); } let source = file.transpiled; indexToRowColumn(source, pos); let backTransform = reverseLookupIndexMappingCursor(file.mapping, pos); this.tsEnv.env.getSourceFile(path); let hovers = this.tsEnv.env.languageService.getQuickInfoAtPosition(path, backTransform); if (!hovers) { return null; } let startOffset = hovers.textSpan.start; let endOffset = hovers.textSpan.start + hovers.textSpan.length; let offsetRangeReal = lookupIndexMappingRange(file.mapping, startOffset, endOffset); let start = indexToRowColumn(file.content, offsetRangeReal.start); let end = indexToRowColumn(file.content, offsetRangeReal.end); hovers.range = { startLineNumber: start.row + 1, startColumn: start.column + 1, endLineNumber: end.row + 1, endColumn: end.column + 1 }; return hovers; } getFileErrorData(f, estart, eend) { let file = this.files.find((f2) => f2.path === f.path); if (!file) { return { file: f, source: f.getFullText(), start: estart, end: eend }; } let start = indexToRowColumn(file.transpiled, estart ?? 0); let realStart = file.map?.originalPositionFor({ column: start.column, line: start.row + 1 }); let end = indexToRowColumn(file.transpiled, eend); let realEnd = file.map?.originalPositionFor({ column: end.column, line: end.row + 1 }); let startIndex = realStart?.line && realStart?.column ? rowColumnToIndex(file.content, realStart?.line, realStart?.column) : 0; let endIndex = realEnd?.line && realEnd?.column ? rowColumnToIndex(file.content, realEnd?.line, realEnd?.column) : 0; startIndex = lookupIndexMapping(file.mapping, estart ?? 0); endIndex = lookupIndexMapping(file.mapping, eend); let o = lookupIndexMappingRange(file.mapping, estart ?? 0, eend); startIndex = o.start; endIndex = o.end; return { file, source: file.content, start: startIndex, end: endIndex }; } transformTSError(file, error) { if (error.file === void 0) { return { error, file: file.path, message: error.messageText.toString() }; } const printReal = true; let { source, start, end } = this.getFileErrorData( error.file, error.start ?? 0, (error.start ?? 0) + (error.length ?? 0) ); { start = error.start ?? 0; end = (error.start ?? 0) + (error.length ?? 0); } let categorymapping = { [ts.DiagnosticCategory.Error]: ReportKind.Error, [ts.DiagnosticCategory.Warning]: ReportKind.Warning, [ts.DiagnosticCategory.Message]: ReportKind.Advice, [ts.DiagnosticCategory.Suggestion]: ReportKind.Advice }; let r = Report.build(categorymapping[error.category], file.path, start).with_code(error.code); if (typeof error.messageText === "string") { r = r.with_message(error.messageText); } function addMessage(msgObj) { if (typeof msgObj === "string") { r = r.with_label( Label.from([file.path, Range.new(start, Math.max(start, end))]).with_message(msgObj) ); } else { r = r.with_label( Label.from([file.path, Range.new(start, Math.max(start, end))]).with_message( nicerError(msgObj) ) ); for (let d of msgObj.next ?? []) { addMessage(d); } } } if (typeof error.messageText === "string") { addMessage(nicerError(error)); } else { addMessage(error.messageText); } for (let d of error.relatedInformation ?? []) { let relatedRange = { start: d.start ?? 0, end: (d.start ?? 0) + (d.length ?? 0) }; if (typeof d.messageText === "string") { r.with_label( Label.from([ file.path, Range.new(relatedRange.start, Math.max(relatedRange.start, relatedRange.end)) ]).with_message(nicerError(d)) ); } else { for (let d2 of d.messageText.next ?? []) { addMessage(d2); } } } let rf = r.finish(); let writer = mkStringWriter(); try { rf.printTo( [file.path, Source.from(printReal ? error.file.text : source)], writer ); } catch (e) { this.print(e); } let ansi_up2 = new AnsiUp(); let msg = writer.unwrap(); if (typeof process === "undefined" || typeof process.stdout === "undefined") { msg = ansi_up2.ansi_to_html(msg); } return { error, file: file.path, message: msg }; } async translateSource(file, range2 = null) { if (!this.parser) { throw new Error("Parser not initialized"); } let now = performance.now(); if (range2) file.oldTree?.edit(range2); let f = this.parser.parse(file.content, range2 ? file.oldTree ?? void 0 : void 0); if (file.oldTree) { let nowTree = performance.now(); file.oldTree.getChangedRanges(f); this.print("Got edited range in", performance.now() - nowTree, "ms"); } this.print("Parsed in", performance.now() - now, "ms"); file.oldTree = f; file.parsedFlatSymbolMap = this.extractFlatSymbolMap(f.rootNode); now = performance.now(); try { let ctx = new AstContext("file:///" + file.path); prePass(ctx, f.rootNode); let compiled = compile(ctx, f.rootNode); file.parseDiagnostics = ctx.diagnostics.map((d) => ({ message: d.message, startIndex: d.node.startIndex, endIndex: d.node.endIndex })); this.print("Compiled in", performance.now() - now, "ms"); now = performance.now(); let ss = { str: "", indexMapping: [] }; compiled.toString(ss); this.print("Rendered with source map in ", performance.now() - now, "ms"); this.print("---- Translated ----"); file.transpiled = ss.str; now = performance.now(); file.mapping = ss.indexMapping; this.print("Created source map consumer in", performance.now() - now, "ms"); } catch (e) { console.error("Error while compiling", e); this.print(f.rootNode.toString()); } } extractFlatSymbolMap(rootNode) { let symbols = []; let stack = [rootNode]; while (stack.length > 0) { let node2 = stack.pop(); if (node2.type === "identifier" || node2.type === "property_identifier" || node2.type === "type_identifier") { symbols.push({ startIndex: node2.startIndex, endIndex: node2.endIndex }); } for (let c2 of node2.children) { stack.push(c2); } } return symbols; } async writeFile(path, content, ignoreValidate = false) { if (!ignoreValidate) console.log("Writing", path); let now = performance.now(); let file = this.files.find((f) => f.path === path); let oldContent = ""; if (!file) { this.files.push({ path, content, transpiled: "", shaders: [], map: null, oldTree: null, mapping: [], parseDiagnostics: [], parsedFlatSymbolMap: [] }); file = this.files[this.files.length - 1]; } else { oldContent = file.content; file.content = content; } let nowDiff = performance.now(); let r = getDiffRange(oldContent, content); this.print( "Source code diff took", performance.now() - nowDiff, "ms", "with", countLines(content), "lines" ); let getNow = performance.now(); this.print("Get source file took", performance.now() - getNow, "ms"); await this.translateSource(file, r); let sf = this.tsEnv?.env.getSourceFile(path); if (sf) { nowDiff = performance.now(); let r2 = getReplaceRange(sf.text, file.transpiled); this.print( "TypeScript code diff took", performance.now() - nowDiff, "ms", "with", countLines(sf.text), "lines" ); let updateNow = performance.now(); this.print("Replacing", r2.range, "with", r2.content.length, "chars"); this.tsEnv?.env.updateFile(path, r2.content, r2.range); this.print("Update took", performance.now() - updateNow, "ms"); let finalText = this.tsEnv.env.getSourceFile(path)?.text; if (finalText !== file.transpiled) { console.error("Final text does not match transpiled text"); } } else { this.tsEnv?.env.createFile(path, file.transpiled); } this.print("---- Took", performance.now() - now, "ms ----"); this.print(""); if (!ignoreValidate) { let sourceFile = this.tsEnv?.env.getSourceFile(path); if (sourceFile) { let program = this.tsEnv?.env.languageService.getProgram(); let checker = program?.getTypeChecker(); if (checker) { this.validationDiagnostics.set(path, validate(file, sourceFile, checker)); } } } } async writeFileTypescript(path, content) { this.print("Writing", path); let now = performance.now(); let sf = this.tsEnv?.env.getSourceFile(path); if (sf) { let nowDiff = performance.now(); let r = getReplaceRange(sf.text, content); this.print(sf.text.substring(r.range.start, r.range.start + r.range.length), r.content); this.print( "TypeScript code diff took", performance.now() - nowDiff, "ms", "with", countLines(sf.text), "lines" ); let updateNow = performance.now(); this.print("Replacing", r.range, "with", r.content.length, "chars"); this.tsEnv?.env.updateFile(path, r.content, r.range); this.print("Update took", performance.now() - updateNow, "ms"); let finalText = this.tsEnv.env.getSourceFile(path)?.text; this.print(finalText); if (finalText !== content) { console.error("Final text does not match input text"); } } else { this.tsEnv?.env.createFile(path, content); } this.print("---- Took", performance.now() - now, "ms ----"); this.print(""); } addDiagnostic(path, diagnostic) { if (!this.validationDiagnostics.has(path)) { this.validationDiagnostics.set(path, []); } this.validationDiagnostics.get(path)?.push(diagnostic); } printNodeLocation(n) { let sf = n.getSourceFile(); let file = this.files.find((f) => f.path === sf.fileName); if (!file) { return "internal"; } else { let mapping = lookupIndexMappingRange(file.mapping, n.getStart(), n.getEnd()); let loc = indexToRowColumn(file.content, mapping.start); return `${sf.fileName}:${loc.row + 1}:${loc.column + 1}`; } } renderShaders(path) { let shaders = []; this.tsEnv?.env.getSourceFile(path); let program = this.tsEnv?.env.languageService.getProgram(); if (!program) { return []; } let checker = program?.getTypeChecker(); if (!checker) { return []; } for (let sourceFile of program?.getSourceFiles() ?? []) { if (sourceFile.fileName === path) { walkNodes(sourceFile, (node2) => { if (ts.isCallExpression(node2) && node2.expression.getText() == "makeShader") { let lhsType = checker?.getTypeAtLocation(node2.getChildAt(0)); let sig = lhsType?.getCallSignatures(); if (sig && sig[0] && sig[0].getDeclaration()) { let declaration = sig[0].getDeclaration(); if (hasShadeupDocTag(declaration, "shader")) { let isComputeShader = false; let computeShaderSize = [0, 0, 0]; let parentNode = node2.parent; if (parentNode && ts.isAsExpression(parentNode) && parentNode.parent && ts.isCallExpression(parentNode.parent)) { if (parentNode.parent.arguments.length === 2) { isComputeShader = true; let lastChildArg = parentNode.parent.arguments[1]; if (ts.isArrayLiteralExpression(lastChildArg)) { let elements = lastChildArg.elements; if (elements.length === 3) { computeShaderSize = [ parseInt(elements[0].getText().replace(/[^\d]/g, "")), parseInt(elements[1].getText().replace(/[^\d]/g, "")), parseInt(elements[2].getText().replace(/[^\d]/g, "")) ]; } } } } checker?.getTypeAtLocation(declaration); if (node2.arguments.length === 2) { if (ts.isStringLiteral(node2.arguments[0])) { let key = node2.arguments[0].text; try { let glslShader = addGLSLShader( key, node2.arguments[1], checker, this, isComputeShader, computeShaderSize ); let wgslShader = addWGSLShader( key, node2.arguments[1], checker, this, isComputeShader, computeShaderSize ); if (glslShader && wgslShader) { shaders.push({ glsl: glslShader, wgsl: wgslShader }); } } catch (e) { console.error(e); if (e instanceof GLSLCompilationError) { this.addDiagnostic(path, { file: e.node.getSourceFile(), code: 0, messageText: e.message + " (this is being used in the shader defined at " + this.printNodeLocation(node2) + ")", category: ts.DiagnosticCategory.Error, start: e.node.getStart(), length: 2 }); this.addDiagnostic(path, { file: node2.getSourceFile(), code: 0, messageText: "this shader has an error in its code (" + e.message + " at " + this.printNodeLocation(e.node) + ")", category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }); } } } } } } } }); } } return shaders; } patchFile(path, content, start, length) { } } function walkNodes(node2, cb) { cb(node2); node2.forEachChild((n) => walkNodes(n, cb)); } function hasShadeupDocTag(node2, tagName) { return ts.getJSDocTags(node2).some((tag) => tag.tagName.text === "shadeup" && tag.comment === "=" + tagName); } const std = "export { ui } from '/_std/ui';\r\nexport { mesh, Mesh } from '/_std/mesh';\r\nexport { sdf } from '/_std/sdf';\r\nexport { geo } from '/_std/geo';\r\nexport * from '/_std/native';\r\n"; const ui = "import { getShadeupLocalContext } from '/_std/context';\r\n\r\nexport namespace ui {\r\n export function puck(position: float2): float2 {\r\n return getShadeupLocalContext()._SHADEUP_UI_PUCK(position);\r\n }\r\n\r\n export function draggable(position: float2, radius: float = 10): float2 {\r\n return getShadeupLocalContext()._SHADEUP_UI_PUCK(position, radius, true);\r\n }\r\n\r\n export function textbox(value: string): string {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('textbox', value);\r\n }\r\n\r\n export function slider(value: float, min: float, max: float): float {\r\n return getShadeupLocalContext()._SHADEUP_UI_SLIDER(value, { min, max });\r\n }\r\n\r\n export function label(text: string): void {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('label', text);\r\n }\r\n\r\n export function checkbox(value: bool): bool {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('checkbox', value);\r\n }\r\n\r\n export function combo(value: string, options: string[]): string {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('combo', value, { options });\r\n }\r\n\r\n export function group(text: string): void {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('group', text);\r\n }\r\n\r\n export function button(text: string): bool {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('button', false, { text });\r\n }\r\n\r\n export function pop(): void {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('pop');\r\n }\r\n}\r\n"; const native = `import { float4, float3, float, float2, bool, int } from '/std_math';\r import { texture2d } from '/_std/texture';\r import { Camera, Camera2d, quat } from '/_std/common';\r import { getShadeupLocalContext } from '/_std/context';\r \r export function shadeupMakeTextureFromUrl(url: string): texture2d {\r return getShadeupLocalContext()['shadeupMakeTextureFromUrlNative'](url);\r }\r \r export class FrameContext {\r /** Delta between the previous frame's time and this frame (in seconds */\r deltaTime: float;\r /** Current time in seconds from the start of the renderer */\r time: float;\r /** Canvas size in pixels */\r screenSize: float2;\r /** Current frame index */\r frame: int;\r \r /** Mouse/touch screen input state for this frame */\r mouse: MouseInputState = new MouseInputState();\r \r /** Keyboard input state for this frame */\r keyboard: KeyboardInputState = new KeyboardInputState();\r \r /** Controllable camera (Hold right click and use WASD to move) */\r camera: Camera = new Camera();\r \r camera2d: Camera2d = new Camera2d();\r \r configureCamera(options: {\r mode?: 'free' | 'orbit' | 'orbit-free';\r \r spinning?: boolean;\r \r initialPosition?: float3;\r initialPitch?: float;\r initialYaw?: float;\r \r speed?: float;\r \r orbitTarget?: float3;\r orbitDistance?: float;\r orbitPitch?: float;\r orbitYaw?: float;\r orbitMinDistance?: float;\r orbitMaxDistance?: float;\r orbitMinPitch?: float;\r orbitMaxPitch?: float;\r }) {}\r \r /**\r * Use external values from the host JavaScript environment.\r */\r input(key: string, defaultValue: T): T {\r return defaultValue;\r }\r \r /**\r * Send values to the host JavaScript environment.\r */\r output(key: string, value: T) {}\r }\r \r export class MouseInputState {\r /** Current mouse position relative to canvas in pixels ((0, 0) is the top left */\r screen: float2;\r /** Current mouse position mapped from 0-1 in canvas space ((0, 0) is the top left while (1, 1) is the bottom right */\r uv: float2;\r /** Caches the mouse position relative to canvas in pixels when any mouse button is pressed (resets after subsequent presses */\r startScreen: float2;\r /** Caches the mouse position mapped from 0-1 in canvas space when any mouse button is pressed (resets after subsequent presses */\r startUv: float2;\r /** If dragging, this will be the delta between the start and current mouse position */\r deltaUv: float2;\r /** If dragging, this will be the delta between the mouse position last frame and the current mouse position */\r frameDeltaUv: float2;\r /** If dragging, this will be the delta between the start and current mouse position */\r deltaScreen: float2;\r /** If dragging, this will be the delta between the mouse position last frame and the current mouse position */\r frameDeltaScreen: float2;\r /** , Some("Mouse button down state for buttons 0-3 (left, middle, right */\r button: [boolean, boolean, boolean] = [false, false, false];\r /** Mouse button pressed state for buttons 0-3 (left, middle, right) */\r clicked: [boolean, boolean, boolean] = [false, false, false];\r /** If currently dragging */\r dragging: bool;\r /** Accumulated mouse wheel movement for this frame in the range of -1 to 1 */\r wheel: float;\r /** Rate of change */\r velocity: float;\r /** Is the mouse focused within the screen */\r focused: bool;\r }\r \r export class KeyboardInputState {\r /** Is key down this frame */\r backspace: bool;\r \r /** Is key down this frame */\r tab: bool;\r \r /** Is key down this frame */\r enter: bool;\r \r /** Is key down this frame */\r shiftLeft: bool;\r \r /** Is key down this frame */\r shiftRight: bool;\r \r /** Is key down this frame */\r controlLeft: bool;\r \r /** Is key down this frame */\r controlRight: bool;\r \r /** Is key down this frame */\r altLeft: bool;\r \r /** Is key down this frame */\r altRight: bool;\r \r /** Is key down this frame */\r pause: bool;\r \r /** Is key down this frame */\r capsLock: bool;\r \r /** Is key down this frame */\r escape: bool;\r \r /** Is key down this frame */\r space: bool;\r \r /** Is key down this frame */\r pageUp: bool;\r \r /** Is key down this frame */\r pageDown: bool;\r \r /** Is key down this frame */\r end: bool;\r \r /** Is key down this frame */\r home: bool;\r \r /** Is key down this frame */\r arrowLeft: bool;\r \r /** Is key down this frame */\r arrowUp: bool;\r \r /** Is key down this frame */\r arrowRight: bool;\r \r /** Is key down this frame */\r arrowDown: bool;\r \r /** Is key down this frame */\r printScreen: bool;\r \r /** Is key down this frame */\r insert: bool;\r \r /** Is key down this frame */\r delete: bool;\r \r /** Is key down this frame */\r digit0: bool;\r \r /** Is key down this frame */\r digit1: bool;\r \r /** Is key down this frame */\r digit2: bool;\r \r /** Is key down this frame */\r digit3: bool;\r \r /** Is key down this frame */\r digit4: bool;\r \r /** Is key down this frame */\r digit5: bool;\r \r /** Is key down this frame */\r digit6: bool;\r \r /** Is key down this frame */\r digit7: bool;\r \r /** Is key down this frame */\r digit8: bool;\r \r /** Is key down this frame */\r digit9: bool;\r \r /** Is key down this frame */\r keyA: bool;\r \r /** Is key down this frame */\r keyB: bool;\r \r /** Is key down this frame */\r keyC: bool;\r \r /** Is key down this frame */\r keyD: bool;\r \r /** Is key down this frame */\r keyE: bool;\r \r /** Is key down this frame */\r keyF: bool;\r \r /** Is key down this frame */\r keyG: bool;\r \r /** Is key down this frame */\r keyH: bool;\r \r /** Is key down this frame */\r keyI: bool;\r \r /** Is key down this frame */\r keyJ: bool;\r \r /** Is key down this frame */\r keyK: bool;\r \r /** Is key down this frame */\r keyL: bool;\r \r /** Is key down this frame */\r keyM: bool;\r \r /** Is key down this frame */\r keyN: bool;\r \r /** Is key down this frame */\r keyO: bool;\r \r /** Is key down this frame */\r keyP: bool;\r \r /** Is key down this frame */\r keyQ: bool;\r \r /** Is key down this frame */\r keyR: bool;\r \r /** Is key down this frame */\r keyS: bool;\r \r /** Is key down this frame */\r keyT: bool;\r \r /** Is key down this frame */\r keyU: bool;\r \r /** Is key down this frame */\r keyV: bool;\r \r /** Is key down this frame */\r keyW: bool;\r \r /** Is key down this frame */\r keyX: bool;\r \r /** Is key down this frame */\r keyY: bool;\r \r /** Is key down this frame */\r keyZ: bool;\r \r /** Is key down this frame */\r metaLeft: bool;\r \r /** Is key down this frame */\r metaRight: bool;\r \r /** Is key down this frame */\r contextMenu: bool;\r \r /** Is key down this frame */\r numpad0: bool;\r \r /** Is key down this frame */\r numpad1: bool;\r \r /** Is key down this frame */\r numpad2: bool;\r \r /** Is key down this frame */\r numpad3: bool;\r \r /** Is key down this frame */\r numpad4: bool;\r \r /** Is key down this frame */\r numpad5: bool;\r \r /** Is key down this frame */\r numpad6: bool;\r \r /** Is key down this frame */\r numpad7: bool;\r \r /** Is key down this frame */\r numpad8: bool;\r \r /** Is key down this frame */\r numpad9: bool;\r \r /** Is key down this frame */\r numpadMultiply: bool;\r \r /** Is key down this frame */\r numpadAdd: bool;\r \r /** Is key down this frame */\r numpadSubtract: bool;\r \r /** Is key down this frame */\r numpadDecimal: bool;\r \r /** Is key down this frame */\r numpadDivide: bool;\r \r /** Is key down this frame */\r f1: bool;\r \r /** Is key down this frame */\r f2: bool;\r \r /** Is key down this frame */\r f3: bool;\r \r /** Is key down this frame */\r f4: bool;\r \r /** Is key down this frame */\r f5: bool;\r \r /** Is key down this frame */\r f6: bool;\r \r /** Is key down this frame */\r f7: bool;\r \r /** Is key down this frame */\r f8: bool;\r \r /** Is key down this frame */\r f9: bool;\r \r /** Is key down this frame */\r f10: bool;\r \r /** Is key down this frame */\r f11: bool;\r \r /** Is key down this frame */\r f12: bool;\r \r /** Is key down this frame */\r numLock: bool;\r \r /** Is key down this frame */\r scrollLock: bool;\r \r /** Is key down this frame */\r semicolon: bool;\r \r /** Is key down this frame */\r equal: bool;\r \r /** Is key down this frame */\r comma: bool;\r \r /** Is key down this frame */\r minus: bool;\r \r /** Is key down this frame */\r period: bool;\r \r /** Is key down this frame */\r slash: bool;\r \r /** Is key down this frame */\r backquote: bool;\r \r /** Is key down this frame */\r bracketLeft: bool;\r \r /** Is key down this frame */\r backslash: bool;\r \r /** Is key down this frame */\r bracketRight: bool;\r \r /** Is key down this frame */\r quote: bool;\r \r /** Key pressed, triggered once until released */ pressedBackspace: bool;\r /** Key pressed, triggered once until released */ pressedTab: bool;\r /** Key pressed, triggered once until released */ pressedEnter: bool;\r /** Key pressed, triggered once until released */ pressedShiftLeft: bool;\r /** Key pressed, triggered once until released */ pressedShiftRight: bool;\r /** Key pressed, triggered once until released */ pressedControlLeft: bool;\r /** Key pressed, triggered once until released */ pressedControlRight: bool;\r /** Key pressed, triggered once until released */ pressedAltLeft: bool;\r /** Key pressed, triggered once until released */ pressedAltRight: bool;\r /** Key pressed, triggered once until released */ pressedPause: bool;\r /** Key pressed, triggered once until released */ pressedCapsLock: bool;\r /** Key pressed, triggered once until released */ pressedEscape: bool;\r /** Key pressed, triggered once until released */ pressedSpace: bool;\r /** Key pressed, triggered once until released */ pressedPageUp: bool;\r /** Key pressed, triggered once until released */ pressedPageDown: bool;\r /** Key pressed, triggered once until released */ pressedEnd: bool;\r /** Key pressed, triggered once until released */ pressedHome: bool;\r /** Key pressed, triggered once until released */ pressedArrowLeft: bool;\r /** Key pressed, triggered once until released */ pressedArrowUp: bool;\r /** Key pressed, triggered once until released */ pressedArrowRight: bool;\r /** Key pressed, triggered once until released */ pressedArrowDown: bool;\r /** Key pressed, triggered once until released */ pressedPrintScreen: bool;\r /** Key pressed, triggered once until released */ pressedInsert: bool;\r /** Key pressed, triggered once until released */ pressedDelete: bool;\r /** Key pressed, triggered once until released */ pressedDigit0: bool;\r /** Key pressed, triggered once until released */ pressedDigit1: bool;\r /** Key pressed, triggered once until released */ pressedDigit2: bool;\r /** Key pressed, triggered once until released */ pressedDigit3: bool;\r /** Key pressed, triggered once until released */ pressedDigit4: bool;\r /** Key pressed, triggered once until released */ pressedDigit5: bool;\r /** Key pressed, triggered once until released */ pressedDigit6: bool;\r /** Key pressed, triggered once until released */ pressedDigit7: bool;\r /** Key pressed, triggered once until released */ pressedDigit8: bool;\r /** Key pressed, triggered once until released */ pressedDigit9: bool;\r /** Key pressed, triggered once until released */ pressedKeyA: bool;\r /** Key pressed, triggered once until released */ pressedKeyB: bool;\r /** Key pressed, triggered once until released */ pressedKeyC: bool;\r /** Key pressed, triggered once until released */ pressedKeyD: bool;\r /** Key pressed, triggered once until released */ pressedKeyE: bool;\r /** Key pressed, triggered once until released */ pressedKeyF: bool;\r /** Key pressed, triggered once until released */ pressedKeyG: bool;\r /** Key pressed, triggered once until released */ pressedKeyH: bool;\r /** Key pressed, triggered once until released */ pressedKeyI: bool;\r /** Key pressed, triggered once until released */ pressedKeyJ: bool;\r /** Key pressed, triggered once until released */ pressedKeyK: bool;\r /** Key pressed, triggered once until released */ pressedKeyL: bool;\r /** Key pressed, triggered once until released */ pressedKeyM: bool;\r /** Key pressed, triggered once until released */ pressedKeyN: bool;\r /** Key pressed, triggered once until released */ pressedKeyO: bool;\r /** Key pressed, triggered once until released */ pressedKeyP: bool;\r /** Key pressed, triggered once until released */ pressedKeyQ: bool;\r /** Key pressed, triggered once until released */ pressedKeyR: bool;\r /** Key pressed, triggered once until released */ pressedKeyS: bool;\r /** Key pressed, triggered once until released */ pressedKeyT: bool;\r /** Key pressed, triggered once until released */ pressedKeyU: bool;\r /** Key pressed, triggered once until released */ pressedKeyV: bool;\r /** Key pressed, triggered once until released */ pressedKeyW: bool;\r /** Key pressed, triggered once until released */ pressedKeyX: bool;\r /** Key pressed, triggered once until released */ pressedKeyY: bool;\r /** Key pressed, triggered once until released */ pressedKeyZ: bool;\r /** Key pressed, triggered once until released */ pressedMetaLeft: bool;\r /** Key pressed, triggered once until released */ pressedMetaRight: bool;\r /** Key pressed, triggered once until released */ pressedContextMenu: bool;\r /** Key pressed, triggered once until released */ pressedNumpad0: bool;\r /** Key pressed, triggered once until released */ pressedNumpad1: bool;\r /** Key pressed, triggered once until released */ pressedNumpad2: bool;\r /** Key pressed, triggered once until released */ pressedNumpad3: bool;\r /** Key pressed, triggered once until released */ pressedNumpad4: bool;\r /** Key pressed, triggered once until released */ pressedNumpad5: bool;\r /** Key pressed, triggered once until released */ pressedNumpad6: bool;\r /** Key pressed, triggered once until released */ pressedNumpad7: bool;\r /** Key pressed, triggered once until released */ pressedNumpad8: bool;\r /** Key pressed, triggered once until released */ pressedNumpad9: bool;\r /** Key pressed, triggered once until released */ pressedNumpadMultiply: bool;\r /** Key pressed, triggered once until released */ pressedNumpadAdd: bool;\r /** Key pressed, triggered once until released */ pressedNumpadSubtract: bool;\r /** Key pressed, triggered once until released */ pressedNumpadDecimal: bool;\r /** Key pressed, triggered once until released */ pressedNumpadDivide: bool;\r /** Key pressed, triggered once until released */ pressedF1: bool;\r /** Key pressed, triggered once until released */ pressedF2: bool;\r /** Key pressed, triggered once until released */ pressedF3: bool;\r /** Key pressed, triggered once until released */ pressedF4: bool;\r /** Key pressed, triggered once until released */ pressedF5: bool;\r /** Key pressed, triggered once until released */ pressedF6: bool;\r /** Key pressed, triggered once until released */ pressedF7: bool;\r /** Key pressed, triggered once until released */ pressedF8: bool;\r /** Key pressed, triggered once until released */ pressedF9: bool;\r /** Key pressed, triggered once until released */ pressedF10: bool;\r /** Key pressed, triggered once until released */ pressedF11: bool;\r /** Key pressed, triggered once until released */ pressedF12: bool;\r /** Key pressed, triggered once until released */ pressedNumLock: bool;\r /** Key pressed, triggered once until released */ pressedScrollLock: bool;\r /** Key pressed, triggered once until released */ pressedSemicolon: bool;\r /** Key pressed, triggered once until released */ pressedEqual: bool;\r /** Key pressed, triggered once until released */ pressedComma: bool;\r /** Key pressed, triggered once until released */ pressedMinus: bool;\r /** Key pressed, triggered once until released */ pressedPeriod: bool;\r /** Key pressed, triggered once until released */ pressedSlash: bool;\r /** Key pressed, triggered once until released */ pressedBackquote: bool;\r /** Key pressed, triggered once until released */ pressedBracketLeft: bool;\r /** Key pressed, triggered once until released */ pressedBackslash: bool;\r /** Key pressed, triggered once until released */ pressedBracketRight: bool;\r /** Key pressed, triggered once until released */ pressedQuote: bool;\r /** 2D vector that encodes the arrow keys and WASD aligned with the screen (e.g. up arrow = (0, -1)) */\r arrowVector: float2;\r }\r \r declare global {\r const env: FrameContext;\r }\r `; const buffer = "import { getValueSize } from '../engine/adapters/webgpu';\r\nimport { getShadeupLocalContext } from '/_std/context';\r\nimport {\r\n float4,\r\n float3,\r\n float,\r\n float2,\r\n bool,\r\n int,\r\n int2,\r\n int3,\r\n int4,\r\n uint,\r\n uint2,\r\n uint3,\r\n uint4,\r\n atomic,\r\n intifyVector\r\n} from '/std_math';\r\n\r\nlet __ = { intifyVector };\r\n\r\nexport class buffer_internal {\r\n __opaque_buffer: true = true;\r\n\r\n structArray: T[] | null = null;\r\n floatArray: Float32Array | null = null;\r\n intArray: Int32Array | null = null;\r\n uintArray: Uint32Array | null = null;\r\n arrayBuffer: ArrayBuffer | null = null;\r\n vectorSize: int = 0;\r\n typeName: string;\r\n\r\n platformPayload: any = null;\r\n adapter: any = null;\r\n\r\n dirty: boolean = false;\r\n pendingWrites: number = 0;\r\n cpuReadDirty: boolean = false;\r\n cpuWriteDirty: boolean = false;\r\n\r\n elementCount: int = 0;\r\n elementBytes: int = 0;\r\n structured: boolean = false;\r\n\r\n fastIndex: (index: int) => T;\r\n fastIndexAssign: (index: int, value: T) => void;\r\n\r\n destroy() {\r\n this.adapter.destroyBuffer(this);\r\n }\r\n\r\n [index: number]: T;\r\n\r\n __index(index: int | uint): T {\r\n // this.download();\r\n // return this.fastIndex(index);\r\n return null as any;\r\n }\r\n\r\n __index_assign(index: int | uint, value: T): void {\r\n // this.download();\r\n // this.cpuWriteDirty = true;\r\n // this.fastIndexAssign(index, value);\r\n }\r\n\r\n __index_assign_op(op_fn: (a: T, b: T) => T, index: int | uint, value: T): void {\r\n // this.download();\r\n // this.cpuWriteDirty = true;\r\n // this.fastIndexAssign(index, op_fn(this.fastIndex(index), value));\r\n }\r\n\r\n len() {\r\n return this.elementCount;\r\n }\r\n\r\n /**\r\n * Returns the underlying cpu buffer as a typed array.\r\n *\r\n * > [!NOTE]\r\n * > This is considerably faster than using the raw index [] operator.\r\n *\r\n * > [!NOTE]\r\n * > If the buffer contents are structured (atomic, or a struct), this will return a normal array\r\n *\r\n * ```shadeup\r\n * let buf = buffer();\r\n * let data = buf.getData();\r\n *\r\n * for (let i = 0; i < data.length; i += 4) {\r\n * // Do something with data[i]\r\n * }\r\n * ```\r\n */\r\n getData(): Uint32Array | Float32Array | Uint8Array | Int32Array | T[] {\r\n if (this.structured) {\r\n return this.structArray!;\r\n } else {\r\n return this.floatArray ?? this.intArray ?? this.uintArray ?? new Uint8Array(0);\r\n }\r\n }\r\n\r\n write(other: buffer_internal) {\r\n if (!this.adapter) return;\r\n\r\n this.adapter.copyBufferToBuffer(other, this);\r\n }\r\n\r\n watchMutation: boolean = false;\r\n\r\n /** @shadeup=tag(async) @shadeup=noemit_gpu */\r\n async download() {\r\n if (!this.adapter) return;\r\n\r\n if (this.pendingWrites > 0) {\r\n getShadeupLocalContext().flushAdapter();\r\n }\r\n\r\n if (this.cpuReadDirty) {\r\n this.cpuReadDirty = false;\r\n await this.adapter.downloadBuffer(this);\r\n }\r\n }\r\n\r\n downloadAsync(): Promise {\r\n return this['download']();\r\n }\r\n\r\n /** @shadeup=noemit_gpu */\r\n upload(): void {\r\n if (!this.adapter) return;\r\n\r\n if (this.cpuWriteDirty) {\r\n this.cpuWriteDirty = false;\r\n this.adapter.uploadBuffer(this);\r\n }\r\n }\r\n symbol: Symbol = Symbol();\r\n\r\n constructor(size: int, typeName: string, structure: any) {\r\n this.adapter = getShadeupLocalContext().shadeupGetGraphicsAdapter();\r\n this.typeName = typeName;\r\n if (structure) {\r\n if (structure.name && !structure.name.startsWith('atomic')) {\r\n this.typeName = structure.name;\r\n }\r\n }\r\n this.elementCount = size;\r\n this.elementBytes = 4;\r\n if (\r\n typeName == 'float4' ||\r\n typeName == 'float3' ||\r\n typeName == 'float2' ||\r\n typeName == 'float'\r\n ) {\r\n this.vectorSize = 1;\r\n\r\n this.fastIndex = (index: int) => {\r\n return this.floatArray![index] as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.floatArray![index] = value as float;\r\n };\r\n\r\n if (typeName == 'float4') {\r\n this.vectorSize = 4;\r\n\r\n this.fastIndex = (index: int) => {\r\n return float4(\r\n this.floatArray![index * 4],\r\n this.floatArray![index * 4 + 1],\r\n this.floatArray![index * 4 + 2],\r\n this.floatArray![index * 4 + 3]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: float4) => {\r\n this.floatArray![index * 4] = value[0];\r\n this.floatArray![index * 4 + 1] = value[1];\r\n this.floatArray![index * 4 + 2] = value[2];\r\n this.floatArray![index * 4 + 3] = value[3];\r\n };\r\n }\r\n\r\n if (typeName == 'float3') {\r\n this.vectorSize = 3;\r\n\r\n this.fastIndex = (index: int) => {\r\n return float3(\r\n this.floatArray![index * 3],\r\n this.floatArray![index * 3 + 1],\r\n this.floatArray![index * 3 + 2]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: float3) => {\r\n this.floatArray![index * 3] = value[0];\r\n this.floatArray![index * 3 + 1] = value[1];\r\n this.floatArray![index * 3 + 2] = value[2];\r\n };\r\n }\r\n if (typeName == 'float2') {\r\n this.vectorSize = 2;\r\n\r\n this.fastIndex = (index: int) => {\r\n return float2(this.floatArray![index * 2], this.floatArray![index * 2 + 1]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: float2) => {\r\n this.floatArray![index * 2] = value[0];\r\n this.floatArray![index * 2 + 1] = value[1];\r\n };\r\n }\r\n this.floatArray = new Float32Array(size * this.vectorSize);\r\n this.arrayBuffer = this.floatArray.buffer;\r\n } else if (\r\n typeName == 'int4' ||\r\n typeName == 'int3' ||\r\n typeName == 'int2' ||\r\n typeName == 'int'\r\n ) {\r\n this.vectorSize = 1;\r\n\r\n this.fastIndex = (index: int) => {\r\n return this.intArray![index] as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.intArray![index] = value as int;\r\n };\r\n\r\n if (typeName == 'int4') {\r\n this.vectorSize = 4;\r\n\r\n this.fastIndex = (index: int) => {\r\n return int4(\r\n this.intArray![index * 4],\r\n this.intArray![index * 4 + 1],\r\n this.intArray![index * 4 + 2],\r\n this.intArray![index * 4 + 3]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: int4) => {\r\n this.intArray![index * 4] = value[0];\r\n this.intArray![index * 4 + 1] = value[1];\r\n this.intArray![index * 4 + 2] = value[2];\r\n this.intArray![index * 4 + 3] = value[3];\r\n };\r\n }\r\n\r\n if (typeName == 'int3') {\r\n this.vectorSize = 3;\r\n\r\n this.fastIndex = (index: int) => {\r\n return int3(\r\n this.intArray![index * 3],\r\n this.intArray![index * 3 + 1],\r\n this.intArray![index * 3 + 2]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: int3) => {\r\n this.intArray![index * 3] = value[0];\r\n this.intArray![index * 3 + 1] = value[1];\r\n this.intArray![index * 3 + 2] = value[2];\r\n };\r\n }\r\n\r\n if (typeName == 'int2') {\r\n this.vectorSize = 2;\r\n\r\n this.fastIndex = (index: int) => {\r\n return int2(this.intArray![index * 2], this.intArray![index * 2 + 1]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: int2) => {\r\n this.intArray![index * 2] = value[0];\r\n this.intArray![index * 2 + 1] = value[1];\r\n };\r\n }\r\n\r\n this.intArray = new Int32Array(size * this.vectorSize);\r\n this.arrayBuffer = this.intArray.buffer;\r\n } else if (\r\n typeName == 'uint4' ||\r\n typeName == 'uint3' ||\r\n typeName == 'uint2' ||\r\n typeName == 'uint'\r\n ) {\r\n this.vectorSize = 1;\r\n\r\n this.fastIndex = (index: int) => {\r\n return this.uintArray![index] as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.uintArray![index] = value as uint;\r\n };\r\n\r\n if (typeName == 'uint4') {\r\n this.vectorSize = 4;\r\n\r\n this.fastIndex = (index: int) => {\r\n return uint4(\r\n this.uintArray![index * 4],\r\n this.uintArray![index * 4 + 1],\r\n this.uintArray![index * 4 + 2],\r\n this.uintArray![index * 4 + 3]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: uint4) => {\r\n this.uintArray![index * 4] = value[0];\r\n this.uintArray![index * 4 + 1] = value[1];\r\n this.uintArray![index * 4 + 2] = value[2];\r\n this.uintArray![index * 4 + 3] = value[3];\r\n };\r\n }\r\n\r\n if (typeName == 'uint3') {\r\n this.vectorSize = 3;\r\n\r\n this.fastIndex = (index: int) => {\r\n return uint3(\r\n this.uintArray![index * 3],\r\n this.uintArray![index * 3 + 1],\r\n this.uintArray![index * 3 + 2]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: uint3) => {\r\n this.uintArray![index * 3] = value[0];\r\n this.uintArray![index * 3 + 1] = value[1];\r\n this.uintArray![index * 3 + 2] = value[2];\r\n };\r\n }\r\n\r\n if (typeName == 'uint2') {\r\n this.vectorSize = 2;\r\n\r\n this.fastIndex = (index: int) => {\r\n return uint2(this.uintArray![index * 2], this.uintArray![index * 2 + 1]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: uint2) => {\r\n this.uintArray![index * 2] = value[0];\r\n this.uintArray![index * 2 + 1] = value[1];\r\n };\r\n }\r\n\r\n this.uintArray = new Uint32Array(size * this.vectorSize);\r\n this.arrayBuffer = this.uintArray.buffer;\r\n } else {\r\n this.structured = true;\r\n\r\n if (typeName.startsWith('atomic<')) {\r\n // this.structArray = new Array(size);\r\n this.arrayBuffer = new ArrayBuffer(size * 4);\r\n\r\n this.watchMutation = true;\r\n this.vectorSize = 1;\r\n this.elementBytes = 4;\r\n this.elementCount = size;\r\n for (let i = 0; i < size; i++) {\r\n // this.structArray[i] = atomic(0) as T;\r\n }\r\n if (typeName == 'atomic') {\r\n this.uintArray = new Uint32Array(this.arrayBuffer);\r\n this.fastIndex = (index: int) => {\r\n return atomic(this.uintArray![index]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.uintArray![index] = value.__value as any;\r\n };\r\n } else {\r\n this.intArray = new Int32Array(this.arrayBuffer);\r\n this.fastIndex = (index: int) => {\r\n return atomic(this.intArray![index]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.intArray![index] = value.__value as any;\r\n };\r\n }\r\n } else {\r\n let elementSize = this.adapter.getValueSize(structure);\r\n let realSize = elementSize * size;\r\n this.elementCount = size;\r\n this.elementBytes = elementSize;\r\n this.arrayBuffer = new ArrayBuffer(realSize);\r\n\r\n this.fastIndex = (index: int) => {\r\n return this.adapter.readStructuredBuffer(\r\n structure,\r\n this.arrayBuffer,\r\n index * elementSize\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.cpuWriteDirty = true;\r\n this.adapter.writeStructuredBuffer(\r\n structure,\r\n value,\r\n this.arrayBuffer,\r\n index * (elementSize / 4)\r\n );\r\n };\r\n }\r\n }\r\n\r\n (this.__index as any) = (index: int): T => {\r\n // await this.download();\r\n if (this.watchMutation) {\r\n let data = this.fastIndex(index);\r\n (data as any).$mutate = (to?: T) => {\r\n this.cpuWriteDirty = true;\r\n if (to !== undefined) {\r\n if (this.intArray) {\r\n this.intArray[index] = to as any;\r\n } else {\r\n this.uintArray![index] = to as any;\r\n }\r\n }\r\n };\r\n return data;\r\n } else {\r\n return this.fastIndex(index);\r\n }\r\n };\r\n\r\n this.__index_assign = (index: int, value: T): void => {\r\n // await this.download();\r\n this.cpuWriteDirty = true;\r\n this.fastIndexAssign(index, value);\r\n };\r\n\r\n this.__index_assign_op = (op_fn: (a: T, b: T) => T, index: int, value: T): void => {\r\n // await this.download();\r\n this.cpuWriteDirty = true;\r\n\r\n this.fastIndexAssign(index, op_fn(this.fastIndex(index), value));\r\n };\r\n }\r\n}\r\n\r\nexport type buffer = buffer_internal;\r\n\r\n/**\r\n * Creates a new buffer.\r\n * ```shadeup\r\n * let buf = buffer(100);\r\n *\r\n * ```\r\n */\r\nexport function buffer(data: T[], typeName: string, structure?: object): buffer;\r\nexport function buffer(size: int, typeName: string, structure?: object): buffer;\r\nexport function buffer(e1: any, typeName: string, structure?: object): buffer {\r\n if (typeof e1 === 'number') {\r\n let size = e1;\r\n let buf = new buffer_internal(size, typeName, structure!);\r\n return buf;\r\n } else {\r\n let data = e1;\r\n let buf = new buffer_internal(data.length, typeName, structure!);\r\n for (let i = 0; i < data.length; i++) {\r\n buf.fastIndexAssign(i, data[i]);\r\n }\r\n return buf;\r\n }\r\n}\r\n"; const texture = "import {\r\n float4,\r\n float3,\r\n float,\r\n float2,\r\n bool,\r\n int,\r\n int2,\r\n int3,\r\n int4,\r\n uint,\r\n uint2,\r\n uint3,\r\n uint4,\r\n uint8\r\n} from '/std_math';\r\n\r\nimport {\r\n ShaderInput,\r\n ShaderOutput,\r\n shader,\r\n draw,\r\n drawInstanced,\r\n drawAdvanced,\r\n drawIndexed\r\n} from '/_std/drawIndexed';\r\n\r\nimport { Mesh } from '/_std/mesh';\r\nimport { PaintingContext } from '/_std/paint';\r\nimport { getShadeupLocalContext } from '/_std/context';\r\n\r\nexport class texture2d_internal_empty {\r\n __opaque_texture2d: true = true;\r\n\r\n /** @shadeup=glsl(!texture($self$, $0$)) */\r\n __index(index: int2 | uint2): T {\r\n return null as any;\r\n }\r\n\r\n __index_assign(index: int2 | uint2, value: T): void {\r\n return null as any;\r\n }\r\n\r\n getFast(index: int2 | uint2): T {\r\n return null as any;\r\n }\r\n\r\n setFast(index: int2 | uint2, value: T): void {\r\n return null as any;\r\n }\r\n\r\n /** @shadeup=tag(async) */\r\n download(): void {}\r\n\r\n downloadAsync(): Promise {\r\n return null as any;\r\n }\r\n\r\n /**\r\n * Returns the underlying cpu buffer as a typed array.\r\n *\r\n * Note that this is considerably faster than using the raw index [] operator.\r\n *\r\n * ```shadeup\r\n * let tex = texture2d();\r\n * let data = tex.getData();\r\n *\r\n * for (let i = 0; i < data.length; i += 4) {\r\n * let r = data[i];\r\n * let g = data[i + 1];\r\n * let b = data[i + 2];\r\n * let a = data[i + 3];\r\n *\r\n * // Do something with the pixel\r\n * }\r\n * ```\r\n */\r\n getData(): Uint32Array | Float32Array | Uint8Array | Int32Array {\r\n return new Uint32Array(0);\r\n }\r\n\r\n upload(): void {}\r\n\r\n size: float2 = [0, 0];\r\n\r\n paint: PaintingContext = null as any;\r\n\r\n sample(position: float2): float4 {}\r\n\r\n clear(color: float | float4 | 'auto' = 'auto'): void {}\r\n flush(): void {}\r\n // draw(\r\n // geometry: Mesh,\r\n // vertexShader: shader,\r\n // pixelShader: shader\r\n // ): void;\r\n // draw(fullScreenPixelShader: shader): void;\r\n // draw() {\r\n // throw new Error('Not implemented');\r\n // }\r\n\r\n draw: typeof draw;\r\n\r\n drawIndexed: typeof drawIndexed;\r\n drawAdvanced: typeof drawAdvanced;\r\n drawInstanced: typeof drawInstanced;\r\n\r\n /** Release the texture */\r\n destroy() {}\r\n}\r\n\r\nexport type texture2d = texture2d_internal_empty;\r\nexport type TextureFormat = '32bit' | '16bit' | '8bit' | 'depth' | 'depth-32' | 'auto';\r\nexport function texture2d(\r\n size: float2,\r\n format: TextureFormat,\r\n type: string\r\n): texture2d {\r\n return getShadeupLocalContext().shadeupMakeTextureInternal(size, format, type) as texture2d;\r\n}\r\n\r\nexport class texture3d_internal_empty {\r\n __opaque_texture3d: true = true;\r\n\r\n /** @shadeup=glsl(!texture($self$, $0$)) */\r\n __index(index: int3): T {\r\n return null as any;\r\n }\r\n __index_assign(index: int3, value: T): void {}\r\n size: float3 = [0, 0, 0];\r\n\r\n sample(position: float3): float4 {}\r\n}\r\n\r\nexport type texture3d = texture3d_internal_empty;\r\n\r\nexport function texture3d(size: float3, type: string): texture3d {\r\n return getShadeupLocalContext().shadeupMakeTextureInternal(size, type) as texture3d;\r\n}\r\n"; const physics = "import type RAPIER2DNamespace from '@dimforge/rapier2d/rapier';\r\nimport type RAPIER3DNamespace from '@dimforge/rapier3d/rapier';\r\nimport type { float, float2, float3 } from './types';\r\n\r\ntype RAPIER2D = typeof RAPIER2DNamespace;\r\n\r\nexport class PhysicsCollider2d {\r\n rapier: RAPIER2D;\r\n world: RAPIER2DNamespace.World;\r\n collider: RAPIER2DNamespace.Collider;\r\n\r\n constructor(\r\n rapier: RAPIER2D,\r\n world: RAPIER2DNamespace.World,\r\n collider: RAPIER2DNamespace.Collider\r\n ) {\r\n this.rapier = rapier;\r\n this.world = world;\r\n this.collider = collider;\r\n }\r\n\r\n setTranslation(position: float2) {\r\n this.collider.setTranslation(toVec2(position));\r\n }\r\n\r\n setRotation(rotation: float) {\r\n this.collider.setRotation(rotation);\r\n }\r\n\r\n setSensor(isSensor: boolean) {\r\n this.collider.setSensor(isSensor);\r\n }\r\n\r\n setCollisionGroups(groups: int) {\r\n this.collider.setCollisionGroups(groups);\r\n }\r\n\r\n setCollidesWith(groups: int) {\r\n this.collider.setActiveCollisionTypes(groups);\r\n }\r\n\r\n setFriction(friction: float) {\r\n this.collider.setFriction(friction);\r\n }\r\n\r\n setRestitution(restitution: float) {\r\n this.collider.setRestitution(restitution);\r\n }\r\n\r\n setDensity(density: float) {\r\n this.collider.setDensity(density);\r\n }\r\n\r\n setMass(mass: float) {\r\n this.collider.setMass(mass);\r\n }\r\n\r\n setRadius(radius: float) {\r\n this.collider.setRadius(radius);\r\n }\r\n\r\n setHalfExtents(halfExtents: float2) {\r\n this.collider.setHalfExtents(toVec2(halfExtents));\r\n }\r\n}\r\nfunction toVec2(v: float2): RAPIER2DNamespace.Vector2 {\r\n return { x: v[0], y: v[1] };\r\n}\r\n\r\nfunction toVec3(v: float3): RAPIER3DNamespace.Vector {\r\n return { x: v[0], y: v[1], z: v[2] };\r\n}\r\n\r\nexport class PhysicsRayCastResult2d {\r\n rapier: RAPIER2D;\r\n result: RAPIER2DNamespace.RayIntersection;\r\n\r\n constructor(rapier: RAPIER2D, result: RAPIER2DNamespace.RayIntersection) {\r\n this.rapier = rapier;\r\n this.result = result;\r\n }\r\n}\r\n\r\nexport class PhysicsRigidBody2d {\r\n rapier: RAPIER2D;\r\n world: RAPIER2DNamespace.World;\r\n body: RAPIER2DNamespace.RigidBody;\r\n\r\n constructor(rapier: RAPIER2D, world: RAPIER2DNamespace.World, body: RAPIER2DNamespace.RigidBody) {\r\n this.rapier = rapier;\r\n this.world = world;\r\n this.body = body;\r\n }\r\n\r\n addBallCollider(radius: float): PhysicsCollider2d {\r\n let colDesc = this.rapier.ColliderDesc.ball(radius);\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addBoxCollider(halfExtents: float2): PhysicsCollider2d {\r\n let colDesc = this.rapier.ColliderDesc.cuboid(halfExtents[0], halfExtents[1]);\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addCapsuleCollider(radius: float, halfHeight: float): PhysicsCollider2d {\r\n let colDesc = this.rapier.ColliderDesc.capsule(radius, halfHeight);\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addTriangleCollider(a: float2, b: float2, c: float2): PhysicsCollider2d {\r\n let colDesc = this.rapier.ColliderDesc.triangle(toVec2(a), toVec2(b), toVec2(c));\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addConvexCollider(points: float2[]): PhysicsCollider2d {\r\n let floatarr = new Float32Array(points.length * 2);\r\n for (let i = 0; i < points.length; i++) {\r\n floatarr[i * 2 + 0] = points[i][0];\r\n floatarr[i * 2 + 1] = points[i][1];\r\n }\r\n let colDesc = this.rapier.ColliderDesc.convexHull(floatarr);\r\n if (!colDesc) throw new Error('Failed to create convex hull collider');\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addHeightfieldCollider(heights: float[], scale: float2): PhysicsCollider2d {\r\n let arr = new Float32Array(heights.length);\r\n for (let i = 0; i < heights.length; i++) {\r\n arr[i] = heights[i];\r\n }\r\n let colDesc = this.rapier.ColliderDesc.heightfield(arr, toVec2(scale));\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n setTranslation(position: float2) {\r\n this.body.setTranslation(toVec2(position), true);\r\n }\r\n\r\n setRotation(rotation: float) {\r\n this.body.setRotation(rotation, true);\r\n }\r\n\r\n setVelocity(velocity: float2) {\r\n this.body.setLinvel(toVec2(velocity), true);\r\n }\r\n\r\n setAngularVelocity(velocity: float) {\r\n this.body.setAngvel(velocity, true);\r\n }\r\n\r\n addForce(force: float2) {\r\n this.body.addForce(toVec2(force), true);\r\n }\r\n\r\n addForceAtPoint(force: float2, point: float2) {\r\n this.body.addForceAtPoint(toVec2(force), toVec2(point), true);\r\n }\r\n\r\n addTorque(torque: float) {\r\n this.body.addTorque(torque, true);\r\n }\r\n\r\n setAdditionalMass(mass: float) {\r\n this.body.setAdditionalMass(mass, true);\r\n }\r\n\r\n setEnabled(enabled: boolean) {\r\n this.body.setEnabled(enabled);\r\n }\r\n\r\n sleep() {\r\n this.body.sleep();\r\n }\r\n\r\n wakeUp() {\r\n this.body.wakeUp();\r\n }\r\n\r\n setGravityScale(scale: float) {\r\n this.body.setGravityScale(scale, true);\r\n }\r\n\r\n setLinearDamping(damping: float) {\r\n this.body.setLinearDamping(damping);\r\n }\r\n\r\n setAngularDamping(damping: float) {\r\n this.body.setAngularDamping(damping);\r\n }\r\n\r\n isSleeping(): boolean {\r\n return this.body.isSleeping();\r\n }\r\n\r\n mass(): float {\r\n return this.body.mass() as float;\r\n }\r\n\r\n translation(): float2 {\r\n let t = this.body.translation();\r\n return [t.x as float, t.y as float];\r\n }\r\n\r\n rotation(): float {\r\n return this.body.rotation() as float;\r\n }\r\n\r\n velocity(): float2 {\r\n let t = this.body.linvel();\r\n return [t.x as float, t.y as float];\r\n }\r\n\r\n angularVelocity(): float {\r\n return this.body.angvel() as float;\r\n }\r\n\r\n isMoving(): boolean {\r\n return this.body.isMoving();\r\n }\r\n\r\n collider(index: int): PhysicsCollider2d {\r\n let collider = this.body.collider(index);\r\n if (!collider) throw new Error('Failed to get collider');\r\n return new PhysicsCollider2d(this.rapier, this.world, collider);\r\n }\r\n\r\n applyImpulse(impulse: float2) {\r\n this.body.applyImpulse(toVec2(impulse), true);\r\n }\r\n\r\n applyTorqueImpulse(impulse: float) {\r\n this.body.applyTorqueImpulse(impulse, true);\r\n }\r\n}\r\n\r\nexport class PhysicsEngine2d {\r\n rapier: RAPIER2D;\r\n world: RAPIER2DNamespace.World;\r\n constructor(rapier: RAPIER2D) {\r\n this.rapier = rapier;\r\n this.world = new rapier.World(new rapier.Vector2(0.0, -9.81));\r\n }\r\n\r\n step() {\r\n this.world.step();\r\n }\r\n\r\n createRigidBody(\r\n position: float2,\r\n rotation: float,\r\n mode: 'dynamic' | 'fixed'\r\n ): PhysicsRigidBody2d {\r\n let rbDesc =\r\n mode == 'dynamic'\r\n ? this.rapier.RigidBodyDesc.dynamic()\r\n : mode == 'fixed'\r\n ? this.rapier.RigidBodyDesc.fixed()\r\n : this.rapier.RigidBodyDesc.dynamic();\r\n rbDesc.setTranslation(position[0], position[1]);\r\n rbDesc.setRotation(rotation);\r\n let rb = this.world.createRigidBody(rbDesc);\r\n\r\n return new PhysicsRigidBody2d(this.rapier, this.world, rb);\r\n }\r\n\r\n bodies(): PhysicsRigidBody2d[] {\r\n let bodies = this.world.bodies;\r\n let result: PhysicsRigidBody2d[] = [];\r\n for (let i = 0; i < bodies.len(); i++) {\r\n result.push(new PhysicsRigidBody2d(this.rapier, this.world, bodies.get(i)!));\r\n }\r\n return result;\r\n }\r\n\r\n castRay(start: float2, end: float2, maxi: int): PhysicsRigidBody2d | null {\r\n let result = this.world.castRay(new this.rapier.Ray(toVec2(start), toVec2(end)), maxi, true);\r\n if (!result) return null;\r\n return new PhysicsRigidBody2d(this.rapier, this.world, result.collider.parent()!);\r\n }\r\n\r\n setGravity(gravity: float2) {\r\n this.world.gravity = toVec2(gravity);\r\n }\r\n}\r\n\r\nexport class PhysicsEngine3d {\r\n constructor() {}\r\n}\r\n\r\nexport namespace physics {\r\n export function engine2d(): PhysicsEngine2d {\r\n return new PhysicsEngine2d((window as any).RAPIER_2D);\r\n }\r\n}\r\n"; const context = "declare global {\r\n const localEngineContext: any;\r\n}\r\nexport const getShadeupLocalContext = (): any => {\r\n if (typeof localEngineContext !== 'undefined') {\r\n return localEngineContext;\r\n } else {\r\n return window;\r\n }\r\n};\r\n"; const drawIndexed = "import { getShadeupLocalContext } from '/_std/context';\r\nimport { buffer } from '/_std/buffer';\r\nimport { Mesh } from '/_std/mesh';\r\nimport { texture2d } from '/_std/texture';\r\nimport { float4, float3, float, float2, bool, int, uint, atomic, int3 } from '/std_math';\r\n\r\nexport function drawIndexed(\r\n indexBuffer: buffer,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_indexed(indexBuffer, vertexShader, pixelShader);\r\n}\r\n\r\nexport function drawInstanced(\r\n mesh: Mesh,\r\n instanceCount: int,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_instanced(\r\n mesh,\r\n instanceCount,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n\r\nexport function drawInstancedIndexed(\r\n indexBuffer: buffer,\r\n instanceCount: int,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_instanced_indexed(\r\n indexBuffer,\r\n instanceCount,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n\r\nexport function drawIndexedIndirect(\r\n indirectBuffer: buffer | buffer>,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_indexed_indirect(\r\n indirectBuffer,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n\r\nexport function drawIndirect(\r\n mesh: Mesh,\r\n indirectBuffer: buffer | buffer>,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_indirect(\r\n mesh,\r\n indirectBuffer,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n\r\nexport function shader_start_shd_(\r\n s: shader,\r\n groupSize?: any\r\n): shader {\r\n return s;\r\n}\r\n\r\nexport type shader = (\r\n __in: Omit\r\n) => T_OUT;\r\ndeclare global {\r\n // function __shadeup_make_shader_inst(\r\n // key: string,\r\n // params: any,\r\n // closure: any\r\n // ): shader;\r\n // function __shadeup_dispatch_draw(fullScreenPixelShader: shader): void;\r\n // function __shadeup_dispatch_draw_geometry(\r\n // geometry: Mesh,\r\n // vertexShader: shader,\r\n // pixelShader: shader\r\n // ): void;\r\n\r\n interface Array {\r\n [index: int]: T;\r\n }\r\n\r\n let window: {\r\n [index: string]: any;\r\n };\r\n}\r\n\r\n/**@shadeup=struct*/\r\nexport class ShaderInput {\r\n /** Interpolated world position (available in fragment, and vertex) */\r\n position: float3 = float3(0, 0, 0);\r\n\r\n /** Interpolated normal (fragment), Source mesh normal (vertex) */\r\n normal: float3 = float3(0, 0, 0);\r\n\r\n /** Interpolated tangent (fragment), Source mesh tangent (vertex) */\r\n tangent: float3 = float3(0, 0, 0);\r\n\r\n /** Interpolated bitangent (fragment), Source mesh bitangent (vertex) */\r\n bitangent: float3 = float3(0, 0, 0);\r\n\r\n /** Vertex shader output position */\r\n clipPosition: float4 = float4(0, 0, 0, 0);\r\n\r\n realPosition: float4 = float4(0, 0, 0, 0);\r\n\r\n /** UV channel 0 input (available in fragment, and vertex) */\r\n uv: float2 = float2(0, 0);\r\n\r\n /** Screen position in pixels (available in fragment, and vertex) */\r\n screen: float2 = float2(0, 0);\r\n\r\n /** Interpolated vertex color (available in fragment, and vertex) */\r\n color: float4 = float4(0, 0, 0, 0);\r\n\r\n /** Group ID (available in compute) */\r\n groupId: int3 = int3(0, 0, 0);\r\n\r\n /** Group size (available in compute) */\r\n groupSize: int3 = int3(0, 0, 0);\r\n\r\n /** Global id (groupId * groupSize + localId) (available in compute) */\r\n globalId: int3 = int3(0, 0, 0);\r\n\r\n /** Local id (available in compute) */\r\n localId: int3 = int3(0, 0, 0);\r\n\r\n /** Instance index (available in fragment, and vertex) */\r\n instanceIndex: int = 0;\r\n\r\n /** Vertex index (available in vertex) */\r\n vertexIndex: int = 0;\r\n\r\n /** @shadeup=noemit_gpu */\r\n attr(index: int, interpolation?: 'flat' | 'linear' | 'perspective'): T {\r\n return null as any;\r\n }\r\n}\r\n\r\n/**@shadeup=struct*/\r\nexport class ShaderOutput {\r\n /** Vertex output position */\r\n position: float4 = float4(0, 0, 0, 0);\r\n\r\n /** Vertex output normal */\r\n normal: float3 = float3(0, 0, 0);\r\n\r\n /** Vertex output tangent */\r\n tangent: float3 = float3(0, 0, 0);\r\n\r\n /** Vertex output bitangent */\r\n bitangent: float3 = float3(0, 0, 0);\r\n\r\n /** UV channel 0 output */\r\n uv: float2 = float2(0, 0);\r\n\r\n /** Pixel color output */\r\n color: float4 = float4(0, 0, 0, 0);\r\n\r\n /** @shadeup=noemit_gpu */\r\n attr(index: int, value: T, interpolation?: 'flat' | 'linear' | 'perspective') {}\r\n}\r\n\r\n/** @shadeup=shader */\r\nexport function makeShader(\r\n key: string,\r\n fn: (__in: I, __out: O) => void\r\n): shader {\r\n return fn as shader;\r\n}\r\n\r\ntype AttachmentBindings1 = {\r\n attachments: [texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings2 = {\r\n attachments: [texture2d, texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings3 = {\r\n attachments: [texture2d, texture2d, texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings4 = {\r\n attachments: [texture2d, texture2d, texture2d, texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings5 = {\r\n attachments: [texture2d, texture2d, texture2d, texture2d, texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n attachment4: A4;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings6 = {\r\n attachments: [\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d\r\n ];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n attachment4: A4;\r\n attachment5: A5;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings7 = {\r\n attachments: [\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d\r\n ];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n attachment4: A4;\r\n attachment5: A5;\r\n attachment6: A6;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings8 = {\r\n attachments: [\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d\r\n ];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n attachment4: A4;\r\n attachment5: A5;\r\n attachment6: A6;\r\n attachment7: A7;\r\n }\r\n >;\r\n};\r\n\r\ntype DrawDescriptorBase = (\r\n | {\r\n mesh: Mesh;\r\n }\r\n | {\r\n indexBuffer: buffer;\r\n }\r\n | {}\r\n) & {\r\n indirect?: buffer | buffer>;\r\n indirectOffset?: int | uint;\r\n depth?: texture2d;\r\n depthOnly?: boolean;\r\n depthTest?: boolean;\r\n depthCompare?:\r\n | 'greater'\r\n | 'less'\r\n | 'equal'\r\n | 'greater_equal'\r\n | 'less_equal'\r\n | 'not_equal'\r\n | 'always'\r\n | 'never';\r\n backfaceCulling?: boolean;\r\n instances?: int;\r\n};\r\n\r\n/**\r\n * Normal:\r\n * ```shadeup\r\n * drawAdvanced({\r\n * mesh: mesh::box(0.xyz, 100.xyz),\r\n * vertex: shader {\r\n * // ...\r\n * },\r\n * fragment: shader {\r\n * // ...\r\n * },\r\n * });\r\n * ```\r\n *\r\n * Instancing:\r\n * ```shadeup\r\n * drawAdvanced({\r\n * mesh: mesh::box(0.xyz, 100.xyz),\r\n * vertex: shader {\r\n * in.instanceIndex;\r\n * },\r\n * fragment: shader {\r\n * // ...\r\n * },\r\n * instances: 100,\r\n * });\r\n * ```\r\n *\r\n * Indirect:\r\n * ```shadeup\r\n * let mesh = mesh::box(0.xyz, 100.xyz);\r\n *\r\n * let indirectBuffer = buffer(5);\r\n * indirectBuffer[0] = uint(m.getTriangles().len()); // indexCount\r\n * indirectBuffer[1] = 1; // instanceCount\r\n * indirectBuffer[2] = 0; // firstIndex\r\n * indirectBuffer[3] = 0; // vertexOffset\r\n * indirectBuffer[4] = 0; // firstInstance\r\n *\r\n * drawAdvanced({\r\n * mesh: mesh::box(0.xyz, 100.xyz),\r\n * vertex: shader {\r\n * // ...\r\n * },\r\n * fragment: shader {\r\n * // ...\r\n * },\r\n * indirect: indirectBuffer,\r\n * });\r\n * ```\r\n *\r\n * Attachments:\r\n * ```shadeup\r\n * let mesh = mesh::box(0.xyz, 100.xyz);\r\n * let color = texture2d(100.xy);\r\n * let normal = texture2d(100.xy);\r\n * let depth = texture2d(100.xy, \"depth\");\r\n *\r\n * drawAdvanced({\r\n * mesh: mesh,\r\n * vertex: shader {\r\n * // ...\r\n * },\r\n * fragment: shader {\r\n * out.attachment0 = float4(1, 0, 0, 1);\r\n * out.attachment1 = float3(0, 0, 1);\r\n * },\r\n * depth: depth, // Override depth buffer\r\n * attachments: [color, normal],\r\n * });\r\n */\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings8\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings7\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings6\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings5\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings4\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings3\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings2\r\n): void;\r\nexport function drawAdvanced(descriptor: DrawDescriptorBase & AttachmentBindings1): void;\r\n\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & {\r\n vertex: shader;\r\n fragment: shader;\r\n }\r\n): void;\r\nexport function drawAdvanced(descriptor: any): void {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_advanced(descriptor);\r\n}\r\n\r\nexport function draw(\r\n geometry: Mesh,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n): void;\r\nexport function draw(fullScreenPixelShader: shader): void;\r\nexport function draw(\r\n first: Mesh | DrawDescriptorBase | shader,\r\n second?: shader | number,\r\n third?: shader\r\n) {\r\n if ('vertices' in first && second && third) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_geometry(first, second, third);\r\n } else if (first && !second && !third) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw(first as shader);\r\n }\r\n}\r\n\r\nexport function drawFullscreen(fullScreenPixelShader: shader): void;\r\nexport function drawFullscreen(\r\n first: Mesh | any | shader,\r\n second?: shader,\r\n third?: shader\r\n) {\r\n if ('vertices' in first && second && third) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_geometry(first, second, third);\r\n } else if (first && !second && !third) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw(first as shader);\r\n }\r\n}\r\n\r\nexport function drawAlt2(fullScreenPixelShader: shader): void {}\r\n\r\nexport function drawCount(\r\n triCount: number,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader);\r\n}\r\n\r\nexport function drawAttributes(\r\n indexBuffer: buffer,\r\n buffers:\r\n | Map>\r\n | {\r\n [key in keyof T]: buffer;\r\n },\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_attributes(\r\n indexBuffer,\r\n buffer,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\nexport function computeIndirect(\r\n indirectBuffer: buffer | buffer>,\r\n indirectOffset: int,\r\n computeShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_compute_indirect(\r\n indirectBuffer,\r\n indirectOffset,\r\n computeShader\r\n );\r\n}\r\n"; const drawCount = "import { getShadeupLocalContext } from '/_std/context';\r\nimport { buffer } from '/_std/buffer';\r\nimport { float4, float3, float, float2, bool, int, uint } from '/std_math';\r\n\r\nexport function drawCount(triCount: number, vertexShader: shader, pixelShader: shader) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader);\r\n}\r\n"; const drawAttributes = "import { getShadeupLocalContext } from '/_std/context';\r\nimport { buffer } from '/_std/buffer';\r\nimport { float4, float3, float, float2, bool, int, uint } from '/std_math';\r\n\r\nexport function drawAttributes(\r\n indexBuffer: buffer,\r\n buffers:\r\n | Map>\r\n | {\r\n [key in keyof T]: buffer;\r\n },\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_attributes(\r\n indexBuffer,\r\n buffer,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n"; const paint = "type GraphicsAdapter = {\r\n drawImage(image: HTMLCanvasElement): void;\r\n addEventListener(name: string, fn: (...args: any) => void): void;\r\n activatePaintContext(): void;\r\n};\r\nimport type { float4, float2 } from './types';\r\n\r\nexport class PaintingContext {\r\n markDirtyCallback: () => void = () => {};\r\n constructor(canvas: HTMLCanvasElement, gl: GraphicsAdapter | null) {\r\n if (!gl) return;\r\n this.__gl = gl;\r\n this.__canvas = canvas;\r\n this.__offscreen_canvas = document.createElement('canvas');\r\n this.__offscreen_canvas.width = canvas.width;\r\n this.__offscreen_canvas.height = canvas.height;\r\n // document.body.appendChild(this.__offscreen_canvas);\r\n this.__ctx = this.__offscreen_canvas.getContext('2d', {\r\n willReadFrequently: true\r\n })!;\r\n this.__offscreen_canvas.style.position = 'absolute';\r\n this.__offscreen_canvas.style.zIndex = '10';\r\n // document.body.appendChild(this.__offscreen_canvas);\r\n this.__setColor([0, 0, 0, 1] as float4);\r\n\r\n gl.addEventListener('context', (toContext: string) => {\r\n if (toContext == 'draw') {\r\n this.flush();\r\n }\r\n });\r\n\r\n gl.addEventListener('flush', () => {\r\n this.flush();\r\n });\r\n }\r\n\r\n flush() {\r\n if (!this.__gl) return;\r\n if (!this.__canvas) return;\r\n if (!this.__offscreen_canvas) return;\r\n\r\n if (!this.stagedChanges) return;\r\n\r\n if (this.fastPoints) this.flushPoints();\r\n\r\n this.__gl.drawImage(this.__offscreen_canvas);\r\n this.stagedChanges = false;\r\n\r\n if (\r\n this.__offscreen_canvas.width != this.__canvas.width ||\r\n this.__offscreen_canvas.height != this.__canvas.height\r\n ) {\r\n this.__offscreen_canvas.width = this.__canvas.width;\r\n this.__offscreen_canvas.height = this.__canvas.height;\r\n }\r\n\r\n this.pointsCounter = 0;\r\n }\r\n\r\n private __ctx: CanvasRenderingContext2D | null = null;\r\n private __gl: GraphicsAdapter | null = null;\r\n private __offscreen_canvas: HTMLCanvasElement | null = null;\r\n\r\n private __program: WebGLProgram | null = null;\r\n\r\n private stagedChanges: boolean = false;\r\n private dirty: boolean = false;\r\n\r\n private fastPoints: boolean = false;\r\n private fastPointsBuffer: ImageData | null = null;\r\n\r\n private __beforeDraw() {\r\n if (!this.__offscreen_canvas) return;\r\n if (!this.__ctx) return;\r\n if (!this.__canvas) return;\r\n this.markDirtyCallback();\r\n this.__gl?.activatePaintContext();\r\n\r\n if (!this.stagedChanges) {\r\n this.__ctx.clearRect(0, 0, this.__canvas.width, this.__canvas.height);\r\n\r\n this.__ctx.drawImage(this.__canvas, 0, 0);\r\n\r\n let color = this.__currentColor;\r\n this.__ctx.fillStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n this.__ctx.strokeStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n }\r\n }\r\n\r\n private __afterDraw() {\r\n let gl = this.__gl;\r\n this.dirty = true;\r\n this.stagedChanges = true;\r\n }\r\n\r\n private __currentColor: number[] | null = null;\r\n private __setColor(color?: float4) {\r\n if (!this.__ctx || !color) return;\r\n\r\n if (\r\n this.__currentColor &&\r\n this.__currentColor[0] == color[0] &&\r\n this.__currentColor[1] == color[1] &&\r\n this.__currentColor[2] == color[2] &&\r\n this.__currentColor[3] == color[3]\r\n )\r\n return;\r\n\r\n this.__ctx.strokeStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n this.__ctx.fillStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n\r\n this.__currentColor = [color[0], color[1], color[2], color[3]];\r\n }\r\n\r\n fillRect(pos: float2, size: float2, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.fillRect(pos[0], pos[1], size[0], size[1]);\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n fillCircle(pos: float2, radius: number, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2);\r\n this.__ctx.fill();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n fillArc(pos: float2, radius: number, startAngle: number, endAngle: number, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle);\r\n this.__ctx.fill();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n line(pos1: float2, pos2: float2, color?: float4, width: number = 1) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.moveTo(pos1[0], pos1[1]);\r\n\r\n this.__ctx.lineTo(pos2[0], pos2[1]);\r\n this.__ctx.lineWidth = width;\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n circle(pos: float2, radius: number, color?: float4, width: number = 1) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2);\r\n this.__ctx.lineWidth = width;\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n arc(\r\n pos: float2,\r\n radius: number,\r\n startAngle: number,\r\n endAngle: number,\r\n color?: float4,\r\n width: number = 1\r\n ) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle);\r\n this.__ctx.lineWidth = width;\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n text(pos: float2, text: string, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.fillText(text, pos[0], pos[1]);\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n startPath(pos: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__ctx.beginPath();\r\n this.__ctx.moveTo(pos[0], pos[1]);\r\n }\r\n\r\n lineTo(pos: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineTo(pos[0], pos[1]);\r\n }\r\n\r\n strokePath(color?: float4, width: number = 1) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineWidth = width;\r\n this.__setColor(color);\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n fillPath(color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.__setColor(color);\r\n this.__ctx.fill();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n setStrokeWidth(width: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineWidth = width;\r\n }\r\n\r\n setFont(font: string) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.font = font;\r\n }\r\n\r\n setFontSize(size: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.font = `${size}px ${this.__ctx.font.split(' ').slice(1).join(' ')}`;\r\n }\r\n\r\n setTextAlign(align: CanvasTextAlign) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.textAlign = align;\r\n }\r\n\r\n setTextBaseline(baseline: CanvasTextBaseline) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.textBaseline = baseline;\r\n }\r\n\r\n setLineCap(cap: 'butt' | 'round' | 'square') {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineCap = cap;\r\n }\r\n\r\n setLineJoin(join: CanvasLineJoin) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineJoin = join;\r\n }\r\n\r\n setMiterLimit(limit: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.miterLimit = limit;\r\n }\r\n\r\n setShadowColor(color: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.shadowColor = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n }\r\n\r\n setShadowBlur(blur: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.shadowBlur = blur;\r\n }\r\n\r\n setShadowOffset(offset: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.shadowOffsetX = offset[0];\r\n this.__ctx.shadowOffsetY = offset[1];\r\n }\r\n\r\n setGlobalAlpha(alpha: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.globalAlpha = alpha;\r\n }\r\n\r\n setGlobalCompositeOperation(op: string) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.globalCompositeOperation = op as any;\r\n }\r\n\r\n setImageSmoothingEnabled(enabled: boolean) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.imageSmoothingEnabled = enabled;\r\n }\r\n\r\n setImageSmoothingQuality(quality: ImageSmoothingQuality) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.imageSmoothingQuality = quality;\r\n }\r\n\r\n setLineDash(dash: number[]) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.setLineDash(dash);\r\n }\r\n\r\n setLineDashOffset(offset: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineDashOffset = offset;\r\n }\r\n\r\n setTransform(a: number, b: number, c: number, d: number, e: number, f: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.setTransform(a, b, c, d, e, f);\r\n }\r\n\r\n resetTransform() {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.resetTransform();\r\n }\r\n\r\n scale(v: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.scale(v[0], v[1]);\r\n }\r\n\r\n rotate(angle: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.rotate(angle);\r\n }\r\n\r\n translate(v: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.translate(v[0], v[1]);\r\n }\r\n\r\n private flushPoints() {\r\n if (!this.__ctx) return;\r\n if (!this.fastPoints) return;\r\n if (!this.fastPointsBuffer) return;\r\n\r\n this.__ctx.putImageData(this.fastPointsBuffer, 0, 0);\r\n\r\n this.fastPoints = false;\r\n this.fastPointsBuffer = null;\r\n\r\n this.pointsCounter = 0;\r\n }\r\n\r\n private pointsCounter: number = 0;\r\n private cacheSize: [number, number] = [0, 0];\r\n point(pos: float2, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.pointsCounter++;\r\n\r\n this.__beforeDraw();\r\n if (this.pointsCounter > 10) {\r\n if (!this.fastPoints) {\r\n this.fastPoints = true;\r\n this.cacheSize = [this.__offscreen_canvas!.width, this.__offscreen_canvas!.height];\r\n this.fastPointsBuffer = this.__ctx.getImageData(0, 0, this.cacheSize[0], this.cacheSize[1]);\r\n }\r\n\r\n if (!this.fastPointsBuffer) return;\r\n\r\n let x = Math.floor(pos[0]);\r\n let y = Math.floor(pos[1]);\r\n\r\n let index = (y * this.cacheSize[0] + x) * 4;\r\n\r\n if (!color) {\r\n color = this.__currentColor;\r\n }\r\n let oldColorx = this.fastPointsBuffer.data[index] / 255;\r\n let oldColory = this.fastPointsBuffer.data[index + 1] / 255;\r\n let oldColorz = this.fastPointsBuffer.data[index + 2] / 255;\r\n let oldColora = this.fastPointsBuffer.data[index + 3] / 255;\r\n\r\n this.fastPointsBuffer.data[index] =\r\n color[0] * 255 * color[3] + oldColorx * 255 * (1 - color[3]);\r\n this.fastPointsBuffer.data[index + 1] =\r\n color[1] * 255 * color[3] + oldColory * 255 * (1 - color[3]);\r\n this.fastPointsBuffer.data[index + 2] =\r\n color[2] * 255 * color[3] + oldColorz * 255 * (1 - color[3]);\r\n this.fastPointsBuffer.data[index + 3] = color[3] * 255 + oldColora * 255 * (1 - color[3]);\r\n } else {\r\n this.__setColor(color);\r\n this.__ctx.fillRect(pos[0], pos[1], 1, 1);\r\n }\r\n this.__afterDraw();\r\n }\r\n\r\n vector(\r\n pos: float2,\r\n dir: float2,\r\n color: float4 = [0.9803921568627451, 0.8, 0.08235294117647059, 1] as float4,\r\n width: number = 4\r\n ) {\r\n if (!this.__ctx || (dir[0] == 0 && dir[1] == 0)) return;\r\n\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.setStrokeWidth(width);\r\n this.__ctx.moveTo(pos[0], pos[1]);\r\n this.__ctx.lineCap = 'round';\r\n\r\n this.__ctx.lineTo(pos[0] + dir[0], pos[1] + dir[1]);\r\n this.__ctx.stroke();\r\n this.__ctx.beginPath();\r\n this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]);\r\n // Arrows\r\n let arrowSize = 20;\r\n let arrowAngle = Math.PI / 5;\r\n let dirAngle = Math.atan2(dir[1], dir[0]) + Math.PI;\r\n let arrow1 = [\r\n Math.cos(dirAngle + arrowAngle) * arrowSize,\r\n Math.sin(dirAngle + arrowAngle) * arrowSize\r\n ];\r\n let arrow2 = [\r\n Math.cos(dirAngle - arrowAngle) * arrowSize,\r\n Math.sin(dirAngle - arrowAngle) * arrowSize\r\n ];\r\n this.__ctx.lineTo(pos[0] + dir[0] + arrow1[0], pos[1] + dir[1] + arrow1[1]);\r\n this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]);\r\n this.__ctx.lineTo(pos[0] + dir[0] + arrow2[0], pos[1] + dir[1] + arrow2[1]);\r\n\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n grid(\r\n center: float2,\r\n count: float2,\r\n gap: float2,\r\n color: float4 = [0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1] as float4,\r\n width: number = 2\r\n ) {\r\n if (!this.__ctx) return;\r\n\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.setStrokeWidth(width);\r\n\r\n let start = [\r\n center[0] - (count[0] / 2) * gap[0],\r\n center[1] - (count[1] / 2) * gap[1]\r\n ] as float2;\r\n\r\n for (let i = 0; i <= count[0]; i++) {\r\n this.__ctx.moveTo(start[0] + i * gap[0], start[1]);\r\n this.__ctx.lineTo(start[0] + i * gap[0], start[1] + count[1] * gap[1]);\r\n }\r\n\r\n for (let i = 0; i <= count[1]; i++) {\r\n this.__ctx.moveTo(start[0], start[1] + i * gap[1]);\r\n this.__ctx.lineTo(start[0] + count[0] * gap[0], start[1] + i * gap[1]);\r\n }\r\n\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n}\r\n\r\ndeclare global {\r\n const paint: PaintingContext;\r\n}\r\n"; const mesh = "\r\npub struct Mesh {\r\n vertices: float3[];\r\n triangles: int[];\r\n normals: float3[];\r\n tangents: float3[];\r\n bitangents: float3[];\r\n uvs: float2[];\r\n colors: float4[];\r\n pub symbol: any;\r\n}\r\n\r\nimpl Mesh {\r\n pub fn rect(self, size: float2) {\r\n let index = self.vertices.len();\r\n\r\n self.vertices.push((-size.x / 2, -size.y / 2, 0));\r\n self.vertices.push((size.x / 2, -size.y / 2, 0));\r\n self.vertices.push((size.x / 2, size.y / 2, 0));\r\n self.vertices.push((-size.x / 2, size.y / 2, 0));\r\n\r\n self.triangles.push(index + 2);\r\n self.triangles.push(index + 1);\r\n self.triangles.push(index + 0);\r\n\r\n self.triangles.push(index + 0);\r\n self.triangles.push(index + 3);\r\n self.triangles.push(index + 2);\r\n\r\n self.normals.push((0, 0, 1));\r\n self.normals.push((0, 0, 1));\r\n self.normals.push((0, 0, 1));\r\n self.normals.push((0, 0, 1));\r\n\r\n self.tangents.push((1, 0, 0));\r\n self.tangents.push((1, 0, 0));\r\n self.tangents.push((1, 0, 0));\r\n self.tangents.push((1, 0, 0));\r\n\r\n self.bitangents.push((0, 1, 0));\r\n self.bitangents.push((0, 1, 0));\r\n self.bitangents.push((0, 1, 0));\r\n self.bitangents.push((0, 1, 0));\r\n\r\n self.uvs.push((0, 0));\r\n self.uvs.push((1, 0));\r\n self.uvs.push((0, 1));\r\n self.uvs.push((1, 1));\r\n }\r\n\r\n pub fn quad(self, position: float3, direction: float3, right: float3, size: float2) {\r\n let up = normalize(cross(right, direction));\r\n\r\n let halfSize = size / 2.0;\r\n\r\n let index = self.vertices.len();\r\n \r\n self.vertices.push(position + right * -halfSize.x + up * halfSize.y);\r\n self.vertices.push(position + right * halfSize.x + up * halfSize.y);\r\n self.vertices.push(position + right * halfSize.x + up * -halfSize.y);\r\n self.vertices.push(position + right * -halfSize.x + up * -halfSize.y);\r\n\r\n self.triangles.push(index + 0);\r\n self.triangles.push(index + 1);\r\n self.triangles.push(index + 2);\r\n\r\n self.triangles.push(index + 2);\r\n self.triangles.push(index + 3);\r\n self.triangles.push(index + 0);\r\n\r\n self.normals.push(direction);\r\n self.normals.push(direction);\r\n self.normals.push(direction);\r\n self.normals.push(direction);\r\n\r\n self.tangents.push(right);\r\n self.tangents.push(right);\r\n self.tangents.push(right);\r\n self.tangents.push(right);\r\n\r\n self.bitangents.push(up);\r\n self.bitangents.push(up);\r\n self.bitangents.push(up);\r\n self.bitangents.push(up);\r\n\r\n self.uvs.push((1, 0));\r\n self.uvs.push((0, 0));\r\n self.uvs.push((0, 1));\r\n self.uvs.push((1, 1));\r\n }\r\n\r\n pub fn box(self, size: float3) {\r\n let halfSize = size / 2.0;\r\n\r\n const UP = (0, 1.0, 0);\r\n const DOWN = (0, -1.0, 0);\r\n const LEFT = (-1.0, 0, 0);\r\n const RIGHT = (1.0, 0, 0);\r\n const FORWARD = (0, 0, 1.0);\r\n const BACK = (0, 0, -1.0);\r\n\r\n // Up\r\n self.quad(UP * halfSize.y, UP, LEFT, (size.x, size.z));\r\n\r\n // Down\r\n self.quad(DOWN * halfSize.y, DOWN, RIGHT, (size.x, size.z));\r\n\r\n // Left\r\n self.quad(LEFT * halfSize.x, LEFT, BACK, (size.z, size.y));\r\n\r\n // Right\r\n self.quad(RIGHT * halfSize.x, RIGHT, FORWARD, (size.z, size.y));\r\n\r\n // Forward\r\n self.quad(FORWARD * halfSize.z, FORWARD, LEFT, (size.x, size.y));\r\n\r\n // Back\r\n self.quad(BACK * halfSize.z, BACK, RIGHT, (size.x, size.y));\r\n }\r\n\r\n pub fn rectAt(self, minPos: float2, maxPos: float2) {\r\n self.rect(maxPos - minPos);\r\n self.translate((minPos, 0));\r\n }\r\n\r\n pub fn circle(self, pos: float2, radius: float, vertices: int = 32) {\r\n\r\n }\r\n\r\n pub fn uvSphere(self, pos: float3, radius: float, vertices: int = 32, rings: int = 16) {\r\n let index = self.vertices.len();\r\n\r\n let verticesPerRing = vertices + 1;\r\n\r\n for (let i = 0; i <= rings; i++) {\r\n let y = i / float(rings);\r\n let angleY = y * PI;\r\n\r\n let posY = cos(angleY);\r\n let radiusY = sin(angleY);\r\n\r\n for (let j = 0; j <= vertices; j++) {\r\n let x = j / float(vertices);\r\n let angleX = x * PI * 2;\r\n\r\n let posX = cos(angleX);\r\n let posZ = sin(angleX);\r\n\r\n self.vertices.push((posX * radiusY * radius, posY * radius, posZ * radiusY * radius));\r\n self.normals.push(normalize((posX * radiusY, posY, posZ * radiusY)));\r\n \r\n let tangent = normalize((posZ, 0, -posX));\r\n let bitangent = normalize(cross(self.normals[self.normals.len() - 1], tangent));\r\n\r\n self.tangents.push(tangent);\r\n self.bitangents.push(bitangent);\r\n self.uvs.push((x, y));\r\n }\r\n }\r\n\r\n for (let i = 0; i < rings; i++) {\r\n for (let j = 0; j < vertices; j++) {\r\n let i0 = i * verticesPerRing + j;\r\n let i1 = i0 + 1;\r\n let i2 = i0 + verticesPerRing;\r\n let i3 = i2 + 1;\r\n\r\n self.triangles.push(index + i0);\r\n self.triangles.push(index + i1);\r\n self.triangles.push(index + i2);\r\n\r\n self.triangles.push(index + i2);\r\n self.triangles.push(index + i1);\r\n self.triangles.push(index + i3);\r\n }\r\n }\r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn icoSphere(self, pos: float3, radius: float, subdivisions: int = 1) {\r\n let index = self.vertices.len();\r\n\r\n let t = (1.0 + sqrt(5.0)) / 2.0;\r\n\r\n let vertices: float3[] = [\r\n (-1, t, 0),\r\n (1, t, 0),\r\n (-1, -t, 0),\r\n (1, -t, 0),\r\n (0, -1, t),\r\n (0, 1, t),\r\n (0, -1, -t),\r\n (0, 1, -t),\r\n (t, 0, -1),\r\n (t, 0, 1),\r\n (-t, 0, -1),\r\n (-t, 0, 1),\r\n ];\r\n\r\n let triangles: int3[] = [\r\n (0, 11, 5),\r\n (0, 5, 1),\r\n (0, 1, 7),\r\n (0, 7, 10),\r\n (0, 10, 11),\r\n (1, 5, 9),\r\n (5, 11, 4),\r\n (11, 10, 2),\r\n (10, 7, 6),\r\n (7, 1, 8),\r\n (3, 9, 4),\r\n (3, 4, 2),\r\n (3, 2, 6),\r\n (3, 6, 8),\r\n (3, 8, 9),\r\n (4, 9, 5),\r\n (2, 4, 11),\r\n (6, 2, 10),\r\n (8, 6, 7),\r\n (9, 8, 1),\r\n ];\r\n\r\n for (let i = 0; i < vertices.len(); i++) {\r\n self.vertices.push(normalize(vertices[i]) * radius);\r\n }\r\n\r\n for (let i = 0; i < triangles.len(); i++) {\r\n self.triangles.push(index + triangles[i].x);\r\n self.triangles.push(index + triangles[i].y);\r\n self.triangles.push(index + triangles[i].z);\r\n }\r\n\r\n for (let i = 0; i < subdivisions; i++) {\r\n let newTriangles: int[] = [];\r\n\r\n for (let j = 0; j < self.triangles.len(); j += 3) {\r\n let i0 = self.triangles[j + 0];\r\n let i1 = self.triangles[j + 1];\r\n let i2 = self.triangles[j + 2];\r\n\r\n let v0 = self.vertices[i0];\r\n let v1 = self.vertices[i1];\r\n let v2 = self.vertices[i2];\r\n\r\n let v3 = normalize((v0 + v1) / 2.0);\r\n let v4 = normalize((v1 + v2) / 2.0);\r\n let v5 = normalize((v2 + v0) / 2.0);\r\n\r\n let i3 = self.vertices.len();\r\n let i4 = i3 + 1;\r\n let i5 = i3 + 2;\r\n\r\n self.vertices.push(v3 * radius);\r\n self.vertices.push(v4 * radius);\r\n self.vertices.push(v5 * radius);\r\n\r\n newTriangles.push(i0, i3, i5);\r\n newTriangles.push(i3, i1, i4);\r\n newTriangles.push(i3, i4, i5);\r\n newTriangles.push(i5, i4, i2);\r\n }\r\n\r\n self.triangles = newTriangles;\r\n }\r\n\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n let normal = normalize(self.vertices[i]);\r\n let tangent = normalize((normal.z, 0, -normal.x));\r\n let bitangent = normalize(cross(normal, tangent));\r\n self.normals.push(normal);\r\n self.tangents.push(tangent);\r\n self.bitangents.push(bitangent);\r\n }\r\n\r\n for (let i = 0; i < self.triangles.len(); i += 3) {\r\n let i0 = self.triangles[i + 0];\r\n let i1 = self.triangles[i + 1];\r\n let i2 = self.triangles[i + 2];\r\n\r\n let v0 = self.vertices[i0];\r\n let v1 = self.vertices[i1];\r\n let v2 = self.vertices[i2];\r\n\r\n let uv0 = float2(atan2(v0.z, v0.x) / PI / 2.0 + 0.5, asin(v0.y) / PI + 0.5);\r\n let uv1 = float2(atan2(v1.z, v1.x) / PI / 2.0 + 0.5, asin(v1.y) / PI + 0.5);\r\n let uv2 = float2(atan2(v2.z, v2.x) / PI / 2.0 + 0.5, asin(v2.y) / PI + 0.5);\r\n\r\n self.uvs.push(uv0);\r\n self.uvs.push(uv1);\r\n self.uvs.push(uv2);\r\n }\r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn cylinder(self, pos: float3, radius: float, height: float, vertices: int = 32) {\r\n \r\n\r\n self.translate(pos);\r\n\r\n }\r\n\r\n pub fn capsule(self, pos: float3, radius: float, height: float, vertices: int = 32) {\r\n \r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn cone(self, pos: float3, radius: float, height: float, vertices: int = 32) {\r\n let index = self.vertices.len();\r\n\r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn plane(self, pos: float3, size: float2, subdivisions: int2 = (2, 2)) {\r\n let index = self.vertices.len();\r\n\r\n let halfSize = size / 2.0;\r\n\r\n for (let i = 0; i <= subdivisions.x; i++) {\r\n let x = i / float(subdivisions.x);\r\n let posX = x * size.x - halfSize.x;\r\n\r\n for (let j = 0; j <= subdivisions.y; j++) {\r\n let y = j / float(subdivisions.y);\r\n let posY = y * size.y - halfSize.y;\r\n\r\n self.vertices.push((posX, 0, posY));\r\n self.normals.push((0, 1, 0));\r\n self.tangents.push((1, 0, 0));\r\n self.bitangents.push((0, 0, 1));\r\n self.uvs.push((x, y));\r\n }\r\n }\r\n\r\n for (let i = 0; i < subdivisions.x; i++) {\r\n for (let j = 0; j < subdivisions.y; j++) {\r\n let i0 = i * (subdivisions.y + 1) + j;\r\n let i1 = i0 + 1;\r\n let i2 = i0 + subdivisions.y + 1;\r\n let i3 = i2 + 1;\r\n\r\n self.triangles.push(index + i0);\r\n self.triangles.push(index + i1);\r\n self.triangles.push(index + i2);\r\n\r\n self.triangles.push(index + i2);\r\n self.triangles.push(index + i1);\r\n self.triangles.push(index + i3);\r\n }\r\n }\r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn translate(self, pos: float3): Mesh {\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n self.vertices[i] += pos;\r\n }\r\n\r\n return self;\r\n }\r\n\r\n pub fn rotate(self, quaternion: float4): Mesh {\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n self.vertices[i] = quat::rotate(quaternion, self.vertices[i]);\r\n }\r\n\r\n for (let i = 0; i < self.normals.len(); i++) {\r\n self.normals[i] = quat::rotate(quaternion, self.normals[i]);\r\n }\r\n\r\n return self;\r\n }\r\n\r\n pub fn transform(self, matrix: float4x4): Mesh {\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n self.vertices[i] = ((self.vertices[i], 1) * matrix).xyz;\r\n }\r\n\r\n for (let i = 0; i < self.normals.len(); i++) {\r\n self.normals[i] = ((self.normals[i], 1) * matrix).xyz;\r\n }\r\n\r\n return self;\r\n }\r\n\r\n pub fn scale(self, scale: float3): Mesh {\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n self.vertices[i] *= scale;\r\n }\r\n\r\n return self;\r\n }\r\n\r\n pub fn bounds(self): float3 {\r\n let mn = 0.0.xyz;\r\n let mx = 0.0.xyz;\r\n\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n mn = min(mn, self.vertices[i]);\r\n mx = max(mx, self.vertices[i]);\r\n }\r\n\r\n return mx - mn;\r\n }\r\n\r\n pub fn center(self): float3 {\r\n let bounds = self.bounds();\r\n return bounds / 2.0;\r\n }\r\n\r\n pub fn new() {\r\n return Mesh {\r\n vertices: [],\r\n triangles: [],\r\n tangents: [],\r\n bitangents: [],\r\n normals: [],\r\n uvs: [],\r\n colors: [],\r\n }\r\n }\r\n\r\n pub fn append(self, other: Mesh) {\r\n let oldVertices = self.vertices.len();\r\n let oldTriangles = self.triangles.len();\r\n\r\n self.vertices.append(other.vertices);\r\n self.triangles.append(other.triangles);\r\n self.normals.append(other.normals);\r\n self.tangents.append(other.tangents);\r\n self.bitangents.append(other.bitangents);\r\n self.uvs.append(other.uvs);\r\n self.colors.append(other.colors);\r\n\r\n for (let i = oldTriangles; i < self.triangles.len(); i++) {\r\n self.triangles[i] += oldVertices;\r\n }\r\n }\r\n\r\n pub fn getVertices(self) {\r\n return self.vertices;\r\n }\r\n\r\n pub fn getTriangles(self) {\r\n return self.triangles;\r\n }\r\n\r\n pub fn getNormals(self) {\r\n return self.normals;\r\n }\r\n\r\n pub fn getTangents(self) {\r\n return self.tangents;\r\n }\r\n\r\n pub fn getBitangents(self) {\r\n return self.bitangents;\r\n }\r\n\r\n pub fn getUVs(self) {\r\n return self.uvs;\r\n }\r\n\r\n pub fn getColors(self) {\r\n return self.colors;\r\n }\r\n\r\n pub fn setVertices(self, vertices: float3[]) {\r\n self.vertices = vertices;\r\n }\r\n\r\n pub fn setTriangles(self, triangles: int[]) {\r\n self.triangles = triangles;\r\n }\r\n\r\n pub fn setNormals(self, normals: float3[]) {\r\n self.normals = normals;\r\n }\r\n\r\n pub fn setTangents(self, tangents: float3[]) {\r\n self.tangents = tangents;\r\n }\r\n\r\n pub fn setBitangents(self, bitangents: float3[]) {\r\n self.bitangents = bitangents;\r\n }\r\n\r\n pub fn setUVs(self, uvs: float2[]) {\r\n self.uvs = uvs;\r\n }\r\n\r\n pub fn setColors(self, colors: float4[]) {\r\n self.colors = colors;\r\n }\r\n}\r\n\r\npub struct mesh {}\r\n\r\nimpl mesh {\r\n pub fn rect(pos: float2, size: float2) -> Mesh {\r\n let g = Mesh::new();\r\n g.rectAt(pos, pos + size);\r\n\r\n return g;\r\n }\r\n\r\n pub fn box(pos: float3, size: float3) -> Mesh {\r\n let g = Mesh::new();\r\n g.box(size);\r\n g.translate(pos);\r\n\r\n return g;\r\n }\r\n\r\n pub fn uvSphere(pos: float3, radius: float, vertices: int = 32, rings: int = 16) -> Mesh {\r\n let g = Mesh::new();\r\n g.uvSphere(pos, radius, vertices, rings);\r\n\r\n return g;\r\n }\r\n\r\n pub fn icoSphere(pos: float3, radius: float, subdivisions: int = 1) -> Mesh {\r\n let g = Mesh::new();\r\n g.icoSphere(pos, radius, subdivisions);\r\n\r\n return g;\r\n }\r\n\r\n pub fn plane(pos: float3, size: float2, subdivisions: int2 = (2, 2)) -> Mesh {\r\n let g = Mesh::new();\r\n g.plane(pos, size, subdivisions);\r\n\r\n return g;\r\n }\r\n\r\n /**\r\n * Returns a [-1, 1] position for a given index.\r\n */\r\n pub fn triangleFromIndex(index: int): float2 {\r\n if (index == 0) {\r\n return float2(-1, 1);\r\n } else if (index == 1) {\r\n return float2(1, 1);\r\n } else if (index == 2) {\r\n return float2(0, -1);\r\n } else {\r\n return float2(0, 0);\r\n }\r\n }\r\n\r\n pub fn circleFromIndex(vertexIndex: int, vertices: int): float2 {\r\n vertexIndex = vertices - vertexIndex;\r\n let numSlices = vertices / 3;\r\n let sliceIndex = floor(float(vertexIndex) / float(vertices) * float(numSlices));\r\n \r\n let incAngle = PI * 2.0 / float(numSlices);\r\n let baseAngle = incAngle * float(sliceIndex);\r\n\r\n if (vertexIndex % 3 == 0) {\r\n return float2(0, 0);\r\n } else if (vertexIndex % 3 == 1) {\r\n return float2(cos(baseAngle), sin(baseAngle));\r\n } else {\r\n return float2(cos(baseAngle + incAngle), sin(baseAngle + incAngle));\r\n }\r\n }\r\n\r\n pub fn rectFromIndex(index: int, vertices: int): float2 {\r\n let x = index % vertices;\r\n let y = index / vertices;\r\n\r\n return float2(x, y) / float(vertices) * 2.0 - 1.0;\r\n }\r\n\r\n pub fn empty(numVerts: int = 0) -> Mesh {\r\n let g = Mesh::new();\r\n if (numVerts > 0) {\r\n g.setVertices(array(numVerts, 0.xyz));\r\n g.setNormals(array(numVerts, 0.xyz));\r\n g.setTangents(array(numVerts, 0.xyz));\r\n g.setBitangents(array(numVerts, 0.xyz));\r\n g.setUVs(array(numVerts, 0.xy));\r\n g.setColors(array(numVerts, 0.xyzw));\r\n let tris = array(numVerts, 0);\r\n for (let i = 0; i < numVerts; i++) {\r\n tris[i] = i;\r\n }\r\n g.setTriangles(tris);\r\n }\r\n\r\n return g;\r\n }\r\n\r\n pub fn join(mesh1: Mesh, mesh2: Mesh) {\r\n let g = Mesh::new();\r\n g.append(mesh1);\r\n g.append(mesh2);\r\n\r\n return g;\r\n }\r\n\r\n // pub fn cylinder(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh {\r\n // let g = Mesh::new();\r\n // g.cylinder(pos, radius, height, vertices);\r\n\r\n // return g;\r\n // }\r\n\r\n // pub fn capsule(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh {\r\n // let g = Mesh::new();\r\n // g.capsule(pos, radius, height, vertices);\r\n\r\n // return g;\r\n // }\r\n\r\n // pub fn cone(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh {\r\n // let g = Mesh::new();\r\n // g.cone(pos, radius, height, vertices);\r\n\r\n // return g;\r\n // }\r\n}\r\n\r\npub struct Material {\r\n pub baseColor: float4,\r\n pub color: texture2d,\r\n \r\n pub normal: texture2d,\r\n pub normalScale: float2,\r\n pub roughness: texture2d,\r\n pub emissive: texture2d,\r\n \r\n \r\n pub metallic: texture2d,\r\n}\r\n\r\npub struct ModelPart {\r\n pub mesh: Mesh,\r\n pub material: Material,\r\n pub transform: float4x4,\r\n}\r\n\r\npub struct Model {\r\n pub parts: ModelPart[],\r\n}\r\n\r\nwindow.SHD_Mesh = Mesh;\r\nwindow.SHD_Model = Model;\r\nwindow.SHD_ModelPart = ModelPart;\r\nwindow.SHD_Material = Material;"; const geo = "struct GeoSegment {\r\n start: float2,\r\n end: float2,\r\n kind: int,\r\n arcRadius: float,\r\n arcStart: float,\r\n arcEnd: float\r\n}\r\n\r\nstruct GeoPoly {\r\n segments: GeoSegment[]\r\n}\r\n\r\ntrait Geometry {\r\n fn area(self) -> float;\r\n fn perimeter(self) -> float;\r\n fn discretize(self) -> GeoPoly;\r\n}\r\n\r\nimpl Geometry for GeoPoly {\r\n pub fn area(self) -> float {\r\n return 0.0;\r\n }\r\n\r\n pub fn perimeter(self) -> float {\r\n return 0.0;\r\n }\r\n\r\n pub fn discretize(self) -> GeoPoly {\r\n return self.clone();\r\n }\r\n}"; const textures = ""; const common = `\r import buffer from "/_std/buffer";\r import ui from "/_std/ui";\r import texture2d, texture3d from "/_std/texture";\r \r /**\r * Converts a position in screenSpace to a position in 2d clipSpace. e.g. (0, screenSize.x) -> (-1, 1)\r */\r pub fn pixelToClip(pixelPosition: float2) -> float2 {\r let zeroToOne = pixelPosition / env.screenSize;\r let zeroToTwo = zeroToOne * 2.0;\r let clipSpace = zeroToTwo - 1.0.xy;\r return (clipSpace.x, clipSpace.y * -1.0);\r }\r \r /**\r * Value of PI to 35 decimal places.\r */\r const PI = 3.14159265358979323846264338327950288;\r \r export {\r PI,\r buffer,\r texture2d,\r texture3d,\r ui\r };\r \r /**\r * Quaternion helpers\r */\r pub struct quat {}\r \r impl quat {\r /**\r * Creates a quaternion from an angle and axis.\r */\r pub fn fromAngleAxis(angle: float, axis: float3) -> float4 {\r return float4(axis * sin(angle * 0.5), cos(angle * 0.5));\r }\r \r /**\r * Multiplies two quaternions and returns the result.\r */\r pub fn mul(a: float4, b: float4) -> float4 {\r return float4(\r b.xyz * a.w + a.xyz * b.w + cross(a.xyz, b.xyz),\r a.w * b.w - dot(a.xyz, b.xyz)\r );\r }\r \r /**\r * Rotates a vector by a quaternion and returns the rotated vector.\r */\r pub fn rotate(quaternion: float4, vector: float3) -> float3 {\r let q = quat::mul(quat::mul(quaternion, float4(vector, 0)), quat::conjugate(quaternion));\r return q.xyz;\r }\r \r /**\r * Returns the conjugate of the input quaternion.\r *\r * The conjugate of a quaternion number is a quaternion with the same magnitudes but with the sign of the imaginary parts changed\r */\r pub fn conjugate(quaternion: float4) -> float4 {\r return float4(-quaternion.xyz, quaternion.w);\r }\r \r /**\r * Returns the inverse of the input quaternion.\r */\r pub fn inverse(quaternion: float4) -> float4 {\r return quat::conjugate(quaternion) / dot(quaternion, quaternion);\r }\r \r /**\r * Generates a quaternion that rotates from one direction to another via the shortest path.\r */\r pub fn fromToRotation(from: float3, to: float3) -> float4 {\r let q = 0.0.xyzw;\r let d = dot(from, to);\r if (d < -0.999999)\r {\r let right = float3(1, 0, 0);\r let up = float3(0, 1, 0);\r let tmp = cross(right, from);\r if (length(tmp) < 0.000001)\r {\r tmp = cross(up, from);\r }\r tmp = normalize(tmp);\r q = quat::fromAngleAxis(PI, tmp);\r } else if (d > 0.999999) {\r q = float4(0, 0, 0, 1);\r } else {\r q = float4(cross(from, to), 1 + d);\r q = normalize(q);\r }\r return q;\r }\r \r \r pub fn diff(a: float4, b: float4) -> float {\r return a * quat::inverse(b);\r }\r \r \r /**\r * Generates lookAt quaternion.\r */\r pub fn lookAt(forward: float3, up: float3): float4 {\r let right = normalize(cross(forward, up));\r up = normalize(cross(forward, right));\r \r let m00 = right.x;\r let m01 = right.y;\r let m02 = right.z;\r let m10 = up.x;\r let m11 = up.y;\r let m12 = up.z;\r let m20 = forward.x;\r let m21 = forward.y;\r let m22 = forward.z;\r \r let num8 = (m00 + m11) + m22;\r let q = float4(0, 0, 0, 1);\r if (num8 > 0.0)\r {\r let num = sqrt(num8 + 1.0);\r let w = num * 0.5;\r num = 0.5 / num;\r let x = (m12 - m21) * num;\r let y = (m20 - m02) * num;\r let z = (m01 - m10) * num;\r return float4(x, y, z, w);\r }\r \r if ((m00 >= m11) && (m00 >= m22))\r {\r let num7 = sqrt(((1.0 + m00) - m11) - m22);\r let num4 = 0.5 / num7;\r let x = 0.5 * num7;\r let y = (m01 + m10) * num4;\r let z = (m02 + m20) * num4;\r let w = (m12 - m21) * num4;\r return float4(x, y, z, w);\r }\r \r if (m11 > m22)\r {\r let num6 = sqrt(((1.0 + m11) - m00) - m22);\r let num3 = 0.5 / num6;\r let x = (m10 + m01) * num3;\r let y = 0.5 * num6;\r let z = (m21 + m12) * num3;\r let w = (m20 - m02) * num3;\r return float4(x, y, z, w);\r }\r \r let num5 = sqrt(((1.0 + m22) - m00) - m11);\r let num2 = 0.5 / num5;\r let x = (m20 + m02) * num2;\r let y = (m21 + m12) * num2;\r let z = 0.5 * num5;\r let w = (m01 - m10) * num2;\r return float4(x, y, z, w);\r }\r \r /**\r * Smooth interpolation between two quaternions.\r */\r pub fn slerp(a: float4, b: float4, t: float) -> float4 {\r \r if (length(a) == 0.0)\r {\r if (length(b) == 0.0)\r {\r return float4(0, 0, 0, 1);\r }\r return b;\r } else if (length(b) == 0.0) {\r return a;\r }\r \r let cosHalfAngle = a.w * b.w + dot(a.xyz, b.xyz);\r \r if (cosHalfAngle >= 1.0 || cosHalfAngle <= -1.0)\r {\r return a;\r } else if (cosHalfAngle < 0.0) {\r b *= -1.0;\r cosHalfAngle = -cosHalfAngle;\r }\r \r let blendA = 0.0;\r let blendB = 0.0;\r if (cosHalfAngle < 0.99)\r {\r let halfAngle = acos(cosHalfAngle);\r let sinHalfAngle = sin(halfAngle);\r let oneOverSinHalfAngle = 1.0 / sinHalfAngle;\r blendA = sin(halfAngle * (1.0 - t)) * oneOverSinHalfAngle;\r blendB = sin(halfAngle * t) * oneOverSinHalfAngle;\r }\r else\r {\r blendA = 1.0 - t;\r blendB = t;\r }\r \r let result = float4(blendA * a.xyz + blendB * b.xyz, blendA * a.w + blendB * b.w);\r if (length(result) > 0.0)\r {\r return normalize(result);\r }\r return float4(0, 0, 0, 1);\r }\r \r /**\r * Converts quaternion to matrix.\r */\r pub fn toMatrix(quaternion: float4) {\r let x = quaternion.x;\r let y = quaternion.y;\r let z = quaternion.z;\r let w = quaternion.w;\r let x2 = x + x;\r let y2 = y + y;\r let z2 = z + z;\r let xx = x * x2;\r let xy = x * y2;\r let xz = x * z2;\r let yy = y * y2;\r let yz = y * z2;\r let zz = z * z2;\r let wx = w * x2;\r let wy = w * y2;\r let wz = w * z2;\r \r \r let m = float4x4(\r 1.0 - (yy + zz), xy + wz, xz - wy, 0,\r xy - wz, 1.0 - (xx + zz), yz + wx, 0,\r xz + wy, yz - wx, 1.0 - (xx + yy), 0,\r 0, 0, 0, 1.0\r );\r \r return m;\r }\r \r pub fn fromEulerAngles(angles: float3) {\r let cr = cos(angles.x * 0.5);\r let sr = sin(angles.x * 0.5);\r let cp = cos(angles.y * 0.5);\r let sp = sin(angles.y * 0.5);\r let cy = cos(angles.z * 0.5);\r let sy = sin(angles.z * 0.5);\r \r return float4(\r sr * cp * cy - cr * sp * sy,\r cr * sp * cy + sr * cp * sy,\r cr * cp * sy - sr * sp * cy,\r cr * cp * cy + sr * sp * sy\r )\r }\r }\r \r window.shadeupQuat = quat;\r \r \r pub struct Camera2d {\r pub position: float2 = float2(0, 0);\r pub zoom: float = 1;\r }\r \r impl Camera2d {\r pub fn transform(self, position: float2) -> float2 {\r return (position - self.position) * self.zoom;\r }\r \r /**\r * Moves and zooms the camera to fit the given size. (centers the camera in the viewport)\r */\r pub fn fit(self, size: float2) {\r let zoom = 1/min(env.screenSize.x / size.x, env.screenSize.y / size.y);\r let position = (env.screenSize - size * (1/zoom)) / 2;\r self.position = position;\r self.zoom = zoom;\r }\r }\r \r pub struct Camera {\r pub position: float3 = float3(0, 0, 0);\r pub rotation: float4 = float4(1, 0, 0, 0);\r pub width: float = 1920;\r pub height: float = 1080;\r pub fov: float = 90;\r pub near: float = 1;\r pub far: float = 100000;\r }\r \r impl Camera {\r pub fn getRay(self, screen: float2) {\r let aspect = self.width / self.height;\r let x = screen.x;\r let y = screen.y;\r let Px = (2 * ((x + 0.5) / self.width) - 1) * tan(self.fov / 2 * PI / 180) * aspect;\r let Py = (1 - 2 * ((y + 0.5) / self.height)) * tan(self.fov / 2 * PI / 180);\r \r return quat::rotate(self.rotation, normalize((Px, Py, -1)));\r }\r \r pub fn getTransformToViewMatrix(self, position: float3, scale: float3, rotation: float4) {\r let rotationMatrix = quat::toMatrix(rotation);\r let translationMatrix = float4x4(\r scale.x, 0, 0, 0,\r 0, scale.y, 0, 0,\r 0, 0, scale.z, 0,\r position.x, position.y, position.z, 1\r );\r return self.getPerspectiveMatrix() * self.getWorldToViewMatrix() * translationMatrix * rotationMatrix;\r }\r \r pub fn getCombinedMatrix(self) -> float4x4 {\r return self.getPerspectiveMatrix() * self.getWorldToViewMatrix();\r }\r \r pub fn getCombinedMatrixReverseZ(self) -> float4x4 {\r return self.getPerspectiveMatrixReverseZ() * self.getWorldToViewMatrix();\r }\r \r pub fn getWorldToViewMatrix(self) -> float4x4 {\r let rotationMatrix = quat::toMatrix(self.rotation);\r let translationMatrix = float4x4(\r 1, 0, 0, 0,\r 0, 1, 0, 0,\r 0, 0, 1, 0,\r self.position.x, self.position.y, self.position.z, 1\r );\r return inverse(translationMatrix * rotationMatrix);\r }\r \r pub fn getPerspectiveMatrixReverseZ(self) -> float4x4 {\r return matrix::perspectiveReverseZ(self.fov, self.width / self.height, self.near);\r }\r \r pub fn getPerspectiveMatrix(self) -> float4x4 {\r return matrix::perspective(self.fov, self.width / self.height, self.near, self.far);\r // // let matrix = float4x4();\r // let far = self.far;\r // let near = self.near;\r // let aspect = self.width / self.height;\r // let fovRad = radians(self.fov);\r // let tanFov = tan( fovRad * 0.5 );\r // // matrix[0][0] = ;\r // // matrix[1][1] = 1.0 / tanFov;\r // // matrix[2][2] = -((far + near)/(far - near));\r // // matrix[3][2] = -((2*(near*far))/(far - near));\r // // matrix[2][3] = -1;\r // // matrix[3][3] = 0;\r \r // let matrix = float4x4(\r // 1.0 / (tanFov * aspect), 0, 0, 0,\r // 0, 1.0 / tanFov, 0, 0,\r // 0, 0, -((far + near)/(far - near)), -1,\r // 0, 0, -((2*(near*far))/(far - near)), 0\r // );\r \r // return matrix;\r }\r \r pub fn getOrthographicMatrix(self) -> float4x4 {\r let matrix = float4x4();\r let far = self.far;\r let near = self.near;\r \r let w = 1.0 / self.width;\r let h = 1.0 / self.height;\r \r matrix[0][0] = w;\r matrix[1][1] = h;\r matrix[2][2] = -(2.0/(far - near));\r matrix[2][3] = ((far + near)/(far-near));\r //matrix[2][2] = -((far + near)/(far - near));\r //matrix[3][2] = -((2*(near*far))/(far - near));\r matrix[3][3] = 1.0;\r \r return matrix;\r }\r }\r \r \r window._makeCamera = Camera;\r window._makeCamera2d = Camera2d;\r \r fn easeA(aA1: float, aA2: float) -> float {\r return 1.0 - 3.0 * aA2 + 3.0 * aA1;\r }\r \r fn easeB(aA1: float, aA2: float) -> float {\r return 3.0 * aA2 - 6.0 * aA1;\r }\r \r fn easeC(aA1: float) -> float {\r return 3.0 * aA1;\r }\r \r fn calcBezier(aT: float, aA1: float, aA2: float) -> float {\r return ((easeA(aA1, aA2) * aT + easeB(aA1, aA2)) * aT + easeC(aA1)) * aT;\r }\r \r fn getSlope(aT: float, aA1: float, aA2: float) -> float {\r return 3.0 * easeA(aA1, aA2) * aT * aT + 2.0 * easeB(aA1, aA2) * aT + easeC(aA1);\r }\r \r // fn getTForX(aX: float, aA1: float, aA2: float) -> float {\r // let aGuessT = aX;\r // for (let i = 0; i <= 10; i++) {\r // let currentSlope = bezSlope(aGuessT, aA1, aA2);\r // if (currentSlope == 0.0) {\r // return aGuessT;\r // }\r // let currentX = calcBezier(aGuessT, aA1, aA2) - aX;\r // aGuessT -= currentX / currentSlope;\r // }\r // return aGuessT;\r // }\r \r \r const NEWTON_ITERATIONS = 4;\r const NEWTON_MIN_SLOPE = 0.02;\r const SUBDIVISION_PRECISION = 0.0000001;\r const SUBDIVISION_MAX_ITERATIONS = 10;\r const kSplineTableSize = 11;\r \r const kSampleStepSize =\r 1.0 / float(kSplineTableSize - 1);\r \r \r fn getTForX(aX: float, mX1: float, mX2: float) {\r let mSampleValues: array = array(11, 0);\r for (let i = 0; i < kSplineTableSize; i++) {\r mSampleValues[i] = calcBezier(float(i) * kSampleStepSize, mX1, mX2);\r }\r \r // Find interval where t lies\r let intervalStart = 0.0;\r let currentSample = 1;\r let lastSample = kSplineTableSize - 1;\r \r for (let dummy = 0; currentSample != lastSample && mSampleValues[currentSample] <= aX; currentSample++) {\r intervalStart += kSampleStepSize;\r }\r currentSample--; // t now lies between *currentSample and *currentSample+1\r \r // Interpolate to provide an initial guess for t\r let csamp = mSampleValues[currentSample];\r let dst = (aX - csamp) /\r (mSampleValues[currentSample + 1] - csamp);\r let guessForT = intervalStart + dst * kSampleStepSize;\r \r // Check the slope to see what strategy to use. If the slope is too small\r // Newton-Raphson iteration won't converge on a root so we use bisection\r // instead.\r let initialSlope = getSlope(guessForT, mX1, mX2);\r if (initialSlope >= NEWTON_MIN_SLOPE) {\r return newtonRaphsonIterate(aX, guessForT, mX1, mX2);\r } else if (initialSlope == 0.0) {\r return guessForT;\r } else {\r return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);\r }\r }\r \r fn newtonRaphsonIterate(aX: float, aGuessT: float, mX1: float, mX2: float) {\r // Refine guess with Newton-Raphson iteration\r for (let i = 0; i < NEWTON_ITERATIONS; i++) {\r // We're trying to find where f(t) = aX,\r // so we're actually looking for a root for: CalcBezier(t) - aX\r let currentX = calcBezier(aGuessT, mX1, mX2) - aX;\r let currentSlope = getSlope(aGuessT, mX1, mX2);\r \r if (currentSlope == 0.0)\r return aGuessT;\r \r aGuessT -= currentX / currentSlope;\r }\r \r return aGuessT;\r }\r \r fn binarySubdivide(aX: float, aA: float, aB: float) {\r let currentX = 0.0;\r let currentT = 0.0;\r let i = 0;\r let mX1 = aA;\r let mX2 = aB;\r \r while (true) {\r i++;\r if (abs(currentX) > SUBDIVISION_PRECISION && i < SUBDIVISION_MAX_ITERATIONS) {\r currentT = aA + (aB - aA) / 2.0;\r currentX = calcBezier(currentT, mX1, mX2) - aX;\r \r if (currentX > 0.0) {\r aB = currentT;\r } else {\r aA = currentT;\r }\r }else{\r break;\r }\r }\r \r return currentT;\r }\r \r pub struct bezier {};\r \r impl bezier {\r pub fn cubic2(a: float2, b: float2, c: float2, d: float2, t: float) -> float2 {\r return (1.0 - t)**3 * a + 3.0 * (1.0 - t)**2 * t * b + 3.0 * (1.0 - t) * t**2 * c + t**3 * d;\r }\r \r pub fn cubic3(a: float3, b: float3, c: float3, d: float3, t: float) -> float3 {\r return (1.0 - t)**3 * a + 3.0 * (1.0 - t)**2 * t * b + 3.0 * (1.0 - t) * t**2 * c + t**3 * d;\r }\r \r pub fn quadratic2(a: float2, b: float2, c: float2, t: float) -> float2 {\r return (1.0 - t)**2 * a + 2.0 * (1.0 - t) * t * b + t**2 * c;\r }\r \r pub fn quadratic3(a: float3, b: float3, c: float3, t: float) -> float3 {\r return (1.0 - t)**2 * a + 2.0 * (1.0 - t) * t * b + t**2 * c;\r }\r \r /**\r * 3d triangle patch evaulation with barycentric coordinates.\r */\r pub fn patch(a: float3, ab: float3, b: float3, bc: float3, c: float3, ca: float3, barycentricT: float3) {\r const s = barycentricT.x;\r const t = barycentricT.y;\r const u = barycentricT.z;\r return 1.0 * c * (s * s) +\r 2.0 * bc * s * t +\r 2.0 * ca * s * u +\r 1.0 * b * (t * t) +\r 2.0 * ab * t * u +\r 1.0 * a * (u * u);\r }\r \r \r \r pub fn easing(controlA: float2, controlB: float2, t: float) -> float {\r return calcBezier(getTForX(t, controlA.x, controlB.x), controlA.y, controlB.y);\r }\r }\r \r /**\r * Provides space related utilities like z-order curves and quadtrees.\r */\r pub struct spatial {};\r \r impl spatial {\r pub fn cantorPair(v: int2) -> int {\r return ((v.x + v.y) * (v.x + v.y + 1)) / 2 + v.y;\r }\r \r pub fn cantorUnpair(v: int) -> int2 {\r let w = floor((sqrt(8.0 * v + 1.0) - 1.0) / 2.0);\r let t = (w * w + w) / 2.0;\r let y = v - t;\r let x = w - y;\r return int2(x, y);\r }\r \r pub fn hilbertRotate(n: int, b: int2, r: int2) -> int2 {\r let x = b.x;\r let y = b.y;\r if (r.y == 0) {\r if (r.x == 1) {\r x = n-1 - x;\r y = n-1 - y;\r }\r \r let t = x;\r x = y;\r y = t;\r }\r \r return int2(x, y);\r }\r \r pub fn hilbertUncurve(n: int, v: int2) -> int {\r let x = v.x;\r let y = v.y;\r let rx: int = 0;\r let ry: int = 0;\r let s: int = 0;\r let d: int = 0;\r for (s=n/2; s>0; s/=2) {\r rx = ((x & s) > 0) ? 1 : 0;\r ry = ((y & s) > 0) ? 1 : 0;\r d += s * s * ((3 * rx) ^ ry);\r let o = spatial::hilbertRotate(n, (x, y), (rx, ry));\r x = o.x;\r y = o.y;\r }\r return d;\r }\r \r pub fn hilbertCurve(n: int, v: int) -> int2 {\r let rx: int = 0;\r let ry: int = 0;\r let t = v;\r let x = 0;\r let y = 0;\r for (let s: int = 1; s < n; s *= 2) {\r rx = 1 & (t/2);\r ry = 1 & (t ^ rx);\r let o = spatial::hilbertRotate(s, (x, y), (rx, ry));\r x = o.x;\r y = o.y;\r x += s * rx;\r y += s * ry;\r t /= 4;\r }\r \r return int2(x, y);\r }\r \r pub fn mortonDecode(p: uint) -> uint2 {\r return uint2(reverseMortonCode2(p), reverseMortonCode2(p >> 1u));\r }\r \r pub fn mortonEncode(p: uint2) -> uint {\r return uint(mortonCode2(p.x) | (mortonCode2(p.y) << 1u));\r }\r \r }\r \r pub fn mortonCode2(x: uint) -> uint {\r x = x & 0x0000ffffu;\r let n8 = 8u;\r let n4 = 4u;\r let n2 = 2u;\r let n1 = 1u;\r x = (x ^ (x << n8)) & 0x00ff00ffu;\r x = (x ^ (x << n4)) & 0x0f0f0f0fu;\r x = (x ^ (x << n2)) & 0x33333333u;\r x = (x ^ (x << n1)) & 0x55555555u;\r return x;\r }\r \r pub fn randColor(seed: float) -> float4 {\r return float4(rand2((seed,5)), rand2((seed, 1)), rand2((seed, 4)), 1);\r }\r \r pub fn randColor2(seed: float2) -> float4 {\r return float4(rand3((seed,5)), rand3((seed, 1)), rand3((seed, 4)), 1);\r }\r \r pub fn reverseMortonCode2(x: uint) -> uint {\r x = x & 0x55555555u;\r x = (x ^ (x >> 1u)) & 0x33333333u;\r x = (x ^ (x >> 2u)) & 0x0f0f0f0fu;\r x = (x ^ (x >> 4u)) & 0x00ff00ffu;\r x = (x ^ (x >> 8u)) & 0x0000ffffu;\r return x;\r }\r \r pub struct noise {};\r \r \r const PERLIN_YWRAPB = 4;\r const PERLIN_YWRAP = 1 << PERLIN_YWRAPB;\r const PERLIN_ZWRAPB = 8;\r const PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB;\r const PERLIN_SIZE = 4095;\r \r let perlin_octaves = 4; // default to medium smooth\r let perlin_amp_falloff = 0.5; // 50% reduction/octave\r \r \r fn scaled_cosine(i: float) -> float {\r return 0.5 * (1.0 - cos(i * PI));\r }\r \r let perlin = buffer(PERLIN_SIZE + 1);\r for (let i = 0; i < PERLIN_SIZE + 1; i++) {\r perlin[i] = rand(i);\r }\r \r // \r // By Morgan McGuire @morgan3d, http://graphicscodex.com\r //\r fn hash(n: float) -> float { return frac(sin(n) * 1e4); }\r fn hash2(p: float2) -> float { return frac(1e4 * sin(17.0 * p.x + p.y * 0.1) * (0.1 + abs(sin(p.y * 13.0 + p.x)))); }\r fn hash3(p: float3) -> float { let h = dot(p, float3(127.1, 311.7, 74.7)); return frac(sin(h) * 43758.5453123); }\r \r \r \r impl noise {\r pub fn gaussian3(v: float3) -> float {\r let p = v;\r let a = floor(p);\r let d = p - a;\r d = d * d * (3.0 - 2.0 * d);\r \r let b = a.xxyy + float4(0.0, 1.0, 0.0, 1.0);\r let k1 = perm(b.xyxy);\r let k2 = perm(k1.xyxy + b.zzww);\r \r let c = k2 + a.zzzz;\r let k3 = perm(c);\r let k4 = perm(c + 1.0);\r \r let o1 = frac(k3 * (1.0 / 41.0));\r let o2 = frac(k4 * (1.0 / 41.0));\r \r let o3 = o2 * d.z + o1 * (1.0 - d.z);\r let o4 = o3.yw * d.x + o3.xz * (1.0 - d.x);\r \r return o4.y * d.y + o4.x * (1.0 - d.y);\r }\r \r pub fn gaussian2(v: float2) -> float {\r return noise::gaussian3((v, 0));\r }\r \r pub fn noise1(x: float) {\r let i = floor(x);\r let f = frac(x);\r let u = f * f * (3.0 - 2.0 * f);\r return lerp(hash(i), hash(i + 1.0), u);\r }\r \r pub fn noise2(x: float2) -> float {\r let i = floor(x);\r let f = frac(x);\r \r // Four corners in 2D of a tile\r let a = hash2(i);\r let b = hash2(i + float2(1.0, 0.0));\r let c = hash2(i + float2(0.0, 1.0));\r let d = hash2(i + float2(1.0, 1.0));\r \r // Simple 2D lerp using smoothstep envelope between the values.\r // return float3(lerp(lerp(a, b, smoothstep(0.0, 1.0, f.x)),\r // lerp(c, d, smoothstep(0.0, 1.0, f.x)),\r // smoothstep(0.0, 1.0, f.y)));\r \r // Same code, with the clamps in smoothstep and common subexpressions\r // optimized away.\r let u = f * f * (3.0 - 2.0 * f);\r return lerp(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y;\r }\r \r pub fn fmb1(x: float) -> float {\r let v = 0.0;\r let a = 0.5;\r let shift = float(100);\r for (let i = 0; i < 5; i++) {\r v += a * noise::noise1(x);\r x = x * 2.0 + shift;\r a *= 0.5;\r }\r return v;\r }\r \r pub fn fbm2(x: float2) -> float {\r let v = 0.0;\r let a = 0.5;\r let shift = float2(100.xy);\r // Rotate to reduce axial bias\r let rot = float2x2(cos(0.5), sin(0.5), -sin(0.5), cos(0.50));\r for (let i = 0; i < 5; i++) {\r v += a * noise::noise2(x);\r x = rot * x * 2.0 + shift;\r a *= 0.5;\r }\r return v;\r }\r \r pub fn fbm3(x: float3) -> float {\r let v = 0.0;\r let a = 0.5;\r let shift = float3(100.xyz);\r for (let i = 0; i < 5; i++) {\r v += a * noise::noise3(x);\r x = x * 2.0 + shift;\r a *= 0.5;\r }\r return v;\r }\r \r pub fn noise3(x: float3) -> float {\r const step = float3(110, 241, 171);\r \r let i = floor(x);\r let f = frac(x);\r \r // For performance, compute the base input to a 1D hash from the integer part of the argument and the \r // incremental change to the 1D based on the 3D -> 1D wrapping\r let n = dot(i, step);\r \r let u = f * f * (3.0 - 2.0 * f);\r return lerp(lerp(lerp( hash(n + dot(step, float3(0, 0, 0))), hash(n + dot(step, float3(1, 0, 0))), u.x),\r lerp( hash(n + dot(step, float3(0, 1, 0))), hash(n + dot(step, float3(1, 1, 0))), u.x), u.y),\r lerp(lerp( hash(n + dot(step, float3(0, 0, 1))), hash(n + dot(step, float3(1, 0, 1))), u.x),\r lerp( hash(n + dot(step, float3(0, 1, 1))), hash(n + dot(step, float3(1, 1, 1))), u.x), u.y), u.z);\r }\r \r pub fn simplex2(v: float2) -> float {\r let C = float4(0.211324865405187,\r 0.366025403784439,\r -0.577350269189626,\r 0.024390243902439);\r \r let i = floor(v + dot(v, C.yy));\r let x0 = v - i + dot(i, C.xx);\r \r let xv = step(x0.y, x0.x);\r \r let i1 = float2(xv, 1.0 - xv);\r \r let x1 = x0 + C.xx - i1;\r let x2 = x0 + C.zz;\r \r \r i = mod289_2(i);\r let p =\r permute(\r permute(float3(0.0, i1.y, 1.0) + i.y)\r + float3(0.0, i1.x, 1.0) + i.x);\r \r let m = max(0.5.xyz - float3(dot(x0, x0), dot(x1, x1), dot(x2, x2)), 0.0);\r m = m * m;\r m = m * m;\r \r let x = 2.0 * frac(p * C.www) - 1.0;\r let h = abs(x) - 0.5;\r let ox = floor(x + 0.5);\r let a0 = x - ox;\r \r // Normalise gradients implicitly by scaling m\r m *= taylorInvSqrt(a0 * a0 + h * h);\r \r // Compute final noise value at P\r let g = float3(\r a0.x * x0.x + h.x * x0.y,\r a0.y * x1.x + h.y * x1.y,\r a0.z * x2.x + h.z * x2.y\r );\r return 130.0 * dot(m, g);\r }\r \r pub fn perlin2(v: float2) -> float {\r let x = v.x;\r let y = v.y;\r let z = 0.0;\r \r if (x < 0) {\r x = -x;\r }\r if (y < 0) {\r y = -y;\r }\r if (z < 0) {\r z = -z;\r }\r \r let xi = int(floor(x)),\r yi = int(floor(y)),\r zi = int(floor(z));\r let xf = x - xi;\r let yf = y - yi;\r let zf = z - zi;\r let rxf = 0.0, ryf = 0.0;\r \r let r = 0.0;\r let ampl = 0.5;\r \r let n1= 0.0, n2 = 0.0, n3 = 0.0;\r \r for (let o = 0; o < perlin_octaves; o++) {\r let of1: int = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB);\r \r rxf = scaled_cosine(xf);\r ryf = scaled_cosine(yf);\r \r n1 = perlin[of1 & PERLIN_SIZE];\r n1 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n1);\r n2 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE];\r n2 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2);\r n1 += ryf * (n2 - n1);\r \r of1 += PERLIN_ZWRAP;\r n2 = perlin[of1 & PERLIN_SIZE];\r n2 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n2);\r n3 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE];\r n3 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3);\r n2 += ryf * (n3 - n2);\r \r n1 += scaled_cosine(zf) * (n2 - n1);\r \r r += n1 * ampl;\r ampl *= perlin_amp_falloff;\r xi = xi << 1;\r xf *= 2.0;\r yi = yi << 1;\r yf *= 2.0;\r zi = zi << 1;\r zf *= 2.0;\r \r if (xf >= 1.0) {\r xi++;\r xf-= 1.0;\r }\r if (yf >= 1.0) {\r yi++;\r yf-= 1.0;\r }\r if (zf >= 1.0) {\r zi++;\r zf-= 1.0;\r }\r }\r return r;\r \r }\r \r pub fn perlin3(v: float3) -> float {\r let x = v.x;\r let y = v.y;\r let z = v.z;\r \r if (x < 0) {\r x = -x;\r }\r if (y < 0) {\r y = -y;\r }\r if (z < 0) {\r z = -z;\r }\r \r let xi = int(floor(x)),\r yi = int(floor(y)),\r zi = int(floor(z));\r let xf = x - xi;\r let yf = y - yi;\r let zf = z - zi;\r let rxf = 0.0, ryf = 0.0;\r \r let r = 0.0;\r let ampl = 0.5;\r \r let n1= 0.0, n2 = 0.0, n3 = 0.0;\r \r for (let o = 0; o < perlin_octaves; o++) {\r let of1: int = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB);\r \r rxf = scaled_cosine(xf);\r ryf = scaled_cosine(yf);\r \r n1 = perlin[of1 & PERLIN_SIZE];\r n1 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n1);\r n2 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE];\r n2 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2);\r n1 += ryf * (n2 - n1);\r \r of1 += PERLIN_ZWRAP;\r n2 = perlin[of1 & PERLIN_SIZE];\r n2 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n2);\r n3 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE];\r n3 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3);\r n2 += ryf * (n3 - n2);\r \r n1 += scaled_cosine(zf) * (n2 - n1);\r \r r += n1 * ampl;\r ampl *= perlin_amp_falloff;\r xi = xi << 1;\r xf *= 2.0;\r yi = yi << 1;\r yf *= 2.0;\r zi = zi << 1;\r zf *= 2.0;\r \r if (xf >= 1.0) {\r xi++;\r xf-= 1.0;\r }\r if (yf >= 1.0) {\r yi++;\r yf-= 1.0;\r }\r if (zf >= 1.0) {\r zi++;\r zf-= 1.0;\r }\r }\r return r;\r }\r \r /**\r * Returns 3 values: distance to closest cell, random value of closest cell, distance to closest edge.\r */\r pub fn voronoi2(v: float2) -> float3 {\r let n = floor(v);\r let minDist = 10.0;\r let toClose = 0.0.xy;\r let closestCell = 0.0.xy;\r \r \r for (let j = -1; j <= 1; j++) {\r for (let i = -1; i <= 1; i++) {\r let cell = n + float2(i, j);\r let cellPos = cell + hash2(cell);\r let toCell = cellPos - v;\r let dst = length(toCell);\r if (dst < minDist) {\r minDist = dst;\r toClose = toCell;\r closestCell = cell;\r }\r }\r }\r \r let minEdge = 10.0;\r for (let j = -1; j <= 1; j++) {\r for (let i = -1; i <= 1; i++) {\r let cell = n + float2(i, j);\r let cellPos = cell + hash2(cell);\r let toCell = cellPos - v;\r let diff = abs(closestCell - cell);\r let isClosest = diff.x + diff.y < 0.1;\r if (!isClosest) {\r let toCenter = (toClose + toCell) * 0.5;\r let cellDiff = normalize(toCell - toClose);\r let edge = dot(toCenter, cellDiff);\r minEdge = min(minEdge, edge);\r }\r }\r }\r \r let random = hash2(closestCell);\r return float3(minDist, random, minEdge);\r }\r \r pub fn simplex3(v: float3) -> float {\r let C = float4(0.138196601125011,\r 0.276393202250021,\r 0.414589803375032,\r -0.447213595499958);\r \r let i = floor(v + dot(v, C.yyy));\r let x0 = v - i + dot(i, C.xxx);\r \r let g = step(x0.yzx, x0.xyz);\r let l = 1.0 - g;\r let i1 = min(g.xyz, l.zxy);\r let i2 = max(g.xyz, l.zxy);\r \r let x1 = x0 - i1 + 1.0 * C.xxx;\r let x2 = x0 - i2 + 2.0 * C.xxx;\r let x3 = x0 - 1. + 3.0 * C.xxx;\r \r i = mod289_3(i);\r let p =\r permute(\r permute(\r permute(i.z + float3(0.0, i1.z, i2.z))\r + i.y + float3(0.0, i1.y, i2.y))\r + i.x + float3(0.0, i1.x, i2.x));\r \r let m = max(0.5 - float3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0);\r m = m * m;\r m = m * m;\r \r let x = 2.0 * frac(p * C.www) - 1.0;\r let h = abs(x) - 0.5;\r let ox = floor(x + 0.5);\r let a0 = x - ox;\r \r // Normalise gradients implicitly by scaling m\r // Approximation of: m *= inversesqrt(a0 * a0 + h * h);\r m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\r \r // Compute final noise value at P\r let g2 = float3(\r a0.x * x0.x + h.x * x0.y,\r a0.y * x1.x + h.y * x1.y,\r a0.z * x2.x + h.z * x2.y\r );\r return 130.0 * dot(m, g2);\r }\r }\r \r fn mod289_1(x: float) -> float { return x - floor(x * (1.0 / 289.0)) * 289.0;}\r fn mod289_4(x: float4) -> float4 { return x - floor(x * (1.0 / 289.0)) * 289.0;}\r fn perm(x: float4) -> float4 { return mod289_4(((x * 34.0) + 1.0) * x);}\r \r fn mod289_3(x: float3) -> float3 {\r return x - floor(x * (1.0 / 289.0)) * 289.0;\r }\r \r fn mod289_2(x: float2) -> float2 {\r return x - floor(x * (1.0 / 289.0)) * 289.0;\r }\r \r fn permute(x: float3) -> float3 {\r return mod289_3((x * 34.0 + 1.0) * x);\r }\r \r fn taylorInvSqrt(r: float3) -> float3 {\r return 1.79284291400159 - 0.85373472095314 * r;\r }\r \r pub struct matrix {}\r \r impl matrix {\r pub fn lookAt(from: float3, to: float3, up: float3) -> float4x4 {\r let zAxis = normalize(from - to);\r let xAxis = normalize(cross(up, zAxis));\r let yAxis = normalize(cross(zAxis, xAxis));\r let dst = float4x4();\r dst[0][0] = xAxis.x; dst[0][1] = yAxis.x; dst[0][2] = zAxis.x; dst[0][3] = 0;\r dst[1][0] = xAxis.y; dst[1][1] = yAxis.y; dst[1][2] = zAxis.y; dst[1][3] = 0;\r dst[2][0] = xAxis.z; dst[2][1] = yAxis.z; dst[2][2] = zAxis.z; dst[2][3] = 0;\r \r dst[3][0] = -(xAxis.x * from.x + xAxis.y * from.y + xAxis.z * from.z);\r dst[3][1] = -(yAxis.x * from.x + yAxis.y * from.y + yAxis.z * from.z);\r dst[3][2] = -(zAxis.x * from.x + zAxis.y * from.y + zAxis.z * from.z);\r dst[3][3] = 1;\r \r return dst;\r \r let forward = normalize(from - to); \r \r let right = normalize(cross(up, forward)); \r \r let newup = cross(forward, right); \r let m = float4x4();\r m[0][0] = right.x, m[0][1] = right.y, m[0][2] = right.z; \r m[1][0] = newup.x, m[1][1] = newup.y, m[1][2] = newup.z; \r m[2][0] = forward.x, m[2][1] = forward.y, m[2][2] = forward.z; \r m[3][0] = from.x, m[3][1] = from.y, m[3][2] = from.z; \r \r return m;\r \r }\r \r \r pub fn perspective(fov: float, aspect: float, near: float, far: float) -> float4x4 {\r \r // set the basic projection matrix\r // let scale = 1.0 / tan(fov * 0.5 * PI / 180); \r // let M = float4x4();\r // M[0][0] = scale; //scale the x coordinates of the projected point \r // M[1][1] = scale * aspect; //scale the y coordinates of the projected point \r // M[2][2] = -far / (far - near); //used to remap z to [0,1] \r // M[3][2] = -far * near / (far - near); //used to remap z [0,1] \r // M[2][3] = -1; //set w = -z \r // M[3][3] = 0; \r \r //return M;\r \r let fovRad = radians(fov);\r let tanFov = tan( fovRad * 0.5 );\r \r let matrx = float4x4(\r 1.0 / (tanFov * aspect), 0, 0, 0,\r 0, 1.0 / tanFov, 0, 0,\r 0, 0, -((far + near)/(far - near)), -1,\r 0, 0, -((2*(near*far))/(far - near)), 0\r );\r \r return matrx;\r }\r \r pub fn perspectiveReverseZ(fov: float, aspect: float, near: float) -> float4 {\r // let scale = 1.0 / tan(fov * 0.5 * PI / 180);\r // let far = 10000000.0;\r // let M = float4x4();\r // M[0][0] = scale; //scale the x coordinates of the projected point \r // M[1][1] = scale * aspect; //scale the y coordinates of the projected point \r // M[2][2] = (-far / (far - near)) * -1; //used to remap z to [0,1] \r // M[3][2] = -far * near / (far - near); //used to remap z [0,1] \r // M[2][3] = 0; //set w = -z \r // M[3][3] = 0; \r // return M;\r \r let matrx = float4x4(\r 1, 0, 0, 0,\r 0, 1, 0, 0,\r 0, 0, -1, 0,\r 0, 0, 1, 1\r ) * matrix::perspective(fov, aspect, near, 10000000.0);\r \r return matrx;\r }\r }\r \r /**\r * Uses Super Sampling Anti Aliasing to smooth out the image.\r */\r pub fn screenAA(inScreenPos: float2, gridSize: int, func: (screenPos: float2) -> float4) {\r let weightSum = 0.0;\r let accumulatedColor = float4(0, 0, 0, 0);\r \r for (let y = 0; y < gridSize; y++) {\r for (let x = 0; x < gridSize; x++) {\r let offset = float2(\r (x + 0.5 - gridSize * 0.5) / gridSize,\r (y + 0.5 - gridSize * 0.5) / gridSize\r );\r \r let weight = exp(-dot(offset, offset) * 5); // Gaussian weight\r accumulatedColor += func(inScreenPos + offset) * weight;\r weightSum += weight;\r }\r }\r \r return accumulatedColor / weightSum;\r }\r \r \r // Color conversion helpers\r // A color = float4 containing rgba values in the range [0, 1]\r // All functions have an extra alpha functon and a reverse\r // i.e. hsl, hsla, hslFromColor, hslaFromColor\r // fn hsl(v: float3) -> float4\r \r pub fn hsl(v: float3) -> float4 {\r return hsla((v, 1));\r }\r \r pub fn hsla(v: float4) -> float4 {\r let h = v.x;\r let s = v.y;\r let l = v.z;\r let a = v.w;\r let c = (1 - abs(2 * l - 1)) * s;\r let x = c * (1 - abs(((h / 60) % 2) - 1));\r let m = l - c / 2;\r let r = 0.0;\r let g = 0.0;\r let b = 0.0;\r if (h < 60) {\r r = c;\r g = x;\r b = 0;\r } else if (h < 120) {\r r = x;\r g = c;\r b = 0;\r } else if (h < 180) {\r r = 0;\r g = c;\r b = x;\r } else if (h < 240) {\r r = 0;\r g = x;\r b = c;\r } else if (h < 300) {\r r = x;\r g = 0;\r b = c;\r } else {\r r = c;\r g = 0;\r b = x;\r }\r return float4(r + m, g + m, b + m, a);\r }\r \r pub fn hslFromColor(c: float4) -> float3 {\r let r = c.r;\r let g = c.g;\r let b = c.b;\r let a = c.a;\r let mx = max(r, max(g, b));\r let mn = min(r, min(g, b));\r let h = 0.0;\r let s = 0.0;\r let l = (mx + mn) / 2;\r if (mx == mn) {\r h = 0;\r s = 0;\r } else {\r let d = mx - mn;\r s = (l > 0.5) ? d / (2 - mx - mn) : d / (mx + mn);\r if (mx == r) {\r h = (g - b) / d + ((g < b) ? 6:0);\r } else if (mx == g) {\r h = (b - r) / d + 2;\r } else if (mx == b) {\r h = (r - g) / d + 4;\r }\r h /= 6;\r }\r return float3(h * 360, s, l);\r }\r \r pub fn hslaFromColor(c: float4) -> float4 {\r let hsl = hslFromColor(c);\r return float4(hsl, c.a);\r }\r \r pub fn hsv(v: float3) -> float4 {\r return hsva((v, 1));\r }\r \r pub fn hsva(val: float4) -> float4 {\r let h = val.x;\r let s = val.y;\r let v = val.z;\r let a = val.w;\r let c = v * s;\r let x = c * (1 - abs(mod(h / 60, 2) - 1));\r let m = v - c;\r let r = 0.0;\r let g = 0.0;\r let b = 0.0;\r if (h < 60) {\r r = c;\r g = x;\r b = 0;\r } else if (h < 120) {\r r = x;\r g = c;\r b = 0;\r } else if (h < 180) {\r r = 0;\r g = c;\r b = x;\r } else if (h < 240) {\r r = 0;\r g = x;\r b = c;\r } else if (h < 300) {\r r = x;\r g = 0;\r b = c;\r } else {\r r = c;\r g = 0;\r b = x;\r }\r return float4(r + m, g + m, b + m, a);\r }\r \r pub fn hsvFromColor(c: float4) -> float3 {\r let r = c.r;\r let g = c.g;\r let b = c.b;\r let mx = max(r, max(g, b));\r let mn = min(r, min(g, b));\r let h = 0.0;\r let s = 0.0;\r let v = mx;\r let d = mx - mn;\r s = (mx == 0) ? 0 : d / mx ;\r if (mx == mn) {\r h = 0;\r } else {\r if (mx == r) {\r h = (g - b) / d + ((g < b) ? 6 : 0 );\r } else if (mx == g) {\r h = (b - r) / d + 2;\r } else if (mx == b) {\r h = (r - g) / d + 4;\r }\r h /= 6;\r }\r return float3(h * 360, s, v);\r }\r \r pub fn hsvaFromColor(c: float4) -> float4 {\r let hsv = hsvFromColor(c);\r return float4(hsv, c.a);\r }\r \r pub fn rgb(v: float3) -> float4 {\r return float4(v / 255.0, 1);\r }\r \r pub fn rgba(v: float4) -> float4 {\r return float4(v / 255.0);\r }\r \r pub fn rgbFromColor(c: float4) -> float3 {\r return c.rgb * 255.0;\r }\r \r pub fn rgbaFromColor(c: float4) -> float4 {\r return c * 255.0;\r }\r \r pub fn cmyk(v: float4) -> float4 {\r let c = v.r;\r let m = v.g;\r let y = v.b;\r let k = v.a;\r let r = 1 - min(1, c * (1 - k) + k);\r let g = 1 - min(1, m * (1 - k) + k);\r let b = 1 - min(1, y * (1 - k) + k);\r return float4(r, g, b, 1);\r }\r \r pub fn cmykFromColor(c: float4) -> float4 {\r let r = c.r;\r let g = c.g;\r let b = c.b;\r let k = 1 - max(r, max(g, b));\r let c1 = (1 - r - k) / (1 - k);\r let m = (1 - g - k) / (1 - k);\r let y = (1 - b - k) / (1 - k);\r return float4(c1, m, y, k);\r }\r \r pub fn hex(v: int) -> float4 {\r let r: float = (v >> 16) & 0xFF;\r let g: float = (v >> 8) & 0xFF;\r let b: float = v & 0xFF;\r return float4(r / 255.0, g / 255.0, b / 255.0, 1.0);\r }\r \r pub fn hexFromColor(c: float4) -> int {\r let r = int(c.r * 255.0);\r let g = int(c.g * 255.0);\r let b = int(c.b * 255.0);\r return (r << 16) | (g << 8) | b;\r }\r \r /**\r * Returns sin remapped to [0, 1]\r */\r pub fn sin1(v: float) -> float {\r return (sin(v) + 1) * 0.5;\r }\r \r /**\r * Returns cos remapped to [0, 1]\r */\r pub fn cos1(v: float) -> float {\r return (cos(v) + 1) * 0.5;\r }\r \r /**\r * Returns tan remapped to [0, 1]\r */\r pub fn tan1(v: float) -> float {\r return (tan(v) + 1) * 0.5;\r }\r \r pub fn remap(v: float, low1: float, high1: float, low2: float, high2: float) -> float {\r return low2 + (v - low1) * (high2 - low2) / (high1 - low1);\r }\r \r pub fn remap1(v: float, low: float, high: float) -> float {\r return remap(v, low, high, 0, 1);\r }\r \r pub struct color {\r static slate50: float4 = float4(0.9725490196078431, 0.9803921568627451, 0.9882352941176471, 1);\r static slate100: float4 = float4(0.9450980392156862, 0.9607843137254902, 0.9764705882352941, 1);\r static slate200: float4 = float4(0.8862745098039215, 0.9098039215686274, 0.9411764705882353, 1);\r static slate300: float4 = float4(0.796078431372549, 0.8352941176470589, 0.8823529411764706, 1);\r static slate400: float4 = float4(0.5803921568627451, 0.6392156862745098, 0.7215686274509804, 1);\r static slate500: float4 = float4(0.39215686274509803, 0.4549019607843137, 0.5450980392156862, 1);\r static slate600: float4 = float4(0.2784313725490196, 0.3333333333333333, 0.4117647058823529, 1);\r static slate700: float4 = float4(0.2, 0.2549019607843137, 0.3333333333333333, 1);\r static slate800: float4 = float4(0.11764705882352941, 0.1607843137254902, 0.23137254901960785, 1);\r static slate900: float4 = float4(0.058823529411764705, 0.09019607843137255, 0.16470588235294117, 1);\r static slate950: float4 = float4(0.00784313725490196, 0.023529411764705882, 0.09019607843137255, 1);\r static gray50: float4 = float4(0.9764705882352941, 0.9803921568627451, 0.984313725490196, 1);\r static gray100: float4 = float4(0.9529411764705882, 0.9568627450980393, 0.9647058823529412, 1);\r static gray200: float4 = float4(0.8980392156862745, 0.9058823529411765, 0.9215686274509803, 1);\r static gray300: float4 = float4(0.8196078431372549, 0.8352941176470589, 0.8588235294117647, 1);\r static gray400: float4 = float4(0.611764705882353, 0.6392156862745098, 0.6862745098039216, 1);\r static gray500: float4 = float4(0.4196078431372549, 0.4470588235294118, 0.5019607843137255, 1);\r static gray600: float4 = float4(0.29411764705882354, 0.3333333333333333, 0.38823529411764707, 1);\r static gray700: float4 = float4(0.21568627450980393, 0.2549019607843137, 0.3176470588235294, 1);\r static gray800: float4 = float4(0.12156862745098039, 0.1607843137254902, 0.21568627450980393, 1);\r static gray900: float4 = float4(0.06666666666666667, 0.09411764705882353, 0.15294117647058825, 1);\r static gray950: float4 = float4(0.011764705882352941, 0.027450980392156862, 0.07058823529411765, 1);\r static zinc50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9803921568627451, 1);\r static zinc100: float4 = float4(0.9568627450980393, 0.9568627450980393, 0.9607843137254902, 1);\r static zinc200: float4 = float4(0.8941176470588236, 0.8941176470588236, 0.9058823529411765, 1);\r static zinc300: float4 = float4(0.8313725490196079, 0.8313725490196079, 0.8470588235294118, 1);\r static zinc400: float4 = float4(0.6313725490196078, 0.6313725490196078, 0.6666666666666666, 1);\r static zinc500: float4 = float4(0.44313725490196076, 0.44313725490196076, 0.47843137254901963, 1);\r static zinc600: float4 = float4(0.3215686274509804, 0.3215686274509804, 0.3568627450980392, 1);\r static zinc700: float4 = float4(0.24705882352941178, 0.24705882352941178, 0.27450980392156865, 1);\r static zinc800: float4 = float4(0.15294117647058825, 0.15294117647058825, 0.16470588235294117, 1);\r static zinc900: float4 = float4(0.09411764705882353, 0.09411764705882353, 0.10588235294117647, 1);\r static zinc950: float4 = float4(0.03529411764705882, 0.03529411764705882, 0.043137254901960784, 1);\r static neutral50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9803921568627451, 1);\r static neutral100: float4 = float4(0.9607843137254902, 0.9607843137254902, 0.9607843137254902, 1);\r static neutral200: float4 = float4(0.8980392156862745, 0.8980392156862745, 0.8980392156862745, 1);\r static neutral300: float4 = float4(0.8313725490196079, 0.8313725490196079, 0.8313725490196079, 1);\r static neutral400: float4 = float4(0.6392156862745098, 0.6392156862745098, 0.6392156862745098, 1);\r static neutral500: float4 = float4(0.45098039215686275, 0.45098039215686275, 0.45098039215686275, 1);\r static neutral600: float4 = float4(0.3215686274509804, 0.3215686274509804, 0.3215686274509804, 1);\r static neutral700: float4 = float4(0.25098039215686274, 0.25098039215686274, 0.25098039215686274, 1);\r static neutral800: float4 = float4(0.14901960784313725, 0.14901960784313725, 0.14901960784313725, 1);\r static neutral900: float4 = float4(0.09019607843137255, 0.09019607843137255, 0.09019607843137255, 1);\r static neutral950: float4 = float4(0.0392156862745098, 0.0392156862745098, 0.0392156862745098, 1);\r static stone50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9764705882352941, 1);\r static stone100: float4 = float4(0.9607843137254902, 0.9607843137254902, 0.9568627450980393, 1);\r static stone200: float4 = float4(0.9058823529411765, 0.8980392156862745, 0.8941176470588236, 1);\r static stone300: float4 = float4(0.8392156862745098, 0.8274509803921568, 0.8196078431372549, 1);\r static stone400: float4 = float4(0.6588235294117647, 0.6352941176470588, 0.6196078431372549, 1);\r static stone500: float4 = float4(0.47058823529411764, 0.44313725490196076, 0.4235294117647059, 1);\r static stone600: float4 = float4(0.3411764705882353, 0.3254901960784314, 0.3058823529411765, 1);\r static stone700: float4 = float4(0.26666666666666666, 0.25098039215686274, 0.23529411764705882, 1);\r static stone800: float4 = float4(0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1);\r static stone900: float4 = float4(0.10980392156862745, 0.09803921568627451, 0.09019607843137255, 1);\r static stone950: float4 = float4(0.047058823529411764, 0.0392156862745098, 0.03529411764705882, 1);\r static red50: float4 = float4(0.996078431372549, 0.9490196078431372, 0.9490196078431372, 1);\r static red100: float4 = float4(0.996078431372549, 0.8862745098039215, 0.8862745098039215, 1);\r static red200: float4 = float4(0.996078431372549, 0.792156862745098, 0.792156862745098, 1);\r static red300: float4 = float4(0.9882352941176471, 0.6470588235294118, 0.6470588235294118, 1);\r static red400: float4 = float4(0.9725490196078431, 0.44313725490196076, 0.44313725490196076, 1);\r static red500: float4 = float4(0.9372549019607843, 0.26666666666666666, 0.26666666666666666, 1);\r static red600: float4 = float4(0.8627450980392157, 0.14901960784313725, 0.14901960784313725, 1);\r static red700: float4 = float4(0.7254901960784313, 0.10980392156862745, 0.10980392156862745, 1);\r static red800: float4 = float4(0.6, 0.10588235294117647, 0.10588235294117647, 1);\r static red900: float4 = float4(0.4980392156862745, 0.11372549019607843, 0.11372549019607843, 1);\r static red950: float4 = float4(0.27058823529411763, 0.0392156862745098, 0.0392156862745098, 1);\r static orange50: float4 = float4(1, 0.9686274509803922, 0.9294117647058824, 1);\r static orange100: float4 = float4(1, 0.9294117647058824, 0.8352941176470589, 1);\r static orange200: float4 = float4(0.996078431372549, 0.8431372549019608, 0.6666666666666666, 1);\r static orange300: float4 = float4(0.9921568627450981, 0.7294117647058823, 0.4549019607843137, 1);\r static orange400: float4 = float4(0.984313725490196, 0.5725490196078431, 0.23529411764705882, 1);\r static orange500: float4 = float4(0.9764705882352941, 0.45098039215686275, 0.08627450980392157, 1);\r static orange600: float4 = float4(0.9176470588235294, 0.34509803921568627, 0.047058823529411764, 1);\r static orange700: float4 = float4(0.7607843137254902, 0.2549019607843137, 0.047058823529411764, 1);\r static orange800: float4 = float4(0.6039215686274509, 0.20392156862745098, 0.07058823529411765, 1);\r static orange900: float4 = float4(0.48627450980392156, 0.17647058823529413, 0.07058823529411765, 1);\r static orange950: float4 = float4(0.2627450980392157, 0.0784313725490196, 0.027450980392156862, 1);\r static amber50: float4 = float4(1, 0.984313725490196, 0.9215686274509803, 1);\r static amber100: float4 = float4(0.996078431372549, 0.9529411764705882, 0.7803921568627451, 1);\r static amber200: float4 = float4(0.9921568627450981, 0.9019607843137255, 0.5411764705882353, 1);\r static amber300: float4 = float4(0.9882352941176471, 0.8274509803921568, 0.30196078431372547, 1);\r static amber400: float4 = float4(0.984313725490196, 0.7490196078431373, 0.1411764705882353, 1);\r static amber500: float4 = float4(0.9607843137254902, 0.6196078431372549, 0.043137254901960784, 1);\r static amber600: float4 = float4(0.8509803921568627, 0.4666666666666667, 0.023529411764705882, 1);\r static amber700: float4 = float4(0.7058823529411765, 0.3254901960784314, 0.03529411764705882, 1);\r static amber800: float4 = float4(0.5725490196078431, 0.25098039215686274, 0.054901960784313725, 1);\r static amber900: float4 = float4(0.47058823529411764, 0.20784313725490197, 0.058823529411764705, 1);\r static amber950: float4 = float4(0.27058823529411763, 0.10196078431372549, 0.011764705882352941, 1);\r static yellow50: float4 = float4(0.996078431372549, 0.9882352941176471, 0.9098039215686274, 1);\r static yellow100: float4 = float4(0.996078431372549, 0.9764705882352941, 0.7647058823529411, 1);\r static yellow200: float4 = float4(0.996078431372549, 0.9411764705882353, 0.5411764705882353, 1);\r static yellow300: float4 = float4(0.9921568627450981, 0.8784313725490196, 0.2784313725490196, 1);\r static yellow400: float4 = float4(0.9803921568627451, 0.8, 0.08235294117647059, 1);\r static yellow500: float4 = float4(0.9176470588235294, 0.7019607843137254, 0.03137254901960784, 1);\r static yellow600: float4 = float4(0.792156862745098, 0.5411764705882353, 0.01568627450980392, 1);\r static yellow700: float4 = float4(0.6313725490196078, 0.3843137254901961, 0.027450980392156862, 1);\r static yellow800: float4 = float4(0.5215686274509804, 0.30196078431372547, 0.054901960784313725, 1);\r static yellow900: float4 = float4(0.44313725490196076, 0.24705882352941178, 0.07058823529411765, 1);\r static yellow950: float4 = float4(0.25882352941176473, 0.12549019607843137, 0.023529411764705882, 1);\r static lime50: float4 = float4(0.9686274509803922, 0.996078431372549, 0.9058823529411765, 1);\r static lime100: float4 = float4(0.9254901960784314, 0.9882352941176471, 0.796078431372549, 1);\r static lime200: float4 = float4(0.8509803921568627, 0.9764705882352941, 0.615686274509804, 1);\r static lime300: float4 = float4(0.7450980392156863, 0.9490196078431372, 0.39215686274509803, 1);\r static lime400: float4 = float4(0.6392156862745098, 0.9019607843137255, 0.20784313725490197, 1);\r static lime500: float4 = float4(0.5176470588235295, 0.8, 0.08627450980392157, 1);\r static lime600: float4 = float4(0.396078431372549, 0.6392156862745098, 0.050980392156862744, 1);\r static lime700: float4 = float4(0.30196078431372547, 0.48627450980392156, 0.058823529411764705, 1);\r static lime800: float4 = float4(0.24705882352941178, 0.3843137254901961, 0.07058823529411765, 1);\r static lime900: float4 = float4(0.21176470588235294, 0.3254901960784314, 0.0784313725490196, 1);\r static lime950: float4 = float4(0.10196078431372549, 0.1803921568627451, 0.0196078431372549, 1);\r static green50: float4 = float4(0.9411764705882353, 0.9921568627450981, 0.9568627450980393, 1);\r static green100: float4 = float4(0.8627450980392157, 0.9882352941176471, 0.9058823529411765, 1);\r static green200: float4 = float4(0.7333333333333333, 0.9686274509803922, 0.8156862745098039, 1);\r static green300: float4 = float4(0.5254901960784314, 0.9372549019607843, 0.6745098039215687, 1);\r static green400: float4 = float4(0.2901960784313726, 0.8705882352941177, 0.5019607843137255, 1);\r static green500: float4 = float4(0.13333333333333333, 0.7725490196078432, 0.3686274509803922, 1);\r static green600: float4 = float4(0.08627450980392157, 0.6392156862745098, 0.2901960784313726, 1);\r static green700: float4 = float4(0.08235294117647059, 0.5019607843137255, 0.23921568627450981, 1);\r static green800: float4 = float4(0.08627450980392157, 0.396078431372549, 0.20392156862745098, 1);\r static green900: float4 = float4(0.0784313725490196, 0.3254901960784314, 0.17647058823529413, 1);\r static green950: float4 = float4(0.0196078431372549, 0.1803921568627451, 0.08627450980392157, 1);\r static emerald50: float4 = float4(0.9254901960784314, 0.9921568627450981, 0.9607843137254902, 1);\r static emerald100: float4 = float4(0.8196078431372549, 0.9803921568627451, 0.8980392156862745, 1);\r static emerald200: float4 = float4(0.6549019607843137, 0.9529411764705882, 0.8156862745098039, 1);\r static emerald300: float4 = float4(0.43137254901960786, 0.9058823529411765, 0.7176470588235294, 1);\r static emerald400: float4 = float4(0.20392156862745098, 0.8274509803921568, 0.6, 1);\r static emerald500: float4 = float4(0.06274509803921569, 0.7254901960784313, 0.5058823529411764, 1);\r static emerald600: float4 = float4(0.0196078431372549, 0.5882352941176471, 0.4117647058823529, 1);\r static emerald700: float4 = float4(0.01568627450980392, 0.47058823529411764, 0.3411764705882353, 1);\r static emerald800: float4 = float4(0.023529411764705882, 0.37254901960784315, 0.27450980392156865, 1);\r static emerald900: float4 = float4(0.023529411764705882, 0.3058823529411765, 0.23137254901960785, 1);\r static emerald950: float4 = float4(0.00784313725490196, 0.17254901960784313, 0.13333333333333333, 1);\r static teal50: float4 = float4(0.9411764705882353, 0.9921568627450981, 0.9803921568627451, 1);\r static teal100: float4 = float4(0.8, 0.984313725490196, 0.9450980392156862, 1);\r static teal200: float4 = float4(0.6, 0.9647058823529412, 0.8941176470588236, 1);\r static teal300: float4 = float4(0.3686274509803922, 0.9176470588235294, 0.8313725490196079, 1);\r static teal400: float4 = float4(0.17647058823529413, 0.8313725490196079, 0.7490196078431373, 1);\r static teal500: float4 = float4(0.0784313725490196, 0.7215686274509804, 0.6509803921568628, 1);\r static teal600: float4 = float4(0.050980392156862744, 0.5803921568627451, 0.5333333333333333, 1);\r static teal700: float4 = float4(0.058823529411764705, 0.4627450980392157, 0.43137254901960786, 1);\r static teal800: float4 = float4(0.06666666666666667, 0.3686274509803922, 0.34901960784313724, 1);\r static teal900: float4 = float4(0.07450980392156863, 0.3058823529411765, 0.2901960784313726, 1);\r static teal950: float4 = float4(0.01568627450980392, 0.1843137254901961, 0.1803921568627451, 1);\r static cyan50: float4 = float4(0.9254901960784314, 0.996078431372549, 1, 1);\r static cyan100: float4 = float4(0.8117647058823529, 0.9803921568627451, 0.996078431372549, 1);\r static cyan200: float4 = float4(0.6470588235294118, 0.9529411764705882, 0.9882352941176471, 1);\r static cyan300: float4 = float4(0.403921568627451, 0.9098039215686274, 0.9764705882352941, 1);\r static cyan400: float4 = float4(0.13333333333333333, 0.8274509803921568, 0.9333333333333333, 1);\r static cyan500: float4 = float4(0.023529411764705882, 0.7137254901960784, 0.8313725490196079, 1);\r static cyan600: float4 = float4(0.03137254901960784, 0.5686274509803921, 0.6980392156862745, 1);\r static cyan700: float4 = float4(0.054901960784313725, 0.4549019607843137, 0.5647058823529412, 1);\r static cyan800: float4 = float4(0.08235294117647059, 0.3686274509803922, 0.4588235294117647, 1);\r static cyan900: float4 = float4(0.08627450980392157, 0.3058823529411765, 0.38823529411764707, 1);\r static cyan950: float4 = float4(0.03137254901960784, 0.2, 0.26666666666666666, 1);\r static sky50: float4 = float4(0.9411764705882353, 0.9764705882352941, 1, 1);\r static sky100: float4 = float4(0.8784313725490196, 0.9490196078431372, 0.996078431372549, 1);\r static sky200: float4 = float4(0.7294117647058823, 0.9019607843137255, 0.9921568627450981, 1);\r static sky300: float4 = float4(0.49019607843137253, 0.8274509803921568, 0.9882352941176471, 1);\r static sky400: float4 = float4(0.2196078431372549, 0.7411764705882353, 0.9725490196078431, 1);\r static sky500: float4 = float4(0.054901960784313725, 0.6470588235294118, 0.9137254901960784, 1);\r static sky600: float4 = float4(0.00784313725490196, 0.5176470588235295, 0.7803921568627451, 1);\r static sky700: float4 = float4(0.011764705882352941, 0.4117647058823529, 0.6313725490196078, 1);\r static sky800: float4 = float4(0.027450980392156862, 0.34901960784313724, 0.5215686274509804, 1);\r static sky900: float4 = float4(0.047058823529411764, 0.2901960784313726, 0.43137254901960786, 1);\r static sky950: float4 = float4(0.03137254901960784, 0.1843137254901961, 0.28627450980392155, 1);\r static blue50: float4 = float4(0.9372549019607843, 0.9647058823529412, 1, 1);\r static blue100: float4 = float4(0.8588235294117647, 0.9176470588235294, 0.996078431372549, 1);\r static blue200: float4 = float4(0.7490196078431373, 0.8588235294117647, 0.996078431372549, 1);\r static blue300: float4 = float4(0.5764705882352941, 0.7725490196078432, 0.9921568627450981, 1);\r static blue400: float4 = float4(0.3764705882352941, 0.6470588235294118, 0.9803921568627451, 1);\r static blue500: float4 = float4(0.23137254901960785, 0.5098039215686274, 0.9647058823529412, 1);\r static blue600: float4 = float4(0.1450980392156863, 0.38823529411764707, 0.9215686274509803, 1);\r static blue700: float4 = float4(0.11372549019607843, 0.3058823529411765, 0.8470588235294118, 1);\r static blue800: float4 = float4(0.11764705882352941, 0.25098039215686274, 0.6862745098039216, 1);\r static blue900: float4 = float4(0.11764705882352941, 0.22745098039215686, 0.5411764705882353, 1);\r static blue950: float4 = float4(0.09019607843137255, 0.1450980392156863, 0.32941176470588235, 1);\r static indigo50: float4 = float4(0.9333333333333333, 0.9490196078431372, 1, 1);\r static indigo100: float4 = float4(0.8784313725490196, 0.9058823529411765, 1, 1);\r static indigo200: float4 = float4(0.7803921568627451, 0.8235294117647058, 0.996078431372549, 1);\r static indigo300: float4 = float4(0.6470588235294118, 0.7058823529411765, 0.9882352941176471, 1);\r static indigo400: float4 = float4(0.5058823529411764, 0.5490196078431373, 0.9725490196078431, 1);\r static indigo500: float4 = float4(0.38823529411764707, 0.4, 0.9450980392156862, 1);\r static indigo600: float4 = float4(0.30980392156862746, 0.27450980392156865, 0.8980392156862745, 1);\r static indigo700: float4 = float4(0.2627450980392157, 0.2196078431372549, 0.792156862745098, 1);\r static indigo800: float4 = float4(0.21568627450980393, 0.18823529411764706, 0.6392156862745098, 1);\r static indigo900: float4 = float4(0.19215686274509805, 0.1803921568627451, 0.5058823529411764, 1);\r static indigo950: float4 = float4(0.11764705882352941, 0.10588235294117647, 0.29411764705882354, 1);\r static violet50: float4 = float4(0.9607843137254902, 0.9529411764705882, 1, 1);\r static violet100: float4 = float4(0.9294117647058824, 0.9137254901960784, 0.996078431372549, 1);\r static violet200: float4 = float4(0.8666666666666667, 0.8392156862745098, 0.996078431372549, 1);\r static violet300: float4 = float4(0.7686274509803922, 0.7098039215686275, 0.9921568627450981, 1);\r static violet400: float4 = float4(0.6549019607843137, 0.5450980392156862, 0.9803921568627451, 1);\r static violet500: float4 = float4(0.5450980392156862, 0.3607843137254902, 0.9647058823529412, 1);\r static violet600: float4 = float4(0.48627450980392156, 0.22745098039215686, 0.9294117647058824, 1);\r static violet700: float4 = float4(0.42745098039215684, 0.1568627450980392, 0.8509803921568627, 1);\r static violet800: float4 = float4(0.3568627450980392, 0.12941176470588237, 0.7137254901960784, 1);\r static violet900: float4 = float4(0.2980392156862745, 0.11372549019607843, 0.5843137254901961, 1);\r static violet950: float4 = float4(0.1803921568627451, 0.06274509803921569, 0.396078431372549, 1);\r static purple50: float4 = float4(0.9803921568627451, 0.9607843137254902, 1, 1);\r static purple100: float4 = float4(0.9529411764705882, 0.9098039215686274, 1, 1);\r static purple200: float4 = float4(0.9137254901960784, 0.8352941176470589, 1, 1);\r static purple300: float4 = float4(0.8470588235294118, 0.7058823529411765, 0.996078431372549, 1);\r static purple400: float4 = float4(0.7529411764705882, 0.5176470588235295, 0.9882352941176471, 1);\r static purple500: float4 = float4(0.6588235294117647, 0.3333333333333333, 0.9686274509803922, 1);\r static purple600: float4 = float4(0.5764705882352941, 0.2, 0.9176470588235294, 1);\r static purple700: float4 = float4(0.49411764705882355, 0.13333333333333333, 0.807843137254902, 1);\r static purple800: float4 = float4(0.4196078431372549, 0.12941176470588237, 0.6588235294117647, 1);\r static purple900: float4 = float4(0.34509803921568627, 0.10980392156862745, 0.5294117647058824, 1);\r static purple950: float4 = float4(0.23137254901960785, 0.027450980392156862, 0.39215686274509803, 1);\r static fuchsia50: float4 = float4(0.9921568627450981, 0.9568627450980393, 1, 1);\r static fuchsia100: float4 = float4(0.9803921568627451, 0.9098039215686274, 1, 1);\r static fuchsia200: float4 = float4(0.9607843137254902, 0.8156862745098039, 0.996078431372549, 1);\r static fuchsia300: float4 = float4(0.9411764705882353, 0.6705882352941176, 0.9882352941176471, 1);\r static fuchsia400: float4 = float4(0.9098039215686274, 0.4745098039215686, 0.9764705882352941, 1);\r static fuchsia500: float4 = float4(0.8509803921568627, 0.27450980392156865, 0.9372549019607843, 1);\r static fuchsia600: float4 = float4(0.7529411764705882, 0.14901960784313725, 0.8274509803921568, 1);\r static fuchsia700: float4 = float4(0.6352941176470588, 0.10980392156862745, 0.6862745098039216, 1);\r static fuchsia800: float4 = float4(0.5254901960784314, 0.09803921568627451, 0.5607843137254902, 1);\r static fuchsia900: float4 = float4(0.4392156862745098, 0.10196078431372549, 0.4588235294117647, 1);\r static fuchsia950: float4 = float4(0.2901960784313726, 0.01568627450980392, 0.3058823529411765, 1);\r static pink50: float4 = float4(0.9921568627450981, 0.9490196078431372, 0.9725490196078431, 1);\r static pink100: float4 = float4(0.9882352941176471, 0.9058823529411765, 0.9529411764705882, 1);\r static pink200: float4 = float4(0.984313725490196, 0.8117647058823529, 0.9098039215686274, 1);\r static pink300: float4 = float4(0.9764705882352941, 0.6588235294117647, 0.8313725490196079, 1);\r static pink400: float4 = float4(0.9568627450980393, 0.4470588235294118, 0.7137254901960784, 1);\r static pink500: float4 = float4(0.9254901960784314, 0.2823529411764706, 0.6, 1);\r static pink600: float4 = float4(0.8588235294117647, 0.15294117647058825, 0.4666666666666667, 1);\r static pink700: float4 = float4(0.7450980392156863, 0.09411764705882353, 0.36470588235294116, 1);\r static pink800: float4 = float4(0.615686274509804, 0.09019607843137255, 0.30196078431372547, 1);\r static pink900: float4 = float4(0.5137254901960784, 0.09411764705882353, 0.2627450980392157, 1);\r static pink950: float4 = float4(0.3137254901960784, 0.027450980392156862, 0.1411764705882353, 1);\r static rose50: float4 = float4(1, 0.9450980392156862, 0.9490196078431372, 1);\r static rose100: float4 = float4(1, 0.8941176470588236, 0.9019607843137255, 1);\r static rose200: float4 = float4(0.996078431372549, 0.803921568627451, 0.8274509803921568, 1);\r static rose300: float4 = float4(0.9921568627450981, 0.6431372549019608, 0.6862745098039216, 1);\r static rose400: float4 = float4(0.984313725490196, 0.44313725490196076, 0.5215686274509804, 1);\r static rose500: float4 = float4(0.9568627450980393, 0.24705882352941178, 0.3686274509803922, 1);\r static rose600: float4 = float4(0.8823529411764706, 0.11372549019607843, 0.2823529411764706, 1);\r static rose700: float4 = float4(0.7450980392156863, 0.07058823529411765, 0.23529411764705882, 1);\r static rose800: float4 = float4(0.6235294117647059, 0.07058823529411765, 0.2235294117647059, 1);\r static rose900: float4 = float4(0.5333333333333333, 0.07450980392156863, 0.21568627450980393, 1);\r static rose950: float4 = float4(0.2980392156862745, 0.0196078431372549, 0.09803921568627451, 1);\r \r }\r \r \r pub fn wrap2(value: float2, low: float, high: float) {\r return (wrap(value.x, low, high), wrap(value.y, low, high));\r }\r \r pub fn wrap3(value: float3, low: float, high: float) {\r return (wrap(value.x, low, high), wrap(value.y, low, high), wrap(value.z, low, high));\r }\r \r pub fn wrap4(value: float4, low: float, high: float) {\r return (wrap(value.x, low, high), wrap(value.y, low, high), wrap(value.z, low, high), wrap(value.w, low, high));\r }`; const sdf = "/**\r\n* Heplful utility for working with signed distance fields.\r\n* Most of the implementation was taken from https://iquilezles.org/articles/distfunctions/\r\n*/\r\n\r\npub struct sdf {}\r\n\r\nfn dot2( v: float2 ) -> float { return dot(v,v); }\r\nfn dot3( v: float3 ) -> float { return dot(v,v); }\r\nfn ndot( a: float2, b: float2 ) -> float { return a.x*b.x - a.y*b.y; }\r\n\r\nimpl sdf {\r\n pub fn sphere(samplePosition: float3, sphereCenter: float3, radius: float) -> float {\r\n let p = samplePosition - sphereCenter;\r\n let r = radius;\r\n return length(p) - r;\r\n }\r\n\r\n pub fn box(samplePosition: float3, boxCenter: float3, boxSize: float3) -> float {\r\n let p = samplePosition - boxCenter;\r\n let s = boxSize;\r\n let q = abs(p) - s;\r\n return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.0);\r\n }\r\n\r\n pub fn roundBox(samplePosition: float3, boxCenter: float3, boxSize: float3, cornerRadius: float) -> float {\r\n let p = samplePosition - boxCenter;\r\n let s = boxSize;\r\n let r = cornerRadius;\r\n let q = abs(p) - s;\r\n return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;\r\n }\r\n\r\n pub fn boxFrame(samplePosition: float3, boxCenter: float3, boxSize: float3, frameThickness: float) -> float {\r\n let p = samplePosition - boxCenter;\r\n let b = boxSize;\r\n let e = frameThickness;\r\n p = abs(p )-b;\r\n let q = abs(p+e)-e;\r\n return min(min(\r\n length(max(float3(p.x,q.y,q.z),0.0))+min(max(p.x,max(q.y,q.z)),0.0),\r\n length(max(float3(q.x,p.y,q.z),0.0))+min(max(q.x,max(p.y,q.z)),0.0)),\r\n length(max(float3(q.x,q.y,p.z),0.0))+min(max(q.x,max(q.y,p.z)),0.0));\r\n }\r\n\r\n pub fn torus( samplePosition: float3, torusCenter: float3, torusSize: float2 ) -> float\r\n {\r\n let p = samplePosition - torusCenter;\r\n let t = torusSize;\r\n let q = float2(length(p.xz)-t.x,p.y);\r\n return length(q)-t.y;\r\n }\r\n\r\n pub fn cappedTorus( samplePosition: float3, torusCenter: float3, torusSize: float2, ra: float, rb: float) -> float\r\n {\r\n \r\n let p1 = samplePosition - torusCenter;\r\n let p = (abs(p1.x), p1.yz);\r\n let sc = torusSize;\r\n let k = (sc.y*p.x>sc.x*p.y) ? dot(p.xy,sc) : length(p.xy);\r\n return sqrt( dot(p,p) + ra*ra - 2.0*ra*k ) - rb;\r\n }\r\n\r\n pub fn link( samplePosition: float3, linkCenter: float3, linkLength: float, r1: float, r2: float ) -> float\r\n {\r\n let p = samplePosition - linkCenter;\r\n let le = linkLength;\r\n let q = float3( p.x, max(abs(p.y)-le,0.0), p.z );\r\n return length(float2(length(q.xy)-r1,q.z)) - r2;\r\n }\r\n\r\n pub fn infinteCylinder( samplePosition: float3, cylinderCenter: float3, cylinderSize: float3) -> float\r\n {\r\n let p = samplePosition - cylinderCenter;\r\n let c = cylinderSize;\r\n return length(p.xz-c.xy)-c.z;\r\n }\r\n\r\n pub fn cone( samplePosition: float3, coneCenter: float3, c: float2, coneHeight: float ) -> float\r\n {\r\n let p = samplePosition - coneCenter;\r\n let h = coneHeight;\r\n // c is the sin/cos of the angle, h is height\r\n // Alternatively pass q instead of (c,h),\r\n // which is the point at the base in 2D\r\n let q = h*float2(c.x/c.y,-1.0);\r\n \r\n let w = float2( length(p.xz), p.y );\r\n let a = w - q*clamp( dot(w,q)/dot(q,q), 0.0, 1.0 );\r\n let b = w - q*float2( clamp( w.x/q.x, 0.0, 1.0 ), 1.0 );\r\n let k = sign( q.y );\r\n let d = min(dot( a, a ),dot(b, b));\r\n let s = max( k*(w.x*q.y-w.y*q.x),k*(w.y-q.y) );\r\n return sqrt(d)*sign(s);\r\n }\r\n\r\n pub fn plane( samplePosition: float3, planeCenter: float3, planeNormal: float3, planeHeight: float ) -> float\r\n {\r\n let p = samplePosition - planeCenter;\r\n let n = planeNormal;\r\n let h = planeHeight;\r\n \r\n // n must be normalized\r\n return dot(p,n) + h;\r\n }\r\n\r\n pub fn hexPrism( samplePosition: float3, hexCenter: float3, hexSize: float2 ) -> float\r\n {\r\n let p = samplePosition - hexCenter;\r\n let h = hexSize;\r\n\r\n let k = float3(-0.8660254, 0.5, 0.57735);\r\n p = abs(p);\r\n let dddd = min(dot(k.xy, p.xy), 0.0) * 2.0;\r\n\r\n p = p - float3(dddd * k.xy, 0.0);\r\n let d = float2(\r\n length(p.xy-float2(clamp(p.x,-k.z*h.x,k.z*h.x), h.x))*sign(p.y-h.x),\r\n p.z-h.y );\r\n return min(max(d.x,d.y),0.0) + length(max(d,0.0));\r\n }\r\n\r\n pub fn triPrism( samplePosition: float3, triCenter: float3, triSize: float2 ) -> float\r\n {\r\n let p = samplePosition - triCenter;\r\n let h = triSize;\r\n let q = abs(p);\r\n return max(q.z-h.y,max(q.x*0.866025+p.y*0.5,-p.y)-h.x*0.5);\r\n }\r\n\r\n pub fn capsuleLine( samplePosition: float3, lineStart: float3, lineEnd: float3, capsuleRadius: float ) -> float\r\n {\r\n let p = samplePosition;\r\n let a = lineStart;\r\n let b = lineEnd;\r\n let r = capsuleRadius;\r\n let pa = p - a;\r\n let ba = b - a;\r\n let h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );\r\n return length( pa - ba*h ) - r;\r\n }\r\n\r\n pub fn capsule( samplePosition: float3, capsuleCenter: float3, height: float, radius: float ) -> float\r\n {\r\n let p1 = samplePosition - capsuleCenter;\r\n let h = height;\r\n let r = radius;\r\n let p = (p1.x, p1.y - clamp( p1.y, 0.0, h ), p1.z);\r\n return length( p ) - r;\r\n }\r\n\r\n pub fn cylinder( samplePosition: float3, cylinderCenter: float3, height: float, radius: float ) -> float\r\n {\r\n let p = samplePosition - cylinderCenter;\r\n let h = height;\r\n let r = radius;\r\n let d = abs(float2(length(p.xz),p.y)) - float2(r,h);\r\n return min(max(d.x,d.y),0.0) + length(max(d,0.0));\r\n }\r\n\r\n pub fn cylinderLine( samplePosition: float3, lineStart: float3, lineEnd: float3, radius: float) -> float\r\n {\r\n let p = samplePosition;\r\n let a = lineStart;\r\n let b = lineEnd;\r\n let r = radius;\r\n\r\n let ba = b - a;\r\n let pa = p - a;\r\n let baba = dot(ba,ba);\r\n let paba = dot(pa,ba);\r\n let x = length(pa*baba-ba*paba) - r*baba;\r\n let y = abs(paba-baba*0.5) - baba*0.5;\r\n let x2 = x*x;\r\n let y2 = y*y*baba;\r\n let mxxy = max(x,y);\r\n let d = (mxxy<0.0)?-min(x2,y2):(((x>0.0)?x2:0.0)+((y>0.0)?y2:0.0));\r\n return sign(d)*sqrt(abs(d))/baba;\r\n }\r\n\r\n pub fn roundedCylinder( samplePosition: float3, cylinderCenter: float, cylinderRadius: float, cornerRadius: float, height: float ) -> float\r\n {\r\n let p = samplePosition - cylinderCenter;\r\n let h = height;\r\n let ra = cylinderRadius;\r\n let rb = cornerRadius;\r\n let d = float2( length(p.xz)-2.0*ra+rb, abs(p.y) - h );\r\n return min(max(d.x,d.y),0.0) + length(max(d,0.0)) - rb;\r\n }\r\n\r\n pub fn cappedCone( samplePosition: float3, coneCenter: float3, height: float, r1: float, r2: float ) -> float\r\n {\r\n let p = samplePosition - coneCenter;\r\n let h = height;\r\n\r\n let q = float2( length(p.xz), p.y );\r\n let k1 = float2(r2,h);\r\n let k2 = float2(r2-r1,2.0*h);\r\n let ca = float2(q.x-min(q.x,(q.y<0.0)?r1:r2), abs(q.y)-h);\r\n let cb = q - k1 + k2*clamp( dot(k1-q,k2)/dot2(k2), 0.0, 1.0 );\r\n let s = (cb.x<0.0 && ca.y<0.0) ? -1.0 : 1.0;\r\n return s*sqrt( min(dot2(ca),dot2(cb)) );\r\n }\r\n\r\n pub fn solidAngle( samplePosition: float3, solidCenter: float3, size: float2, radius: float) -> float\r\n {\r\n let p = samplePosition - solidCenter;\r\n let c = size;\r\n let ra = radius;\r\n // c is the sin/cos of the angle\r\n let q = float2( length(p.xz), p.y );\r\n let l = length(q) - ra;\r\n let m = length(q - c*clamp(dot(q,c),0.0,ra) );\r\n return max(l,m*sign(c.y*q.x-c.x*q.y));\r\n }\r\n\r\n pub fn cutSphere( samplePosition: float3, sphereCenter: float3, radius: float, height: float ) -> float\r\n {\r\n let p = samplePosition - sphereCenter;\r\n let h = height;\r\n let r = radius;\r\n\r\n // sampling independent computations (only depend on shape)\r\n let w = sqrt(r*r-h*h);\r\n\r\n // sampling dependant computations\r\n let q = float2( length(p.xz), p.y );\r\n let s = max( (h-r)*q.x*q.x+w*w*(h+r-2.0*q.y), h*q.x-w*q.y );\r\n return (s<0.0) ? length(q)-r :\r\n (q.x float\r\n {\r\n let p = samplePosition - sphereCenter;\r\n let r = radius;\r\n let h = height;\r\n let t = thickness;\r\n\r\n // sampling independent computations (only depend on shape)\r\n let w = sqrt(r*r-h*h);\r\n\r\n // sampling dependant computations\r\n let q = float2( length(p.xz), p.y );\r\n return ((h*q.x float\r\n {\r\n let p = samplePosition - coneCenter;\r\n let h = height;\r\n let r1 = coneRadius;\r\n let r2 = cornerRadius;\r\n\r\n // sampling independent computations (only depend on shape)\r\n let b = (r1-r2)/h;\r\n let a = sqrt(1.0-b*b);\r\n\r\n // sampling dependant computations\r\n let q = float2( length(p.xz), p.y );\r\n let k = dot(q,float2(-b,a));\r\n if( k<0.0 ) return length(q) - r1;\r\n if( k>a*h ) return length(q-float2(0.0,h)) - r2;\r\n return dot(q, float2(a,b) ) - r1;\r\n }\r\n\r\n pub fn ellipsoid( samplePosition: float3, center: float3, radius: float3 ) -> float\r\n { \r\n let p = samplePosition - center;\r\n let r = radius;\r\n let k0 = length(p/r);\r\n let k1 = length(p/(r*r));\r\n return k0*(k0-1.0)/k1;\r\n }\r\n\r\n pub fn rhombus( samplePosition: float3, rhombusCenter: float3, la: float, lb: float, height: float, ra: float) -> float\r\n {\r\n let p = samplePosition - rhombusCenter;\r\n let h = height;\r\n\r\n p = abs(p);\r\n let b = float2(la,lb);\r\n let f = clamp( (ndot(b,b-2.0*p.xz))/dot(b,b), -1.0, 1.0 );\r\n let q = float2(length(p.xz-0.5*b*float2(1.0-f,1.0+f))*sign(p.x*b.y+p.z*b.x-b.x*b.y)-ra, p.y-h);\r\n return min(max(q.x,q.y),0.0) + length(max(q,0.0));\r\n }\r\n\r\n pub fn octahedron( samplePosition: float3, center: float3, size: float) -> float\r\n {\r\n let p = samplePosition - center;\r\n let s = size;\r\n p = abs(p);\r\n let m = p.x+p.y+p.z-s;\r\n let q = 0.0.xyz;\r\n if( 3.0*p.x < m ) q = p.xyz;\r\n else if( 3.0*p.y < m ) q = p.yzx;\r\n else if( 3.0*p.z < m ) q = p.zxy;\r\n else return m*0.57735027;\r\n \r\n let k = clamp(0.5*(q.z-q.y+s),0.0,s); \r\n return length(float3(q.x,q.y-s+k,q.z-k)); \r\n }\r\n\r\n pub fn pyramid( samplePosition: float3, pyramidCenter: float3, height: float) -> float\r\n {\r\n let p1 = samplePosition - pyramidCenter;\r\n let h = height;\r\n\r\n let m2 = h*h + 0.25;\r\n \r\n let p2 = (abs(p1.x), p1.y, abs(p1.z));\r\n if (p1.z > p1.x) {\r\n p2 = (p2.z, p2.y, p2.x);\r\n }\r\n p2 = (p2.x - 0.5, p2.y, p2.z - 0.5);\r\n let p = p2;\r\n\r\n let q = float3( p.z, h*p.y - 0.5*p.x, h*p.x + 0.5*p.y);\r\n \r\n let s = max(-q.x,0.0);\r\n let t = clamp( (q.y-0.5*p.z)/(m2+0.25), 0.0, 1.0 );\r\n \r\n let a = m2*(q.x+s)*(q.x+s) + q.y*q.y;\r\n let b = m2*(q.x+0.5*t)*(q.x+0.5*t) + (q.y-m2*t)*(q.y-m2*t);\r\n \r\n let d2 = min(q.y,-q.x*m2-q.y*0.5) > 0.0 ? 0.0 : min(a,b);\r\n \r\n return sqrt( (d2+q.z*q.z)/m2 ) * sign(max(q.z,-p.y));\r\n }\r\n\r\n pub fn udTriangle( samplePosition: float3, a: float3, b: float3, c: float3 ) -> float\r\n {\r\n let p = samplePosition;\r\n let ba = b - a;\r\n let pa = p - a;\r\n let cb = c - b;\r\n let pb = p - b;\r\n let ac = a - c;\r\n let pc = p - c;\r\n let nor = cross( ba, ac );\r\n\r\n return sqrt(\r\n (sign(dot(cross(ba,nor),pa)) +\r\n sign(dot(cross(cb,nor),pb)) +\r\n sign(dot(cross(ac,nor),pc))<2.0)\r\n ?\r\n min( min(\r\n dot3(ba*clamp(dot(ba,pa)/dot3(ba),0.0,1.0) - pa),\r\n dot3(cb*clamp(dot(cb,pb)/dot3(cb),0.0,1.0) - pb) ),\r\n dot3(ac*clamp(dot(ac,pc)/dot3(ac),0.0,1.0) - pc) )\r\n :\r\n dot(nor,pa)*dot(nor,pa)/dot3(nor) );\r\n }\r\n\r\n pub fn udQuad( samplePosition: float3, a: float3, b: float3, c: float3, d: float3 ) -> float\r\n {\r\n let p = samplePosition;\r\n let ba = b - a; let pa = p - a;\r\n let cb = c - b; let pb = p - b;\r\n let dc = d - c; let pc = p - c;\r\n let ad = a - d; let pd = p - d;\r\n let nor = cross( ba, ad );\r\n\r\n return sqrt(\r\n (sign(dot(cross(ba,nor),pa)) +\r\n sign(dot(cross(cb,nor),pb)) +\r\n sign(dot(cross(dc,nor),pc)) +\r\n sign(dot(cross(ad,nor),pd))<3.0)\r\n ?\r\n min( min( min(\r\n dot3(ba*clamp(dot(ba,pa)/dot3(ba),0.0,1.0)-pa),\r\n dot3(cb*clamp(dot(cb,pb)/dot3(cb),0.0,1.0)-pb) ),\r\n dot3(dc*clamp(dot(dc,pc)/dot3(dc),0.0,1.0)-pc) ),\r\n dot3(ad*clamp(dot(ad,pd)/dot3(ad),0.0,1.0)-pd) )\r\n :\r\n dot(nor,pa)*dot(nor,pa)/dot3(nor) );\r\n }\r\n\r\n\r\n /**\r\n * Returns the intersection of two SDFs\r\n * = max(a, b)\r\n */\r\n pub fn intersect(a: float, b: float) -> float {\r\n return max(a, b);\r\n }\r\n\r\n /**\r\n * Returns the union of two SDFs\r\n * = min(a, b)\r\n */\r\n pub fn union(a: float, b: float) -> float {\r\n return min(a, b);\r\n }\r\n\r\n pub fn subtract(a: float, b: float) -> float {\r\n return max(-a, b);\r\n }\r\n\r\n pub fn smoothIntersect(a: float, b: float, k: float) -> float {\r\n let h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);\r\n return lerp(b, a, h) - k * h * (1.0 - h);\r\n }\r\n\r\n /**\r\n * Smoothly joins two SDFs using blending distance k\r\n */\r\n pub fn smoothUnion(a: float, b: float, k: float) -> float {\r\n let d1 = a;\r\n let d2 = b;\r\n let h = clamp( 0.5 + 0.5*(d2-d1)/k, 0.0, 1.0 );\r\n return lerp( d2, d1, h ) - k*h*(1.0-h);\r\n }\r\n\r\n pub fn smoothSubtract(a: float, b: float, k: float) -> float {\r\n let d1 = a;\r\n let d2 = b;\r\n let h = clamp( 0.5 - 0.5*(d2+d1)/k, 0.0, 1.0 );\r\n return lerp( d2, -d1, h ) + k*h*(1.0-h); \r\n }\r\n\r\n /**\r\n * Blends between two SDFs using interpolation\r\n */\r\n pub fn blend(a: float, b: float, t: float) -> float {\r\n return t * a + (1 - t) * b;\r\n }\r\n\r\n pub fn round(a: float, r: float) -> float {\r\n return a - r;\r\n }\r\n\r\n /**\r\n * Carve out the interior of an SDF\r\n */\r\n pub fn onion(a: float, thickness: float) -> float {\r\n return abs(a) - thickness;\r\n }\r\n\r\n\r\n pub fn grad(p:float3, sampler: (pos: float3) -> float) {\r\n const DELTA = 0.0001;\r\n return float3(sampler(p + float3(DELTA, 0.0, 0.0)) - sampler(p - float3(DELTA, 0.0, 0.0)),\r\n sampler(p + float3(0.0, DELTA, 0.0)) - sampler(p - float3(0.0, DELTA, 0.0)),\r\n sampler(p + float3(0.0, 0.0, DELTA)) - sampler(p - float3(0.0, 0.0, DELTA))) / (2.0 * DELTA);\r\n }\r\n\r\n /**\r\n * Poorly returns the closest point on the surface of an SDF\r\n * This is an inaccurate method\r\n */\r\n pub fn closest(position: float3, sampler: (pos: float3) -> float) -> float3 {\r\n let sep = 0.0001;\r\n let zero = min(env.frame, 0);\r\n let closest = position;\r\n let initialDist = sampler(position);\r\n let seed = 0;\r\n for (let j: int = 0; j < 200; j++) {\r\n let n = 0.0.xyz;\r\n let distSum = 0.0;\r\n for (let i: int = zero; i < 4; i++) {\r\n let e = 0.5773*(2.0*float3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0);\r\n let d = sampler(closest+e*sep);\r\n distSum += d;\r\n n += e*d;\r\n }\r\n closest = normalize(n) * distSum * -1 / 4.0 + closest;\r\n if (distSum < 0.0001) {\r\n break;\r\n }\r\n }\r\n\r\n return closest;\r\n }\r\n\r\n pub fn normal(position: float3, sampler: (pos: float3) -> float) -> float3 {\r\n const h = 0.1;\r\n let zero = min(env.frame, 0);\r\n let n = 0.0.xyz;\r\n let distSum = 0.0;\r\n \r\n for (let i: int = zero; i < 4; i++) {\r\n let e = 0.5773*(2.0*float3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0);\r\n let d = sampler(position+e*h);\r\n distSum += d;\r\n n += e*d;\r\n }\r\n return normalize(n);\r\n }\r\n\r\n pub fn vizRings(d: float) -> float4 {\r\n if (false) {\r\n let color = 1.0 - sign(d) * float3(0.1, 0.4, 0.7);\r\n color *= 1.0 - exp(-4.0 * abs(d));\r\n color *= 0.8 + 0.2 * cos(140.0 * d);\r\n color = lerp(color, 1.0.xyz, 1.0 - smoothstep(0.0, 0.015, abs(d)));\r\n return (color, 1.0);\r\n }else{\r\n\r\n let size = 2;\r\n let fadeDist = 100;\r\n let v = 1-clamp(d/ fadeDist, 0, 1);\r\n let color = (0.4 * v, 0.6* v, 1, 1);\r\n let s = sin(d / size);\r\n if (abs(d) < 1) {\r\n return float4(1.xyzw);\r\n }else{\r\n return d > 0 ? color * ceil(1-s) : color * ceil(s);\r\n }\r\n }\r\n }\r\n\r\n pub fn march(position: float3, direction: float3, sampler: (pos: float3) -> float) -> float {\r\n let maxDist = 100000.0;\r\n let minDist = 1.0;\r\n let dist = minDist;\r\n\r\n for (let i = 0; i < 256 && dist < maxDist; i++) {\r\n let samp = sampler(position + direction * dist);\r\n dist += samp;\r\n if (abs(samp) < (0.00005 * dist)) {\r\n break;\r\n }\r\n }\r\n if (dist > maxDist) {\r\n dist = -1.0;\r\n }\r\n return dist;\r\n }\r\n\r\n /**\r\n * See: https://iquilezles.org/articles/distfunctions/\r\n * Infinitely repeats an SDF with space in between. This returns an updated position\r\n *\r\n * Example:\r\n * ```shadeup\r\n * sdf::sphere(sdf::repeat(p, 100.xyz), 0.xyz, 50.0);\r\n * ```\r\n */\r\n pub fn repeat(position: float3, space: float3) -> float3 {\r\n let p = position;\r\n let s = space;\r\n return p - s*round(p/s);\r\n }\r\n\r\n /**\r\n * See: https://iquilezles.org/articles/distfunctions/\r\n * Repeats an SDF with space in between upto the limit. This returns an updated position\r\n *\r\n * Example:\r\n * ```shadeup\r\n * sdf::sphere(sdf::repeatLimited(p, 100, 10.xyz), 0.xyz, 50.0);\r\n * ```\r\n */\r\n pub fn repeatLimited(position: float3, space: float, limit: float3) -> float3 {\r\n let p = position;\r\n let s = space;\r\n return p - s*clamp(round(p/s),-limit,limit);\r\n }\r\n \r\n}"; const files = { shadeup: { mesh, textures, common, sdf, geo }, ts: { std, ui, native, paint, buffer, texture, drawIndexed, drawAttributes, drawCount, physics, context } }; async function makeSimpleShadeupEnvironment(esnext = false, declaration = false) { let env2 = new ShadeupEnvironment({ esnext, declaration }); env2.emitLogs = false; await env2.init(); await env2.writeFile( "/file.ts", ` ` ); let writes = []; performance.now(); for (let [path, contents] of Object.entries(files.ts)) { let p = "/_std/" + path + ".ts"; if (path == "std") p = "/std.ts"; writes.push(env2.writeFileTypescript(p, contents)); } for (let [path, contents] of Object.entries(files.shadeup)) { let p = "/_std/" + path + ".ts"; writes.push(env2.writeFile(p, contents, true)); } return env2; } export { makeSimpleShadeupEnvironment }; ================================================ FILE: cli/electron/index.html ================================================ Shadeup Preview ================================================ FILE: cli/electron/main.js ================================================ import { app, BrowserWindow } from "electron/main"; import path from "node:path"; const __dirname = path.dirname( new URL(import.meta.url).pathname.replace(/^\//g, "") ); function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, autoHideMenuBar: true, icon: path.join(__dirname, "icon.ico"), webPreferences: {}, }); win.loadFile("index.html"); } app.whenReady().then(() => { createWindow(); app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } }); }); app.on("window-all-closed", () => { if (process.platform !== "darwin") { app.quit(); } }); ================================================ FILE: cli/index.js ================================================ throw new Error("This is a CLI only package"); ================================================ FILE: cli/package.json ================================================ { "name": "@shadeup/cli", "version": "1.3.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "cli": "node cli.js" }, "bin": { "shadeup": "./cli.js" }, "repository": { "type": "git", "url": "https://github.com/AskingQuestions/Shadeup" }, "author": "AskingQuestions ", "license": "MIT", "dependencies": { "@typescript/vfs": "^1.5.0", "boxen": "^7.0.0", "colors": "^1.4.0", "commander": "^9.2.0", "electron": "^28.2.2", "inquirer": "^8.2.4", "shadeup": "^1.3.6", "typescript": "^5.3.3", "uglify-js": "^3.17.4", "vite": "^5.1.1", "web-tree-sitter": "^0.20.8" } } ================================================ FILE: cli/test/main.d.ts ================================================ import * as __ from "/std_math"; export declare function main(): void; export declare function giveFloat(): __.float; ================================================ FILE: cli/test/main.js ================================================ import { bindShadeupEngine } from "shadeup"; export const makeShadeupInstance = bindShadeupEngine((define, localEngineContext) => { const __shadeup_gen_shader = localEngineContext.__shadeup_gen_shader.bind(localEngineContext); const __shadeup_make_shader_inst = localEngineContext.__shadeup_make_shader_inst.bind(localEngineContext); const __shadeup_register_struct = localEngineContext.__shadeup_register_struct.bind(localEngineContext); ((defineFunc) => { let define = (deps, func) => defineFunc("/main.js", deps, func); __shadeup_gen_shader("shd_6515406754369975000349600057000435695077700680380", { webgl: {}, webgpu: {"attributeInput":"","attributeOutput":"","locals":[],"globals":[]} }, {webgpu: `fn shadeup_up_swizzle_xxxx_i32(n: i32) -> vec4{ return vec4(n, n, n, n); } struct ShaderInput { @align(16) position: vec3, @align(16) normal: vec3, @align(16) tangent: vec3, @align(16) bitangent: vec3, @align(16) clipPosition: vec4, @align(16) realPosition: vec4, @align(16) uv: vec2, @align(16) screen: vec2, @align(16) color: vec4, @align(16) groupId: vec3, @align(16) groupSize: vec3, @align(16) globalId: vec3, @align(16) localId: vec3, @align(16) instanceIndex: i32, @align(16) vertexIndex: i32, }; struct ShaderOutput { @align(16) position: vec4, @align(16) normal: vec3, @align(16) tangent: vec3, @align(16) bitangent: vec3, @align(16) uv: vec2, @align(16) color: vec4, // %SHADER_ShaderOutput% }; struct _InUniformsStruct { /*SHADEUP_UNIFORM_STRUCT_START*/ dummy: vec4, }; @group(%GROUP_INDEX%) @binding(1) var _in_uniforms: _InUniformsStruct; /*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/ fn main(/*__SHADEUP_TEMPLATE_INPUT*/)-> /*__SHADEUP_TEMPLATE_OUTPUT*/{ /*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/ _i_out.color = vec4f(shadeup_up_swizzle_xxxx_i32(i32(1))); /*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/ } `,webgl:`ivec4 shadeup_up_swizzle_xxxx_int(int n) { return ivec4(n, n, n, n); } ivec4 shadeup_up_swizzle_xxxx_int(int n) { return ivec4(n, n, n, n); } ivec2 shadeup_up_swizzle_xy_int(int n) { return ivec2(n, n); } ivec3 shadeup_up_swizzle_xyz_int(int n) { return ivec3(n, n, n); } ivec4 shadeup_up_swizzle_xxxx_int(int n) { return ivec4(n, n, n, n); } ivec2 shadeup_up_swizzle_xy_int(int n) { return ivec2(n, n); } ivec3 shadeup_up_swizzle_xyz_int(int n) { return ivec3(n, n, n); } ivec4 shadeup_up_swizzle_xyzw_int(int n) { return ivec4(n, n, n, n); } ivec4 shadeup_up_swizzle_xxxx_int(int n) { return ivec4(n, n, n, n); } struct ShaderInput { vec3 position; vec3 normal; vec3 tangent; vec3 bitangent; vec4 clipPosition; vec4 realPosition; vec2 uv; vec2 screen; vec4 color; ivec3 groupId; ivec3 groupSize; ivec3 globalId; ivec3 localId; int instanceIndex; int vertexIndex; }; struct ShaderOutput { vec4 position; vec3 normal; vec3 tangent; vec3 bitangent; vec2 uv; vec4 color; }; /*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/ void main() { /*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/ _i_out.color = vec4(shadeup_up_swizzle_xxxx_int(int(1))); /*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/ } `, software: () => {}}, [[2830,2865,21,38],[2939,2972,38,53],[3048,3082,53,69],[3162,3198,69,87],[3242,3284,87,108],[3289,3331,108,129],[3400,3426,129,140],[3502,3532,140,155],[3609,3644,155,169],[3690,3720,169,186],[3768,3800,186,205],[3879,3910,205,223],[3956,3986,223,240],[4051,4074,240,261],[4123,4144,261,280],[2728,4283,0,284],[4371,4409,306,323],[4444,4477,323,338],[4513,4547,338,354],[4585,4621,354,372],[4655,4681,372,383],[4714,4749,383,397],[4309,4869,284,401],[0,0,503,509],[0,0,510,515],[0,0,503,515],[1882,1888,551,554],[0,0,555,556],[0,0,551,557],[0,0,523,558],[0,0,503,559],[0,0,503,561],[57,87,401,605],[1839,1903,0,605]]); var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; define(["require", "exports", "/std_math", "/std___std_all", "/_std/drawIndexed"], function (require, exports, __, std___std_all_1, drawIndexed_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.giveFloat = exports.main = void 0; __ = __importStar(__); var globalVarGet = std___std_all_1.globalVarGet; function main() { var _this = this; (0, drawIndexed_1.draw)(__shadeup_make_shader_inst("shd_6515406754369975000349600057000435695077700680380", {}, /**@shadeup=shader*/ function (__in, __out) { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { __out.color = (_a = (1 | 0), [_a, _a, _a, _a]); return [2 /*return*/]; }); }); })); } exports.main = main; function giveFloat() { return 1.0; } exports.giveFloat = giveFloat; ; }); })(define); }); ================================================ FILE: cli/test/other.js ================================================ ================================================ FILE: cli/test/other.shadeup ================================================ pub fn drawer() { return shader { out.color = 1.xxxx; }; } ================================================ FILE: cli/test/vite-project/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: cli/test/vite-project/index.html ================================================ Vite + TS
================================================ FILE: cli/test/vite-project/package.json ================================================ { "name": "vite-project", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "devDependencies": { "typescript": "^5.2.2", "vite": "^5.1.1" } } ================================================ FILE: cli/test/vite-project/src/index.ts ================================================ import { makeShadeupInstance } from "./main"; const canvas = document.querySelector("#canvas")!; (async () => { let engine = await makeShadeupInstance(canvas); await engine.enableUI(); console.log(engine); let tex = await engine.loadTexture2dFromURL( "https://i.imgur.com/XxtTu4t.jpeg" ); engine.files.main.setTexture(tex); let model = await engine.loadModelFromURL( "https://s3-eu-west-1.amazonaws.com/fetchcfd/original/file-1571050371399.glb" ); // console.log(model); // engine.files.main.setModel(model); // engine.files.main.setSpawning(true); // engine.files.main.useTex(await engine); })(); function sizeCanvas() { canvas.width = window.innerWidth * devicePixelRatio; canvas.height = window.innerHeight * devicePixelRatio; } sizeCanvas(); window.addEventListener("resize", sizeCanvas); ================================================ FILE: cli/test/vite-project/src/logoPath.shadeup ================================================ pub const testVal = 12; pub const logoPath = [ (331.8819682214535,309.37499982761074), (371.32282194357356,303.64633707500263), (407.46032126878504,286.8163539059281), (437.274252663429,260.35535066551427), (458.29984831576394,226.50580234284354), (468.7136104513537,188.03532791839726), (467.7118086191006,148.17574354216006), (455.35191297112505,110.29043620450224), (432.6263207130228,77.53229396479205), (401.5178156140271,52.615834986960536), (364.58359174118056,37.654862578958394), (324.8932794340484,33.92378272686386), (285.7795001390052,41.64769023829373), (250.56380617643717,60.281665182363334), (222.1106045175098,88.2185302598852), (202.82739785088438,123.09151777807875), (194.38489856271633,162.05350582157), (197.38939677012752,201.79863233626673), (211.66487429790584,239.00609777264683), (236.00990811938493,270.56874343985766), (268.34764758612255,293.8916209452305), (305.99793844636343,306.94940550263783), ]; pub const logoPath2 = [ (451.87140094230557,602.1619078110434), (486.29251847854266,622.2323459015123), (525.0474675157033,631.5641981376127), (564.852311019554,629.356639856118), (602.3248780708933,615.8045994091574), (634.3309736404595,592.0422272891796), (658.1539457850712,560.0779291620549), (671.7748167680887,522.6324487372781), (674.0564197042156,482.83741996002925), (664.802513049373,444.0747441577281), (644.7848636535293,409.5942420839993), (615.7020857431386,382.3322773053413), (580.0140772066509,364.5860070980618), (540.7286331849546,357.84918467153614), (501.165415783651,362.6925101786735), (464.6647081529237,378.70718806257287), (432.3072593603389,402.199889140537), (398.2575592626505,423.1228910326879), (360.9127940340042,437.14799612337356), (321.174878646251,438.4183448188125), (283.2521603337715,426.1623983366661), (248.70900986328027,406.05151673315385), (216.43777559524344,382.4456871602924), (180.8200178325316,364.5371472183075), (141.5630951779306,357.6283420525193), (101.9834477806449,362.29764865112304), (65.40326447164699,378.15686103433126), (34.94644591589244,403.8478116568671), (13.153800354272045,437.21996187233935), (1.8759296978847086,475.4505834586918), (2.066709423006884,515.3093933970973), (13.710149187603491,553.4309022236707), (35.820909042632074,586.5925166847115), (66.5392314406395,612.0011914315223), (103.252336820272,627.4988351532799), (142.8763750292417,631.7887844293851), (182.0634692296343,624.5048369401586), (217.51107280796145,606.2551520383203), (249.81667583724186,582.6938662902708), (284.49393762749804,562.8132021128339), (322.56195677111145,551.0072036701465), (362.2746942768097,552.8769284491539), (399.45542942085626,567.3067293377287), (433.38932465259774,588.460027547873), ]; ================================================ FILE: cli/test/vite-project/src/main.d.ts ================================================ import * as __ from "shadeup/math"; declare namespace ShadeupFiles { declare namespace main { /**__SHADEUP_STRUCT_INJECTION_HOOK__*/ export declare function setTexture(newTex: texture2d<__.float4>): void; export declare function setModel(newModel: Model): void; export declare function main(): void; } } export declare function makeShadeupInstance( canvas: HTMLCanvasElement ): Promise<{ /** * Set to false to pause */ playing: boolean; canvas: HTMLCanvasElement; adapter: any; hooks: { beforeFrame?: () => {}; afterFrame?: () => {}; reset?: () => {}; }[]; start: () => void; env: { camera: { position: __.float3; rotation: __.float4; width: __.float; height: __.float; fov: __.float; near: __.float; far: __.float; }; camera2d: { position: __.float2; zoom: __.float; }; deltaTime: __.float; frame: __.int; keyboard: any; mouse: any; screenSize: __.float2; time: __.float; }; /** * Used to pass values into the shadeup env (accessed as env.input("name") inside) */ inputValues: Map; enableUI: () => Promise; loadTextureFromImageLike: ( img: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas | HTMLVideoElement ) => Promise<__.texture2d<__.float4>>; loadTexture2dFromURL: (url: string) =? Promise<__.texture2d<__.float4>>; loadModelFromURL(urlGltf: string) => Promise<__.texture2d<__.float4>>; files: typeof ShadeupFiles; }>; ================================================ FILE: cli/test/vite-project/src/main.js ================================================ import { bindShadeupEngine } from "shadeup"; export const makeShadeupInstance = bindShadeupEngine((define, localEngineContext) => { const __shadeup_gen_shader = localEngineContext.__shadeup_gen_shader.bind(localEngineContext); const __shadeup_make_shader_inst = localEngineContext.__shadeup_make_shader_inst.bind(localEngineContext); const __shadeup_register_struct = localEngineContext.__shadeup_register_struct.bind(localEngineContext); const env = localEngineContext.env; ((defineFunc) => { let define = (deps, func) => defineFunc("/__meta.js", deps, func); define(["require", "exports"], function (require, exports, __, std___std_all_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.files = ["main"]; }); })(define); ((defineFunc) => { let define = (deps, func) => defineFunc("/main.js", deps, func); __shadeup_gen_shader("shd_000710086052666091061257200756375023002800009", { webgl: {_ext_uniform_global_tex: {"type":"primitive","name":"texture2d"}}, webgpu: {"attributeInput":"","attributeOutput":"","locals":[],"globals":[["tex",{"fileName":"/main.ts","structure":{"type":"primitive","name":"texture2d","access":"sample"}}]]} }, {webgpu: `struct ShaderInput { @align(16) position: vec3, @align(16) normal: vec3, @align(16) tangent: vec3, @align(16) bitangent: vec3, @align(16) clipPosition: vec4, @align(16) realPosition: vec4, @align(16) uv: vec2, @align(16) screen: vec2, @align(16) color: vec4, @align(16) groupId: vec3, @align(16) groupSize: vec3, @align(16) globalId: vec3, @align(16) localId: vec3, @align(16) instanceIndex: i32, @align(16) vertexIndex: i32, }; struct ShaderOutput { @align(16) position: vec4, @align(16) normal: vec3, @align(16) tangent: vec3, @align(16) bitangent: vec3, @align(16) uv: vec2, @align(16) color: vec4, // %SHADER_ShaderOutput% }; struct _InUniformsStruct { /*SHADEUP_UNIFORM_STRUCT_START*/ @align(16) _ext_uniform_global_tex_size: vec2, }; @group(%GROUP_INDEX%) @binding(1) var _in_uniforms: _InUniformsStruct; @group(%GROUP_INDEX%) @binding(2) var _ext_uniform_global_tex_texture: texture_2d; @group(%GROUP_INDEX%) @binding(3) var _ext_uniform_global_tex: sampler; /*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/ fn main(/*__SHADEUP_TEMPLATE_INPUT*/)-> /*__SHADEUP_TEMPLATE_OUTPUT*/{ /*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/ var normal: vec3 = normalize(_i_in.normal); var lightDir: vec3 = normalize(vec3(f32(i32(2)), f32(4), f32(0.5))); var diffuse: vec4 = max(dot(normal, lightDir), f32(0)) * textureSample(_ext_uniform_global_tex_texture, _ext_uniform_global_tex, vec2(_i_in.uv)); _i_out.color = vec4(diffuse.xyz, f32(i32(1))); /*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/ } `,webgl:`struct ShaderInput { vec3 position; vec3 normal; vec3 tangent; vec3 bitangent; vec4 clipPosition; vec4 realPosition; vec2 uv; vec2 screen; vec4 color; ivec3 groupId; ivec3 groupSize; ivec3 globalId; ivec3 localId; int instanceIndex; int vertexIndex; }; struct ShaderOutput { vec4 position; vec3 normal; vec3 tangent; vec3 bitangent; vec2 uv; vec4 color; }; uniform sampler2D _ext_uniform_global_tex; uniform vec2 _ext_uniform_global_tex_size; /*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/ void main() { /*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/ vec3 normal = normalize(_i_in.normal); vec3 lightDir = normalize(vec3(int(2), float(4), float(0.5))); vec4 diffuse = max(dot(normal, lightDir), float(0)) * texture(_ext_uniform_global_tex, vec2(_i_in.uv)); _i_out.color = vec4(diffuse.xyz, int(1)); /*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/ } `, software: () => {}}, [[2830,2865,21,38],[2939,2972,38,53],[3048,3082,53,69],[3162,3198,69,87],[3242,3284,87,108],[3289,3331,108,129],[3400,3426,129,140],[3502,3532,140,155],[3609,3644,155,169],[3690,3720,169,186],[3768,3800,186,205],[3879,3910,205,223],[3956,3986,223,240],[4051,4074,240,261],[4123,4144,261,280],[2728,4283,0,284],[4371,4409,306,323],[4444,4477,323,338],[4513,4547,338,354],[4585,4621,354,372],[4655,4681,372,383],[4714,4749,383,397],[4309,4869,284,401],[1922,2081,401,444],[1922,2081,444,487],[3054,3063,603,612],[0,0,613,618],[0,0,619,625],[0,0,613,625],[0,0,603,626],[0,0,589,626],[0,0,589,628],[3134,3143,644,653],[3158,3164,659,662],[0,0,663,664],[0,0,659,665],[3169,3177,667,672],[0,0,673,674],[0,0,667,675],[3184,3192,677,682],[0,0,683,686],[0,0,677,687],[0,0,654,688],[0,0,644,689],[0,0,628,689],[0,0,628,691],[3258,3261,706,709],[3262,3265,710,713],[0,0,714,720],[0,0,722,730],[0,0,710,731],[3285,3293,733,738],[0,0,739,740],[0,0,733,741],[0,0,706,742],[0,0,753,776],[0,0,783,788],[0,0,789,791],[0,0,783,791],[0,0,745,793],[0,0,706,793],[0,0,691,793],[0,0,691,795],[0,0,795,801],[0,0,802,807],[0,0,795,807],[0,0,815,822],[0,0,815,826],[3401,3407,828,831],[0,0,832,833],[0,0,828,834],[0,0,810,835],[0,0,795,835],[0,0,795,837],[628,985,487,881],[2983,3414,0,881]]); __shadeup_gen_shader("shd_0012035060108500265800533466056020000547600000", { webgl: {_ext_uniform_global_env: {"type":"struct","name":"str_i_iistd_native_ts_387_FrameContext","fields":{"time":{"type":"primitive","name":"float"},"camera":{"type":"struct","name":"str_i_iistd_common_ts_10681_Camera","fields":{"position":{"type":"primitive","name":"float3"},"rotation":{"type":"primitive","name":"float4"},"width":{"type":"primitive","name":"float"},"height":{"type":"primitive","name":"float"},"fov":{"type":"primitive","name":"float"},"near":{"type":"primitive","name":"float"},"far":{"type":"primitive","name":"float"}}}}}}, webgpu: {"attributeInput":"","attributeOutput":"","locals":[],"globals":[["env",{"fileName":"/_std/native.ts","structure":{"type":"struct","name":"str_i_iistd_native_ts_387_FrameContext","fields":[["time",{"type":"primitive","name":"float"}],["camera",{"type":"struct","name":"str_i_iistd_common_ts_10681_Camera","fields":[["position",{"type":"primitive","name":"float3"}],["rotation",{"type":"primitive","name":"float4"}],["width",{"type":"primitive","name":"float"}],["height",{"type":"primitive","name":"float"}],["fov",{"type":"primitive","name":"float"}],["near",{"type":"primitive","name":"float"}],["far",{"type":"primitive","name":"float"}]]}]]}}]]} }, {webgpu: `fn matrix_inversefloat4x4(m: mat4x4) -> mat4x4{ let n11 = m[0][0]; let n12 = m[1][0]; let n13 = m[2][0]; let n14 = m[3][0]; let n21 = m[0][1]; let n22 = m[1][1]; let n23 = m[2][1]; let n24 = m[3][1]; let n31 = m[0][2]; let n32 = m[1][2]; let n33 = m[2][2]; let n34 = m[3][2]; let n41 = m[0][3]; let n42 = m[1][3]; let n43 = m[2][3]; let n44 = m[3][3]; let t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44; let t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44; let t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44; let t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; let det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; let idet = 1.0 / det; var ret: mat4x4 = mat4x4(); ret[0][0] = t11 * idet; ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet; ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet; ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet; ret[1][0] = t12 * idet; ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet; ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet; ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet; ret[2][0] = t13 * idet; ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet; ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet; ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet; ret[3][0] = t14 * idet; ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet; ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet; ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet; return ret; } struct ShaderInput { @align(16) position: vec3, @align(16) normal: vec3, @align(16) tangent: vec3, @align(16) bitangent: vec3, @align(16) clipPosition: vec4, @align(16) realPosition: vec4, @align(16) uv: vec2, @align(16) screen: vec2, @align(16) color: vec4, @align(16) groupId: vec3, @align(16) groupSize: vec3, @align(16) globalId: vec3, @align(16) localId: vec3, @align(16) instanceIndex: i32, @align(16) vertexIndex: i32, }; struct ShaderOutput { @align(16) position: vec4, @align(16) normal: vec3, @align(16) tangent: vec3, @align(16) bitangent: vec3, @align(16) uv: vec2, @align(16) color: vec4, // %SHADER_ShaderOutput% }; struct str_i_iistd_common_ts_10681_Camera { @align(16) position: vec3, @align(16) rotation: vec4, @align(16) width: f32, @align(16) height: f32, @align(16) fov: f32, @align(16) near: f32, @align(16) far: f32, }; fn _make_struct_str_i_iistd_common_ts_10681_Camera( far: f32, fov: f32, height: f32, near: f32, position: vec3, rotation: vec4, width: f32,) -> str_i_iistd_common_ts_10681_Camera { var _s: str_i_iistd_common_ts_10681_Camera; _s.far = far; _s.fov = fov; _s.height = height; _s.near = near; _s.position = position; _s.rotation = rotation; _s.width = width; return _s; } struct str_i_iistd_native_ts_387_FrameContext { // @align(16) deltaTime: f32, @align(16) time: f32, // @align(16) screenSize: vec2, // @align(16) frame: i32, // mouse: str_i_iistd_native_ts_1719_MouseInputState, // keyboard: str_i_iistd_native_ts_3334_KeyboardInputState, camera: str_i_iistd_common_ts_10681_Camera, // camera2d: str_i_iistd_common_ts_9656_Camera2d, }; fn _make_struct_str_i_iistd_native_ts_387_FrameContext( camera: str_i_iistd_common_ts_10681_Camera, time: f32,) -> str_i_iistd_native_ts_387_FrameContext { var _s: str_i_iistd_native_ts_387_FrameContext; _s.camera = camera; _s.time = time; return _s; } struct _InUniformsStruct { /*SHADEUP_UNIFORM_STRUCT_START*/ _ext_uniform_global_env: str_i_iistd_native_ts_387_FrameContext, }; @group(%GROUP_INDEX%) @binding(1) var _in_uniforms: _InUniformsStruct; fn fn_ii_std_common_ts_3330_quat_static_conjugate(quaternion_const: vec4) -> vec4 { var quaternion = quaternion_const; return vec4(-(quaternion.xyz), quaternion.w); } fn fn_ii_std_common_ts_2513_quat_static_mul(a_const: vec4, b_const: vec4) -> vec4 { var a = a_const; var b = b_const; return vec4(b.xyz * a.w + a.xyz * b.w + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz)); } fn fn_ii_std_common_ts_7975_quat_static_toMatrix(quaternion_const: vec4) -> mat4x4 { var quaternion = quaternion_const; var x: f32 = quaternion.x; var y: f32 = quaternion.y; var z: f32 = quaternion.z; var w: f32 = quaternion.w; var x2: f32 = x + x; var y2: f32 = y + y; var z2: f32 = z + z; var xx: f32 = x * x2; var xy: f32 = x * y2; var xz: f32 = x * z2; var yy: f32 = y * y2; var yz: f32 = y * z2; var zz: f32 = z * z2; var wx: f32 = w * x2; var wy: f32 = w * y2; var wz: f32 = w * z2; var m: mat4x4 = mat4x4(f32(1) - (yy + zz), xy + wz, xz - wy, f32(i32(0)), xy - wz, f32(1) - (xx + zz), yz + wx, f32(i32(0)), xz + wy, yz - wx, f32(1) - (xx + yy), f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(1)); return m; } fn fn_ii_std_common_ts_47518_matrix_static_perspective(fov_const: f32, aspect_const: f32, near_const: f32, far_const: f32) -> mat4x4 { var fov = fov_const; var aspect = aspect_const; var near = near_const; var far = far_const; var fovRad: f32 = radians(fov); var tanFov: f32 = tan(fovRad * f32(0.5)); var matrx: mat4x4 = mat4x4(f32(1) / (tanFov * aspect), f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(1) / tanFov, f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(i32(0)), -(((far + near) / (far - near))), f32(-(i32(1))), f32(i32(0)), f32(i32(0)), -(((f32(i32(2)) * (near * far)) / (far - near))), f32(i32(0))); return matrx; } fn fn_ii_std_common_ts_12813_Camera_static_getWorldToViewMatrix(_this: str_i_iistd_common_ts_10681_Camera) -> mat4x4 { var shader_self_temp: str_i_iistd_common_ts_10681_Camera = _this; var rotationMatrix: mat4x4 = fn_ii_std_common_ts_7975_quat_static_toMatrix(_this.rotation); var translationMatrix: mat4x4 = mat4x4(f32(i32(1)), f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(i32(1)), f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(i32(0)), f32(i32(1)), f32(i32(0)), _this.position.x, _this.position.y, _this.position.z, f32(i32(1))); return matrix_inversefloat4x4(translationMatrix * rotationMatrix); } fn fn_ii_std_common_ts_13404_Camera_static_getPerspectiveMatrix(_this: str_i_iistd_common_ts_10681_Camera) -> mat4x4 { var shader_self_temp: str_i_iistd_common_ts_10681_Camera = _this; return fn_ii_std_common_ts_47518_matrix_static_perspective(_this.fov, _this.width / _this.height, _this.near, _this.far); } fn fn_ii_std_common_ts_8827_quat_static_fromEulerAngles(angles_const: vec3) -> vec4 { var angles = angles_const; var cr: f32 = cos(angles.x * f32(0.5)); var sr: f32 = sin(angles.x * f32(0.5)); var cp: f32 = cos(angles.y * f32(0.5)); var sp: f32 = sin(angles.y * f32(0.5)); var cy: f32 = cos(angles.z * f32(0.5)); var sy: f32 = sin(angles.z * f32(0.5)); return vec4(sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy); } fn fn_ii_std_common_ts_2939_quat_static_rotate(quaternion_const: vec4, vector_const: vec3) -> vec3 { var quaternion = quaternion_const; var vector = vector_const; var q: vec4 = fn_ii_std_common_ts_2513_quat_static_mul(fn_ii_std_common_ts_2513_quat_static_mul(quaternion, vec4(vector, f32(i32(0)))), fn_ii_std_common_ts_3330_quat_static_conjugate(quaternion)); return q.xyz; } fn fn_ii_std_common_ts_12549_Camera_static_getCombinedMatrix(_this: str_i_iistd_common_ts_10681_Camera) -> mat4x4 { var shader_self_temp: str_i_iistd_common_ts_10681_Camera = _this; return fn_ii_std_common_ts_13404_Camera_static_getPerspectiveMatrix(_this) * fn_ii_std_common_ts_12813_Camera_static_getWorldToViewMatrix(_this); } /*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/ fn main(/*__SHADEUP_TEMPLATE_INPUT*/)-> /*__SHADEUP_TEMPLATE_OUTPUT*/{ /*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/ _i_out.position = fn_ii_std_common_ts_12549_Camera_static_getCombinedMatrix(_in_uniforms._ext_uniform_global_env.camera) * vec4(fn_ii_std_common_ts_2939_quat_static_rotate(fn_ii_std_common_ts_8827_quat_static_fromEulerAngles(vec3(f32(i32(0)), _in_uniforms._ext_uniform_global_env.time, f32(i32(0)))), _i_in.position), f32(i32(1))); /*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/ } `,webgl:`mat4 matrix_inversefloat4x4(mat4 m) { return inverse(m); } struct ShaderInput { vec3 position; vec3 normal; vec3 tangent; vec3 bitangent; vec4 clipPosition; vec4 realPosition; vec2 uv; vec2 screen; vec4 color; ivec3 groupId; ivec3 groupSize; ivec3 globalId; ivec3 localId; int instanceIndex; int vertexIndex; }; struct ShaderOutput { vec4 position; vec3 normal; vec3 tangent; vec3 bitangent; vec2 uv; vec4 color; }; struct str_i_iistd_common_ts_10681_Camera { vec3 position; vec4 rotation; float width; float height; float fov; float near; float far; }; str_i_iistd_common_ts_10681_Camera _make_struct_str_i_iistd_common_ts_10681_Camera(vec3 position, vec4 rotation, float width, float height, float fov, float near, float far) { str_i_iistd_common_ts_10681_Camera _s; _s.position = position; _s.rotation = rotation; _s.width = width; _s.height = height; _s.fov = fov; _s.near = near; _s.far = far; return _s; } struct str_i_iistd_native_ts_387_FrameContext { // float deltaTime; float time; // vec2 screenSize; // int frame; // str_i_iistd_native_ts_1719_MouseInputState mouse; // str_i_iistd_native_ts_3334_KeyboardInputState keyboard; str_i_iistd_common_ts_10681_Camera camera; // str_i_iistd_common_ts_9656_Camera2d camera2d; }; str_i_iistd_native_ts_387_FrameContext _make_struct_str_i_iistd_native_ts_387_FrameContext(float time, str_i_iistd_common_ts_10681_Camera camera) { str_i_iistd_native_ts_387_FrameContext _s; _s.time = time; _s.camera = camera; return _s; } uniform str_i_iistd_native_ts_387_FrameContext _ext_uniform_global_env; vec4 fn_ii_std_common_ts_3330_quat_static_conjugate(vec4 quaternion) { return vec4(-(quaternion.xyz), quaternion.w); } vec4 fn_ii_std_common_ts_2513_quat_static_mul(vec4 a, vec4 b) { return vec4(b.xyz * a.w + a.xyz * b.w + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz)); } mat4 fn_ii_std_common_ts_7975_quat_static_toMatrix(vec4 quaternion) { float x = quaternion.x; float y = quaternion.y; float z = quaternion.z; float w = quaternion.w; float x2 = x + x; float y2 = y + y; float z2 = z + z; float xx = x * x2; float xy = x * y2; float xz = x * z2; float yy = y * y2; float yz = y * z2; float zz = z * z2; float wx = w * x2; float wy = w * y2; float wz = w * z2; mat4 m = mat4(float(1) - (yy + zz), xy + wz, xz - wy, int(0), xy - wz, float(1) - (xx + zz), yz + wx, int(0), xz + wy, yz - wx, float(1) - (xx + yy), int(0), int(0), int(0), int(0), float(1)); return m; } mat4 fn_ii_std_common_ts_47518_matrix_static_perspective(float fov, float aspect, float near, float far) { float fovRad = radians(fov); float tanFov = tan(fovRad * float(0.5)); mat4 matrx = mat4(float(1) / (tanFov * aspect), int(0), int(0), int(0), int(0), float(1) / tanFov, int(0), int(0), int(0), int(0), -(((far + near) / (far - near))), -(int(1)), int(0), int(0), -(((float(int(2)) * (near * far)) / (far - near))), int(0)); return matrx; } mat4 fn_ii_std_common_ts_12813_Camera_static_getWorldToViewMatrix(str_i_iistd_common_ts_10681_Camera _this) { str_i_iistd_common_ts_10681_Camera shader_self_temp = _this; mat4 rotationMatrix = fn_ii_std_common_ts_7975_quat_static_toMatrix(_this.rotation); mat4 translationMatrix = mat4(int(1), int(0), int(0), int(0), int(0), int(1), int(0), int(0), int(0), int(0), int(1), int(0), _this.position.x, _this.position.y, _this.position.z, int(1)); return matrix_inversefloat4x4(translationMatrix * rotationMatrix); } mat4 fn_ii_std_common_ts_13404_Camera_static_getPerspectiveMatrix(str_i_iistd_common_ts_10681_Camera _this) { str_i_iistd_common_ts_10681_Camera shader_self_temp = _this; return fn_ii_std_common_ts_47518_matrix_static_perspective(_this.fov, _this.width / _this.height, _this.near, _this.far); } vec4 fn_ii_std_common_ts_8827_quat_static_fromEulerAngles(vec3 angles) { float cr = cos(angles.x * float(0.5)); float sr = sin(angles.x * float(0.5)); float cp = cos(angles.y * float(0.5)); float sp = sin(angles.y * float(0.5)); float cy = cos(angles.z * float(0.5)); float sy = sin(angles.z * float(0.5)); return vec4(sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy); } vec3 fn_ii_std_common_ts_2939_quat_static_rotate(vec4 quaternion, vec3 vector) { vec4 q = fn_ii_std_common_ts_2513_quat_static_mul(fn_ii_std_common_ts_2513_quat_static_mul(quaternion, vec4(vector, int(0))), fn_ii_std_common_ts_3330_quat_static_conjugate(quaternion)); return q.xyz; } mat4 fn_ii_std_common_ts_12549_Camera_static_getCombinedMatrix(str_i_iistd_common_ts_10681_Camera _this) { str_i_iistd_common_ts_10681_Camera shader_self_temp = _this; return fn_ii_std_common_ts_13404_Camera_static_getPerspectiveMatrix(_this) * fn_ii_std_common_ts_12813_Camera_static_getWorldToViewMatrix(_this); } /*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/ void main() { /*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/ _i_out.position = fn_ii_std_common_ts_12549_Camera_static_getCombinedMatrix(_ext_uniform_global_env.camera) * vec4(fn_ii_std_common_ts_2939_quat_static_rotate(fn_ii_std_common_ts_8827_quat_static_fromEulerAngles(vec3(int(0), _ext_uniform_global_env.time, int(0))), _i_in.position), int(1)); /*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/ } `, software: () => {}}, [[2830,2865,21,38],[2939,2972,38,53],[3048,3082,53,69],[3162,3198,69,87],[3242,3284,87,108],[3289,3331,108,129],[3400,3426,129,140],[3502,3532,140,155],[3609,3644,155,169],[3690,3720,169,186],[3768,3800,186,205],[3879,3910,205,223],[3956,3986,223,240],[4051,4074,240,261],[4123,4144,261,280],[2728,4283,0,284],[4371,4409,306,323],[4444,4477,323,338],[4513,4547,338,354],[4585,4621,354,372],[4655,4681,372,383],[4714,4749,383,397],[4309,4869,284,401],[14920,14947,445,462],[14949,14976,462,479],[14978,15001,479,494],[15003,15027,494,510],[15029,15050,510,523],[15052,15074,523,537],[15076,15097,537,550],[10681,15372,401,554],[10681,15372,554,927],[493,510,975,997],[577,589,997,1011],[623,642,1011,1033],[674,685,1033,1049],[745,792,1049,1104],[842,898,1104,1165],[972,1002,1165,1210],[1007,1043,1210,1261],[387,1715,927,1265],[387,1715,1265,1510],[16316,16333,1510,1582],[0,0,1634,1649],[0,0,1667,1677],[0,0,1667,1681],[0,0,1665,1682],[0,0,1684,1694],[0,0,1684,1696],[0,0,1660,1697],[0,0,1653,1699],[682,696,1582,1703],[0,0,1749,1755],[0,0,1757,1763],[0,0,1779,1780],[0,0,1779,1784],[0,0,1787,1788],[0,0,1787,1790],[0,0,1779,1790],[0,0,1793,1794],[0,0,1793,1798],[0,0,1801,1802],[0,0,1801,1804],[0,0,1793,1804],[0,0,1779,1804],[0,0,1807,1812],[0,0,1813,1814],[0,0,1813,1818],[0,0,1820,1821],[0,0,1820,1825],[0,0,1807,1826],[0,0,1779,1826],[0,0,1828,1829],[0,0,1828,1831],[0,0,1834,1835],[0,0,1834,1837],[0,0,1828,1837],[2802,2805,1840,1843],[0,0,1844,1845],[0,0,1844,1849],[0,0,1851,1852],[0,0,1851,1856],[0,0,1840,1857],[0,0,1828,1857],[0,0,1774,1858],[0,0,1767,1860],[682,696,1703,1864],[0,0,1915,1930],[0,0,1944,1954],[0,0,1944,1956],[0,0,1934,1956],[0,0,1934,1958],[0,0,1968,1978],[0,0,1968,1980],[0,0,1958,1980],[0,0,1958,1982],[0,0,1992,2002],[0,0,1992,2004],[0,0,1982,2004],[0,0,1982,2006],[0,0,2016,2026],[0,0,2016,2028],[0,0,2006,2028],[0,0,2006,2030],[0,0,2041,2042],[0,0,2045,2046],[0,0,2041,2046],[0,0,2030,2046],[0,0,2030,2048],[0,0,2059,2060],[0,0,2063,2064],[0,0,2059,2064],[0,0,2048,2064],[0,0,2048,2066],[0,0,2077,2078],[0,0,2081,2082],[0,0,2077,2082],[0,0,2066,2082],[0,0,2066,2084],[0,0,2095,2096],[0,0,2099,2101],[0,0,2095,2101],[0,0,2084,2101],[0,0,2084,2103],[0,0,2114,2115],[0,0,2118,2120],[0,0,2114,2120],[0,0,2103,2120],[0,0,2103,2122],[0,0,2133,2134],[0,0,2137,2139],[0,0,2133,2139],[0,0,2122,2139],[0,0,2122,2141],[0,0,2152,2153],[0,0,2156,2158],[0,0,2152,2158],[0,0,2141,2158],[0,0,2141,2160],[0,0,2171,2172],[0,0,2175,2177],[0,0,2171,2177],[0,0,2160,2177],[0,0,2160,2179],[0,0,2190,2191],[0,0,2194,2196],[0,0,2190,2196],[0,0,2179,2196],[0,0,2179,2198],[0,0,2209,2210],[0,0,2213,2215],[0,0,2209,2215],[0,0,2198,2215],[0,0,2198,2217],[0,0,2228,2229],[0,0,2232,2234],[0,0,2228,2234],[0,0,2217,2234],[0,0,2217,2236],[0,0,2247,2248],[0,0,2251,2253],[0,0,2247,2253],[0,0,2236,2253],[0,0,2236,2255],[8499,8507,2269,2274],[0,0,2275,2276],[0,0,2269,2277],[0,0,2281,2283],[0,0,2286,2288],[0,0,2281,2288],[0,0,2280,2289],[0,0,2269,2289],[0,0,2291,2293],[0,0,2296,2298],[0,0,2291,2298],[0,0,2300,2302],[0,0,2305,2307],[0,0,2300,2307],[8572,8578,2309,2312],[0,0,2313,2314],[0,0,2309,2315],[0,0,2317,2319],[0,0,2322,2324],[0,0,2317,2324],[8609,8617,2326,2331],[0,0,2332,2333],[0,0,2326,2334],[0,0,2338,2340],[0,0,2343,2345],[0,0,2338,2345],[0,0,2337,2346],[0,0,2326,2346],[0,0,2348,2350],[0,0,2353,2355],[0,0,2348,2355],[8664,8670,2357,2360],[0,0,2361,2362],[0,0,2357,2363],[0,0,2365,2367],[0,0,2370,2372],[0,0,2365,2372],[0,0,2374,2376],[0,0,2379,2381],[0,0,2374,2381],[8719,8727,2383,2388],[0,0,2389,2390],[0,0,2383,2391],[0,0,2395,2397],[0,0,2400,2402],[0,0,2395,2402],[0,0,2394,2403],[0,0,2383,2403],[8756,8762,2405,2408],[0,0,2409,2410],[0,0,2405,2411],[8767,8773,2413,2416],[0,0,2417,2418],[0,0,2413,2419],[8778,8784,2421,2424],[0,0,2425,2426],[0,0,2421,2427],[8789,8795,2429,2432],[0,0,2433,2434],[0,0,2429,2435],[8800,8808,2437,2442],[0,0,2443,2444],[0,0,2437,2445],[0,0,2264,2446],[0,0,2255,2446],[0,0,2255,2448],[0,0,2455,2456],[0,0,2448,2458],[682,696,1864,2462],[0,0,2519,2528],[0,0,2530,2542],[0,0,2544,2554],[0,0,2556,2565],[48073,48080,2584,2591],[0,0,2592,2595],[0,0,2584,2596],[0,0,2569,2596],[0,0,2569,2598],[48100,48103,2613,2616],[0,0,2617,2623],[48120,48128,2626,2631],[0,0,2632,2635],[0,0,2626,2636],[0,0,2617,2636],[0,0,2613,2637],[0,0,2598,2637],[0,0,2598,2639],[48170,48178,2657,2662],[0,0,2663,2664],[0,0,2657,2665],[0,0,2669,2675],[0,0,2678,2684],[0,0,2669,2684],[0,0,2668,2685],[0,0,2657,2685],[48215,48221,2687,2690],[0,0,2691,2692],[0,0,2687,2693],[48226,48232,2695,2698],[0,0,2699,2700],[0,0,2695,2701],[48237,48243,2703,2706],[0,0,2707,2708],[0,0,2703,2709],[48248,48254,2711,2714],[0,0,2715,2716],[0,0,2711,2717],[48267,48275,2719,2724],[0,0,2725,2726],[0,0,2719,2727],[0,0,2730,2736],[0,0,2719,2736],[48292,48298,2738,2741],[0,0,2742,2743],[0,0,2738,2744],[48303,48309,2746,2749],[0,0,2750,2751],[0,0,2746,2752],[48314,48320,2754,2757],[0,0,2758,2759],[0,0,2754,2760],[48325,48331,2762,2765],[0,0,2766,2767],[0,0,2762,2768],[0,0,2774,2777],[0,0,2780,2784],[0,0,2774,2784],[0,0,2773,2785],[0,0,2789,2792],[0,0,2795,2799],[0,0,2789,2799],[0,0,2788,2800],[0,0,2773,2800],[0,0,2772,2801],[0,0,2770,2802],[48415,48421,2806,2809],[0,0,2810,2811],[0,0,2806,2812],[0,0,2804,2813],[48427,48433,2815,2818],[0,0,2819,2820],[0,0,2815,2821],[48438,48444,2823,2826],[0,0,2827,2828],[0,0,2823,2829],[48477,48483,2841,2844],[0,0,2845,2846],[0,0,2841,2847],[0,0,2835,2848],[0,0,2852,2856],[0,0,2859,2862],[0,0,2852,2862],[0,0,2851,2863],[0,0,2835,2863],[0,0,2834,2864],[0,0,2868,2871],[0,0,2874,2878],[0,0,2868,2878],[0,0,2867,2879],[0,0,2834,2879],[0,0,2833,2880],[0,0,2831,2881],[48541,48547,2883,2886],[0,0,2887,2888],[0,0,2883,2889],[0,0,2652,2890],[0,0,2639,2890],[0,0,2639,2892],[0,0,2899,2904],[0,0,2892,2906],[33022,33038,2462,2910],[0,0,3074,3079],[0,0,3020,3079],[0,0,3020,3081],[12885,12898,3103,3148],[0,0,3149,3154],[0,0,3155,3163],[0,0,3149,3163],[0,0,3103,3164],[0,0,3081,3164],[0,0,3081,3166],[12951,12957,3196,3199],[0,0,3200,3201],[0,0,3196,3202],[12962,12968,3204,3207],[0,0,3208,3209],[0,0,3204,3210],[12973,12979,3212,3215],[0,0,3216,3217],[0,0,3212,3218],[12984,12990,3220,3223],[0,0,3224,3225],[0,0,3220,3226],[12995,13001,3228,3231],[0,0,3232,3233],[0,0,3228,3234],[13006,13012,3236,3239],[0,0,3240,3241],[0,0,3236,3242],[13017,13023,3244,3247],[0,0,3248,3249],[0,0,3244,3250],[13028,13034,3252,3255],[0,0,3256,3257],[0,0,3252,3258],[13039,13045,3260,3263],[0,0,3264,3265],[0,0,3260,3266],[13050,13056,3268,3271],[0,0,3272,3273],[0,0,3268,3274],[13061,13067,3276,3279],[0,0,3280,3281],[0,0,3276,3282],[13072,13078,3284,3287],[0,0,3288,3289],[0,0,3284,3290],[0,0,3292,3297],[0,0,3298,3306],[0,0,3292,3306],[0,0,3292,3308],[0,0,3310,3315],[0,0,3316,3324],[0,0,3310,3324],[0,0,3310,3326],[0,0,3328,3333],[0,0,3334,3342],[0,0,3328,3342],[0,0,3328,3344],[13179,13185,3346,3349],[0,0,3350,3351],[0,0,3346,3352],[0,0,3191,3353],[0,0,3166,3353],[0,0,3166,3355],[13198,13205,3362,3384],[0,0,3385,3402],[0,0,3405,3419],[0,0,3385,3419],[0,0,3362,3420],[0,0,3355,3422],[8125,8367,2910,3426],[0,0,3590,3595],[0,0,3536,3595],[0,0,3536,3597],[13462,13480,3604,3655],[0,0,3656,3661],[0,0,3662,3665],[0,0,3656,3665],[0,0,3667,3672],[0,0,3673,3678],[0,0,3667,3678],[0,0,3681,3686],[0,0,3687,3693],[0,0,3681,3693],[0,0,3667,3693],[0,0,3695,3700],[0,0,3701,3705],[0,0,3695,3705],[0,0,3707,3712],[0,0,3713,3716],[0,0,3707,3716],[0,0,3604,3717],[0,0,3597,3719],[8125,8367,3426,3723],[0,0,3781,3792],[8878,8881,3807,3810],[0,0,3811,3817],[0,0,3811,3819],[8915,8923,3822,3827],[0,0,3828,3831],[0,0,3822,3832],[0,0,3811,3832],[0,0,3807,3833],[0,0,3796,3833],[0,0,3796,3835],[8942,8945,3846,3849],[0,0,3850,3856],[0,0,3850,3858],[8979,8987,3861,3866],[0,0,3867,3870],[0,0,3861,3871],[0,0,3850,3871],[0,0,3846,3872],[0,0,3835,3872],[0,0,3835,3874],[9006,9009,3885,3888],[0,0,3889,3895],[0,0,3889,3897],[9043,9051,3900,3905],[0,0,3906,3909],[0,0,3900,3910],[0,0,3889,3910],[0,0,3885,3911],[0,0,3874,3911],[0,0,3874,3913],[9070,9073,3924,3927],[0,0,3928,3934],[0,0,3928,3936],[9107,9115,3939,3944],[0,0,3945,3948],[0,0,3939,3949],[0,0,3928,3949],[0,0,3924,3950],[0,0,3913,3950],[0,0,3913,3952],[9134,9137,3963,3966],[0,0,3967,3973],[0,0,3967,3975],[9171,9179,3978,3983],[0,0,3984,3987],[0,0,3978,3988],[0,0,3967,3988],[0,0,3963,3989],[0,0,3952,3989],[0,0,3952,3991],[9198,9201,4002,4005],[0,0,4006,4012],[0,0,4006,4014],[9235,9243,4017,4022],[0,0,4023,4026],[0,0,4017,4027],[0,0,4006,4027],[0,0,4002,4028],[0,0,3991,4028],[0,0,3991,4030],[0,0,4042,4044],[0,0,4047,4049],[0,0,4042,4049],[0,0,4052,4054],[0,0,4042,4054],[0,0,4057,4059],[0,0,4062,4064],[0,0,4057,4064],[0,0,4067,4069],[0,0,4057,4069],[0,0,4042,4069],[0,0,4071,4073],[0,0,4076,4078],[0,0,4071,4078],[0,0,4081,4083],[0,0,4071,4083],[0,0,4086,4088],[0,0,4091,4093],[0,0,4086,4093],[0,0,4096,4098],[0,0,4086,4098],[0,0,4071,4098],[0,0,4100,4102],[0,0,4105,4107],[0,0,4100,4107],[0,0,4110,4112],[0,0,4100,4112],[0,0,4115,4117],[0,0,4120,4122],[0,0,4115,4122],[0,0,4125,4127],[0,0,4115,4127],[0,0,4100,4127],[0,0,4129,4131],[0,0,4134,4136],[0,0,4129,4136],[0,0,4139,4141],[0,0,4129,4141],[0,0,4144,4146],[0,0,4149,4151],[0,0,4144,4151],[0,0,4154,4156],[0,0,4144,4156],[0,0,4129,4156],[0,0,4037,4157],[0,0,4030,4159],[682,696,3723,4163],[0,0,4212,4227],[0,0,4229,4240],[3003,3011,4253,4293],[3012,3020,4294,4334],[0,0,4335,4345],[0,0,4352,4358],[3051,3057,4360,4363],[0,0,4364,4365],[0,0,4360,4366],[0,0,4347,4367],[0,0,4294,4368],[3064,3078,4370,4416],[0,0,4417,4427],[0,0,4370,4428],[0,0,4253,4429],[0,0,4244,4429],[0,0,4244,4431],[0,0,4438,4439],[0,0,4438,4443],[0,0,4431,4445],[682,696,4163,4449],[0,0,4610,4615],[0,0,4556,4615],[0,0,4556,4617],[12612,12637,4624,4684],[0,0,4685,4690],[0,0,4624,4691],[12641,12666,4694,4754],[0,0,4755,4760],[0,0,4694,4761],[0,0,4624,4761],[0,0,4617,4763],[9276,9402,4449,4767],[0,0,4869,4875],[0,0,4876,4884],[0,0,4869,4884],[2723,2751,4887,4944],[0,0,4945,4968],[0,0,4969,4975],[0,0,4945,4975],[0,0,4887,4976],[2769,2780,4984,5027],[2781,2801,5028,5080],[2816,2822,5086,5089],[0,0,5090,5091],[0,0,5086,5092],[0,0,5094,5117],[0,0,5118,5122],[0,0,5094,5122],[2837,2843,5124,5127],[0,0,5128,5129],[0,0,5124,5130],[0,0,5081,5131],[0,0,5028,5132],[0,0,5134,5139],[0,0,5140,5148],[0,0,5134,5148],[0,0,4984,5149],[2866,2872,5151,5154],[0,0,5155,5156],[0,0,5151,5157],[0,0,4979,5158],[0,0,4887,5158],[0,0,4869,5158],[0,0,4869,5160],[470,623,4767,5204],[2680,2881,0,5204]]); __shadeup_gen_shader("shd_1701801860004512470030001480000000600500422857", { webgl: {}, webgpu: {"attributeInput":"","attributeOutput":"","locals":[],"globals":[]} }, {webgpu: `fn shadeup_up_swizzle_xxxx_i32(n: i32) -> vec4{ return vec4(n, n, n, n); } struct ShaderInput { @align(16) position: vec3, @align(16) normal: vec3, @align(16) tangent: vec3, @align(16) bitangent: vec3, @align(16) clipPosition: vec4, @align(16) realPosition: vec4, @align(16) uv: vec2, @align(16) screen: vec2, @align(16) color: vec4, @align(16) groupId: vec3, @align(16) groupSize: vec3, @align(16) globalId: vec3, @align(16) localId: vec3, @align(16) instanceIndex: i32, @align(16) vertexIndex: i32, }; struct ShaderOutput { @align(16) position: vec4, @align(16) normal: vec3, @align(16) tangent: vec3, @align(16) bitangent: vec3, @align(16) uv: vec2, @align(16) color: vec4, // %SHADER_ShaderOutput% }; struct _InUniformsStruct { /*SHADEUP_UNIFORM_STRUCT_START*/ dummy: vec4, }; @group(%GROUP_INDEX%) @binding(1) var _in_uniforms: _InUniformsStruct; /*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/ fn main(/*__SHADEUP_TEMPLATE_INPUT*/)-> /*__SHADEUP_TEMPLATE_OUTPUT*/{ /*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/ _i_out.color = vec4f(shadeup_up_swizzle_xxxx_i32(i32(1))); /*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/ } `,webgl:`ivec4 shadeup_up_swizzle_xxxx_int(int n) { return ivec4(n, n, n, n); } ivec4 shadeup_up_swizzle_xxxx_int(int n) { return ivec4(n, n, n, n); } ivec2 shadeup_up_swizzle_xy_int(int n) { return ivec2(n, n); } ivec3 shadeup_up_swizzle_xyz_int(int n) { return ivec3(n, n, n); } ivec4 shadeup_up_swizzle_xxxx_int(int n) { return ivec4(n, n, n, n); } ivec2 shadeup_up_swizzle_xy_int(int n) { return ivec2(n, n); } ivec3 shadeup_up_swizzle_xyz_int(int n) { return ivec3(n, n, n); } ivec4 shadeup_up_swizzle_xyzw_int(int n) { return ivec4(n, n, n, n); } ivec4 shadeup_up_swizzle_xxxx_int(int n) { return ivec4(n, n, n, n); } struct ShaderInput { vec3 position; vec3 normal; vec3 tangent; vec3 bitangent; vec4 clipPosition; vec4 realPosition; vec2 uv; vec2 screen; vec4 color; ivec3 groupId; ivec3 groupSize; ivec3 globalId; ivec3 localId; int instanceIndex; int vertexIndex; }; struct ShaderOutput { vec4 position; vec3 normal; vec3 tangent; vec3 bitangent; vec2 uv; vec4 color; }; /*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/ void main() { /*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/ _i_out.color = vec4(shadeup_up_swizzle_xxxx_int(int(1))); /*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/ } `, software: () => {}}, [[2830,2865,21,38],[2939,2972,38,53],[3048,3082,53,69],[3162,3198,69,87],[3242,3284,87,108],[3289,3331,108,129],[3400,3426,129,140],[3502,3532,140,155],[3609,3644,155,169],[3690,3720,169,186],[3768,3800,186,205],[3879,3910,205,223],[3956,3986,223,240],[4051,4074,240,261],[4123,4144,261,280],[2728,4283,0,284],[4371,4409,306,323],[4444,4477,323,338],[4513,4547,338,354],[4585,4621,354,372],[4655,4681,372,383],[4714,4749,383,397],[4309,4869,284,401],[0,0,503,509],[0,0,510,515],[0,0,503,515],[2234,2240,551,554],[0,0,555,556],[0,0,551,557],[0,0,523,558],[0,0,503,559],[0,0,503,561],[166,199,401,605],[2191,2255,0,605]]); var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; define(["require", "exports", "/std_math", "/std_math", "/std___std_all", "/_std/drawIndexed", "/_std/common", "/_std/mesh"], function (require, exports, __, std_math_1, std___std_all_1, drawIndexed_1, common_1, mesh_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.main = exports.setModel = exports.setTexture = void 0; __ = __importStar(__); var globalVarGet = std___std_all_1.globalVarGet; // with a size of 100 units (100.xyz) var cube = (0, std___std_all_1.globalVarInit)("_slash_main_dot_ts", "cube", function () { var _a, _b; return mesh_1.mesh.box((_a = (0 | 0), [_a, _a, _a]), (_b = (100 | 0), [_b, _b, _b])); }, function () { return cube; }); var tex = (0, std___std_all_1.globalVarInit)("_slash_main_dot_ts", "tex", function () { var _a; return (0, common_1.texture2d)((_a = (10 | 0), [_a, _a]), "auto", "float4"); }, function () { return tex; }); tex.draw(__shadeup_make_shader_inst("shd_1701801860004512470030001480000000600500422857", {}, /**@shadeup=shader*/ function (__in, __out) { return __awaiter(void 0, void 0, void 0, function () { var _a; return __generator(this, function (_b) { __out.color = (_a = (1 | 0), [_a, _a, _a, _a]); return [2 /*return*/]; }); }); })); function setTexture(newTex) { tex = newTex; } exports.setTexture = setTexture; ; function setModel(newModel) { var _a; cube = newModel.parts[(0 | 0)].mesh.scale((_a = (20 | 0), [_a, _a, _a])); tex = newModel.parts[(0 | 0)].material.color; } exports.setModel = setModel; ; function main() { var _this = this; common_1.ui.button("Hello, world!"); (0, drawIndexed_1.draw)(cube, __shadeup_make_shader_inst("shd_0012035060108500265800533466056020000547600000", { _ext_uniform_global_env: globalVarGet("_slash__std_slash_native_dot_ts", "env") }, /**@shadeup=shader*/ function (__in, __out) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { __out.position = __.mul(env.camera.getCombinedMatrix(), __.makeVector(common_1.quat.rotate(common_1.quat.fromEulerAngles(__.makeVector((0 | 0), env.time, (0 | 0))), __in.position), (1 | 0))); return [2 /*return*/]; }); }); }), __shadeup_make_shader_inst("shd_000710086052666091061257200756375023002800009", { _ext_uniform_global_tex: globalVarGet("_slash_main_dot_ts", "tex") }, /**@shadeup=shader*/ function (__in, __out) { return __awaiter(_this, void 0, void 0, function () { var normal, lightDir, diffuse; var _a, _b, _c; return __generator(this, function (_d) { normal = (0, std_math_1.normalize)(__in.normal); lightDir = (0, std_math_1.normalize)(__.makeVector((2 | 0), 4.0, 0.5)); diffuse = (_a = (0, std_math_1.max)((0, std_math_1.dot)(normal, lightDir), 0.0), _b = tex.sample(__in.uv), [_a * _b[0], _a * _b[1], _a * _b[2], _a * _b[3]]); // Output the color __out.color = __.makeVector((_c = diffuse, [_c[0], _c[1], _c[2]]), (1 | 0)); return [2 /*return*/]; }); }); })); } exports.main = main; }); })(define); }); ================================================ FILE: cli/test/vite-project/src/main.shadeup ================================================ // Create a cube at the origin (0.xyz) // with a size of 100 units (100.xyz) let cube = mesh::box(0.xyz, 100.xyz); let tex = texture2d(10.xy); tex.draw(shader { out.color = 1.xxxx; }); pub fn setTexture(newTex: texture2d) { tex = newTex; } pub fn setModel(newModel: Model) { cube = newModel.parts[0].mesh.scale(20.xxx); tex = newModel.parts[0].material.color; } fn main() { ui::button("Hello, world!"); draw( cube, shader { out.position = env.camera.getCombinedMatrix() * (quat::rotate(quat::fromEulerAngles((0, env.time, 0)), in.position), 1); }, shader { // Calculate the normal of the surface let normal = normalize(in.normal); // Calculate the direction of the light let lightDir = normalize((2, 4.0, 0.5)); // Calculate the diffuse lighting let diffuse = max(dot(normal, lightDir), 0.0) * tex.sample(in.uv); // Output the color out.color = (diffuse.xyz, 1); } ); } ================================================ FILE: cli/test/vite-project/src/style.css ================================================ :root { font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; line-height: 1.5; font-weight: 400; color-scheme: light dark; color: rgba(255, 255, 255, 0.87); background-color: #242424; font-synthesis: none; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } a { font-weight: 500; color: #646cff; text-decoration: inherit; } a:hover { color: #535bf2; } body { margin: 0; display: flex; place-items: center; min-width: 320px; min-height: 100vh; } h1 { font-size: 3.2em; line-height: 1.1; } #app { max-width: 1280px; margin: 0 auto; padding: 2rem; text-align: center; } .logo { height: 6em; padding: 1.5em; will-change: filter; transition: filter 300ms; } .logo:hover { filter: drop-shadow(0 0 2em #646cffaa); } .logo.vanilla:hover { filter: drop-shadow(0 0 2em #3178c6aa); } .card { padding: 2em; } .read-the-docs { color: #888; } button { border-radius: 8px; border: 1px solid transparent; padding: 0.6em 1.2em; font-size: 1em; font-weight: 500; font-family: inherit; background-color: #1a1a1a; cursor: pointer; transition: border-color 0.25s; } button:hover { border-color: #646cff; } button:focus, button:focus-visible { outline: 4px auto -webkit-focus-ring-color; } @media (prefers-color-scheme: light) { :root { color: #213547; background-color: #ffffff; } a:hover { color: #747bff; } button { background-color: #f9f9f9; } } ================================================ FILE: cli/test/vite-project/src/vite-env.d.ts ================================================ /// ================================================ FILE: cli/test/vite-project/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2020", "DOM", "DOM.Iterable"], "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src"] } ================================================ FILE: cli/vite/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: cli/vite/index.html ================================================ Vite App
================================================ FILE: cli/vite/main.js ================================================ import "./style.css"; import { makeShadeupInstance } from "./runner"; const canvas = document.querySelector("#canvas"); (async () => { let engine = await makeShadeupInstance(canvas, { ui: true, }); })(); function sizeCanvas() { canvas.width = window.innerWidth * devicePixelRatio; canvas.height = window.innerHeight * devicePixelRatio; } sizeCanvas(); window.addEventListener("resize", sizeCanvas); ================================================ FILE: cli/vite/package.json ================================================ { "name": "vite-project", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "devDependencies": { "vite": "^5.1.0" }, "dependencies": { "shadeup": "^1.3.6" } } ================================================ FILE: cli/vite/runner.d.ts ================================================ import * as __ from "shadeup/math"; declare namespace ShadeupFiles { declare namespace sand { export declare function pcg_hash(input: __.uint): __.uint; export declare function main(): void; } declare namespace camera { declare class CustomCamera2d { constructor(data: { position?: __.float2; zoom?: __.float; }); screenToCamera(screen: __.float2): __.float2; cameraToScreen(camera: __.float2): __.float2; transform(position: __.float2): __.float2; zoomBy(zoom: __.float, center: __.float2): void; position: __.float2; zoom: __.float; clone(): CustomCamera2d; } export declare function getCamera2d(): CustomCamera2d; export {}; } } export declare function makeShadeupInstance( canvas: HTMLCanvasElement, options?: { preferredAdapter?: "webgl" | "webgpu"; limits?: GPUSupportedLimits; ui?: boolean; } ): Promise<{ /** * Set to false to pause */ playing: boolean; canvas: HTMLCanvasElement; adapter: any; hooks: { beforeFrame?: () => void; afterFrame?: () => void; reset?: () => void; }[]; start: () => void; env: { camera: { position: __.float3; rotation: __.float4; width: __.float; height: __.float; fov: __.float; near: __.float; far: __.float; }; camera2d: { position: __.float2; zoom: __.float; }; deltaTime: __.float; frame: __.int; keyboard: any; mouse: any; screenSize: __.float2; time: __.float; }; /** * Used to pass values into the shadeup env (accessed as env.input("name") inside) */ inputValues: Map; enableUI: () => Promise; loadTextureFromImageLike: ( img: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas | HTMLVideoElement ) => Promise<__.texture2d<__.float4>>; loadTexture2dFromURL: (url: string) => Promise<__.texture2d<__.float4>>; loadModelFromURL: (urlGltf: string) => Promise<__.texture2d<__.float4>>; files: typeof ShadeupFiles; }>; ================================================ FILE: cli/vite/runner.js ================================================ export const makeShadeupInstance = async (canvas) => { return { enableUI: async () => {}, }; }; ================================================ FILE: cli/vite/style.css ================================================ html, body { margin: 0; padding: 0; font-family: "Roboto", sans-serif; background-color: black; overflow: hidden; } .puck { position: absolute; width: 20px; height: 20px; border-radius: 50%; /* transform: translate(-50%, -50%); */ background-color: #3a3a3a; box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16); cursor: grab; display: flex; justify-content: center; align-items: center; color: rgb(80, 80, 80); user-select: none; font-family: monospace; line-height: 12px; font-size: 12px; } .puck[data-down="true"] { cursor: grabbing; } .puck span { height: 14px; } ================================================ FILE: cli/vite/vite.config.js ================================================ /** @type {import('vite').UserConfig} */ export default { // ... }; ================================================ FILE: extension/vscode/shadeup/.vscodeignore ================================================ .vscode/** .vscode-test/** .gitignore ================================================ FILE: extension/vscode/shadeup/CHANGELOG.md ================================================ # Change Log All notable changes to the "shadeup" extension will be documented in this file. Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file. ## [Unreleased] - Initial release ================================================ FILE: extension/vscode/shadeup/README.md ================================================ ![logo](https://raw.githubusercontent.com/AskingQuestions/Shadeup/main/unreal-engine/resources/img/logo.png) # Shadeup Language Support [BETA] ### [shadeup.dev](https://shadeup.dev) This extension provides language support for the Shadeup language. ## Features - Syntax highlighting for Shadeup files - Shadeup language server - Intellisense - Diagnostics - Hover - File icon for Shadeup files ## Release Notes ### 1.0.0 Initial release ================================================ FILE: extension/vscode/shadeup/Shadeup-tmLanguage.json ================================================ { "information_for_contributors": [ "This file has been converted from https://github.com/microsoft/TypeScript-TmLanguage/blob/master/TypeScript.tmLanguage", "If you want to provide a fix or improvement, please create a pull request against the original repository.", "Once accepted there, we are happy to receive an update request." ], "version": "https://github.com/microsoft/TypeScript-TmLanguage/commit/b80b7509a78e642f789c567e144ed951ab98b4e3", "name": "Shadeup", "scopeName": "source.shadeup", "patterns": [ { "include": "#directives" }, { "include": "#statements" }, { "include": "#shebang" } ], "repository": { "shebang": { "name": "comment.line.shebang.shadeup", "match": "\\A(#!).*(?=$)", "captures": { "1": { "name": "punctuation.definition.comment.shadeup" } } }, "statements": { "patterns": [ { "include": "#declaration" }, { "include": "#control-statement" }, { "include": "#after-operator-block-as-object-literal" }, { "include": "#decl-block" }, { "include": "#label" }, { "include": "#expression" }, { "include": "#punctuation-semicolon" }, { "include": "#string" }, { "include": "#comment" } ] }, "declaration": { "patterns": [ { "include": "#decorator" }, { "include": "#var-expr" }, { "include": "#function-declaration" }, { "include": "#class-declaration" }, { "include": "#interface-declaration" }, { "include": "#enum-declaration" }, { "include": "#namespace-declaration" }, { "include": "#type-alias-declaration" }, { "include": "#import-equals-declaration" }, { "include": "#import-declaration" }, { "include": "#export-declaration" }, { "name": "storage.modifier.shadeup", "match": "(?)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)) |\n# typeannotation is fn type: < | () | (... | (param: | (param, | (param? | (param= | (param) =>\n(:\\s*(\n (<) |\n ([(]\\s*(\n ([)]) |\n (\\.\\.\\.) |\n ([_$[:alnum:]]+\\s*(\n ([:,?=])|\n ([)]\\s*=>)\n ))\n ))\n)) |\n(:\\s*(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*))))))) |\n(:\\s*(=>|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(<[^<>]*>)|[^<>(),=])+=\\s*(\n ((async\\s+)?(\n (function\\s*[(<*]) |\n (function\\s+) |\n ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)))", "beginCaptures": { "1": { "name": "meta.definition.variable.shadeup entity.name.function.shadeup" }, "2": { "name": "keyword.operator.definiteassignment.shadeup" } }, "end": "(?=$|^|[;,=}]|((?)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)) |\n# typeannotation is fn type: < | () | (... | (param: | (param, | (param? | (param= | (param) =>\n(:\\s*(\n (<) |\n ([(]\\s*(\n ([)]) |\n (\\.\\.\\.) |\n ([_$[:alnum:]]+\\s*(\n ([:,?=])|\n ([)]\\s*=>)\n ))\n ))\n)) |\n(:\\s*(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*))))))) |\n(:\\s*(=>|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(<[^<>]*>)|[^<>(),=])+=\\s*(\n ((async\\s+)?(\n (function\\s*[(<*]) |\n (function\\s+) |\n ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)))", "beginCaptures": { "1": { "name": "meta.definition.variable.shadeup variable.other.constant.shadeup entity.name.function.shadeup" } }, "end": "(?=$|^|[;,=}]|((?)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)) |\n# typeannotation is fn type: < | () | (... | (param: | (param, | (param? | (param= | (param) =>\n(:\\s*(\n (<) |\n ([(]\\s*(\n ([)]) |\n (\\.\\.\\.) |\n ([_$[:alnum:]]+\\s*(\n ([:,?=])|\n ([)]\\s*=>)\n ))\n ))\n)) |\n(:\\s*(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*))))))) |\n(:\\s*(=>|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(<[^<>]*>)|[^<>(),=])+=\\s*(\n ((async\\s+)?(\n (function\\s*[(<*]) |\n (function\\s+) |\n ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)))", "captures": { "1": { "name": "storage.modifier.shadeup" }, "2": { "name": "keyword.operator.rest.shadeup" }, "3": { "name": "entity.name.function.shadeup variable.language.this.shadeup" }, "4": { "name": "entity.name.function.shadeup" }, "5": { "name": "keyword.operator.optional.shadeup" } } }, { "match": "(?x)(?:(?)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)) |\n# typeannotation is fn type: < | () | (... | (param: | (param, | (param? | (param= | (param) =>\n(:\\s*(\n (<) |\n ([(]\\s*(\n ([)]) |\n (\\.\\.\\.) |\n ([_$[:alnum:]]+\\s*(\n ([:,?=])|\n ([)]\\s*=>)\n ))\n ))\n)) |\n(:\\s*(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*))))))) |\n(:\\s*(=>|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(<[^<>]*>)|[^<>(),=])+=\\s*(\n ((async\\s+)?(\n (function\\s*[(<*]) |\n (function\\s+) |\n ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)))", "captures": { "1": { "name": "meta.definition.property.shadeup entity.name.function.shadeup" }, "2": { "name": "keyword.operator.optional.shadeup" }, "3": { "name": "keyword.operator.definiteassignment.shadeup" } } }, { "name": "meta.definition.property.shadeup variable.object.property.shadeup", "match": "\\#?[_$[:alpha:]][_$[:alnum:]]*" }, { "name": "keyword.operator.optional.shadeup", "match": "\\?" }, { "name": "keyword.operator.definiteassignment.shadeup", "match": "\\!" } ] }, "variable-initializer": { "patterns": [ { "begin": "(?\\s*$)", "beginCaptures": { "1": { "name": "keyword.operator.assignment.shadeup" } }, "end": "(?=$|^|[,);}\\]]|((?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*))?[\\(])", "beginCaptures": { "1": { "name": "storage.modifier.shadeup" }, "2": { "name": "storage.modifier.shadeup" }, "3": { "name": "storage.modifier.shadeup" }, "4": { "name": "storage.modifier.async.shadeup" }, "5": { "name": "keyword.operator.new.shadeup" }, "6": { "name": "keyword.generator.asterisk.shadeup" } }, "end": "(?=\\}|;|,|$)|(?<=\\})", "patterns": [ { "include": "#method-declaration-name" }, { "include": "#function-body" } ] }, { "name": "meta.method.declaration.shadeup", "begin": "(?x)(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*))?[\\(])", "beginCaptures": { "1": { "name": "storage.modifier.shadeup" }, "2": { "name": "storage.modifier.shadeup" }, "3": { "name": "storage.modifier.shadeup" }, "4": { "name": "storage.modifier.async.shadeup" }, "5": { "name": "storage.type.property.shadeup" }, "6": { "name": "keyword.generator.asterisk.shadeup" } }, "end": "(?=\\}|;|,|$)|(?<=\\})", "patterns": [ { "include": "#method-declaration-name" }, { "include": "#function-body" } ] } ] }, "object-literal-method-declaration": { "name": "meta.method.declaration.shadeup", "begin": "(?x)(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*))?[\\(])", "beginCaptures": { "1": { "name": "storage.modifier.async.shadeup" }, "2": { "name": "storage.type.property.shadeup" }, "3": { "name": "keyword.generator.asterisk.shadeup" } }, "end": "(?=\\}|;|,)|(?<=\\})", "patterns": [ { "include": "#method-declaration-name" }, { "include": "#function-body" }, { "begin": "(?x)(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*))?[\\(])", "beginCaptures": { "1": { "name": "storage.modifier.async.shadeup" }, "2": { "name": "storage.type.property.shadeup" }, "3": { "name": "keyword.generator.asterisk.shadeup" } }, "end": "(?=\\(|\\<)", "patterns": [ { "include": "#method-declaration-name" } ] } ] }, "method-declaration-name": { "begin": "(?x)(?=((\\b(?)", "captures": { "1": { "name": "storage.modifier.async.shadeup" }, "2": { "name": "variable.parameter.shadeup" } } }, { "name": "meta.arrow.shadeup", "begin": "(?x) (?:\n (? is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n )\n)", "beginCaptures": { "1": { "name": "storage.modifier.async.shadeup" } }, "end": "(?==>|\\{|(^\\s*(export|function|class|interface|let|var|(?:\\busing(?=\\s+(?!in\\b|of\\b(?!\\s*(?:of\\b|=)))[_$[:alpha:]])\\b)|(?:\\bawait\\s+(?:\\busing(?=\\s+(?!in\\b|of\\b(?!\\s*(?:of\\b|=)))[_$[:alpha:]])\\b)\\b)|const|import|enum|namespace|module|type|abstract|declare)\\s+))", "patterns": [ { "include": "#comment" }, { "include": "#type-parameters" }, { "include": "#function-parameters" }, { "include": "#arrow-return-type" }, { "include": "#possibly-arrow-return-type" } ] }, { "name": "meta.arrow.shadeup", "begin": "=>", "beginCaptures": { "0": { "name": "storage.type.function.arrow.shadeup" } }, "end": "((?<=\\}|\\S)(?)|((?!\\{)(?=\\S)))(?!\\/[\\/\\*])", "patterns": [ { "include": "#single-line-comment-consuming-line-ending" }, { "include": "#decl-block" }, { "include": "#expression" } ] } ] }, "indexer-declaration": { "name": "meta.indexer.declaration.shadeup", "begin": "(?:(?]|^await|[^\\._$[:alnum:]]await|^return|[^\\._$[:alnum:]]return|^yield|[^\\._$[:alnum:]]yield|^throw|[^\\._$[:alnum:]]throw|^in|[^\\._$[:alnum:]]in|^of|[^\\._$[:alnum:]]of|^typeof|[^\\._$[:alnum:]]typeof|&&|\\|\\||\\*)\\s*(\\{)", "beginCaptures": { "1": { "name": "punctuation.definition.block.shadeup" } }, "end": "\\}", "endCaptures": { "0": { "name": "punctuation.definition.block.shadeup" } }, "patterns": [ { "include": "#object-member" } ] }, "object-literal": { "name": "meta.objectliteral.shadeup", "begin": "\\{", "beginCaptures": { "0": { "name": "punctuation.definition.block.shadeup" } }, "end": "\\}", "endCaptures": { "0": { "name": "punctuation.definition.block.shadeup" } }, "patterns": [ { "include": "#object-member" } ] }, "object-member": { "patterns": [ { "include": "#comment" }, { "include": "#object-literal-method-declaration" }, { "name": "meta.object.member.shadeup meta.object-literal.key.shadeup", "begin": "(?=\\[)", "end": "(?=:)|((?<=[\\]])(?=\\s*[\\(\\<]))", "patterns": [ { "include": "#comment" }, { "include": "#array-literal" } ] }, { "name": "meta.object.member.shadeup meta.object-literal.key.shadeup", "begin": "(?=[\\'\\\"\\`])", "end": "(?=:)|((?<=[\\'\\\"\\`])(?=((\\s*[\\(\\<,}])|(\\s+(as|satisifies)\\s+))))", "patterns": [ { "include": "#comment" }, { "include": "#string" } ] }, { "name": "meta.object.member.shadeup meta.object-literal.key.shadeup", "begin": "(?x)(?=(\\b(?)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)))", "captures": { "0": { "name": "meta.object-literal.key.shadeup" }, "1": { "name": "entity.name.function.shadeup" } } }, { "name": "meta.object.member.shadeup", "match": "(?:[_$[:alpha:]][_$[:alnum:]]*)\\s*(?=(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*:)", "captures": { "0": { "name": "meta.object-literal.key.shadeup" } } }, { "name": "meta.object.member.shadeup", "begin": "\\.\\.\\.", "beginCaptures": { "0": { "name": "keyword.operator.spread.shadeup" } }, "end": "(?=,|\\})", "patterns": [ { "include": "#expression" } ] }, { "name": "meta.object.member.shadeup", "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(?=,|\\}|$|\\/\\/|\\/\\*)", "captures": { "1": { "name": "variable.other.readwrite.shadeup" } } }, { "name": "meta.object.member.shadeup", "match": "(?]|\\|\\||\\&\\&|\\!\\=\\=|$|^|((?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)\\(\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))", "beginCaptures": { "1": { "name": "storage.modifier.async.shadeup" } }, "end": "(?<=\\))", "patterns": [ { "include": "#type-parameters" }, { "begin": "\\(", "beginCaptures": { "0": { "name": "meta.brace.round.shadeup" } }, "end": "\\)", "endCaptures": { "0": { "name": "meta.brace.round.shadeup" } }, "patterns": [ { "include": "#expression-inside-possibly-arrow-parens" } ] } ] }, { "begin": "(?<=:)\\s*(async)?\\s*(\\()(?=\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))", "beginCaptures": { "1": { "name": "storage.modifier.async.shadeup" }, "2": { "name": "meta.brace.round.shadeup" } }, "end": "\\)", "endCaptures": { "0": { "name": "meta.brace.round.shadeup" } }, "patterns": [ { "include": "#expression-inside-possibly-arrow-parens" } ] }, { "begin": "(?<=:)\\s*(async)?\\s*(?=\\<\\s*$)", "beginCaptures": { "1": { "name": "storage.modifier.async.shadeup" } }, "end": "(?<=\\>)", "patterns": [ { "include": "#type-parameters" } ] }, { "begin": "(?<=\\>)\\s*(\\()(?=\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))", "beginCaptures": { "1": { "name": "meta.brace.round.shadeup" } }, "end": "\\)", "endCaptures": { "0": { "name": "meta.brace.round.shadeup" } }, "patterns": [ { "include": "#expression-inside-possibly-arrow-parens" } ] }, { "include": "#possibly-arrow-return-type" }, { "include": "#expression" } ] }, { "include": "#punctuation-comma" }, { "include": "#decl-block" } ] }, "ternary-expression": { "begin": "(?!\\?\\.\\s*[^[:digit:]])(\\?)(?!\\?)", "beginCaptures": { "1": { "name": "keyword.operator.ternary.shadeup" } }, "end": "\\s*(:)", "endCaptures": { "1": { "name": "keyword.operator.ternary.shadeup" } }, "patterns": [ { "include": "#expression" } ] }, "function-call": { "patterns": [ { "begin": "(?=(((([_$[:alpha:]][_$[:alnum:]]*)(\\s*\\??\\.\\s*(\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\??\\.\\s*\\#?[_$[:alpha:]][_$[:alnum:]]*))|(?<=[\\)]))\\s*(?:(\\?\\.\\s*)|(\\!))?((<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))(([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>)*(?))*(?)*(?\\s*)?\\())", "end": "(?<=\\))(?!(((([_$[:alpha:]][_$[:alnum:]]*)(\\s*\\??\\.\\s*(\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\??\\.\\s*\\#?[_$[:alpha:]][_$[:alnum:]]*))|(?<=[\\)]))\\s*(?:(\\?\\.\\s*)|(\\!))?((<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))(([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>)*(?))*(?)*(?\\s*)?\\())", "patterns": [ { "name": "meta.function-call.shadeup", "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)(\\s*\\??\\.\\s*(\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\??\\.\\s*\\#?[_$[:alpha:]][_$[:alnum:]]*))", "end": "(?=\\s*(?:(\\?\\.\\s*)|(\\!))?((<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))(([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>)*(?))*(?)*(?\\s*)?\\())", "patterns": [ { "include": "#function-call-target" } ] }, { "include": "#comment" }, { "include": "#function-call-optionals" }, { "include": "#type-arguments" }, { "include": "#paren-expression" } ] }, { "begin": "(?=(((([_$[:alpha:]][_$[:alnum:]]*)(\\s*\\??\\.\\s*(\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\??\\.\\s*\\#?[_$[:alpha:]][_$[:alnum:]]*))|(?<=[\\)]))(<\\s*[\\{\\[\\(]\\s*$))", "end": "(?<=\\>)(?!(((([_$[:alpha:]][_$[:alnum:]]*)(\\s*\\??\\.\\s*(\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\??\\.\\s*\\#?[_$[:alpha:]][_$[:alnum:]]*))|(?<=[\\)]))(<\\s*[\\{\\[\\(]\\s*$))", "patterns": [ { "name": "meta.function-call.shadeup", "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*)(\\s*\\??\\.\\s*(\\#?[_$[:alpha:]][_$[:alnum:]]*))*)|(\\??\\.\\s*\\#?[_$[:alpha:]][_$[:alnum:]]*))", "end": "(?=(<\\s*[\\{\\[\\(]\\s*$))", "patterns": [ { "include": "#function-call-target" } ] }, { "include": "#comment" }, { "include": "#function-call-optionals" }, { "include": "#type-arguments" } ] } ] }, "function-call-target": { "patterns": [ { "include": "#support-function-call-identifiers" }, { "name": "entity.name.function.shadeup", "match": "(\\#?[_$[:alpha:]][_$[:alnum:]]*)" } ] }, "function-call-optionals": { "patterns": [ { "name": "meta.function-call.shadeup punctuation.accessor.optional.shadeup", "match": "\\?\\." }, { "name": "meta.function-call.shadeup keyword.operator.definiteassignment.shadeup", "match": "\\!" } ] }, "support-function-call-identifiers": { "patterns": [ { "include": "#literal" }, { "include": "#support-objects" }, { "include": "#object-identifiers" }, { "include": "#punctuation-accessor" }, { "name": "keyword.operator.expression.import.shadeup", "match": "(?:(?]|\\|\\||\\&\\&|\\!\\=\\=|$|((?]|\\|\\||\\&\\&|\\!\\=\\=|$|(===|!==|==|!=)|(([\\&\\~\\^\\|]\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s+instanceof(?![_$[:alnum:]])(?:(?=\\.\\.\\.)|(?!\\.)))|((?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*))?\\(\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))", "beginCaptures": { "1": { "name": "storage.modifier.async.shadeup" } }, "end": "(?<=\\))", "patterns": [ { "include": "#paren-expression-possibly-arrow-with-typeparameters" } ] }, { "begin": "(?<=[(=,]|=>|^return|[^\\._$[:alnum:]]return)\\s*(async)?(?=\\s*((((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*))?\\()|(<)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)))\\s*$)", "beginCaptures": { "1": { "name": "storage.modifier.async.shadeup" } }, "end": "(?<=\\))", "patterns": [ { "include": "#paren-expression-possibly-arrow-with-typeparameters" } ] }, { "include": "#possibly-arrow-return-type" } ] }, "paren-expression-possibly-arrow-with-typeparameters": { "patterns": [ { "include": "#type-parameters" }, { "begin": "\\(", "beginCaptures": { "0": { "name": "meta.brace.round.shadeup" } }, "end": "\\)", "endCaptures": { "0": { "name": "meta.brace.round.shadeup" } }, "patterns": [ { "include": "#expression-inside-possibly-arrow-parens" } ] } ] }, "expression-inside-possibly-arrow-parens": { "patterns": [ { "include": "#expressionWithoutIdentifiers" }, { "include": "#comment" }, { "include": "#string" }, { "include": "#decorator" }, { "include": "#destructuring-parameter" }, { "match": "(?)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)) |\n# typeannotation is fn type: < | () | (... | (param: | (param, | (param? | (param= | (param) =>\n(:\\s*(\n (<) |\n ([(]\\s*(\n ([)]) |\n (\\.\\.\\.) |\n ([_$[:alnum:]]+\\s*(\n ([:,?=])|\n ([)]\\s*=>)\n ))\n ))\n)) |\n(:\\s*(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*))))))) |\n(:\\s*(=>|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(<[^<>]*>)|[^<>(),=])+=\\s*(\n ((async\\s+)?(\n (function\\s*[(<*]) |\n (function\\s+) |\n ([_$[:alpha:]][_$[:alnum:]]*\\s*=>)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n)))", "captures": { "1": { "name": "storage.modifier.shadeup" }, "2": { "name": "keyword.operator.rest.shadeup" }, "3": { "name": "entity.name.function.shadeup variable.language.this.shadeup" }, "4": { "name": "entity.name.function.shadeup" }, "5": { "name": "keyword.operator.optional.shadeup" } } }, { "match": "(?x)(?:(?)", "captures": { "1": { "name": "meta.brace.angle.shadeup" }, "2": { "name": "storage.modifier.shadeup" }, "3": { "name": "meta.brace.angle.shadeup" } } }, { "name": "cast.expr.shadeup", "begin": "(?:(?*?\\&\\|\\^]|[^_$[:alnum:]](?:\\+\\+|\\-\\-)|[^\\+]\\+|[^\\-]\\-))\\s*(<)(?!)", "endCaptures": { "1": { "name": "meta.brace.angle.shadeup" } }, "patterns": [ { "include": "#type" } ] }, { "name": "cast.expr.shadeup", "begin": "(?:(?<=^))\\s*(<)(?=[_$[:alpha:]][_$[:alnum:]]*\\s*>)", "beginCaptures": { "1": { "name": "meta.brace.angle.shadeup" } }, "end": "(\\>)", "endCaptures": { "1": { "name": "meta.brace.angle.shadeup" } }, "patterns": [ { "include": "#type" } ] } ] }, "expression-operators": { "patterns": [ { "name": "keyword.control.flow.shadeup", "match": "(?]|\\|\\||\\&\\&|\\!\\=\\=|$|((?>=|>>>=|\\|=" }, { "name": "keyword.operator.bitwise.shift.shadeup", "match": "<<|>>>|>>" }, { "name": "keyword.operator.comparison.shadeup", "match": "===|!==|==|!=" }, { "name": "keyword.operator.relational.shadeup", "match": "<=|>=|<>|<|>" }, { "match": "(?<=[_$[:alnum:]])(\\!)\\s*(?:(/=)|(?:(/)(?![/*])))", "captures": { "1": { "name": "keyword.operator.logical.shadeup" }, "2": { "name": "keyword.operator.assignment.compound.shadeup" }, "3": { "name": "keyword.operator.arithmetic.shadeup" } } }, { "name": "keyword.operator.logical.shadeup", "match": "\\!|&&|\\|\\||\\?\\?" }, { "name": "keyword.operator.bitwise.shadeup", "match": "\\&|~|\\^|\\|" }, { "name": "keyword.operator.assignment.shadeup", "match": "\\=" }, { "name": "keyword.operator.decrement.shadeup", "match": "--" }, { "name": "keyword.operator.increment.shadeup", "match": "\\+\\+" }, { "name": "keyword.operator.arithmetic.shadeup", "match": "%|\\*|/|-|\\+" }, { "begin": "(?<=[_$[:alnum:])\\]])\\s*(?=(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)+(?:(/=)|(?:(/)(?![/*]))))", "end": "(?:(/=)|(?:(/)(?!\\*([^\\*]|(\\*[^\\/]))*\\*\\/)))", "endCaptures": { "1": { "name": "keyword.operator.assignment.compound.shadeup" }, "2": { "name": "keyword.operator.arithmetic.shadeup" } }, "patterns": [ { "include": "#comment" } ] }, { "match": "(?<=[_$[:alnum:])\\]])\\s*(?:(/=)|(?:(/)(?![/*])))", "captures": { "1": { "name": "keyword.operator.assignment.compound.shadeup" }, "2": { "name": "keyword.operator.arithmetic.shadeup" } } } ] }, "typeof-operator": { "begin": "(?:&|{\\?]|(extends\\s+)|$|;|^\\s*$|(?:^\\s*(?:abstract|async|(?:\\bawait\\s+(?:\\busing(?=\\s+(?!in\\b|of\\b(?!\\s*(?:of\\b|=)))[_$[:alpha:]])\\b)\\b)|break|case|catch|class|const|continue|declare|do|else|enum|export|finally|for|goto|if|import|interface|let|module|namespace|switch|return|throw|try|type|impl|struct|fn|trait|shader|workgroup|pub|(?:\\busing(?=\\s+(?!in\\b|of\\b(?!\\s*(?:of\\b|=)))[_$[:alpha:]])\\b)|var|while)\\b))", "patterns": [ { "include": "#type-arguments" }, { "include": "#expression" } ] }, "literal": { "patterns": [ { "include": "#numeric-literal" }, { "include": "#boolean-literal" }, { "include": "#null-literal" }, { "include": "#undefined-literal" }, { "include": "#numericConstant-literal" }, { "include": "#array-literal" }, { "include": "#this-literal" }, { "include": "#super-literal" } ] }, "array-literal": { "name": "meta.array.literal.shadeup", "begin": "\\s*(\\[)", "beginCaptures": { "1": { "name": "meta.brace.square.shadeup" } }, "end": "\\]", "endCaptures": { "0": { "name": "meta.brace.square.shadeup" } }, "patterns": [ { "include": "#expression" }, { "include": "#punctuation-comma" } ] }, "numeric-literal": { "patterns": [ { "name": "constant.numeric.hex.shadeup", "match": "\\b(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\\())\n |\n (?:(EPSILON|MAX_SAFE_INTEGER|MAX_VALUE|MIN_SAFE_INTEGER|MIN_VALUE|NEGATIVE_INFINITY|POSITIVE_INFINITY)\\b(?!\\$)))", "captures": { "1": { "name": "punctuation.accessor.shadeup" }, "2": { "name": "punctuation.accessor.optional.shadeup" }, "3": { "name": "support.variable.property.shadeup" }, "4": { "name": "support.constant.shadeup" } } }, { "match": "(?)\n )) |\n ((async\\s*)?(\n ((<\\s*$)|((<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))))) |\n # sure shot arrow functions even if => is on new line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?\n [(]\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*\n (\n ([)]\\s*:) | # ():\n ((\\.\\.\\.\\s*)?[_$[:alpha:]][_$[:alnum:]]*\\s*:) # [(]param: | [(]...param:\n )\n) |\n\n# arrow function possible to detect only with => on same line\n(\n (<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)? # typeparameters\n \\(\\s*(\\/\\*([^\\*]|(\\*[^\\/]))*\\*\\/\\s*)*(([_$[:alpha:]]|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\.\\.\\.\\s*[_$[:alpha:]]))([^()\\'\\\"\\`]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))*)?\\) # parameters\n (\\s*:\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+)? # return type\n \\s*=> # arrow operator\n)\n ))\n))", "captures": { "1": { "name": "punctuation.accessor.shadeup" }, "2": { "name": "punctuation.accessor.optional.shadeup" }, "3": { "name": "entity.name.function.shadeup" } } }, { "match": "(?:(\\.)|(\\?\\.(?!\\s*[[:digit:]])))\\s*(\\#?[[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])", "captures": { "1": { "name": "punctuation.accessor.shadeup" }, "2": { "name": "punctuation.accessor.optional.shadeup" }, "3": { "name": "variable.other.constant.property.shadeup" } } }, { "match": "(?:(\\.)|(\\?\\.(?!\\s*[[:digit:]])))\\s*(\\#?[_$[:alpha:]][_$[:alnum:]]*)", "captures": { "1": { "name": "punctuation.accessor.shadeup" }, "2": { "name": "punctuation.accessor.optional.shadeup" }, "3": { "name": "variable.other.property.shadeup" } } }, { "name": "variable.other.constant.shadeup", "match": "([[:upper:]][_$[:digit:][:upper:]]*)(?![_$[:alnum:]])" }, { "name": "variable.other.readwrite.shadeup", "match": "[_$[:alpha:]][_$[:alnum:]]*" } ] }, "object-identifiers": { "patterns": [ { "name": "support.class.shadeup", "match": "([_$[:alpha:]][_$[:alnum:]]*)(?=\\s*\\??\\.\\s*prototype\\b(?!\\$))" }, { "match": "(?x)(?:(\\.)|(\\?\\.(?!\\s*[[:digit:]])))\\s*(?:\n (\\#?[[:upper:]][_$[:digit:][:upper:]]*) |\n (\\#?[_$[:alpha:]][_$[:alnum:]]*)\n)(?=\\s*\\??\\.\\s*\\#?[_$[:alpha:]][_$[:alnum:]]*)", "captures": { "1": { "name": "punctuation.accessor.shadeup" }, "2": { "name": "punctuation.accessor.optional.shadeup" }, "3": { "name": "variable.other.constant.object.property.shadeup" }, "4": { "name": "variable.other.object.property.shadeup" } } }, { "match": "(?x)(?:\n ([[:upper:]][_$[:digit:][:upper:]]*) |\n ([_$[:alpha:]][_$[:alnum:]]*)\n)(?=\\s*\\??\\.\\s*\\#?[_$[:alpha:]][_$[:alnum:]]*)", "captures": { "1": { "name": "variable.other.constant.object.shadeup" }, "2": { "name": "variable.other.object.shadeup" } } } ] }, "type-annotation": { "patterns": [ { "name": "meta.type.annotation.shadeup", "begin": "(:)(?=\\s*\\S)", "beginCaptures": { "1": { "name": "keyword.operator.type.annotation.shadeup" } }, "end": "(?])|((?<=[\\}>\\]\\)]|[_$[:alpha:]])\\s*(?=\\{)))", "patterns": [ { "include": "#type" } ] }, { "name": "meta.type.annotation.shadeup", "begin": "(:)", "beginCaptures": { "1": { "name": "keyword.operator.type.annotation.shadeup" } }, "end": "(?])|(?=^\\s*$)|((?<=[\\}>\\]\\)]|[_$[:alpha:]])\\s*(?=\\{)))", "patterns": [ { "include": "#type" } ] } ] }, "parameter-type-annotation": { "patterns": [ { "name": "meta.type.annotation.shadeup", "begin": "(:)", "beginCaptures": { "1": { "name": "keyword.operator.type.annotation.shadeup" } }, "end": "(?=[,)])|(?==[^>])", "patterns": [ { "include": "#type" } ] } ] }, "return-type": { "patterns": [ { "name": "meta.return.type.shadeup", "begin": "(?<=\\))\\s*(:)(?=\\s*\\S)", "beginCaptures": { "1": { "name": "keyword.operator.type.annotation.shadeup" } }, "end": "(?|\\{|(^\\s*(export|function|class|interface|let|var|(?:\\busing(?=\\s+(?!in\\b|of\\b(?!\\s*(?:of\\b|=)))[_$[:alpha:]])\\b)|(?:\\bawait\\s+(?:\\busing(?=\\s+(?!in\\b|of\\b(?!\\s*(?:of\\b|=)))[_$[:alpha:]])\\b)\\b)|const|import|enum|namespace|module|type|abstract|declare)\\s+))", "patterns": [ { "include": "#arrow-return-type-body" } ] }, "possibly-arrow-return-type": { "begin": "(?<=\\)|^)\\s*(:)(?=\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*=>)", "beginCaptures": { "1": { "name": "meta.arrow.shadeup meta.return.type.arrow.shadeup keyword.operator.type.annotation.shadeup" } }, "end": "(?==>|\\{|(^\\s*(export|function|class|interface|let|var|(?:\\busing(?=\\s+(?!in\\b|of\\b(?!\\s*(?:of\\b|=)))[_$[:alpha:]])\\b)|(?:\\bawait\\s+(?:\\busing(?=\\s+(?!in\\b|of\\b(?!\\s*(?:of\\b|=)))[_$[:alpha:]])\\b)\\b)|const|import|enum|namespace|module|type|abstract|declare)\\s+))", "contentName": "meta.arrow.shadeup meta.return.type.arrow.shadeup", "patterns": [ { "include": "#arrow-return-type-body" } ] }, "arrow-return-type-body": { "patterns": [ { "begin": "(?<=[:])(?=\\s*\\{)", "end": "(?<=\\})", "patterns": [ { "include": "#type-object" } ] }, { "include": "#type-predicate-operator" }, { "include": "#type" } ] }, "type-parameters": { "name": "meta.type.parameters.shadeup", "begin": "(<)", "beginCaptures": { "1": { "name": "punctuation.definition.typeparameters.begin.shadeup" } }, "end": "(>)", "endCaptures": { "1": { "name": "punctuation.definition.typeparameters.end.shadeup" } }, "patterns": [ { "include": "#comment" }, { "name": "storage.modifier.shadeup", "match": "(?)" } ] }, "type-arguments": { "name": "meta.type.parameters.shadeup", "begin": "\\<", "beginCaptures": { "0": { "name": "punctuation.definition.typeparameters.begin.shadeup" } }, "end": "\\>", "endCaptures": { "0": { "name": "punctuation.definition.typeparameters.end.shadeup" } }, "patterns": [ { "include": "#type-arguments-body" } ] }, "type-arguments-body": { "patterns": [ { "match": "(?)\n ))\n ))\n)) |\n(:\\s*(?]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<]|\\<\\s*(((const\\s+)?[_$[:alpha:]])|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\]))([^=<>]|=[^<])*\\>)*\\>)*>\\s*)?[\\(]\\s*((([\\{\\[]\\s*)?$)|((\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})\\s*((:\\s*\\{?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*)))|((\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])\\s*((:\\s*\\[?$)|((\\s*([^<>\\(\\)\\{\\}]|\\<([^<>]|\\<([^<>]|\\<[^<>]+\\>)+\\>)+\\>|\\([^\\(\\)]+\\)|\\{[^\\{\\}]+\\})+\\s*)?=\\s*))))))))", "captures": { "1": { "name": "storage.modifier.shadeup" }, "2": { "name": "keyword.operator.rest.shadeup" }, "3": { "name": "entity.name.function.shadeup variable.language.this.shadeup" }, "4": { "name": "entity.name.function.shadeup" }, "5": { "name": "keyword.operator.optional.shadeup" } } }, { "match": "(?x)(?:(?)", "patterns": [ { "include": "#comment" }, { "include": "#type-parameters" } ] }, { "name": "meta.type.constructor.shadeup", "begin": "(?)\n ))\n )\n )\n)", "end": "(?<=\\))", "patterns": [ { "include": "#function-parameters" } ] } ] }, "type-function-return-type": { "patterns": [ { "name": "meta.type.function.return.shadeup", "begin": "(=>)(?=\\s*\\S)", "beginCaptures": { "1": { "name": "storage.type.function.arrow.shadeup" } }, "end": "(?)(?:\\?]|//|$)", "patterns": [ { "include": "#type-function-return-type-core" } ] }, { "name": "meta.type.function.return.shadeup", "begin": "=>", "beginCaptures": { "0": { "name": "storage.type.function.arrow.shadeup" } }, "end": "(?)(?]|//|^\\s*$)|((?<=\\S)(?=\\s*$)))", "patterns": [ { "include": "#type-function-return-type-core" } ] } ] }, "type-function-return-type-core": { "patterns": [ { "include": "#comment" }, { "begin": "(?<==>)(?=\\s*\\{)", "end": "(?<=\\})", "patterns": [ { "include": "#type-object" } ] }, { "include": "#type-predicate-operator" }, { "include": "#type" } ] }, "type-operators": { "patterns": [ { "include": "#typeof-operator" }, { "include": "#type-infer" }, { "begin": "([&|])(?=\\s*\\{)", "beginCaptures": { "0": { "name": "keyword.operator.type.shadeup" } }, "end": "(?<=\\})", "patterns": [ { "include": "#type-object" } ] }, { "begin": "[&|]", "beginCaptures": { "0": { "name": "keyword.operator.type.shadeup" } }, "end": "(?=\\S)" }, { "name": "keyword.operator.expression.keyof.shadeup", "match": "(?)", "endCaptures": { "1": { "name": "meta.type.parameters.shadeup punctuation.definition.typeparameters.end.shadeup" } }, "contentName": "meta.type.parameters.shadeup", "patterns": [ { "include": "#type-arguments-body" } ] }, { "begin": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(<)", "beginCaptures": { "1": { "name": "entity.name.type.shadeup" }, "2": { "name": "meta.type.parameters.shadeup punctuation.definition.typeparameters.begin.shadeup" } }, "end": "(>)", "endCaptures": { "1": { "name": "meta.type.parameters.shadeup punctuation.definition.typeparameters.end.shadeup" } }, "contentName": "meta.type.parameters.shadeup", "patterns": [ { "include": "#type-arguments-body" } ] }, { "match": "([_$[:alpha:]][_$[:alnum:]]*)\\s*(?:(\\.)|(\\?\\.(?!\\s*[[:digit:]])))", "captures": { "1": { "name": "entity.name.type.module.shadeup" }, "2": { "name": "punctuation.accessor.shadeup" }, "3": { "name": "punctuation.accessor.optional.shadeup" } } }, { "name": "entity.name.type.shadeup", "match": "[_$[:alpha:]][_$[:alnum:]]*" } ] }, "punctuation-comma": { "name": "punctuation.separator.comma.shadeup", "match": "," }, "punctuation-semicolon": { "name": "punctuation.terminator.statement.shadeup", "match": ";" }, "punctuation-accessor": { "match": "(?:(\\.)|(\\?\\.(?!\\s*[[:digit:]])))", "captures": { "1": { "name": "punctuation.accessor.shadeup" }, "2": { "name": "punctuation.accessor.optional.shadeup" } } }, "string": { "patterns": [ { "include": "#qstring-single" }, { "include": "#qstring-double" }, { "include": "#template" } ] }, "qstring-double": { "name": "string.quoted.double.shadeup", "begin": "\"", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.shadeup" } }, "end": "(\")|((?:[^\\\\\\n])$)", "endCaptures": { "1": { "name": "punctuation.definition.string.end.shadeup" }, "2": { "name": "invalid.illegal.newline.shadeup" } }, "patterns": [ { "include": "#string-character-escape" } ] }, "qstring-single": { "name": "string.quoted.single.shadeup", "begin": "'", "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.shadeup" } }, "end": "(\\')|((?:[^\\\\\\n])$)", "endCaptures": { "1": { "name": "punctuation.definition.string.end.shadeup" }, "2": { "name": "invalid.illegal.newline.shadeup" } }, "patterns": [ { "include": "#string-character-escape" } ] }, "string-character-escape": { "name": "constant.character.escape.shadeup", "match": "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|u\\{[0-9A-Fa-f]+\\}|[0-2][0-7]{0,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.|$)" }, "template": { "patterns": [ { "include": "#template-call" }, { "contentName": "string.template.shadeup", "begin": "([_$[:alpha:]][_$[:alnum:]]*)?(`)", "beginCaptures": { "1": { "name": "entity.name.function.tagged-template.shadeup" }, "2": { "name": "string.template.shadeup punctuation.definition.string.template.begin.shadeup" } }, "end": "`", "endCaptures": { "0": { "name": "string.template.shadeup punctuation.definition.string.template.end.shadeup" } }, "patterns": [ { "include": "#template-substitution-element" }, { "include": "#string-character-escape" } ] } ] }, "template-call": { "patterns": [ { "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*\\s*\\??\\.\\s*)*|(\\??\\.\\s*)?)([_$[:alpha:]][_$[:alnum:]]*)(<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))(([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>)*(?))*(?)*(?\\s*)?`)", "end": "(?=`)", "patterns": [ { "begin": "(?=(([_$[:alpha:]][_$[:alnum:]]*\\s*\\??\\.\\s*)*|(\\??\\.\\s*)?)([_$[:alpha:]][_$[:alnum:]]*))", "end": "(?=(<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))(([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>)*(?))*(?)*(?\\s*)?`)", "patterns": [ { "include": "#support-function-call-identifiers" }, { "name": "entity.name.function.tagged-template.shadeup", "match": "([_$[:alpha:]][_$[:alnum:]]*)" } ] }, { "include": "#type-arguments" } ] }, { "begin": "([_$[:alpha:]][_$[:alnum:]]*)?\\s*(?=(<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))(([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>|\\<\\s*(((keyof|infer|typeof|readonly)\\s+)|(([_$[:alpha:]][_$[:alnum:]]*|(\\{([^\\{\\}]|(\\{([^\\{\\}]|\\{[^\\{\\}]*\\})*\\}))*\\})|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(\\[([^\\[\\]]|(\\[([^\\[\\]]|\\[[^\\[\\]]*\\])*\\]))*\\])|(\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`))(?=\\s*([\\<\\>\\,\\.\\[]|=>|&(?!&)|\\|(?!\\|)))))([^<>\\(]|(\\(([^\\(\\)]|(\\(([^\\(\\)]|\\([^\\(\\)]*\\))*\\)))*\\))|(?<==)\\>)*(?))*(?)*(?\\s*)`)", "beginCaptures": { "1": { "name": "entity.name.function.tagged-template.shadeup" } }, "end": "(?=`)", "patterns": [ { "include": "#type-arguments" } ] } ] }, "template-substitution-element": { "name": "meta.template.expression.shadeup", "begin": "\\$\\{", "beginCaptures": { "0": { "name": "punctuation.definition.template-expression.begin.shadeup" } }, "end": "\\}", "endCaptures": { "0": { "name": "punctuation.definition.template-expression.end.shadeup" } }, "patterns": [ { "include": "#expression" } ], "contentName": "meta.embedded.line.shadeup" }, "type-string": { "patterns": [ { "include": "#qstring-single" }, { "include": "#qstring-double" }, { "include": "#template-type" } ] }, "template-type": { "patterns": [ { "include": "#template-call" }, { "contentName": "string.template.shadeup", "begin": "([_$[:alpha:]][_$[:alnum:]]*)?(`)", "beginCaptures": { "1": { "name": "entity.name.function.tagged-template.shadeup" }, "2": { "name": "string.template.shadeup punctuation.definition.string.template.begin.shadeup" } }, "end": "`", "endCaptures": { "0": { "name": "string.template.shadeup punctuation.definition.string.template.end.shadeup" } }, "patterns": [ { "include": "#template-type-substitution-element" }, { "include": "#string-character-escape" } ] } ] }, "template-type-substitution-element": { "name": "meta.template.expression.shadeup", "begin": "\\$\\{", "beginCaptures": { "0": { "name": "punctuation.definition.template-expression.begin.shadeup" } }, "end": "\\}", "endCaptures": { "0": { "name": "punctuation.definition.template-expression.end.shadeup" } }, "patterns": [ { "include": "#type" } ], "contentName": "meta.embedded.line.shadeup" }, "regex": { "patterns": [ { "name": "string.regexp.shadeup", "begin": "(?|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[\\()]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\]|\\(([^\\)\\\\]|\\\\.)+\\))+\\/([dgimsuy]+|(?![\\/\\*])|(?=\\/\\*))(?!\\s*[a-zA-Z0-9_$]))", "beginCaptures": { "1": { "name": "punctuation.definition.string.begin.shadeup" } }, "end": "(/)([dgimsuy]*)", "endCaptures": { "1": { "name": "punctuation.definition.string.end.shadeup" }, "2": { "name": "keyword.other.shadeup" } }, "patterns": [ { "include": "#regexp" } ] }, { "name": "string.regexp.shadeup", "begin": "((?", "captures": { "0": { "name": "keyword.other.back-reference.regexp" }, "1": { "name": "variable.other.regexp" } } }, { "name": "keyword.operator.quantifier.regexp", "match": "[?+*]|\\{(\\d+,\\d+|\\d+,|,\\d+|\\d+)\\}\\??" }, { "name": "keyword.operator.or.regexp", "match": "\\|" }, { "name": "meta.group.assertion.regexp", "begin": "(\\()((\\?=)|(\\?!)|(\\?<=)|(\\?))?", "beginCaptures": { "0": { "name": "punctuation.definition.group.regexp" }, "1": { "name": "punctuation.definition.group.no-capture.regexp" }, "2": { "name": "variable.other.regexp" } }, "end": "\\)", "endCaptures": { "0": { "name": "punctuation.definition.group.regexp" } }, "patterns": [ { "include": "#regexp" } ] }, { "name": "constant.other.character-class.set.regexp", "begin": "(\\[)(\\^)?", "beginCaptures": { "1": { "name": "punctuation.definition.character-class.regexp" }, "2": { "name": "keyword.operator.negation.regexp" } }, "end": "(\\])", "endCaptures": { "1": { "name": "punctuation.definition.character-class.regexp" } }, "patterns": [ { "name": "constant.other.character-class.range.regexp", "match": "(?:.|(\\\\(?:[0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}))|(\\\\c[A-Z])|(\\\\.))\\-(?:[^\\]\\\\]|(\\\\(?:[0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}))|(\\\\c[A-Z])|(\\\\.))", "captures": { "1": { "name": "constant.character.numeric.regexp" }, "2": { "name": "constant.character.control.regexp" }, "3": { "name": "constant.character.escape.backslash.regexp" }, "4": { "name": "constant.character.numeric.regexp" }, "5": { "name": "constant.character.control.regexp" }, "6": { "name": "constant.character.escape.backslash.regexp" } } }, { "include": "#regex-character-class" } ] }, { "include": "#regex-character-class" } ] }, "regex-character-class": { "patterns": [ { "name": "constant.other.character-class.regexp", "match": "\\\\[wWsSdDtrnvf]|\\." }, { "name": "constant.character.numeric.regexp", "match": "\\\\([0-7]{3}|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4})" }, { "name": "constant.character.control.regexp", "match": "\\\\c[A-Z]" }, { "name": "constant.character.escape.backslash.regexp", "match": "\\\\." } ] }, "comment": { "patterns": [ { "name": "comment.block.documentation.shadeup", "begin": "/\\*\\*(?!/)", "beginCaptures": { "0": { "name": "punctuation.definition.comment.shadeup" } }, "end": "\\*/", "endCaptures": { "0": { "name": "punctuation.definition.comment.shadeup" } }, "patterns": [ { "include": "#docblock" } ] }, { "name": "comment.block.shadeup", "begin": "(/\\*)(?:\\s*((@)internal)(?=\\s|(\\*/)))?", "beginCaptures": { "1": { "name": "punctuation.definition.comment.shadeup" }, "2": { "name": "storage.type.internaldeclaration.shadeup" }, "3": { "name": "punctuation.decorator.internaldeclaration.shadeup" } }, "end": "\\*/", "endCaptures": { "0": { "name": "punctuation.definition.comment.shadeup" } } }, { "begin": "(^[ \\t]+)?((//)(?:\\s*((@)internal)(?=\\s|$))?)", "beginCaptures": { "1": { "name": "punctuation.whitespace.comment.leading.shadeup" }, "2": { "name": "comment.line.double-slash.shadeup" }, "3": { "name": "punctuation.definition.comment.shadeup" }, "4": { "name": "storage.type.internaldeclaration.shadeup" }, "5": { "name": "punctuation.decorator.internaldeclaration.shadeup" } }, "end": "(?=$)", "contentName": "comment.line.double-slash.shadeup" } ] }, "single-line-comment-consuming-line-ending": { "begin": "(^[ \\t]+)?((//)(?:\\s*((@)internal)(?=\\s|$))?)", "beginCaptures": { "1": { "name": "punctuation.whitespace.comment.leading.shadeup" }, "2": { "name": "comment.line.double-slash.shadeup" }, "3": { "name": "punctuation.definition.comment.shadeup" }, "4": { "name": "storage.type.internaldeclaration.shadeup" }, "5": { "name": "punctuation.decorator.internaldeclaration.shadeup" } }, "end": "(?=^)", "contentName": "comment.line.double-slash.shadeup" }, "directives": { "name": "comment.line.triple-slash.directive.shadeup", "begin": "^(///)\\s*(?=<(reference|amd-dependency|amd-module)(\\s+(path|types|no-default-lib|lib|name|resolution-mode)\\s*=\\s*((\\'([^\\'\\\\]|\\\\.)*\\')|(\\\"([^\\\"\\\\]|\\\\.)*\\\")|(\\`([^\\`\\\\]|\\\\.)*\\`)))+\\s*/>\\s*$)", "beginCaptures": { "1": { "name": "punctuation.definition.comment.shadeup" } }, "end": "(?=$)", "patterns": [ { "name": "meta.tag.shadeup", "begin": "(<)(reference|amd-dependency|amd-module)", "beginCaptures": { "1": { "name": "punctuation.definition.tag.directive.shadeup" }, "2": { "name": "entity.name.tag.directive.shadeup" } }, "end": "/>", "endCaptures": { "0": { "name": "punctuation.definition.tag.directive.shadeup" } }, "patterns": [ { "name": "entity.other.attribute-name.directive.shadeup", "match": "path|types|no-default-lib|lib|name|resolution-mode" }, { "name": "keyword.operator.assignment.shadeup", "match": "=" }, { "include": "#string" } ] } ] }, "docblock": { "patterns": [ { "match": "(?x)\n((@)(?:access|api))\n\\s+\n(private|protected|public)\n\\b", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "constant.language.access-type.jsdoc" } } }, { "match": "(?x)\n((@)author)\n\\s+\n(\n [^@\\s<>*/]\n (?:[^@<>*/]|\\*[^/])*\n)\n(?:\n \\s*\n (<)\n ([^>\\s]+)\n (>)\n)?", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "entity.name.type.instance.jsdoc" }, "4": { "name": "punctuation.definition.bracket.angle.begin.jsdoc" }, "5": { "name": "constant.other.email.link.underline.jsdoc" }, "6": { "name": "punctuation.definition.bracket.angle.end.jsdoc" } } }, { "match": "(?x)\n((@)borrows) \\s+\n((?:[^@\\s*/]|\\*[^/])+) # \n\\s+ (as) \\s+ # as\n((?:[^@\\s*/]|\\*[^/])+) # ", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "entity.name.type.instance.jsdoc" }, "4": { "name": "keyword.operator.control.jsdoc" }, "5": { "name": "entity.name.type.instance.jsdoc" } } }, { "name": "meta.example.jsdoc", "begin": "((@)example)\\s+", "end": "(?=@|\\*/)", "beginCaptures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" } }, "patterns": [ { "match": "^\\s\\*\\s+" }, { "contentName": "constant.other.description.jsdoc", "begin": "\\G(<)caption(>)", "beginCaptures": { "0": { "name": "entity.name.tag.inline.jsdoc" }, "1": { "name": "punctuation.definition.bracket.angle.begin.jsdoc" }, "2": { "name": "punctuation.definition.bracket.angle.end.jsdoc" } }, "end": "()|(?=\\*/)", "endCaptures": { "0": { "name": "entity.name.tag.inline.jsdoc" }, "1": { "name": "punctuation.definition.bracket.angle.begin.jsdoc" }, "2": { "name": "punctuation.definition.bracket.angle.end.jsdoc" } } }, { "match": "[^\\s@*](?:[^*]|\\*[^/])*", "captures": { "0": { "name": "source.embedded.shadeup" } } } ] }, { "match": "(?x) ((@)kind) \\s+ (class|constant|event|external|file|function|member|mixin|module|namespace|typedef) \\b", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "constant.language.symbol-type.jsdoc" } } }, { "match": "(?x)\n((@)see)\n\\s+\n(?:\n # URL\n (\n (?=https?://)\n (?:[^\\s*]|\\*[^/])+\n )\n |\n # JSDoc namepath\n (\n (?!\n # Avoid matching bare URIs (also acceptable as links)\n https?://\n |\n # Avoid matching {@inline tags}; we match those below\n (?:\\[[^\\[\\]]*\\])? # Possible description [preceding]{@tag}\n {@(?:link|linkcode|linkplain|tutorial)\\b\n )\n # Matched namepath\n (?:[^@\\s*/]|\\*[^/])+\n )\n)", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "variable.other.link.underline.jsdoc" }, "4": { "name": "entity.name.type.instance.jsdoc" } } }, { "match": "(?x)\n((@)template)\n\\s+\n# One or more valid identifiers\n(\n [A-Za-z_$] # First character: non-numeric word character\n [\\w$.\\[\\]]* # Rest of identifier\n (?: # Possible list of additional identifiers\n \\s* , \\s*\n [A-Za-z_$]\n [\\w$.\\[\\]]*\n )*\n)", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "variable.other.jsdoc" } } }, { "begin": "(?x)((@)template)\\s+(?={)", "beginCaptures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" } }, "end": "(?=\\s|\\*/|[^{}\\[\\]A-Za-z_$])", "patterns": [ { "include": "#jsdoctype" }, { "name": "variable.other.jsdoc", "match": "([A-Za-z_$][\\w$.\\[\\]]*)" } ] }, { "match": "(?x)\n(\n (@)\n (?:arg|argument|const|constant|member|namespace|param|var)\n)\n\\s+\n(\n [A-Za-z_$]\n [\\w$.\\[\\]]*\n)", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "variable.other.jsdoc" } } }, { "begin": "((@)typedef)\\s+(?={)", "beginCaptures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" } }, "end": "(?=\\s|\\*/|[^{}\\[\\]A-Za-z_$])", "patterns": [ { "include": "#jsdoctype" }, { "name": "entity.name.type.instance.jsdoc", "match": "(?:[^@\\s*/]|\\*[^/])+" } ] }, { "begin": "((@)(?:arg|argument|const|constant|member|namespace|param|prop|property|var))\\s+(?={)", "beginCaptures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" } }, "end": "(?=\\s|\\*/|[^{}\\[\\]A-Za-z_$])", "patterns": [ { "include": "#jsdoctype" }, { "name": "variable.other.jsdoc", "match": "([A-Za-z_$][\\w$.\\[\\]]*)" }, { "name": "variable.other.jsdoc", "match": "(?x)\n(\\[)\\s*\n[\\w$]+\n(?:\n (?:\\[\\])? # Foo[ ].bar properties within an array\n \\. # Foo.Bar namespaced parameter\n [\\w$]+\n)*\n(?:\n \\s*\n (=) # [foo=bar] Default parameter value\n \\s*\n (\n # The inner regexes are to stop the match early at */ and to not stop at escaped quotes\n (?>\n \"(?:(?:\\*(?!/))|(?:\\\\(?!\"))|[^*\\\\])*?\" | # [foo=\"bar\"] Double-quoted\n '(?:(?:\\*(?!/))|(?:\\\\(?!'))|[^*\\\\])*?' | # [foo='bar'] Single-quoted\n \\[ (?:(?:\\*(?!/))|[^*])*? \\] | # [foo=[1,2]] Array literal\n (?:(?:\\*(?!/))|\\s(?!\\s*\\])|\\[.*?(?:\\]|(?=\\*/))|[^*\\s\\[\\]])* # Everything else\n )*\n )\n)?\n\\s*(?:(\\])((?:[^*\\s]|\\*[^\\s/])+)?|(?=\\*/))", "captures": { "1": { "name": "punctuation.definition.optional-value.begin.bracket.square.jsdoc" }, "2": { "name": "keyword.operator.assignment.jsdoc" }, "3": { "name": "source.embedded.shadeup" }, "4": { "name": "punctuation.definition.optional-value.end.bracket.square.jsdoc" }, "5": { "name": "invalid.illegal.syntax.jsdoc" } } } ] }, { "begin": "(?x)\n(\n (@)\n (?:define|enum|exception|export|extends|lends|implements|modifies\n |namespace|private|protected|returns?|satisfies|suppress|this|throws|type\n |yields?)\n)\n\\s+(?={)", "beginCaptures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" } }, "end": "(?=\\s|\\*/|[^{}\\[\\]A-Za-z_$])", "patterns": [ { "include": "#jsdoctype" } ] }, { "match": "(?x)\n(\n (@)\n (?:alias|augments|callback|constructs|emits|event|fires|exports?\n |extends|external|function|func|host|lends|listens|interface|memberof!?\n |method|module|mixes|mixin|name|requires|see|this|typedef|uses)\n)\n\\s+\n(\n (?:\n [^{}@\\s*] | \\*[^/]\n )+\n)", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "entity.name.type.instance.jsdoc" } } }, { "contentName": "variable.other.jsdoc", "begin": "((@)(?:default(?:value)?|license|version))\\s+(([''\"]))", "beginCaptures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "variable.other.jsdoc" }, "4": { "name": "punctuation.definition.string.begin.jsdoc" } }, "end": "(\\3)|(?=$|\\*/)", "endCaptures": { "0": { "name": "variable.other.jsdoc" }, "1": { "name": "punctuation.definition.string.end.jsdoc" } } }, { "match": "((@)(?:default(?:value)?|license|tutorial|variation|version))\\s+([^\\s*]+)", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" }, "3": { "name": "variable.other.jsdoc" } } }, { "name": "storage.type.class.jsdoc", "match": "(?x) (@) (?:abstract|access|alias|api|arg|argument|async|attribute|augments|author|beta|borrows|bubbles |callback|chainable|class|classdesc|code|config|const|constant|constructor|constructs|copyright |default|defaultvalue|define|deprecated|desc|description|dict|emits|enum|event|example|exception |exports?|extends|extension(?:_?for)?|external|externs|file|fileoverview|final|fires|for|func |function|generator|global|hideconstructor|host|ignore|implements|implicitCast|inherit[Dd]oc |inner|instance|interface|internal|kind|lends|license|listens|main|member|memberof!?|method |mixes|mixins?|modifies|module|name|namespace|noalias|nocollapse|nocompile|nosideeffects |override|overview|package|param|polymer(?:Behavior)?|preserve|private|prop|property|protected |public|read[Oo]nly|record|require[ds]|returns?|see|since|static|struct|submodule|summary |suppress|template|this|throws|todo|tutorial|type|typedef|unrestricted|uses|var|variation |version|virtual|writeOnce|yields?) \\b", "captures": { "1": { "name": "punctuation.definition.block.tag.jsdoc" } } }, { "include": "#inline-tags" }, { "match": "((@)(?:[_$[:alpha:]][_$[:alnum:]]*))(?=\\s+)", "captures": { "1": { "name": "storage.type.class.jsdoc" }, "2": { "name": "punctuation.definition.block.tag.jsdoc" } } } ] }, "brackets": { "patterns": [ { "begin": "{", "end": "}|(?=\\*/)", "patterns": [ { "include": "#brackets" } ] }, { "begin": "\\[", "end": "\\]|(?=\\*/)", "patterns": [ { "include": "#brackets" } ] } ] }, "inline-tags": { "patterns": [ { "name": "constant.other.description.jsdoc", "match": "(\\[)[^\\]]+(\\])(?={@(?:link|linkcode|linkplain|tutorial))", "captures": { "1": { "name": "punctuation.definition.bracket.square.begin.jsdoc" }, "2": { "name": "punctuation.definition.bracket.square.end.jsdoc" } } }, { "name": "entity.name.type.instance.jsdoc", "begin": "({)((@)(?:link(?:code|plain)?|tutorial))\\s*", "beginCaptures": { "1": { "name": "punctuation.definition.bracket.curly.begin.jsdoc" }, "2": { "name": "storage.type.class.jsdoc" }, "3": { "name": "punctuation.definition.inline.tag.jsdoc" } }, "end": "}|(?=\\*/)", "endCaptures": { "0": { "name": "punctuation.definition.bracket.curly.end.jsdoc" } }, "patterns": [ { "match": "\\G((?=https?://)(?:[^|}\\s*]|\\*[/])+)(\\|)?", "captures": { "1": { "name": "variable.other.link.underline.jsdoc" }, "2": { "name": "punctuation.separator.pipe.jsdoc" } } }, { "match": "\\G((?:[^{}@\\s|*]|\\*[^/])+)(\\|)?", "captures": { "1": { "name": "variable.other.description.jsdoc" }, "2": { "name": "punctuation.separator.pipe.jsdoc" } } } ] } ] }, "jsdoctype": { "patterns": [ { "contentName": "entity.name.type.instance.jsdoc", "begin": "\\G({)", "beginCaptures": { "0": { "name": "entity.name.type.instance.jsdoc" }, "1": { "name": "punctuation.definition.bracket.curly.begin.jsdoc" } }, "end": "((}))\\s*|(?=\\*/)", "endCaptures": { "1": { "name": "entity.name.type.instance.jsdoc" }, "2": { "name": "punctuation.definition.bracket.curly.end.jsdoc" } }, "patterns": [ { "include": "#brackets" } ] } ] } } } ================================================ FILE: extension/vscode/shadeup/client/package.json ================================================ { "name": "lsp-shadeup-client", "description": "VSCode part of a language server", "author": "Microsoft Corporation", "license": "MIT", "version": "0.0.1", "publisher": "shadeup", "engines": { "vscode": "^1.75.0" }, "dependencies": { "vscode-languageclient": "^9.0.1" }, "devDependencies": { "@types/vscode": "^1.75.1", "@vscode/test-electron": "^2.3.8" } } ================================================ FILE: extension/vscode/shadeup/client/src/extension.ts ================================================ /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ import * as path from "path"; import { workspace, ExtensionContext } from "vscode"; import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, } from "vscode-languageclient/node"; let client: LanguageClient; export function activate(context: ExtensionContext) { // The server is implemented in node const serverModule = context.asAbsolutePath( path.join("server", "out", "server.js") ); let debugOptions = { execArgv: ["--nolazy", "--inspect=6009"] }; // If the extension is launched in debug mode then the debug server options are used // Otherwise the run options are used const serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions, }, }; // Options to control the language client const clientOptions: LanguageClientOptions = { // Register the server for plain text documents documentSelector: [{ scheme: "file", language: "shadeup" }], synchronize: { // Notify the server about file changes to '.clientrc files contained in the workspace fileEvents: workspace.createFileSystemWatcher("**/.clientrc"), }, }; // Create the language client and start the client. client = new LanguageClient( "shadeupLanguageServer", "Shadeup Language Server", serverOptions, clientOptions ); // Start the client. This will also launch the server client.start(); } export function deactivate(): Thenable | undefined { if (!client) { return undefined; } return client.stop(); } ================================================ FILE: extension/vscode/shadeup/client/testFixture/completion.txt ================================================ ================================================ FILE: extension/vscode/shadeup/client/testFixture/diagnostics.txt ================================================ ANY browsers, ANY OS. ================================================ FILE: extension/vscode/shadeup/client/tsconfig.json ================================================ { "compilerOptions": { "module": "commonjs", "target": "es2020", "lib": ["es2020"], "outDir": "out", "rootDir": "src", "sourceMap": true }, "include": ["src"], "exclude": ["node_modules", ".vscode-test"] } ================================================ FILE: extension/vscode/shadeup/lang.ts ================================================ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import * as tm from "tmlanguage-generator"; import path from "path"; import fs from "fs"; import plist from "plist"; const __dirname = path .dirname(new URL(import.meta.url).pathname) .replace(/^file:\/\//, "") .replace(/^\//, ""); export const grammarPath = path.resolve(__dirname, "./shadeup.tmlanguage.json"); type Rule = tm.Rule; type IncludeRule = tm.IncludeRule; type BeginEndRule = tm.BeginEndRule; type MatchRule = tm.MatchRule; type Grammar = tm.Grammar; export type BicepScope = | "comment.block.shadeup" | "comment.line.double-slash.shadeup" | "constant.character.escape.shadeup" | "constant.numeric.shadeup" | "constant.language.shadeup" | "entity.name.function.shadeup" | "keyword.control.declaration.shadeup" | "string.quoted.single.shadeup" | "string.quoted.double.shadeup" | "string.quoted.multi.shadeup" | "variable.other.readwrite.shadeup" | "storage.type.function.shadeup" | "variable.other.property.shadeup" | "punctuation.definition.template-expression.begin.shadeup" | "punctuation.definition.template-expression.end.shadeup" | "storage.modifier.shadeup" | "storage.type.shadeup"; const bounded = (text: string) => `\\b${text}\\b`; // eslint-disable-next-line @typescript-eslint/no-unused-vars const after = (regex: string) => `(?<=${regex})`; const notAfter = (regex: string) => `(? `(?=${regex})`; const notBefore = (regex: string) => `(?!${regex})`; const meta: typeof tm.meta = tm.meta; const identifierStart = "[_$[:alpha:]]"; const identifierContinue = "[_$[:alnum:]]"; const identifier = bounded(`${identifierStart}${identifierContinue}*`); const directive = bounded(`[_a-zA-Z-0-9]+`); // whitespace. ideally we'd tokenize in-line block comments, but that's a lot of work. For now, ignore them. const ws = `(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*`; const keywords = [ "metadata", "targetScope", "resource", "module", "param", "shader", "workgroup", "output", "for", "in", "if", "while", "break", "continue", "else", "return", "existing", "import", "as", "type", "with", "using", "assert", "provider", ]; const storage = ["fn", "struct", "trait", "impl"]; const keywordExpression: MatchRule = { key: "keyword", scope: "keyword.control.declaration.shadeup", match: bounded(`(${keywords.join("|")})`), }; const storageFunc: MatchRule = { key: "storage-func", scope: "storage.type.function.shadeup", match: bounded(`(${storage.join("|")})`), }; const variableExpression: MatchRule = { key: "variable", scope: "storage.type.shadeup", match: bounded(`(${["let", "const"].join("|")})`), }; const storageMod: MatchRule = { key: "storage-modifier", scope: "storage.modifier.shadeup", match: bounded(`(${["pub"].join("|")})`), }; const lineComment: MatchRule = { key: "line-comment", scope: "comment.line.double-slash.shadeup", match: `//.*${before(`$`)}`, }; const blockComment: BeginEndRule = { key: "block-comment", scope: "comment.block.shadeup", begin: `/\\*`, end: `\\*/`, }; const comments: IncludeRule = { key: "comments", patterns: [lineComment, blockComment], }; function withComments(input: Rule[]): Rule[] { return [...input, comments]; } const expression: IncludeRule = { key: "expression", patterns: [ /* placeholder filled later due to cycle*/ ], }; const escapeChar: MatchRule = { key: "escape-character", scope: "constant.character.escape.shadeup", match: `\\\\(u{[0-9A-Fa-f]+}|n|r|t|\\\\|'|\\\${)`, }; const stringVerbatim: BeginEndRule = { key: "string-verbatim", scope: "string.quoted.multi.shadeup", begin: `'''`, end: `'''`, patterns: [], }; const stringSubstitution: BeginEndRule = { key: "string-literal-subst", scope: meta, begin: `${notAfter(`\\\\`)}(\\\${)`, beginCaptures: { "1": { scope: "punctuation.definition.template-expression.begin.shadeup" }, }, end: `(})`, endCaptures: { "1": { scope: "punctuation.definition.template-expression.end.shadeup" }, }, patterns: withComments([expression]), }; const stringLiteral: BeginEndRule = { key: "string-literal", scope: "string.quoted.single.shadeup", begin: `'${notBefore(`''`)}`, end: `'`, patterns: [escapeChar, stringSubstitution], }; const stringLiteralDouble: BeginEndRule = { key: "string-literal-double", scope: "string.quoted.double.shadeup", begin: `"${notBefore(`""`)}`, end: `"`, patterns: [escapeChar, stringSubstitution], }; const numericLiteral: MatchRule = { key: "numeric-literal", scope: "constant.numeric.shadeup", match: `[0-9]+`, }; const namedLiteral: MatchRule = { key: "named-literal", scope: "constant.language.shadeup", match: bounded(`(true|false|null)`), }; const identifierExpression: MatchRule = { key: "identifier", scope: "variable.other.readwrite.shadeup", match: `${identifier}${notBefore(`${ws}\\(`)}`, }; const objectLiteral: BeginEndRule = { key: "object-literal", scope: meta, begin: `{`, end: `}`, patterns: withComments([ { key: "object-property-key", scope: "variable.other.property.shadeup", match: `${identifier}${before(`${ws}:`)}`, }, expression, ]), }; const arrayLiteral: BeginEndRule = { key: "array-literal", scope: meta, begin: `\\[${notBefore(`${ws}${bounded(`for`)}`)}`, end: `]`, patterns: withComments([expression]), }; const functionCall: BeginEndRule = { key: "function-call", scope: meta, begin: `(${identifier})${ws}\\(`, beginCaptures: { "1": { scope: "entity.name.function.shadeup" }, }, end: `\\)`, patterns: withComments([expression]), }; const decorator: BeginEndRule = { key: "decorator", scope: meta, begin: `@${ws}${before(identifier)}`, end: ``, patterns: withComments([expression]), }; const lambdaStart = `(` + `\\(${ws}${identifier}${ws}(,${ws}${identifier}${ws})*\\)|` + `\\(${ws}\\)|` + `${ws}${identifier}${ws}` + `)${before(`${ws}=>`)}`; const lambda: BeginEndRule = { key: "lambda-start", scope: meta, begin: lambdaStart, beginCaptures: { "1": { scope: meta, patterns: withComments([identifierExpression]), }, }, end: `${ws}=>`, }; const directiveStatement: BeginEndRule = { key: "directive", scope: meta, begin: `#${directive}`, end: `$`, patterns: withComments([ { key: "directive-variable", scope: "keyword.control.declaration.shadeup", match: directive, }, ]), }; expression.patterns = [ stringLiteralDouble, stringLiteral, stringVerbatim, numericLiteral, namedLiteral, objectLiteral, arrayLiteral, keywordExpression, storageFunc, variableExpression, storageMod, identifierExpression, functionCall, decorator, lambda, directiveStatement, ]; const grammar: Grammar = { $schema: tm.schema, name: "Shadeup", scopeName: "source.shadeup", fileTypes: [".shadeup"], patterns: withComments([expression]), }; export async function generateGrammar(): Promise { const json = await tm.emitJSON(grammar); return JSON.parse(json); } generateGrammar().then((grammar) => { const json = JSON.stringify(grammar, null, 2); fs.writeFileSync(grammarPath, json); }); ================================================ FILE: extension/vscode/shadeup/language-configuration.json ================================================ { "wordPattern": "(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\.\\<\\>\\/\\?\\s]+)", "comments": { // symbol used for single line comment. Remove this entry if your language does not support line comments "lineComment": "//", // symbols used for start and end a block comment. Remove this entry if your language does not support block comments "blockComment": ["/*", "*/"] }, // symbols used as brackets "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], // symbols that are auto closed when typing "autoClosingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"] ], // symbols that can be used to surround a selection "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"] ], "folding": { "markers": { "start": "^\\\\s*//\\\\s*#?region\\\\b", "end": "^\\\\s*//\\\\s*#?endregion\\\\b" } } } ================================================ FILE: extension/vscode/shadeup/package.json ================================================ { "name": "shadeup-vscode", "displayName": "Shadeup for VS Code", "description": "Shadeup language server and tools", "version": "1.0.0", "engines": { "vscode": "^1.85.0" }, "publisher": "Shadeup", "keywords": [ "shadeup", "language", "syntax", "highlighting" ], "icon": "icon.png", "repository": { "type": "git", "url": "https://github.com/AskingQuestions/shadeup" }, "main": "./client/out/extension", "categories": [ "Programming Languages" ], "contributes": { "languages": [ { "id": "shadeup", "aliases": [ "Shadeup", "shadeup" ], "extensions": [ ".shadeup" ], "configuration": "./language-configuration.json", "icon": { "light": "./icon.png", "dark": "./icon.png" } } ], "grammars": [ { "language": "shadeup", "scopeName": "source.shadeup", "path": "./shadeup.tmlanguage.json" } ] }, "scripts": { "vscode:prepublish": "npm run compile", "compile": "tsc -b", "watch": "tsc -b -w", "lint": "eslint ./client/src ./server/src --ext .ts,.tsx", "postinstall": "cd client && npm install && cd ../server && npm install && cd .." }, "devDependencies": { "@types/mocha": "^10.0.6", "@types/node": "^18.14.6", "@typescript-eslint/eslint-plugin": "^6.14.0", "@typescript-eslint/parser": "^6.14.0", "eslint": "^8.56.0", "mocha": "^10.2.0", "typescript": "^5.3.3" } } ================================================ FILE: extension/vscode/shadeup/server/compiler-dist/compiler.d.ts ================================================ export function makeLSPCompiler(): Promise; ================================================ FILE: extension/vscode/shadeup/server/compiler-dist/compiler.js ================================================ const { makeSimpleShadeupEnvironment } = require("./shadeup-compiler.umd.cjs"); const Parser = require("web-tree-sitter"); const path = require("path"); const { fileURLToPath } = require("url"); module.exports.makeLSPCompiler = async function makeLSPCompiler() { await Parser.init(); const parser = new Parser(); const Lang = await Parser.Language.load( path.resolve(path.dirname(__filename), "tree-sitter-shadeup.wasm") ); parser.setLanguage(Lang); global.shadeupParser = () => { return parser; }; const env = await makeSimpleShadeupEnvironment(true); return env; }; ================================================ FILE: extension/vscode/shadeup/server/compiler-dist/readme.md ================================================ modify the output of shadeup-compiler.js to: 1. remove the tree sitter wasm strings 2. Replace getShadeupParse with: async function getShadeupParser() { return global.shadeupParser(); } 3. import fs and replace e4.readFileSync e4 trace up to \_\_viteexternal with fs ================================================ FILE: extension/vscode/shadeup/server/compiler-dist/shadeup-compiler.umd.cjs ================================================ (function(global2, factory) { typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("typescript"), require("path"), require("fs"), require("@typescript/vfs")) : typeof define === "function" && define.amd ? define(["exports", "typescript", "path", "fs", "@typescript/vfs"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.ShadeupCompiler = {}, global2.typescript, global2.path, global2.fs, global2["@typescript/vfs"])); })(this, function(exports2, ts, require$$0$1, require$$1, vfs) { "use strict"; var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; } function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a2() { if (this instanceof a2) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, "__esModule", { value: true }); Object.keys(n).forEach(function(k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function() { return n[k]; } }); }); return a; } var sha256$1 = { exports: {} }; (function(module2) { (function(root, factory2) { var exports3 = {}; factory2(exports3); var sha2562 = exports3["default"]; for (var k in exports3) { sha2562[k] = exports3[k]; } { module2.exports = sha2562; } })(commonjsGlobal, function(exports3) { exports3.__esModule = true; exports3.digestLength = 32; exports3.blockSize = 64; var K = new Uint32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); function hashBlocks(w, v, p, pos, len) { var a, b, c2, d, e, f, g2, h, u, i, j, t1, t2; while (len >= 64) { a = v[0]; b = v[1]; c2 = v[2]; d = v[3]; e = v[4]; f = v[5]; g2 = v[6]; h = v[7]; for (i = 0; i < 16; i++) { j = pos + i * 4; w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255; } for (i = 16; i < 64; i++) { u = w[i - 2]; t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10; u = w[i - 15]; t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3; w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0); } for (i = 0; i < 64; i++) { t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g2) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0; t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c2 ^ b & c2) | 0; h = g2; g2 = f; f = e; e = d + t1 | 0; d = c2; c2 = b; b = a; a = t1 + t2 | 0; } v[0] += a; v[1] += b; v[2] += c2; v[3] += d; v[4] += e; v[5] += f; v[6] += g2; v[7] += h; pos += 64; len -= 64; } return pos; } var Hash = ( /** @class */ function() { function Hash2() { this.digestLength = exports3.digestLength; this.blockSize = exports3.blockSize; this.state = new Int32Array(8); this.temp = new Int32Array(64); this.buffer = new Uint8Array(128); this.bufferLength = 0; this.bytesHashed = 0; this.finished = false; this.reset(); } Hash2.prototype.reset = function() { this.state[0] = 1779033703; this.state[1] = 3144134277; this.state[2] = 1013904242; this.state[3] = 2773480762; this.state[4] = 1359893119; this.state[5] = 2600822924; this.state[6] = 528734635; this.state[7] = 1541459225; this.bufferLength = 0; this.bytesHashed = 0; this.finished = false; return this; }; Hash2.prototype.clean = function() { for (var i = 0; i < this.buffer.length; i++) { this.buffer[i] = 0; } for (var i = 0; i < this.temp.length; i++) { this.temp[i] = 0; } this.reset(); }; Hash2.prototype.update = function(data, dataLength) { if (dataLength === void 0) { dataLength = data.length; } if (this.finished) { throw new Error("SHA256: can't update because hash was finished."); } var dataPos = 0; this.bytesHashed += dataLength; if (this.bufferLength > 0) { while (this.bufferLength < 64 && dataLength > 0) { this.buffer[this.bufferLength++] = data[dataPos++]; dataLength--; } if (this.bufferLength === 64) { hashBlocks(this.temp, this.state, this.buffer, 0, 64); this.bufferLength = 0; } } if (dataLength >= 64) { dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength); dataLength %= 64; } while (dataLength > 0) { this.buffer[this.bufferLength++] = data[dataPos++]; dataLength--; } return this; }; Hash2.prototype.finish = function(out) { if (!this.finished) { var bytesHashed = this.bytesHashed; var left = this.bufferLength; var bitLenHi = bytesHashed / 536870912 | 0; var bitLenLo = bytesHashed << 3; var padLength = bytesHashed % 64 < 56 ? 64 : 128; this.buffer[left] = 128; for (var i = left + 1; i < padLength - 8; i++) { this.buffer[i] = 0; } this.buffer[padLength - 8] = bitLenHi >>> 24 & 255; this.buffer[padLength - 7] = bitLenHi >>> 16 & 255; this.buffer[padLength - 6] = bitLenHi >>> 8 & 255; this.buffer[padLength - 5] = bitLenHi >>> 0 & 255; this.buffer[padLength - 4] = bitLenLo >>> 24 & 255; this.buffer[padLength - 3] = bitLenLo >>> 16 & 255; this.buffer[padLength - 2] = bitLenLo >>> 8 & 255; this.buffer[padLength - 1] = bitLenLo >>> 0 & 255; hashBlocks(this.temp, this.state, this.buffer, 0, padLength); this.finished = true; } for (var i = 0; i < 8; i++) { out[i * 4 + 0] = this.state[i] >>> 24 & 255; out[i * 4 + 1] = this.state[i] >>> 16 & 255; out[i * 4 + 2] = this.state[i] >>> 8 & 255; out[i * 4 + 3] = this.state[i] >>> 0 & 255; } return this; }; Hash2.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; Hash2.prototype._saveState = function(out) { for (var i = 0; i < this.state.length; i++) { out[i] = this.state[i]; } }; Hash2.prototype._restoreState = function(from, bytesHashed) { for (var i = 0; i < this.state.length; i++) { this.state[i] = from[i]; } this.bytesHashed = bytesHashed; this.finished = false; this.bufferLength = 0; }; return Hash2; }() ); exports3.Hash = Hash; var HMAC = ( /** @class */ function() { function HMAC2(key) { this.inner = new Hash(); this.outer = new Hash(); this.blockSize = this.inner.blockSize; this.digestLength = this.inner.digestLength; var pad = new Uint8Array(this.blockSize); if (key.length > this.blockSize) { new Hash().update(key).finish(pad).clean(); } else { for (var i = 0; i < key.length; i++) { pad[i] = key[i]; } } for (var i = 0; i < pad.length; i++) { pad[i] ^= 54; } this.inner.update(pad); for (var i = 0; i < pad.length; i++) { pad[i] ^= 54 ^ 92; } this.outer.update(pad); this.istate = new Uint32Array(8); this.ostate = new Uint32Array(8); this.inner._saveState(this.istate); this.outer._saveState(this.ostate); for (var i = 0; i < pad.length; i++) { pad[i] = 0; } } HMAC2.prototype.reset = function() { this.inner._restoreState(this.istate, this.inner.blockSize); this.outer._restoreState(this.ostate, this.outer.blockSize); return this; }; HMAC2.prototype.clean = function() { for (var i = 0; i < this.istate.length; i++) { this.ostate[i] = this.istate[i] = 0; } this.inner.clean(); this.outer.clean(); }; HMAC2.prototype.update = function(data) { this.inner.update(data); return this; }; HMAC2.prototype.finish = function(out) { if (this.outer.finished) { this.outer.finish(out); } else { this.inner.finish(out); this.outer.update(out, this.digestLength).finish(out); } return this; }; HMAC2.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; return HMAC2; }() ); exports3.HMAC = HMAC; function hash(data) { var h = new Hash().update(data); var digest = h.digest(); h.clean(); return digest; } exports3.hash = hash; exports3["default"] = hash; function hmac(key, data) { var h = new HMAC(key).update(data); var digest = h.digest(); h.clean(); return digest; } exports3.hmac = hmac; function fillBuffer(buffer2, hmac2, info, counter) { var num = counter[0]; if (num === 0) { throw new Error("hkdf: cannot expand more"); } hmac2.reset(); if (num > 1) { hmac2.update(buffer2); } if (info) { hmac2.update(info); } hmac2.update(counter); hmac2.finish(buffer2); counter[0]++; } var hkdfSalt = new Uint8Array(exports3.digestLength); function hkdf(key, salt, info, length) { if (salt === void 0) { salt = hkdfSalt; } if (length === void 0) { length = 32; } var counter = new Uint8Array([1]); var okm = hmac(salt, key); var hmac_ = new HMAC(okm); var buffer2 = new Uint8Array(hmac_.digestLength); var bufpos = buffer2.length; var out = new Uint8Array(length); for (var i = 0; i < length; i++) { if (bufpos === buffer2.length) { fillBuffer(buffer2, hmac_, info, counter); bufpos = 0; } out[i] = buffer2[bufpos++]; } hmac_.clean(); buffer2.fill(0); counter.fill(0); return out; } exports3.hkdf = hkdf; function pbkdf2(password, salt, iterations, dkLen) { var prf = new HMAC(password); var len = prf.digestLength; var ctr = new Uint8Array(4); var t = new Uint8Array(len); var u = new Uint8Array(len); var dk = new Uint8Array(dkLen); for (var i = 0; i * len < dkLen; i++) { var c2 = i + 1; ctr[0] = c2 >>> 24 & 255; ctr[1] = c2 >>> 16 & 255; ctr[2] = c2 >>> 8 & 255; ctr[3] = c2 >>> 0 & 255; prf.reset(); prf.update(salt); prf.update(ctr); prf.finish(u); for (var j = 0; j < len; j++) { t[j] = u[j]; } for (var j = 2; j <= iterations; j++) { prf.reset(); prf.update(u).finish(u); for (var k = 0; k < len; k++) { t[k] ^= u[k]; } } for (var j = 0; j < len && i * len + j < dkLen; j++) { dk[i * len + j] = t[j]; } } for (var i = 0; i < len; i++) { t[i] = u[i] = 0; } for (var i = 0; i < 4; i++) { ctr[i] = 0; } prf.clean(); return dk; } exports3.pbkdf2 = pbkdf2; }); })(sha256$1); var sha256Exports = sha256$1.exports; const sha256 = /* @__PURE__ */ getDefaultExportFromCjs(sha256Exports); function cleanName(name) { return name.replaceAll("file:///", "").replaceAll(".", "_dot_").replaceAll("/", "_slash_").replaceAll("-", "_dash_"); } function closest(node2, cb) { while (node2) { if (cb(node2)) return node2; node2 = node2.parent; } return null; } function findShadeupTags(declar) { let matcher = /=tag\((.+)\)$/g; let doc = ts.getJSDocTags(declar); for (let d of doc) { if (d.tagName.text !== "shadeup") continue; if (typeof d.comment === "string") { let matches = matcher.exec(d.comment); if (matches) { return matches[1].split(",").map((s) => s.trim()); } } } return []; } function getFunctionDeclarationFromCallExpression(checker, node2) { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && ts.isFunctionDeclaration(funcDeclar)) { return funcDeclar; } } } } function toposort(edges) { return toposortinternal(uniqueNodes(edges), edges); } function toposortinternal(nodes, edges) { var cursor = nodes.length, sorted = new Array(cursor), visited = {}, i = cursor, outgoingEdges = makeOutgoingEdges(edges), nodesHash = makeNodesHash(nodes); edges.forEach(function(edge) { if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) { throw new Error("Unknown node. There is an unknown node in the supplied edges."); } }); while (i--) { if (!visited[i]) visit(nodes[i], i, /* @__PURE__ */ new Set()); } return sorted; function visit(node2, i2, predecessors) { if (predecessors.has(node2)) { var nodeRep; try { nodeRep = ", node was:" + JSON.stringify(node2); } catch (e) { nodeRep = ""; } throw new Error("Cyclic dependency" + nodeRep); } if (!nodesHash.has(node2)) { throw new Error( "Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(node2) ); } if (visited[i2]) return; visited[i2] = true; var outgoing = outgoingEdges.get(node2) || /* @__PURE__ */ new Set(); outgoing = Array.from(outgoing); if (i2 = outgoing.length) { predecessors.add(node2); do { var child = outgoing[--i2]; visit(child, nodesHash.get(child), predecessors); } while (i2); predecessors.delete(node2); } sorted[--cursor] = node2; } } function uniqueNodes(arr) { var res = /* @__PURE__ */ new Set(); for (var i = 0, len = arr.length; i < len; i++) { var edge = arr[i]; res.add(edge[0]); res.add(edge[1]); } return Array.from(res); } function makeOutgoingEdges(arr) { var edges = /* @__PURE__ */ new Map(); for (var i = 0, len = arr.length; i < len; i++) { var edge = arr[i]; if (!edges.has(edge[0])) edges.set(edge[0], /* @__PURE__ */ new Set()); if (!edges.has(edge[1])) edges.set(edge[1], /* @__PURE__ */ new Set()); edges.get(edge[0]).add(edge[1]); } return edges; } function makeNodesHash(arr) { var res = /* @__PURE__ */ new Map(); for (var i = 0, len = arr.length; i < len; i++) { res.set(arr[i], i); } return res; } const wgslHeader = "fn shadeup_up_swizzle_x_u32(n: u32) -> u32{\r\n return n;\r\n}\r\nfn shadeup_up_swizzle_xx_u32(n: u32) -> vec2{\r\n return vec2(n, n);\r\n}\r\nfn shadeup_up_swizzle_xxx_u32(n: u32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\nfn shadeup_up_swizzle_xxxx_u32(n: u32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_u32(n: u32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_u32(n: u32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_u32(n: u32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_x_i32(n: i32) -> i32{\r\n return n;\r\n}\r\n\r\nfn shadeup_up_swizzle_xx_i32(n: i32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxx_i32(n: i32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxxx_i32(n: i32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_i32(n: i32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_i32(n: i32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_i32(n: i32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_x_f32(n: f32) -> f32{\r\n return n;\r\n}\r\n\r\nfn shadeup_up_swizzle_xx_f32(n: f32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxx_f32(n: f32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxxx_f32(n: f32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_f32(n: f32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_f32(n: f32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_f32(n: f32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn squash_bool_vec2(n: vec2) -> bool {\r\n return n.x && n.y;\r\n}\r\n\r\nfn squash_bool_vec3(n: vec3) -> bool {\r\n return n.x && n.y && n.z;\r\n}\r\n\r\nfn squash_bool_vec4(n: vec4) -> bool {\r\n return n.x && n.y && n.z && n.w;\r\n}\r\n\r\nfn matrix_inversefloat4x4(m: mat4x4) -> mat4x4{\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n13 = m[2][0];\r\n let n14 = m[3][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n let n23 = m[2][1];\r\n let n24 = m[3][1];\r\n let n31 = m[0][2];\r\n let n32 = m[1][2];\r\n let n33 = m[2][2];\r\n let n34 = m[3][2];\r\n let n41 = m[0][3];\r\n let n42 = m[1][3];\r\n let n43 = m[2][3];\r\n let n44 = m[3][3];\r\n\r\n let t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;\r\n let t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;\r\n let t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;\r\n let t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;\r\n\r\n let det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat4x4 = mat4x4();\r\n\r\n ret[0][0] = t11 * idet;\r\n ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet;\r\n ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet;\r\n ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet;\r\n\r\n ret[1][0] = t12 * idet;\r\n ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet;\r\n ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet;\r\n ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet;\r\n\r\n ret[2][0] = t13 * idet;\r\n ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet;\r\n ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet;\r\n ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet;\r\n\r\n ret[3][0] = t14 * idet;\r\n ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet;\r\n ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet;\r\n ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_inversefloat3x3(m: mat3x3) -> mat3x3{\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n13 = m[2][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n let n23 = m[2][1];\r\n let n31 = m[0][2];\r\n let n32 = m[1][2];\r\n let n33 = m[2][2];\r\n\r\n let t11 = n22 * n33 - n23 * n32;\r\n let t12 = n13 * n32 - n12 * n33;\r\n let t13 = n12 * n23 - n13 * n22;\r\n\r\n let det = n11 * t11 + n21 * t12 + n31 * t13;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat3x3 = mat3x3();\r\n\r\n ret[0][0] = t11 * idet;\r\n ret[0][1] = (n23 * n31 - n21 * n33) * idet;\r\n ret[0][2] = (n21 * n32 - n22 * n31) * idet;\r\n\r\n ret[1][0] = t12 * idet;\r\n ret[1][1] = (n11 * n33 - n13 * n31) * idet;\r\n ret[1][2] = (n12 * n31 - n11 * n32) * idet;\r\n\r\n ret[2][0] = t13 * idet;\r\n ret[2][1] = (n13 * n21 - n11 * n23) * idet;\r\n ret[2][2] = (n11 * n22 - n12 * n21) * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_inversefloat2x2(m: mat2x2) -> mat2x2 {\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n\r\n let det = n11 * n22 - n12 * n21;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat2x2 = mat2x2();\r\n\r\n ret[0][0] = n22 * idet;\r\n ret[0][1] = -n12 * idet;\r\n ret[1][0] = -n21 * idet;\r\n ret[1][1] = n11 * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_transposefloat2x2(m: mat2x2) -> mat2x2 {\r\n return mat2x2(m[0][0], m[1][0], m[0][1], m[1][1]);\r\n}\r\n\r\nfn matrix_transposefloat3x3(m: mat3x3) -> mat3x3 {\r\n return mat3x3\r\n (\r\n m[0][0], m[1][0], m[2][0],\r\n m[0][1], m[1][1], m[2][1],\r\n m[0][2], m[1][2], m[2][2]\r\n );\r\n}\r\n\r\nfn matrix_transposefloat4x4(m: mat4x4) -> mat4x4 {\r\n return mat4x4\r\n (\r\n m[0][0], m[1][0], m[2][0], m[3][0],\r\n m[0][1], m[1][1], m[2][1], m[3][1],\r\n m[0][2], m[1][2], m[2][2], m[3][2],\r\n m[0][3], m[1][3], m[2][3], m[3][3]\r\n );\r\n}\r\n\r\nfn bilerp_float(a: f32, b: f32, c: f32, d: f32, x: f32, y: f32) -> f32 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float2(a: vec2, b: vec2, c: vec2, d: vec2, x: f32, y: f32) -> vec2 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float3(a: vec3, b: vec3, c: vec3, d: vec3, x: f32, y: f32) -> vec3 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float4(a: vec4, b: vec4, c: vec4, d: vec4, x: f32, y: f32) -> vec4 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float2x2(a: mat2x2, b: mat2x2, c: mat2x2, d: mat2x2, x: f32, y: f32) -> mat2x2 {\r\n return mat2x2\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y)\r\n );\r\n}\r\n\r\nfn bilerp_float3x3(a: mat3x3, b: mat3x3, c: mat3x3, d: mat3x3, x: f32, y: f32) -> mat3x3 {\r\n return mat3x3\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[0][2], b[0][2], c[0][2], d[0][2], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y),\r\n bilerp_float(a[1][2], b[1][2], c[1][2], d[1][2], x, y),\r\n bilerp_float(a[2][0], b[2][0], c[2][0], d[2][0], x, y),\r\n bilerp_float(a[2][1], b[2][1], c[2][1], d[2][1], x, y),\r\n bilerp_float(a[2][2], b[2][2], c[2][2], d[2][2], x, y)\r\n );\r\n}\r\n\r\nfn bilerp_float4x4(a: mat4x4, b: mat4x4, c: mat4x4, d: mat4x4, x: f32, y: f32) -> mat4x4 {\r\n return mat4x4\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[0][2], b[0][2], c[0][2], d[0][2], x, y),\r\n bilerp_float(a[0][3], b[0][3], c[0][3], d[0][3], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y),\r\n bilerp_float(a[1][2], b[1][2], c[1][2], d[1][2], x, y),\r\n bilerp_float(a[1][3], b[1][3], c[1][3], d[1][3], x, y),\r\n bilerp_float(a[2][0], b[2][0], c[2][0], d[2][0], x, y),\r\n bilerp_float(a[2][1], b[2][1], c[2][1], d[2][1], x, y),\r\n bilerp_float(a[2][2], b[2][2], c[2][2], d[2][2], x, y),\r\n bilerp_float(a[2][3], b[2][3], c[2][3], d[2][3], x, y),\r\n bilerp_float(a[3][0], b[3][0], c[3][0], d[3][0], x, y),\r\n bilerp_float(a[3][1], b[3][1], c[3][1], d[3][1], x, y),\r\n bilerp_float(a[3][2], b[3][2], c[3][2], d[3][2], x, y),\r\n bilerp_float(a[3][3], b[3][3], c[3][3], d[3][3], x, y)\r\n );\r\n}"; function validate(file, ast, checker) { performance.now(); const errors2 = []; function add(e) { if (e) { if (Array.isArray(e)) { errors2.push(...e); } else { errors2.push(e); } } } function visit(ctx) { ctx.node.forEachChild( (node2) => visit({ ...ctx, node: node2 }) ); if (ctx.node.kind == ts.SyntaxKind.PropertyAccessExpression) { if (ts.isPropertyAccessExpression(ctx.node)) { add(validatePropertyAccessExpression(ctx, ctx.node)); } } else if (ctx.node.kind == ts.SyntaxKind.ConditionalExpression) { if (ts.isConditionalExpression(ctx.node)) { add(validateConditionalExpression(ctx, ctx.node)); } } else if (ctx.node.kind == ts.SyntaxKind.CallExpression) { if (ts.isCallExpression(ctx.node)) { add(validateCallExpression(ctx, ctx.node)); } } } visit({ file, ast, checker, node: ast }); return errors2; } function validateGraph(env2, file, ast, checker) { performance.now(); const errors2 = []; function add(e) { if (e) { if (Array.isArray(e)) { errors2.push(...e); } else { errors2.push(e); } } } function visit(ctx) { ctx.node.forEachChild( (node2) => visit({ ...ctx, node: node2 }) ); if (ts.isCallExpression(ctx.node)) { let lhsType = checker?.getTypeAtLocation(ctx.node.getChildAt(0)); let sig = lhsType?.getCallSignatures(); if (sig && sig[0] && sig[0].getDeclaration()) { let declaration = sig[0].getDeclaration(); if (ts.isIdentifier(ctx.node.expression) && ctx.node.expression.text == "makeShader") { checker?.getTypeAtLocation(declaration); if (ctx.node.arguments.length >= 2) { if (ts.isArrowFunction(ctx.node.arguments[1])) { add(validateShaderCalls(env2, ctx, ctx.node.arguments[1])); } } } } } if (ts.isExpressionStatement(ctx.node)) { add(validateStatement(ctx, ctx.node)); } if (ts.isArrayLiteralExpression(ctx.node)) { add(validateArrayLiteral(ctx, ctx.node)); } } visit({ file, ast, checker, node: ast }); return errors2; } function isStaticPropertyAccessExpression(checker, node2) { let resultType = checker.getSymbolAtLocation(node2); if (!resultType) return false; let tos = checker.getTypeOfSymbolAtLocation(resultType, node2); let isStaticMember = false; if (resultType.parent) { let p = resultType.parent; if (p.valueDeclaration && p.name != "__" && !ts.isSourceFile(p.valueDeclaration) && p.flags & ts.SymbolFlags.Namespace) { isStaticMember = true; } } tos.getCallSignatures().forEach((s) => { if (s.declaration) { s.declaration.modifiers?.forEach((m) => { if (m.kind == ts.SyntaxKind.StaticKeyword) { isStaticMember = true; } }); } }); return isStaticMember; } function validateStatement({ checker, file }, node2) { if (ts.isLiteralExpression(node2.expression) || ts.isPropertyAccessChain(node2.expression) || ts.isPropertyAccessExpression(node2.expression) || ts.isIdentifier(node2.expression)) { return { file: node2.getSourceFile(), code: 0, messageText: `This expression has no effect`, category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }; } } function validateConditionalExpression({ checker, file }, node2) { let thenType = checker.getTypeAtLocation(node2.whenTrue); let elseType = checker.getTypeAtLocation(node2.whenFalse); if (!isTypeCompatible(checker, thenType, elseType)) { return void 0; } return void 0; } function validateCallExpression({ checker, file }, node2) { if (ts.isPropertyAccessExpression(node2.expression)) { let left = node2.expression.expression; if (!ts.isIdentifier(left)) return void 0; if (left.text != "__") return void 0; let right = node2.expression.name.text; if (right.startsWith("int") && (right[right.length - 1] == "2" || right[right.length - 1] == "3" || right[right.length - 1] == "4")) { for (let i = 0; i < node2.arguments.length; i++) { let arg = node2.arguments[i]; let type2 = checker.getTypeAtLocation(arg); let typeName = checker.typeToString(type2); if (typeName.startsWith("uint")) { if (node2.arguments.length != 1) { return { file: node2.getSourceFile(), code: 0, messageText: `Cannot convert from uint to int during vector construction, use int() before`, category: ts.DiagnosticCategory.Error, start: arg.getStart(), length: arg.getEnd() - arg.getStart() }; } } } } } return void 0; } function validatePropertyAccessExpression({ checker, file }, node2) { let midNode = node2.getChildren()[1]; if (file.mapping && midNode) { let range2 = lookupIndexMappingRange(file.mapping, midNode.getStart(), midNode.getEnd()); let s = file.content.substring(range2.start, range2.end); let isStaticAccess = s == "::"; let resultType = checker.getSymbolAtLocation(node2); if (resultType) { let tos = checker.getTypeOfSymbolAtLocation(resultType, node2); let isStaticMember = false; if (resultType.parent) { let p = resultType.parent; if (p.valueDeclaration && p.name != "__" && !ts.isSourceFile(p.valueDeclaration) && p.flags & ts.SymbolFlags.Namespace) { isStaticMember = true; } } tos.getCallSignatures().forEach((s2) => { if (s2.declaration) { s2.declaration.modifiers?.forEach((m) => { if (m.kind == ts.SyntaxKind.StaticKeyword) { isStaticMember = true; } }); } }); resultType.getDeclarations()?.forEach((d) => { if (ts.canHaveModifiers(d) && d.modifiers) { d.modifiers.forEach((m) => { if (m.kind == ts.SyntaxKind.StaticKeyword) { isStaticMember = true; } }); } }); if (isStaticMember && !isStaticAccess) { return { file: node2.getSourceFile(), code: 0, messageText: `Cannot access static member with '${s}' use '::' instead`, category: ts.DiagnosticCategory.Error, start: midNode.getStart(), length: midNode.getEnd() - midNode.getStart() }; } else if (!isStaticMember && isStaticAccess) { return { file: node2.getSourceFile(), code: 0, messageText: `Cannot access non-static member with '${s}' use '.' instead`, category: ts.DiagnosticCategory.Error, start: midNode.getStart(), length: midNode.getEnd() - midNode.getStart() }; } } } return void 0; } function isTypeCompatible(checker, type2, typeOther) { return checker.isTypeAssignableTo(type2, typeOther); } function validateArrayLiteral({ checker, file }, node2) { if (node2.elements.length == 3) { let name1 = checker.typeToString(checker.getTypeAtLocation(node2.elements[0])); let name2 = checker.typeToString(checker.getTypeAtLocation(node2.elements[1])); let name3 = checker.typeToString(checker.getTypeAtLocation(node2.elements[2])); if (name1 == "0" && name2 == "shader" && name3 == "0") { return void 0; } } return void 0; } const SHADER_TYPE_BLACKLIST = ["string", "null", "map"]; function validateShaderTypeUse(env2, { checker, file }, diags, node2, typeNode) { let type2 = checker.typeToString(typeNode); if (SHADER_TYPE_BLACKLIST.includes(type2) || type2.startsWith("map<")) { diags.push({ file: node2.getSourceFile(), code: 0, messageText: `Cannot use type '${type2}' in shader`, category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }); } if (typeNode.isUnion() && type2 != "boolean") { diags.push({ file: node2.getSourceFile(), code: 0, messageText: `Cannot use union types in shaders ('${type2}')`, category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }); } if (typeNode.isLiteral()) { diags.push({ file: node2.getSourceFile(), code: 0, messageText: `Cannot use literal types in shaders ('${type2}')`, category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }); } } function validateShaderCalls(env2, vs, node2) { let diags = []; const { checker, file } = vs; let visit = (node22) => { if (ts.isCallExpression(node22)) { let declar = getFunctionDeclarationFromCallExpression(checker, node22); if (declar) { let graphNodeName = getFunctionNodeName(declar); let graphNode = env2.tagGraph.getNode(graphNodeName); if (graphNode) { if (graphNode.tags.includes("async")) { let rawChain = env2.tagGraph.resolveTagSourceChain(graphNodeName, "async"); let chain = rawChain.map((m) => m.split(":")[1]).join(" <- "); if (rawChain[rawChain.length - 1].split(":")[1] == "texture2d_internal_empty") ; else { diags.push({ file: node22.getSourceFile(), code: 0, messageText: `Cannot call cpu-only function from a shader. ${chain}`, category: ts.DiagnosticCategory.Error, start: node22.getStart(), length: node22.getEnd() - node22.getStart() }); } } } } validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22)); } if (ts.isPropertyAccessExpression(node22)) { validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22)); } if (ts.isIdentifier(node22)) { validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22)); } if (ts.isElementAccessExpression(node22)) { validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22)); } if (ts.isVariableDeclaration(node22)) { let arrType = checker.getTypeAtLocation(node22); let typeInfo = getArrayTypeInfo(checker, arrType); if (typeInfo.isArray) { if (typeInfo.staticSize <= 0) { diags.push({ file: node22.getSourceFile(), code: 0, messageText: `Please explicitly specify the size of the array (let a: T[10] = ...)`, category: ts.DiagnosticCategory.Error, start: node22.getStart(), length: node22.getEnd() - node22.getStart() }); } } } ts.forEachChild(node22, visit); }; ts.forEachChild(node2, visit); return diags; } var tsutils = {}; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { d2.__proto__ = b2; } || function(d2, b2) { for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign2(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c2 = arguments.length, r = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c2 < 3 ? d(r) : c2 > 3 ? d(target, key, r) : d(target, key)) || r; return c2 > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g2; return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() { return this; }), g2; function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __createBinding(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; } function __exportStar(m, exports3) { for (var p in m) if (p !== "default" && !exports3.hasOwnProperty(p)) exports3[p] = m[p]; } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function() { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g2 = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i; function verb(n) { if (g2[n]) i[n] = function(v) { return new Promise(function(a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g2[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function(e) { throw e; }), verb("return"), i[Symbol.iterator] = function() { return this; }, i; function verb(n, f) { i[n] = o[n] ? function(v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve({ value: v2, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; } result.default = mod; return result; } function __importDefault(mod) { return mod && mod.__esModule ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } const tslib_es6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, get __assign() { return __assign; }, __asyncDelegator, __asyncGenerator, __asyncValues, __await, __awaiter, __classPrivateFieldGet, __classPrivateFieldSet, __createBinding, __decorate, __exportStar, __extends, __generator, __importDefault, __importStar, __makeTemplateObject, __metadata, __param, __read, __rest, __spread, __spreadArrays, __values }, Symbol.toStringTag, { value: "Module" })); const require$$0 = /* @__PURE__ */ getAugmentedNamespace(tslib_es6); var typeguard = {}; var node$4 = {}; var node$3 = {}; var node$2 = {}; var node$1 = {}; var node = {}; var hasRequiredNode$4; function requireNode$4() { if (hasRequiredNode$4) return node; hasRequiredNode$4 = 1; Object.defineProperty(node, "__esModule", { value: true }); node.isExpressionStatement = node.isExpression = node.isExportSpecifier = node.isExportDeclaration = node.isExportAssignment = node.isEnumMember = node.isEnumDeclaration = node.isEntityNameExpression = node.isEntityName = node.isEmptyStatement = node.isElementAccessExpression = node.isDoStatement = node.isDeleteExpression = node.isDefaultClause = node.isDecorator = node.isDebuggerStatement = node.isComputedPropertyName = node.isContinueStatement = node.isConstructSignatureDeclaration = node.isConstructorTypeNode = node.isConstructorDeclaration = node.isConditionalTypeNode = node.isConditionalExpression = node.isCommaListExpression = node.isClassLikeDeclaration = node.isClassExpression = node.isClassDeclaration = node.isCatchClause = node.isCaseOrDefaultClause = node.isCaseClause = node.isCaseBlock = node.isCallSignatureDeclaration = node.isCallLikeExpression = node.isCallExpression = node.isBreakStatement = node.isBreakOrContinueStatement = node.isBooleanLiteral = node.isBlockLike = node.isBlock = node.isBindingPattern = node.isBindingElement = node.isBinaryExpression = node.isAwaitExpression = node.isAssertionExpression = node.isAsExpression = node.isArrowFunction = node.isArrayTypeNode = node.isArrayLiteralExpression = node.isArrayBindingPattern = node.isAccessorDeclaration = void 0; node.isNamespaceImport = node.isNamespaceDeclaration = node.isNamedImports = node.isNamedExports = node.isModuleDeclaration = node.isModuleBlock = node.isMethodSignature = node.isMethodDeclaration = node.isMetaProperty = node.isMappedTypeNode = node.isLiteralTypeNode = node.isLiteralExpression = node.isLabeledStatement = node.isJsxText = node.isJsxSpreadAttribute = node.isJsxSelfClosingElement = node.isJsxOpeningLikeElement = node.isJsxOpeningFragment = node.isJsxOpeningElement = node.isJsxFragment = node.isJsxExpression = node.isJsxElement = node.isJsxClosingFragment = node.isJsxClosingElement = node.isJsxAttributes = node.isJsxAttributeLike = node.isJsxAttribute = node.isJsDoc = node.isIterationStatement = node.isIntersectionTypeNode = node.isInterfaceDeclaration = node.isInferTypeNode = node.isIndexSignatureDeclaration = node.isIndexedAccessTypeNode = node.isImportSpecifier = node.isImportEqualsDeclaration = node.isImportDeclaration = node.isImportClause = node.isIfStatement = node.isIdentifier = node.isGetAccessorDeclaration = node.isFunctionTypeNode = node.isFunctionExpression = node.isFunctionDeclaration = node.isForStatement = node.isForOfStatement = node.isForInOrOfStatement = node.isForInStatement = node.isExternalModuleReference = node.isExpressionWithTypeArguments = void 0; node.isVariableStatement = node.isVariableDeclaration = node.isUnionTypeNode = node.isTypeQueryNode = node.isTypeReferenceNode = node.isTypePredicateNode = node.isTypeParameterDeclaration = node.isTypeOperatorNode = node.isTypeOfExpression = node.isTypeLiteralNode = node.isTypeAssertion = node.isTypeAliasDeclaration = node.isTupleTypeNode = node.isTryStatement = node.isThrowStatement = node.isTextualLiteral = node.isTemplateLiteral = node.isTemplateExpression = node.isTaggedTemplateExpression = node.isSyntaxList = node.isSwitchStatement = node.isStringLiteral = node.isSpreadElement = node.isSpreadAssignment = node.isSourceFile = node.isSignatureDeclaration = node.isShorthandPropertyAssignment = node.isSetAccessorDeclaration = node.isReturnStatement = node.isRegularExpressionLiteral = node.isQualifiedName = node.isPropertySignature = node.isPropertyDeclaration = node.isPropertyAssignment = node.isPropertyAccessExpression = node.isPrefixUnaryExpression = node.isPostfixUnaryExpression = node.isParenthesizedTypeNode = node.isParenthesizedExpression = node.isParameterDeclaration = node.isOmittedExpression = node.isObjectLiteralExpression = node.isObjectBindingPattern = node.isNumericOrStringLikeLiteral = node.isNumericLiteral = node.isNullLiteral = node.isNoSubstitutionTemplateLiteral = node.isNonNullExpression = node.isNewExpression = node.isNamespaceExportDeclaration = void 0; node.isWithStatement = node.isWhileStatement = node.isVoidExpression = node.isVariableDeclarationList = void 0; const ts$1 = ts; function isAccessorDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.GetAccessor || node2.kind === ts$1.SyntaxKind.SetAccessor; } node.isAccessorDeclaration = isAccessorDeclaration; function isArrayBindingPattern(node2) { return node2.kind === ts$1.SyntaxKind.ArrayBindingPattern; } node.isArrayBindingPattern = isArrayBindingPattern; function isArrayLiteralExpression(node2) { return node2.kind === ts$1.SyntaxKind.ArrayLiteralExpression; } node.isArrayLiteralExpression = isArrayLiteralExpression; function isArrayTypeNode2(node2) { return node2.kind === ts$1.SyntaxKind.ArrayType; } node.isArrayTypeNode = isArrayTypeNode2; function isArrowFunction(node2) { return node2.kind === ts$1.SyntaxKind.ArrowFunction; } node.isArrowFunction = isArrowFunction; function isAsExpression(node2) { return node2.kind === ts$1.SyntaxKind.AsExpression; } node.isAsExpression = isAsExpression; function isAssertionExpression(node2) { return node2.kind === ts$1.SyntaxKind.AsExpression || node2.kind === ts$1.SyntaxKind.TypeAssertionExpression; } node.isAssertionExpression = isAssertionExpression; function isAwaitExpression(node2) { return node2.kind === ts$1.SyntaxKind.AwaitExpression; } node.isAwaitExpression = isAwaitExpression; function isBinaryExpression(node2) { return node2.kind === ts$1.SyntaxKind.BinaryExpression; } node.isBinaryExpression = isBinaryExpression; function isBindingElement(node2) { return node2.kind === ts$1.SyntaxKind.BindingElement; } node.isBindingElement = isBindingElement; function isBindingPattern(node2) { return node2.kind === ts$1.SyntaxKind.ArrayBindingPattern || node2.kind === ts$1.SyntaxKind.ObjectBindingPattern; } node.isBindingPattern = isBindingPattern; function isBlock(node2) { return node2.kind === ts$1.SyntaxKind.Block; } node.isBlock = isBlock; function isBlockLike(node2) { return node2.statements !== void 0; } node.isBlockLike = isBlockLike; function isBooleanLiteral(node2) { return node2.kind === ts$1.SyntaxKind.TrueKeyword || node2.kind === ts$1.SyntaxKind.FalseKeyword; } node.isBooleanLiteral = isBooleanLiteral; function isBreakOrContinueStatement(node2) { return node2.kind === ts$1.SyntaxKind.BreakStatement || node2.kind === ts$1.SyntaxKind.ContinueStatement; } node.isBreakOrContinueStatement = isBreakOrContinueStatement; function isBreakStatement(node2) { return node2.kind === ts$1.SyntaxKind.BreakStatement; } node.isBreakStatement = isBreakStatement; function isCallExpression2(node2) { return node2.kind === ts$1.SyntaxKind.CallExpression; } node.isCallExpression = isCallExpression2; function isCallLikeExpression(node2) { switch (node2.kind) { case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.Decorator: case ts$1.SyntaxKind.JsxOpeningElement: case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.NewExpression: case ts$1.SyntaxKind.TaggedTemplateExpression: return true; default: return false; } } node.isCallLikeExpression = isCallLikeExpression; function isCallSignatureDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.CallSignature; } node.isCallSignatureDeclaration = isCallSignatureDeclaration; function isCaseBlock(node2) { return node2.kind === ts$1.SyntaxKind.CaseBlock; } node.isCaseBlock = isCaseBlock; function isCaseClause(node2) { return node2.kind === ts$1.SyntaxKind.CaseClause; } node.isCaseClause = isCaseClause; function isCaseOrDefaultClause(node2) { return node2.kind === ts$1.SyntaxKind.CaseClause || node2.kind === ts$1.SyntaxKind.DefaultClause; } node.isCaseOrDefaultClause = isCaseOrDefaultClause; function isCatchClause(node2) { return node2.kind === ts$1.SyntaxKind.CatchClause; } node.isCatchClause = isCatchClause; function isClassDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ClassDeclaration; } node.isClassDeclaration = isClassDeclaration; function isClassExpression(node2) { return node2.kind === ts$1.SyntaxKind.ClassExpression; } node.isClassExpression = isClassExpression; function isClassLikeDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ClassDeclaration || node2.kind === ts$1.SyntaxKind.ClassExpression; } node.isClassLikeDeclaration = isClassLikeDeclaration; function isCommaListExpression(node2) { return node2.kind === ts$1.SyntaxKind.CommaListExpression; } node.isCommaListExpression = isCommaListExpression; function isConditionalExpression(node2) { return node2.kind === ts$1.SyntaxKind.ConditionalExpression; } node.isConditionalExpression = isConditionalExpression; function isConditionalTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.ConditionalType; } node.isConditionalTypeNode = isConditionalTypeNode; function isConstructorDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.Constructor; } node.isConstructorDeclaration = isConstructorDeclaration; function isConstructorTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.ConstructorType; } node.isConstructorTypeNode = isConstructorTypeNode; function isConstructSignatureDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ConstructSignature; } node.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isContinueStatement(node2) { return node2.kind === ts$1.SyntaxKind.ContinueStatement; } node.isContinueStatement = isContinueStatement; function isComputedPropertyName(node2) { return node2.kind === ts$1.SyntaxKind.ComputedPropertyName; } node.isComputedPropertyName = isComputedPropertyName; function isDebuggerStatement(node2) { return node2.kind === ts$1.SyntaxKind.DebuggerStatement; } node.isDebuggerStatement = isDebuggerStatement; function isDecorator(node2) { return node2.kind === ts$1.SyntaxKind.Decorator; } node.isDecorator = isDecorator; function isDefaultClause(node2) { return node2.kind === ts$1.SyntaxKind.DefaultClause; } node.isDefaultClause = isDefaultClause; function isDeleteExpression(node2) { return node2.kind === ts$1.SyntaxKind.DeleteExpression; } node.isDeleteExpression = isDeleteExpression; function isDoStatement(node2) { return node2.kind === ts$1.SyntaxKind.DoStatement; } node.isDoStatement = isDoStatement; function isElementAccessExpression(node2) { return node2.kind === ts$1.SyntaxKind.ElementAccessExpression; } node.isElementAccessExpression = isElementAccessExpression; function isEmptyStatement(node2) { return node2.kind === ts$1.SyntaxKind.EmptyStatement; } node.isEmptyStatement = isEmptyStatement; function isEntityName(node2) { return node2.kind === ts$1.SyntaxKind.Identifier || isQualifiedName(node2); } node.isEntityName = isEntityName; function isEntityNameExpression(node2) { return node2.kind === ts$1.SyntaxKind.Identifier || isPropertyAccessExpression2(node2) && isEntityNameExpression(node2.expression); } node.isEntityNameExpression = isEntityNameExpression; function isEnumDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.EnumDeclaration; } node.isEnumDeclaration = isEnumDeclaration; function isEnumMember(node2) { return node2.kind === ts$1.SyntaxKind.EnumMember; } node.isEnumMember = isEnumMember; function isExportAssignment(node2) { return node2.kind === ts$1.SyntaxKind.ExportAssignment; } node.isExportAssignment = isExportAssignment; function isExportDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ExportDeclaration; } node.isExportDeclaration = isExportDeclaration; function isExportSpecifier(node2) { return node2.kind === ts$1.SyntaxKind.ExportSpecifier; } node.isExportSpecifier = isExportSpecifier; function isExpression(node2) { switch (node2.kind) { case ts$1.SyntaxKind.ArrayLiteralExpression: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.AsExpression: case ts$1.SyntaxKind.AwaitExpression: case ts$1.SyntaxKind.BinaryExpression: case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.CommaListExpression: case ts$1.SyntaxKind.ConditionalExpression: case ts$1.SyntaxKind.DeleteExpression: case ts$1.SyntaxKind.ElementAccessExpression: case ts$1.SyntaxKind.FalseKeyword: case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.Identifier: case ts$1.SyntaxKind.JsxElement: case ts$1.SyntaxKind.JsxFragment: case ts$1.SyntaxKind.JsxExpression: case ts$1.SyntaxKind.JsxOpeningElement: case ts$1.SyntaxKind.JsxOpeningFragment: case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.MetaProperty: case ts$1.SyntaxKind.NewExpression: case ts$1.SyntaxKind.NonNullExpression: case ts$1.SyntaxKind.NoSubstitutionTemplateLiteral: case ts$1.SyntaxKind.NullKeyword: case ts$1.SyntaxKind.NumericLiteral: case ts$1.SyntaxKind.ObjectLiteralExpression: case ts$1.SyntaxKind.OmittedExpression: case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.PostfixUnaryExpression: case ts$1.SyntaxKind.PrefixUnaryExpression: case ts$1.SyntaxKind.PropertyAccessExpression: case ts$1.SyntaxKind.RegularExpressionLiteral: case ts$1.SyntaxKind.SpreadElement: case ts$1.SyntaxKind.StringLiteral: case ts$1.SyntaxKind.SuperKeyword: case ts$1.SyntaxKind.TaggedTemplateExpression: case ts$1.SyntaxKind.TemplateExpression: case ts$1.SyntaxKind.ThisKeyword: case ts$1.SyntaxKind.TrueKeyword: case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.TypeOfExpression: case ts$1.SyntaxKind.VoidExpression: case ts$1.SyntaxKind.YieldExpression: return true; default: return false; } } node.isExpression = isExpression; function isExpressionStatement(node2) { return node2.kind === ts$1.SyntaxKind.ExpressionStatement; } node.isExpressionStatement = isExpressionStatement; function isExpressionWithTypeArguments(node2) { return node2.kind === ts$1.SyntaxKind.ExpressionWithTypeArguments; } node.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isExternalModuleReference(node2) { return node2.kind === ts$1.SyntaxKind.ExternalModuleReference; } node.isExternalModuleReference = isExternalModuleReference; function isForInStatement(node2) { return node2.kind === ts$1.SyntaxKind.ForInStatement; } node.isForInStatement = isForInStatement; function isForInOrOfStatement(node2) { return node2.kind === ts$1.SyntaxKind.ForOfStatement || node2.kind === ts$1.SyntaxKind.ForInStatement; } node.isForInOrOfStatement = isForInOrOfStatement; function isForOfStatement(node2) { return node2.kind === ts$1.SyntaxKind.ForOfStatement; } node.isForOfStatement = isForOfStatement; function isForStatement(node2) { return node2.kind === ts$1.SyntaxKind.ForStatement; } node.isForStatement = isForStatement; function isFunctionDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.FunctionDeclaration; } node.isFunctionDeclaration = isFunctionDeclaration; function isFunctionExpression(node2) { return node2.kind === ts$1.SyntaxKind.FunctionExpression; } node.isFunctionExpression = isFunctionExpression; function isFunctionTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.FunctionType; } node.isFunctionTypeNode = isFunctionTypeNode; function isGetAccessorDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.GetAccessor; } node.isGetAccessorDeclaration = isGetAccessorDeclaration; function isIdentifier2(node2) { return node2.kind === ts$1.SyntaxKind.Identifier; } node.isIdentifier = isIdentifier2; function isIfStatement(node2) { return node2.kind === ts$1.SyntaxKind.IfStatement; } node.isIfStatement = isIfStatement; function isImportClause(node2) { return node2.kind === ts$1.SyntaxKind.ImportClause; } node.isImportClause = isImportClause; function isImportDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ImportDeclaration; } node.isImportDeclaration = isImportDeclaration; function isImportEqualsDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ImportEqualsDeclaration; } node.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportSpecifier(node2) { return node2.kind === ts$1.SyntaxKind.ImportSpecifier; } node.isImportSpecifier = isImportSpecifier; function isIndexedAccessTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.IndexedAccessType; } node.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isIndexSignatureDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.IndexSignature; } node.isIndexSignatureDeclaration = isIndexSignatureDeclaration; function isInferTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.InferType; } node.isInferTypeNode = isInferTypeNode; function isInterfaceDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.InterfaceDeclaration; } node.isInterfaceDeclaration = isInterfaceDeclaration; function isIntersectionTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.IntersectionType; } node.isIntersectionTypeNode = isIntersectionTypeNode; function isIterationStatement(node2) { switch (node2.kind) { case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.ForInStatement: case ts$1.SyntaxKind.WhileStatement: case ts$1.SyntaxKind.DoStatement: return true; default: return false; } } node.isIterationStatement = isIterationStatement; function isJsDoc(node2) { return node2.kind === ts$1.SyntaxKind.JSDocComment; } node.isJsDoc = isJsDoc; function isJsxAttribute(node2) { return node2.kind === ts$1.SyntaxKind.JsxAttribute; } node.isJsxAttribute = isJsxAttribute; function isJsxAttributeLike(node2) { return node2.kind === ts$1.SyntaxKind.JsxAttribute || node2.kind === ts$1.SyntaxKind.JsxSpreadAttribute; } node.isJsxAttributeLike = isJsxAttributeLike; function isJsxAttributes(node2) { return node2.kind === ts$1.SyntaxKind.JsxAttributes; } node.isJsxAttributes = isJsxAttributes; function isJsxClosingElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxClosingElement; } node.isJsxClosingElement = isJsxClosingElement; function isJsxClosingFragment(node2) { return node2.kind === ts$1.SyntaxKind.JsxClosingFragment; } node.isJsxClosingFragment = isJsxClosingFragment; function isJsxElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxElement; } node.isJsxElement = isJsxElement; function isJsxExpression(node2) { return node2.kind === ts$1.SyntaxKind.JsxExpression; } node.isJsxExpression = isJsxExpression; function isJsxFragment(node2) { return node2.kind === ts$1.SyntaxKind.JsxFragment; } node.isJsxFragment = isJsxFragment; function isJsxOpeningElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxOpeningElement; } node.isJsxOpeningElement = isJsxOpeningElement; function isJsxOpeningFragment(node2) { return node2.kind === ts$1.SyntaxKind.JsxOpeningFragment; } node.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxOpeningLikeElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxOpeningElement || node2.kind === ts$1.SyntaxKind.JsxSelfClosingElement; } node.isJsxOpeningLikeElement = isJsxOpeningLikeElement; function isJsxSelfClosingElement(node2) { return node2.kind === ts$1.SyntaxKind.JsxSelfClosingElement; } node.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxSpreadAttribute(node2) { return node2.kind === ts$1.SyntaxKind.JsxSpreadAttribute; } node.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxText(node2) { return node2.kind === ts$1.SyntaxKind.JsxText; } node.isJsxText = isJsxText; function isLabeledStatement(node2) { return node2.kind === ts$1.SyntaxKind.LabeledStatement; } node.isLabeledStatement = isLabeledStatement; function isLiteralExpression(node2) { return node2.kind >= ts$1.SyntaxKind.FirstLiteralToken && node2.kind <= ts$1.SyntaxKind.LastLiteralToken; } node.isLiteralExpression = isLiteralExpression; function isLiteralTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.LiteralType; } node.isLiteralTypeNode = isLiteralTypeNode; function isMappedTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.MappedType; } node.isMappedTypeNode = isMappedTypeNode; function isMetaProperty(node2) { return node2.kind === ts$1.SyntaxKind.MetaProperty; } node.isMetaProperty = isMetaProperty; function isMethodDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.MethodDeclaration; } node.isMethodDeclaration = isMethodDeclaration; function isMethodSignature(node2) { return node2.kind === ts$1.SyntaxKind.MethodSignature; } node.isMethodSignature = isMethodSignature; function isModuleBlock(node2) { return node2.kind === ts$1.SyntaxKind.ModuleBlock; } node.isModuleBlock = isModuleBlock; function isModuleDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.ModuleDeclaration; } node.isModuleDeclaration = isModuleDeclaration; function isNamedExports(node2) { return node2.kind === ts$1.SyntaxKind.NamedExports; } node.isNamedExports = isNamedExports; function isNamedImports(node2) { return node2.kind === ts$1.SyntaxKind.NamedImports; } node.isNamedImports = isNamedImports; function isNamespaceDeclaration(node2) { return isModuleDeclaration(node2) && node2.name.kind === ts$1.SyntaxKind.Identifier && node2.body !== void 0 && (node2.body.kind === ts$1.SyntaxKind.ModuleBlock || isNamespaceDeclaration(node2.body)); } node.isNamespaceDeclaration = isNamespaceDeclaration; function isNamespaceImport(node2) { return node2.kind === ts$1.SyntaxKind.NamespaceImport; } node.isNamespaceImport = isNamespaceImport; function isNamespaceExportDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.NamespaceExportDeclaration; } node.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isNewExpression(node2) { return node2.kind === ts$1.SyntaxKind.NewExpression; } node.isNewExpression = isNewExpression; function isNonNullExpression(node2) { return node2.kind === ts$1.SyntaxKind.NonNullExpression; } node.isNonNullExpression = isNonNullExpression; function isNoSubstitutionTemplateLiteral(node2) { return node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral; } node.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; function isNullLiteral(node2) { return node2.kind === ts$1.SyntaxKind.NullKeyword; } node.isNullLiteral = isNullLiteral; function isNumericLiteral(node2) { return node2.kind === ts$1.SyntaxKind.NumericLiteral; } node.isNumericLiteral = isNumericLiteral; function isNumericOrStringLikeLiteral(node2) { switch (node2.kind) { case ts$1.SyntaxKind.StringLiteral: case ts$1.SyntaxKind.NumericLiteral: case ts$1.SyntaxKind.NoSubstitutionTemplateLiteral: return true; default: return false; } } node.isNumericOrStringLikeLiteral = isNumericOrStringLikeLiteral; function isObjectBindingPattern(node2) { return node2.kind === ts$1.SyntaxKind.ObjectBindingPattern; } node.isObjectBindingPattern = isObjectBindingPattern; function isObjectLiteralExpression(node2) { return node2.kind === ts$1.SyntaxKind.ObjectLiteralExpression; } node.isObjectLiteralExpression = isObjectLiteralExpression; function isOmittedExpression(node2) { return node2.kind === ts$1.SyntaxKind.OmittedExpression; } node.isOmittedExpression = isOmittedExpression; function isParameterDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.Parameter; } node.isParameterDeclaration = isParameterDeclaration; function isParenthesizedExpression(node2) { return node2.kind === ts$1.SyntaxKind.ParenthesizedExpression; } node.isParenthesizedExpression = isParenthesizedExpression; function isParenthesizedTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.ParenthesizedType; } node.isParenthesizedTypeNode = isParenthesizedTypeNode; function isPostfixUnaryExpression(node2) { return node2.kind === ts$1.SyntaxKind.PostfixUnaryExpression; } node.isPostfixUnaryExpression = isPostfixUnaryExpression; function isPrefixUnaryExpression(node2) { return node2.kind === ts$1.SyntaxKind.PrefixUnaryExpression; } node.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPropertyAccessExpression2(node2) { return node2.kind === ts$1.SyntaxKind.PropertyAccessExpression; } node.isPropertyAccessExpression = isPropertyAccessExpression2; function isPropertyAssignment(node2) { return node2.kind === ts$1.SyntaxKind.PropertyAssignment; } node.isPropertyAssignment = isPropertyAssignment; function isPropertyDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.PropertyDeclaration; } node.isPropertyDeclaration = isPropertyDeclaration; function isPropertySignature(node2) { return node2.kind === ts$1.SyntaxKind.PropertySignature; } node.isPropertySignature = isPropertySignature; function isQualifiedName(node2) { return node2.kind === ts$1.SyntaxKind.QualifiedName; } node.isQualifiedName = isQualifiedName; function isRegularExpressionLiteral(node2) { return node2.kind === ts$1.SyntaxKind.RegularExpressionLiteral; } node.isRegularExpressionLiteral = isRegularExpressionLiteral; function isReturnStatement(node2) { return node2.kind === ts$1.SyntaxKind.ReturnStatement; } node.isReturnStatement = isReturnStatement; function isSetAccessorDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.SetAccessor; } node.isSetAccessorDeclaration = isSetAccessorDeclaration; function isShorthandPropertyAssignment(node2) { return node2.kind === ts$1.SyntaxKind.ShorthandPropertyAssignment; } node.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSignatureDeclaration(node2) { return node2.parameters !== void 0; } node.isSignatureDeclaration = isSignatureDeclaration; function isSourceFile(node2) { return node2.kind === ts$1.SyntaxKind.SourceFile; } node.isSourceFile = isSourceFile; function isSpreadAssignment(node2) { return node2.kind === ts$1.SyntaxKind.SpreadAssignment; } node.isSpreadAssignment = isSpreadAssignment; function isSpreadElement(node2) { return node2.kind === ts$1.SyntaxKind.SpreadElement; } node.isSpreadElement = isSpreadElement; function isStringLiteral(node2) { return node2.kind === ts$1.SyntaxKind.StringLiteral; } node.isStringLiteral = isStringLiteral; function isSwitchStatement(node2) { return node2.kind === ts$1.SyntaxKind.SwitchStatement; } node.isSwitchStatement = isSwitchStatement; function isSyntaxList(node2) { return node2.kind === ts$1.SyntaxKind.SyntaxList; } node.isSyntaxList = isSyntaxList; function isTaggedTemplateExpression(node2) { return node2.kind === ts$1.SyntaxKind.TaggedTemplateExpression; } node.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTemplateExpression(node2) { return node2.kind === ts$1.SyntaxKind.TemplateExpression; } node.isTemplateExpression = isTemplateExpression; function isTemplateLiteral(node2) { return node2.kind === ts$1.SyntaxKind.TemplateExpression || node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral; } node.isTemplateLiteral = isTemplateLiteral; function isTextualLiteral(node2) { return node2.kind === ts$1.SyntaxKind.StringLiteral || node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral; } node.isTextualLiteral = isTextualLiteral; function isThrowStatement(node2) { return node2.kind === ts$1.SyntaxKind.ThrowStatement; } node.isThrowStatement = isThrowStatement; function isTryStatement(node2) { return node2.kind === ts$1.SyntaxKind.TryStatement; } node.isTryStatement = isTryStatement; function isTupleTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.TupleType; } node.isTupleTypeNode = isTupleTypeNode; function isTypeAliasDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.TypeAliasDeclaration; } node.isTypeAliasDeclaration = isTypeAliasDeclaration; function isTypeAssertion(node2) { return node2.kind === ts$1.SyntaxKind.TypeAssertionExpression; } node.isTypeAssertion = isTypeAssertion; function isTypeLiteralNode(node2) { return node2.kind === ts$1.SyntaxKind.TypeLiteral; } node.isTypeLiteralNode = isTypeLiteralNode; function isTypeOfExpression(node2) { return node2.kind === ts$1.SyntaxKind.TypeOfExpression; } node.isTypeOfExpression = isTypeOfExpression; function isTypeOperatorNode(node2) { return node2.kind === ts$1.SyntaxKind.TypeOperator; } node.isTypeOperatorNode = isTypeOperatorNode; function isTypeParameterDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.TypeParameter; } node.isTypeParameterDeclaration = isTypeParameterDeclaration; function isTypePredicateNode(node2) { return node2.kind === ts$1.SyntaxKind.TypePredicate; } node.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node2) { return node2.kind === ts$1.SyntaxKind.TypeReference; } node.isTypeReferenceNode = isTypeReferenceNode; function isTypeQueryNode(node2) { return node2.kind === ts$1.SyntaxKind.TypeQuery; } node.isTypeQueryNode = isTypeQueryNode; function isUnionTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.UnionType; } node.isUnionTypeNode = isUnionTypeNode; function isVariableDeclaration(node2) { return node2.kind === ts$1.SyntaxKind.VariableDeclaration; } node.isVariableDeclaration = isVariableDeclaration; function isVariableStatement(node2) { return node2.kind === ts$1.SyntaxKind.VariableStatement; } node.isVariableStatement = isVariableStatement; function isVariableDeclarationList(node2) { return node2.kind === ts$1.SyntaxKind.VariableDeclarationList; } node.isVariableDeclarationList = isVariableDeclarationList; function isVoidExpression(node2) { return node2.kind === ts$1.SyntaxKind.VoidExpression; } node.isVoidExpression = isVoidExpression; function isWhileStatement(node2) { return node2.kind === ts$1.SyntaxKind.WhileStatement; } node.isWhileStatement = isWhileStatement; function isWithStatement(node2) { return node2.kind === ts$1.SyntaxKind.WithStatement; } node.isWithStatement = isWithStatement; return node; } var hasRequiredNode$3; function requireNode$3() { if (hasRequiredNode$3) return node$1; hasRequiredNode$3 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); exports3.isImportTypeNode = void 0; const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$4(), exports3); const ts$1 = ts; function isImportTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.ImportType; } exports3.isImportTypeNode = isImportTypeNode; })(node$1); return node$1; } var hasRequiredNode$2; function requireNode$2() { if (hasRequiredNode$2) return node$2; hasRequiredNode$2 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); exports3.isSyntheticExpression = exports3.isRestTypeNode = exports3.isOptionalTypeNode = void 0; const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$3(), exports3); const ts$1 = ts; function isOptionalTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.OptionalType; } exports3.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node2) { return node2.kind === ts$1.SyntaxKind.RestType; } exports3.isRestTypeNode = isRestTypeNode; function isSyntheticExpression(node2) { return node2.kind === ts$1.SyntaxKind.SyntheticExpression; } exports3.isSyntheticExpression = isSyntheticExpression; })(node$2); return node$2; } var hasRequiredNode$1; function requireNode$1() { if (hasRequiredNode$1) return node$3; hasRequiredNode$1 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); exports3.isBigIntLiteral = void 0; const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$2(), exports3); const ts$1 = ts; function isBigIntLiteral(node2) { return node2.kind === ts$1.SyntaxKind.BigIntLiteral; } exports3.isBigIntLiteral = isBigIntLiteral; })(node$3); return node$3; } var hasRequiredNode; function requireNode() { if (hasRequiredNode) return node$4; hasRequiredNode = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$1(), exports3); })(node$4); return node$4; } var type$5 = {}; var type$4 = {}; var type$3 = {}; var type$2 = {}; var type$1 = {}; var hasRequiredType$5; function requireType$5() { if (hasRequiredType$5) return type$1; hasRequiredType$5 = 1; Object.defineProperty(type$1, "__esModule", { value: true }); type$1.isUniqueESSymbolType = type$1.isUnionType = type$1.isUnionOrIntersectionType = type$1.isTypeVariable = type$1.isTypeReference = type$1.isTypeParameter = type$1.isSubstitutionType = type$1.isObjectType = type$1.isLiteralType = type$1.isIntersectionType = type$1.isInterfaceType = type$1.isInstantiableType = type$1.isIndexedAccessype = type$1.isIndexedAccessType = type$1.isGenericType = type$1.isEnumType = type$1.isConditionalType = void 0; const ts$1 = ts; function isConditionalType(type2) { return (type2.flags & ts$1.TypeFlags.Conditional) !== 0; } type$1.isConditionalType = isConditionalType; function isEnumType(type2) { return (type2.flags & ts$1.TypeFlags.Enum) !== 0; } type$1.isEnumType = isEnumType; function isGenericType(type2) { return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.ClassOrInterface) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.Reference) !== 0; } type$1.isGenericType = isGenericType; function isIndexedAccessType(type2) { return (type2.flags & ts$1.TypeFlags.IndexedAccess) !== 0; } type$1.isIndexedAccessType = isIndexedAccessType; function isIndexedAccessype(type2) { return (type2.flags & ts$1.TypeFlags.Index) !== 0; } type$1.isIndexedAccessype = isIndexedAccessype; function isInstantiableType(type2) { return (type2.flags & ts$1.TypeFlags.Instantiable) !== 0; } type$1.isInstantiableType = isInstantiableType; function isInterfaceType(type2) { return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.ClassOrInterface) !== 0; } type$1.isInterfaceType = isInterfaceType; function isIntersectionType(type2) { return (type2.flags & ts$1.TypeFlags.Intersection) !== 0; } type$1.isIntersectionType = isIntersectionType; function isLiteralType(type2) { return (type2.flags & (ts$1.TypeFlags.StringOrNumberLiteral | ts$1.TypeFlags.BigIntLiteral)) !== 0; } type$1.isLiteralType = isLiteralType; function isObjectType(type2) { return (type2.flags & ts$1.TypeFlags.Object) !== 0; } type$1.isObjectType = isObjectType; function isSubstitutionType(type2) { return (type2.flags & ts$1.TypeFlags.Substitution) !== 0; } type$1.isSubstitutionType = isSubstitutionType; function isTypeParameter(type2) { return (type2.flags & ts$1.TypeFlags.TypeParameter) !== 0; } type$1.isTypeParameter = isTypeParameter; function isTypeReference(type2) { return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.Reference) !== 0; } type$1.isTypeReference = isTypeReference; function isTypeVariable(type2) { return (type2.flags & ts$1.TypeFlags.TypeVariable) !== 0; } type$1.isTypeVariable = isTypeVariable; function isUnionOrIntersectionType(type2) { return (type2.flags & ts$1.TypeFlags.UnionOrIntersection) !== 0; } type$1.isUnionOrIntersectionType = isUnionOrIntersectionType; function isUnionType(type2) { return (type2.flags & ts$1.TypeFlags.Union) !== 0; } type$1.isUnionType = isUnionType; function isUniqueESSymbolType(type2) { return (type2.flags & ts$1.TypeFlags.UniqueESSymbol) !== 0; } type$1.isUniqueESSymbolType = isUniqueESSymbolType; return type$1; } var hasRequiredType$4; function requireType$4() { if (hasRequiredType$4) return type$2; hasRequiredType$4 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireType$5(), exports3); })(type$2); return type$2; } var hasRequiredType$3; function requireType$3() { if (hasRequiredType$3) return type$3; hasRequiredType$3 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); exports3.isTupleTypeReference = exports3.isTupleType = void 0; const tslib_1 = require$$0; tslib_1.__exportStar(requireType$4(), exports3); const ts$1 = ts; const type_1 = requireType$4(); function isTupleType(type2) { return (type2.flags & ts$1.TypeFlags.Object && type2.objectFlags & ts$1.ObjectFlags.Tuple) !== 0; } exports3.isTupleType = isTupleType; function isTupleTypeReference(type2) { return type_1.isTypeReference(type2) && isTupleType(type2.target); } exports3.isTupleTypeReference = isTupleTypeReference; })(type$3); return type$3; } var hasRequiredType$2; function requireType$2() { if (hasRequiredType$2) return type$4; hasRequiredType$2 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireType$3(), exports3); })(type$4); return type$4; } var hasRequiredType$1; function requireType$1() { if (hasRequiredType$1) return type$5; hasRequiredType$1 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireType$2(), exports3); })(type$5); return type$5; } var hasRequiredTypeguard; function requireTypeguard() { if (hasRequiredTypeguard) return typeguard; hasRequiredTypeguard = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireNode(), exports3); tslib_1.__exportStar(requireType$1(), exports3); })(typeguard); return typeguard; } var util$2 = {}; var util$1 = {}; var _3_2 = {}; var hasRequired_3_2; function require_3_2() { if (hasRequired_3_2) return _3_2; hasRequired_3_2 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireNode$1(), exports3); tslib_1.__exportStar(requireType$2(), exports3); })(_3_2); return _3_2; } var type = {}; var hasRequiredType; function requireType() { if (hasRequiredType) return type; hasRequiredType = 1; Object.defineProperty(type, "__esModule", { value: true }); type.getBaseClassMemberOfClassElement = type.getIteratorYieldResultFromIteratorResult = type.getInstanceTypeOfClassLikeDeclaration = type.getConstructorTypeOfClassLikeDeclaration = type.getSymbolOfClassLikeDeclaration = type.getPropertyNameFromType = type.symbolHasReadonlyDeclaration = type.isPropertyReadonlyInType = type.getWellKnownSymbolPropertyOfType = type.getPropertyOfType = type.isBooleanLiteralType = type.isFalsyType = type.isThenableType = type.someTypePart = type.intersectionTypeParts = type.unionTypeParts = type.getCallSignaturesOfType = type.isTypeAssignableToString = type.isTypeAssignableToNumber = type.isOptionalChainingUndefinedMarkerType = type.removeOptionalChainingUndefinedMarkerType = type.removeOptionalityFromType = type.isEmptyObjectType = void 0; const ts$1 = ts; const type_1 = requireType$1(); const util_1 = requireUtil$1(); const node_1 = requireNode(); function isEmptyObjectType(type2) { if (type_1.isObjectType(type2) && type2.objectFlags & ts$1.ObjectFlags.Anonymous && type2.getProperties().length === 0 && type2.getCallSignatures().length === 0 && type2.getConstructSignatures().length === 0 && type2.getStringIndexType() === void 0 && type2.getNumberIndexType() === void 0) { const baseTypes = type2.getBaseTypes(); return baseTypes === void 0 || baseTypes.every(isEmptyObjectType); } return false; } type.isEmptyObjectType = isEmptyObjectType; function removeOptionalityFromType(checker, type2) { if (!containsTypeWithFlag(type2, ts$1.TypeFlags.Undefined)) return type2; const allowsNull = containsTypeWithFlag(type2, ts$1.TypeFlags.Null); type2 = checker.getNonNullableType(type2); return allowsNull ? checker.getNullableType(type2, ts$1.TypeFlags.Null) : type2; } type.removeOptionalityFromType = removeOptionalityFromType; function containsTypeWithFlag(type2, flag) { for (const t of unionTypeParts(type2)) if (util_1.isTypeFlagSet(t, flag)) return true; return false; } function removeOptionalChainingUndefinedMarkerType(checker, type2) { if (!type_1.isUnionType(type2)) return isOptionalChainingUndefinedMarkerType(checker, type2) ? type2.getNonNullableType() : type2; let flags = 0; let containsUndefinedMarker = false; for (const t of type2.types) { if (isOptionalChainingUndefinedMarkerType(checker, t)) { containsUndefinedMarker = true; } else { flags |= t.flags; } } return containsUndefinedMarker ? checker.getNullableType(type2.getNonNullableType(), flags) : type2; } type.removeOptionalChainingUndefinedMarkerType = removeOptionalChainingUndefinedMarkerType; function isOptionalChainingUndefinedMarkerType(checker, t) { return util_1.isTypeFlagSet(t, ts$1.TypeFlags.Undefined) && checker.getNullableType(t.getNonNullableType(), ts$1.TypeFlags.Undefined) !== t; } type.isOptionalChainingUndefinedMarkerType = isOptionalChainingUndefinedMarkerType; function isTypeAssignableToNumber(checker, type2) { return isTypeAssignableTo(checker, type2, ts$1.TypeFlags.NumberLike); } type.isTypeAssignableToNumber = isTypeAssignableToNumber; function isTypeAssignableToString(checker, type2) { return isTypeAssignableTo(checker, type2, ts$1.TypeFlags.StringLike); } type.isTypeAssignableToString = isTypeAssignableToString; function isTypeAssignableTo(checker, type2, flags) { flags |= ts$1.TypeFlags.Any; let typeParametersSeen; return function check(t) { if (type_1.isTypeParameter(t) && t.symbol !== void 0 && t.symbol.declarations !== void 0) { if (typeParametersSeen === void 0) { typeParametersSeen = /* @__PURE__ */ new Set([t]); } else if (!typeParametersSeen.has(t)) { typeParametersSeen.add(t); } else { return false; } const declaration = t.symbol.declarations[0]; if (declaration.constraint === void 0) return true; return check(checker.getTypeFromTypeNode(declaration.constraint)); } if (type_1.isUnionType(t)) return t.types.every(check); if (type_1.isIntersectionType(t)) return t.types.some(check); return util_1.isTypeFlagSet(t, flags); }(type2); } function getCallSignaturesOfType(type2) { if (type_1.isUnionType(type2)) { const signatures = []; for (const t of type2.types) signatures.push(...getCallSignaturesOfType(t)); return signatures; } if (type_1.isIntersectionType(type2)) { let signatures; for (const t of type2.types) { const sig = getCallSignaturesOfType(t); if (sig.length !== 0) { if (signatures !== void 0) return []; signatures = sig; } } return signatures === void 0 ? [] : signatures; } return type2.getCallSignatures(); } type.getCallSignaturesOfType = getCallSignaturesOfType; function unionTypeParts(type2) { return type_1.isUnionType(type2) ? type2.types : [type2]; } type.unionTypeParts = unionTypeParts; function intersectionTypeParts(type2) { return type_1.isIntersectionType(type2) ? type2.types : [type2]; } type.intersectionTypeParts = intersectionTypeParts; function someTypePart(type2, predicate, cb) { return predicate(type2) ? type2.types.some(cb) : cb(type2); } type.someTypePart = someTypePart; function isThenableType(checker, node2, type2 = checker.getTypeAtLocation(node2)) { for (const ty of unionTypeParts(checker.getApparentType(type2))) { const then = ty.getProperty("then"); if (then === void 0) continue; const thenType = checker.getTypeOfSymbolAtLocation(then, node2); for (const t of unionTypeParts(thenType)) for (const signature of t.getCallSignatures()) if (signature.parameters.length !== 0 && isCallback2(checker, signature.parameters[0], node2)) return true; } return false; } type.isThenableType = isThenableType; function isCallback2(checker, param, node2) { let type2 = checker.getApparentType(checker.getTypeOfSymbolAtLocation(param, node2)); if (param.valueDeclaration.dotDotDotToken) { type2 = type2.getNumberIndexType(); if (type2 === void 0) return false; } for (const t of unionTypeParts(type2)) if (t.getCallSignatures().length !== 0) return true; return false; } function isFalsyType(type2) { if (type2.flags & (ts$1.TypeFlags.Undefined | ts$1.TypeFlags.Null | ts$1.TypeFlags.Void)) return true; if (type_1.isLiteralType(type2)) return !type2.value; return isBooleanLiteralType(type2, false); } type.isFalsyType = isFalsyType; function isBooleanLiteralType(type2, literal) { return util_1.isTypeFlagSet(type2, ts$1.TypeFlags.BooleanLiteral) && type2.intrinsicName === (literal ? "true" : "false"); } type.isBooleanLiteralType = isBooleanLiteralType; function getPropertyOfType(type2, name) { if (!name.startsWith("__")) return type2.getProperty(name); return type2.getProperties().find((s) => s.escapedName === name); } type.getPropertyOfType = getPropertyOfType; function getWellKnownSymbolPropertyOfType(type2, wellKnownSymbolName, checker) { const prefix = "__@" + wellKnownSymbolName; for (const prop of type2.getProperties()) { if (!prop.name.startsWith(prefix)) continue; const globalSymbol = checker.getApparentType(checker.getTypeAtLocation(prop.valueDeclaration.name.expression)).symbol; if (prop.escapedName === getPropertyNameOfWellKnownSymbol(checker, globalSymbol, wellKnownSymbolName)) return prop; } return; } type.getWellKnownSymbolPropertyOfType = getWellKnownSymbolPropertyOfType; function getPropertyNameOfWellKnownSymbol(checker, symbolConstructor, symbolName) { const knownSymbol = symbolConstructor && checker.getTypeOfSymbolAtLocation(symbolConstructor, symbolConstructor.valueDeclaration).getProperty(symbolName); const knownSymbolType = knownSymbol && checker.getTypeOfSymbolAtLocation(knownSymbol, knownSymbol.valueDeclaration); if (knownSymbolType && type_1.isUniqueESSymbolType(knownSymbolType)) return knownSymbolType.escapedName; return "__@" + symbolName; } function isPropertyReadonlyInType(type2, name, checker) { let seenProperty = false; let seenReadonlySignature = false; for (const t of unionTypeParts(type2)) { if (getPropertyOfType(t, name) === void 0) { const index = (util_1.isNumericPropertyName(name) ? checker.getIndexInfoOfType(t, ts$1.IndexKind.Number) : void 0) || checker.getIndexInfoOfType(t, ts$1.IndexKind.String); if (index !== void 0 && index.isReadonly) { if (seenProperty) return true; seenReadonlySignature = true; } } else if (seenReadonlySignature || isReadonlyPropertyIntersection(t, name, checker)) { return true; } else { seenProperty = true; } } return false; } type.isPropertyReadonlyInType = isPropertyReadonlyInType; function isReadonlyPropertyIntersection(type2, name, checker) { return someTypePart(type2, type_1.isIntersectionType, (t) => { const prop = getPropertyOfType(t, name); if (prop === void 0) return false; if (prop.flags & ts$1.SymbolFlags.Transient) { if (/^(?:[1-9]\d*|0)$/.test(name) && type_1.isTupleTypeReference(t)) return t.target.readonly; switch (isReadonlyPropertyFromMappedType(t, name, checker)) { case true: return true; case false: return false; } } return ( // members of namespace import util_1.isSymbolFlagSet(prop, ts$1.SymbolFlags.ValueModule) || // we unwrapped every mapped type, now we can check the actual declarations symbolHasReadonlyDeclaration(prop, checker) ); }); } function isReadonlyPropertyFromMappedType(type2, name, checker) { if (!type_1.isObjectType(type2) || !util_1.isObjectFlagSet(type2, ts$1.ObjectFlags.Mapped)) return; const declaration = type2.symbol.declarations[0]; if (declaration.readonlyToken !== void 0 && !/^__@[^@]+$/.test(name)) return declaration.readonlyToken.kind !== ts$1.SyntaxKind.MinusToken; return isPropertyReadonlyInType(type2.modifiersType, name, checker); } function symbolHasReadonlyDeclaration(symbol, checker) { return (symbol.flags & ts$1.SymbolFlags.Accessor) === ts$1.SymbolFlags.GetAccessor || symbol.declarations !== void 0 && symbol.declarations.some((node2) => util_1.isModifierFlagSet(node2, ts$1.ModifierFlags.Readonly) || node_1.isVariableDeclaration(node2) && util_1.isNodeFlagSet(node2.parent, ts$1.NodeFlags.Const) || node_1.isCallExpression(node2) && util_1.isReadonlyAssignmentDeclaration(node2, checker) || node_1.isEnumMember(node2) || (node_1.isPropertyAssignment(node2) || node_1.isShorthandPropertyAssignment(node2)) && util_1.isInConstContext(node2.parent)); } type.symbolHasReadonlyDeclaration = symbolHasReadonlyDeclaration; function getPropertyNameFromType(type2) { if (type2.flags & (ts$1.TypeFlags.StringLiteral | ts$1.TypeFlags.NumberLiteral)) { const value = String(type2.value); return { displayName: value, symbolName: ts$1.escapeLeadingUnderscores(value) }; } if (type_1.isUniqueESSymbolType(type2)) return { displayName: `[${type2.symbol ? `${isKnownSymbol(type2.symbol) ? "Symbol." : ""}${type2.symbol.name}` : type2.escapedName.replace(/^__@|@\d+$/g, "")}]`, symbolName: type2.escapedName }; } type.getPropertyNameFromType = getPropertyNameFromType; function isKnownSymbol(symbol) { return util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Property) && symbol.valueDeclaration !== void 0 && node_1.isInterfaceDeclaration(symbol.valueDeclaration.parent) && symbol.valueDeclaration.parent.name.text === "SymbolConstructor" && isGlobalDeclaration(symbol.valueDeclaration.parent); } function isGlobalDeclaration(node2) { return util_1.isNodeFlagSet(node2.parent, ts$1.NodeFlags.GlobalAugmentation) || node_1.isSourceFile(node2.parent) && !ts$1.isExternalModule(node2.parent); } function getSymbolOfClassLikeDeclaration(node2, checker) { var _a; return checker.getSymbolAtLocation((_a = node2.name) !== null && _a !== void 0 ? _a : util_1.getChildOfKind(node2, ts$1.SyntaxKind.ClassKeyword)); } type.getSymbolOfClassLikeDeclaration = getSymbolOfClassLikeDeclaration; function getConstructorTypeOfClassLikeDeclaration(node2, checker) { return node2.kind === ts$1.SyntaxKind.ClassExpression ? checker.getTypeAtLocation(node2) : checker.getTypeOfSymbolAtLocation(getSymbolOfClassLikeDeclaration(node2, checker), node2); } type.getConstructorTypeOfClassLikeDeclaration = getConstructorTypeOfClassLikeDeclaration; function getInstanceTypeOfClassLikeDeclaration(node2, checker) { return node2.kind === ts$1.SyntaxKind.ClassDeclaration ? checker.getTypeAtLocation(node2) : checker.getDeclaredTypeOfSymbol(getSymbolOfClassLikeDeclaration(node2, checker)); } type.getInstanceTypeOfClassLikeDeclaration = getInstanceTypeOfClassLikeDeclaration; function getIteratorYieldResultFromIteratorResult(type2, node2, checker) { return type_1.isUnionType(type2) && type2.types.find((t) => { const done = t.getProperty("done"); return done !== void 0 && isBooleanLiteralType(removeOptionalityFromType(checker, checker.getTypeOfSymbolAtLocation(done, node2)), false); }) || type2; } type.getIteratorYieldResultFromIteratorResult = getIteratorYieldResultFromIteratorResult; function getBaseClassMemberOfClassElement(node2, checker) { if (!node_1.isClassLikeDeclaration(node2.parent)) return; const base = util_1.getBaseOfClassLikeExpression(node2.parent); if (base === void 0) return; const name = util_1.getSingleLateBoundPropertyNameOfPropertyName(node2.name, checker); if (name === void 0) return; const baseType = checker.getTypeAtLocation(util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.StaticKeyword) ? base.expression : base); return getPropertyOfType(baseType, name.symbolName); } type.getBaseClassMemberOfClassElement = getBaseClassMemberOfClassElement; return type; } var hasRequiredUtil$1; function requireUtil$1() { if (hasRequiredUtil$1) return util$1; hasRequiredUtil$1 = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); exports3.isValidIdentifier = exports3.getLineBreakStyle = exports3.getLineRanges = exports3.forEachComment = exports3.forEachTokenWithTrivia = exports3.forEachToken = exports3.isFunctionWithBody = exports3.hasOwnThisReference = exports3.isBlockScopeBoundary = exports3.isFunctionScopeBoundary = exports3.isTypeScopeBoundary = exports3.isScopeBoundary = exports3.ScopeBoundarySelector = exports3.ScopeBoundary = exports3.isInSingleStatementContext = exports3.isBlockScopedDeclarationStatement = exports3.isBlockScopedVariableDeclaration = exports3.isBlockScopedVariableDeclarationList = exports3.getVariableDeclarationKind = exports3.VariableDeclarationKind = exports3.forEachDeclaredVariable = exports3.forEachDestructuringIdentifier = exports3.getPropertyName = exports3.getWrappedNodeAtPosition = exports3.getAstNodeAtPosition = exports3.commentText = exports3.isPositionInComment = exports3.getCommentAtPosition = exports3.getTokenAtPosition = exports3.getNextToken = exports3.getPreviousToken = exports3.getNextStatement = exports3.getPreviousStatement = exports3.isModifierFlagSet = exports3.isObjectFlagSet = exports3.isSymbolFlagSet = exports3.isTypeFlagSet = exports3.isNodeFlagSet = exports3.hasAccessModifier = exports3.isParameterProperty = exports3.hasModifier = exports3.getModifier = exports3.isThisParameter = exports3.isKeywordKind = exports3.isJsDocKind = exports3.isTypeNodeKind = exports3.isAssignmentKind = exports3.isNodeKind = exports3.isTokenKind = exports3.getChildOfKind = void 0; exports3.getBaseOfClassLikeExpression = exports3.hasExhaustiveCaseClauses = exports3.formatPseudoBigInt = exports3.unwrapParentheses = exports3.getSingleLateBoundPropertyNameOfPropertyName = exports3.getLateBoundPropertyNamesOfPropertyName = exports3.getLateBoundPropertyNames = exports3.getPropertyNameOfWellKnownSymbol = exports3.isWellKnownSymbolLiterally = exports3.isBindableObjectDefinePropertyCall = exports3.isReadonlyAssignmentDeclaration = exports3.isInConstContext = exports3.isConstAssertion = exports3.getTsCheckDirective = exports3.getCheckJsDirective = exports3.isAmbientModule = exports3.isCompilerOptionEnabled = exports3.isStrictCompilerOptionEnabled = exports3.getIIFE = exports3.isAmbientModuleBlock = exports3.isStatementInAmbientContext = exports3.findImportLikeNodes = exports3.findImports = exports3.ImportKind = exports3.parseJsDocOfNode = exports3.getJsDoc = exports3.canHaveJsDoc = exports3.isReassignmentTarget = exports3.getAccessKind = exports3.AccessKind = exports3.isExpressionValueUsed = exports3.getDeclarationOfBindingElement = exports3.hasSideEffects = exports3.SideEffectOptions = exports3.isSameLine = exports3.isNumericPropertyName = exports3.isValidJsxIdentifier = exports3.isValidNumericLiteral = exports3.isValidPropertyName = exports3.isValidPropertyAccess = void 0; const ts$1 = ts; const node_1 = requireNode(); const _3_2_1 = require_3_2(); const type_1 = requireType(); function getChildOfKind(node2, kind, sourceFile) { for (const child of node2.getChildren(sourceFile)) if (child.kind === kind) return child; } exports3.getChildOfKind = getChildOfKind; function isTokenKind(kind) { return kind >= ts$1.SyntaxKind.FirstToken && kind <= ts$1.SyntaxKind.LastToken; } exports3.isTokenKind = isTokenKind; function isNodeKind(kind) { return kind >= ts$1.SyntaxKind.FirstNode; } exports3.isNodeKind = isNodeKind; function isAssignmentKind(kind) { return kind >= ts$1.SyntaxKind.FirstAssignment && kind <= ts$1.SyntaxKind.LastAssignment; } exports3.isAssignmentKind = isAssignmentKind; function isTypeNodeKind(kind) { return kind >= ts$1.SyntaxKind.FirstTypeNode && kind <= ts$1.SyntaxKind.LastTypeNode; } exports3.isTypeNodeKind = isTypeNodeKind; function isJsDocKind(kind) { return kind >= ts$1.SyntaxKind.FirstJSDocNode && kind <= ts$1.SyntaxKind.LastJSDocNode; } exports3.isJsDocKind = isJsDocKind; function isKeywordKind(kind) { return kind >= ts$1.SyntaxKind.FirstKeyword && kind <= ts$1.SyntaxKind.LastKeyword; } exports3.isKeywordKind = isKeywordKind; function isThisParameter(parameter) { return parameter.name.kind === ts$1.SyntaxKind.Identifier && parameter.name.originalKeywordKind === ts$1.SyntaxKind.ThisKeyword; } exports3.isThisParameter = isThisParameter; function getModifier(node2, kind) { if (node2.modifiers !== void 0) { for (const modifier of node2.modifiers) if (modifier.kind === kind) return modifier; } } exports3.getModifier = getModifier; function hasModifier(modifiers, ...kinds) { if (modifiers === void 0) return false; for (const modifier of modifiers) if (kinds.includes(modifier.kind)) return true; return false; } exports3.hasModifier = hasModifier; function isParameterProperty(node2) { return hasModifier(node2.modifiers, ts$1.SyntaxKind.PublicKeyword, ts$1.SyntaxKind.ProtectedKeyword, ts$1.SyntaxKind.PrivateKeyword, ts$1.SyntaxKind.ReadonlyKeyword); } exports3.isParameterProperty = isParameterProperty; function hasAccessModifier(node2) { return isModifierFlagSet(node2, ts$1.ModifierFlags.AccessibilityModifier); } exports3.hasAccessModifier = hasAccessModifier; function isFlagSet(obj, flag) { return (obj.flags & flag) !== 0; } exports3.isNodeFlagSet = isFlagSet; exports3.isTypeFlagSet = isFlagSet; exports3.isSymbolFlagSet = isFlagSet; function isObjectFlagSet(objectType, flag) { return (objectType.objectFlags & flag) !== 0; } exports3.isObjectFlagSet = isObjectFlagSet; function isModifierFlagSet(node2, flag) { return (ts$1.getCombinedModifierFlags(node2) & flag) !== 0; } exports3.isModifierFlagSet = isModifierFlagSet; function getPreviousStatement(statement) { const parent = statement.parent; if (node_1.isBlockLike(parent)) { const index = parent.statements.indexOf(statement); if (index > 0) return parent.statements[index - 1]; } } exports3.getPreviousStatement = getPreviousStatement; function getNextStatement(statement) { const parent = statement.parent; if (node_1.isBlockLike(parent)) { const index = parent.statements.indexOf(statement); if (index < parent.statements.length) return parent.statements[index + 1]; } } exports3.getNextStatement = getNextStatement; function getPreviousToken(node2, sourceFile) { const { pos } = node2; if (pos === 0) return; do node2 = node2.parent; while (node2.pos === pos); return getTokenAtPositionWorker(node2, pos - 1, sourceFile !== null && sourceFile !== void 0 ? sourceFile : node2.getSourceFile(), false); } exports3.getPreviousToken = getPreviousToken; function getNextToken(node2, sourceFile) { if (node2.kind === ts$1.SyntaxKind.SourceFile || node2.kind === ts$1.SyntaxKind.EndOfFileToken) return; const end = node2.end; node2 = node2.parent; while (node2.end === end) { if (node2.parent === void 0) return node2.endOfFileToken; node2 = node2.parent; } return getTokenAtPositionWorker(node2, end, sourceFile !== null && sourceFile !== void 0 ? sourceFile : node2.getSourceFile(), false); } exports3.getNextToken = getNextToken; function getTokenAtPosition(parent, pos, sourceFile, allowJsDoc) { if (pos < parent.pos || pos >= parent.end) return; if (isTokenKind(parent.kind)) return parent; return getTokenAtPositionWorker(parent, pos, sourceFile !== null && sourceFile !== void 0 ? sourceFile : parent.getSourceFile(), allowJsDoc === true); } exports3.getTokenAtPosition = getTokenAtPosition; function getTokenAtPositionWorker(node2, pos, sourceFile, allowJsDoc) { if (!allowJsDoc) { node2 = getAstNodeAtPosition(node2, pos); if (isTokenKind(node2.kind)) return node2; } outer: while (true) { for (const child of node2.getChildren(sourceFile)) { if (child.end > pos && (allowJsDoc || child.kind !== ts$1.SyntaxKind.JSDocComment)) { if (isTokenKind(child.kind)) return child; node2 = child; continue outer; } } return; } } function getCommentAtPosition(sourceFile, pos, parent = sourceFile) { const token = getTokenAtPosition(parent, pos, sourceFile); if (token === void 0 || token.kind === ts$1.SyntaxKind.JsxText || pos >= token.end - (ts$1.tokenToString(token.kind) || "").length) return; const startPos = token.pos === 0 ? (ts$1.getShebang(sourceFile.text) || "").length : token.pos; return startPos !== 0 && ts$1.forEachTrailingCommentRange(sourceFile.text, startPos, commentAtPositionCallback, pos) || ts$1.forEachLeadingCommentRange(sourceFile.text, startPos, commentAtPositionCallback, pos); } exports3.getCommentAtPosition = getCommentAtPosition; function commentAtPositionCallback(pos, end, kind, _nl, at) { return at >= pos && at < end ? { pos, end, kind } : void 0; } function isPositionInComment(sourceFile, pos, parent) { return getCommentAtPosition(sourceFile, pos, parent) !== void 0; } exports3.isPositionInComment = isPositionInComment; function commentText(sourceText, comment) { return sourceText.substring(comment.pos + 2, comment.kind === ts$1.SyntaxKind.SingleLineCommentTrivia ? comment.end : comment.end - 2); } exports3.commentText = commentText; function getAstNodeAtPosition(node2, pos) { if (node2.pos > pos || node2.end <= pos) return; while (isNodeKind(node2.kind)) { const nested = ts$1.forEachChild(node2, (child) => child.pos <= pos && child.end > pos ? child : void 0); if (nested === void 0) break; node2 = nested; } return node2; } exports3.getAstNodeAtPosition = getAstNodeAtPosition; function getWrappedNodeAtPosition(wrap, pos) { if (wrap.node.pos > pos || wrap.node.end <= pos) return; outer: while (true) { for (const child of wrap.children) { if (child.node.pos > pos) return wrap; if (child.node.end > pos) { wrap = child; continue outer; } } return wrap; } } exports3.getWrappedNodeAtPosition = getWrappedNodeAtPosition; function getPropertyName(propertyName) { if (propertyName.kind === ts$1.SyntaxKind.ComputedPropertyName) { const expression = unwrapParentheses(propertyName.expression); if (node_1.isPrefixUnaryExpression(expression)) { let negate = false; switch (expression.operator) { case ts$1.SyntaxKind.MinusToken: negate = true; case ts$1.SyntaxKind.PlusToken: return node_1.isNumericLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text}` : _3_2_1.isBigIntLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text.slice(0, -1)}` : void 0; default: return; } } if (_3_2_1.isBigIntLiteral(expression)) return expression.text.slice(0, -1); if (node_1.isNumericOrStringLikeLiteral(expression)) return expression.text; return; } return propertyName.kind === ts$1.SyntaxKind.PrivateIdentifier ? void 0 : propertyName.text; } exports3.getPropertyName = getPropertyName; function forEachDestructuringIdentifier(pattern, fn) { for (const element of pattern.elements) { if (element.kind !== ts$1.SyntaxKind.BindingElement) continue; let result; if (element.name.kind === ts$1.SyntaxKind.Identifier) { result = fn(element); } else { result = forEachDestructuringIdentifier(element.name, fn); } if (result) return result; } } exports3.forEachDestructuringIdentifier = forEachDestructuringIdentifier; function forEachDeclaredVariable(declarationList, cb) { for (const declaration of declarationList.declarations) { let result; if (declaration.name.kind === ts$1.SyntaxKind.Identifier) { result = cb(declaration); } else { result = forEachDestructuringIdentifier(declaration.name, cb); } if (result) return result; } } exports3.forEachDeclaredVariable = forEachDeclaredVariable; (function(VariableDeclarationKind) { VariableDeclarationKind[VariableDeclarationKind["Var"] = 0] = "Var"; VariableDeclarationKind[VariableDeclarationKind["Let"] = 1] = "Let"; VariableDeclarationKind[VariableDeclarationKind["Const"] = 2] = "Const"; })(exports3.VariableDeclarationKind || (exports3.VariableDeclarationKind = {})); function getVariableDeclarationKind(declarationList) { if (declarationList.flags & ts$1.NodeFlags.Let) return 1; if (declarationList.flags & ts$1.NodeFlags.Const) return 2; return 0; } exports3.getVariableDeclarationKind = getVariableDeclarationKind; function isBlockScopedVariableDeclarationList(declarationList) { return (declarationList.flags & ts$1.NodeFlags.BlockScoped) !== 0; } exports3.isBlockScopedVariableDeclarationList = isBlockScopedVariableDeclarationList; function isBlockScopedVariableDeclaration(declaration) { const parent = declaration.parent; return parent.kind === ts$1.SyntaxKind.CatchClause || isBlockScopedVariableDeclarationList(parent); } exports3.isBlockScopedVariableDeclaration = isBlockScopedVariableDeclaration; function isBlockScopedDeclarationStatement(statement) { switch (statement.kind) { case ts$1.SyntaxKind.VariableStatement: return isBlockScopedVariableDeclarationList(statement.declarationList); case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.EnumDeclaration: case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: return true; default: return false; } } exports3.isBlockScopedDeclarationStatement = isBlockScopedDeclarationStatement; function isInSingleStatementContext(statement) { switch (statement.parent.kind) { case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.ForInStatement: case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.WhileStatement: case ts$1.SyntaxKind.DoStatement: case ts$1.SyntaxKind.IfStatement: case ts$1.SyntaxKind.WithStatement: case ts$1.SyntaxKind.LabeledStatement: return true; default: return false; } } exports3.isInSingleStatementContext = isInSingleStatementContext; (function(ScopeBoundary) { ScopeBoundary[ScopeBoundary["None"] = 0] = "None"; ScopeBoundary[ScopeBoundary["Function"] = 1] = "Function"; ScopeBoundary[ScopeBoundary["Block"] = 2] = "Block"; ScopeBoundary[ScopeBoundary["Type"] = 4] = "Type"; ScopeBoundary[ScopeBoundary["ConditionalType"] = 8] = "ConditionalType"; })(exports3.ScopeBoundary || (exports3.ScopeBoundary = {})); (function(ScopeBoundarySelector) { ScopeBoundarySelector[ScopeBoundarySelector["Function"] = 1] = "Function"; ScopeBoundarySelector[ScopeBoundarySelector["Block"] = 3] = "Block"; ScopeBoundarySelector[ScopeBoundarySelector["Type"] = 7] = "Type"; ScopeBoundarySelector[ScopeBoundarySelector["InferType"] = 8] = "InferType"; })(exports3.ScopeBoundarySelector || (exports3.ScopeBoundarySelector = {})); function isScopeBoundary(node2) { return isFunctionScopeBoundary(node2) || isBlockScopeBoundary(node2) || isTypeScopeBoundary(node2); } exports3.isScopeBoundary = isScopeBoundary; function isTypeScopeBoundary(node2) { switch (node2.kind) { case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: case ts$1.SyntaxKind.MappedType: return 4; case ts$1.SyntaxKind.ConditionalType: return 8; default: return 0; } } exports3.isTypeScopeBoundary = isTypeScopeBoundary; function isFunctionScopeBoundary(node2) { switch (node2.kind) { case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.Constructor: case ts$1.SyntaxKind.ModuleDeclaration: case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.EnumDeclaration: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.MethodSignature: case ts$1.SyntaxKind.CallSignature: case ts$1.SyntaxKind.ConstructSignature: case ts$1.SyntaxKind.ConstructorType: case ts$1.SyntaxKind.FunctionType: return 1; case ts$1.SyntaxKind.SourceFile: return ts$1.isExternalModule(node2) ? 1 : 0; default: return 0; } } exports3.isFunctionScopeBoundary = isFunctionScopeBoundary; function isBlockScopeBoundary(node2) { switch (node2.kind) { case ts$1.SyntaxKind.Block: const parent = node2.parent; return parent.kind !== ts$1.SyntaxKind.CatchClause && // blocks inside SourceFile are block scope boundaries (parent.kind === ts$1.SyntaxKind.SourceFile || // blocks that are direct children of a function scope boundary are no scope boundary // for example the FunctionBlock is part of the function scope of the containing function !isFunctionScopeBoundary(parent)) ? 2 : 0; case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.ForInStatement: case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.CaseBlock: case ts$1.SyntaxKind.CatchClause: case ts$1.SyntaxKind.WithStatement: return 2; default: return 0; } } exports3.isBlockScopeBoundary = isBlockScopeBoundary; function hasOwnThisReference(node2) { switch (node2.kind) { case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.FunctionExpression: return true; case ts$1.SyntaxKind.FunctionDeclaration: return node2.body !== void 0; case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: return node2.parent.kind === ts$1.SyntaxKind.ObjectLiteralExpression; default: return false; } } exports3.hasOwnThisReference = hasOwnThisReference; function isFunctionWithBody(node2) { switch (node2.kind) { case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.Constructor: return node2.body !== void 0; case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.ArrowFunction: return true; default: return false; } } exports3.isFunctionWithBody = isFunctionWithBody; function forEachToken(node2, cb, sourceFile = node2.getSourceFile()) { const queue = []; while (true) { if (isTokenKind(node2.kind)) { cb(node2); } else if (node2.kind !== ts$1.SyntaxKind.JSDocComment) { const children = node2.getChildren(sourceFile); if (children.length === 1) { node2 = children[0]; continue; } for (let i = children.length - 1; i >= 0; --i) queue.push(children[i]); } if (queue.length === 0) break; node2 = queue.pop(); } } exports3.forEachToken = forEachToken; function forEachTokenWithTrivia(node2, cb, sourceFile = node2.getSourceFile()) { const fullText = sourceFile.text; const scanner = ts$1.createScanner(sourceFile.languageVersion, false, sourceFile.languageVariant, fullText); return forEachToken(node2, (token) => { const tokenStart = token.kind === ts$1.SyntaxKind.JsxText || token.pos === token.end ? token.pos : token.getStart(sourceFile); if (tokenStart !== token.pos) { scanner.setTextPos(token.pos); let kind = scanner.scan(); let pos = scanner.getTokenPos(); while (pos < tokenStart) { const textPos = scanner.getTextPos(); cb(fullText, kind, { pos, end: textPos }, token.parent); if (textPos === tokenStart) break; kind = scanner.scan(); pos = scanner.getTokenPos(); } } return cb(fullText, token.kind, { end: token.end, pos: tokenStart }, token.parent); }, sourceFile); } exports3.forEachTokenWithTrivia = forEachTokenWithTrivia; function forEachComment(node2, cb, sourceFile = node2.getSourceFile()) { const fullText = sourceFile.text; const notJsx = sourceFile.languageVariant !== ts$1.LanguageVariant.JSX; return forEachToken(node2, (token) => { if (token.pos === token.end) return; if (token.kind !== ts$1.SyntaxKind.JsxText) ts$1.forEachLeadingCommentRange( fullText, // skip shebang at position 0 token.pos === 0 ? (ts$1.getShebang(fullText) || "").length : token.pos, commentCallback ); if (notJsx || canHaveTrailingTrivia(token)) return ts$1.forEachTrailingCommentRange(fullText, token.end, commentCallback); }, sourceFile); function commentCallback(pos, end, kind) { cb(fullText, { pos, end, kind }); } } exports3.forEachComment = forEachComment; function canHaveTrailingTrivia(token) { switch (token.kind) { case ts$1.SyntaxKind.CloseBraceToken: return token.parent.kind !== ts$1.SyntaxKind.JsxExpression || !isJsxElementOrFragment(token.parent.parent); case ts$1.SyntaxKind.GreaterThanToken: switch (token.parent.kind) { case ts$1.SyntaxKind.JsxOpeningElement: return token.end !== token.parent.end; case ts$1.SyntaxKind.JsxOpeningFragment: return false; case ts$1.SyntaxKind.JsxSelfClosingElement: return token.end !== token.parent.end || // if end is not equal, this is part of the type arguments list !isJsxElementOrFragment(token.parent.parent); case ts$1.SyntaxKind.JsxClosingElement: case ts$1.SyntaxKind.JsxClosingFragment: return !isJsxElementOrFragment(token.parent.parent.parent); } } return true; } function isJsxElementOrFragment(node2) { return node2.kind === ts$1.SyntaxKind.JsxElement || node2.kind === ts$1.SyntaxKind.JsxFragment; } function getLineRanges(sourceFile) { const lineStarts = sourceFile.getLineStarts(); const result = []; const length = lineStarts.length; const sourceText = sourceFile.text; let pos = 0; for (let i = 1; i < length; ++i) { const end = lineStarts[i]; let lineEnd = end; for (; lineEnd > pos; --lineEnd) if (!ts$1.isLineBreak(sourceText.charCodeAt(lineEnd - 1))) break; result.push({ pos, end, contentLength: lineEnd - pos }); pos = end; } result.push({ pos, end: sourceFile.end, contentLength: sourceFile.end - pos }); return result; } exports3.getLineRanges = getLineRanges; function getLineBreakStyle(sourceFile) { const lineStarts = sourceFile.getLineStarts(); return lineStarts.length === 1 || lineStarts[1] < 2 || sourceFile.text[lineStarts[1] - 2] !== "\r" ? "\n" : "\r\n"; } exports3.getLineBreakStyle = getLineBreakStyle; let cachedScanner; function scanToken(text, languageVersion) { if (cachedScanner === void 0) { cachedScanner = ts$1.createScanner(languageVersion, false, void 0, text); } else { cachedScanner.setScriptTarget(languageVersion); cachedScanner.setText(text); } cachedScanner.scan(); return cachedScanner; } function isValidIdentifier(text, languageVersion = ts$1.ScriptTarget.Latest) { const scan = scanToken(text, languageVersion); return scan.isIdentifier() && scan.getTextPos() === text.length && scan.getTokenPos() === 0; } exports3.isValidIdentifier = isValidIdentifier; function charSize(ch) { return ch >= 65536 ? 2 : 1; } function isValidPropertyAccess(text, languageVersion = ts$1.ScriptTarget.Latest) { if (text.length === 0) return false; let ch = text.codePointAt(0); if (!ts$1.isIdentifierStart(ch, languageVersion)) return false; for (let i = charSize(ch); i < text.length; i += charSize(ch)) { ch = text.codePointAt(i); if (!ts$1.isIdentifierPart(ch, languageVersion)) return false; } return true; } exports3.isValidPropertyAccess = isValidPropertyAccess; function isValidPropertyName(text, languageVersion = ts$1.ScriptTarget.Latest) { if (isValidPropertyAccess(text, languageVersion)) return true; const scan = scanToken(text, languageVersion); return scan.getTextPos() === text.length && scan.getToken() === ts$1.SyntaxKind.NumericLiteral && scan.getTokenValue() === text; } exports3.isValidPropertyName = isValidPropertyName; function isValidNumericLiteral(text, languageVersion = ts$1.ScriptTarget.Latest) { const scan = scanToken(text, languageVersion); return scan.getToken() === ts$1.SyntaxKind.NumericLiteral && scan.getTextPos() === text.length && scan.getTokenPos() === 0; } exports3.isValidNumericLiteral = isValidNumericLiteral; function isValidJsxIdentifier(text, languageVersion = ts$1.ScriptTarget.Latest) { if (text.length === 0) return false; let seenNamespaceSeparator = false; let ch = text.codePointAt(0); if (!ts$1.isIdentifierStart(ch, languageVersion)) return false; for (let i = charSize(ch); i < text.length; i += charSize(ch)) { ch = text.codePointAt(i); if (!ts$1.isIdentifierPart(ch, languageVersion) && ch !== 45) { if (!seenNamespaceSeparator && ch === 58 && i + charSize(ch) !== text.length) { seenNamespaceSeparator = true; } else { return false; } } } return true; } exports3.isValidJsxIdentifier = isValidJsxIdentifier; function isNumericPropertyName(name) { return String(+name) === name; } exports3.isNumericPropertyName = isNumericPropertyName; function isSameLine(sourceFile, pos1, pos2) { return ts$1.getLineAndCharacterOfPosition(sourceFile, pos1).line === ts$1.getLineAndCharacterOfPosition(sourceFile, pos2).line; } exports3.isSameLine = isSameLine; (function(SideEffectOptions) { SideEffectOptions[SideEffectOptions["None"] = 0] = "None"; SideEffectOptions[SideEffectOptions["TaggedTemplate"] = 1] = "TaggedTemplate"; SideEffectOptions[SideEffectOptions["Constructor"] = 2] = "Constructor"; SideEffectOptions[SideEffectOptions["JsxElement"] = 4] = "JsxElement"; })(exports3.SideEffectOptions || (exports3.SideEffectOptions = {})); function hasSideEffects(node2, options) { var _a, _b; const queue = []; while (true) { switch (node2.kind) { case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.PostfixUnaryExpression: case ts$1.SyntaxKind.AwaitExpression: case ts$1.SyntaxKind.YieldExpression: case ts$1.SyntaxKind.DeleteExpression: return true; case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.AsExpression: case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.NonNullExpression: case ts$1.SyntaxKind.VoidExpression: case ts$1.SyntaxKind.TypeOfExpression: case ts$1.SyntaxKind.PropertyAccessExpression: case ts$1.SyntaxKind.SpreadElement: case ts$1.SyntaxKind.PartiallyEmittedExpression: node2 = node2.expression; continue; case ts$1.SyntaxKind.BinaryExpression: if (isAssignmentKind(node2.operatorToken.kind)) return true; queue.push(node2.right); node2 = node2.left; continue; case ts$1.SyntaxKind.PrefixUnaryExpression: switch (node2.operator) { case ts$1.SyntaxKind.PlusPlusToken: case ts$1.SyntaxKind.MinusMinusToken: return true; default: node2 = node2.operand; continue; } case ts$1.SyntaxKind.ElementAccessExpression: if (node2.argumentExpression !== void 0) queue.push(node2.argumentExpression); node2 = node2.expression; continue; case ts$1.SyntaxKind.ConditionalExpression: queue.push(node2.whenTrue, node2.whenFalse); node2 = node2.condition; continue; case ts$1.SyntaxKind.NewExpression: if (options & 2) return true; if (node2.arguments !== void 0) queue.push(...node2.arguments); node2 = node2.expression; continue; case ts$1.SyntaxKind.TaggedTemplateExpression: if (options & 1) return true; queue.push(node2.tag); node2 = node2.template; if (node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral) break; case ts$1.SyntaxKind.TemplateExpression: for (const child of node2.templateSpans) queue.push(child.expression); break; case ts$1.SyntaxKind.ClassExpression: { if (node2.decorators !== void 0) return true; for (const child of node2.members) { if (child.decorators !== void 0) return true; if (!hasModifier(child.modifiers, ts$1.SyntaxKind.DeclareKeyword)) { if (((_a = child.name) === null || _a === void 0 ? void 0 : _a.kind) === ts$1.SyntaxKind.ComputedPropertyName) queue.push(child.name.expression); if (node_1.isMethodDeclaration(child)) { for (const p of child.parameters) if (p.decorators !== void 0) return true; } else if (node_1.isPropertyDeclaration(child) && child.initializer !== void 0 && hasModifier(child.modifiers, ts$1.SyntaxKind.StaticKeyword)) { queue.push(child.initializer); } } } const base = getBaseOfClassLikeExpression(node2); if (base === void 0) break; node2 = base.expression; continue; } case ts$1.SyntaxKind.ArrayLiteralExpression: queue.push(...node2.elements); break; case ts$1.SyntaxKind.ObjectLiteralExpression: for (const child of node2.properties) { if (((_b = child.name) === null || _b === void 0 ? void 0 : _b.kind) === ts$1.SyntaxKind.ComputedPropertyName) queue.push(child.name.expression); switch (child.kind) { case ts$1.SyntaxKind.PropertyAssignment: queue.push(child.initializer); break; case ts$1.SyntaxKind.SpreadAssignment: queue.push(child.expression); } } break; case ts$1.SyntaxKind.JsxExpression: if (node2.expression === void 0) break; node2 = node2.expression; continue; case ts$1.SyntaxKind.JsxElement: case ts$1.SyntaxKind.JsxFragment: for (const child of node2.children) if (child.kind !== ts$1.SyntaxKind.JsxText) queue.push(child); if (node2.kind === ts$1.SyntaxKind.JsxFragment) break; node2 = node2.openingElement; case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.JsxOpeningElement: if (options & 4) return true; for (const child of node2.attributes.properties) { if (child.kind === ts$1.SyntaxKind.JsxSpreadAttribute) { queue.push(child.expression); } else if (child.initializer !== void 0) { queue.push(child.initializer); } } break; case ts$1.SyntaxKind.CommaListExpression: queue.push(...node2.elements); } if (queue.length === 0) return false; node2 = queue.pop(); } } exports3.hasSideEffects = hasSideEffects; function getDeclarationOfBindingElement(node2) { let parent = node2.parent.parent; while (parent.kind === ts$1.SyntaxKind.BindingElement) parent = parent.parent.parent; return parent; } exports3.getDeclarationOfBindingElement = getDeclarationOfBindingElement; function isExpressionValueUsed(node2) { while (true) { const parent = node2.parent; switch (parent.kind) { case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.NewExpression: case ts$1.SyntaxKind.ElementAccessExpression: case ts$1.SyntaxKind.WhileStatement: case ts$1.SyntaxKind.DoStatement: case ts$1.SyntaxKind.WithStatement: case ts$1.SyntaxKind.ThrowStatement: case ts$1.SyntaxKind.ReturnStatement: case ts$1.SyntaxKind.JsxExpression: case ts$1.SyntaxKind.JsxSpreadAttribute: case ts$1.SyntaxKind.JsxElement: case ts$1.SyntaxKind.JsxFragment: case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.ComputedPropertyName: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.ExportSpecifier: case ts$1.SyntaxKind.ExportAssignment: case ts$1.SyntaxKind.ImportDeclaration: case ts$1.SyntaxKind.ExternalModuleReference: case ts$1.SyntaxKind.Decorator: case ts$1.SyntaxKind.TaggedTemplateExpression: case ts$1.SyntaxKind.TemplateSpan: case ts$1.SyntaxKind.ExpressionWithTypeArguments: case ts$1.SyntaxKind.TypeOfExpression: case ts$1.SyntaxKind.AwaitExpression: case ts$1.SyntaxKind.YieldExpression: case ts$1.SyntaxKind.LiteralType: case ts$1.SyntaxKind.JsxAttributes: case ts$1.SyntaxKind.JsxOpeningElement: case ts$1.SyntaxKind.JsxClosingElement: case ts$1.SyntaxKind.IfStatement: case ts$1.SyntaxKind.CaseClause: case ts$1.SyntaxKind.SwitchStatement: return true; case ts$1.SyntaxKind.PropertyAccessExpression: return parent.expression === node2; case ts$1.SyntaxKind.QualifiedName: return parent.left === node2; case ts$1.SyntaxKind.ShorthandPropertyAssignment: return parent.objectAssignmentInitializer === node2 || !isInDestructuringAssignment(parent); case ts$1.SyntaxKind.PropertyAssignment: return parent.initializer === node2 && !isInDestructuringAssignment(parent); case ts$1.SyntaxKind.SpreadAssignment: case ts$1.SyntaxKind.SpreadElement: case ts$1.SyntaxKind.ArrayLiteralExpression: return !isInDestructuringAssignment(parent); case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.AsExpression: case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.PostfixUnaryExpression: case ts$1.SyntaxKind.PrefixUnaryExpression: case ts$1.SyntaxKind.NonNullExpression: node2 = parent; continue; case ts$1.SyntaxKind.ForStatement: return parent.condition === node2; case ts$1.SyntaxKind.ForInStatement: case ts$1.SyntaxKind.ForOfStatement: return parent.expression === node2; case ts$1.SyntaxKind.ConditionalExpression: if (parent.condition === node2) return true; node2 = parent; break; case ts$1.SyntaxKind.PropertyDeclaration: case ts$1.SyntaxKind.BindingElement: case ts$1.SyntaxKind.VariableDeclaration: case ts$1.SyntaxKind.Parameter: case ts$1.SyntaxKind.EnumMember: return parent.initializer === node2; case ts$1.SyntaxKind.ImportEqualsDeclaration: return parent.moduleReference === node2; case ts$1.SyntaxKind.CommaListExpression: if (parent.elements[parent.elements.length - 1] !== node2) return false; node2 = parent; break; case ts$1.SyntaxKind.BinaryExpression: if (parent.right === node2) { if (parent.operatorToken.kind === ts$1.SyntaxKind.CommaToken) { node2 = parent; break; } return true; } switch (parent.operatorToken.kind) { case ts$1.SyntaxKind.CommaToken: case ts$1.SyntaxKind.EqualsToken: return false; case ts$1.SyntaxKind.EqualsEqualsEqualsToken: case ts$1.SyntaxKind.EqualsEqualsToken: case ts$1.SyntaxKind.ExclamationEqualsEqualsToken: case ts$1.SyntaxKind.ExclamationEqualsToken: case ts$1.SyntaxKind.InstanceOfKeyword: case ts$1.SyntaxKind.PlusToken: case ts$1.SyntaxKind.MinusToken: case ts$1.SyntaxKind.AsteriskToken: case ts$1.SyntaxKind.SlashToken: case ts$1.SyntaxKind.PercentToken: case ts$1.SyntaxKind.AsteriskAsteriskToken: case ts$1.SyntaxKind.GreaterThanToken: case ts$1.SyntaxKind.GreaterThanGreaterThanToken: case ts$1.SyntaxKind.GreaterThanGreaterThanGreaterThanToken: case ts$1.SyntaxKind.GreaterThanEqualsToken: case ts$1.SyntaxKind.LessThanToken: case ts$1.SyntaxKind.LessThanLessThanToken: case ts$1.SyntaxKind.LessThanEqualsToken: case ts$1.SyntaxKind.AmpersandToken: case ts$1.SyntaxKind.BarToken: case ts$1.SyntaxKind.CaretToken: case ts$1.SyntaxKind.BarBarToken: case ts$1.SyntaxKind.AmpersandAmpersandToken: case ts$1.SyntaxKind.QuestionQuestionToken: case ts$1.SyntaxKind.InKeyword: case ts$1.SyntaxKind.QuestionQuestionEqualsToken: case ts$1.SyntaxKind.AmpersandAmpersandEqualsToken: case ts$1.SyntaxKind.BarBarEqualsToken: return true; default: node2 = parent; } break; default: return false; } } } exports3.isExpressionValueUsed = isExpressionValueUsed; function isInDestructuringAssignment(node2) { switch (node2.kind) { case ts$1.SyntaxKind.ShorthandPropertyAssignment: if (node2.objectAssignmentInitializer !== void 0) return true; case ts$1.SyntaxKind.PropertyAssignment: case ts$1.SyntaxKind.SpreadAssignment: node2 = node2.parent; break; case ts$1.SyntaxKind.SpreadElement: if (node2.parent.kind !== ts$1.SyntaxKind.ArrayLiteralExpression) return false; node2 = node2.parent; } while (true) { switch (node2.parent.kind) { case ts$1.SyntaxKind.BinaryExpression: return node2.parent.left === node2 && node2.parent.operatorToken.kind === ts$1.SyntaxKind.EqualsToken; case ts$1.SyntaxKind.ForOfStatement: return node2.parent.initializer === node2; case ts$1.SyntaxKind.ArrayLiteralExpression: case ts$1.SyntaxKind.ObjectLiteralExpression: node2 = node2.parent; break; case ts$1.SyntaxKind.SpreadAssignment: case ts$1.SyntaxKind.PropertyAssignment: node2 = node2.parent.parent; break; case ts$1.SyntaxKind.SpreadElement: if (node2.parent.parent.kind !== ts$1.SyntaxKind.ArrayLiteralExpression) return false; node2 = node2.parent.parent; break; default: return false; } } } (function(AccessKind) { AccessKind[AccessKind["None"] = 0] = "None"; AccessKind[AccessKind["Read"] = 1] = "Read"; AccessKind[AccessKind["Write"] = 2] = "Write"; AccessKind[AccessKind["Delete"] = 4] = "Delete"; AccessKind[AccessKind["ReadWrite"] = 3] = "ReadWrite"; AccessKind[AccessKind["Modification"] = 6] = "Modification"; })(exports3.AccessKind || (exports3.AccessKind = {})); function getAccessKind(node2) { const parent = node2.parent; switch (parent.kind) { case ts$1.SyntaxKind.DeleteExpression: return 4; case ts$1.SyntaxKind.PostfixUnaryExpression: return 3; case ts$1.SyntaxKind.PrefixUnaryExpression: return parent.operator === ts$1.SyntaxKind.PlusPlusToken || parent.operator === ts$1.SyntaxKind.MinusMinusToken ? 3 : 1; case ts$1.SyntaxKind.BinaryExpression: return parent.right === node2 ? 1 : !isAssignmentKind(parent.operatorToken.kind) ? 1 : parent.operatorToken.kind === ts$1.SyntaxKind.EqualsToken ? 2 : 3; case ts$1.SyntaxKind.ShorthandPropertyAssignment: return parent.objectAssignmentInitializer === node2 ? 1 : isInDestructuringAssignment(parent) ? 2 : 1; case ts$1.SyntaxKind.PropertyAssignment: return parent.name === node2 ? 0 : isInDestructuringAssignment(parent) ? 2 : 1; case ts$1.SyntaxKind.ArrayLiteralExpression: case ts$1.SyntaxKind.SpreadElement: case ts$1.SyntaxKind.SpreadAssignment: return isInDestructuringAssignment(parent) ? 2 : 1; case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.NonNullExpression: case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.AsExpression: return getAccessKind(parent); case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.ForInStatement: return parent.initializer === node2 ? 2 : 1; case ts$1.SyntaxKind.ExpressionWithTypeArguments: return parent.parent.token === ts$1.SyntaxKind.ExtendsKeyword && parent.parent.parent.kind !== ts$1.SyntaxKind.InterfaceDeclaration ? 1 : 0; case ts$1.SyntaxKind.ComputedPropertyName: case ts$1.SyntaxKind.ExpressionStatement: case ts$1.SyntaxKind.TypeOfExpression: case ts$1.SyntaxKind.ElementAccessExpression: case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.IfStatement: case ts$1.SyntaxKind.DoStatement: case ts$1.SyntaxKind.WhileStatement: case ts$1.SyntaxKind.SwitchStatement: case ts$1.SyntaxKind.WithStatement: case ts$1.SyntaxKind.ThrowStatement: case ts$1.SyntaxKind.CallExpression: case ts$1.SyntaxKind.NewExpression: case ts$1.SyntaxKind.TaggedTemplateExpression: case ts$1.SyntaxKind.JsxExpression: case ts$1.SyntaxKind.Decorator: case ts$1.SyntaxKind.TemplateSpan: case ts$1.SyntaxKind.JsxOpeningElement: case ts$1.SyntaxKind.JsxSelfClosingElement: case ts$1.SyntaxKind.JsxSpreadAttribute: case ts$1.SyntaxKind.VoidExpression: case ts$1.SyntaxKind.ReturnStatement: case ts$1.SyntaxKind.AwaitExpression: case ts$1.SyntaxKind.YieldExpression: case ts$1.SyntaxKind.ConditionalExpression: case ts$1.SyntaxKind.CaseClause: case ts$1.SyntaxKind.JsxElement: return 1; case ts$1.SyntaxKind.ArrowFunction: return parent.body === node2 ? 1 : 2; case ts$1.SyntaxKind.PropertyDeclaration: case ts$1.SyntaxKind.VariableDeclaration: case ts$1.SyntaxKind.Parameter: case ts$1.SyntaxKind.EnumMember: case ts$1.SyntaxKind.BindingElement: case ts$1.SyntaxKind.JsxAttribute: return parent.initializer === node2 ? 1 : 0; case ts$1.SyntaxKind.PropertyAccessExpression: return parent.expression === node2 ? 1 : 0; case ts$1.SyntaxKind.ExportAssignment: return parent.isExportEquals ? 1 : 0; } return 0; } exports3.getAccessKind = getAccessKind; function isReassignmentTarget(node2) { return (getAccessKind(node2) & 2) !== 0; } exports3.isReassignmentTarget = isReassignmentTarget; function canHaveJsDoc(node2) { const kind = node2.kind; switch (kind) { case ts$1.SyntaxKind.Parameter: case ts$1.SyntaxKind.CallSignature: case ts$1.SyntaxKind.ConstructSignature: case ts$1.SyntaxKind.MethodSignature: case ts$1.SyntaxKind.PropertySignature: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.SpreadAssignment: case ts$1.SyntaxKind.ShorthandPropertyAssignment: case ts$1.SyntaxKind.PropertyAssignment: case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.LabeledStatement: case ts$1.SyntaxKind.ExpressionStatement: case ts$1.SyntaxKind.VariableStatement: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.Constructor: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.PropertyDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: case ts$1.SyntaxKind.EnumMember: case ts$1.SyntaxKind.EnumDeclaration: case ts$1.SyntaxKind.ModuleDeclaration: case ts$1.SyntaxKind.ImportEqualsDeclaration: case ts$1.SyntaxKind.ImportDeclaration: case ts$1.SyntaxKind.NamespaceExportDeclaration: case ts$1.SyntaxKind.ExportAssignment: case ts$1.SyntaxKind.IndexSignature: case ts$1.SyntaxKind.FunctionType: case ts$1.SyntaxKind.ConstructorType: case ts$1.SyntaxKind.JSDocFunctionType: case ts$1.SyntaxKind.ExportDeclaration: case ts$1.SyntaxKind.NamedTupleMember: case ts$1.SyntaxKind.EndOfFileToken: return true; default: return false; } } exports3.canHaveJsDoc = canHaveJsDoc; function getJsDoc(node2, sourceFile) { const result = []; for (const child of node2.getChildren(sourceFile)) { if (!node_1.isJsDoc(child)) break; result.push(child); } return result; } exports3.getJsDoc = getJsDoc; function parseJsDocOfNode(node2, considerTrailingComments, sourceFile = node2.getSourceFile()) { if (canHaveJsDoc(node2) && node2.kind !== ts$1.SyntaxKind.EndOfFileToken) { const result = getJsDoc(node2, sourceFile); if (result.length !== 0 || !considerTrailingComments) return result; } return parseJsDocWorker(node2, node2.getStart(sourceFile), sourceFile, considerTrailingComments); } exports3.parseJsDocOfNode = parseJsDocOfNode; function parseJsDocWorker(node2, nodeStart, sourceFile, considerTrailingComments) { const start = ts$1[considerTrailingComments && isSameLine(sourceFile, node2.pos, nodeStart) ? "forEachTrailingCommentRange" : "forEachLeadingCommentRange"]( sourceFile.text, node2.pos, // return object to make `0` a truthy value (pos, _end, kind) => kind === ts$1.SyntaxKind.MultiLineCommentTrivia && sourceFile.text[pos + 2] === "*" ? { pos } : void 0 ); if (start === void 0) return []; const startPos = start.pos; const text = sourceFile.text.slice(startPos, nodeStart); const newSourceFile = ts$1.createSourceFile("jsdoc.ts", `${text}var a;`, sourceFile.languageVersion); const result = getJsDoc(newSourceFile.statements[0], newSourceFile); for (const doc of result) updateNode(doc, node2); return result; function updateNode(n, parent) { n.pos += startPos; n.end += startPos; n.parent = parent; return ts$1.forEachChild(n, (child) => updateNode(child, n), (children) => { children.pos += startPos; children.end += startPos; for (const child of children) updateNode(child, n); }); } } (function(ImportKind) { ImportKind[ImportKind["ImportDeclaration"] = 1] = "ImportDeclaration"; ImportKind[ImportKind["ImportEquals"] = 2] = "ImportEquals"; ImportKind[ImportKind["ExportFrom"] = 4] = "ExportFrom"; ImportKind[ImportKind["DynamicImport"] = 8] = "DynamicImport"; ImportKind[ImportKind["Require"] = 16] = "Require"; ImportKind[ImportKind["ImportType"] = 32] = "ImportType"; ImportKind[ImportKind["All"] = 63] = "All"; ImportKind[ImportKind["AllImports"] = 59] = "AllImports"; ImportKind[ImportKind["AllStaticImports"] = 3] = "AllStaticImports"; ImportKind[ImportKind["AllImportExpressions"] = 24] = "AllImportExpressions"; ImportKind[ImportKind["AllRequireLike"] = 18] = "AllRequireLike"; ImportKind[ImportKind["AllNestedImports"] = 56] = "AllNestedImports"; ImportKind[ImportKind["AllTopLevelImports"] = 7] = "AllTopLevelImports"; })(exports3.ImportKind || (exports3.ImportKind = {})); function findImports(sourceFile, kinds, ignoreFileName = true) { const result = []; for (const node2 of findImportLikeNodes(sourceFile, kinds, ignoreFileName)) { switch (node2.kind) { case ts$1.SyntaxKind.ImportDeclaration: addIfTextualLiteral(node2.moduleSpecifier); break; case ts$1.SyntaxKind.ImportEqualsDeclaration: addIfTextualLiteral(node2.moduleReference.expression); break; case ts$1.SyntaxKind.ExportDeclaration: addIfTextualLiteral(node2.moduleSpecifier); break; case ts$1.SyntaxKind.CallExpression: addIfTextualLiteral(node2.arguments[0]); break; case ts$1.SyntaxKind.ImportType: if (node_1.isLiteralTypeNode(node2.argument)) addIfTextualLiteral(node2.argument.literal); break; default: throw new Error("unexpected node"); } } return result; function addIfTextualLiteral(node2) { if (node_1.isTextualLiteral(node2)) result.push(node2); } } exports3.findImports = findImports; function findImportLikeNodes(sourceFile, kinds, ignoreFileName = true) { return new ImportFinder(sourceFile, kinds, ignoreFileName).find(); } exports3.findImportLikeNodes = findImportLikeNodes; class ImportFinder { constructor(_sourceFile, _options, _ignoreFileName) { this._sourceFile = _sourceFile; this._options = _options; this._ignoreFileName = _ignoreFileName; this._result = []; } find() { if (this._sourceFile.isDeclarationFile) this._options &= ~24; if (this._options & 7) this._findImports(this._sourceFile.statements); if (this._options & 56) this._findNestedImports(); return this._result; } _findImports(statements) { for (const statement of statements) { if (node_1.isImportDeclaration(statement)) { if (this._options & 1) this._result.push(statement); } else if (node_1.isImportEqualsDeclaration(statement)) { if (this._options & 2 && statement.moduleReference.kind === ts$1.SyntaxKind.ExternalModuleReference) this._result.push(statement); } else if (node_1.isExportDeclaration(statement)) { if (statement.moduleSpecifier !== void 0 && this._options & 4) this._result.push(statement); } else if (node_1.isModuleDeclaration(statement)) { this._findImportsInModule(statement); } } } _findImportsInModule(declaration) { if (declaration.body === void 0) return; if (declaration.body.kind === ts$1.SyntaxKind.ModuleDeclaration) return this._findImportsInModule(declaration.body); this._findImports(declaration.body.statements); } _findNestedImports() { const isJavaScriptFile = this._ignoreFileName || (this._sourceFile.flags & ts$1.NodeFlags.JavaScriptFile) !== 0; let re; let includeJsDoc; if ((this._options & 56) === 16) { if (!isJavaScriptFile) return; re = /\brequire\s*[ 1) this._result.push(token.parent); } } else if (token.kind === ts$1.SyntaxKind.Identifier && token.end - "require".length === match2.index && token.parent.kind === ts$1.SyntaxKind.CallExpression && token.parent.expression === token && token.parent.arguments.length === 1) { this._result.push(token.parent); } } } } function isStatementInAmbientContext(node2) { while (node2.flags & ts$1.NodeFlags.NestedNamespace) node2 = node2.parent; return hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword) || isAmbientModuleBlock(node2.parent); } exports3.isStatementInAmbientContext = isStatementInAmbientContext; function isAmbientModuleBlock(node2) { while (node2.kind === ts$1.SyntaxKind.ModuleBlock) { do node2 = node2.parent; while (node2.flags & ts$1.NodeFlags.NestedNamespace); if (hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword)) return true; node2 = node2.parent; } return false; } exports3.isAmbientModuleBlock = isAmbientModuleBlock; function getIIFE(func) { let node2 = func.parent; while (node2.kind === ts$1.SyntaxKind.ParenthesizedExpression) node2 = node2.parent; return node_1.isCallExpression(node2) && func.end <= node2.expression.end ? node2 : void 0; } exports3.getIIFE = getIIFE; function isStrictCompilerOptionEnabled(options, option) { return (options.strict ? options[option] !== false : options[option] === true) && (option !== "strictPropertyInitialization" || isStrictCompilerOptionEnabled(options, "strictNullChecks")); } exports3.isStrictCompilerOptionEnabled = isStrictCompilerOptionEnabled; function isCompilerOptionEnabled(options, option) { switch (option) { case "stripInternal": case "declarationMap": case "emitDeclarationOnly": return options[option] === true && isCompilerOptionEnabled(options, "declaration"); case "declaration": return options.declaration || isCompilerOptionEnabled(options, "composite"); case "incremental": return options.incremental === void 0 ? isCompilerOptionEnabled(options, "composite") : options.incremental; case "skipDefaultLibCheck": return options.skipDefaultLibCheck || isCompilerOptionEnabled(options, "skipLibCheck"); case "suppressImplicitAnyIndexErrors": return options.suppressImplicitAnyIndexErrors === true && isCompilerOptionEnabled(options, "noImplicitAny"); case "allowSyntheticDefaultImports": return options.allowSyntheticDefaultImports !== void 0 ? options.allowSyntheticDefaultImports : isCompilerOptionEnabled(options, "esModuleInterop") || options.module === ts$1.ModuleKind.System; case "noUncheckedIndexedAccess": return options.noUncheckedIndexedAccess === true && isCompilerOptionEnabled(options, "strictNullChecks"); case "allowJs": return options.allowJs === void 0 ? isCompilerOptionEnabled(options, "checkJs") : options.allowJs; case "noImplicitAny": case "noImplicitThis": case "strictNullChecks": case "strictFunctionTypes": case "strictPropertyInitialization": case "alwaysStrict": case "strictBindCallApply": return isStrictCompilerOptionEnabled(options, option); } return options[option] === true; } exports3.isCompilerOptionEnabled = isCompilerOptionEnabled; function isAmbientModule(node2) { return node2.name.kind === ts$1.SyntaxKind.StringLiteral || (node2.flags & ts$1.NodeFlags.GlobalAugmentation) !== 0; } exports3.isAmbientModule = isAmbientModule; function getCheckJsDirective(source) { return getTsCheckDirective(source); } exports3.getCheckJsDirective = getCheckJsDirective; function getTsCheckDirective(source) { let directive; ts$1.forEachLeadingCommentRange(source, (ts$1.getShebang(source) || "").length, (pos, end, kind) => { if (kind === ts$1.SyntaxKind.SingleLineCommentTrivia) { const text = source.slice(pos, end); const match2 = /^\/{2,3}\s*@ts-(no)?check(?:\s|$)/i.exec(text); if (match2 !== null) directive = { pos, end, enabled: match2[1] === void 0 }; } }); return directive; } exports3.getTsCheckDirective = getTsCheckDirective; function isConstAssertion(node2) { return node_1.isTypeReferenceNode(node2.type) && node2.type.typeName.kind === ts$1.SyntaxKind.Identifier && node2.type.typeName.escapedText === "const"; } exports3.isConstAssertion = isConstAssertion; function isInConstContext(node2) { let current = node2; while (true) { const parent = current.parent; outer: switch (parent.kind) { case ts$1.SyntaxKind.TypeAssertionExpression: case ts$1.SyntaxKind.AsExpression: return isConstAssertion(parent); case ts$1.SyntaxKind.PrefixUnaryExpression: if (current.kind !== ts$1.SyntaxKind.NumericLiteral) return false; switch (parent.operator) { case ts$1.SyntaxKind.PlusToken: case ts$1.SyntaxKind.MinusToken: current = parent; break outer; default: return false; } case ts$1.SyntaxKind.PropertyAssignment: if (parent.initializer !== current) return false; current = parent.parent; break; case ts$1.SyntaxKind.ShorthandPropertyAssignment: current = parent.parent; break; case ts$1.SyntaxKind.ParenthesizedExpression: case ts$1.SyntaxKind.ArrayLiteralExpression: case ts$1.SyntaxKind.ObjectLiteralExpression: case ts$1.SyntaxKind.TemplateExpression: current = parent; break; default: return false; } } } exports3.isInConstContext = isInConstContext; function isReadonlyAssignmentDeclaration(node2, checker) { if (!isBindableObjectDefinePropertyCall(node2)) return false; const descriptorType = checker.getTypeAtLocation(node2.arguments[2]); if (descriptorType.getProperty("value") === void 0) return descriptorType.getProperty("set") === void 0; const writableProp = descriptorType.getProperty("writable"); if (writableProp === void 0) return false; const writableType = writableProp.valueDeclaration !== void 0 && node_1.isPropertyAssignment(writableProp.valueDeclaration) ? checker.getTypeAtLocation(writableProp.valueDeclaration.initializer) : checker.getTypeOfSymbolAtLocation(writableProp, node2.arguments[2]); return type_1.isBooleanLiteralType(writableType, false); } exports3.isReadonlyAssignmentDeclaration = isReadonlyAssignmentDeclaration; function isBindableObjectDefinePropertyCall(node2) { return node2.arguments.length === 3 && node_1.isEntityNameExpression(node2.arguments[0]) && node_1.isNumericOrStringLikeLiteral(node2.arguments[1]) && node_1.isPropertyAccessExpression(node2.expression) && node2.expression.name.escapedText === "defineProperty" && node_1.isIdentifier(node2.expression.expression) && node2.expression.expression.escapedText === "Object"; } exports3.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; function isWellKnownSymbolLiterally(node2) { return ts$1.isPropertyAccessExpression(node2) && ts$1.isIdentifier(node2.expression) && node2.expression.escapedText === "Symbol"; } exports3.isWellKnownSymbolLiterally = isWellKnownSymbolLiterally; function getPropertyNameOfWellKnownSymbol(node2) { return { displayName: `[Symbol.${node2.name.text}]`, symbolName: "__@" + node2.name.text }; } exports3.getPropertyNameOfWellKnownSymbol = getPropertyNameOfWellKnownSymbol; const isTsBefore43 = (([major, minor]) => major < "4" || major === "4" && minor < "3")(ts$1.versionMajorMinor.split(".")); function getLateBoundPropertyNames(node2, checker) { const result = { known: true, names: [] }; node2 = unwrapParentheses(node2); if (isTsBefore43 && isWellKnownSymbolLiterally(node2)) { result.names.push(getPropertyNameOfWellKnownSymbol(node2)); } else { const type2 = checker.getTypeAtLocation(node2); for (const key of type_1.unionTypeParts(checker.getBaseConstraintOfType(type2) || type2)) { const propertyName = type_1.getPropertyNameFromType(key); if (propertyName) { result.names.push(propertyName); } else { result.known = false; } } } return result; } exports3.getLateBoundPropertyNames = getLateBoundPropertyNames; function getLateBoundPropertyNamesOfPropertyName(node2, checker) { const staticName = getPropertyName(node2); return staticName !== void 0 ? { known: true, names: [{ displayName: staticName, symbolName: ts$1.escapeLeadingUnderscores(staticName) }] } : node2.kind === ts$1.SyntaxKind.PrivateIdentifier ? { known: true, names: [{ displayName: node2.text, symbolName: checker.getSymbolAtLocation(node2).escapedName }] } : getLateBoundPropertyNames(node2.expression, checker); } exports3.getLateBoundPropertyNamesOfPropertyName = getLateBoundPropertyNamesOfPropertyName; function getSingleLateBoundPropertyNameOfPropertyName(node2, checker) { const staticName = getPropertyName(node2); if (staticName !== void 0) return { displayName: staticName, symbolName: ts$1.escapeLeadingUnderscores(staticName) }; if (node2.kind === ts$1.SyntaxKind.PrivateIdentifier) return { displayName: node2.text, symbolName: checker.getSymbolAtLocation(node2).escapedName }; const { expression } = node2; return isTsBefore43 && isWellKnownSymbolLiterally(expression) ? getPropertyNameOfWellKnownSymbol(expression) : type_1.getPropertyNameFromType(checker.getTypeAtLocation(expression)); } exports3.getSingleLateBoundPropertyNameOfPropertyName = getSingleLateBoundPropertyNameOfPropertyName; function unwrapParentheses(node2) { while (node2.kind === ts$1.SyntaxKind.ParenthesizedExpression) node2 = node2.expression; return node2; } exports3.unwrapParentheses = unwrapParentheses; function formatPseudoBigInt(v) { return `${v.negative ? "-" : ""}${v.base10Value}n`; } exports3.formatPseudoBigInt = formatPseudoBigInt; function hasExhaustiveCaseClauses(node2, checker) { const caseClauses = node2.caseBlock.clauses.filter(node_1.isCaseClause); if (caseClauses.length === 0) return false; const typeParts = type_1.unionTypeParts(checker.getTypeAtLocation(node2.expression)); if (typeParts.length > caseClauses.length) return false; const types2 = new Set(typeParts.map(getPrimitiveLiteralFromType)); if (types2.has(void 0)) return false; const seen = /* @__PURE__ */ new Set(); for (const clause of caseClauses) { const expressionType = checker.getTypeAtLocation(clause.expression); if (exports3.isTypeFlagSet(expressionType, ts$1.TypeFlags.Never)) continue; const type2 = getPrimitiveLiteralFromType(expressionType); if (types2.has(type2)) { seen.add(type2); } else if (type2 !== "null" && type2 !== "undefined") { return false; } } return types2.size === seen.size; } exports3.hasExhaustiveCaseClauses = hasExhaustiveCaseClauses; function getPrimitiveLiteralFromType(t) { if (exports3.isTypeFlagSet(t, ts$1.TypeFlags.Null)) return "null"; if (exports3.isTypeFlagSet(t, ts$1.TypeFlags.Undefined)) return "undefined"; if (exports3.isTypeFlagSet(t, ts$1.TypeFlags.NumberLiteral)) return `${exports3.isTypeFlagSet(t, ts$1.TypeFlags.EnumLiteral) ? "enum:" : ""}${t.value}`; if (exports3.isTypeFlagSet(t, ts$1.TypeFlags.StringLiteral)) return `${exports3.isTypeFlagSet(t, ts$1.TypeFlags.EnumLiteral) ? "enum:" : ""}string:${t.value}`; if (exports3.isTypeFlagSet(t, ts$1.TypeFlags.BigIntLiteral)) return formatPseudoBigInt(t.value); if (_3_2_1.isUniqueESSymbolType(t)) return t.escapedName; if (type_1.isBooleanLiteralType(t, true)) return "true"; if (type_1.isBooleanLiteralType(t, false)) return "false"; } function getBaseOfClassLikeExpression(node2) { var _a; if (((_a = node2.heritageClauses) === null || _a === void 0 ? void 0 : _a[0].token) === ts$1.SyntaxKind.ExtendsKeyword) return node2.heritageClauses[0].types[0]; } exports3.getBaseOfClassLikeExpression = getBaseOfClassLikeExpression; })(util$1); return util$1; } var usage = {}; var hasRequiredUsage; function requireUsage() { if (hasRequiredUsage) return usage; hasRequiredUsage = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); exports3.collectVariableUsage = exports3.getDeclarationDomain = exports3.getUsageDomain = exports3.UsageDomain = exports3.DeclarationDomain = void 0; const util_1 = requireUtil$1(); const ts$1 = ts; (function(DeclarationDomain) { DeclarationDomain[DeclarationDomain["Namespace"] = 1] = "Namespace"; DeclarationDomain[DeclarationDomain["Type"] = 2] = "Type"; DeclarationDomain[DeclarationDomain["Value"] = 4] = "Value"; DeclarationDomain[DeclarationDomain["Import"] = 8] = "Import"; DeclarationDomain[DeclarationDomain["Any"] = 7] = "Any"; })(exports3.DeclarationDomain || (exports3.DeclarationDomain = {})); (function(UsageDomain) { UsageDomain[UsageDomain["Namespace"] = 1] = "Namespace"; UsageDomain[UsageDomain["Type"] = 2] = "Type"; UsageDomain[UsageDomain["Value"] = 4] = "Value"; UsageDomain[UsageDomain["ValueOrNamespace"] = 5] = "ValueOrNamespace"; UsageDomain[UsageDomain["Any"] = 7] = "Any"; UsageDomain[UsageDomain["TypeQuery"] = 8] = "TypeQuery"; })(exports3.UsageDomain || (exports3.UsageDomain = {})); function getUsageDomain(node2) { const parent = node2.parent; switch (parent.kind) { case ts$1.SyntaxKind.TypeReference: return node2.originalKeywordKind !== ts$1.SyntaxKind.ConstKeyword ? 2 : void 0; case ts$1.SyntaxKind.ExpressionWithTypeArguments: return parent.parent.token === ts$1.SyntaxKind.ImplementsKeyword || parent.parent.parent.kind === ts$1.SyntaxKind.InterfaceDeclaration ? 2 : 4; case ts$1.SyntaxKind.TypeQuery: return 5 | 8; case ts$1.SyntaxKind.QualifiedName: if (parent.left === node2) { if (getEntityNameParent(parent).kind === ts$1.SyntaxKind.TypeQuery) return 1 | 8; return 1; } break; case ts$1.SyntaxKind.ExportSpecifier: if (parent.propertyName === void 0 || parent.propertyName === node2) return 7; break; case ts$1.SyntaxKind.ExportAssignment: return 7; case ts$1.SyntaxKind.BindingElement: if (parent.initializer === node2) return 5; break; case ts$1.SyntaxKind.Parameter: case ts$1.SyntaxKind.EnumMember: case ts$1.SyntaxKind.PropertyDeclaration: case ts$1.SyntaxKind.VariableDeclaration: case ts$1.SyntaxKind.PropertyAssignment: case ts$1.SyntaxKind.PropertyAccessExpression: case ts$1.SyntaxKind.ImportEqualsDeclaration: if (parent.name !== node2) return 5; break; case ts$1.SyntaxKind.JsxAttribute: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.NamespaceImport: case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: case ts$1.SyntaxKind.ModuleDeclaration: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.EnumDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.LabeledStatement: case ts$1.SyntaxKind.BreakStatement: case ts$1.SyntaxKind.ContinueStatement: case ts$1.SyntaxKind.ImportClause: case ts$1.SyntaxKind.ImportSpecifier: case ts$1.SyntaxKind.TypePredicate: case ts$1.SyntaxKind.MethodSignature: case ts$1.SyntaxKind.PropertySignature: case ts$1.SyntaxKind.NamespaceExportDeclaration: case ts$1.SyntaxKind.NamespaceExport: case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: case ts$1.SyntaxKind.TypeParameter: case ts$1.SyntaxKind.NamedTupleMember: break; default: return 5; } } exports3.getUsageDomain = getUsageDomain; function getDeclarationDomain(node2) { switch (node2.parent.kind) { case ts$1.SyntaxKind.TypeParameter: case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: return 2; case ts$1.SyntaxKind.ClassDeclaration: case ts$1.SyntaxKind.ClassExpression: return 2 | 4; case ts$1.SyntaxKind.EnumDeclaration: return 7; case ts$1.SyntaxKind.NamespaceImport: case ts$1.SyntaxKind.ImportClause: return 7 | 8; case ts$1.SyntaxKind.ImportEqualsDeclaration: case ts$1.SyntaxKind.ImportSpecifier: return node2.parent.name === node2 ? 7 | 8 : void 0; case ts$1.SyntaxKind.ModuleDeclaration: return 1; case ts$1.SyntaxKind.Parameter: if (node2.parent.parent.kind === ts$1.SyntaxKind.IndexSignature || node2.originalKeywordKind === ts$1.SyntaxKind.ThisKeyword) return; case ts$1.SyntaxKind.BindingElement: case ts$1.SyntaxKind.VariableDeclaration: return node2.parent.name === node2 ? 4 : void 0; case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.FunctionExpression: return 4; } } exports3.getDeclarationDomain = getDeclarationDomain; function collectVariableUsage(sourceFile) { return new UsageWalker().getUsage(sourceFile); } exports3.collectVariableUsage = collectVariableUsage; class AbstractScope { constructor(_global) { this._global = _global; this._variables = /* @__PURE__ */ new Map(); this._uses = []; this._namespaceScopes = void 0; this._enumScopes = void 0; } addVariable(identifier, name, selector, exported, domain) { const variables = this.getDestinationScope(selector).getVariables(); const declaration = { domain, exported, declaration: name }; const variable = variables.get(identifier); if (variable === void 0) { variables.set(identifier, { domain, declarations: [declaration], uses: [] }); } else { variable.domain |= domain; variable.declarations.push(declaration); } } addUse(use) { this._uses.push(use); } getVariables() { return this._variables; } getFunctionScope() { return this; } end(cb) { if (this._namespaceScopes !== void 0) this._namespaceScopes.forEach((value) => value.finish(cb)); this._namespaceScopes = this._enumScopes = void 0; this._applyUses(); this._variables.forEach((variable) => { for (const declaration of variable.declarations) { const result = { declarations: [], domain: declaration.domain, exported: declaration.exported, inGlobalScope: this._global, uses: [] }; for (const other of variable.declarations) if (other.domain & declaration.domain) result.declarations.push(other.declaration); for (const use of variable.uses) if (use.domain & declaration.domain) result.uses.push(use); cb(result, declaration.declaration, this); } }); } // tslint:disable-next-line:prefer-function-over-method markExported(_name) { } // only relevant for the root scope createOrReuseNamespaceScope(name, _exported, ambient, hasExportStatement) { let scope; if (this._namespaceScopes === void 0) { this._namespaceScopes = /* @__PURE__ */ new Map(); } else { scope = this._namespaceScopes.get(name); } if (scope === void 0) { scope = new NamespaceScope(ambient, hasExportStatement, this); this._namespaceScopes.set(name, scope); } else { scope.refresh(ambient, hasExportStatement); } return scope; } createOrReuseEnumScope(name, _exported) { let scope; if (this._enumScopes === void 0) { this._enumScopes = /* @__PURE__ */ new Map(); } else { scope = this._enumScopes.get(name); } if (scope === void 0) { scope = new EnumScope(this); this._enumScopes.set(name, scope); } return scope; } _applyUses() { for (const use of this._uses) if (!this._applyUse(use)) this._addUseToParent(use); this._uses = []; } _applyUse(use, variables = this._variables) { const variable = variables.get(use.location.text); if (variable === void 0 || (variable.domain & use.domain) === 0) return false; variable.uses.push(use); return true; } _addUseToParent(_use) { } // tslint:disable-line:prefer-function-over-method } class RootScope extends AbstractScope { constructor(_exportAll, global2) { super(global2); this._exportAll = _exportAll; this._exports = void 0; this._innerScope = new NonRootScope( this, 1 /* Function */ ); } addVariable(identifier, name, selector, exported, domain) { if (domain & 8) return super.addVariable(identifier, name, selector, exported, domain); return this._innerScope.addVariable(identifier, name, selector, exported, domain); } addUse(use, origin) { if (origin === this._innerScope) return super.addUse(use); return this._innerScope.addUse(use); } markExported(id) { if (this._exports === void 0) { this._exports = [id.text]; } else { this._exports.push(id.text); } } end(cb) { this._innerScope.end((value, key) => { value.exported = value.exported || this._exportAll || this._exports !== void 0 && this._exports.includes(key.text); value.inGlobalScope = this._global; return cb(value, key, this); }); return super.end((value, key, scope) => { value.exported = value.exported || scope === this && this._exports !== void 0 && this._exports.includes(key.text); return cb(value, key, scope); }); } getDestinationScope() { return this; } } class NonRootScope extends AbstractScope { constructor(_parent, _boundary) { super(false); this._parent = _parent; this._boundary = _boundary; } _addUseToParent(use) { return this._parent.addUse(use, this); } getDestinationScope(selector) { return this._boundary & selector ? this : this._parent.getDestinationScope(selector); } } class EnumScope extends NonRootScope { constructor(parent) { super( parent, 1 /* Function */ ); } end() { this._applyUses(); } } class ConditionalTypeScope extends NonRootScope { constructor(parent) { super( parent, 8 /* ConditionalType */ ); this._state = 0; } updateState(newState) { this._state = newState; } addUse(use) { if (this._state === 2) return void this._uses.push(use); return this._parent.addUse(use, this); } } class FunctionScope extends NonRootScope { constructor(parent) { super( parent, 1 /* Function */ ); } beginBody() { this._applyUses(); } } class AbstractNamedExpressionScope extends NonRootScope { constructor(_name, _domain, parent) { super( parent, 1 /* Function */ ); this._name = _name; this._domain = _domain; } end(cb) { this._innerScope.end(cb); return cb({ declarations: [this._name], domain: this._domain, exported: false, uses: this._uses, inGlobalScope: false }, this._name, this); } addUse(use, source) { if (source !== this._innerScope) return this._innerScope.addUse(use); if (use.domain & this._domain && use.location.text === this._name.text) { this._uses.push(use); } else { return this._parent.addUse(use, this); } } getFunctionScope() { return this._innerScope; } getDestinationScope() { return this._innerScope; } } class FunctionExpressionScope extends AbstractNamedExpressionScope { constructor(name, parent) { super(name, 4, parent); this._innerScope = new FunctionScope(this); } beginBody() { return this._innerScope.beginBody(); } } class ClassExpressionScope extends AbstractNamedExpressionScope { constructor(name, parent) { super(name, 4 | 2, parent); this._innerScope = new NonRootScope( this, 1 /* Function */ ); } } class BlockScope extends NonRootScope { constructor(_functionScope, parent) { super( parent, 2 /* Block */ ); this._functionScope = _functionScope; } getFunctionScope() { return this._functionScope; } } function mapDeclaration(declaration) { return { declaration, exported: true, domain: getDeclarationDomain(declaration) }; } class NamespaceScope extends NonRootScope { constructor(_ambient, _hasExport, parent) { super( parent, 1 /* Function */ ); this._ambient = _ambient; this._hasExport = _hasExport; this._innerScope = new NonRootScope( this, 1 /* Function */ ); this._exports = void 0; } finish(cb) { return super.end(cb); } end(cb) { this._innerScope.end((variable, key, scope) => { if (scope !== this._innerScope || !variable.exported && (!this._ambient || this._exports !== void 0 && !this._exports.has(key.text))) return cb(variable, key, scope); const namespaceVar = this._variables.get(key.text); if (namespaceVar === void 0) { this._variables.set(key.text, { declarations: variable.declarations.map(mapDeclaration), domain: variable.domain, uses: [...variable.uses] }); } else { outer: for (const declaration of variable.declarations) { for (const existing of namespaceVar.declarations) if (existing.declaration === declaration) continue outer; namespaceVar.declarations.push(mapDeclaration(declaration)); } namespaceVar.domain |= variable.domain; for (const use of variable.uses) { if (namespaceVar.uses.includes(use)) continue; namespaceVar.uses.push(use); } } }); this._applyUses(); this._innerScope = new NonRootScope( this, 1 /* Function */ ); } createOrReuseNamespaceScope(name, exported, ambient, hasExportStatement) { if (!exported && (!this._ambient || this._hasExport)) return this._innerScope.createOrReuseNamespaceScope(name, exported, ambient || this._ambient, hasExportStatement); return super.createOrReuseNamespaceScope(name, exported, ambient || this._ambient, hasExportStatement); } createOrReuseEnumScope(name, exported) { if (!exported && (!this._ambient || this._hasExport)) return this._innerScope.createOrReuseEnumScope(name, exported); return super.createOrReuseEnumScope(name, exported); } addUse(use, source) { if (source !== this._innerScope) return this._innerScope.addUse(use); this._uses.push(use); } refresh(ambient, hasExport) { this._ambient = ambient; this._hasExport = hasExport; } markExported(name, _as) { if (this._exports === void 0) this._exports = /* @__PURE__ */ new Set(); this._exports.add(name.text); } getDestinationScope() { return this._innerScope; } } function getEntityNameParent(name) { let parent = name.parent; while (parent.kind === ts$1.SyntaxKind.QualifiedName) parent = parent.parent; return parent; } class UsageWalker { constructor() { this._result = /* @__PURE__ */ new Map(); } getUsage(sourceFile) { const variableCallback = (variable, key) => { this._result.set(key, variable); }; const isModule = ts$1.isExternalModule(sourceFile); this._scope = new RootScope(sourceFile.isDeclarationFile && isModule && !containsExportStatement(sourceFile), !isModule); const cb = (node2) => { if (util_1.isBlockScopeBoundary(node2)) return continueWithScope(node2, new BlockScope(this._scope.getFunctionScope(), this._scope), handleBlockScope); switch (node2.kind) { case ts$1.SyntaxKind.ClassExpression: return continueWithScope(node2, node2.name !== void 0 ? new ClassExpressionScope(node2.name, this._scope) : new NonRootScope( this._scope, 1 /* Function */ )); case ts$1.SyntaxKind.ClassDeclaration: this._handleDeclaration( node2, true, 4 | 2 /* Type */ ); return continueWithScope(node2, new NonRootScope( this._scope, 1 /* Function */ )); case ts$1.SyntaxKind.InterfaceDeclaration: case ts$1.SyntaxKind.TypeAliasDeclaration: this._handleDeclaration( node2, true, 2 /* Type */ ); return continueWithScope(node2, new NonRootScope( this._scope, 4 /* Type */ )); case ts$1.SyntaxKind.EnumDeclaration: this._handleDeclaration( node2, true, 7 /* Any */ ); return continueWithScope(node2, this._scope.createOrReuseEnumScope(node2.name.text, util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword))); case ts$1.SyntaxKind.ModuleDeclaration: return this._handleModule(node2, continueWithScope); case ts$1.SyntaxKind.MappedType: return continueWithScope(node2, new NonRootScope( this._scope, 4 /* Type */ )); case ts$1.SyntaxKind.FunctionExpression: case ts$1.SyntaxKind.ArrowFunction: case ts$1.SyntaxKind.Constructor: case ts$1.SyntaxKind.MethodDeclaration: case ts$1.SyntaxKind.FunctionDeclaration: case ts$1.SyntaxKind.GetAccessor: case ts$1.SyntaxKind.SetAccessor: case ts$1.SyntaxKind.MethodSignature: case ts$1.SyntaxKind.CallSignature: case ts$1.SyntaxKind.ConstructSignature: case ts$1.SyntaxKind.ConstructorType: case ts$1.SyntaxKind.FunctionType: return this._handleFunctionLikeDeclaration(node2, cb, variableCallback); case ts$1.SyntaxKind.ConditionalType: return this._handleConditionalType(node2, cb, variableCallback); case ts$1.SyntaxKind.VariableDeclarationList: this._handleVariableDeclaration(node2); break; case ts$1.SyntaxKind.Parameter: if (node2.parent.kind !== ts$1.SyntaxKind.IndexSignature && (node2.name.kind !== ts$1.SyntaxKind.Identifier || node2.name.originalKeywordKind !== ts$1.SyntaxKind.ThisKeyword)) this._handleBindingName(node2.name, false, false); break; case ts$1.SyntaxKind.EnumMember: this._scope.addVariable( util_1.getPropertyName(node2.name), node2.name, 1, true, 4 /* Value */ ); break; case ts$1.SyntaxKind.ImportClause: case ts$1.SyntaxKind.ImportSpecifier: case ts$1.SyntaxKind.NamespaceImport: case ts$1.SyntaxKind.ImportEqualsDeclaration: this._handleDeclaration( node2, false, 7 | 8 /* Import */ ); break; case ts$1.SyntaxKind.TypeParameter: this._scope.addVariable( node2.name.text, node2.name, node2.parent.kind === ts$1.SyntaxKind.InferType ? 8 : 7, false, 2 /* Type */ ); break; case ts$1.SyntaxKind.ExportSpecifier: if (node2.propertyName !== void 0) return this._scope.markExported(node2.propertyName, node2.name); return this._scope.markExported(node2.name); case ts$1.SyntaxKind.ExportAssignment: if (node2.expression.kind === ts$1.SyntaxKind.Identifier) return this._scope.markExported(node2.expression); break; case ts$1.SyntaxKind.Identifier: const domain = getUsageDomain(node2); if (domain !== void 0) this._scope.addUse({ domain, location: node2 }); return; } return ts$1.forEachChild(node2, cb); }; const continueWithScope = (node2, scope, next = forEachChild) => { const savedScope = this._scope; this._scope = scope; next(node2); this._scope.end(variableCallback); this._scope = savedScope; }; const handleBlockScope = (node2) => { if (node2.kind === ts$1.SyntaxKind.CatchClause && node2.variableDeclaration !== void 0) this._handleBindingName(node2.variableDeclaration.name, true, false); return ts$1.forEachChild(node2, cb); }; ts$1.forEachChild(sourceFile, cb); this._scope.end(variableCallback); return this._result; function forEachChild(node2) { return ts$1.forEachChild(node2, cb); } } _handleConditionalType(node2, cb, varCb) { const savedScope = this._scope; const scope = this._scope = new ConditionalTypeScope(savedScope); cb(node2.checkType); scope.updateState( 1 /* Extends */ ); cb(node2.extendsType); scope.updateState( 2 /* TrueType */ ); cb(node2.trueType); scope.updateState( 3 /* FalseType */ ); cb(node2.falseType); scope.end(varCb); this._scope = savedScope; } _handleFunctionLikeDeclaration(node2, cb, varCb) { if (node2.decorators !== void 0) node2.decorators.forEach(cb); const savedScope = this._scope; if (node2.kind === ts$1.SyntaxKind.FunctionDeclaration) this._handleDeclaration( node2, false, 4 /* Value */ ); const scope = this._scope = node2.kind === ts$1.SyntaxKind.FunctionExpression && node2.name !== void 0 ? new FunctionExpressionScope(node2.name, savedScope) : new FunctionScope(savedScope); if (node2.name !== void 0) cb(node2.name); if (node2.typeParameters !== void 0) node2.typeParameters.forEach(cb); node2.parameters.forEach(cb); if (node2.type !== void 0) cb(node2.type); if (node2.body !== void 0) { scope.beginBody(); cb(node2.body); } scope.end(varCb); this._scope = savedScope; } _handleModule(node2, next) { if (node2.flags & ts$1.NodeFlags.GlobalAugmentation) return next(node2, this._scope.createOrReuseNamespaceScope("-global", false, true, false)); if (node2.name.kind === ts$1.SyntaxKind.Identifier) { const exported = isNamespaceExported(node2); this._scope.addVariable( node2.name.text, node2.name, 1, exported, 1 | 4 /* Value */ ); const ambient = util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword); return next(node2, this._scope.createOrReuseNamespaceScope(node2.name.text, exported, ambient, ambient && namespaceHasExportStatement(node2))); } return next(node2, this._scope.createOrReuseNamespaceScope(`"${node2.name.text}"`, false, true, namespaceHasExportStatement(node2))); } _handleDeclaration(node2, blockScoped, domain) { if (node2.name !== void 0) this._scope.addVariable(node2.name.text, node2.name, blockScoped ? 3 : 1, util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword), domain); } _handleBindingName(name, blockScoped, exported) { if (name.kind === ts$1.SyntaxKind.Identifier) return this._scope.addVariable( name.text, name, blockScoped ? 3 : 1, exported, 4 /* Value */ ); util_1.forEachDestructuringIdentifier(name, (declaration) => { this._scope.addVariable( declaration.name.text, declaration.name, blockScoped ? 3 : 1, exported, 4 /* Value */ ); }); } _handleVariableDeclaration(declarationList) { const blockScoped = util_1.isBlockScopedVariableDeclarationList(declarationList); const exported = declarationList.parent.kind === ts$1.SyntaxKind.VariableStatement && util_1.hasModifier(declarationList.parent.modifiers, ts$1.SyntaxKind.ExportKeyword); for (const declaration of declarationList.declarations) this._handleBindingName(declaration.name, blockScoped, exported); } } function isNamespaceExported(node2) { return node2.parent.kind === ts$1.SyntaxKind.ModuleDeclaration || util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword); } function namespaceHasExportStatement(ns) { if (ns.body === void 0 || ns.body.kind !== ts$1.SyntaxKind.ModuleBlock) return false; return containsExportStatement(ns.body); } function containsExportStatement(block) { for (const statement of block.statements) if (statement.kind === ts$1.SyntaxKind.ExportDeclaration || statement.kind === ts$1.SyntaxKind.ExportAssignment) return true; return false; } })(usage); return usage; } var controlFlow = {}; var hasRequiredControlFlow; function requireControlFlow() { if (hasRequiredControlFlow) return controlFlow; hasRequiredControlFlow = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); exports3.callExpressionAffectsControlFlow = exports3.SignatureEffect = exports3.getControlFlowEnd = exports3.endsControlFlow = void 0; const ts$1 = ts; const node_1 = requireNode(); const util_1 = requireUtil$1(); function endsControlFlow(statement, checker) { return getControlFlowEnd(statement, checker).end; } exports3.endsControlFlow = endsControlFlow; const defaultControlFlowEnd = { statements: [], end: false }; function getControlFlowEnd(statement, checker) { return node_1.isBlockLike(statement) ? handleBlock(statement, checker) : getControlFlowEndWorker(statement, checker); } exports3.getControlFlowEnd = getControlFlowEnd; function getControlFlowEndWorker(statement, checker) { switch (statement.kind) { case ts$1.SyntaxKind.ReturnStatement: case ts$1.SyntaxKind.ThrowStatement: case ts$1.SyntaxKind.ContinueStatement: case ts$1.SyntaxKind.BreakStatement: return { statements: [statement], end: true }; case ts$1.SyntaxKind.Block: return handleBlock(statement, checker); case ts$1.SyntaxKind.ForStatement: case ts$1.SyntaxKind.WhileStatement: return handleForAndWhileStatement(statement, checker); case ts$1.SyntaxKind.ForOfStatement: case ts$1.SyntaxKind.ForInStatement: return handleForInOrOfStatement(statement, checker); case ts$1.SyntaxKind.DoStatement: return matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement); case ts$1.SyntaxKind.IfStatement: return handleIfStatement(statement, checker); case ts$1.SyntaxKind.SwitchStatement: return matchBreakOrContinue(handleSwitchStatement(statement, checker), node_1.isBreakStatement); case ts$1.SyntaxKind.TryStatement: return handleTryStatement(statement, checker); case ts$1.SyntaxKind.LabeledStatement: return matchLabel(getControlFlowEndWorker(statement.statement, checker), statement.label); case ts$1.SyntaxKind.WithStatement: return getControlFlowEndWorker(statement.statement, checker); case ts$1.SyntaxKind.ExpressionStatement: if (checker === void 0) return defaultControlFlowEnd; return handleExpressionStatement(statement, checker); default: return defaultControlFlowEnd; } } function handleBlock(statement, checker) { const result = { statements: [], end: false }; for (const s of statement.statements) { const current = getControlFlowEndWorker(s, checker); result.statements.push(...current.statements); if (current.end) { result.end = true; break; } } return result; } function handleForInOrOfStatement(statement, checker) { const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement); end.end = false; return end; } function handleForAndWhileStatement(statement, checker) { const constantCondition = statement.kind === ts$1.SyntaxKind.WhileStatement ? getConstantCondition(statement.expression) : statement.condition === void 0 || getConstantCondition(statement.condition); if (constantCondition === false) return defaultControlFlowEnd; const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement); if (constantCondition === void 0) end.end = false; return end; } function getConstantCondition(node2) { switch (node2.kind) { case ts$1.SyntaxKind.TrueKeyword: return true; case ts$1.SyntaxKind.FalseKeyword: return false; default: return; } } function handleIfStatement(node2, checker) { switch (getConstantCondition(node2.expression)) { case true: return getControlFlowEndWorker(node2.thenStatement, checker); case false: return node2.elseStatement === void 0 ? defaultControlFlowEnd : getControlFlowEndWorker(node2.elseStatement, checker); } const then = getControlFlowEndWorker(node2.thenStatement, checker); if (node2.elseStatement === void 0) return { statements: then.statements, end: false }; const elze = getControlFlowEndWorker(node2.elseStatement, checker); return { statements: [...then.statements, ...elze.statements], end: then.end && elze.end }; } function handleSwitchStatement(node2, checker) { let hasDefault = false; const result = { statements: [], end: false }; for (const clause of node2.caseBlock.clauses) { if (clause.kind === ts$1.SyntaxKind.DefaultClause) hasDefault = true; const current = handleBlock(clause, checker); result.end = current.end; result.statements.push(...current.statements); } result.end && (result.end = hasDefault || checker !== void 0 && util_1.hasExhaustiveCaseClauses(node2, checker)); return result; } function handleTryStatement(node2, checker) { let finallyResult; if (node2.finallyBlock !== void 0) { finallyResult = handleBlock(node2.finallyBlock, checker); if (finallyResult.end) return finallyResult; } const tryResult = handleBlock(node2.tryBlock, checker); if (node2.catchClause === void 0) return { statements: finallyResult.statements.concat(tryResult.statements), end: tryResult.end }; const catchResult = handleBlock(node2.catchClause.block, checker); return { statements: tryResult.statements.filter((s) => s.kind !== ts$1.SyntaxKind.ThrowStatement && s.kind !== ts$1.SyntaxKind.ExpressionStatement).concat(catchResult.statements, finallyResult === void 0 ? [] : finallyResult.statements), end: tryResult.end && catchResult.end // only ends control flow if try AND catch definitely end control flow }; } function isDottedNameWithExplicitTypeAnnotation(node2, checker) { while (true) { switch (node2.kind) { case ts$1.SyntaxKind.Identifier: { const symbol = checker.getExportSymbolOfSymbol(checker.getSymbolAtLocation(node2)); return isExplicitlyTypedSymbol(util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Alias) ? checker.getAliasedSymbol(symbol) : symbol, checker); } case ts$1.SyntaxKind.ThisKeyword: return isExplicitlyTypedThis(node2); case ts$1.SyntaxKind.SuperKeyword: return true; case ts$1.SyntaxKind.PropertyAccessExpression: if (!isExplicitlyTypedSymbol(checker.getSymbolAtLocation(node2), checker)) return false; case ts$1.SyntaxKind.ParenthesizedExpression: node2 = node2.expression; continue; default: return false; } } } function isExplicitlyTypedSymbol(symbol, checker) { if (symbol === void 0) return false; if (util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Function | ts$1.SymbolFlags.Method | ts$1.SymbolFlags.Class | ts$1.SymbolFlags.ValueModule)) return true; if (!util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Variable | ts$1.SymbolFlags.Property)) return false; if (symbol.valueDeclaration === void 0) return false; if (declarationHasExplicitTypeAnnotation(symbol.valueDeclaration)) return true; return node_1.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.parent.parent.kind === ts$1.SyntaxKind.ForOfStatement && isDottedNameWithExplicitTypeAnnotation(symbol.valueDeclaration.parent.parent.expression, checker); } function declarationHasExplicitTypeAnnotation(node2) { if (ts$1.isJSDocPropertyLikeTag(node2)) return node2.typeExpression !== void 0; return (node_1.isVariableDeclaration(node2) || node_1.isParameterDeclaration(node2) || node_1.isPropertyDeclaration(node2) || node_1.isPropertySignature(node2)) && (util_1.isNodeFlagSet(node2, ts$1.NodeFlags.JavaScriptFile) ? ts$1.getJSDocType(node2) : node2.type) !== void 0; } function isExplicitlyTypedThis(node2) { var _a; do { node2 = node2.parent; if (node_1.isDecorator(node2)) { if (node2.parent.kind === ts$1.SyntaxKind.Parameter && node_1.isClassLikeDeclaration(node2.parent.parent.parent)) { node2 = node2.parent.parent.parent.parent; } else if (node_1.isClassLikeDeclaration(node2.parent.parent)) { node2 = node2.parent.parent.parent; } else if (node_1.isClassLikeDeclaration(node2.parent)) { node2 = node2.parent.parent; } } } while (util_1.isFunctionScopeBoundary(node2) !== 1 || node2.kind === ts$1.SyntaxKind.ArrowFunction); return util_1.isFunctionWithBody(node2) && (util_1.isNodeFlagSet(node2, ts$1.NodeFlags.JavaScriptFile) ? ((_a = ts$1.getJSDocThisTag(node2)) === null || _a === void 0 ? void 0 : _a.typeExpression) !== void 0 : node2.parameters.length !== 0 && util_1.isThisParameter(node2.parameters[0]) && node2.parameters[0].type !== void 0) || node_1.isClassLikeDeclaration(node2.parent); } (function(SignatureEffect) { SignatureEffect[SignatureEffect["Never"] = 1] = "Never"; SignatureEffect[SignatureEffect["Asserts"] = 2] = "Asserts"; })(exports3.SignatureEffect || (exports3.SignatureEffect = {})); function callExpressionAffectsControlFlow(node2, checker) { var _a, _b, _c; if (!node_1.isExpressionStatement(node2.parent) || ts$1.isOptionalChain(node2) || !isDottedNameWithExplicitTypeAnnotation(node2.expression, checker)) return; const signature = checker.getResolvedSignature(node2); if ((signature === null || signature === void 0 ? void 0 : signature.declaration) === void 0) return; const typeNode = ts$1.isJSDocSignature(signature.declaration) ? (_b = (_a = signature.declaration.type) === null || _a === void 0 ? void 0 : _a.typeExpression) === null || _b === void 0 ? void 0 : _b.type : (_c = signature.declaration.type) !== null && _c !== void 0 ? _c : util_1.isNodeFlagSet(signature.declaration, ts$1.NodeFlags.JavaScriptFile) ? ts$1.getJSDocReturnType(signature.declaration) : void 0; if (typeNode === void 0) return; if (node_1.isTypePredicateNode(typeNode) && typeNode.assertsModifier !== void 0) return 2; return util_1.isTypeFlagSet(checker.getTypeFromTypeNode(typeNode), ts$1.TypeFlags.Never) ? 1 : void 0; } exports3.callExpressionAffectsControlFlow = callExpressionAffectsControlFlow; function handleExpressionStatement(node2, checker) { if (!node_1.isCallExpression(node2.expression)) return defaultControlFlowEnd; switch (callExpressionAffectsControlFlow(node2.expression, checker)) { case 2: return { statements: [node2], end: false }; case 1: return { statements: [node2], end: true }; case void 0: return defaultControlFlowEnd; } } function matchBreakOrContinue(current, pred) { const result = { statements: [], end: current.end }; for (const statement of current.statements) { if (pred(statement) && statement.label === void 0) { result.end = false; continue; } result.statements.push(statement); } return result; } function matchLabel(current, label) { const result = { statements: [], end: current.end }; const labelText = label.text; for (const statement of current.statements) { switch (statement.kind) { case ts$1.SyntaxKind.BreakStatement: case ts$1.SyntaxKind.ContinueStatement: if (statement.label !== void 0 && statement.label.text === labelText) { result.end = false; continue; } } result.statements.push(statement); } return result; } })(controlFlow); return controlFlow; } var convertAst = {}; var hasRequiredConvertAst; function requireConvertAst() { if (hasRequiredConvertAst) return convertAst; hasRequiredConvertAst = 1; Object.defineProperty(convertAst, "__esModule", { value: true }); convertAst.convertAst = void 0; const ts$1 = ts; const util_1 = requireUtil$1(); function convertAst$1(sourceFile) { const wrapped = { node: sourceFile, parent: void 0, kind: ts$1.SyntaxKind.SourceFile, children: [], next: void 0, skip: void 0 }; const flat = []; let current = wrapped; function collectChildren(node2) { current.children.push({ node: node2, parent: current, kind: node2.kind, children: [], next: void 0, skip: void 0 }); } const stack = []; while (true) { if (current.children.length === 0) { ts$1.forEachChild(current.node, collectChildren); if (current.children.length === 0) { current = current.parent; } else { const firstChild = current.children[0]; current.next = firstChild; flat.push(firstChild.node); if (util_1.isNodeKind(firstChild.kind)) current = firstChild; stack.push(1); } } else { const index = stack[stack.length - 1]; if (index < current.children.length) { const currentChild = current.children[index]; flat.push(currentChild.node); let previous = current.children[index - 1]; while (previous.children.length !== 0) { previous.skip = currentChild; previous = previous.children[previous.children.length - 1]; } previous.skip = previous.next = currentChild; ++stack[stack.length - 1]; if (util_1.isNodeKind(currentChild.kind)) current = currentChild; } else { if (stack.length === 1) break; stack.pop(); current = current.parent; } } } return { wrapped, flat }; } convertAst.convertAst = convertAst$1; return convertAst; } var hasRequiredUtil; function requireUtil() { if (hasRequiredUtil) return util$2; hasRequiredUtil = 1; (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireUtil$1(), exports3); tslib_1.__exportStar(requireUsage(), exports3); tslib_1.__exportStar(requireControlFlow(), exports3); tslib_1.__exportStar(requireType(), exports3); tslib_1.__exportStar(requireConvertAst(), exports3); })(util$2); return util$2; } (function(exports3) { Object.defineProperty(exports3, "__esModule", { value: true }); const tslib_1 = require$$0; tslib_1.__exportStar(requireTypeguard(), exports3); tslib_1.__exportStar(requireUtil(), exports3); })(tsutils); const glslHeader = "uint shadeup_up_swizzle_x_uint(uint n) {\r\n return n;\r\n}\r\n\r\nuvec2 shadeup_up_swizzle_xx_uint(uint n) {\r\n return uvec2(n, n);\r\n}\r\n\r\nuvec3 shadeup_up_swizzle_xxx_uint(uint n) {\r\n return uvec3(n, n, n);\r\n}\r\n\r\nuvec4 shadeup_up_swizzle_xxxx_uint(uint n) {\r\n return uvec4(n, n, n, n);\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xy_uint(uint n) {\r\n return uvec2(n, n);\r\n}\r\n\r\nuvec3 shadeup_up_swizzle_xyz_uint(uint n) {\r\n return uvec3(n, n, n);\r\n}\r\n\r\nuvec4 shadeup_up_swizzle_xyzw_uint(uint n) {\r\n return uvec4(n, n, n, n);\r\n}\r\n\r\nint shadeup_up_swizzle_x_int(int n) {\r\n return n;\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xx_int(int n) {\r\n return ivec2(n, n);\r\n}\r\n\r\nivec3 shadeup_up_swizzle_xxx_int(int n) {\r\n return ivec3(n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xxxx_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xy_int(int n) {\r\n return ivec2(n, n);\r\n}\r\n\r\nivec3 shadeup_up_swizzle_xyz_int(int n) {\r\n return ivec3(n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xyzw_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xxxx_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nfloat shadeup_up_swizzle_x_float(float n) {\r\n return n;\r\n}\r\n\r\nvec2 shadeup_up_swizzle_xx_float(float n) {\r\n return vec2(n, n);\r\n}\r\n\r\nvec3 shadeup_up_swizzle_xxx_float(float n) {\r\n return vec3(n, n, n);\r\n}\r\n\r\nvec4 shadeup_up_swizzle_xxxx_float(float n) {\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nvec2 shadeup_up_swizzle_xy_float(float n) {\r\n return vec2(n, n);\r\n}\r\n\r\nvec3 shadeup_up_swizzle_xyz_float(float n) {\r\n return vec3(n, n, n);\r\n}\r\n\r\nvec4 shadeup_up_swizzle_xyzw_float(float n) {\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nmat4 matrix_inversefloat4x4(mat4 m) {\r\n return inverse(m);\r\n}\r\n\r\nmat3 matrix_inversefloat3x3(mat3 m) {\r\n return inverse(m);\r\n}\r\n\r\nmat2 matrix_inversefloat2x2(mat2 m) {\r\n return inverse(m);\r\n}\r\n\r\nfloat bilerp_float(float a, float b, float c, float d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec2 bilerp_float2(vec2 a, vec2 b, vec2 c, vec2 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec3 bilerp_float3(vec3 a, vec3 b, vec3 c, vec3 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec4 bilerp_float4(vec4 a, vec4 b, vec4 c, vec4 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nmat2 bilerp_float2x2(mat2 a, mat2 b, mat2 c, mat2 d, float u, float v) {\r\n return mat2(bilerp_float2(a[0], b[0], c[0], d[0], u, v), bilerp_float2(a[1], b[1], c[1], d[1], u, v));\r\n}\r\n\r\nmat3 bilerp_float3x3(mat3 a, mat3 b, mat3 c, mat3 d, float u, float v) {\r\n return mat3(bilerp_float3(a[0], b[0], c[0], d[0], u, v), bilerp_float3(a[1], b[1], c[1], d[1], u, v), bilerp_float3(a[2], b[2], c[2], d[2], u, v));\r\n}\r\n\r\nmat4 bilerp_float4x4(mat4 a, mat4 b, mat4 c, mat4 d, float u, float v) {\r\n return mat4(bilerp_float4(a[0], b[0], c[0], d[0], u, v), bilerp_float4(a[1], b[1], c[1], d[1], u, v), bilerp_float4(a[2], b[2], c[2], d[2], u, v), bilerp_float4(a[3], b[3], c[3], d[3], u, v));\r\n}"; let { factory: factory$1, isIdentifier: isIdentifier$1 } = ts; const TYPE_BLACKLIST$1 = [ "never", "object", "symbol", "bigint", "undefined", "null", "map", "string" ]; const RESERVED_WORDS$1 = ["attribute", "sample", "varying", "uniform", "layout"]; class GLSLCompilationError extends Error { constructor(message, node2) { super(message); this.message = message; this.node = node2; this.context = node2; } } function generateDefaultForType$2(checker, _type_node) { let _type = checker.getTypeFromTypeNode(_type_node); let name = (_type.aliasSymbol || _type.getSymbol())?.escapedName.toString(); switch (name) { case "int": return "int(0)"; case "uint": return "uint(0)"; case "uint8": return "uint(0)"; case "float": return "float(0.0)"; case "float2": return "vec2(0.0, 0.0)"; case "float3": return "vec3(0.0, 0.0, 0.0)"; case "float4": return "vec4(0.0, 0.0, 0.0, 0.0)"; case "int2": return "ivec2(0, 0)"; case "int3": return "ivec3(0, 0, 0)"; case "int4": return "ivec4(0, 0, 0, 0)"; case "uint2": return "uvec2(0u, 0u)"; case "uint3": return "uvec3(0u, 0u, 0u)"; case "uint4": return "uvec4(0u, 0u, 0u, 0u)"; case "float2x2": return "mat2(0.0, 0.0, 0.0, 0.0)"; case "float3x3": return "mat3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "float4x4": return "mat4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "bool": return "false"; default: let decl = _type.getSymbol()?.getDeclarations(); if (ts.isTupleTypeNode(_type_node)) { let len = _type_node.elements.length; let args = []; let rootNode = _type_node.elements[0]; if (rootNode) { for (let i = 0; i < len; i++) { args.push(generateDefaultForType$2(checker, _type_node.elements[i])); } let rootType = checker.getTypeFromTypeNode(rootNode); return translateType$1(checker, rootType) + `[${len}] {` + args.join(", ") + "}"; } else { return "0"; } } if (decl && decl.length > 0) { let d = decl[0]; let structProps = []; if (ts.isClassDeclaration(d)) { let symd = _type.getSymbol(); symd?.members?.forEach((v, k) => { let decl2 = v.valueDeclaration; if (decl2 && ts.isPropertyDeclaration(decl2)) { structProps.push([k?.toString() ?? "", decl2.type]); } }); let sortedPropsByKey = structProps.sort((a, b) => { return a[0].localeCompare(b[0]); }); let args = sortedPropsByKey.map((p) => { return "/* " + p[0] + ": */ " + generateDefaultForType$2(checker, p[1]) + "\n"; }); return "_make_struct_" + resolveStructName$1(d) + "(\n" + args.join(", ") + "\n)"; } else { return "0"; } } else { return "0"; } } } function getTypeFallback$2(checker, t) { let n = (t.aliasSymbol || t.getSymbol())?.escapedName; if (!n && t.intrinsicName) n = t.intrinsicName; if (typeof n !== "string") { let props = t.getApparentProperties(); if (props.length > 0) { for (let p of props) { if (p.escapedName.toString() === "_opaque_int") return "int"; if (p.escapedName.toString() === "_opaque_float") return "float"; if (p.escapedName.toString() === "_opaque_uint") return "uint"; } } let btype = t.getBaseTypes(); if (btype && btype.length > 0) { for (let b of btype) { let tn = getTypeFallback$2(checker, b); if (tn) return tn; } return null; } } else { return n; } } function followTypeReferences$1(t) { if (t.flags & ts.TypeFlags.Object && t.objectFlags & ts.ObjectFlags.Reference) { if (t.target === t) { return t; } return followTypeReferences$1(t.target); } else { return t; } } function translateType$1(checker, t, templateFormat = false) { let n = getTypeFallback$2(checker, t); let originalType = t; if (n === void 0) { t = followTypeReferences$1(t); } if (templateFormat) { let name = n?.toString() ?? "unknown"; if (name === "Array" || name === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); return { type: "array", element: translateType$1(checker, args[0], true) }; } if (name == "boolean" || name == "false" || name == "true") name = "bool"; if (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint") || name == "bool" || name == "texture2d" || name == "atomic") return { type: "primitive", name }; let symbol = t.aliasSymbol || t.getSymbol(); if (symbol && symbol.declarations && symbol.declarations.length > 0) { if (ts.isClassDeclaration(symbol.declarations[0])) { let fields = {}; let decl = symbol.declarations[0]; for (let member of decl.members) { if (ts.isPropertyDeclaration(member)) { let name2 = member.name.getText(); let type2 = checker.getTypeFromTypeNode(member.type); fields[name2] = translateType$1(checker, type2, true); } } return { type: "struct", name: resolveStructName$1(decl), fields }; } else { return { type: "unknown" }; } } } else { if (n === "Array" || n === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let toStringed = checker.typeToString(typeRef); let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); let translated = translateType$1(checker, args[0]); if (toStringed.endsWith("[]")) { return translated + "[]"; } else { let staticSize = 0; if (tsutils.isTupleType(t)) { staticSize = t.fixedLength; } return translated + "[" + staticSize + "]"; } } if (n === "texture2d") return `sampler2D`; if (n == "atomic") { let args = t.typeArguments || checker.getTypeArguments(t); let translated = translateType$1(checker, args[0]); return `atomic_${translated}`; } if (n === "bool") return "bool"; if (n === "boolean") return "bool"; if (n === "float") return "float"; if (n === "float2") return "vec2"; if (n === "float3") return "vec3"; if (n === "float4") return "vec4"; if (n === "int") return "int"; if (n === "int2") return "ivec2"; if (n === "int3") return "ivec3"; if (n === "int4") return "ivec4"; if (n === "uint") return "uint"; if (n === "uint8") return "uint"; if (n === "uint2") return "uvec2"; if (n === "uint3") return "uvec3"; if (n === "uint4") return "uvec4"; if (n === "float2x2") return "mat2"; if (n === "float3x3") return "mat3"; if (n === "float4x4") return "mat4"; if (n === "void") return "void"; if (n === "error") return "void"; if (t.isUnion()) { let types2 = t.types.map((t2) => translateType$1(checker, t2)); for (let sub of types2) { if (sub && sub !== "void" && sub !== "undefined") return sub; } } let symbol = t.aliasSymbol || t.getSymbol(); if (symbol && symbol.declarations && symbol.declarations.length > 0) { if (ts.isClassDeclaration(symbol.declarations[0])) { return resolveStructName$1(symbol.declarations[0]); } else { return n?.toString() ?? "void"; } } else { return n?.toString() ?? "void"; } } } function isTypeNameVector$1(name) { if (name.startsWith("float") || name.startsWith("int")) { if (name.endsWith("2") || name.endsWith("3") || name.endsWith("4")) { return true; } } return false; } function getTypeNameVectorElementType$1(name) { if (name == "float") { return ["float", 1]; } if (name == "int") { return ["int", 1]; } if (name == "uint") { return ["uint", 1]; } if (name.startsWith("float")) { return ["float", parseInt(name.substring(5))]; } if (name.startsWith("int")) { return ["int", parseInt(name.substring(3))]; } if (name.startsWith("uint")) { return ["uint", parseInt(name.substring(4))]; } if (name.startsWith("vec")) { return ["float", parseInt(name.substring(3))]; } if (name.startsWith("ivec")) { return ["int", parseInt(name.substring(4))]; } if (name.startsWith("uvec")) { return ["uint", parseInt(name.substring(4))]; } return ["", 0]; } function isTranslatedTypeNameVectorOrScalar$1(name) { if (name == "float" || name == "int" || name == "uint") return true; if (name.startsWith("vec") || name.startsWith("ivec") || name.startsWith("uvec")) { if (name.endsWith("2") || name.endsWith("3") || name.endsWith("4")) { return true; } return true; } return false; } function isVector$1(checker, t) { let name = getTypeFallback$2(checker, t); if (name) { return isTypeNameVector$1(name); } return false; } function getVectorElementType$1(checker, t) { let name = getTypeFallback$2(checker, t); if (name) { return getTypeNameVectorElementType$1(name); } return ["", 0]; } function isNumeric$1(checker, t) { let name = getTypeFallback$2(checker, t); if (name && (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint"))) { return true; } return false; } function escapeIdentifier$1(id) { if (RESERVED_WORDS$1.includes(id)) { return "_" + id; } return id.replaceAll("___", "_ii_").replaceAll("__", "_i_"); } function getVectorMask$1(num) { let outMask = ""; let comps = ["x", "y", "z", "w"]; for (let i = 0; i < num; i++) { outMask += comps[i]; } return outMask; } function isGLSLType$1(name) { return name.startsWith("vec") || name.startsWith("mat") || name.startsWith("sampler") || name.startsWith("texture") || name.startsWith("isampler") || name.startsWith("usampler") || name.startsWith("uvec") || name.startsWith("ivec") || name == "bool" || name == "float" || name == "int" || name == "uint" || name == "uint8" || name == "void"; } function autoCastNumeric$1(value, input, expected) { let inputType = getTypeNameVectorElementType$1(input); let expectedType = getTypeNameVectorElementType$1(expected); if (inputType[0] != expectedType[0]) { if (expectedType[1] == 1) { return new SourceNode(value.startIndex, value.endIndex, [`${expectedType[0]}(`, value, `)`]); } else { return new SourceNode(value.startIndex, value.endIndex, [`${expectedType[0]}(`, value, `)`]); } } return value; } function convertConciseBodyToBlock$1(body) { if (ts.isBlock(body)) { return body; } else { return ts.factory.createBlock([ts.factory.createReturnStatement(body)]); } } function compile$2(ctx, ast, originalMapping) { function c2(ast2) { if (!ast2) { return s([]); } return compile$2(ctx, ast2); } function cplain(ast2) { if (!ast2) { return s([]); } return compile$2( { checker: ctx.checker, parentFunction: ctx.parentFunction }, ast2 ); } function s(c22) { if (originalMapping) { let reverseMapped = lookupIndexMappingRange(originalMapping, ast.getStart(), ast.getEnd()); return new SourceNode(reverseMapped.start, reverseMapped.end, c22); } else { return new SourceNode(0, 0, c22); } } function join(c22, sep) { return c22.reduce((acc, cur) => { if (acc.length === 0) { return [cur]; } return [...acc, sep, cur]; }, []); } function children() { return ast.getChildren().map((child) => c2(child)); } function autoCastParameter(callExpr, argIndex) { let signature = ctx.checker.getResolvedSignature(callExpr); let params = signature.getParameters(); let param = params[argIndex]; let paramType = ctx.checker.getTypeOfSymbolAtLocation(param, callExpr); let paramTypeString = translateType$1(ctx.checker, paramType); let arg = callExpr.arguments[argIndex]; let argType = ctx.checker.getTypeAtLocation(arg); let argTypeString = translateType$1(ctx.checker, argType); if (paramTypeString !== argTypeString) { return autoCastNumeric$1(c2(arg), argTypeString, paramTypeString); } return s([c2(arg)]); } let prefixFunctions = []; if (ctx.composed) { if (ts.isMethodDeclaration(ast) || ts.isFunctionDeclaration(ast)) { for (let [i, arg] of ctx.composed.arguments.entries()) { if (ts.isArrowFunction(arg)) { let paramFromIndex = ast.parameters[i]; let name = paramFromIndex.name.getText() + "_composed_" + arg.pos + "_arg_" + i; let signature = ctx.checker.getSignatureFromDeclaration(arg); let returnType = signature.getReturnType(); let vars = getClosureVars$1(ctx.checker, arg); let vvv = vars.map( (p) => s([ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(p.declarations[0])), " ", p.escapedName ]) ); let joins = join([...arg.parameters.map((p) => cplain(p)), ...vvv], ", "); prefixFunctions.push( s([ translateType$1(ctx.checker, returnType), " ", name, "(", ...joins, ")", " {\n", ...convertConciseBodyToBlock$1(arg.body).statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]) ); } } } } switch (ast.kind) { case ts.SyntaxKind.FirstPunctuation: return s([ast.getText()]); case ts.SyntaxKind.SyntaxList: return s(children()); case ts.SyntaxKind.SourceFile: return s(children()); case ts.SyntaxKind.BreakStatement: return s(["break;"]); case ts.SyntaxKind.ContinueStatement: return s(["continue;"]); case ts.SyntaxKind.MethodDeclaration: let fnDeclar = ast; let fnName = resolveFunctionName$1(fnDeclar); if (ctx.composed) { fnName = fnName + "_composed_" + ctx.composed.pos; } let isStatic = false; let signature = ctx.checker.getSignatureFromDeclaration(fnDeclar); if (ts.canHaveModifiers(fnDeclar)) { let mods = ts.getModifiers(fnDeclar); if (mods) { if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) { isStatic = true; } } } let returnType = signature.getReturnType(); return s([ ...prefixFunctions, translateType$1(ctx.checker, returnType), " ", fnName, "(", , ...join( [ ...isStatic ? [] : [ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(fnDeclar.parent)) + " _this" ], ...fnDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map((p) => c2(p)) ], ", " ), ")", " {\n", ...fnDeclar.body?.statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]); case ts.SyntaxKind.FunctionDeclaration: let mthdDeclar = ast; let mthdsignature = ctx.checker.getSignatureFromDeclaration(mthdDeclar); let mthdreturnType = mthdsignature.getReturnType(); let mthdName = resolveFunctionName$1(mthdDeclar); if (ctx.composed) { mthdName = mthdName + "_composed_" + ctx.composed.pos; } return s([ ...prefixFunctions, translateType$1(ctx.checker, mthdreturnType), " ", mthdName, "(", ...join( mthdDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map((p) => c2(p)), ", " ), ")", " {\n", ...mthdDeclar.body?.statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]); case ts.SyntaxKind.ReturnStatement: let ret = ast; if (!ctx.parentFunction) { if (ret.expression) { return s(["return ", c2(ret.expression), ";\n"]); } else { return s(["return;\n"]); } } else { let expectedReturnType = ctx.checker.getSignatureFromDeclaration(ctx.parentFunction).getReturnType(); let actualReturnType = ctx.checker.getTypeAtLocation(ret.expression); if (ret.expression) { let sss = s([ "return ", autoCastNumeric$1( c2(ret.expression), translateType$1(ctx.checker, actualReturnType), translateType$1(ctx.checker, expectedReturnType) ), ";\n" ]); return sss; } else { return s(["return;\n"]); } } case ts.SyntaxKind.AsExpression: let asExpr = ast; return c2(asExpr.expression); case ts.SyntaxKind.Parameter: let param = ast; if (ctx.composed) { let indexOf = param.parent.parameters.indexOf(param); let expr2 = ctx.composed.arguments[indexOf]; if (expr2) { if (ts.isArrowFunction(expr2)) { let vars = getClosureVars$1(ctx.checker, expr2.body); let closureVars = vars.map((v) => { return s([ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(v.valueDeclaration)), " ", v.name ]); }); return s(join(closureVars, ", ")); } } } return s([ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(param)), " ", escapeIdentifier$1(param.name.getText()) ]); case ts.SyntaxKind.ArrowFunction: let arrow = ast; let body = convertConciseBodyToBlock$1(arrow.body); return s([ "\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/\nvoid main() {\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/\n", ...body.statements.map((s2) => c2(s2)), "\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/\n}\n" ]); case ts.SyntaxKind.VariableStatement: let varStatement = ast; return s([ ...join( varStatement.declarationList.declarations.map((d) => c2(d)), ", " ), ";\n" ]); case ts.SyntaxKind.VariableDeclaration: let varDecl = ast; let type2 = ctx.checker.getTypeAtLocation(varDecl); return s([ translateType$1(ctx.checker, type2), " ", varDecl.name.getText(), " = ", c2(varDecl.initializer) ]); case ts.SyntaxKind.CallExpression: let call = ast; let exprSmybol = ctx.checker.getSymbolAtLocation(call.expression); if (call.expression.getText() == "Math.random") { return s(["0.0"]); } if (!exprSmybol) { return s(["/* TODO: Unknown symbol */"]); } if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = ctx.checker.getAliasedSymbol(exprSmybol); } let symName = exprSmybol?.getName() ?? call.expression.getText(); if (symName == "__index") { if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType$1( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); let returnType2 = ctx.checker.getTypeAtLocation(call); let vecOut = getVectorElementType$1(ctx.checker, returnType2); let outMask = getVectorMask$1(vecOut[1]); if (innerType == "sampler2D") { return s([ "texelFetch(", c2(call.expression.expression), ", ivec2(", c2(call.arguments[0]), "), 0)." + outMask ]); } } return s([c2(call.expression), "[", c2(call.arguments[0]), "]"]); } else if (symName == "len") { let expr2 = call.expression; if (ts.isPropertyAccessExpression(expr2)) { let left = expr2.expression; return s([c2(left), "_size"]); } } else if (symName == "min" || symName == "max") { if (call.arguments.length > 2) { let args2 = call.arguments.map((a) => c2(a)); while (args2.length > 2) { let left = args2.shift(); let right = args2.shift(); args2.unshift(s([symName, "(", left, ",", right, ")"])); } return s([symName, "(", ...join(args2, ","), ")"]); } } else if (symName == "sample") { if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType$1( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); if (innerType == "sampler2D") { return s([ "texture(", c2(call.expression.expression), ", vec2(", c2(call.arguments[0]), "))" ]); } } } else if (symName == "__index_assign") { return s([ c2(call.expression.expression), "[", c2(call.arguments[0]), "] = ", autoCastParameter(call, 1) ]); } else if (symName == "rand" && call.arguments.length == 0 && call.expression.getText() == "rand") { throw new GLSLCompilationError( "rand() in shaders needs to be seeded, use rand(seed) instead", call ); } if (exprSmybol?.getName() == "makeVector" && exprSmybol.valueDeclaration) { if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) { let exprSig2 = ctx.checker.getResolvedSignature(call); if (exprSig2) { return s([ translateType$1(ctx.checker, ctx.checker.getReturnTypeOfSignature(exprSig2)), "(", ...join( call.arguments.map((a) => c2(a)), ", " ), ")" ]); } } } if (exprSmybol?.getName() == "swizzle" && exprSmybol.valueDeclaration) { if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) { ctx.checker.getSignatureFromDeclaration(exprSmybol.valueDeclaration); let arg = call.arguments[0]; let arg2 = call.arguments[1]; let propAccess = ""; if (ts.isStringLiteral(arg2)) { propAccess = arg2.text; } let argType = ctx.checker.getTypeAtLocation(arg); if (isVector$1(ctx.checker, argType)) { return s([c2(arg), ".", propAccess]); } else if (isNumeric$1(ctx.checker, argType)) { let numericType = translateType$1(ctx.checker, argType); return s([`shadeup_up_swizzle_${propAccess}_${numericType}(`, c2(arg), ")"]); } else { return s([c2(arg), ".", propAccess]); } } } if (isTypeNameVector$1(exprSmybol?.getName() ?? "")) { return s([ translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(call.expression)), "(", ...join(call.arguments.length == 0 ? [s(["0"])] : call.arguments.map((a) => c2(a)), ", "), ")" ]); } let funcName = c2(call.expression); let callArgs = []; let preArgs = []; let exprSig = ctx.checker.getResolvedSignature(call); let exprDeclar = exprSig.getDeclaration(); if (exprDeclar) { if (ts.isMethodDeclaration(exprDeclar)) { let isStatic2 = false; if (ts.canHaveModifiers(exprDeclar)) { let mods = ts.getModifiers(exprDeclar); if (mods) { if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) { isStatic2 = true; } } } if (!isStatic2) { if (ts.isPropertyAccessExpression(call.expression)) { preArgs.push(c2(call.expression.expression)); } } } } exprSmybol.getName() + "("; for (let [i, arg] of call.arguments.entries()) { let argStr = c2(arg); if (exprSig) { let p = exprSig.getTypeParameterAtPosition(i); if (p) { let translatedBase = translateType$1(ctx.checker, p); let translatedPass = translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(arg)); if (isTranslatedTypeNameVectorOrScalar$1(translatedPass)) { if (translatedBase != translatedPass && isGLSLType$1(translatedBase)) { argStr = s([`${translatedBase}(`, argStr, `)`]); } } } else { translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(arg)); } } if (ts.isArrowFunction(arg)) { let arrow2 = arg; let vars = getClosureVars$1(ctx.checker, arrow2.body); if (vars.length > 0) callArgs.push(vars.map((v) => v.escapedName).join(", ")); } else { callArgs.push(argStr); } } if (exprSmybol) { let signature2 = ctx.checker.getResolvedSignature(call); let mapping = findRealSignatureMappingToGLSL(ctx.checker, signature2) ?? findSignatureMappingToGLSL(ctx.checker, exprSmybol); if (mapping !== null) { if (mapping.startsWith("!")) { let minType = ""; let noOp = false; for (let arg of call.arguments) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeName = translateType$1(ctx.checker, argType); if (!(argTypeName == "float" || argTypeName.startsWith("vec") || argTypeName == "int" || argTypeName.startsWith("ivec") || argTypeName == "uint" || argTypeName.startsWith("uvec"))) { noOp = true; } if (minType == "") { if (argTypeName == "float" || argTypeName.startsWith("vec")) { minType = "float"; } else if (argTypeName == "int" || argTypeName.startsWith("ivec")) { minType = "int"; } else if (argTypeName == "uint" || minType.startsWith("uvec")) { minType = "uint"; } } else if (argTypeName == "float" || minType.startsWith("vec")) { minType = "float"; } } if (!noOp) { for (let i = 0; i < callArgs.length; i++) { let arg = call.arguments[i]; let argType = ctx.checker.getTypeAtLocation(arg); let argTypeName = translateType$1(ctx.checker, argType); let argTypeStripped = ""; if (argTypeName == "float" || argTypeName.startsWith("vec")) { argTypeStripped = "float"; } else if (argTypeName == "int" || argTypeName.startsWith("ivec")) { argTypeStripped = "int"; } else if (argTypeName == "uint" || argTypeName.startsWith("uvec")) { argTypeStripped = "uint"; } if (argTypeStripped != minType) { if (argTypeName.startsWith("float") || argTypeName.startsWith("int")) { callArgs[i] = s([`${minType}(`, callArgs[i], `)`]); } else if (argTypeName.startsWith("vec") || argTypeName.startsWith("ivec")) { let len = argTypeName.match(/\d+/)?.[0]; if (len === void 0) { throw new Error("Invalid type"); } callArgs[i] = s([ `${minType == "float" ? "vec" : "ivec"}${len}(`, callArgs[i], `)` ]); } else ; } } } let template = mapping.slice(1); let outs = []; let argCounter = 0; let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration()); for (let i = 0; i < callArgs.length; i++) { let paramType = ctx.checker.getTypeAtLocation( sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0] ); template = template.replace( "`" + argCounter + "`", ctx.checker.typeToString(paramType) ); argCounter++; } let result = template.split("$"); for (let r of result) { if (/^\d+$/.test(r)) { outs.push(callArgs[parseInt(r)]); } else if (r == "self") { if (call.expression.kind == ts.SyntaxKind.PropertyAccessExpression) { let propAccess = call.expression; outs.push(c2(propAccess.getChildAt(0))); } else { outs.push(c2(call.expression)); } } else { outs.push(r); } } if (outs.includes(" % ")) { if (call.arguments.length == 2) { let first = getVectorElementType$1( ctx.checker, ctx.checker.getTypeAtLocation(call.arguments[0]) ); let last = getVectorElementType$1( ctx.checker, ctx.checker.getTypeAtLocation(call.arguments[1]) ); if (first[1] != last[1] && last[1] == 1) { getVectorMask$1(first[1]); if (first[0] == "float" || last[0] == "float") { outs = [`mod(`, outs[1], ", ", outs[3], ")"]; } } } } return s(outs); } else if (mapping.startsWith("#")) { let typeName = ""; if (call.arguments.length > 0) { let firstArg = call.arguments[0]; let firstArgType = ctx.checker.getTypeAtLocation(firstArg); typeName = ctx.checker.typeToString(firstArgType); } return s([ new SourceNode(call.expression.getStart(), call.expression.getEnd(), [ mapping.substring(1) + typeName ]), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } else { return s([ new SourceNode(call.expression.getStart(), call.expression.getEnd(), [mapping]), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } if (exprSmybol.declarations[0].parent) { let param2 = exprSmybol.declarations[0]; if (ts.isParameter(param2)) ; } let funcDeclar = exprSmybol.valueDeclaration; if (exprSmybol.declarations[0].parent) { let param2 = exprSmybol.declarations[0]; if (ts.isParameter(param2)) { let indexOf = param2.parent.parameters.indexOf(param2); let additionalArgs = []; if (ctx.composed) { let realAnonymousFunc = ctx.composed.arguments[indexOf]; if (ts.isArrowFunction(realAnonymousFunc)) { let vars = getClosureVars$1(ctx.checker, realAnonymousFunc.body); additionalArgs = vars.map((v) => v.escapedName); callArgs.push(...additionalArgs); return s([ funcName, "_composed_", realAnonymousFunc.pos.toString(), "_arg_", indexOf.toString(), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } } } if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { funcName = new SourceNode( call.expression.getStart(), call.expression.getEnd(), resolveFunctionName$1(funcDeclar) ); let parentDeclar = closest(ast, (n2) => ts.isFunctionDeclaration(n2)); if (parentDeclar && ts.isFunctionDeclaration(parentDeclar)) ; if (isComposedFunction$1(ctx.checker, funcDeclar)) { return s([ funcName, "_composed_", call.pos.toString(), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } } return s([funcName, "(", ...join([...preArgs, ...callArgs], ", "), ")"]); case ts.SyntaxKind.NewExpression: let newExpr = ast; let newExprSymbol = ctx.checker.getSymbolAtLocation(newExpr.expression); let args = []; if (newExpr.arguments?.length == 1 && ts.isObjectLiteralExpression(newExpr.arguments[0])) { let object = newExpr.arguments[0]; let props = object.properties; let sortedPropsByKey = []; let structProps = []; newExprSymbol?.members?.forEach((v, k) => { let decl2 = v.valueDeclaration; if (decl2 && ts.isPropertyDeclaration(decl2)) { structProps.push([k?.toString() ?? "", decl2.type]); } }); sortedPropsByKey = structProps.sort((a, b) => { return a[0].localeCompare(b[0]); }); args = [ ...sortedPropsByKey.map((p) => { let prop2 = props.find((p2) => { if (ts.isPropertyAssignment(p2)) { return p2.name.getText() == p[0]; } else if (ts.isShorthandPropertyAssignment(p2)) { return p2.name.getText() == p[0]; } else { return false; } }); if (prop2) { if (ts.isPropertyAssignment(prop2)) { return s(["/* ", p[0], ": */ ", c2(prop2.initializer), "\n"]); } else if (ts.isShorthandPropertyAssignment(prop2)) { return s(["/* ", p[0], ": */ ", c2(prop2.name), "\n"]); } else { return s(["/* ", c2(prop2), ": */ ", "\n"]); } } else { return s(["/* ", p[0], ": */ ", generateDefaultForType$2(ctx.checker, p[1]), "\n"]); } }) ]; } let decl = ctx.checker.getTypeAtLocation(newExpr.expression).getSymbol()?.getDeclarations(); if (decl && ts.isClassDeclaration(decl[0])) { return s(["_make_struct_", resolveStructName$1(decl[0]), "(\n", ...join(args, ", "), "\n)"]); } else { return s(["/*", ...join(args, ", "), "*/"]); } case ts.SyntaxKind.ExpressionStatement: let expr = ast; return s([c2(expr.expression), ";\n"]); case ts.SyntaxKind.ObjectLiteralExpression: let obj = ast; return s([ "{", ...join( obj.properties.map((p) => { if (ts.isPropertyAssignment(p)) { return s([c2(p.name), ": ", c2(p.initializer)]); } else if (ts.isShorthandPropertyAssignment(p)) { return s([c2(p.name)]); } else { return s(["/*", c2(p), "*/"]); } }), ", " ), "}" ]); case ts.SyntaxKind.ConditionalExpression: let cond = ast; return s([c2(cond.condition), " ? ", c2(cond.whenTrue), " : ", c2(cond.whenFalse)]); case ts.SyntaxKind.Identifier: let id = ast; if (ts.isIdentifier(id)) { let sym = ctx.checker.getSymbolAtLocation(id); if (sym && sym.flags & ts.SymbolFlags.Alias) { sym = ctx.checker.getAliasedSymbol(sym); } if (sym?.declarations?.length == 1) { let decl2 = sym.declarations[0]; if (isUniformable$1(ctx.checker, decl2)) { if (isVariableDeclarationValue$1(ctx.checker, decl2)) { if (!isInSameScope$1(decl2, ast)) { if (!isInShader$2(decl2)) { if (ts.isBinaryExpression(ast.parent)) { if (ast.parent.left == ast) { throw new GLSLCompilationError( `Cannot assign to variable '${id.text.toString()}' because it is not declared in the shader`, ast ); } } let isGlobalVar = isRootNode$1(decl2); let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${id.text.toString()}`; return s([glslVarName]); } else { return s([escapeIdentifier$1(id.text.toString())]); } } } } } return s([escapeIdentifier$1(id.text.toString())]); } else { return c2(id.expression); } case ts.SyntaxKind.PropertyAccessExpression: let prop = ast; let isStaticMember = isStaticPropertyAccessExpression(ctx.checker, prop); if (isStaticMember) { return s([c2(prop.expression), "_static_", c2(prop.name)]); } else { let propName = prop.name.getText(); if (propName == "__index") { return s([c2(prop.expression)]); } else if (propName == "size") { let innerType = translateType$1( ctx.checker, ctx.checker.getTypeAtLocation(prop.expression) ); if (innerType == "sampler2D") { return s([c2(prop.expression), "_", propName]); } } else { return s([c2(prop.expression), ".", c2(prop.name)]); } } case ts.SyntaxKind.ThisKeyword: return s(["_this"]); case ts.SyntaxKind.FirstLiteralToken: let lit = ast; return s([lit.text]); case ts.SyntaxKind.IfStatement: let ifStmt = ast; if (isIdentifier$1(ifStmt.expression)) { if (ifStmt.expression.escapedText == "PLATFORM_WEBGL") { return s([c2(ifStmt.thenStatement)]); } if (ifStmt.expression.escapedText == "PLATFORM_WEBGPU") { if (ifStmt.elseStatement) { return s([c2(ifStmt.elseStatement)]); } else { return s([""]); } } } return s([ "if (", c2(ifStmt.expression), ")", c2(ifStmt.thenStatement), ifStmt.elseStatement ? s(["else \n", c2(ifStmt.elseStatement), "\n"]) : s([""]) ]); case ts.SyntaxKind.TrueKeyword: return s(["true"]); case ts.SyntaxKind.FalseKeyword: return s(["false"]); case ts.SyntaxKind.PostfixUnaryExpression: let post = ast; return s([c2(post.operand), post.operator == ts.SyntaxKind.PlusPlusToken ? "++" : "--"]); case ts.SyntaxKind.PlusPlusToken: return s(["++"]); case ts.SyntaxKind.MinusMinusToken: return s(["--"]); case ts.SyntaxKind.ParenthesizedExpression: let paren = ast; return s(["(", c2(paren.expression), ")"]); case ts.SyntaxKind.VariableDeclarationList: let varDeclList = ast; if (varDeclList.declarations.length > 0) { for (let decl2 of varDeclList.declarations) { let varDecl2 = decl2; let type22 = ctx.checker.getTypeAtLocation(varDecl2); return s([ translateType$1(ctx.checker, type22), " ", varDecl2.name.getText(), " = ", c2(varDecl2.initializer) ]); } } else { return s([""]); } case ts.SyntaxKind.ForStatement: let forStmt = ast; return s([ "for (", c2(forStmt.initializer), ";", c2(forStmt.condition), ";", c2(forStmt.incrementor), ")", c2(forStmt.statement) ]); case ts.SyntaxKind.BinaryExpression: let bin = ast; if (bin.operatorToken.kind == ts.SyntaxKind.EqualsToken) { let leftType = ctx.checker.getTypeAtLocation(bin.left); let rightType = ctx.checker.getTypeAtLocation(bin.right); if (isVector$1(ctx.checker, leftType) && isVector$1(ctx.checker, rightType)) { let [leftElementType, leftElementSize] = getVectorElementType$1(ctx.checker, leftType); let [rightElementType, rightElementSize] = getVectorElementType$1(ctx.checker, rightType); if (leftElementType != rightElementType) { if (leftElementType == "float" && rightElementType == "int") { return s([c2(bin.left), ` = vec${leftElementSize}(`, c2(bin.right), ")"]); } else if (leftElementType == "int" && rightElementType == "float") { return s([c2(bin.left), ` = ivec${leftElementSize}(`, c2(bin.right), ")"]); } } } return s([c2(bin.left), " = ", c2(bin.right)]); } let binExprText = bin.operatorToken.getText(); if (binExprText == "===") { binExprText = "=="; } return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]); case ts.SyntaxKind.StringLiteral: return s(["0"]); case ts.SyntaxKind.ArrayLiteralExpression: let arr = ast; return s([ "[", ...join( arr.elements.map((e) => c2(e)), ", " ), "]" ]); case ts.SyntaxKind.ElementAccessExpression: let elem = ast; return s([c2(elem.expression), "[", c2(elem.argumentExpression), "]"]); case ts.SyntaxKind.Block: let block = ast; return s([ "{\n", ...join( block.statements.map((child) => c2(child)), ";" ), "\n}" ]); case ts.SyntaxKind.TypeOfExpression: return s(["0"]); case ts.SyntaxKind.WhileStatement: let whileStmt = ast; return s(["while (", c2(whileStmt.expression), ") ", c2(whileStmt.statement)]); default: throw new GLSLCompilationError(`Invalid shader syntax '${ast.getText()}'`, ast); } } function getClosureVars$1(checker, func) { let result = []; let recur = (node2) => { if (node2.kind == ts.SyntaxKind.Identifier) { let id = node2; let symbol = checker.getSymbolAtLocation(id); let declar = symbol.valueDeclaration; if (isVariableDeclarationValue$1(checker, declar)) { if (declar) { if (!isInSameScope$1(declar, node2) && isInShader$2(declar)) { result.push(symbol); } } } } else { node2.forEachChild(recur); } }; recur(func); return result; } function getDeclarationType$1(checker, node2) { return node2.type ? checker.getTypeAtLocation(node2.type) : node2.initializer ? checker.getTypeAtLocation(node2.initializer) : checker.getTypeAtLocation(node2); } class GLSLShader { constructor(key, source) { this.globals = {}; this.locals = {}; this.key = key; this.source = source; } } function resolveFunctionName$1(f) { if (ts.isMethodDeclaration(f)) { let parentName = "anon"; if (f.parent && ts.isClassDeclaration(f.parent)) { parentName = f.parent.name?.text ?? "anon"; } return removeDoubleUnderscores$1( `fn_${f.getSourceFile()?.fileName.replaceAll("/", "_").replaceAll(".", "_") ?? "anon"}_${f.getStart()}_${parentName}_static_${f.name.getText() ?? "unknown"}` ); } else { return removeDoubleUnderscores$1( `fn_${f.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${f.getStart()}_${f.name?.text.replaceAll(".", "_dot_") ?? "unknown"}` ); } } function resolveStructName$1(c2) { if (c2.name?.text == "ShaderInput") return "ShaderInput"; if (c2.name?.text == "ShaderOutput") return "ShaderOutput"; return removeDoubleUnderscores$1( `str_${c2.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${c2.getStart()}_${c2.name?.text ?? "unknown"}`.replaceAll("__", "_i_") ); } function isInSameScope$1(node2, other) { return closest(node2, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }) == closest(other, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }); } function isInShader$2(node2) { return closest(node2, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) { if (hasShadeupDocTag(node22, "shader")) { return true; } } return false; }); } function isRootNode$1(node2) { let parentRoot = closest(node2, (node22) => { if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }); return parentRoot && ts.isSourceFile(parentRoot); } function isComposedFunction$1(checker, func) { let isComposed = false; func.parameters.forEach((param) => { let type2 = checker.getTypeAtLocation(param); if (type2.getCallSignatures().length > 0) { isComposed = true; } }); return isComposed; } function resolveDeps$1(checker, root, table = { graph: /* @__PURE__ */ new Map(), functions: /* @__PURE__ */ new Map(), structs: /* @__PURE__ */ new Map(), structsProps: /* @__PURE__ */ new Map(), globals: /* @__PURE__ */ new Map(), composed: /* @__PURE__ */ new Map() }) { function resolveFunction(f1, f2, call) { let n1 = f1 ? resolveFunctionName$1(f1) : "main"; let n2 = resolveFunctionName$1(f2); if (f2.name?.getText() === "__index" || f2.name?.getText() === "__index_assign" || f2.name?.getText() === "__index_assign_op" || f2.name?.getText() === "len" || f2.name?.getText() === "sample" || hasShadeupDocTag(f2, "noemit_gpu")) return; if (isComposedFunction$1(checker, f2)) { n2 = n2 + "_composed_" + call.pos; table.composed.set(n2, call); } let deps = table.graph.get(n1) ?? []; if (!deps.includes(n2)) deps.push(n2); table.graph.set(n1, deps); table.functions.set(n2, f2); } function resolveStruct(decl) { let name = resolveStructName$1(decl); if (table.structs.has(name)) return; for (let member of decl.members) { if (ts.isPropertyDeclaration(member)) { let type2 = checker.getTypeAtLocation(member); resolveTypeUse(type2, member); } } table.structs.set(name, decl); } function isValidShaderType(type2, checker2) { let symbol = type2.aliasSymbol || type2.getSymbol(); let name = checker2.typeToString(type2); let bases = type2.getBaseTypes(); if (bases && bases.length > 0) { for (let base of bases) { if (!isValidShaderType(base, checker2)) return false; } } if (TYPE_BLACKLIST$1.includes(symbol?.getName() ?? "")) { return false; } return !TYPE_BLACKLIST$1.includes(name); } function resolveTypeUse(typeNode, context2, fullStruct = false) { let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); let name = checker.typeToString(typeNode); if (!isValidShaderType(typeNode, checker)) { throw new GLSLCompilationError(`Type '${name}' is not supported in shaders`, context2); } let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { resolveStruct(decl); } let typestr = checker.typeToString(typeNode); if (typeNode.aliasTypeArguments) for (let args of typeNode.aliasTypeArguments) { resolveTypeUse(args, context2, typestr.startsWith("buffer<")); } } function resolvePropertyAccess(node2) { let typeNode = checker.getTypeAtLocation(node2.expression); let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); checker.typeToString(typeNode); if (!isValidShaderType(typeNode, checker)) { throw new GLSLCompilationError( `Type '${symbol?.getName()}' is not supported in shaders`, node2 ); } resolveTypeUse(typeNode, node2); resolveTypeUse(checker.getTypeAtLocation(node2), node2); let prop = node2.name.getText(); let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { let name2 = resolveStructName$1(decl); let props = table.structsProps.get(name2) ?? /* @__PURE__ */ new Set(); props.add(prop); table.structsProps.set(name2, props); } } walkNodes$2(root, (node2) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; exprSmybol.valueDeclaration; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let signature = checker.getResolvedSignature(node2); let mapping = findRealSignatureMappingToGLSL(checker, signature) ?? findSignatureMappingToGLSL(checker, exprSmybol); if (mapping === null) { let parentDeclar = closest( node2, (n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) || ts.isArrowFunction(n) ); if (parentDeclar && ts.isArrowFunction(parentDeclar)) { let parentParentDeclar = closest(parentDeclar, (n) => ts.isCallExpression(n)); if (parentParentDeclar && ts.isCallExpression(parentParentDeclar)) { let parentParentSymbol = checker.getSymbolAtLocation(parentParentDeclar.expression); if (parentParentSymbol && parentParentSymbol.flags & ts.SymbolFlags.Alias) { parentParentSymbol = checker.getAliasedSymbol(parentParentSymbol); } if (parentParentSymbol) { let parentParentFuncDeclar = parentParentSymbol.getDeclarations()?.[0]; if (parentParentFuncDeclar && (ts.isFunctionDeclaration(parentParentFuncDeclar) || ts.isMethodDeclaration(parentParentFuncDeclar))) { resolveFunction(parentParentFuncDeclar, funcDeclar, node2); } } } } else if (parentDeclar && (ts.isFunctionDeclaration(parentDeclar) || ts.isMethodDeclaration(parentDeclar))) { resolveFunction(parentDeclar, funcDeclar, node2); } else { resolveFunction(null, funcDeclar, node2); } if (!table.graph.has(resolveFunctionName$1(funcDeclar))) { table.graph.set(resolveFunctionName$1(funcDeclar), []); resolveDeps$1(checker, funcDeclar, table); } let sig = checker.getSignatureFromDeclaration(funcDeclar); let returnType = checker.getReturnTypeOfSignature(sig); resolveTypeUse(returnType, node2); } } } } if (ts.isPropertyAccessExpression(node2)) { resolvePropertyAccess(node2); } if (ts.isIdentifier(node2)) { if (checker.getSymbolAtLocation(node2)) { let decl = checker.getSymbolAtLocation(node2)?.declarations; let type2 = checker.getTypeAtLocation(node2); resolveTypeUse(type2, node2); if (decl && ts.isVariableDeclaration(decl[0])) { if (!isInSameScope$1(decl[0], node2) && decl[0].getSourceFile().fileName !== root.getSourceFile().fileName) { if (isVariableDeclarationValue$1(checker, decl[0])) { table.globals.set(node2.text.toString(), decl[0]); } } } } } if (ts.isVariableDeclaration(node2)) { let type2 = checker.getTypeAtLocation(node2); resolveTypeUse(type2, node2); } }); return table; } function resolveUniforms$1(checker, root) { let uniforms = []; walkNodesWithCalls$1(checker, root, (node2) => { if (ts.isIdentifier(node2)) { let decl = checker.getSymbolAtLocation(node2); if (decl && decl.flags & ts.SymbolFlags.Alias) { decl = checker.getAliasedSymbol(decl); } if (decl && decl.declarations && decl.declarations.length == 1) { let declNode = decl.declarations[0]; if (declNode) { if (isVariableDeclarationValue$1(checker, declNode)) { if (!isInSameScope$1(declNode, node2) && !isInShader$2(declNode)) { if (uniforms.findIndex((d) => d === declNode) == -1) uniforms.push(declNode); } } } } } }); return uniforms; } function isVariableDeclarationValue$1(checker, node2) { try { if (ts.isVariableDeclaration(node2) || ts.isParameter(node2)) { let type2 = checker.getTypeAtLocation(node2); let calls = type2.getCallSignatures(); return calls.length == 0; } else { return false; } } catch (e) { return false; } } function isUniformable$1(checker, decl) { let exprSmybol = checker.getSymbolAtLocation(decl); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { exprSmybol.getDeclarations()?.[0]; } return ts.isVariableDeclaration(decl) || ts.isParameter(decl); } function addGLSLShader(key, root, checker, env2, isComputeShader = false, computeShaderSize = [1, 1, 1]) { let deps = resolveDeps$1(checker, root); let uniforms = resolveUniforms$1(checker, root); let mapping = [...deps.graph.entries()].map(([k, v]) => v.map((d) => [k, d])).flat(); let sorted = []; try { sorted = toposort(mapping).reverse(); } catch (e) { sorted = []; } let preFuncs = []; for (let s of deps.structs.values()) { let name = resolveStructName$1(s); let hasAnyProperty = false; let sp = deps.structsProps.get(name); let members = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; let type2 = checker.getTypeAtLocation(m); let translated = translateType$1(checker, type2); let preComment = ""; if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { preComment = `// `; } } if (preComment == "") { hasAnyProperty = true; } return new SourceNode( m.getStart(), m.getEnd(), `${preComment} ${translated} ${m.name.getText()}; ` ); }); let memberNames = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; checker.getTypeAtLocation(m); if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { return ""; } } return m.name.getText(); }).filter((m) => m != ""); let memberParams = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; let type2 = checker.getTypeAtLocation(m); let translated = translateType$1(checker, type2); if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { return ""; } } return translated + " " + m.name.getText(); }).filter((m) => m != ""); if (!hasAnyProperty) continue; preFuncs.push( new SourceNode(s.getStart(), s.getEnd(), [`struct ${name} { `, ...members, "\n};\n"]) ); if (name != "ShaderInput" && name != "ShaderOutput") { preFuncs.push( new SourceNode(s.getStart(), s.getEnd(), [ name + " _make_struct_" + name + "(", memberParams.join(", ") + ")", " {\n", name, " _s;", "", ...memberNames.map((m) => ` _s.${m} = ${m}; `), " return _s;\n", "}\n" ]) ); } } for (let u of uniforms) { if (isUniformable$1(checker, u)) { let _type = checker.getTypeAtLocation(u); let translated = translateType$1(checker, _type); let isGlobalVar = isRootNode$1(u); let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`; if (translated.includes("[]")) { translated = translated.replace(/\[\]$/, ``); preFuncs.push( new SourceNode(u.getStart(), u.getEnd(), [ "uniform ", "int", " ", glslVarName, "_size;\n" ]) ); glslVarName += `[%${glslVarName}_size%]`; } preFuncs.push( new SourceNode(u.getStart(), u.getEnd(), ["uniform ", translated, " ", glslVarName, ";\n"]) ); if (translated == "sampler2D") { preFuncs.push( new SourceNode(u.getStart(), u.getEnd(), ["uniform vec2 ", glslVarName, "_size;\n"]) ); } } } for (let k of sorted) { if (k == "main") continue; let v = deps.functions.get(k); if (v) { let sourceFile2 = v.getSourceFile(); let originalFile2 = env2.files.find((f) => f.path == sourceFile2.fileName); preFuncs.push( compile$2( { parentFunction: v, checker, composed: deps.composed.get(k) ?? null }, v, originalFile2?.mapping ) ); } } let sourceFile = root.getSourceFile(); let originalFile = env2.files.find((f) => f.path == sourceFile?.fileName); let main = compile$2( { checker }, root, originalFile.mapping ); preFuncs.push(main); let source = new SourceNode(root.getStart(), root.getEnd(), preFuncs); let ss = { indexMapping: [], str: "" }; source.toString(ss); let matches = glslHeader.match(/^([a-zA-Z_][a-zA-Z0-9_]+ [^\(]+)/gm); let finalShaderOutput = ss.str; let headerSplits = []; for (let i = 0; i < matches.length; i++) { let index = glslHeader.indexOf(matches[i]); let toIndex = i == matches.length - 1 ? glslHeader.length : glslHeader.indexOf(matches[i + 1]); headerSplits.push(glslHeader.substring(index, toIndex)); } let realHeader = ""; for (let i = 0; i < headerSplits.length; i++) { let headerText = headerSplits[i]; let fnName = headerText.match(/^[a-zA-Z_][a-zA-Z0-9_]+ ([^\(]+)/)?.[1]; if (fnName) { if (finalShaderOutput.includes(fnName)) { realHeader += headerText; } } } finalShaderOutput = realHeader + finalShaderOutput; let output = new GLSLShader(`shd_${key}`, finalShaderOutput); output.sourceMapping = ss.indexMapping; for (let u of uniforms) { if (isUniformable$1(checker, u)) { let name = u.name.getText(); let isGlobalVar = isRootNode$1(u); if (name) { let filterProps = function(props) { if (props && props.name) { let sp = deps.structsProps.get(props.name); let realStruct = deps.structs.get(props.name); if (props.type == "struct" && realStruct) { for (let f of Object.keys(props.fields)) { if (!sp || !sp.has(f)) { delete props.fields[f]; } else { if (props.fields[f].type == "struct") { props.fields[f] = filterProps(props.fields[f]); } } } } } return props; }; let typeOut = getDeclarationType$1(checker, u); let typeNode = checker.getTypeAtLocation(u); let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { resolveStructName$1(decl); } if (isGlobalVar) { output.globals[name] = { fileName: getNodeSourceFileName$1(u), structure: filterProps(translateType$1(checker, typeOut, true)) }; } else { output.locals[name] = filterProps(translateType$1(checker, typeOut, true)); } } } } return output; } function getNodeSourceFileName$1(node2) { let found = closest(node2, (n) => ts.isSourceFile(n)); if (found && ts.isSourceFile(found)) { return found.fileName; } else { return ""; } } function walkNodes$2(node2, cb) { cb(node2); node2.forEachChild((n) => walkNodes$2(n, cb)); } function walkNodesWithCalls$1(checker, node2, cb) { cb(node2); node2.forEachChild((n) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let signature = checker.getResolvedSignature(node2); let mapping = findRealSignatureMappingToGLSL(checker, signature) ?? findSignatureMappingToGLSL(checker, exprSmybol); if (mapping === null) { if (funcDeclar.body) { walkNodesWithCalls$1(checker, funcDeclar.body, cb); } } } } } walkNodesWithCalls$1(checker, n, cb); }); } function findSignatureMappingToGLSL(checker, sym) { let matcher = /=(?:glsl|univ)\((.+)\)$/g; if (!sym.valueDeclaration) return null; let doc = ts.getJSDocTags(sym.valueDeclaration); for (let d of doc) { if (d.tagName.text !== "shadeup") continue; if (typeof d.comment === "string") { let matches = matcher.exec(d.comment); if (matches) { return matches[1]; } } } return null; } function findRealSignatureMappingToGLSL(checker, sig) { let matcher = /=(?:glsl|univ)\((.+)\)$/g; let doc = ts.getJSDocTags(sig.getDeclaration()); for (let d of doc) { if (d.tagName.text !== "shadeup") continue; if (typeof d.comment === "string") { let matches = matcher.exec(d.comment); if (matches) { return matches[1]; } } } return null; } function removeDoubleUnderscores$1(str) { return str.replace(/__/g, "_ii"); } let { factory, isArrayTypeNode, isCallExpression, isIdentifier, isPropertyAccessChain, isPropertyAccessExpression } = ts; const TYPE_BLACKLIST = [ "never", "object", "symbol", "bigint", "undefined", "null", "map", "string" ]; const RESERVED_WORDS = [ "this", "target", "attribute", "sample", "varying", "uniform", "layout", "delete" ]; function generateDefaultForType$1(checker, _type_node) { let _type = checker.getTypeFromTypeNode(_type_node); let name = (_type.aliasSymbol || _type.getSymbol())?.escapedName.toString(); switch (name) { case "int": return "i32(0)"; case "float": return "f32(0.0)"; case "float2": return "vec2(0.0, 0.0)"; case "float3": return "vec3(0.0, 0.0, 0.0)"; case "float4": return "vec4(0.0, 0.0, 0.0, 0.0)"; case "int2": return "vec2(0, 0)"; case "int3": return "vec3(0, 0, 0)"; case "int4": return "vec4(0, 0, 0, 0)"; case "uint": return "u32(0)"; case "uint2": return "vec2(0, 0)"; case "uint3": return "vec3(0, 0, 0)"; case "uint4": return "vec4(0, 0, 0, 0)"; case "float2x2": return "mat2x2(0.0, 0.0, 0.0, 0.0)"; case "float3x3": return "mat3x3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "float4x4": return "mat4x4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "bool": return "0"; default: let decl = _type.getSymbol()?.getDeclarations(); if (ts.isTupleTypeNode(_type_node)) { let len = _type_node.elements.length; let args = []; let rootNode = _type_node.elements[0]; if (rootNode) { for (let i = 0; i < len; i++) { args.push(generateDefaultForType$1(checker, _type_node.elements[i])); } let rootType = checker.getTypeFromTypeNode(rootNode); return translateType(checker, rootType) + `[${len}] {` + args.join(", ") + "}"; } else { return "0"; } } if (decl && decl.length > 0) { let d = decl[0]; let structProps = []; if (ts.isClassDeclaration(d)) { let symd = _type.getSymbol(); symd?.members?.forEach((v, k) => { let decl2 = v.valueDeclaration; if (decl2 && ts.isPropertyDeclaration(decl2)) { structProps.push([k?.toString() ?? "", decl2.type]); } }); let sortedPropsByKey = structProps.sort((a, b) => { return a[0].localeCompare(b[0]); }); let args = sortedPropsByKey.map((p) => { return "/* " + p[0] + ": */ " + generateDefaultForType$1(checker, p[1]) + "\n"; }); return "_make_struct_" + resolveStructName(d) + "(\n" + args.join(", ") + "\n)"; } else { return "0"; } } else { return "0"; } } } function getTypeFallback$1(checker, t) { let n = (t.aliasSymbol || t.getSymbol())?.escapedName; if (!n && t.intrinsicName) n = t.intrinsicName; if (typeof n !== "string") { let props = t.getApparentProperties(); if (props.length > 0) { for (let p of props) { if (p.escapedName.toString() === "_opaque_int") return "int"; if (p.escapedName.toString() === "_opaque_float") return "float"; if (p.escapedName.toString() === "_opaque_uint") return "uint"; } } let btype = t.getBaseTypes(); if (btype && btype.length > 0) { for (let b of btype) { let tn = getTypeFallback$1(checker, b); if (tn) return tn; } return null; } } else { return n; } } function followTypeReferences(t) { if (t.flags & ts.TypeFlags.Object && t.objectFlags & ts.ObjectFlags.Reference) { if (t.target === t) { return t; } return followTypeReferences(t.target); } else { return t; } } function getArrayTypeInfo(checker, t) { let n = getTypeFallback$1(checker, t); let originalType = t; if (n === void 0) { t = followTypeReferences(t); } let isArray = false; let staticSize = -1; let elementType = ""; if (n === "Array" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); let translated = translateType(checker, args[0]); if (tsutils.isTupleType(t)) { staticSize = t.fixedLength; } checker.typeToString(typeRef); isArray = true; elementType = translated; } return { isArray, staticSize, elementType }; } function translateType(checker, t, templateFormat = false, usedInsidePotentiallyExternalType = false) { let n = getTypeFallback$1(checker, t); let originalType = t; if (n === void 0) { t = followTypeReferences(t); } if (templateFormat) { let name = n?.toString() ?? "unknown"; if (name === "Array" || name === "array" || name === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); return { type: name == "buffer" ? "buffer" : "array", element: translateType(checker, args[0], true), staticSize: args.length }; } if (name == "boolean" || name == "false" || name == "true") name = "bool"; if (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint") || name == "bool" || name == "texture2d" || name == "texture3d") return { type: "primitive", name }; if (name == "atomic") { let args = t.typeArguments || checker.getTypeArguments(t); let translated = translateType(checker, args[0]); return { type: "primitive", name, element: translated }; } let symbol = t.aliasSymbol || t.getSymbol(); if (symbol && symbol.declarations && symbol.declarations.length > 0) { if (ts.isClassDeclaration(symbol.declarations[0])) { let fields = []; let decl = symbol.declarations[0]; for (let member of decl.members) { if (ts.isPropertyDeclaration(member)) { let name2 = member.name.getText(); let type2 = checker.getTypeFromTypeNode(member.type); fields.push([name2, translateType(checker, type2, true)]); } } return { type: "struct", name: resolveStructName(decl), fields }; } else { return { type: "unknown" }; } } } else { if (n === "Array" || n === "array" || n === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = originalType; let args = typeRef.typeArguments || checker.getTypeArguments(typeRef); let translated = translateType(checker, args[0]); let typeInfo = getWGSLTypeInfo(translated); let toStringed = checker.typeToString(typeRef); if (n == "buffer") { return `array<${translated}>`; } if (typeInfo.needsAlignment) { translated = `vec4<${typeInfo.elementType ?? "f32"}>`; } if (toStringed.endsWith("[]")) { return "array<" + translated + ">"; } else { let arraySize = 0; if (tsutils.isTupleType(t)) { arraySize = t.fixedLength; } return "array<" + translated + ", " + arraySize + ">"; } } if (n === "texture2d") return `sampler`; if (n == "atomic") { let args = t.typeArguments || checker.getTypeArguments(t); let translated = translateType(checker, args[0]); return `atomic<${translated}>`; } if (n === "bool") return "bool"; if (n === "boolean") return "bool"; if (n === "uint8") return "f32"; if (n === "float") return "f32"; if (n === "float2") return "vec2"; if (n === "float3") return "vec3"; if (n === "float4") return "vec4"; if (n === "int") return "i32"; if (n === "int2") return "vec2"; if (n === "int3") return "vec3"; if (n === "int4") return "vec4"; if (n === "uint") return "u32"; if (n === "uint2") return "vec2"; if (n === "uint3") return "vec3"; if (n === "uint4") return "vec4"; if (n === "float2x2") return "mat2x2"; if (n === "float3x3") return "mat3x3"; if (n === "float4x4") return "mat4x4"; if (n === "void") return "void"; if (n === "error") return "void"; if (t.isUnion()) { let types2 = t.types.map((t2) => translateType(checker, t2)); for (let sub of types2) { if (sub && sub !== "void" && sub !== "undefined") return sub; } } let symbol = t.aliasSymbol || t.getSymbol(); if (symbol && symbol.declarations && symbol.declarations.length > 0) { if (ts.isClassDeclaration(symbol.declarations[0])) { return resolveStructName(symbol.declarations[0]); } else { return n?.toString() ?? "void"; } } else { return n?.toString() ?? "void"; } } } function isTypeNameVector(name) { if (name == "float2" || name == "float3" || name == "float4" || name == "int2" || name == "int3" || name == "int4" || name == "uint2" || name == "uint3" || name == "uint4") { return true; } return false; } function getTypeNameVectorElementType(name) { if (name == "float") { return ["float", 1]; } if (name == "int") { return ["int", 1]; } if (name == "uint") { return ["uint", 1]; } if (name.startsWith("float")) { return ["float", parseInt(name.substring(5))]; } if (name.startsWith("int")) { return ["int", parseInt(name.substring(3))]; } if (name.startsWith("uint")) { return ["uint", parseInt(name.substring(4))]; } if (name.startsWith("f32")) { return ["f32", 1]; } if (name.startsWith("i32")) { return ["i32", 1]; } if (name.startsWith("u32")) { return ["u32", 1]; } if (name.endsWith("")) { return ["float", parseInt(name.substring(3, 4))]; } if (name.endsWith("")) { return ["int", parseInt(name.substring(3, 4))]; } if (name.endsWith("")) { return ["uint", parseInt(name.substring(3, 4))]; } return ["", 0]; } function getTypeNameVectorElementTypeWGSL(name) { if (name == "f32") { return ["f32", 1]; } if (name == "i32") { return ["i32", 1]; } if (name == "u32") { return ["u32", 1]; } if (name.endsWith("")) { return ["f32", parseInt(name.substring(3, 4))]; } if (name.endsWith("")) { return ["i32", parseInt(name.substring(3, 4))]; } if (name.endsWith("")) { return ["u32", parseInt(name.substring(3, 4))]; } return ["", 0]; } function isTranslatedTypeNameVectorOrScalar(name) { if (name == "float" || name == "int" || name == "uint") return true; if (name.endsWith("") || name.endsWith("") || name.endsWith("")) { if (name.startsWith("vec2") || name.startsWith("vec3") || name.startsWith("vec4")) { return true; } return true; } return false; } function getWGSLTypeInfo(name) { switch (name) { case "bool": return { type: "bool", length: 1, size: 1, needsAlignment: true, elementType: "i32" }; case "u32": return { type: "integer", length: 1, signed: false, size: 4, needsAlignment: true, elementType: "u32" }; case "i32": return { type: "integer", length: 1, signed: true, size: 4, needsAlignment: true, elementType: "i32" }; case "f32": return { type: "float", length: 1, size: 4, needsAlignment: true, elementType: "f32" }; case "vec2": return { type: "vector", length: 2, element: "float", size: 8, needsAlignment: true, elementType: "f32" }; case "vec3": return { type: "vector", length: 3, element: "float", size: 12, needsAlignment: true, elementType: "f32" }; case "vec4": return { type: "vector", length: 4, element: "float", size: 16, needsAlignment: false, elementType: "f32" }; case "vec2": return { type: "vector", length: 2, signed: true, element: "integer", size: 8, needsAlignment: true, elementType: "i32" }; case "vec3": return { type: "vector", length: 3, signed: true, element: "integer", size: 12, needsAlignment: true, elementType: "i32" }; case "vec4": return { type: "vector", length: 4, signed: true, element: "integer", size: 16, needsAlignment: false, elementType: "i32" }; case "vec2": return { type: "vector", length: 2, signed: false, element: "integer", size: 8, needsAlignment: true, elementType: "u32" }; case "vec3": return { type: "vector", length: 3, signed: false, element: "integer", size: 12, needsAlignment: true, elementType: "u32" }; case "vec4": return { type: "vector", length: 4, signed: false, element: "integer", size: 16, needsAlignment: false, elementType: "u32" }; case "mat2x2": return { type: "matrix", element: "float", size: 16, needsAlignment: false }; case "mat3x3": return { type: "matrix", element: "float", size: 36, needsAlignment: false }; case "mat4x4": return { type: "matrix", element: "float", size: 64, needsAlignment: false }; default: return { type: "unknown", size: 0, needsAlignment: false }; } } function isVector(checker, t) { let name = getTypeFallback$1(checker, t); if (name) { return isTypeNameVector(name); } return false; } function getVectorElementType(checker, t) { let name = getTypeFallback$1(checker, t); if (name) { return getTypeNameVectorElementType(name); } return ["", 0]; } function isNumeric(checker, t) { let name = getTypeFallback$1(checker, t); if (name && (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint"))) { return true; } return false; } function escapeIdentifier(id) { if (RESERVED_WORDS.includes(id)) { return "_" + id; } return id.replaceAll("___", "_ii_").replaceAll("__", "_i_"); } function isAssignableType(t) { return !(t.startsWith("texture") || t.startsWith("sampler") || t.startsWith("buffer")); } function isGLSLType(name) { return name.startsWith("vec") || name.startsWith("mat") || name.startsWith("sampler") || name.startsWith("texture") || name == "bool" || name == "f32" || name == "i32" || name == "void"; } function autoCastNumeric(value, input, expected, node2) { let inputType = getTypeNameVectorElementTypeWGSL(input); let expectedType = getTypeNameVectorElementTypeWGSL(expected); if (inputType[0] !== "" && expectedType[0] !== "") { if (inputType[0] != expectedType[0]) { if (expectedType[1] == 1) { if (typeof expectedType[0] == "string" && expectedType[0].startsWith("vector")) { return new SourceNode(value.startIndex, value.endIndex, [value]); } else { if (inputType[0] == "u32") { throw new GLSLCompilationError(`Cannot cast uint to ${expectedType[0]}`, node2); } if (expectedType[0] == "i32") ; return new SourceNode(value.startIndex, value.endIndex, [ `${expectedType[0]}(`, value, `)` ]); } } else { if (inputType[0] == "u32") { throw new GLSLCompilationError(`Cannot cast uint to ${expectedType[0]}`, node2); } return new SourceNode(value.startIndex, value.endIndex, [ `vec${expectedType[1]}<${expectedType[0]}>(`, value, `)` ]); } } } return value; } function isUniformAccess(ctx, expr) { if (isCallExpression(expr)) { expr = expr.expression; } let id = null; if (ts.isIdentifier(expr)) { id = expr; } if (isPropertyAccessExpression(expr)) { let chain = expr; while (chain.expression) { if (ts.isPropertyAccessExpression(chain.expression)) { chain = chain.expression; } else { break; } } id = chain.expression; } if (id) { if (ts.isIdentifier(id)) { let sym = ctx.checker.getSymbolAtLocation(id); if (sym && sym.flags & ts.SymbolFlags.Alias) { sym = ctx.checker.getAliasedSymbol(sym); } if (sym?.declarations?.length == 1) { let decl = sym.declarations[0]; if (isUniformable(ctx.checker, decl)) { if (isVariableDeclarationValue(ctx.checker, decl)) { if (!isInSameScope(decl, id)) { if (!isInShader$1(decl)) { return true; } } } } } } } return false; } function accessWrap(ctx, expr, inner) { if (isPropertyAccessExpression(expr)) { let chain = expr; while (chain.expression) { if (ts.isPropertyAccessExpression(chain.expression)) { chain = chain.expression; } else { break; } } let id = chain.expression; if (ts.isIdentifier(id)) { let sym = ctx.checker.getSymbolAtLocation(id); if (sym && sym.flags & ts.SymbolFlags.Alias) { sym = ctx.checker.getAliasedSymbol(sym); } if (sym?.declarations?.length == 1) { let decl = sym.declarations[0]; if (isUniformable(ctx.checker, decl)) { if (isVariableDeclarationValue(ctx.checker, decl)) { if (!isInSameScope(decl, chain.expression)) { if (!isInShader$1(decl)) { let outputType = ctx.checker.getTypeAtLocation(expr); let isBooleanAccess = false; if (isArrayType$1(outputType, ctx.checker)) { let typeRef = outputType; let args = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef); let t = args[0]; let n = getTypeFallback$1(ctx.checker, t); if (n == "boolean" || n == "bool") { isBooleanAccess = true; } } else { let n = getTypeFallback$1(ctx.checker, outputType); if (n == "boolean" || n == "bool") { isBooleanAccess = true; } } if (isBooleanAccess) { return new SourceNode(inner.startIndex, inner.endIndex, [`((`, inner, `) == 1)`]); } } } } } } } } return inner; } function getVectorMask(num) { let outMask = ""; let comps = ["x", "y", "z", "w"]; for (let i = 0; i < num; i++) { outMask += comps[i]; } return outMask; } function convertConciseBodyToBlock(body) { if (ts.isBlock(body)) { return body; } else { return ts.factory.createBlock([ts.factory.createReturnStatement(body)]); } } function getRealReturnType(checker, call) { let fnCallSignature = checker.getResolvedSignature(call); return fnCallSignature.getReturnType(); } function augmentParameter(checker, p) { const type2 = checker.getTypeAtLocation(p); const tt = translateType(checker, type2); if (tt == "sampler") { const args = checker.getTypeArguments(type2); let innerType = "f32"; if (args && args.length > 0) { let [et, _] = getVectorElementType(checker, args[0]); innerType = { float: "f32", int: "i32", uint: "u32" }[et]; } return [ new SourceNode(p.getStart(), p.getEnd(), [ p.name.getText() + "_texture: texture_2d<" + innerType + ">" ]) ]; } return []; } function augmentArgument(ctx, arg) { let type2 = ctx.checker.getTypeAtLocation(arg); let tt = translateType(ctx.checker, type2); if (tt == "sampler") { let args = ctx.checker.getTypeArguments(type2); if (args && args.length > 0) { getVectorElementType(ctx.checker, args[0]); } return [new SourceNode(arg.getStart(), arg.getEnd(), [compile$1(ctx, arg), "_texture"])]; } return []; } function compile$1(ctx, ast, originalMapping) { function c2(ast2) { if (!ast2) { return s([]); } return compile$1(ctx, ast2); } function cplain(ast2) { if (!ast2) { return s([]); } return compile$1( { checker: ctx.checker, parentFunction: ctx.parentFunction }, ast2 ); } function s(c22) { if (originalMapping) { let reverseMapped = lookupIndexMappingRange(originalMapping, ast.getStart(), ast.getEnd()); return new SourceNode(reverseMapped.start, reverseMapped.end, c22); } else { return new SourceNode(0, 0, c22); } } function join(c22, sep) { return c22.reduce((acc, cur) => { if (acc.length === 0) { return [cur]; } return [...acc, sep, cur]; }, []); } function children() { return ast.getChildren().map((child) => c2(child)); } let prefixFunctions = []; if (ctx.composed) { if (ts.isMethodDeclaration(ast) || ts.isFunctionDeclaration(ast)) { for (let [i, arg] of ctx.composed.arguments.entries()) { if (ts.isArrowFunction(arg)) { let paramFromIndex = ast.parameters[i]; let name = paramFromIndex.name.getText() + "_composed_" + arg.pos + "_arg_" + i; let signature = ctx.checker.getSignatureFromDeclaration(arg); let returnType = signature.getReturnType(); let vars = getClosureVars(ctx.checker, arg); let vvv = vars.map((p) => { let tt = translateType(ctx.checker, ctx.checker.getTypeAtLocation(p.declarations[0])); return s([p.escapedName, isAssignableType(tt) ? "_const" : "", ": ", tt]); }); let joins = join( [ ...arg.parameters.map((p) => { let aug = augmentParameter(ctx.checker, p); return [cplain(p), ...aug]; }).flat(), ...vvv ], ", " ); let returnStr = " -> " + translateType(ctx.checker, returnType); if (returnStr == " -> void") returnStr = ""; prefixFunctions.push( s([ "fn ", name, "(", ...joins, ")", returnStr, " {\n", ...vars.filter((p) => { let type2 = ctx.checker.getTypeAtLocation(p.declarations[0]); let tt = translateType(ctx.checker, type2); return isAssignableType(tt); }).map((p) => { return s([ "var ", p.escapedName.toString(), " = ", p.escapedName.toString(), "_const;\n" ]); }), ...arg.parameters.filter((p) => { let type2 = ctx.checker.getTypeAtLocation(p.type); let tt = translateType(ctx.checker, type2); return isAssignableType(tt); }).map((p) => { return s(["var ", p.name.getText(), " = ", p.name.getText(), "_const;\n"]); }), ...convertConciseBodyToBlock(arg.body).statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]) ); } } } } function autoCastParameter(callExpr, argIndex) { let signature = ctx.checker.getResolvedSignature(callExpr); let params = signature.getParameters(); let param = params[argIndex]; let paramType = ctx.checker.getTypeOfSymbolAtLocation(param, callExpr); let paramTypeString = translateType(ctx.checker, paramType); let arg = callExpr.arguments[argIndex]; let argType = ctx.checker.getTypeAtLocation(arg); let argTypeString = translateType(ctx.checker, argType); if (paramTypeString !== argTypeString) { return autoCastNumeric(c2(arg), argTypeString, paramTypeString, arg); } return s([c2(arg)]); } switch (ast.kind) { case ts.SyntaxKind.FirstPunctuation: return s([ast.getText()]); case ts.SyntaxKind.SyntaxList: return s(children()); case ts.SyntaxKind.SourceFile: return s(children()); case ts.SyntaxKind.BreakStatement: return s(["break;"]); case ts.SyntaxKind.ContinueStatement: return s(["continue;"]); case ts.SyntaxKind.MethodDeclaration: let fnDeclar = ast; let fnName = resolveFunctionName(fnDeclar); if (ctx.composed) { fnName = fnName + "_composed_" + ctx.composed.pos; } let isStatic = false; let signature = ctx.checker.getSignatureFromDeclaration(fnDeclar); if (ts.canHaveModifiers(fnDeclar)) { let mods = ts.getModifiers(fnDeclar); if (mods) { if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) { isStatic = true; } } } let returnType = signature.getReturnType(); let returnStr = " -> " + translateType(ctx.checker, returnType); if (returnStr == " -> void") returnStr = ""; return s([ ...prefixFunctions, "fn ", fnName, "(", ...join( [ ...isStatic ? [] : [ "_this: " + translateType(ctx.checker, ctx.checker.getTypeAtLocation(fnDeclar.parent)) ], ...fnDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map((p) => { const o = c2(p); const aug = augmentParameter(ctx.checker, p); return [o, ...aug]; }).flat() ], ", " ), ")", returnStr, " {\n", ...fnDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map( (p) => s([ "var ", escapeIdentifier(p.name.getText()), " = ", escapeIdentifier(p.name.getText()), "_const;\n" ]) ), ...fnDeclar.body?.statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]); case ts.SyntaxKind.FunctionDeclaration: let mthdDeclar = ast; let mthdsignature = ctx.checker.getSignatureFromDeclaration(mthdDeclar); let mthdreturnType = mthdsignature.getReturnType(); let mthdName = resolveFunctionName(mthdDeclar); if (ctx.composed) { mthdName = mthdName + "_composed_" + ctx.composed.pos; } let returnStrMethod = " -> " + translateType(ctx.checker, mthdreturnType); if (returnStrMethod == " -> void") returnStrMethod = ""; return s([ ...prefixFunctions, "fn ", mthdName, "(", ...join( mthdDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } return true; }).map((p) => { const o = c2(p); const aug = augmentParameter(ctx.checker, p); return [o, ...aug]; }).flat(), ", " ), ")", returnStrMethod, " {\n", ...mthdDeclar.parameters.filter((p) => { let type22 = ctx.checker.getTypeAtLocation(p); if (type22.getCallSignatures().length > 0) { return false; } let tt2 = translateType(ctx.checker, type22); return isAssignableType(tt2); }).map( (p) => s([ "var ", escapeIdentifier(p.name.getText()), " = ", escapeIdentifier(p.name.getText()), "_const;\n" ]) ), ...mthdDeclar.body?.statements.map((s2) => c2(s2)) ?? [], "\n}\n\n" ]); case ts.SyntaxKind.ReturnStatement: let ret = ast; if (!ctx.parentFunction) { if (ret.expression) { return s(["return ", c2(ret.expression), ";\n"]); } else { return s(["return;\n"]); } } else { let expectedReturnType = ctx.checker.getSignatureFromDeclaration(ctx.parentFunction).getReturnType(); let actualReturnType = ctx.checker.getTypeAtLocation(ret.expression); if (ret.expression) { let sss = s([ "return ", autoCastNumeric( c2(ret.expression), translateType(ctx.checker, actualReturnType), translateType(ctx.checker, expectedReturnType), ret.expression ), ";\n" ]); return sss; } else { return s(["return;\n"]); } } case ts.SyntaxKind.AsExpression: let asExpr = ast; return c2(asExpr.expression); case ts.SyntaxKind.Parameter: let param = ast; if (ctx.composed) { let indexOf = param.parent.parameters.indexOf(param); let expr2 = ctx.composed.arguments[indexOf]; if (expr2) { if (ts.isArrowFunction(expr2)) { let vars = getClosureVars(ctx.checker, expr2.body); let closureVars = vars.map((v) => { return s([ v.name, ": ", translateType(ctx.checker, ctx.checker.getTypeAtLocation(v.valueDeclaration)) ]); }); return s(join(closureVars, ", ")); } } } const tt = translateType(ctx.checker, ctx.checker.getTypeAtLocation(param)); return s([ escapeIdentifier(param.name.getText()), isAssignableType(tt) ? "_const" : "", ": ", tt ]); case ts.SyntaxKind.ArrowFunction: let arrow = ast; let body = convertConciseBodyToBlock(arrow.body); let preMain = ""; if (ctx.isComputeShader) { preMain = ` @compute @workgroup_size(${ctx.computeSize[0]}, ${ctx.computeSize[1]}, ${ctx.computeSize[2]})`; } return s([ "\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/" + preMain + "\nfn main(/*__SHADEUP_TEMPLATE_INPUT*/)" + (ctx.isComputeShader ? "" : "-> /*__SHADEUP_TEMPLATE_OUTPUT*/") + "{\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/\n", ...body.statements.filter((s2) => !ts.isFunctionDeclaration(s2)).map((s2) => c2(s2)), "\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/\n}\n" ]); case ts.SyntaxKind.VariableStatement: let varStatement = ast; return s([ ...join( varStatement.declarationList.declarations.map((d) => c2(d)), ", " ), ";\n" ]); case ts.SyntaxKind.VariableDeclaration: let varDecl = ast; let type2 = ctx.checker.getTypeAtLocation(varDecl); let fullText = varDecl.getSourceFile().getFullText(); let fullStart = varDecl.getFullStart(); let prefix = `// @workgroup `; let mySelf = fullText.slice(fullStart - prefix.length, fullStart); if (mySelf.includes("@workgroup")) { return s([]); } else { let translated = translateType(ctx.checker, type2); if (translated.startsWith("array")) { translated = ""; } if (isInShader$1(varDecl)) { let arrType = ctx.checker.getTypeAtLocation(varDecl); let typeInfo = getArrayTypeInfo(ctx.checker, arrType); if (typeInfo.isArray) { if (typeInfo.staticSize <= 0) { throw new GLSLCompilationError( "Cannot declare an array without a static size in a shader", varDecl ); } } } let initializerVal = c2(varDecl.initializer); if (translated) { let leftType2 = type2; let rightType2 = ctx.checker.getTypeAtLocation(varDecl.initializer); if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) { let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2); let [rightElementType, rightElementSize] = getVectorElementType(ctx.checker, rightType2); if (leftElementType != rightElementType) { if (leftElementType == "float" && rightElementType == "int") { initializerVal = s([`vec${leftElementSize}f(`, initializerVal, ")"]); } else if (leftElementType == "int" && rightElementType == "float") { initializerVal = s([`vec${leftElementSize}i(`, initializerVal, ")"]); } } } if (isNumeric(ctx.checker, leftType2) && isNumeric(ctx.checker, rightType2)) { let leftTypeStr = translateType(ctx.checker, leftType2); let rightTypeStr = translateType(ctx.checker, rightType2); if (leftTypeStr != rightTypeStr) { initializerVal = s([ autoCastNumeric(initializerVal, rightTypeStr, leftTypeStr, varDecl.initializer) ]); } } } if (translated == "___atomic_compare_exchange_result") { translated = ""; } return s([ "var ", escapeIdentifier(varDecl.name.getText()), translated ? ": " : "", translated, " = ", initializerVal ]); } case ts.SyntaxKind.CallExpression: let call = ast; let exprSmybol = ctx.checker.getSymbolAtLocation(call.expression); if (call.expression.getText() == "Math.random") { return s(["0.0"]); } if (!exprSmybol) { return s(["/* TODO: Unknown symbol */"]); } if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = ctx.checker.getAliasedSymbol(exprSmybol); } let symName = exprSmybol?.getName() ?? call.expression.getText(); if (ts.isIdentifier(call.expression)) { if (isUniformAccess(ctx, call.expression)) { let typ = ctx.checker.getTypeAtLocation(call.expression); if (typ.getSymbol().getName().startsWith("shader") || typ.aliasSymbol && typ.aliasSymbol.getName() == "shader") { console.log("Uniform access to shader", typ.getSymbol().getName()); } } } if (symName == "__index") { let postfix2 = ""; let t2 = ctx.checker.getTypeAtLocation( call.expression.expression ); isUniformAccess( ctx, call.expression.expression ); if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); let returnType2 = getRealReturnType(ctx.checker, call); let vecOut = getVectorElementType(ctx.checker, returnType2); let outMask = getVectorMask(vecOut[1]); if (innerType == "sampler") { if (ts.isCallExpression(call.expression.expression)) { let callIndex = call.expression.expression; return s([ "textureLoad(", c2(callIndex.expression), "_texture, ", ...join([...callIndex.arguments.map((a) => c2(a))], ","), ", vec2(", c2(call.arguments[0]), "), 0)." + outMask ]); } else { return s([ "textureLoad(", c2(call.expression.expression), "_texture, vec2(", c2(call.arguments[0]), "), 0)." + outMask ]); } } } let translatedOut = translateType(ctx.checker, ctx.checker.getTypeAtLocation(call)); if (isArrayType$1(t2, ctx.checker) && isUniformAccess(ctx, call.expression.expression) && !translatedOut.startsWith("mat")) { let typeRef = t2; let args2 = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef); let translated = translateType(ctx.checker, args2[0]); let typeInfo = getWGSLTypeInfo(translated); if (typeInfo.needsAlignment) { translated = `vec4<${typeInfo.elementType ?? "f32"}>`; } let lengths = { 1: "x", 2: "xy", 3: "xyz", 4: "xyzw" }; if (typeInfo.type != "unknown") { postfix2 = `.${lengths[typeInfo.length ?? 1]}`; } } return accessWrap( ctx, call.expression.expression, s([c2(call.expression), "[", c2(call.arguments[0]), "]", postfix2]) ); } else if (symName == "attr") { let expr2 = call.expression; if (ts.isPropertyAccessExpression(expr2)) { let left2 = expr2.expression; let leftName = ctx.checker.getTypeAtLocation(left2).getSymbol()?.getName() ?? ""; if (leftName == "ShaderInput") { if (call.arguments.length >= 1) { let arg1 = call.arguments[0]; if (ts.isCallExpression(arg1)) { arg1 = arg1.arguments[0]; } if (!ts.isNumericLiteral(arg1)) { throw new GLSLCompilationError("Attribute index must be a number literal", arg1); } let index = parseInt(arg1.getText()); let interpMode = "perspective"; if (call.arguments.length >= 2) { let arg2 = call.arguments[1]; if (ts.isStringLiteral(arg2)) { interpMode = arg2.text; } } let valType = ""; if (call.typeArguments.length == 1) { valType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.typeArguments[0]) ); } ctx.addCustomAttribute("in", index, valType, interpMode); return s(["_i_in.custom", index.toString()]); } } else if (leftName == "ShaderOutput") { if (call.arguments.length >= 2) { let arg1 = call.arguments[0]; if (ts.isCallExpression(arg1)) { arg1 = arg1.arguments[0]; } if (!ts.isNumericLiteral(arg1)) { throw new GLSLCompilationError("Attribute index must be a number literal", arg1); } let index = parseInt(arg1.getText()); let interpMode = "perspective"; if (call.arguments.length >= 3) { let arg2 = call.arguments[2]; if (ts.isStringLiteral(arg2)) { interpMode = arg2.text; } } let valType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.arguments[1]) ); ctx.addCustomAttribute("out", index, valType, interpMode); return s(["_i_out.custom", index.toString(), " = ", c2(call.arguments[1])]); } } } } else if (symName == "len") { let expr2 = call.expression; if (ts.isPropertyAccessExpression(expr2)) { let left2 = expr2.expression; if (isUniformAccess(ctx, left2)) { return s(["_in_uniforms.", c2(left2), "_size"]); } else { let arrType = ctx.checker.getTypeAtLocation(left2); let typeInfo = getArrayTypeInfo(ctx.checker, arrType); return s([typeInfo.staticSize.toString()]); } } } else if (symName == "min" || symName == "max") { if (call.arguments.length > 2) { let args2 = call.arguments.map((a) => c2(a)); while (args2.length > 2) { let left2 = args2.shift(); let right2 = args2.shift(); args2.unshift(s([symName, "(", left2, ",", right2, ")"])); } return s([symName, "(", ...join(args2, ","), ")"]); } } else if (symName == "clamp") { if (call.arguments.length == 3) { let inType = ctx.checker.getTypeAtLocation(call.arguments[0]); let vType = translateType(ctx.checker, inType); let vTypeInfo = getWGSLTypeInfo(vType); if (vTypeInfo.type == "vector") { let minV = call.arguments[1]; let maxV = call.arguments[2]; let minType = ctx.checker.getTypeAtLocation(minV); let maxType = ctx.checker.getTypeAtLocation(maxV); let minTypeInfo = getWGSLTypeInfo(translateType(ctx.checker, minType)); let maxTypeInfo = getWGSLTypeInfo(translateType(ctx.checker, maxType)); if (minTypeInfo.type == "vector" && maxTypeInfo.type == "vector") ; else { let minStr = c2(minV); let maxStr = c2(maxV); if (minTypeInfo.type != "vector") { minStr = s([`vec${vTypeInfo.length}<${vTypeInfo.elementType}>(`, minStr, ")"]); } if (maxTypeInfo.type != "vector") { maxStr = s([`vec${vTypeInfo.length}<${vTypeInfo.elementType}>(`, maxStr, ")"]); } return s(["clamp(", c2(call.arguments[0]), ",", minStr, ",", maxStr, ")"]); } } } } else if (symName == "atomic") { throw new GLSLCompilationError( "Atomics cannot be constructed in shaders, create them outside or in a workgroup", call.expression ); } else if (symName == "sample") { if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); if (innerType == "sampler") { if (ts.isCallExpression(call.expression.expression)) { let callIndex = call.expression.expression; return s([ "textureSample(", c2(callIndex.expression), "_texture, ", c2(callIndex.expression), ",", "vec2(", c2(call.arguments[0]), "),", ...join([...callIndex.arguments.map((a) => c2(a))], ","), ")" ]); } else { return s([ "textureSample(", c2(call.expression.expression), "_texture, ", c2(call.expression.expression), ", vec2(", c2(call.arguments[0]), "))" ]); } } } } else if (symName == "__index_assign") { let postfix2 = ""; if (ts.isPropertyAccessExpression(call.expression)) { let innerType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.expression.expression) ); if (innerType == "sampler") { if (ts.isCallExpression(call.expression.expression)) { let callIndex = call.expression.expression; return s([ "textureStore(", c2(callIndex.expression), "_texture_write, ", ...join([...callIndex.arguments.map((a) => c2(a))], ","), ", vec2(", c2(call.arguments[0]), "), vec4(", autoCastParameter(call, 1), "))" ]); } else { return s([ "textureStore(", c2(call.expression.expression), "_texture_write, vec2(", c2(call.arguments[0]), "), vec4(", autoCastParameter(call, 1), "))" ]); } } } ctx.checker.getTypeAtLocation( call.expression.expression ); return accessWrap( ctx, call.expression.expression, s([ c2(call.expression.expression), "[", c2(call.arguments[0]), "]", postfix2, " = ", autoCastParameter(call, 1) ]) ); } else if (symName == "eq" && call.expression.getText() == "__.eq") { let leftArg = call.arguments[0]; let rightArg = call.arguments[1]; let leftType2 = ctx.checker.getTypeAtLocation(leftArg); let rightType2 = ctx.checker.getTypeAtLocation(rightArg); let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2); if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) { return s([ "squash_bool_vec", leftElementSize.toString(), "(", c2(leftArg), " == ", c2(rightArg), ")" ]); } } else if (symName == "rand" && call.arguments.length == 0 && call.expression.getText() == "rand") { throw new GLSLCompilationError( "rand() in shaders needs to be seeded, use rand(seed) instead", call ); } if (exprSmybol?.getName() == "makeVector" && exprSmybol.valueDeclaration) { if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) { let exprSig2 = ctx.checker.getResolvedSignature(call); if (exprSig2) { let returnType2 = ctx.checker.getReturnTypeOfSignature(exprSig2); let returnTypeStr = translateType(ctx.checker, returnType2); let returnTypeInfo = getWGSLTypeInfo(returnTypeStr); let callType = translateType(ctx.checker, returnType2); let argStrs = []; for (let [i, arg] of call.arguments.entries()) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeStr = translateType(ctx.checker, argType); let argTypeInfo = getWGSLTypeInfo(argTypeStr); let paramType = ctx.checker.getTypeAtLocation( exprSig2.parameters[i].getDeclarations()[0] ); let paramTypeStr = translateType(ctx.checker, paramType); if (argTypeInfo.elementType !== returnTypeInfo.elementType) { paramTypeStr = `vec${argTypeInfo.length}<${returnTypeInfo.elementType}>`; } argStrs.push(autoCastNumeric(c2(arg), argTypeStr, paramTypeStr, arg)); } return s([callType, "(", ...join(argStrs, ", "), ")"]); } } } if (exprSmybol?.getName() == "swizzle" && exprSmybol.valueDeclaration) { if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) { ctx.checker.getSignatureFromDeclaration(exprSmybol.valueDeclaration); let arg = call.arguments[0]; let arg2 = call.arguments[1]; let propAccess = ""; if (ts.isStringLiteral(arg2)) { propAccess = arg2.text; } let argType = ctx.checker.getTypeAtLocation(arg); if (isVector(ctx.checker, argType)) { if (call.arguments.length == 2) { return s([c2(arg), ".", propAccess]); } else { let t2 = s([ "var tempVal_", call.getStart().toString(), " = ", c2(call.arguments[2]), ";\n" ]); let assigns = []; for (let i = 0; i < propAccess.length; i++) { let char = propAccess[i]; assigns.push( s([ c2(arg), ".", char, " = ", "tempVal_", call.getStart().toString(), ...propAccess.length > 1 ? [".", char] : [], ";\n" ]) ); } return s([t2, ...assigns]); } } else if (isNumeric(ctx.checker, argType)) { let numericType = translateType(ctx.checker, argType); return s([`shadeup_up_swizzle_${propAccess}_${numericType}(`, c2(arg), ")"]); } else { return s([c2(arg), ".", propAccess]); } } } let mutations = { arguments: new Array(call.arguments.length) }; for (let [i, arg] of call.arguments.entries()) { mutations.arguments[i] = null; } if (exprSmybol?.getName() == "max" || exprSmybol?.getName() == "min") { let exprSig2 = ctx.checker.getResolvedSignature(call); if (exprSig2 && exprSig2.parameters.length == 2) { let skip = false; let unbalanced = false; let singleArg = -1; let targetLength = 0; let targetType = ""; for (let [i, arg] of call.arguments.entries()) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeStr = translateType(ctx.checker, argType); let argTypeInfo = getWGSLTypeInfo(argTypeStr); if (argTypeInfo.length === 1) { if (unbalanced) { skip = true; } unbalanced = true; singleArg = i; } } for (let [i, arg] of call.arguments.entries()) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeStr = translateType(ctx.checker, argType); let argTypeInfo = getWGSLTypeInfo(argTypeStr); if (argTypeInfo.length !== 1) { targetLength = argTypeInfo.length; targetType = argTypeInfo.elementType; } } if (!skip && unbalanced && singleArg !== -1) { mutations.arguments[singleArg] = s([ `vec${targetLength}<${targetType}>(`, c2(call.arguments[singleArg]), `)` ]); } } } let funcName = c2(call.expression); let callArgs = []; let preArgs = []; let exprSig = ctx.checker.getResolvedSignature(call); let exprDeclar = exprSig.getDeclaration(); if (exprDeclar) { if (ts.isMethodDeclaration(exprDeclar)) { let isStatic2 = false; if (ts.canHaveModifiers(exprDeclar)) { let mods = ts.getModifiers(exprDeclar); if (mods) { if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) { isStatic2 = true; } } } if (!isStatic2) { if (ts.isPropertyAccessExpression(call.expression)) { preArgs.push(c2(call.expression.expression)); } } } } exprSmybol.getName() + "("; for (let [i, arg] of call.arguments.entries()) { let argStr = c2(arg); if (exprSig) { let p = exprSig.getTypeParameterAtPosition(i); if (p) { let translatedBase = translateType(ctx.checker, p); let translatedPass = translateType(ctx.checker, ctx.checker.getTypeAtLocation(arg)); if (isTranslatedTypeNameVectorOrScalar(translatedPass)) { if (translatedBase != translatedPass && isGLSLType(translatedBase)) { if (translatedBase == "vector2" || translatedBase == "vector3" || translatedBase == "vector4") { argStr = argStr; } else { argStr = s([`${translatedBase}(`, argStr, `)`]); } } } } else { translateType(ctx.checker, ctx.checker.getTypeAtLocation(arg)); } } if (ts.isArrowFunction(arg)) { let arrow2 = arg; let vars = getClosureVars(ctx.checker, arrow2.body); if (vars.length > 0) callArgs.push(vars.map((v) => v.escapedName).join(", ")); } else { let augs = augmentArgument(ctx, arg); if (augs.length > 0) { argStr = s([argStr, ",", ...join(augs, ",")]); } callArgs.push(argStr); } } const levelCalls = { mix: true }; const constructs = { "vec2": true, "vec3": true, "vec4": true, "vec2": true, "vec3": true, "vec4": true, "vec2": true, "vec3": true, "vec4": true, "mat2x2": true, "mat3x3": true, "mat4x4": true, "mat2x2": true, "mat3x3": true, "mat4x4": true }; if (exprSmybol) { let mapping = findSignatureMappingToWGSL(ctx.checker, exprSmybol); if (mapping !== null) { let levelCastArguments = mapping.startsWith("!") || (levelCalls[mapping] ?? false) || (constructs[mapping] ?? false); if (levelCastArguments) { let minType = ""; let noOp = false; for (let arg of call.arguments) { let argType = ctx.checker.getTypeAtLocation(arg); let argTypeName = translateType(ctx.checker, argType); if (!(argTypeName == "f32" || argTypeName.endsWith("") || argTypeName == "i32" || argTypeName.endsWith(""))) { noOp = true; } if (minType == "") { if (argTypeName == "f32" || argTypeName.endsWith("")) { minType = "f32"; } else if (argTypeName == "i32" || argTypeName.endsWith("")) { minType = "i32"; } } else if (argTypeName == "f32" || minType.endsWith("")) { minType = "f32"; } } if (constructs[mapping]) { noOp = false; if (mapping.endsWith("")) { minType = "f32"; } else if (mapping.endsWith("")) { minType = "i32"; } } if (!noOp) { for (let i = 0; i < callArgs.length; i++) { let arg = call.arguments[i]; let argType = ctx.checker.getTypeAtLocation(arg); let argTypeName = translateType(ctx.checker, argType); let argTypeStripped = ""; if (argTypeName == "f32" || argTypeName.endsWith("")) { argTypeStripped = "f32"; } else if (argTypeName == "i32" || argTypeName.endsWith("")) { argTypeStripped = "i32"; } if (argTypeStripped != minType) { if (argTypeName.startsWith("f32") || argTypeName.startsWith("i32")) { callArgs[i] = s([`${minType}(`, callArgs[i], `)`]); } else if (argTypeName.endsWith("") || argTypeName.endsWith("")) { let len = argTypeName.match(/\d+/)?.[0]; if (len === void 0) { throw new Error("Invalid type"); } callArgs[i] = s([`vec${len}<${minType}>(`, callArgs[i], `)`]); } else ; } } } } else { let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration()); sig = exprSig; for (let i = 0; i < callArgs.length; i++) { let arg = call.arguments[i]; let argType = ctx.checker.getTypeAtLocation(arg); let paramType = ctx.checker.getTypeAtLocation( sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0] ); paramType = sig.getTypeParameterAtPosition(Math.min(i, sig.parameters.length - 1)) ?? paramType; let carg = c2(arg); let augs = augmentArgument(ctx, arg); if (augs.length > 0) { carg = s([carg, ",", ...join(augs, ",")]); } callArgs[i] = autoCastNumeric( carg, translateType(ctx.checker, argType), translateType(ctx.checker, paramType), arg ); } } if (mapping.startsWith("!")) { let template = mapping.slice(1); let outs = []; let argCounter = 0; let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration()); for (let i = 0; i < callArgs.length; i++) { let paramType = ctx.checker.getTypeAtLocation( sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0] ); template = template.replace( "`" + argCounter + "`", ctx.checker.typeToString(paramType) ); argCounter++; } let result = template.split("$"); for (let r of result) { if (/^\d+$/.test(r)) { outs.push(callArgs[parseInt(r)]); } else if (/^\[\d+\]$/.test(r)) { let templateType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(call.typeArguments[parseInt(r.slice(1, -1))]) ); outs.push(templateType); } else if (r == "self") { if (call.expression.kind == ts.SyntaxKind.PropertyAccessExpression) { let propAccess = call.expression; outs.push(c2(propAccess.getChildAt(0))); } else { outs.push(c2(call.expression)); } } else { outs.push(r); } } return s(outs); } else if (mapping.startsWith("#")) { let typeName = ""; if (call.arguments.length > 0) { let firstArg = call.arguments[0]; let firstArgType = ctx.checker.getTypeAtLocation(firstArg); typeName = ctx.checker.typeToString(firstArgType); } return s([ new SourceNode(call.expression.getStart(), call.expression.getEnd(), [ mapping.substring(1) + typeName ]), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } else { for (let [i, mutation] of mutations.arguments.entries()) { if (mutation) { callArgs[i] = mutation; } } return s([ new SourceNode(call.expression.getStart(), call.expression.getEnd(), [mapping]), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } else { let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration()); for (let i = 0; i < callArgs.length; i++) { let arg = call.arguments[i]; let argType = ctx.checker.getTypeAtLocation(arg); let paramType = ctx.checker.getTypeAtLocation(sig.parameters[i].getDeclarations()[0]); let carg = c2(arg); let augs = augmentArgument(ctx, arg); if (augs.length > 0) { carg = s([carg, ",", ...join(augs, ",")]); } callArgs[i] = autoCastNumeric( carg, translateType(ctx.checker, argType), translateType(ctx.checker, paramType), arg ); } } if (exprSmybol.declarations[0].parent) { let param2 = exprSmybol.declarations[0]; if (ts.isParameter(param2)) ; } let funcDeclar = exprSmybol.valueDeclaration; if (exprSmybol.declarations[0].parent) { let param2 = exprSmybol.declarations[0]; if (ts.isParameter(param2)) { let indexOf = param2.parent.parameters.indexOf(param2); let additionalArgs = []; if (ctx.composed) { let realAnonymousFunc = ctx.composed.arguments[indexOf]; if (ts.isArrowFunction(realAnonymousFunc)) { let vars = getClosureVars(ctx.checker, realAnonymousFunc.body); additionalArgs = vars.map((v) => v.escapedName); callArgs.push(...additionalArgs); return s([ funcName, "_composed_", realAnonymousFunc.pos.toString(), "_arg_", indexOf.toString(), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } } } if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { funcName = new SourceNode( call.expression.getStart(), call.expression.getEnd(), resolveFunctionName(funcDeclar) ); let parentDeclar = closest(ast, (n3) => ts.isFunctionDeclaration(n3)); if (parentDeclar && ts.isFunctionDeclaration(parentDeclar)) ; if (isComposedFunction(ctx.checker, funcDeclar)) { return s([ funcName, "_composed_", call.pos.toString(), "(", ...join([...preArgs, ...callArgs], ", "), ")" ]); } } } for (let [i, mutation] of mutations.arguments.entries()) { if (mutation) { callArgs[i] = mutation; } } return s([funcName, "(", ...join([...preArgs, ...callArgs], ", "), ")"]); case ts.SyntaxKind.NewExpression: let newExpr = ast; let newExprSymbol = getSymbolAtLocationAndFollowAliases(ctx.checker, newExpr.expression); let args = []; if (newExpr.arguments?.length == 1 && ts.isObjectLiteralExpression(newExpr.arguments[0])) { let object = newExpr.arguments[0]; let props = object.properties; let sortedPropsByKey = []; let structProps = []; newExprSymbol?.members?.forEach((v, k) => { let decl2 = v.valueDeclaration; if (decl2 && ts.isPropertyDeclaration(decl2)) { const typeStr = translateType(ctx.checker, ctx.checker.getTypeAtLocation(decl2)); if (typeStr.startsWith("atomic<")) { return; } structProps.push([k?.toString() ?? "", decl2.type]); } }); sortedPropsByKey = structProps.sort((a, b) => { return a[0].localeCompare(b[0]); }); args = [ ...sortedPropsByKey.map((p) => { let prop2 = props.find((p2) => { if (ts.isPropertyAssignment(p2)) { return p2.name.getText() == p[0]; } else if (ts.isShorthandPropertyAssignment(p2)) { return p2.name.getText() == p[0]; } else { return false; } }); if (prop2) { if (ts.isPropertyAssignment(prop2)) { let propType = ctx.checker.getTypeAtLocation(p[1]); let propValType = ctx.checker.getTypeAtLocation(prop2.initializer); let propTypeStr = translateType(ctx.checker, propType); let propValTypeStr = translateType(ctx.checker, propValType); if (propTypeStr != propValTypeStr) { return s([ "/* ", p[0], ": */ ", autoCastNumeric(c2(prop2.initializer), propValTypeStr, propTypeStr, prop2), "\n" ]); } else { return s(["/* ", p[0], ": */ ", c2(prop2.initializer), "\n"]); } } else if (ts.isShorthandPropertyAssignment(prop2)) { return s(["/* ", p[0], ": */ ", c2(prop2.name), "\n"]); } else { return s(["/* ", c2(prop2), ": */ ", "\n"]); } } else { return s(["/* ", p[0], ": */ ", generateDefaultForType$1(ctx.checker, p[1]), "\n"]); } }) ]; } let decl = ctx.checker.getTypeAtLocation(newExpr.expression).getSymbol()?.getDeclarations(); if (decl && ts.isClassDeclaration(decl[0])) { return s(["_make_struct_", resolveStructName(decl[0]), "(\n", ...join(args, ", "), "\n)"]); } else { return s(["/*", ...join(args, ", "), "*/"]); } case ts.SyntaxKind.ExpressionStatement: let expr = ast; return s([c2(expr.expression), ";\n"]); case ts.SyntaxKind.ObjectLiteralExpression: let obj = ast; return s([ "{", ...join( obj.properties.map((p) => { if (ts.isPropertyAssignment(p)) { return s([c2(p.name), ": ", c2(p.initializer)]); } else if (ts.isShorthandPropertyAssignment(p)) { return s([c2(p.name)]); } else { return s(["/*", c2(p), "*/"]); } }), ", " ), "}" ]); case ts.SyntaxKind.ConditionalExpression: let cond = ast; let left = c2(cond.whenTrue); let right = c2(cond.whenFalse); let leftType = ctx.checker.getTypeAtLocation(cond.whenTrue); let rightType = ctx.checker.getTypeAtLocation(cond.whenFalse); if (isVector(ctx.checker, leftType) && isVector(ctx.checker, rightType) || isNumeric(ctx.checker, leftType) && isNumeric(ctx.checker, rightType)) { let leftTypeStr = translateType(ctx.checker, leftType); let rightTypeStr = translateType(ctx.checker, rightType); let leftTypeInfo = getWGSLTypeInfo(leftTypeStr); let rightTypeInfo = getWGSLTypeInfo(rightTypeStr); if (leftTypeInfo.elementType == "f32") { right = autoCastNumeric( right, translateType(ctx.checker, rightType), translateType(ctx.checker, leftType), cond ); } if (rightTypeInfo.elementType == "f32") { left = autoCastNumeric( left, translateType(ctx.checker, leftType), translateType(ctx.checker, rightType), cond ); } } return s(["select(", right, ", ", left, ", ", c2(cond.condition), ")"]); case ts.SyntaxKind.Identifier: let id = ast; if (ts.isIdentifier(id)) { let sym = ctx.checker.getSymbolAtLocation(id); if (sym && sym.flags & ts.SymbolFlags.Alias) { sym = ctx.checker.getAliasedSymbol(sym); } if (sym?.declarations?.length == 1) { let decl2 = sym.declarations[0]; if (isUniformable(ctx.checker, decl2)) { if (isVariableDeclarationValue(ctx.checker, decl2)) { if (!isInSameScope(decl2, ast)) { if (!isInShader$1(decl2)) { if (ts.isBinaryExpression(ast.parent)) { if (ast.parent.left == ast) { throw new GLSLCompilationError( `Cannot assign to variable '${id.text.toString()}' because it is not declared in the shader`, ast ); } } let _type = ctx.checker.getTypeAtLocation(decl2); let translated = translateType(ctx.checker, _type); let isGlobalVar = isRootNode(decl2); let glslVarName = `${!isSpecialUniformType(translated) ? "_in_uniforms." : ""}_ext_uniform_${isGlobalVar ? "global" : "local"}_${id.text.toString()}`; return s([glslVarName]); } else { return s([escapeIdentifier(id.text.toString())]); } } } } } return s([escapeIdentifier(id.text.toString())]); } else { return c2(id.expression); } case ts.SyntaxKind.PropertyAccessExpression: let prop = ast; let isStaticMember = isStaticPropertyAccessExpression(ctx.checker, prop); if (isStaticMember) { return s([c2(prop.expression), "_static_", c2(prop.name)]); } else { let propName = prop.name.getText(); if (propName == "__index") { return s([c2(prop.expression)]); } else if (propName == "size") { let innerType = translateType( ctx.checker, ctx.checker.getTypeAtLocation(prop.expression) ); if (innerType == "sampler") { return s(["vec2(textureDimensions(", c2(prop.expression), "_texture))"]); } } else { return s([c2(prop.expression), ".", c2(prop.name)]); } } case ts.SyntaxKind.ThisKeyword: return s(["_this"]); case ts.SyntaxKind.FirstLiteralToken: let lit = ast; return s([lit.text]); case ts.SyntaxKind.IfStatement: let ifStmt = ast; if (isIdentifier(ifStmt.expression)) { if (ifStmt.expression.escapedText == "PLATFORM_WEBGPU") { return s([c2(ifStmt.thenStatement)]); } if (ifStmt.expression.escapedText == "PLATFORM_WEBGL") { if (ifStmt.elseStatement) { return s([c2(ifStmt.elseStatement)]); } else { return s([""]); } } } let addBraces = false; if (!ts.isBlock(ifStmt.thenStatement)) { addBraces = true; } return s([ "if (", c2(ifStmt.expression), `) ${addBraces ? "{" : ""} `, c2(ifStmt.thenStatement), `${addBraces ? "}" : ""} `, ifStmt.elseStatement ? s(["else \n", c2(ifStmt.elseStatement), "\n"]) : s([""]) ]); case ts.SyntaxKind.TrueKeyword: return s(["true"]); case ts.SyntaxKind.FalseKeyword: return s(["false"]); case ts.SyntaxKind.PostfixUnaryExpression: let post = ast; return s([c2(post.operand), post.operator == ts.SyntaxKind.PlusPlusToken ? "++" : "--"]); case ts.SyntaxKind.PlusPlusToken: return s(["++"]); case ts.SyntaxKind.MinusMinusToken: return s(["--"]); case ts.SyntaxKind.ParenthesizedExpression: let paren = ast; return s(["(", c2(paren.expression), ")"]); case ts.SyntaxKind.VariableDeclarationList: let varDeclList = ast; if (varDeclList.declarations.length > 0) { for (let decl2 of varDeclList.declarations) { let varDecl2 = decl2; let type22 = ctx.checker.getTypeAtLocation(varDecl2); let translated = translateType(ctx.checker, type22); let postType = ": " + translated; if (translated == "___atomic_compare_exchange_result") { postType = ""; } return s(["var ", varDecl2.name.getText(), postType, " = ", c2(varDecl2.initializer)]); } } else { return s([""]); } case ts.SyntaxKind.ForStatement: let forStmt = ast; return s([ "for (", c2(forStmt.initializer), ";", c2(forStmt.condition), ";", c2(forStmt.incrementor), ")", c2(forStmt.statement) ]); case ts.SyntaxKind.BinaryExpression: let bin = ast; let binExprText = bin.operatorToken.getText(); if (binExprText == "===") { binExprText = "=="; } if (bin.operatorToken.kind == ts.SyntaxKind.EqualsToken) { let leftType2 = ctx.checker.getTypeAtLocation(bin.left); let rightType2 = ctx.checker.getTypeAtLocation(bin.right); if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) { let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2); let [rightElementType, rightElementSize] = getVectorElementType(ctx.checker, rightType2); if (leftElementType != rightElementType) { if (leftElementType == "float" && rightElementType == "int") { return s([c2(bin.left), ` = vec${leftElementSize}f(`, c2(bin.right), ")"]); } else if (leftElementType == "int" && rightElementType == "float") { return s([c2(bin.left), ` = vec${leftElementSize}i(`, c2(bin.right), ")"]); } } } if (isNumeric(ctx.checker, leftType2) && isNumeric(ctx.checker, rightType2)) { let leftTypeStr = translateType(ctx.checker, leftType2); let rightTypeStr = translateType(ctx.checker, rightType2); if (leftTypeStr != rightTypeStr) { return s([ c2(bin.left), ` = `, autoCastNumeric(c2(bin.right), rightTypeStr, leftTypeStr, bin) ]); } } if (isUniformAccess(ctx, bin.left)) { if (translateType(ctx.checker, ctx.checker.getTypeAtLocation(bin.left)) == "bool") { return s([c2(bin.left), " = select(0, 1, ", c2(bin.right), ")"]); } } return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]); } return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]); case ts.SyntaxKind.StringLiteral: return s(["0"]); case ts.SyntaxKind.ArrayLiteralExpression: let arr = ast; return s([ "array(", ...join( arr.elements.map((e) => c2(e)), ", " ), ")" ]); case ts.SyntaxKind.ElementAccessExpression: let elem = ast; let t = ctx.checker.getTypeAtLocation(elem.expression); let n2 = getTypeFallback$1(ctx.checker, t); let postfix = ""; if (n2 === "Array" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) { let typeRef = t; let args2 = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef); let translated = translateType(ctx.checker, args2[0]); let typeInfo = getWGSLTypeInfo(translated); args2.length; if (typeInfo.needsAlignment) { translated = `vec4<${typeInfo.elementType ?? "f32"}>`; } let lengths = { 1: "x", 2: "xy", 3: "xyz", 4: "xyzw" }; postfix = `.${lengths[typeInfo.length ?? 1]}`; } return s([c2(elem.expression), "[", c2(elem.argumentExpression), "]", postfix]); case ts.SyntaxKind.Block: let block = ast; return s([ "{\n", ...join( block.statements.map((child) => c2(child)), ";" ), "\n}" ]); case ts.SyntaxKind.TypeOfExpression: return s(["0"]); case ts.SyntaxKind.WhileStatement: let whileStmt = ast; return s(["while (", c2(whileStmt.expression), ") ", c2(whileStmt.statement)]); default: throw new GLSLCompilationError(`Invalid shader syntax '${ast.getText()}'`, ast); } } function getClosureVars(checker, func) { let result = []; let recur = (node2) => { if (node2.kind == ts.SyntaxKind.Identifier) { let id = node2; let symbol = checker.getSymbolAtLocation(id); let declar = symbol.valueDeclaration; if (isVariableDeclarationValue(checker, declar)) { if (declar) { if (!isInSameScope(declar, node2) && isInShader$1(declar)) { result.push(symbol); } } } } else { node2.forEachChild(recur); } }; recur(func); return result; } function getDeclarationType(checker, node2) { return node2.type ? checker.getTypeAtLocation(node2.type) : node2.initializer ? checker.getTypeAtLocation(node2.initializer) : checker.getTypeAtLocation(node2); } function isArrayType$1(type2, checker) { return checker.isTupleType(type2) || checker.isArrayType(type2); } class WGSLShader { constructor(key, source) { this.globals = []; this.locals = []; this.attributeInput = ""; this.attributeOutput = ""; this.key = key; this.source = source; } } function resolveFunctionName(f) { if (ts.isMethodDeclaration(f)) { let parentName = "anon"; if (f.parent && ts.isClassDeclaration(f.parent)) { parentName = f.parent.name?.text ?? "anon"; } return removeDoubleUnderscores( `fn_${f.getSourceFile()?.fileName.replaceAll("/", "_").replaceAll(".", "_") ?? "anon"}_${f.getStart()}_${parentName}_static_${f.name.getText() ?? "unknown"}` ); } else { return removeDoubleUnderscores( `fn_${f.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${f.getStart()}_${f.name?.text.replaceAll(".", "_dot_") ?? "unknown"}` ); } } function resolveStructName(c2) { if (c2.name?.text == "ShaderInput") return "ShaderInput"; if (c2.name?.text == "ShaderOutput") return "ShaderOutput"; return removeDoubleUnderscores( `str_${c2.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${c2.getStart()}_${c2.name?.text ?? "unknown"}`.replaceAll("__", "_i_") ); } function isInSameScope(node2, other) { return closest(node2, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }) == closest(other, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }); } function isInShader$1(node2) { return closest(node2, (node22) => { if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) { if (hasShadeupDocTag(node22, "shader")) { return true; } } return false; }); } function isInRoot(node2) { let c2 = closest(node2, (node22) => { if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22) || ts.isSourceFile(node22)) { return true; } }); return c2 ? ts.isSourceFile(c2) : false; } function isRootNode(node2) { let parentRoot = closest(node2, (node22) => { if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) { return true; } if (ts.isSourceFile(node22)) { return true; } }); return parentRoot && ts.isSourceFile(parentRoot); } function isComposedFunction(checker, func) { let isComposed = false; func.parameters.forEach((param) => { let type2 = checker.getTypeAtLocation(param); if (type2.getCallSignatures().length > 0) { isComposed = true; } }); return isComposed; } function resolveDeps(checker, root, table = { graph: /* @__PURE__ */ new Map(), functions: /* @__PURE__ */ new Map(), structs: /* @__PURE__ */ new Map(), structsProps: /* @__PURE__ */ new Map(), globals: /* @__PURE__ */ new Map(), composed: /* @__PURE__ */ new Map() }) { function resolveFunction(f1, f2, call) { let n1 = f1 ? resolveFunctionName(f1) : "main"; let n2 = resolveFunctionName(f2); if (f2.name?.getText() === "__index" || f2.name?.getText() === "__index_assign" || f2.name?.getText() === "__index_assign_op" || f2.name?.getText() === "len" || f2.name?.getText() === "sample" || f2.name?.getText() === "atomic" || hasShadeupDocTag(f2, "noemit_gpu")) return; if (isComposedFunction(checker, f2)) { n2 = n2 + "_composed_" + call.pos; table.composed.set(n2, call); } let deps = table.graph.get(n1) ?? []; if (!deps.includes(n2)) deps.push(n2); table.graph.set(n1, deps); table.functions.set(n2, f2); } function resolveStruct(decl, fullStruct = false) { let name = resolveStructName(decl); if (decl.name?.text == "atomic_internal") { return; } if (table.structs.has(name)) { if (!fullStruct) { return; } } let props = table.structsProps.get(name) ?? /* @__PURE__ */ new Set(); for (let member of decl.members) { if (ts.isPropertyDeclaration(member)) { let type2 = checker.getTypeAtLocation(member); resolveTypeUse(type2, member); if (fullStruct) { props.add(member.name.getText()); } } } if (fullStruct) { table.structsProps.set(name, props); } table.structs.set(name, decl); } function isValidShaderType(type2, checker2) { let symbol = type2.aliasSymbol || type2.getSymbol(); let name = checker2.typeToString(type2); let bases = type2.getBaseTypes(); if (bases && bases.length > 0) { for (let base of bases) { if (!isValidShaderType(base, checker2)) return false; } } if (TYPE_BLACKLIST.includes(symbol?.getName() ?? "")) { return false; } return !TYPE_BLACKLIST.includes(name); } function resolveTypeUse(typeNode, context2, fullStruct = false) { let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); if (TYPE_BLACKLIST.includes(symbol?.getName() ?? "")) { throw new GLSLCompilationError( `Type '${symbol?.getName()}' is not supported in shaders`, context2 ); } let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { resolveStruct(decl, fullStruct); } let typestr = checker.typeToString(typeNode); if (typeNode.aliasTypeArguments) for (let args of typeNode.aliasTypeArguments) { resolveTypeUse( args, context2, typestr.startsWith("buffer<") || typestr.startsWith("buffer_internal<") ); } } function resolvePropertyAccess(node2) { let typeNode = checker.getTypeAtLocation(node2.expression); let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); checker.typeToString(typeNode); if (!isValidShaderType(typeNode, checker)) { throw new GLSLCompilationError( `Type '${symbol?.getName()}' is not supported in shaders`, node2 ); } let full = checker.getTypeAtLocation(node2).getCallSignatures().length > 0; resolveTypeUse(typeNode, node2, full); resolveTypeUse(checker.getTypeAtLocation(node2), node2); let prop = node2.name.getText(); let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { let name2 = resolveStructName(decl); let props = table.structsProps.get(name2) ?? /* @__PURE__ */ new Set(); props.add(prop); table.structsProps.set(name2, props); } } walkNodes$1(root, (node2) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; exprSmybol.valueDeclaration; if (ts.isPropertyAccessExpression(node2.expression)) { resolveTypeUse( checker.getTypeAtLocation(node2.expression.expression), node2.expression.expression ); } if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let mapping = findSignatureMappingToWGSL(checker, exprSmybol); if (mapping === null) { let parentDeclar = closest( node2, (n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) || ts.isArrowFunction(n) ); if (parentDeclar && ts.isArrowFunction(parentDeclar)) { let parentParentDeclar = closest(parentDeclar, (n) => ts.isCallExpression(n)); if (parentParentDeclar && ts.isCallExpression(parentParentDeclar)) { let parentParentSymbol = checker.getSymbolAtLocation(parentParentDeclar.expression); if (parentParentSymbol && parentParentSymbol.flags & ts.SymbolFlags.Alias) { parentParentSymbol = checker.getAliasedSymbol(parentParentSymbol); } if (parentParentSymbol) { let parentParentFuncDeclar = parentParentSymbol.getDeclarations()?.[0]; if (parentParentFuncDeclar && (ts.isFunctionDeclaration(parentParentFuncDeclar) || ts.isMethodDeclaration(parentParentFuncDeclar))) { resolveFunction(parentParentFuncDeclar, funcDeclar, node2); } } } } else if (parentDeclar && (ts.isFunctionDeclaration(parentDeclar) || ts.isMethodDeclaration(parentDeclar))) { resolveFunction(parentDeclar, funcDeclar, node2); } else { resolveFunction(null, funcDeclar, node2); } if (!table.graph.has(resolveFunctionName(funcDeclar))) { table.graph.set(resolveFunctionName(funcDeclar), []); resolveDeps(checker, funcDeclar, table); } let sig = checker.getSignatureFromDeclaration(funcDeclar); let returnType = checker.getReturnTypeOfSignature(sig); resolveTypeUse(returnType, node2); } } } } if (ts.isNewExpression(node2)) { resolveTypeUse(checker.getTypeAtLocation(node2), node2.expression, true); } if (ts.isPropertyAccessExpression(node2)) { resolvePropertyAccess(node2); } if (ts.isIdentifier(node2)) { let type2 = checker.getTypeAtLocation(node2); resolveTypeUse(type2, node2); if (checker.getSymbolAtLocation(node2)) { let decl = checker.getSymbolAtLocation(node2)?.declarations; if (decl && ts.isVariableDeclaration(decl[0])) { if (!isInSameScope(decl[0], node2) && decl[0].getSourceFile().fileName !== root.getSourceFile().fileName) { if (isVariableDeclarationValue(checker, decl[0])) { table.globals.set(node2.text.toString(), decl[0]); } } } } } if (ts.isVariableDeclaration(node2)) { let type2 = checker.getTypeAtLocation(node2); resolveTypeUse(type2, node2); } }); return table; } function resolveUniforms(checker, root) { let uniforms = []; walkNodesWithCalls(checker, root, (node2) => { if (ts.isIdentifier(node2)) { let decl = checker.getSymbolAtLocation(node2); if (decl && decl.flags & ts.SymbolFlags.Alias) { decl = checker.getAliasedSymbol(decl); } if (decl && decl.declarations && decl.declarations.length == 1) { let declNode = decl.declarations[0]; if (declNode) { if (isVariableDeclarationValue(checker, declNode)) { if (!isInSameScope(declNode, node2) && !isInShader$1(declNode)) { let indexAssign = false; let indexRead = false; let sampler = false; let parent = node2.parent; if (parent && ts.isPropertyAccessExpression(parent)) { if (parent.expression == node2) { if (parent.name.getText() == "__index_assign") { indexAssign = true; } if (parent.name.getText() == "__index") { indexRead = true; if (parent.parent && parent.parent.parent && ts.isPropertyAccessExpression(parent.parent.parent)) { if (parent.parent.parent.parent && ts.isBinaryExpression(parent.parent.parent.parent) && parent.parent.parent.parent.left == parent.parent.parent) { if (parent.parent.parent.parent.operatorToken.kind == ts.SyntaxKind.EqualsToken) { indexAssign = true; } } if (parent.parent.parent.parent && ts.isPropertyAccessExpression(parent.parent.parent.parent)) { let propType = checker.getTypeAtLocation(parent.parent.parent); let translatedPropType = translateType(checker, propType); if (translatedPropType.startsWith("atomic<")) { if (parent.parent.parent.parent.name.getText() != "read") { indexAssign = true; } else { indexRead = true; } } } } } if (parent.name.getText() == "sample") { sampler = true; } } } let idx = uniforms.findIndex((d) => d.declaration === declNode); if (idx == -1) { let translated = translateType(checker, checker.getTypeAtLocation(declNode)); if (translated.includes("atomic<")) { indexAssign = true; } uniforms.push({ declaration: declNode, usesIndexAssign: indexAssign, usesIndexRead: indexRead, usesSampler: sampler }); } else { uniforms[idx].usesIndexAssign = uniforms[idx].usesIndexAssign || indexAssign; uniforms[idx].usesIndexRead = uniforms[idx].usesIndexRead || indexRead; uniforms[idx].usesSampler = uniforms[idx].usesSampler || sampler; } } } } } } }); return uniforms; } function isVariableDeclarationValue(checker, node2) { try { if (ts.isVariableDeclaration(node2) || ts.isParameter(node2)) { let type2 = checker.getTypeAtLocation(node2); let calls = type2.getCallSignatures(); if (calls.length != 0) { if (type2.aliasSymbol) { if (type2.aliasSymbol.getName() == "shader") { return true; } } } return calls.length == 0; } else { return false; } } catch (e) { return false; } } function isUniformable(checker, decl) { let exprSmybol = checker.getSymbolAtLocation(decl); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { exprSmybol.getDeclarations()?.[0]; } return ts.isVariableDeclaration(decl) || ts.isParameter(decl); } function isValidStructType(checker, type2) { let t = translateType(checker, type2); return t != "sampler"; } function addWGSLShader(key, root, checker, env2, isComputeShader = false, computeShaderSize = [1, 1, 1]) { let deps = resolveDeps(checker, root); let uniforms = resolveUniforms(checker, root); let mapping = [...deps.graph.entries()].map(([k, v]) => v.map((d) => [k, d])).flat(); let sorted = []; try { sorted = toposort(mapping).reverse(); } catch (e) { sorted = []; } let preFuncs = []; for (let s of deps.structs.values()) { let name = resolveStructName(s); let hasAnyProperty = false; let sp = deps.structsProps.get(name); let members = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; let type2 = checker.getTypeAtLocation(m); let translated = translateType(checker, type2); if (translated == "bool") { translated = "i32"; } let preComment = ""; if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { preComment = `// `; } } if (!isValidStructType(checker, type2)) { preComment = `// `; } if (preComment == "") { hasAnyProperty = true; } return new SourceNode( m.getStart(), m.getEnd(), `${preComment} ${isAlignable(translated) ? "@align(16) " : ""} ${escapeIdentifier( m.name.getText() )}: ${translated}, ` ); }); s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ""; let type2 = checker.getTypeAtLocation(m); let translated = translateType(checker, type2); if (translated == "bool") { translated = "i32"; } let preComment = ""; if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { preComment = `// `; } } if (preComment == "") { hasAnyProperty = true; } return new SourceNode( m.getStart(), m.getEnd(), `${preComment} ${escapeIdentifier(m.name.getText())}: ${translated}, ` ); }); let hasAtomic = false; let memberNames = s.members.map((m) => { if (!ts.isPropertyDeclaration(m)) return ["", ""]; let type2 = checker.getTypeAtLocation(m); let translated = translateType(checker, type2); if (!sp || !sp.has(m.name.getText())) { if (name != "ShaderInput" && name != "ShaderOutput") { return ["", ""]; } } if (translated.startsWith("atomic<")) { hasAtomic = true; } return [escapeIdentifier(m.name.getText()), translated, m]; }).filter((m) => m[0] != "").filter((m) => { return isValidStructType(checker, checker.getTypeAtLocation(m[2])); }).sort((a, b) => { return a[0].localeCompare(b[0]); }); if (!hasAnyProperty) continue; if (name == "ShaderInput" || name == "ShaderOutput") { members.push(new SourceNode(s.getStart(), s.getEnd(), ["// %SHADER_" + name + "%"])); } preFuncs.push( new SourceNode(s.getStart(), s.getEnd(), [`struct ${name} { `, ...members, "\n};\n"]) ); if (name != "ShaderInput" && name != "ShaderOutput") { if (!hasAtomic) { preFuncs.push( new SourceNode(s.getStart(), s.getEnd(), [ "fn _make_struct_" + name + "(", ...memberNames.map((m) => { return ` ${m[0]}: ${m[1]},`; }), ") -> ", name, " {\n", "var _s: ", name, ";\n", ...memberNames.map((m) => { if (m[1] == "bool") { return ` _s.${m[0]} = select(0, 1, ${m[0]}); `; } else { return ` _s.${m[0]} = ${m[0]}; `; } }), "\nreturn _s; \n}\n" ]) ); } } } let specialUniforms = []; preFuncs.push( new SourceNode(0, 0, ["struct _InUniformsStruct {\n/*SHADEUP_UNIFORM_STRUCT_START*/\n"]) ); let localStrs = []; let globalStrs = []; let workgroupVars = []; let checkDecl = (node2) => { let fullText = node2.getSourceFile().getFullText(); let fullStart = node2.getFullStart(); let prefix = `// @workgroup `; let mySelf = fullText.slice(fullStart - prefix.length, fullStart); if (mySelf.includes("@workgroup")) { workgroupVars.push(node2); } }; if (ts.isArrowFunction(root)) { ts.forEachChild(root.body, (node2) => { if (ts.isVariableDeclaration(node2) || ts.isVariableStatement(node2) || ts.isVariableDeclarationList) { if (ts.isVariableDeclaration(node2)) { checkDecl(node2); } else if (ts.isVariableStatement(node2)) { node2.declarationList.declarations.forEach((d) => { checkDecl(d); }); } else if (ts.isVariableDeclarationList(node2)) { for (let d of node2.declarations) { checkDecl(d); } } } }); } let globalUnis = []; let localUnis = []; for (let uniformData of uniforms) { let u = uniformData.declaration; if (isUniformable(checker, u)) { let _type = checker.getTypeAtLocation(u); let translated = translateType(checker, _type); let isGlobalVar = isRootNode(u); let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`; let isSpecial = isSpecialUniformType(translated); let pushTo = isGlobalVar ? globalStrs : localStrs; if (translated.startsWith("array")) { pushTo.push( new SourceNode(u.getStart(), u.getEnd(), ["@align(16) ", glslVarName, "_size: i32,\n"]) ); } if (translated.startsWith("atomic")) { pushTo.push( new SourceNode(u.getStart(), u.getEnd(), ["@align(16) ", glslVarName, "_dummy: u32,\n"]) ); } if (translated == "sampler") { pushTo.push( new SourceNode(u.getStart(), u.getEnd(), [ "@align(16) ", glslVarName, "_size: vec2,\n" ]) ); } if (isSpecial) { if (isGlobalVar) { globalUnis.push(uniformData); } else { localUnis.push(uniformData); } } else { pushTo.push( new SourceNode(u.getStart(), u.getEnd(), [ (isAlignable(translated) ? "@align(16) " : "") + glslVarName, ": ", translated, ",\n" ]) ); } } } specialUniforms.push(...localUnis, ...globalUnis); if (localStrs.length == 0 && globalStrs.length == 0) { preFuncs.push(new SourceNode(0, 0, ["", "dummy", ": vec4,\n"])); } else { preFuncs = [...preFuncs, ...localStrs, ...globalStrs]; } preFuncs.push(new SourceNode(0, 0, ["};\n"])); preFuncs.push( new SourceNode(0, 0, [ "@group(%GROUP_INDEX%) @binding(1) var _in_uniforms: _InUniformsStruct;\n" ]) ); let specialUniformsCounter = 2; for (let uniformData of specialUniforms) { let u = uniformData.declaration; if (isUniformable(checker, u)) { let _type = checker.getTypeAtLocation(u); let translated = translateType(checker, _type, false, true); let isGlobalVar = isRootNode(u); let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`; if (translated == "sampler" || translated.startsWith("array]+)>/g; innerTranslated = innerTranslated.replace(vecRegex, "$1"); let textureKind = "texture_2d"; let textureKindStorage = "texture_storage_2d"; if (isArrayType$1(_type, checker)) { textureKind = "texture_2d_array"; textureKindStorage = "texture_storage_2d_array"; } if (translated.startsWith("array; `, `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}: ${translated}; `, `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 2}) var ${glslVarName}_texture_write: ${textureKindStorage}<%WRITE_TYPE_${glslVarName}%, write>; ` ]) ); specialUniformsCounter += 2; } else if (uniformData.usesIndexAssign) { preFuncs.push( new SourceNode(0, 0, [ `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}_texture: ${textureKind}<${innerTranslated}>; `, `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}_texture_write: ${textureKindStorage}<%WRITE_TYPE_${glslVarName}%, write>; ` ]) ); specialUniformsCounter += 1; } else if (uniformData.usesSampler || uniformData.usesIndexRead) { preFuncs.push( new SourceNode(0, 0, [ `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}_texture: ${textureKind}<${innerTranslated}>; `, `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}: ${translated}; ` ]) ); specialUniformsCounter += 1; } } else if (translated.startsWith("atomic")) { preFuncs.push( new SourceNode(0, 0, [ `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}: ${translated}; ` ]) ); } else if (translated.startsWith("array") || translated.startsWith("buffer")) { let usageType = "read"; if (uniformData.usesIndexAssign) { usageType = "read_write"; } preFuncs.push( new SourceNode(0, 0, [ `@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}: ${translated}; ` ]) ); } specialUniformsCounter++; } } for (let workgroupVar of workgroupVars) { preFuncs.push( new SourceNode(0, 0, [ `var ${escapeIdentifier(workgroupVar.name.getText())}: ${translateType( checker, checker.getTypeAtLocation(workgroupVar.type) )}; ` ]) ); } for (let k of sorted) { if (k == "main") continue; let v = deps.functions.get(k); if (v) { let sourceFile2 = v.getSourceFile(); let originalFile2 = env2.files.find((f) => f.path == sourceFile2.fileName); preFuncs.push( compile$1( { parentFunction: v, checker, composed: deps.composed.get(k) ?? null }, v, originalFile2?.mapping ) ); } } let sourceFile = root.getSourceFile(); let originalFile = env2.files.find((f) => f.path == sourceFile?.fileName); let customAttributesIn = /* @__PURE__ */ new Map(); let customAttributesOut = /* @__PURE__ */ new Map(); let main = compile$1( { checker, isComputeShader, computeSize: computeShaderSize, addCustomAttribute(type2, idx, valType, interp) { if (type2 == "in") { customAttributesIn.set(idx, [valType, interp]); } else if (type2 == "out") { customAttributesOut.set(idx, [valType, interp]); } } }, root, originalFile.mapping ); preFuncs.push(main); let source = new SourceNode(root.getStart(), root.getEnd(), preFuncs); let ss = { indexMapping: [], str: "" }; source.toString(ss); let finalShaderOutput = ss.str; let customIns = []; for (let [idx, [valType, interp]] of customAttributesIn.entries()) { customIns.push(`@location(${7 + idx}) @interpolate(${interp}) custom${idx}: ${valType}, `); } finalShaderOutput = finalShaderOutput.replace("// %SHADER_ShaderInput%\n", customIns.join("")); let customOuts = []; for (let [idx, [valType, interp]] of customAttributesOut.entries()) { customOuts.push(`@location(${7 + idx}) @interpolate(${interp}) custom${idx}: ${valType}, `); } let matches = wgslHeader.match(/fn ([^\(]+)/gm); let headerSplits = []; for (let i = 0; i < matches.length; i++) { let index = wgslHeader.indexOf(matches[i]); let toIndex = i == matches.length - 1 ? wgslHeader.length : wgslHeader.indexOf(matches[i + 1]); headerSplits.push(wgslHeader.substring(index, toIndex)); } let realHeader = ""; for (let i = 0; i < headerSplits.length; i++) { let headerText = headerSplits[i]; let fnName = headerText.match(/fn ([^\(]+)/)?.[1]; if (fnName) { if (finalShaderOutput.includes(fnName)) { realHeader += headerText; } } } finalShaderOutput = realHeader + finalShaderOutput; let output = new WGSLShader(`shd_${key}`, finalShaderOutput); output.sourceMapping = ss.indexMapping; output.attributeInput = customIns.join(""); output.attributeOutput = customOuts.join(""); for (let uniformData of uniforms) { let u = uniformData.declaration; if (isUniformable(checker, u)) { let name = u.name.getText(); let isGlobalVar = isRootNode(u); if (name) { let filterProps = function(props) { if (props && props.name) { let sp = deps.structsProps.get(props.name); let realStruct = deps.structs.get(props.name); if (props.type == "struct" && realStruct) { for (let fi = props.fields.length - 1; fi >= 0; fi--) { let f = props.fields[fi]; if (!sp || !sp.has(f[0])) { props.fields.splice(fi, 1); } else { if (f[1].type == "struct") { f[1] = filterProps(f[1]); } } } } } if (props && (props.type == "buffer" || props.type == "primitive" && props.name == "texture2d")) { if (uniformData.usesSampler && uniformData.usesIndexAssign) { props.access = "sample_write"; } else if (uniformData.usesIndexAssign) { props.access = "write"; } else if (uniformData.usesSampler) { props.access = "sample"; } else { props.access = "read"; } } else if (props && props.type == "array" && props.element.type == "primitive" && props.element.name == "texture2d") { if (uniformData.usesSampler && uniformData.usesIndexAssign) { props.element.access = "sample_write"; } else if (uniformData.usesIndexAssign) { props.element.access = "write"; } else if (uniformData.usesSampler) { props.element.access = "sample"; } else { props.element.access = "read"; } } return props; }; getDeclarationType(checker, u); let typeNode = checker.getTypeAtLocation(u); let symbol = typeNode.aliasSymbol || typeNode.getSymbol(); let decl = symbol?.getDeclarations()?.[0]; if (decl && ts.isClassDeclaration(decl)) { resolveStructName(decl); } if (isGlobalVar) { let typeOut2 = getDeclarationType(checker, u); output.globals.push([ name, { fileName: getNodeSourceFileName(u), structure: filterProps(translateType(checker, typeOut2, true)) } ]); } else { output.locals.push([ name, filterProps(translateType(checker, getDeclarationType(checker, u), true)) ]); } } } } return output; } function isAlignable(t) { return t.startsWith("vec") || t == "f32" || t == "i32" || t == "u32"; } function isSpecialUniformType(t) { return t == "sampler" || t.startsWith("array") || t.startsWith("buffer") || t.startsWith("atomic"); } function getNodeSourceFileName(node2) { let found = closest(node2, (n) => ts.isSourceFile(n)); if (found && ts.isSourceFile(found)) { return found.fileName; } else { return ""; } } function walkNodes$1(node2, cb) { cb(node2); node2.forEachChild((n) => walkNodes$1(n, cb)); } function walkNodesWithCalls(checker, node2, cb) { cb(node2); node2.forEachChild((n) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let mapping = findSignatureMappingToWGSL(checker, exprSmybol); if (mapping === null) { if (funcDeclar.body) { walkNodesWithCalls(checker, funcDeclar.body, cb); } } } } } walkNodesWithCalls(checker, n, cb); }); } function getSymbolAtLocationAndFollowAliases(checker, node2) { let exprSmybol = checker.getSymbolAtLocation(node2); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } return exprSmybol; } function findSignatureMappingToWGSL(checker, sym) { let matcher = /=(?:wgsl|univ)\((.+)\)$/g; if (!sym.valueDeclaration) return null; let doc = ts.getJSDocTags(sym.valueDeclaration); for (let d of doc) { if (d.tagName.text !== "shadeup") continue; if (typeof d.comment === "string") { let matches = matcher.exec(d.comment); if (matches) { return matches[1]; } } } return null; } function removeDoubleUnderscores(str) { return str.replace(/__/g, "_ii"); } let rootSymbolsFromMath = [ "abs", "floor", "ceil", "round", "sign", "cos", "sin", "tan", "acos", "asin", "atan", "atan2", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "exp", "log", "pow", "log2", "log10", "sqrt", "inversesqrt", "frac", "min", "max", "step", "clamp", "saturate", "smoothstep", "lerp", "bilerp", "length", "distance", "dist", "normalize", "dot", "reflect", "refract", "cross", "degrees", "radians", "wrap", "rand", "rand2", "rand3", "float2x2", "float3x3", "float4x4", "inverse", "transpose", "pingpong", "atomic", "mod", "workgroupBarrier", "storageBarrier", "workgroupUniformLoad", "discard", "ddx", "ddy", "ddxFine", "ddyFine", "ddxCoarse", "ddyCoarse", "bitcast", "pack4x8snorm", "pack4x8unorm", "pack2x16snorm", "pack2x16unorm", "pack2x16float", "unpack4x8snorm", "unpack4x8unorm", "unpack2x16snorm", "unpack2x16unorm", "unpack2x16float" ]; let rootSymbolsFromAll = [ "print", "stat", "statGraph", "time", "compute", // 'type shader', "flush", // 'addressWorkgroup', // 'drawAlt', // 'shader_start_shd_', "globalVarInit", // 'type ShaderInput', // 'type ShaderOutput', "sleep", "__makeMap", "__deepClone", "map", "array" ]; let rootSymbolsFromDraw = [ "drawIndexed", "drawInstanced", "draw", "makeShader", "ShaderInput", "ShaderOutput", "shader", "drawAlt2", // 'drawIndexedIndirect', // 'drawInstancedIndexed', // 'drawIndirect', "drawCount", "drawAttributes", "drawAdvanced", "computeIndirect", "drawFullscreen", "shader_start_shd_" ]; let rootSymbolsFromCommon = [ "pixelToClip", "PI", "quat", "noise", "spatial", // 'mat4', "Camera", "Camera2d", "buffer", "matrix", "texture2d", "texture3d", "ui", "screenAA", "randColor", "randColor2", "hsl", "hsla", "rgb", "rgba", "hslFromColor", "hslaFromColor", "rgbFromColor", "rgbaFromColor", "hsv", "hsva", "hsvFromColor", "hsvaFromColor", "cmyk", "cmykFromColor", "hex", "hexFromColor", "sin1", "cos1", "tan1", "remap", "remap1", "color", "wrap2", "wrap3", "wrap4", "bezier" ]; let rootSymbolsFromMesh = ["mesh", "Mesh", "Model", "ModelPart", "Material"]; const header = `// This file was generated by Shadeup. import * as __ from "/std_math"; import {${rootSymbolsFromMath.join(", ")}} from "/std_math"; import {${rootSymbolsFromAll.join(", ")}, globalVarGet as __globalVarGet} from "/std___std_all"; import {${rootSymbolsFromDraw.join(", ")}} from "/_std/drawIndexed"; import { physics, PhysicsRigidBody2d, PhysicsCollider2d, PhysicsEngine2d } from "/_std/physics"; let globalVarGet = __globalVarGet; /**__SHADEUP_STRUCT_INJECTION_HOOK__*/ `; class SourceNode { constructor(startIndex, endIndex, children) { this.startIndex = startIndex; this.endIndex = endIndex; if (Array.isArray(children)) { this.children = children; } else { this.children = [children]; } } toString(s) { let start = s.str.length; for (const child of this.children) { if (typeof child === "string") { s.str += child; } else if (child instanceof SourceNode) { child.toString(s); } } s.indexMapping.push([this.startIndex, this.endIndex, start, s.str.length]); } print() { const s = { str: "", indexMapping: [] }; this.toString(s); return s.str; } } function lookupIndexMapping(indexMapping, index) { for (const [start, end, newStart, newEnd] of indexMapping) { if (index >= newStart && index <= newEnd) { return start + (index - newStart); } } return -1; } function lookupIndexMappingRange(indexMapping, start, end) { let minStart = Infinity; let maxEnd = -Infinity; let size = 0; for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) { if (start >= newStart && end <= newEnd) { if (oldEnd - oldStart < size || size === 0) { minStart = oldStart; maxEnd = oldEnd; size = oldEnd - oldStart; } } } return { start: minStart, end: maxEnd }; } function reverseLookupIndexMappingRange(indexMapping, start, end) { let minStart = Infinity; let maxEnd = -Infinity; let size = 0; for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) { if (start >= oldStart && end <= oldEnd) { if (newEnd - newStart < size || size === 0) { minStart = newStart; maxEnd = newEnd; size = newEnd - newStart; } } } return { start: minStart, end: maxEnd }; } function reverseLookupIndexMappingCursor(indexMapping, cursor) { let exact = -Infinity; let size = 0; for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) { if (cursor >= oldStart && cursor <= oldEnd) { if (newEnd - newStart < size || size === 0) { exact = cursor - oldStart + newStart; size = newEnd - newStart; } } } return exact; } function prePass(ctx, ast) { for (const child of ast.namedChildren) { if (child.type === "impl_declaration") { let _for = child.childForFieldName("for"); const name = child.childForFieldName("name"); if (_for) { ctx.addImplFor(name.text, child); } else { ctx.addImpl(name.text, child); } } if (child.type == "lexical_declaration") { let variable_declarator = child.firstNamedChild; if (variable_declarator.type == "variable_declarator") { ctx.globals.push(variable_declarator.firstNamedChild.text); } } } } const math_primitives = [ "atomic", "uint", "uint2", "uint3", "uint4", "uint8", "int", "float", "float2", "float3", "float4", "int2", "int3", "int4", "float2x2", "float3x3", "float4x4", "bool" ]; const operators = { "+": "add", "-": "sub", "*": "mul", "**": "pow", "/": "div", "%": "mod", "==": "eq", "!=": "neq", "<": "lt", "<=": "lte", ">": "gt", ">=": "gte", "&&": "and", "||": "or", "!": "not", "&": "bitand", "|": "bitor", "^": "bitxor", "<<": "lshift", ">>": "rshift", "~": "bitnot" }; const keyFunctions = { float: "__.float", int: "__.int", uint: "__.uint", uint2: "__.uint2", uint3: "__.uint3", uint4: "__.uint4", uint8: "__.uint8", float2: "__.float2", float3: "__.float3", float4: "__.float4", int2: "__.int2", int3: "__.int3", int4: "__.int4", float2x2: "__.float2x2", float3x3: "__.float3x3", float4x4: "__.float4x4" }; const escapeWords = { in: true, out: true }; function generateDefaultForType(name) { switch (name) { case "any": return "null"; case "int": return "__.int(0)"; case "uint": return "__.uint(0)"; case "uint8": return "__.uint8(0)"; case "float": return "__.float(0.0)"; case "float2": return "__.float2(0.0, 0.0)"; case "float3": return "__.float3(0.0, 0.0, 0.0)"; case "float4": return "__.float4(0.0, 0.0, 0.0, 0.0)"; case "int2": return "__.int2(0, 0)"; case "int3": return "__.int3(0, 0, 0)"; case "int4": return "__.int4(0, 0, 0, 0)"; case "float2x2": return "__.float2x2(0.0, 0.0, 0.0, 0.0)"; case "float3x3": return "__.float3x3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "float4x4": return "__.float4x4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)"; case "bool": return "false"; case "string": return '""'; case "atomic": return "atomic<__.uint>(__.uint(0))"; case "atomic": return "atomic<__.int>(__.int(0))"; default: if (name.endsWith("[]")) { return "[]"; } else if (name.endsWith("]")) { let matches = name.match(/(.+)\[(\d+)\]$/); if (matches && matches.length > 2) { let type2 = matches[1]; let count2 = matches[2]; let args = []; for (let i = 0; i < parseInt(count2); i++) { args.push(generateDefaultForType(type2)); } return "[" + args.join(",") + "]"; } else { return "[]"; } } else { if (name.startsWith("buffer") || name.startsWith("texture2d") || name.startsWith("texture3d")) { return "null"; } else { return "new " + name + "({})"; } } } } function isValidInteger(str) { let n = parseInt(str); if (n > Math.pow(2, 31) - 1 || n < -Math.pow(2, 31)) { return false; } return true; } function compile(ctx, ast) { function c2(myAst, errorMessage = "Syntax error") { if (!myAst) { console.log("error"); ctx.report(ast, errorMessage); return s(["/*", errorMessage, "*/"]); } else { return compile(ctx, myAst); } } function s(c22) { return new SourceNode(ast.startIndex, ast.endIndex, c22); } function n(type2) { return ast.childForFieldName(type2); } function flat(...c22) { return c22.reduce((acc, cur) => { return [...acc, ...cur]; }, []); } function join(c22, sep) { return c22.filter((v) => { if (typeof v == "string" && v.length == 0 || v instanceof SourceNode && v.children.length == 0) { return false; } return true; }).reduce((acc, cur) => { if (acc.length === 0) { return [cur]; } return [...acc, sep, cur]; }, []); } function children() { return ast.namedChildren.map((child) => c2(child)); } function hasName(name) { return ast.childForFieldName(name) !== null; } if (!ast) { return new SourceNode(0, 0, ["/*", "Syntax error", "*/"]); } switch (ast.type) { case "program": return s([ header, ...ctx.fileName != "file:////_std/common.ts" ? [`import {${rootSymbolsFromCommon.join(", ")}} from "/_std/common";`] : [], ...ctx.fileName != "file:////_std/mesh.ts" ? [`import {${rootSymbolsFromMesh.join(", ")}} from "/_std/mesh";`] : [], ...ctx.fileName != "file:////_std/sdf.ts" ? [`import { sdf } from "/_std/sdf";`] : [], ...ast.children.map((child) => c2(child)) ]); case "expression_statement": if (ast.firstChild) { if (ast.lastNamedChild?.type === "ERROR") { return s([c2(ast.firstNamedChild), "."]); } if (ast.firstNamedChild.type == "workgroup") { return s([c2(ast.firstNamedChild), "\n"]); } else { return s([c2(ast.firstNamedChild), ";\n"]); } } case "binary_expression": if (ast.firstChild && ast.lastChild) { if (ast.lastChild.text == "null" && (ast.children[1].text == "!=" || ast.children[1].text == "==")) { return s([c2(ast.firstChild), ast.children[1].text + "=", "null"]); } return s([ "__.", operators[ast.children[1].text.trim()] ?? ast.children[1].text.trim(), "( ", c2(ast.firstNamedChild), ", ", c2(ast.lastNamedChild), " )" ]); } case "identifier": if (keyFunctions[ast.text]) { return s([String(keyFunctions[ast.text])]); } else if (escapeWords[ast.text]) { return s([String("__" + ast.text)]); } return s([ String(ast.text === "self" ? isInShader(ast) ? "shader_self_temp" : "this" : ast.text) ]); case "number": if (ast.parent?.type == "pair" && ast.parent.firstNamedChild == ast) { return s([String(ast.text)]); } if (ast.text.match(/.[xyzwrgba]+$/)) { let swizzle = (ast.text.match(/.[xyzwrgba]+$/) ?? [""])[0]; swizzle = swizzle.replace(".", ""); let raw = ast.text.replace(/.[xyzwrgba]+$/, ""); let isUint2 = raw.indexOf("u") !== -1; let isFloat2 = raw.indexOf(".") !== -1; return s([ String( "__.swizzle(" + (isFloat2 ? "__.float" : isUint2 ? "__.uint" : "__.int") + "(" + raw.replace("u", "") + '), "' + swizzle + '")' ) ]); } let isFloat = ast.text.indexOf(".") !== -1; let isUint = ast.text.indexOf("u") !== -1; if (!isFloat && !isValidInteger(ast.text) && !isUint) { ctx.report( ast, "Invalid integer, this overflows the 32 bit integer limit, add a .0 to the end to make it a float" ); } return s([ (isFloat ? "__.float" : isUint ? "__.uint" : "__.int") + "(", new SourceNode(ast.startIndex, ast.endIndex, ast.text.replace("u", "")), ")" ]); case "string": return s([String(ast.text)]); case "function_declaration": if (ast.firstChild && ast.lastChild) { let funcName = n("name").text; let prefix = ""; if (funcName === "main") { prefix += ""; prefix += "export "; } return s([ prefix + "function ", c2(n("name")), c2(n("parameters")), ...hasName("return_type") ? [c2(n("return_type")), " "] : [], c2(n("body")), "\n" ]); } case "block": return s(children()); case "formal_parameters": return s(["(", ...join(children(), ", "), ")"]); case "required_parameter": if (n("pattern")?.text === "self") { return s([]); } return s( flat( [c2(n("pattern"))], hasName("type") ? [": ", c2(n("type"))] : [], hasName("value") ? [" = ", c2(n("value"))] : [] ) ); case "type_annotation": return s([c2(ast.firstNamedChild)]); case "type_identifier": if (math_primitives.indexOf(ast.text) !== -1) { return s([String("__." + ast.text)]); } return s([String(ast.text)]); case "predefined_type": if (math_primitives.indexOf(ast.text) !== -1) { return s([String("__." + ast.text)]); } return s([String(ast.text)]); case "function_type": return s([c2(n("parameters")), " => ", c2(n("return_type"))]); case "lookup_type": let len = parseInt(ast.lastNamedChild?.text ?? "0"); let repeats = []; for (let i = 0; i < len; i++) { repeats.push(c2(ast.firstNamedChild)); } return s(["[", ...join(repeats, ", "), "]"]); case "arrow_function": return s([ c2(n("parameters")), " => ", ...hasName("return_type") ? [c2(n("return_type")), " "] : [], c2(n("body")) ]); case "literal_type": return s([c2(ast.firstNamedChild)]); case "return_statement": if (ast.namedChildCount === 0) { return s(["return;"]); } else { if (ast.lastNamedChild?.type === "ERROR") { return s(["return ", c2(ast.firstNamedChild), "."]); } return s(["return ", c2(ast.firstNamedChild), ";"]); } case "export_statement": return s(["export ", c2(ast.firstNamedChild), ";"]); case "export_clause": return s(["{", ...join(children(), ", "), "}"]); case "export_specifier": return s([c2(ast.firstNamedChild)]); case "array": return s(["[", ...join(children(), ", "), "]"]); case "template_string": return s(["`", ...join(children(), ""), "`"]); case "template_substitution": return s(["${", c2(n("expression")), "}"]); case "template_string_segment": return s([String(ast.text)]); case "type_alias_declaration": ctx.report(ast, "Type aliases aren't supported yet"); return s(["/*error*/0"]); case "import": return s([""]); case "comment": return s([String(ast.text), "\n"]); case "call_expression": if (n("type_arguments")) { if (n("function").text == "buffer" || n("function").text == "texture2d" || n("function").text == "texture3d") { let internalArgs = s([ "(", ...join( [ ...n("arguments").namedChildren.map((chi) => c2(chi)), ...n("arguments").namedChildren.length == 1 && n("function").text == "texture2d" || n("function").text == "texture3d" ? [s(['"auto"'])] : [], s(['"', n("type_arguments").namedChild(0).text, '"']) ], ", " ), ")" ]); return s([c2(n("function")), c2(n("type_arguments")), internalArgs]); } return s([c2(n("function")), c2(n("type_arguments")), c2(n("arguments"))]); } else { return s([c2(n("function")), c2(n("arguments"))]); } case "construct_expression": return s(["new ", c2(n("identifier")), "(", c2(n("body")), ")"]); case "member_expression": let prop = n("property"); let p = prop.text ?? ""; let isParentAssignment = ast.parent?.type == "assignment_expression" || ast.parent?.type == "augmented_assignment_expression"; if (isParentAssignment) { let left2 = ast.parent.childForFieldName("left"); isParentAssignment = left2.startIndex == ast.startIndex && left2.endIndex == ast.endIndex; } if (p.length > 0 && p.length < 5) { let isSwizzle = true; for (let i = 0; i < p.length; i++) { let char = p[i]; if (char !== "x" && char !== "y" && char !== "z" && char !== "w" && char !== "r" && char !== "g" && char !== "b" && char !== "a") { isSwizzle = false; break; } } if (isSwizzle) { if (isParentAssignment) { ast.parent.childForFieldName("right"); } return s([ `__.swizzle(`, c2(n("object")), `, '`, new SourceNode(prop.startIndex, prop.endIndex, p), `'`, ...isParentAssignment ? [`, `, c2(ast.parent.childForFieldName("right"))] : [], `)` // new SourceNode(ast.children[1].startIndex, ast.children[1].endIndex, '.'), // c(n('property')!) ]); } } return s([ c2(n("object")), new SourceNode(ast.children[1].startIndex, ast.children[1].endIndex, "."), c2(n("property")) ]); case "pair": return s([c2(n("key")), ": ", c2(n("value"), "Expected value in pair")]); case "object": let childrens = ast.namedChildren.filter((subc) => subc.type !== "comment").map((subc) => c2(subc)); return s(["{", ...join(childrens, ", "), "}"]); case "property_identifier": return s([String(ast.text)]); case "arguments": return s(["(", ...join(children(), ", "), ")"]); case "parenthesized_expression": if (ast.lastNamedChild?.type === "ERROR") { return s(["(", c2(ast.firstNamedChild), ".", ")"]); } return s(["(", c2(ast.firstNamedChild), ")"]); case "function_signature": ctx.report(ast, "Missing function body"); return s(["/*error*/0"]); case "parenthesized_expression_vector": if (ast.firstNamedChild) { if (ast.firstNamedChild.type === "sequence_expression") { return s(["__.makeVector(", c2(ast.firstNamedChild), ")"]); } else { return s(["(", c2(ast.firstNamedChild), ")"]); } } case "if_statement": return s([ "if ", c2(n("condition")), c2(n("consequence")), hasName("alternative") ? c2(n("alternative")) : "" ]); case "else": return s([" else ", c2(ast.firstNamedChild), "\n"]); case "generic_type": return s([c2(n("name")), c2(n("type_arguments"))]); case "type_arguments": return s(["<", ...join(children(), ", "), ">"]); case "array_type": if (ast.namedChildCount == 2) { return s([c2(ast.firstNamedChild), "[", c2(ast.lastNamedChild), "]"]); } else { return s([c2(ast.firstNamedChild), "[]"]); } case "ternary_expression": return s([c2(n("condition")), " ? ", c2(n("consequence")), " : ", c2(n("alternative"))]); case "update_expression": return s([c2(n("argument")), n("operator").text]); case "augmented_assignment_expression": let opMapping = { "+=": "add", "-=": "sub", "*=": "mul", "/=": "div", "%=": "mod" }; let leftAssignAug = n("left"); if (leftAssignAug?.type === "subscript_expression") { return s([ c2(leftAssignAug.childForFieldName("object")), ".__index_assign_op(__.", opMapping[n("operator").text], ", ", c2(leftAssignAug.childForFieldName("index")), ", ", c2(n("right")), ")" ]); } return s([ c2(n("left")), " = __.", opMapping[n("operator").text], "(", c2(n("left")), ", ", c2(n("right")), ")" ]); case "for_statement": return s([ "for (", c2(n("initializer")), " ", c2(n("condition")), " ", c2(n("increment")), ") ", c2(n("body")) ]); case "for_in_statement": let leftFor = n("left"); let rightFor = n("right"); if (leftFor.type === "parenthesized_expression") { let forComponents = []; for (let i = 0; i < leftFor.namedChildren[0].namedChildren.length; i++) { let name = leftFor.namedChildren[0].namedChildren[i]; if (name.type != "identifier") { ctx.report( leftFor.namedChild(i), "Invalid for loop variable name, must be x, y, z or w" ); } let key2 = name.text; if (!["x", "y", "z", "w"].includes(key2)) { ctx.report( leftFor.namedChild(i), "Invalid for loop variable name, must be x, y, z or w" ); } if (forComponents.includes(key2)) { ctx.report(leftFor.namedChild(i), "Duplicate for loop variable name"); } forComponents.push(key2); } forComponents = forComponents.reverse(); let parts = []; parts.push(s(["let __for_iter = ", c2(rightFor), ";\n"])); let indexes = ["x", "y", "z", "w"]; for (let n2 of forComponents) { parts.push( s([ "for (let ", n2, ": __.int = __.int(0); ", n2, " < __for_iter[", indexes.indexOf(n2).toString(), "]; ", n2, "++) {\n" ]) ); } parts.push(s([c2(n("body")), "\n"])); for (let n2 of forComponents) { parts.push(s(["}\n"])); } return s(parts); } return s(["for (let ", c2(n("left")), " of ", c2(n("right")), ") ", c2(n("body"))]); case "while_statement": return s(["while (", c2(n("condition")), ") ", c2(n("body"))]); case "break_statement": return s(["break;"]); case "continue_statement": return s(["continue;"]); case "new_expression": return s(["new ", c2(n("constructor")), c2(n("arguments"))]); case "else_clause": return s([" else ", c2(ast.firstNamedChild), "\n"]); case "statement_block": if (ast.parent.type == "method_definition") { let recur = function(a) { if (a.type == "identifier") { if (a.text == "self") { doesRefSelf = true; } } a.children.forEach(recur); }; let doesRefSelf = false; ast.children.forEach(recur); if (doesRefSelf) { return s(["{let shader_self_temp = this;", ...children(), "}"]); } } return s(["{", ...children(), "}"]); case "import_statement": let sourceString = n("source"); let fromString = sourceString.firstNamedChild?.text; if (fromString) { if (!fromString.startsWith("/") && !fromString.startsWith("@") && !fromString.startsWith(".")) { fromString = "/" + fromString; } } return s([ "import ", ...ast.namedChildCount == 2 ? [" ", c2(ast.firstNamedChild), " from "] : [], new SourceNode(sourceString.startIndex, sourceString.endIndex, [ JSON.stringify(fromString) ]), ";" ]); case "named_imports": return s(["{", ...join(children(), ", "), "}"]); case "import_clause": return s([c2(ast.firstChild)]); case "import_specifier": return hasName("alias") ? s([c2(n("name")), " as ", c2(n("alias"))]) : c2(n("name")); case "predefined_type": return s([String(ast.text)]); case "interface_declaration": return s(["interface ", c2(n("name")), c2(n("body")), "\n"]); case "object_method_signature_type": return s(["{\n", ...children(), "\n}"]); case "method_signature": let isStaticSignature = n("parameters")?.firstNamedChild?.text != "self"; let accessibilityMethod = ast.firstNamedChild?.type === "accessibility_modifier_member" ? "public" : "private"; if (ast.parent?.type === "object_method_signature_type" && ast.parent?.parent?.type === "interface_declaration") { accessibilityMethod = ""; } return s([ accessibilityMethod, " ", ...isStaticSignature ? ["static "] : [], c2(n("name")), c2(n("parameters")), c2(n("return_type")), ";\n" ]); case "type_annotation_arrow": return s([": ", c2(ast.firstNamedChild)]); case "struct_declaration": let impls = ctx.implsFor.get(n("name").text) ?? []; let properties = n("body")?.namedChildren ?? []; properties = properties.filter((i) => { let isStatic2 = false; for (let child of i.children) { if (child.type === "static") { isStatic2 = true; } } return !isStatic2; }); let implBodies = [ ...(ctx.implsFor.get(n("name").text) ?? []).map((i) => i.childForFieldName("body")), ...(ctx.impls.get(n("name").text) ?? []).map((i) => i.childForFieldName("body")), ...properties ]; let staticProperties = n("body")?.namedChildren ?? []; staticProperties = staticProperties.filter((i) => { let isStatic2 = false; for (let child of i.children) { if (child.type === "static") { isStatic2 = true; } } return isStatic2; }); let props = properties.map((i) => ({ name: i.childForFieldName("name")?.text ?? "_unknown", type: i.childForFieldName("type")?.firstNamedChild?.text ?? "", renderedType: compileToString(ctx, i.childForFieldName("type")), default: i.childForFieldName("value") ? compileToString(ctx, i.childForFieldName("value")) : generateDefaultForType(i.childForFieldName("type")?.firstNamedChild?.text ?? "") })); let cls = s([ "/**@shadeup=struct*/class ", c2(n("name")), ...impls.length > 0 ? [ " implements ", ...join( impls.map((i) => c2(i.childForFieldName("for"))), "," ) ] : [], " {\n", ...join( staticProperties.map((i) => { return s([ "public static ", c2(i.childForFieldName("name")), ": ", c2(i.childForFieldName("type")), " = ", c2(i.childForFieldName("value")), ";\n" ]); }), "" ), `constructor(data: {`, `${props.map( (i) => `${i.name}?: ${math_primitives.includes(i.type ?? "") ? "__." + i.type : i.renderedType},` ).join("\n")}`, `}) { `, `${props.map((i) => `this.${i.name} = (data.${i.name} ?? ${i.default}) as any;`).join("\n")}`, ` } `, ...join( implBodies.map((i) => c2(i)), "\n" ), "\n", `clone(): `, c2(n("name")), ` { `, `return new `, c2(n("name")), `({ `, `${props.map((i) => { return `${i.name}: __deepClone(this.${i.name}),`; }).join("\n")}`, `}); `, `} `, "\n}", "\n" ]); return cls; case "object_method_type": return s([...children()]); case "method_definition": let isStatic = n("parameters")?.firstNamedChild?.text != "self"; return s([ ...isStatic ? ["static "] : [], c2(n("name")), c2(n("parameters")), c2(n("body")), "\n" ]); case "impl_for_clause": return s([ast.firstNamedChild.text]); case "unary_expression": let op = ast.firstChild?.text ?? ""; if (op == "-") { return s(["__.negate(", c2(n("argument")), ")"]); } else if (op == "+") { return s(["__.positive(", c2(n("argument")), ")"]); } else if (op == "!") { return s(["__.not(", c2(n("argument")), ")"]); } else { return s([c2(n("argument"))]); } case "class_body": return s(["{\n", ...children(), "\n}"]); case "public_field_definition": let accessibility = ast.firstNamedChild?.type === "accessibility_modifier_member" ? "public" : "private"; return s([accessibility, " ", c2(n("name")), ": ", c2(n("type")), ";\n"]); case "impl_declaration": return s([`/* impl ${n("name")?.text} */ `]); case "lexical_declaration": return s([...children().map((i) => s(["let ", i, ";\n"]))]); case "variable_declarator": let isRoot = ast?.parent?.parent.type === "program"; return s([ c2(n("name")), n("type") ? s([": ", c2(n("type"))]) : "", ...hasName("value") ? [ " = ", ...isRoot ? [ 'globalVarInit("' + cleanName(ctx.fileName) + '", "', c2(n("name")), '", () => { return ', c2(n("value")), "; }, () => { return ", c2(n("name")), "; })" ] : [c2(n("value"))] ] : [" = ", generateDefaultForType(n("type").text.replace(/^:/, "")).trim()] ]); case "object_type": return s([ "{", ...join( ast.namedChildren.map((i) => { return s([c2(i), ","]); }), "" ), "}" ]); case "property_signature": return s([c2(n("name")), ": ", c2(n("type"))]); case "workgroup_member": let typeName = ast.childForFieldName("type")?.firstNamedChild?.text ?? ""; if (typeName === "atomic" || typeName === "atomic") { if (hasName("value")) { ctx.report(ast, "Atomic variables cannot have a default value"); } return s([ "\n// @workgroup\n let ", c2(n("name")), ": ", c2(n("type")), " = ", generateDefaultForType(typeName), ";\n" ]); } if (hasName("value")) { return s([ "\n// @workgroup\n let ", c2(n("name")), ": ", c2(n("type")), " = ", c2(n("value")), ";\n" ]); } else { let t = c2(n("type")); return s([ "\n// @workgroup\n let ", c2(n("name")), ": ", t, " = ", generateDefaultForType(typeName), ";\n" ]); } case "workgroup": return s([...children()]); case "async_block": return s([ "/** Runs immediately but does not block when running async code inside (e.g. downloading textures from the gpu)*/(async () => ", c2(n("body")), ")()" ]); case "shader": let encoder = new TextEncoder(); let u8a = encoder.encode(n("body").text); let key = sha256(u8a).map((x) => x.toString(16).padStart(2, "0")).join(""); if (hasName("type_arguments")) { let isComputeShader = n("type_arguments")?.namedChildCount == 3; if (isComputeShader) { let templateArgsRaw = join( n(`type_arguments`).namedChildren.map((nc) => { let innerString = c2(nc).print(); return innerString.replace(/__\.int\((\d+)\)/g, "$1"); }), ", " ); let templateArgs = join( n(`type_arguments`).namedChildren.map((nc) => { return c2(nc); }), ", " ); return new SourceNode(ast.startIndex, ast.endIndex, [ new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`), new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`), `"${key}", /**@shadeup=shader*/(__in: ShaderInput`, `, __out: {}`, `) => `, c2(n("body")), `) as any, [`, ...templateArgs, `]) as shader<`, ...templateArgsRaw, ">" ]); } else { let arg1 = n("type_arguments")?.firstNamedChild; let arg2 = n("type_arguments")?.lastNamedChild; return new SourceNode(ast.startIndex, ast.endIndex, [ new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`), new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`), `"${key}", /**@shadeup=shader*/(__in:`, c2(arg1), ` & {vertexIndex: __.int}, __out: `, c2(arg2), `) => `, c2(n("body")), `))` ]); } } else { return new SourceNode(ast.startIndex, ast.endIndex, [ new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`), new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`), `"${key}", /**@shadeup=shader*/(__in, __out) => `, c2(n("body")), `))` ]); } case "assignment_expression": let left = n("left"); if (left?.type === "subscript_expression") { return s([ c2(left.childForFieldName("object")), ".__index_assign(", c2(left.childForFieldName("index")), ", ", c2(n("right")), ")" ]); } else if (left?.type == "member_expression") { let prop2 = left.childForFieldName("property"); let p2 = prop2.text ?? ""; if (p2.length > 0 && p2.length < 5) { let isSwizzle = true; for (let i = 0; i < p2.length; i++) { let char = p2[i]; if (char !== "x" && char !== "y" && char !== "z" && char !== "w" && char !== "r" && char !== "g" && char !== "b" && char !== "a") { isSwizzle = false; break; } } if (isSwizzle) { return s([c2(n("left"))]); } else { return s([c2(n("left")), " = ", c2(n("right"))]); } } else { return s([c2(n("left")), " = ", c2(n("right"))]); } } else { return s([c2(n("left")), " = ", c2(n("right"))]); } case "sequence_expression": return s([...join(children(), ", ")]); case "subscript_expression": return s([c2(n("object")), ".__index(", c2(n("index")), ")"]); case "empty_statement": return s([""]); case "true": return s(["true"]); case "false": return s(["false"]); case "null": return s(["null"]); case "union_type": return s([...join(children(), " | ")]); case "intersection_type": return s([...join(children(), " & ")]); case "ERROR": ctx.report(ast, "Syntax error"); if (ast.firstNamedChild?.type == "identifier") { return s([c2(ast.firstNamedChild), "."]); } return s(["/* ERROR */ 0"]); default: ctx.report(ast, "Unsupported syntax"); console.error(new Error("Bad AST " + ast.type)); return s(["/* ERROR */ 0"]); } } function compileToString(ctx, ast) { let sn = compile(ctx, ast); let ss = { str: "", indexMapping: [] }; sn.toString(ss); return ss.str; } function isInShader(ast) { if (ast.type === "shader") { return true; } if (ast.parent) { return isInShader(ast.parent); } return false; } var treeSitter = { exports: {} }; (function(module2, exports3) { var Module = void 0 !== Module ? Module : {}, TreeSitter = function() { var e, t = "object" == typeof window ? { currentScript: window.document.currentScript } : null; class Parser2 { constructor() { this.initialize(); } initialize() { throw new Error("cannot construct a Parser before calling `init()`"); } static init(r) { return e || (Module = Object.assign({}, Module, r), e = new Promise((e2) => { var r2, n = {}; for (r2 in Module) Module.hasOwnProperty(r2) && (n[r2] = Module[r2]); var o, s, _ = [], a = "./this.program", i = function(e3, t2) { throw t2; }, u = false, l = false; u = "object" == typeof window, l = "function" == typeof importScripts, o = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, s = !u && !o && !l; var d, c2, m, f, p, h = ""; o ? (h = l ? require$$0$1.dirname(h) + "/" : __dirname + "/", d = function(e3, t2) { return f || (f = require$$1), p || (p = require$$0$1), e3 = p.normalize(e3), f.readFileSync(e3, t2 ? null : "utf8"); }, m = function(e3) { var t2 = d(e3, true); return t2.buffer || (t2 = new Uint8Array(t2)), k(t2.buffer), t2; }, process.argv.length > 1 && (a = process.argv[1].replace(/\\/g, "/")), _ = process.argv.slice(2), module2.exports = Module, i = function(e3) { process.exit(e3); }, Module.inspect = function() { return "[Emscripten Module object]"; }) : s ? ("undefined" != typeof read && (d = function(e3) { return read(e3); }), m = function(e3) { var t2; return "function" == typeof readbuffer ? new Uint8Array(readbuffer(e3)) : (k("object" == typeof (t2 = read(e3, "binary"))), t2); }, "undefined" != typeof scriptArgs ? _ = scriptArgs : void 0 !== arguments && (_ = arguments), "function" == typeof quit && (i = function(e3) { quit(e3); }), "undefined" != typeof print && ("undefined" == typeof console && (console = {}), console.log = print, console.warn = console.error = "undefined" != typeof printErr ? printErr : print)) : (u || l) && (l ? h = self.location.href : void 0 !== t && t.currentScript && (h = t.currentScript.src), h = 0 !== h.indexOf("blob:") ? h.substr(0, h.lastIndexOf("/") + 1) : "", d = function(e3) { var t2 = new XMLHttpRequest(); return t2.open("GET", e3, false), t2.send(null), t2.responseText; }, l && (m = function(e3) { var t2 = new XMLHttpRequest(); return t2.open("GET", e3, false), t2.responseType = "arraybuffer", t2.send(null), new Uint8Array(t2.response); }), c2 = function(e3, t2, r3) { var n2 = new XMLHttpRequest(); n2.open("GET", e3, true), n2.responseType = "arraybuffer", n2.onload = function() { 200 == n2.status || 0 == n2.status && n2.response ? t2(n2.response) : r3(); }, n2.onerror = r3, n2.send(null); }); Module.print || console.log.bind(console); var g2 = Module.printErr || console.warn.bind(console); for (r2 in n) n.hasOwnProperty(r2) && (Module[r2] = n[r2]); n = null, Module.arguments && (_ = Module.arguments), Module.thisProgram && (a = Module.thisProgram), Module.quit && (i = Module.quit); var w = 16; var M, y = []; function b(e3, t2) { if (!M) { M = /* @__PURE__ */ new WeakMap(); for (var r3 = 0; r3 < K.length; r3++) { var n2 = K.get(r3); n2 && M.set(n2, r3); } } if (M.has(e3)) return M.get(e3); var o2 = function() { if (y.length) return y.pop(); try { K.grow(1); } catch (e4) { if (!(e4 instanceof RangeError)) throw e4; throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."; } return K.length - 1; }(); try { K.set(o2, e3); } catch (r4) { if (!(r4 instanceof TypeError)) throw r4; var s2 = function(e4, t3) { if ("function" == typeof WebAssembly.Function) { for (var r5 = { i: "i32", j: "i64", f: "f32", d: "f64" }, n3 = { parameters: [], results: "v" == t3[0] ? [] : [r5[t3[0]]] }, o3 = 1; o3 < t3.length; ++o3) n3.parameters.push(r5[t3[o3]]); return new WebAssembly.Function(n3, e4); } var s3 = [1, 0, 1, 96], _2 = t3.slice(0, 1), a2 = t3.slice(1), i2 = { i: 127, j: 126, f: 125, d: 124 }; for (s3.push(a2.length), o3 = 0; o3 < a2.length; ++o3) s3.push(i2[a2[o3]]); "v" == _2 ? s3.push(0) : s3 = s3.concat([1, i2[_2]]), s3[1] = s3.length - 2; var u2 = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0].concat(s3, [2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0])), l2 = new WebAssembly.Module(u2); return new WebAssembly.Instance(l2, { e: { f: e4 } }).exports.f; }(e3, t2); K.set(o2, s2); } return M.set(e3, o2), o2; } var v, S = Module.dynamicLibraries || []; Module.wasmBinary && (v = Module.wasmBinary); var I, A = Module.noExitRuntime || true; function x(e3, t2, r3, n2) { switch ("*" === (r3 = r3 || "i8").charAt(r3.length - 1) && (r3 = "i32"), r3) { case "i1": case "i8": q[e3 >> 0] = t2; break; case "i16": R[e3 >> 1] = t2; break; case "i32": W[e3 >> 2] = t2; break; case "i64": ie = [t2 >>> 0, (ae = t2, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[e3 >> 2] = ie[0], W[e3 + 4 >> 2] = ie[1]; break; case "float": L[e3 >> 2] = t2; break; case "double": O[e3 >> 3] = t2; break; default: se("invalid type for setValue: " + r3); } } function N(e3, t2, r3) { switch ("*" === (t2 = t2 || "i8").charAt(t2.length - 1) && (t2 = "i32"), t2) { case "i1": case "i8": return q[e3 >> 0]; case "i16": return R[e3 >> 1]; case "i32": case "i64": return W[e3 >> 2]; case "float": return L[e3 >> 2]; case "double": return O[e3 >> 3]; default: se("invalid type for getValue: " + t2); } return null; } "object" != typeof WebAssembly && se("no native wasm support detected"); var P = false; function k(e3, t2) { e3 || se("Assertion failed: " + t2); } var F = 1; var C, q, T, R, W, L, O, j = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0; function $(e3, t2, r3) { for (var n2 = t2 + r3, o2 = t2; e3[o2] && !(o2 >= n2); ) ++o2; if (o2 - t2 > 16 && e3.subarray && j) return j.decode(e3.subarray(t2, o2)); for (var s2 = ""; t2 < o2; ) { var _2 = e3[t2++]; if (128 & _2) { var a2 = 63 & e3[t2++]; if (192 != (224 & _2)) { var i2 = 63 & e3[t2++]; if ((_2 = 224 == (240 & _2) ? (15 & _2) << 12 | a2 << 6 | i2 : (7 & _2) << 18 | a2 << 12 | i2 << 6 | 63 & e3[t2++]) < 65536) s2 += String.fromCharCode(_2); else { var u2 = _2 - 65536; s2 += String.fromCharCode(55296 | u2 >> 10, 56320 | 1023 & u2); } } else s2 += String.fromCharCode((31 & _2) << 6 | a2); } else s2 += String.fromCharCode(_2); } return s2; } function Z(e3, t2) { return e3 ? $(T, e3, t2) : ""; } function D(e3, t2, r3, n2) { if (!(n2 > 0)) return 0; for (var o2 = r3, s2 = r3 + n2 - 1, _2 = 0; _2 < e3.length; ++_2) { var a2 = e3.charCodeAt(_2); if (a2 >= 55296 && a2 <= 57343) a2 = 65536 + ((1023 & a2) << 10) | 1023 & e3.charCodeAt(++_2); if (a2 <= 127) { if (r3 >= s2) break; t2[r3++] = a2; } else if (a2 <= 2047) { if (r3 + 1 >= s2) break; t2[r3++] = 192 | a2 >> 6, t2[r3++] = 128 | 63 & a2; } else if (a2 <= 65535) { if (r3 + 2 >= s2) break; t2[r3++] = 224 | a2 >> 12, t2[r3++] = 128 | a2 >> 6 & 63, t2[r3++] = 128 | 63 & a2; } else { if (r3 + 3 >= s2) break; t2[r3++] = 240 | a2 >> 18, t2[r3++] = 128 | a2 >> 12 & 63, t2[r3++] = 128 | a2 >> 6 & 63, t2[r3++] = 128 | 63 & a2; } } return t2[r3] = 0, r3 - o2; } function z(e3, t2, r3) { return D(e3, T, t2, r3); } function U(e3) { for (var t2 = 0, r3 = 0; r3 < e3.length; ++r3) { var n2 = e3.charCodeAt(r3); n2 >= 55296 && n2 <= 57343 && (n2 = 65536 + ((1023 & n2) << 10) | 1023 & e3.charCodeAt(++r3)), n2 <= 127 ? ++t2 : t2 += n2 <= 2047 ? 2 : n2 <= 65535 ? 3 : 4; } return t2; } function H(e3) { var t2 = U(e3) + 1, r3 = Be(t2); return D(e3, q, r3, t2), r3; } function G(e3) { C = e3, Module.HEAP8 = q = new Int8Array(e3), Module.HEAP16 = R = new Int16Array(e3), Module.HEAP32 = W = new Int32Array(e3), Module.HEAPU8 = T = new Uint8Array(e3), Module.HEAPU16 = new Uint16Array(e3), Module.HEAPU32 = new Uint32Array(e3), Module.HEAPF32 = L = new Float32Array(e3), Module.HEAPF64 = O = new Float64Array(e3); } var B = Module.INITIAL_MEMORY || 33554432; (I = Module.wasmMemory ? Module.wasmMemory : new WebAssembly.Memory({ initial: B / 65536, maximum: 32768 })) && (C = I.buffer), B = C.byteLength, G(C); var K = new WebAssembly.Table({ initial: 20, element: "anyfunc" }), V = [], X = [], Q = [], J = [], Y = false; var ee = 0, re = null; function ne(e3) { ee++, Module.monitorRunDependencies && Module.monitorRunDependencies(ee); } function oe(e3) { if (ee--, Module.monitorRunDependencies && Module.monitorRunDependencies(ee), 0 == ee && re) { var t2 = re; re = null, t2(); } } function se(e3) { throw Module.onAbort && Module.onAbort(e3), g2(e3 += ""), P = true, e3 = "abort(" + e3 + "). Build with -s ASSERTIONS=1 for more info.", new WebAssembly.RuntimeError(e3); } Module.preloadedImages = {}, Module.preloadedAudios = {}, Module.preloadedWasm = {}; var _e, ae, ie, ue = "data:application/octet-stream;base64,"; function le(e3) { return e3.startsWith(ue); } function de(e3) { return e3.startsWith("file://"); } function ce(e3) { try { if (e3 == _e && v) return new Uint8Array(v); if (m) return m(e3); throw "both async and sync fetching of the wasm failed"; } catch (e4) { se(e4); } } le(_e = "tree-sitter.wasm") || (_e = function(e3) { return Module.locateFile ? Module.locateFile(e3, h) : h + e3; }(_e)); var me = {}, fe = { get: function(e3, t2) { return me[t2] || (me[t2] = new WebAssembly.Global({ value: "i32", mutable: true })), me[t2]; } }; function pe(e3) { for (; e3.length > 0; ) { var t2 = e3.shift(); if ("function" != typeof t2) { var r3 = t2.func; "number" == typeof r3 ? void 0 === t2.arg ? K.get(r3)() : K.get(r3)(t2.arg) : r3(void 0 === t2.arg ? null : t2.arg); } else t2(Module); } } function he(e3) { var t2 = 0; function r3() { for (var r4 = 0, n3 = 1; ; ) { var o3 = e3[t2++]; if (r4 += (127 & o3) * n3, n3 *= 128, !(128 & o3)) break; } return r4; } if (e3 instanceof WebAssembly.Module) { var n2 = WebAssembly.Module.customSections(e3, "dylink"); k(0 != n2.length, "need dylink section"), e3 = new Int8Array(n2[0]); } else { k(1836278016 == new Uint32Array(new Uint8Array(e3.subarray(0, 24)).buffer)[0], "need to see wasm magic number"), k(0 === e3[8], "need the dylink section to be first"), t2 = 9, r3(), k(6 === e3[t2]), k(e3[++t2] === "d".charCodeAt(0)), k(e3[++t2] === "y".charCodeAt(0)), k(e3[++t2] === "l".charCodeAt(0)), k(e3[++t2] === "i".charCodeAt(0)), k(e3[++t2] === "n".charCodeAt(0)), k(e3[++t2] === "k".charCodeAt(0)), t2++; } var o2 = {}; o2.memorySize = r3(), o2.memoryAlign = r3(), o2.tableSize = r3(), o2.tableAlign = r3(); var s2 = r3(); o2.neededDynlibs = []; for (var _2 = 0; _2 < s2; ++_2) { var a2 = r3(), i2 = e3.subarray(t2, t2 + a2); t2 += a2; var u2 = $(i2, 0); o2.neededDynlibs.push(u2); } return o2; } var ge = 0; function we() { return A || ge > 0; } function Me(e3) { return 0 == e3.indexOf("dynCall_") || ["stackAlloc", "stackSave", "stackRestore"].includes(e3) ? e3 : "_" + e3; } function ye(e3, t2) { for (var r3 in e3) if (e3.hasOwnProperty(r3)) { De.hasOwnProperty(r3) || (De[r3] = e3[r3]); var n2 = Me(r3); Module.hasOwnProperty(n2) || (Module[n2] = e3[r3]); } } var be = { nextHandle: 1, loadedLibs: {}, loadedLibNames: {} }; function ve(e3, t2, r3) { return e3.includes("j") ? function(e4, t3, r4) { var n2 = Module["dynCall_" + e4]; return r4 && r4.length ? n2.apply(null, [t3].concat(r4)) : n2.call(null, t3); }(e3, t2, r3) : K.get(t2).apply(null, r3); } var Ee = 5251072; function Se(e3) { return ["__cpp_exception", "__wasm_apply_data_relocs", "__dso_handle", "__set_stack_limits"].includes(e3); } function Ie(e3, t2) { var r3 = {}; for (var n2 in e3) { var o2 = e3[n2]; "object" == typeof o2 && (o2 = o2.value), "number" == typeof o2 && (o2 += t2), r3[n2] = o2; } return function(e4) { for (var t3 in e4) if (!Se(t3)) { var r4 = false, n3 = e4[t3]; t3.startsWith("orig$") && (t3 = t3.split("$")[1], r4 = true), me[t3] || (me[t3] = new WebAssembly.Global({ value: "i32", mutable: true })), (r4 || 0 == me[t3].value) && ("function" == typeof n3 ? me[t3].value = b(n3) : "number" == typeof n3 ? me[t3].value = n3 : g2("unhandled export type for `" + t3 + "`: " + typeof n3)); } }(r3), r3; } function Ae(e3, t2) { var r3, n2; return t2 && (r3 = De["orig$" + e3]), r3 || (r3 = De[e3]), r3 || (r3 = Module[Me(e3)]), !r3 && e3.startsWith("invoke_") && (n2 = e3.split("_")[1], r3 = function() { var e4 = He(); try { return ve(n2, arguments[0], Array.prototype.slice.call(arguments, 1)); } catch (t3) { if (Ge(e4), t3 !== t3 + 0 && "longjmp" !== t3) throw t3; Ke(1, 0); } }), r3; } function xe(e3, t2) { var r3 = he(e3); function n2() { var n3 = Math.pow(2, r3.memoryAlign); n3 = Math.max(n3, w); var o2, s2, _2, a2 = (o2 = function(e4) { if (Y) return ze(e4); var t3 = Ee, r4 = t3 + e4 + 15 & -16; return Ee = r4, me.__heap_base.value = r4, t3; }(r3.memorySize + n3), (s2 = n3) || (s2 = w), Math.ceil(o2 / s2) * s2), i2 = K.length; K.grow(r3.tableSize); for (var u2 = a2; u2 < a2 + r3.memorySize; u2++) q[u2] = 0; for (u2 = i2; u2 < i2 + r3.tableSize; u2++) K.set(u2, null); var l2 = new Proxy({}, { get: function(e4, t3) { switch (t3) { case "__memory_base": return a2; case "__table_base": return i2; } if (t3 in De) return De[t3]; var r4; t3 in e4 || (e4[t3] = function() { return r4 || (r4 = function(e5) { var t4 = Ae(e5, false); return t4 || (t4 = _2[e5]), t4; }(t3)), r4.apply(null, arguments); }); return e4[t3]; } }), d2 = { "GOT.mem": new Proxy({}, fe), "GOT.func": new Proxy({}, fe), env: l2, wasi_snapshot_preview1: l2 }; function c3(e4) { for (var n4 = 0; n4 < r3.tableSize; n4++) { var o3 = K.get(i2 + n4); o3 && M.set(o3, i2 + n4); } _2 = Ie(e4.exports, a2), t2.allowUndefined || Pe(); var s3 = _2.__wasm_call_ctors; return s3 || (s3 = _2.__post_instantiate), s3 && (Y ? s3() : X.push(s3)), _2; } if (t2.loadAsync) { if (e3 instanceof WebAssembly.Module) { var m2 = new WebAssembly.Instance(e3, d2); return Promise.resolve(c3(m2)); } return WebAssembly.instantiate(e3, d2).then(function(e4) { return c3(e4.instance); }); } var f2 = e3 instanceof WebAssembly.Module ? e3 : new WebAssembly.Module(e3); return c3(m2 = new WebAssembly.Instance(f2, d2)); } return t2.loadAsync ? r3.neededDynlibs.reduce(function(e4, r4) { return e4.then(function() { return Ne(r4, t2); }); }, Promise.resolve()).then(function() { return n2(); }) : (r3.neededDynlibs.forEach(function(e4) { Ne(e4, t2); }), n2()); } function Ne(e3, t2) { "__main__" != e3 || be.loadedLibNames[e3] || (be.loadedLibs[-1] = { refcount: 1 / 0, name: "__main__", module: Module.asm, global: true }, be.loadedLibNames.__main__ = -1), t2 = t2 || { global: true, nodelete: true }; var r3, n2 = be.loadedLibNames[e3]; if (n2) return r3 = be.loadedLibs[n2], t2.global && !r3.global && (r3.global = true, "loading" !== r3.module && ye(r3.module)), t2.nodelete && r3.refcount !== 1 / 0 && (r3.refcount = 1 / 0), r3.refcount++, t2.loadAsync ? Promise.resolve(n2) : n2; function o2(e4) { if (t2.fs) { var r4 = t2.fs.readFile(e4, { encoding: "binary" }); return r4 instanceof Uint8Array || (r4 = new Uint8Array(r4)), t2.loadAsync ? Promise.resolve(r4) : r4; } return t2.loadAsync ? (n3 = e4, fetch(n3, { credentials: "same-origin" }).then(function(e5) { if (!e5.ok) throw "failed to load binary file at '" + n3 + "'"; return e5.arrayBuffer(); }).then(function(e5) { return new Uint8Array(e5); })) : m(e4); var n3; } function s2() { if (void 0 !== Module.preloadedWasm && void 0 !== Module.preloadedWasm[e3]) { var r4 = Module.preloadedWasm[e3]; return t2.loadAsync ? Promise.resolve(r4) : r4; } return t2.loadAsync ? o2(e3).then(function(e4) { return xe(e4, t2); }) : xe(o2(e3), t2); } function _2(e4) { r3.global && ye(e4), r3.module = e4; } return n2 = be.nextHandle++, r3 = { refcount: t2.nodelete ? 1 / 0 : 1, name: e3, module: "loading", global: t2.global }, be.loadedLibNames[e3] = n2, be.loadedLibs[n2] = r3, t2.loadAsync ? s2().then(function(e4) { return _2(e4), n2; }) : (_2(s2()), n2); } function Pe() { for (var e3 in me) if (0 == me[e3].value) { var t2 = Ae(e3, true); "function" == typeof t2 ? me[e3].value = b(t2, t2.sig) : "number" == typeof t2 ? me[e3].value = t2 : k(false, "bad export type for `" + e3 + "`: " + typeof t2); } } Module.___heap_base = Ee; var ke, Fe = new WebAssembly.Global({ value: "i32", mutable: true }, 5251072); function Ce() { se(); } Module._abort = Ce, Ce.sig = "v", ke = o ? function() { var e3 = process.hrtime(); return 1e3 * e3[0] + e3[1] / 1e6; } : "undefined" != typeof dateNow ? dateNow : function() { return performance.now(); }; var qe = true; function Te(e3, t2) { var r3, n2; if (0 === e3) r3 = Date.now(); else { if (1 !== e3 && 4 !== e3 || !qe) return n2 = 28, W[Ue() >> 2] = n2, -1; r3 = ke(); } return W[t2 >> 2] = r3 / 1e3 | 0, W[t2 + 4 >> 2] = r3 % 1e3 * 1e3 * 1e3 | 0, 0; } function Re(e3) { try { return I.grow(e3 - C.byteLength + 65535 >>> 16), G(I.buffer), 1; } catch (e4) { } } function We(e3) { Je(e3); } Te.sig = "iii", We.sig = "vi"; var Le = { mappings: {}, DEFAULT_POLLMASK: 5, umask: 511, calculateAt: function(e3, t2, r3) { if ("/" === t2[0]) return t2; var n2; if (-100 === e3) n2 = FS.cwd(); else { var o2 = FS.getStream(e3); if (!o2) throw new FS.ErrnoError(8); n2 = o2.path; } if (0 == t2.length) { if (!r3) throw new FS.ErrnoError(44); return n2; } return PATH.join2(n2, t2); }, doStat: function(e3, t2, r3) { try { var n2 = e3(t2); } catch (e4) { if (e4 && e4.node && PATH.normalize(t2) !== PATH.normalize(FS.getPath(e4.node))) return -54; throw e4; } return W[r3 >> 2] = n2.dev, W[r3 + 4 >> 2] = 0, W[r3 + 8 >> 2] = n2.ino, W[r3 + 12 >> 2] = n2.mode, W[r3 + 16 >> 2] = n2.nlink, W[r3 + 20 >> 2] = n2.uid, W[r3 + 24 >> 2] = n2.gid, W[r3 + 28 >> 2] = n2.rdev, W[r3 + 32 >> 2] = 0, ie = [n2.size >>> 0, (ae = n2.size, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[r3 + 40 >> 2] = ie[0], W[r3 + 44 >> 2] = ie[1], W[r3 + 48 >> 2] = 4096, W[r3 + 52 >> 2] = n2.blocks, W[r3 + 56 >> 2] = n2.atime.getTime() / 1e3 | 0, W[r3 + 60 >> 2] = 0, W[r3 + 64 >> 2] = n2.mtime.getTime() / 1e3 | 0, W[r3 + 68 >> 2] = 0, W[r3 + 72 >> 2] = n2.ctime.getTime() / 1e3 | 0, W[r3 + 76 >> 2] = 0, ie = [n2.ino >>> 0, (ae = n2.ino, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[r3 + 80 >> 2] = ie[0], W[r3 + 84 >> 2] = ie[1], 0; }, doMsync: function(e3, t2, r3, n2, o2) { var s2 = T.slice(e3, e3 + r3); FS.msync(t2, s2, o2, r3, n2); }, doMkdir: function(e3, t2) { return "/" === (e3 = PATH.normalize(e3))[e3.length - 1] && (e3 = e3.substr(0, e3.length - 1)), FS.mkdir(e3, t2, 0), 0; }, doMknod: function(e3, t2, r3) { switch (61440 & t2) { case 32768: case 8192: case 24576: case 4096: case 49152: break; default: return -28; } return FS.mknod(e3, t2, r3), 0; }, doReadlink: function(e3, t2, r3) { if (r3 <= 0) return -28; var n2 = FS.readlink(e3), o2 = Math.min(r3, U(n2)), s2 = q[t2 + o2]; return z(n2, t2, r3 + 1), q[t2 + o2] = s2, o2; }, doAccess: function(e3, t2) { if (-8 & t2) return -28; var r3; if (!(r3 = FS.lookupPath(e3, { follow: true }).node)) return -44; var n2 = ""; return 4 & t2 && (n2 += "r"), 2 & t2 && (n2 += "w"), 1 & t2 && (n2 += "x"), n2 && FS.nodePermissions(r3, n2) ? -2 : 0; }, doDup: function(e3, t2, r3) { var n2 = FS.getStream(r3); return n2 && FS.close(n2), FS.open(e3, t2, 0, r3, r3).fd; }, doReadv: function(e3, t2, r3, n2) { for (var o2 = 0, s2 = 0; s2 < r3; s2++) { var _2 = W[t2 + 8 * s2 >> 2], a2 = W[t2 + (8 * s2 + 4) >> 2], i2 = FS.read(e3, q, _2, a2, n2); if (i2 < 0) return -1; if (o2 += i2, i2 < a2) break; } return o2; }, doWritev: function(e3, t2, r3, n2) { for (var o2 = 0, s2 = 0; s2 < r3; s2++) { var _2 = W[t2 + 8 * s2 >> 2], a2 = W[t2 + (8 * s2 + 4) >> 2], i2 = FS.write(e3, q, _2, a2, n2); if (i2 < 0) return -1; o2 += i2; } return o2; }, varargs: void 0, get: function() { return Le.varargs += 4, W[Le.varargs - 4 >> 2]; }, getStr: function(e3) { return Z(e3); }, getStreamFromFD: function(e3) { var t2 = FS.getStream(e3); if (!t2) throw new FS.ErrnoError(8); return t2; }, get64: function(e3, t2) { return e3; } }; function Oe(e3) { try { var t2 = Le.getStreamFromFD(e3); return FS.close(t2), 0; } catch (e4) { return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno; } } function je(e3, t2, r3, n2) { try { var o2 = Le.getStreamFromFD(e3), s2 = Le.doWritev(o2, t2, r3); return W[n2 >> 2] = s2, 0; } catch (e4) { return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno; } } function $e(e3) { } Oe.sig = "ii", je.sig = "iiiii", $e.sig = "vi"; var Ze, De = { __heap_base: Ee, __indirect_function_table: K, __memory_base: 1024, __stack_pointer: Fe, __table_base: 1, abort: Ce, clock_gettime: Te, emscripten_memcpy_big: function(e3, t2, r3) { T.copyWithin(e3, t2, t2 + r3); }, emscripten_resize_heap: function(e3) { var t2, r3, n2 = T.length; if ((e3 >>>= 0) > 2147483648) return false; for (var o2 = 1; o2 <= 4; o2 *= 2) { var s2 = n2 * (1 + 0.2 / o2); if (s2 = Math.min(s2, e3 + 100663296), Re(Math.min(2147483648, ((t2 = Math.max(e3, s2)) % (r3 = 65536) > 0 && (t2 += r3 - t2 % r3), t2)))) return true; } return false; }, exit: We, fd_close: Oe, fd_seek: function(e3, t2, r3, n2, o2) { try { var s2 = Le.getStreamFromFD(e3), _2 = 4294967296 * r3 + (t2 >>> 0); return _2 <= -9007199254740992 || _2 >= 9007199254740992 ? -61 : (FS.llseek(s2, _2, n2), ie = [s2.position >>> 0, (ae = s2.position, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[o2 >> 2] = ie[0], W[o2 + 4 >> 2] = ie[1], s2.getdents && 0 === _2 && 0 === n2 && (s2.getdents = null), 0); } catch (e4) { return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno; } }, fd_write: je, memory: I, setTempRet0: $e, tree_sitter_log_callback: function(e3, t2) { if (pt) { const r3 = Z(t2); pt(r3, 0 !== e3); } }, tree_sitter_parse_callback: function(e3, t2, r3, n2, o2) { var s2 = ft(t2, { row: r3, column: n2 }); "string" == typeof s2 ? (x(o2, s2.length, "i32"), function(e4, t3, r4) { if (void 0 === r4 && (r4 = 2147483647), r4 < 2) return 0; for (var n3 = (r4 -= 2) < 2 * e4.length ? r4 / 2 : e4.length, o3 = 0; o3 < n3; ++o3) { var s3 = e4.charCodeAt(o3); R[t3 >> 1] = s3, t3 += 2; } R[t3 >> 1] = 0; }(s2, e3, 10240)) : x(o2, 0, "i32"); } }, ze = (function() { var e3 = { env: De, wasi_snapshot_preview1: De, "GOT.mem": new Proxy(De, fe), "GOT.func": new Proxy(De, fe) }; function t2(e4, t3) { var r4 = e4.exports; r4 = Ie(r4, 1024), Module.asm = r4; var n3, o2 = he(t3); o2.neededDynlibs && (S = o2.neededDynlibs.concat(S)), ye(r4), n3 = Module.asm.__wasm_call_ctors, X.unshift(n3), oe(); } function r3(e4) { t2(e4.instance, e4.module); } function n2(t3) { return function() { if (!v && (u || l)) { if ("function" == typeof fetch && !de(_e)) return fetch(_e, { credentials: "same-origin" }).then(function(e4) { if (!e4.ok) throw "failed to load wasm binary file at '" + _e + "'"; return e4.arrayBuffer(); }).catch(function() { return ce(_e); }); if (c2) return new Promise(function(e4, t4) { c2(_e, function(t5) { e4(new Uint8Array(t5)); }, t4); }); } return Promise.resolve().then(function() { return ce(_e); }); }().then(function(t4) { return WebAssembly.instantiate(t4, e3); }).then(t3, function(e4) { g2("failed to asynchronously prepare wasm: " + e4), se(e4); }); } if (ne(), Module.instantiateWasm) try { return Module.instantiateWasm(e3, t2); } catch (e4) { return g2("Module.instantiateWasm callback failed with error: " + e4), false; } v || "function" != typeof WebAssembly.instantiateStreaming || le(_e) || de(_e) || "function" != typeof fetch ? n2(r3) : fetch(_e, { credentials: "same-origin" }).then(function(t3) { return WebAssembly.instantiateStreaming(t3, e3).then(r3, function(e4) { return g2("wasm streaming compile failed: " + e4), g2("falling back to ArrayBuffer instantiation"), n2(r3); }); }); }(), Module.___wasm_call_ctors = function() { return (Module.___wasm_call_ctors = Module.asm.__wasm_call_ctors).apply(null, arguments); }, Module._malloc = function() { return (ze = Module._malloc = Module.asm.malloc).apply(null, arguments); }), Ue = (Module._calloc = function() { return (Module._calloc = Module.asm.calloc).apply(null, arguments); }, Module._realloc = function() { return (Module._realloc = Module.asm.realloc).apply(null, arguments); }, Module._free = function() { return (Module._free = Module.asm.free).apply(null, arguments); }, Module._ts_language_symbol_count = function() { return (Module._ts_language_symbol_count = Module.asm.ts_language_symbol_count).apply(null, arguments); }, Module._ts_language_version = function() { return (Module._ts_language_version = Module.asm.ts_language_version).apply(null, arguments); }, Module._ts_language_field_count = function() { return (Module._ts_language_field_count = Module.asm.ts_language_field_count).apply(null, arguments); }, Module._ts_language_symbol_name = function() { return (Module._ts_language_symbol_name = Module.asm.ts_language_symbol_name).apply(null, arguments); }, Module._ts_language_symbol_for_name = function() { return (Module._ts_language_symbol_for_name = Module.asm.ts_language_symbol_for_name).apply(null, arguments); }, Module._ts_language_symbol_type = function() { return (Module._ts_language_symbol_type = Module.asm.ts_language_symbol_type).apply(null, arguments); }, Module._ts_language_field_name_for_id = function() { return (Module._ts_language_field_name_for_id = Module.asm.ts_language_field_name_for_id).apply(null, arguments); }, Module._memcpy = function() { return (Module._memcpy = Module.asm.memcpy).apply(null, arguments); }, Module._ts_parser_delete = function() { return (Module._ts_parser_delete = Module.asm.ts_parser_delete).apply(null, arguments); }, Module._ts_parser_reset = function() { return (Module._ts_parser_reset = Module.asm.ts_parser_reset).apply(null, arguments); }, Module._ts_parser_set_language = function() { return (Module._ts_parser_set_language = Module.asm.ts_parser_set_language).apply(null, arguments); }, Module._ts_parser_timeout_micros = function() { return (Module._ts_parser_timeout_micros = Module.asm.ts_parser_timeout_micros).apply(null, arguments); }, Module._ts_parser_set_timeout_micros = function() { return (Module._ts_parser_set_timeout_micros = Module.asm.ts_parser_set_timeout_micros).apply(null, arguments); }, Module._memmove = function() { return (Module._memmove = Module.asm.memmove).apply(null, arguments); }, Module._memcmp = function() { return (Module._memcmp = Module.asm.memcmp).apply(null, arguments); }, Module._ts_query_new = function() { return (Module._ts_query_new = Module.asm.ts_query_new).apply(null, arguments); }, Module._ts_query_delete = function() { return (Module._ts_query_delete = Module.asm.ts_query_delete).apply(null, arguments); }, Module._iswspace = function() { return (Module._iswspace = Module.asm.iswspace).apply(null, arguments); }, Module._iswalnum = function() { return (Module._iswalnum = Module.asm.iswalnum).apply(null, arguments); }, Module._ts_query_pattern_count = function() { return (Module._ts_query_pattern_count = Module.asm.ts_query_pattern_count).apply(null, arguments); }, Module._ts_query_capture_count = function() { return (Module._ts_query_capture_count = Module.asm.ts_query_capture_count).apply(null, arguments); }, Module._ts_query_string_count = function() { return (Module._ts_query_string_count = Module.asm.ts_query_string_count).apply(null, arguments); }, Module._ts_query_capture_name_for_id = function() { return (Module._ts_query_capture_name_for_id = Module.asm.ts_query_capture_name_for_id).apply(null, arguments); }, Module._ts_query_string_value_for_id = function() { return (Module._ts_query_string_value_for_id = Module.asm.ts_query_string_value_for_id).apply(null, arguments); }, Module._ts_query_predicates_for_pattern = function() { return (Module._ts_query_predicates_for_pattern = Module.asm.ts_query_predicates_for_pattern).apply(null, arguments); }, Module._ts_tree_copy = function() { return (Module._ts_tree_copy = Module.asm.ts_tree_copy).apply(null, arguments); }, Module._ts_tree_delete = function() { return (Module._ts_tree_delete = Module.asm.ts_tree_delete).apply(null, arguments); }, Module._ts_init = function() { return (Module._ts_init = Module.asm.ts_init).apply(null, arguments); }, Module._ts_parser_new_wasm = function() { return (Module._ts_parser_new_wasm = Module.asm.ts_parser_new_wasm).apply(null, arguments); }, Module._ts_parser_enable_logger_wasm = function() { return (Module._ts_parser_enable_logger_wasm = Module.asm.ts_parser_enable_logger_wasm).apply(null, arguments); }, Module._ts_parser_parse_wasm = function() { return (Module._ts_parser_parse_wasm = Module.asm.ts_parser_parse_wasm).apply(null, arguments); }, Module._ts_language_type_is_named_wasm = function() { return (Module._ts_language_type_is_named_wasm = Module.asm.ts_language_type_is_named_wasm).apply(null, arguments); }, Module._ts_language_type_is_visible_wasm = function() { return (Module._ts_language_type_is_visible_wasm = Module.asm.ts_language_type_is_visible_wasm).apply(null, arguments); }, Module._ts_tree_root_node_wasm = function() { return (Module._ts_tree_root_node_wasm = Module.asm.ts_tree_root_node_wasm).apply(null, arguments); }, Module._ts_tree_edit_wasm = function() { return (Module._ts_tree_edit_wasm = Module.asm.ts_tree_edit_wasm).apply(null, arguments); }, Module._ts_tree_get_changed_ranges_wasm = function() { return (Module._ts_tree_get_changed_ranges_wasm = Module.asm.ts_tree_get_changed_ranges_wasm).apply(null, arguments); }, Module._ts_tree_cursor_new_wasm = function() { return (Module._ts_tree_cursor_new_wasm = Module.asm.ts_tree_cursor_new_wasm).apply(null, arguments); }, Module._ts_tree_cursor_delete_wasm = function() { return (Module._ts_tree_cursor_delete_wasm = Module.asm.ts_tree_cursor_delete_wasm).apply(null, arguments); }, Module._ts_tree_cursor_reset_wasm = function() { return (Module._ts_tree_cursor_reset_wasm = Module.asm.ts_tree_cursor_reset_wasm).apply(null, arguments); }, Module._ts_tree_cursor_goto_first_child_wasm = function() { return (Module._ts_tree_cursor_goto_first_child_wasm = Module.asm.ts_tree_cursor_goto_first_child_wasm).apply(null, arguments); }, Module._ts_tree_cursor_goto_next_sibling_wasm = function() { return (Module._ts_tree_cursor_goto_next_sibling_wasm = Module.asm.ts_tree_cursor_goto_next_sibling_wasm).apply(null, arguments); }, Module._ts_tree_cursor_goto_parent_wasm = function() { return (Module._ts_tree_cursor_goto_parent_wasm = Module.asm.ts_tree_cursor_goto_parent_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_type_id_wasm = function() { return (Module._ts_tree_cursor_current_node_type_id_wasm = Module.asm.ts_tree_cursor_current_node_type_id_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_is_named_wasm = function() { return (Module._ts_tree_cursor_current_node_is_named_wasm = Module.asm.ts_tree_cursor_current_node_is_named_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_is_missing_wasm = function() { return (Module._ts_tree_cursor_current_node_is_missing_wasm = Module.asm.ts_tree_cursor_current_node_is_missing_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_id_wasm = function() { return (Module._ts_tree_cursor_current_node_id_wasm = Module.asm.ts_tree_cursor_current_node_id_wasm).apply(null, arguments); }, Module._ts_tree_cursor_start_position_wasm = function() { return (Module._ts_tree_cursor_start_position_wasm = Module.asm.ts_tree_cursor_start_position_wasm).apply(null, arguments); }, Module._ts_tree_cursor_end_position_wasm = function() { return (Module._ts_tree_cursor_end_position_wasm = Module.asm.ts_tree_cursor_end_position_wasm).apply(null, arguments); }, Module._ts_tree_cursor_start_index_wasm = function() { return (Module._ts_tree_cursor_start_index_wasm = Module.asm.ts_tree_cursor_start_index_wasm).apply(null, arguments); }, Module._ts_tree_cursor_end_index_wasm = function() { return (Module._ts_tree_cursor_end_index_wasm = Module.asm.ts_tree_cursor_end_index_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_field_id_wasm = function() { return (Module._ts_tree_cursor_current_field_id_wasm = Module.asm.ts_tree_cursor_current_field_id_wasm).apply(null, arguments); }, Module._ts_tree_cursor_current_node_wasm = function() { return (Module._ts_tree_cursor_current_node_wasm = Module.asm.ts_tree_cursor_current_node_wasm).apply(null, arguments); }, Module._ts_node_symbol_wasm = function() { return (Module._ts_node_symbol_wasm = Module.asm.ts_node_symbol_wasm).apply(null, arguments); }, Module._ts_node_child_count_wasm = function() { return (Module._ts_node_child_count_wasm = Module.asm.ts_node_child_count_wasm).apply(null, arguments); }, Module._ts_node_named_child_count_wasm = function() { return (Module._ts_node_named_child_count_wasm = Module.asm.ts_node_named_child_count_wasm).apply(null, arguments); }, Module._ts_node_child_wasm = function() { return (Module._ts_node_child_wasm = Module.asm.ts_node_child_wasm).apply(null, arguments); }, Module._ts_node_named_child_wasm = function() { return (Module._ts_node_named_child_wasm = Module.asm.ts_node_named_child_wasm).apply(null, arguments); }, Module._ts_node_child_by_field_id_wasm = function() { return (Module._ts_node_child_by_field_id_wasm = Module.asm.ts_node_child_by_field_id_wasm).apply(null, arguments); }, Module._ts_node_next_sibling_wasm = function() { return (Module._ts_node_next_sibling_wasm = Module.asm.ts_node_next_sibling_wasm).apply(null, arguments); }, Module._ts_node_prev_sibling_wasm = function() { return (Module._ts_node_prev_sibling_wasm = Module.asm.ts_node_prev_sibling_wasm).apply(null, arguments); }, Module._ts_node_next_named_sibling_wasm = function() { return (Module._ts_node_next_named_sibling_wasm = Module.asm.ts_node_next_named_sibling_wasm).apply(null, arguments); }, Module._ts_node_prev_named_sibling_wasm = function() { return (Module._ts_node_prev_named_sibling_wasm = Module.asm.ts_node_prev_named_sibling_wasm).apply(null, arguments); }, Module._ts_node_parent_wasm = function() { return (Module._ts_node_parent_wasm = Module.asm.ts_node_parent_wasm).apply(null, arguments); }, Module._ts_node_descendant_for_index_wasm = function() { return (Module._ts_node_descendant_for_index_wasm = Module.asm.ts_node_descendant_for_index_wasm).apply(null, arguments); }, Module._ts_node_named_descendant_for_index_wasm = function() { return (Module._ts_node_named_descendant_for_index_wasm = Module.asm.ts_node_named_descendant_for_index_wasm).apply(null, arguments); }, Module._ts_node_descendant_for_position_wasm = function() { return (Module._ts_node_descendant_for_position_wasm = Module.asm.ts_node_descendant_for_position_wasm).apply(null, arguments); }, Module._ts_node_named_descendant_for_position_wasm = function() { return (Module._ts_node_named_descendant_for_position_wasm = Module.asm.ts_node_named_descendant_for_position_wasm).apply(null, arguments); }, Module._ts_node_start_point_wasm = function() { return (Module._ts_node_start_point_wasm = Module.asm.ts_node_start_point_wasm).apply(null, arguments); }, Module._ts_node_end_point_wasm = function() { return (Module._ts_node_end_point_wasm = Module.asm.ts_node_end_point_wasm).apply(null, arguments); }, Module._ts_node_start_index_wasm = function() { return (Module._ts_node_start_index_wasm = Module.asm.ts_node_start_index_wasm).apply(null, arguments); }, Module._ts_node_end_index_wasm = function() { return (Module._ts_node_end_index_wasm = Module.asm.ts_node_end_index_wasm).apply(null, arguments); }, Module._ts_node_to_string_wasm = function() { return (Module._ts_node_to_string_wasm = Module.asm.ts_node_to_string_wasm).apply(null, arguments); }, Module._ts_node_children_wasm = function() { return (Module._ts_node_children_wasm = Module.asm.ts_node_children_wasm).apply(null, arguments); }, Module._ts_node_named_children_wasm = function() { return (Module._ts_node_named_children_wasm = Module.asm.ts_node_named_children_wasm).apply(null, arguments); }, Module._ts_node_descendants_of_type_wasm = function() { return (Module._ts_node_descendants_of_type_wasm = Module.asm.ts_node_descendants_of_type_wasm).apply(null, arguments); }, Module._ts_node_is_named_wasm = function() { return (Module._ts_node_is_named_wasm = Module.asm.ts_node_is_named_wasm).apply(null, arguments); }, Module._ts_node_has_changes_wasm = function() { return (Module._ts_node_has_changes_wasm = Module.asm.ts_node_has_changes_wasm).apply(null, arguments); }, Module._ts_node_has_error_wasm = function() { return (Module._ts_node_has_error_wasm = Module.asm.ts_node_has_error_wasm).apply(null, arguments); }, Module._ts_node_is_missing_wasm = function() { return (Module._ts_node_is_missing_wasm = Module.asm.ts_node_is_missing_wasm).apply(null, arguments); }, Module._ts_query_matches_wasm = function() { return (Module._ts_query_matches_wasm = Module.asm.ts_query_matches_wasm).apply(null, arguments); }, Module._ts_query_captures_wasm = function() { return (Module._ts_query_captures_wasm = Module.asm.ts_query_captures_wasm).apply(null, arguments); }, Module._iswdigit = function() { return (Module._iswdigit = Module.asm.iswdigit).apply(null, arguments); }, Module._iswalpha = function() { return (Module._iswalpha = Module.asm.iswalpha).apply(null, arguments); }, Module._iswlower = function() { return (Module._iswlower = Module.asm.iswlower).apply(null, arguments); }, Module._towupper = function() { return (Module._towupper = Module.asm.towupper).apply(null, arguments); }, Module.___errno_location = function() { return (Ue = Module.___errno_location = Module.asm.__errno_location).apply(null, arguments); }), He = (Module._memchr = function() { return (Module._memchr = Module.asm.memchr).apply(null, arguments); }, Module._strlen = function() { return (Module._strlen = Module.asm.strlen).apply(null, arguments); }, Module.stackSave = function() { return (He = Module.stackSave = Module.asm.stackSave).apply(null, arguments); }), Ge = Module.stackRestore = function() { return (Ge = Module.stackRestore = Module.asm.stackRestore).apply(null, arguments); }, Be = Module.stackAlloc = function() { return (Be = Module.stackAlloc = Module.asm.stackAlloc).apply(null, arguments); }, Ke = Module._setThrew = function() { return (Ke = Module._setThrew = Module.asm.setThrew).apply(null, arguments); }; Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm).apply(null, arguments); }, Module.__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm = function() { return (Module.__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm = Module.asm._ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc = function() { return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev = function() { return (Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev = Module.asm._ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev).apply(null, arguments); }, Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw = function() { return (Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw = Module.asm._ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw).apply(null, arguments); }, Module.__Znwm = function() { return (Module.__Znwm = Module.asm._Znwm).apply(null, arguments); }, Module.__ZdlPv = function() { return (Module.__ZdlPv = Module.asm._ZdlPv).apply(null, arguments); }, Module.dynCall_jiji = function() { return (Module.dynCall_jiji = Module.asm.dynCall_jiji).apply(null, arguments); }, Module._orig$ts_parser_timeout_micros = function() { return (Module._orig$ts_parser_timeout_micros = Module.asm.orig$ts_parser_timeout_micros).apply(null, arguments); }, Module._orig$ts_parser_set_timeout_micros = function() { return (Module._orig$ts_parser_set_timeout_micros = Module.asm.orig$ts_parser_set_timeout_micros).apply(null, arguments); }; function Ve(e3) { this.name = "ExitStatus", this.message = "Program terminated with exit(" + e3 + ")", this.status = e3; } Module.allocate = function(e3, t2) { var r3; return r3 = t2 == F ? Be(e3.length) : ze(e3.length), e3.subarray || e3.slice ? T.set(e3, r3) : T.set(new Uint8Array(e3), r3), r3; }; re = function e3() { Ze || Qe(), Ze || (re = e3); }; var Xe = false; function Qe(e3) { function t2() { Ze || (Ze = true, Module.calledRun = true, P || (Y = true, pe(X), pe(Q), Module.onRuntimeInitialized && Module.onRuntimeInitialized(), Ye && function(e4) { var t3 = Module._main; if (t3) { var r3 = (e4 = e4 || []).length + 1, n2 = Be(4 * (r3 + 1)); W[n2 >> 2] = H(a); for (var o2 = 1; o2 < r3; o2++) W[(n2 >> 2) + o2] = H(e4[o2 - 1]); W[(n2 >> 2) + r3] = 0; try { Je(t3(r3, n2), true); } catch (e5) { if (e5 instanceof Ve) return; if ("unwind" == e5) return; var s2 = e5; e5 && "object" == typeof e5 && e5.stack && (s2 = [e5, e5.stack]), g2("exception thrown: " + s2), i(1, e5); } finally { } } }(e3), function() { if (Module.postRun) for ("function" == typeof Module.postRun && (Module.postRun = [Module.postRun]); Module.postRun.length; ) e4 = Module.postRun.shift(), J.unshift(e4); var e4; pe(J); }())); } e3 = e3 || _, ee > 0 || !Xe && (function() { if (S.length) { if (!m) return ne(), void S.reduce(function(e4, t3) { return e4.then(function() { return Ne(t3, { loadAsync: true, global: true, nodelete: true, allowUndefined: true }); }); }, Promise.resolve()).then(function() { oe(), Pe(); }); S.forEach(function(e4) { Ne(e4, { global: true, nodelete: true, allowUndefined: true }); }), Pe(); } else Pe(); }(), Xe = true, ee > 0) || (!function() { if (Module.preRun) for ("function" == typeof Module.preRun && (Module.preRun = [Module.preRun]); Module.preRun.length; ) e4 = Module.preRun.shift(), V.unshift(e4); var e4; pe(V); }(), ee > 0 || (Module.setStatus ? (Module.setStatus("Running..."), setTimeout(function() { setTimeout(function() { Module.setStatus(""); }, 1), t2(); }, 1)) : t2())); } function Je(e3, t2) { t2 && we() && 0 === e3 || (we() || (Module.onExit && Module.onExit(e3), P = true), i(e3, new Ve(e3))); } if (Module.run = Qe, Module.preInit) for ("function" == typeof Module.preInit && (Module.preInit = [Module.preInit]); Module.preInit.length > 0; ) Module.preInit.pop()(); var Ye = true; Module.noInitialRun && (Ye = false), Qe(); const et = Module, tt = {}, rt = 4, nt = 5 * rt, ot = 2 * rt, st = 2 * rt + 2 * ot, _t = { row: 0, column: 0 }, at = /[\w-.]*/g, it = 1, ut = 2, lt = /^_?tree_sitter_\w+/; var dt, ct, mt, ft, pt; class ParserImpl { static init() { mt = et._ts_init(), dt = N(mt, "i32"), ct = N(mt + rt, "i32"); } initialize() { et._ts_parser_new_wasm(), this[0] = N(mt, "i32"), this[1] = N(mt + rt, "i32"); } delete() { et._ts_parser_delete(this[0]), et._free(this[1]), this[0] = 0, this[1] = 0; } setLanguage(e3) { let t2; if (e3) { if (e3.constructor !== Language) throw new Error("Argument must be a Language"); { t2 = e3[0]; const r3 = et._ts_language_version(t2); if (r3 < ct || dt < r3) throw new Error(`Incompatible language version ${r3}. Compatibility range ${ct} through ${dt}.`); } } else t2 = 0, e3 = null; return this.language = e3, et._ts_parser_set_language(this[0], t2), this; } getLanguage() { return this.language; } parse(e3, t2, r3) { if ("string" == typeof e3) ft = (t3, r4, n3) => e3.slice(t3, n3); else { if ("function" != typeof e3) throw new Error("Argument must be a string or a function"); ft = e3; } this.logCallback ? (pt = this.logCallback, et._ts_parser_enable_logger_wasm(this[0], 1)) : (pt = null, et._ts_parser_enable_logger_wasm(this[0], 0)); let n2 = 0, o2 = 0; if (r3 && r3.includedRanges) { n2 = r3.includedRanges.length; let e4 = o2 = et._calloc(n2, st); for (let t3 = 0; t3 < n2; t3++) At(e4, r3.includedRanges[t3]), e4 += st; } const s2 = et._ts_parser_parse_wasm(this[0], this[1], t2 ? t2[0] : 0, o2, n2); if (!s2) throw ft = null, pt = null, new Error("Parsing failed"); const _2 = new Tree(tt, s2, this.language, ft); return ft = null, pt = null, _2; } reset() { et._ts_parser_reset(this[0]); } setTimeoutMicros(e3) { et._ts_parser_set_timeout_micros(this[0], e3); } getTimeoutMicros() { return et._ts_parser_timeout_micros(this[0]); } setLogger(e3) { if (e3) { if ("function" != typeof e3) throw new Error("Logger callback must be a function"); } else e3 = null; return this.logCallback = e3, this; } getLogger() { return this.logCallback; } } class Tree { constructor(e3, t2, r3, n2) { wt(e3), this[0] = t2, this.language = r3, this.textCallback = n2; } copy() { const e3 = et._ts_tree_copy(this[0]); return new Tree(tt, e3, this.language, this.textCallback); } delete() { et._ts_tree_delete(this[0]), this[0] = 0; } edit(e3) { !function(e4) { let t2 = mt; St(t2, e4.startPosition), St(t2 += ot, e4.oldEndPosition), St(t2 += ot, e4.newEndPosition), x(t2 += ot, e4.startIndex, "i32"), x(t2 += rt, e4.oldEndIndex, "i32"), x(t2 += rt, e4.newEndIndex, "i32"), t2 += rt; }(e3), et._ts_tree_edit_wasm(this[0]); } get rootNode() { return et._ts_tree_root_node_wasm(this[0]), bt(this); } getLanguage() { return this.language; } walk() { return this.rootNode.walk(); } getChangedRanges(e3) { if (e3.constructor !== Tree) throw new TypeError("Argument must be a Tree"); et._ts_tree_get_changed_ranges_wasm(this[0], e3[0]); const t2 = N(mt, "i32"), r3 = N(mt + rt, "i32"), n2 = new Array(t2); if (t2 > 0) { let e4 = r3; for (let r4 = 0; r4 < t2; r4++) n2[r4] = xt(e4), e4 += st; et._free(r3); } return n2; } } class Node { constructor(e3, t2) { wt(e3), this.tree = t2; } get typeId() { return yt(this), et._ts_node_symbol_wasm(this.tree[0]); } get type() { return this.tree.language.types[this.typeId] || "ERROR"; } get endPosition() { return yt(this), et._ts_node_end_point_wasm(this.tree[0]), It(mt); } get endIndex() { return yt(this), et._ts_node_end_index_wasm(this.tree[0]); } get text() { return ht(this.tree, this.startIndex, this.endIndex); } isNamed() { return yt(this), 1 === et._ts_node_is_named_wasm(this.tree[0]); } hasError() { return yt(this), 1 === et._ts_node_has_error_wasm(this.tree[0]); } hasChanges() { return yt(this), 1 === et._ts_node_has_changes_wasm(this.tree[0]); } isMissing() { return yt(this), 1 === et._ts_node_is_missing_wasm(this.tree[0]); } equals(e3) { return this.id === e3.id; } child(e3) { return yt(this), et._ts_node_child_wasm(this.tree[0], e3), bt(this.tree); } namedChild(e3) { return yt(this), et._ts_node_named_child_wasm(this.tree[0], e3), bt(this.tree); } childForFieldId(e3) { return yt(this), et._ts_node_child_by_field_id_wasm(this.tree[0], e3), bt(this.tree); } childForFieldName(e3) { const t2 = this.tree.language.fields.indexOf(e3); if (-1 !== t2) return this.childForFieldId(t2); } get childCount() { return yt(this), et._ts_node_child_count_wasm(this.tree[0]); } get namedChildCount() { return yt(this), et._ts_node_named_child_count_wasm(this.tree[0]); } get firstChild() { return this.child(0); } get firstNamedChild() { return this.namedChild(0); } get lastChild() { return this.child(this.childCount - 1); } get lastNamedChild() { return this.namedChild(this.namedChildCount - 1); } get children() { if (!this._children) { yt(this), et._ts_node_children_wasm(this.tree[0]); const e3 = N(mt, "i32"), t2 = N(mt + rt, "i32"); if (this._children = new Array(e3), e3 > 0) { let r3 = t2; for (let t3 = 0; t3 < e3; t3++) this._children[t3] = bt(this.tree, r3), r3 += nt; et._free(t2); } } return this._children; } get namedChildren() { if (!this._namedChildren) { yt(this), et._ts_node_named_children_wasm(this.tree[0]); const e3 = N(mt, "i32"), t2 = N(mt + rt, "i32"); if (this._namedChildren = new Array(e3), e3 > 0) { let r3 = t2; for (let t3 = 0; t3 < e3; t3++) this._namedChildren[t3] = bt(this.tree, r3), r3 += nt; et._free(t2); } } return this._namedChildren; } descendantsOfType(e3, t2, r3) { Array.isArray(e3) || (e3 = [e3]), t2 || (t2 = _t), r3 || (r3 = _t); const n2 = [], o2 = this.tree.language.types; for (let t3 = 0, r4 = o2.length; t3 < r4; t3++) e3.includes(o2[t3]) && n2.push(t3); const s2 = et._malloc(rt * n2.length); for (let e4 = 0, t3 = n2.length; e4 < t3; e4++) x(s2 + e4 * rt, n2[e4], "i32"); yt(this), et._ts_node_descendants_of_type_wasm(this.tree[0], s2, n2.length, t2.row, t2.column, r3.row, r3.column); const _2 = N(mt, "i32"), a2 = N(mt + rt, "i32"), i2 = new Array(_2); if (_2 > 0) { let e4 = a2; for (let t3 = 0; t3 < _2; t3++) i2[t3] = bt(this.tree, e4), e4 += nt; } return et._free(a2), et._free(s2), i2; } get nextSibling() { return yt(this), et._ts_node_next_sibling_wasm(this.tree[0]), bt(this.tree); } get previousSibling() { return yt(this), et._ts_node_prev_sibling_wasm(this.tree[0]), bt(this.tree); } get nextNamedSibling() { return yt(this), et._ts_node_next_named_sibling_wasm(this.tree[0]), bt(this.tree); } get previousNamedSibling() { return yt(this), et._ts_node_prev_named_sibling_wasm(this.tree[0]), bt(this.tree); } get parent() { return yt(this), et._ts_node_parent_wasm(this.tree[0]), bt(this.tree); } descendantForIndex(e3, t2 = e3) { if ("number" != typeof e3 || "number" != typeof t2) throw new Error("Arguments must be numbers"); yt(this); let r3 = mt + nt; return x(r3, e3, "i32"), x(r3 + rt, t2, "i32"), et._ts_node_descendant_for_index_wasm(this.tree[0]), bt(this.tree); } namedDescendantForIndex(e3, t2 = e3) { if ("number" != typeof e3 || "number" != typeof t2) throw new Error("Arguments must be numbers"); yt(this); let r3 = mt + nt; return x(r3, e3, "i32"), x(r3 + rt, t2, "i32"), et._ts_node_named_descendant_for_index_wasm(this.tree[0]), bt(this.tree); } descendantForPosition(e3, t2 = e3) { if (!Mt(e3) || !Mt(t2)) throw new Error("Arguments must be {row, column} objects"); yt(this); let r3 = mt + nt; return St(r3, e3), St(r3 + ot, t2), et._ts_node_descendant_for_position_wasm(this.tree[0]), bt(this.tree); } namedDescendantForPosition(e3, t2 = e3) { if (!Mt(e3) || !Mt(t2)) throw new Error("Arguments must be {row, column} objects"); yt(this); let r3 = mt + nt; return St(r3, e3), St(r3 + ot, t2), et._ts_node_named_descendant_for_position_wasm(this.tree[0]), bt(this.tree); } walk() { return yt(this), et._ts_tree_cursor_new_wasm(this.tree[0]), new TreeCursor(tt, this.tree); } toString() { yt(this); const e3 = et._ts_node_to_string_wasm(this.tree[0]), t2 = function(e4) { for (var t3 = ""; ; ) { var r3 = T[e4++ >> 0]; if (!r3) return t3; t3 += String.fromCharCode(r3); } }(e3); return et._free(e3), t2; } } class TreeCursor { constructor(e3, t2) { wt(e3), this.tree = t2, Et(this); } delete() { vt(this), et._ts_tree_cursor_delete_wasm(this.tree[0]), this[0] = this[1] = this[2] = 0; } reset(e3) { yt(e3), vt(this, mt + nt), et._ts_tree_cursor_reset_wasm(this.tree[0]), Et(this); } get nodeType() { return this.tree.language.types[this.nodeTypeId] || "ERROR"; } get nodeTypeId() { return vt(this), et._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]); } get nodeId() { return vt(this), et._ts_tree_cursor_current_node_id_wasm(this.tree[0]); } get nodeIsNamed() { return vt(this), 1 === et._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]); } get nodeIsMissing() { return vt(this), 1 === et._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]); } get nodeText() { vt(this); const e3 = et._ts_tree_cursor_start_index_wasm(this.tree[0]), t2 = et._ts_tree_cursor_end_index_wasm(this.tree[0]); return ht(this.tree, e3, t2); } get startPosition() { return vt(this), et._ts_tree_cursor_start_position_wasm(this.tree[0]), It(mt); } get endPosition() { return vt(this), et._ts_tree_cursor_end_position_wasm(this.tree[0]), It(mt); } get startIndex() { return vt(this), et._ts_tree_cursor_start_index_wasm(this.tree[0]); } get endIndex() { return vt(this), et._ts_tree_cursor_end_index_wasm(this.tree[0]); } currentNode() { return vt(this), et._ts_tree_cursor_current_node_wasm(this.tree[0]), bt(this.tree); } currentFieldId() { return vt(this), et._ts_tree_cursor_current_field_id_wasm(this.tree[0]); } currentFieldName() { return this.tree.language.fields[this.currentFieldId()]; } gotoFirstChild() { vt(this); const e3 = et._ts_tree_cursor_goto_first_child_wasm(this.tree[0]); return Et(this), 1 === e3; } gotoNextSibling() { vt(this); const e3 = et._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]); return Et(this), 1 === e3; } gotoParent() { vt(this); const e3 = et._ts_tree_cursor_goto_parent_wasm(this.tree[0]); return Et(this), 1 === e3; } } class Language { constructor(e3, t2) { wt(e3), this[0] = t2, this.types = new Array(et._ts_language_symbol_count(this[0])); for (let e4 = 0, t3 = this.types.length; e4 < t3; e4++) et._ts_language_symbol_type(this[0], e4) < 2 && (this.types[e4] = Z(et._ts_language_symbol_name(this[0], e4))); this.fields = new Array(et._ts_language_field_count(this[0]) + 1); for (let e4 = 0, t3 = this.fields.length; e4 < t3; e4++) { const t4 = et._ts_language_field_name_for_id(this[0], e4); this.fields[e4] = 0 !== t4 ? Z(t4) : null; } } get version() { return et._ts_language_version(this[0]); } get fieldCount() { return this.fields.length - 1; } fieldIdForName(e3) { const t2 = this.fields.indexOf(e3); return -1 !== t2 ? t2 : null; } fieldNameForId(e3) { return this.fields[e3] || null; } idForNodeType(e3, t2) { const r3 = U(e3), n2 = et._malloc(r3 + 1); z(e3, n2, r3 + 1); const o2 = et._ts_language_symbol_for_name(this[0], n2, r3, t2); return et._free(n2), o2 || null; } get nodeTypeCount() { return et._ts_language_symbol_count(this[0]); } nodeTypeForId(e3) { const t2 = et._ts_language_symbol_name(this[0], e3); return t2 ? Z(t2) : null; } nodeTypeIsNamed(e3) { return !!et._ts_language_type_is_named_wasm(this[0], e3); } nodeTypeIsVisible(e3) { return !!et._ts_language_type_is_visible_wasm(this[0], e3); } query(e3) { const t2 = U(e3), r3 = et._malloc(t2 + 1); z(e3, r3, t2 + 1); const n2 = et._ts_query_new(this[0], r3, t2, mt, mt + rt); if (!n2) { const t3 = N(mt + rt, "i32"), n3 = Z(r3, N(mt, "i32")).length, o3 = e3.substr(n3, 100).split("\n")[0]; let s3, _3 = o3.match(at)[0]; switch (t3) { case 2: s3 = new RangeError(`Bad node name '${_3}'`); break; case 3: s3 = new RangeError(`Bad field name '${_3}'`); break; case 4: s3 = new RangeError(`Bad capture name @${_3}`); break; case 5: s3 = new TypeError(`Bad pattern structure at offset ${n3}: '${o3}'...`), _3 = ""; break; default: s3 = new SyntaxError(`Bad syntax at offset ${n3}: '${o3}'...`), _3 = ""; } throw s3.index = n3, s3.length = _3.length, et._free(r3), s3; } const o2 = et._ts_query_string_count(n2), s2 = et._ts_query_capture_count(n2), _2 = et._ts_query_pattern_count(n2), a2 = new Array(s2), i2 = new Array(o2); for (let e4 = 0; e4 < s2; e4++) { const t3 = et._ts_query_capture_name_for_id(n2, e4, mt), r4 = N(mt, "i32"); a2[e4] = Z(t3, r4); } for (let e4 = 0; e4 < o2; e4++) { const t3 = et._ts_query_string_value_for_id(n2, e4, mt), r4 = N(mt, "i32"); i2[e4] = Z(t3, r4); } const u2 = new Array(_2), l2 = new Array(_2), d2 = new Array(_2), c3 = new Array(_2), m2 = new Array(_2); for (let e4 = 0; e4 < _2; e4++) { const t3 = et._ts_query_predicates_for_pattern(n2, e4, mt), r4 = N(mt, "i32"); c3[e4] = [], m2[e4] = []; const o3 = []; let s3 = t3; for (let t4 = 0; t4 < r4; t4++) { const t5 = N(s3, "i32"), r5 = N(s3 += rt, "i32"); if (s3 += rt, t5 === it) o3.push({ type: "capture", name: a2[r5] }); else if (t5 === ut) o3.push({ type: "string", value: i2[r5] }); else if (o3.length > 0) { if ("string" !== o3[0].type) throw new Error("Predicates must begin with a literal value"); const t6 = o3[0].value; let r6 = true; switch (t6) { case "not-eq?": r6 = false; case "eq?": if (3 !== o3.length) throw new Error(`Wrong number of arguments to \`#eq?\` predicate. Expected 2, got ${o3.length - 1}`); if ("capture" !== o3[1].type) throw new Error(`First argument of \`#eq?\` predicate must be a capture. Got "${o3[1].value}"`); if ("capture" === o3[2].type) { const t7 = o3[1].name, n4 = o3[2].name; m2[e4].push(function(e5) { let o4, s5; for (const r7 of e5) r7.name === t7 && (o4 = r7.node), r7.name === n4 && (s5 = r7.node); return void 0 === o4 || void 0 === s5 || o4.text === s5.text === r6; }); } else { const t7 = o3[1].name, n4 = o3[2].value; m2[e4].push(function(e5) { for (const o4 of e5) if (o4.name === t7) return o4.node.text === n4 === r6; return true; }); } break; case "not-match?": r6 = false; case "match?": if (3 !== o3.length) throw new Error(`Wrong number of arguments to \`#match?\` predicate. Expected 2, got ${o3.length - 1}.`); if ("capture" !== o3[1].type) throw new Error(`First argument of \`#match?\` predicate must be a capture. Got "${o3[1].value}".`); if ("string" !== o3[2].type) throw new Error(`Second argument of \`#match?\` predicate must be a string. Got @${o3[2].value}.`); const n3 = o3[1].name, s4 = new RegExp(o3[2].value); m2[e4].push(function(e5) { for (const t7 of e5) if (t7.name === n3) return s4.test(t7.node.text) === r6; return true; }); break; case "set!": if (o3.length < 2 || o3.length > 3) throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${o3.length - 1}.`); if (o3.some((e5) => "string" !== e5.type)) throw new Error('Arguments to `#set!` predicate must be a strings.".'); u2[e4] || (u2[e4] = {}), u2[e4][o3[1].value] = o3[2] ? o3[2].value : null; break; case "is?": case "is-not?": if (o3.length < 2 || o3.length > 3) throw new Error(`Wrong number of arguments to \`#${t6}\` predicate. Expected 1 or 2. Got ${o3.length - 1}.`); if (o3.some((e5) => "string" !== e5.type)) throw new Error(`Arguments to \`#${t6}\` predicate must be a strings.".`); const _3 = "is?" === t6 ? l2 : d2; _3[e4] || (_3[e4] = {}), _3[e4][o3[1].value] = o3[2] ? o3[2].value : null; break; default: c3[e4].push({ operator: t6, operands: o3.slice(1) }); } o3.length = 0; } } Object.freeze(u2[e4]), Object.freeze(l2[e4]), Object.freeze(d2[e4]); } return et._free(r3), new Query(tt, n2, a2, m2, c3, Object.freeze(u2), Object.freeze(l2), Object.freeze(d2)); } static load(e3) { let t2; if (e3 instanceof Uint8Array) t2 = Promise.resolve(e3); else { const r4 = e3; if ("undefined" != typeof process && process.versions && process.versions.node) { const e4 = require$$1; t2 = Promise.resolve(e4.readFileSync(r4)); } else t2 = fetch(r4).then((e4) => e4.arrayBuffer().then((t3) => { if (e4.ok) return new Uint8Array(t3); { const r5 = new TextDecoder("utf-8").decode(t3); throw new Error(`Language.load failed with status ${e4.status}. ${r5}`); } })); } const r3 = "function" == typeof loadSideModule ? loadSideModule : xe; return t2.then((e4) => r3(e4, { loadAsync: true })).then((e4) => { const t3 = Object.keys(e4), r4 = t3.find((e5) => lt.test(e5) && !e5.includes("external_scanner_")); r4 || console.log(`Couldn't find language function in WASM file. Symbols: ${JSON.stringify(t3, null, 2)}`); const n2 = e4[r4](); return new Language(tt, n2); }); } } class Query { constructor(e3, t2, r3, n2, o2, s2, _2, a2) { wt(e3), this[0] = t2, this.captureNames = r3, this.textPredicates = n2, this.predicates = o2, this.setProperties = s2, this.assertedProperties = _2, this.refutedProperties = a2, this.exceededMatchLimit = false; } delete() { et._ts_query_delete(this[0]), this[0] = 0; } matches(e3, t2, r3, n2) { t2 || (t2 = _t), r3 || (r3 = _t), n2 || (n2 = {}); let o2 = n2.matchLimit; if (void 0 === o2) o2 = 0; else if ("number" != typeof o2) throw new Error("Arguments must be numbers"); yt(e3), et._ts_query_matches_wasm(this[0], e3.tree[0], t2.row, t2.column, r3.row, r3.column, o2); const s2 = N(mt, "i32"), _2 = N(mt + rt, "i32"), a2 = N(mt + 2 * rt, "i32"), i2 = new Array(s2); this.exceededMatchLimit = !!a2; let u2 = 0, l2 = _2; for (let t3 = 0; t3 < s2; t3++) { const r4 = N(l2, "i32"), n3 = N(l2 += rt, "i32"); l2 += rt; const o3 = new Array(n3); if (l2 = gt(this, e3.tree, l2, o3), this.textPredicates[r4].every((e4) => e4(o3))) { i2[u2++] = { pattern: r4, captures: o3 }; const e4 = this.setProperties[r4]; e4 && (i2[t3].setProperties = e4); const n4 = this.assertedProperties[r4]; n4 && (i2[t3].assertedProperties = n4); const s3 = this.refutedProperties[r4]; s3 && (i2[t3].refutedProperties = s3); } } return i2.length = u2, et._free(_2), i2; } captures(e3, t2, r3, n2) { t2 || (t2 = _t), r3 || (r3 = _t), n2 || (n2 = {}); let o2 = n2.matchLimit; if (void 0 === o2) o2 = 0; else if ("number" != typeof o2) throw new Error("Arguments must be numbers"); yt(e3), et._ts_query_captures_wasm(this[0], e3.tree[0], t2.row, t2.column, r3.row, r3.column, o2); const s2 = N(mt, "i32"), _2 = N(mt + rt, "i32"), a2 = N(mt + 2 * rt, "i32"), i2 = []; this.exceededMatchLimit = !!a2; const u2 = []; let l2 = _2; for (let t3 = 0; t3 < s2; t3++) { const t4 = N(l2, "i32"), r4 = N(l2 += rt, "i32"), n3 = N(l2 += rt, "i32"); if (l2 += rt, u2.length = r4, l2 = gt(this, e3.tree, l2, u2), this.textPredicates[t4].every((e4) => e4(u2))) { const e4 = u2[n3], r5 = this.setProperties[t4]; r5 && (e4.setProperties = r5); const o3 = this.assertedProperties[t4]; o3 && (e4.assertedProperties = o3); const s3 = this.refutedProperties[t4]; s3 && (e4.refutedProperties = s3), i2.push(e4); } } return et._free(_2), i2; } predicatesForPattern(e3) { return this.predicates[e3]; } didExceedMatchLimit() { return this.exceededMatchLimit; } } function ht(e3, t2, r3) { const n2 = r3 - t2; let o2 = e3.textCallback(t2, null, r3); for (t2 += o2.length; t2 < r3; ) { const n3 = e3.textCallback(t2, null, r3); if (!(n3 && n3.length > 0)) break; t2 += n3.length, o2 += n3; } return t2 > r3 && (o2 = o2.slice(0, n2)), o2; } function gt(e3, t2, r3, n2) { for (let o2 = 0, s2 = n2.length; o2 < s2; o2++) { const s3 = N(r3, "i32"), _2 = bt(t2, r3 += rt); r3 += nt, n2[o2] = { name: e3.captureNames[s3], node: _2 }; } return r3; } function wt(e3) { if (e3 !== tt) throw new Error("Illegal constructor"); } function Mt(e3) { return e3 && "number" == typeof e3.row && "number" == typeof e3.column; } function yt(e3) { let t2 = mt; x(t2, e3.id, "i32"), x(t2 += rt, e3.startIndex, "i32"), x(t2 += rt, e3.startPosition.row, "i32"), x(t2 += rt, e3.startPosition.column, "i32"), x(t2 += rt, e3[0], "i32"); } function bt(e3, t2 = mt) { const r3 = N(t2, "i32"); if (0 === r3) return null; const n2 = N(t2 += rt, "i32"), o2 = N(t2 += rt, "i32"), s2 = N(t2 += rt, "i32"), _2 = N(t2 += rt, "i32"), a2 = new Node(tt, e3); return a2.id = r3, a2.startIndex = n2, a2.startPosition = { row: o2, column: s2 }, a2[0] = _2, a2; } function vt(e3, t2 = mt) { x(t2 + 0 * rt, e3[0], "i32"), x(t2 + 1 * rt, e3[1], "i32"), x(t2 + 2 * rt, e3[2], "i32"); } function Et(e3) { e3[0] = N(mt + 0 * rt, "i32"), e3[1] = N(mt + 1 * rt, "i32"), e3[2] = N(mt + 2 * rt, "i32"); } function St(e3, t2) { x(e3, t2.row, "i32"), x(e3 + rt, t2.column, "i32"); } function It(e3) { return { row: N(e3, "i32"), column: N(e3 + rt, "i32") }; } function At(e3, t2) { St(e3, t2.startPosition), St(e3 += ot, t2.endPosition), x(e3 += ot, t2.startIndex, "i32"), x(e3 += rt, t2.endIndex, "i32"), e3 += rt; } function xt(e3) { const t2 = {}; return t2.startPosition = It(e3), e3 += ot, t2.endPosition = It(e3), e3 += ot, t2.startIndex = N(e3, "i32"), e3 += rt, t2.endIndex = N(e3, "i32"), t2; } for (const e3 of Object.getOwnPropertyNames(ParserImpl.prototype)) Object.defineProperty(Parser2.prototype, e3, { value: ParserImpl.prototype[e3], enumerable: false, writable: false }); Parser2.Language = Language, Module.onRuntimeInitialized = () => { ParserImpl.init(), e2(); }; })); } } return Parser2; }(); module2.exports = TreeSitter; })(treeSitter); var treeSitterExports = treeSitter.exports; const Parser = /* @__PURE__ */ getDefaultExportFromCjs(treeSitterExports); const treeSitterShadeupURL = ""; async function getShadeupParser() { if (typeof process === "object" && process.versions && process.versions.node) { return global.shadeupParser(); } let url = treeSitterShadeupURL; let shadeUrl = treeSitterShadeupURL; await Parser.init({ locateFile(scriptName, scriptDirectory) { return url; } }); const parser = new Parser(); parser.setLanguage(await Parser.Language.load(shadeUrl)); return parser; } class AstContext { constructor(fileName) { this.impls = /* @__PURE__ */ new Map(); this.implsFor = /* @__PURE__ */ new Map(); this.shaders = []; this.diagnostics = []; this.globals = []; this.fileName = fileName; } report(node2, message) { this.diagnostics.push({ message, node: node2 }); } addImpl(name, node2) { if (this.impls.has(name)) { this.impls.get(name).push(node2); } else { this.impls.set(name, [node2]); } } addImplFor(name, node2) { if (this.implsFor.has(name)) { this.implsFor.get(name).push(node2); } else { this.implsFor.set(name, [node2]); } } } const stdMath = "export type bool = boolean;\r\nexport type float = number & { _opaque_float: 2 };\r\nexport type int = number & { _opaque_int: 1 } & float;\r\nexport type uint = number & { _opaque_uint: 1 };\r\ntype scalar = float | int | uint;\r\n\r\nexport type float2 = [float, float] & { _opaque_vector_float_2: 2; length: 2 };\r\nexport type float3 = [float, float, float] & { _opaque_vector_float_3: 3; length: 3 };\r\nexport type float4 = [float, float, float, float] & { _opaque_vector_float_4: 4; length: 4 };\r\nexport type int2 = [int, int] & { _opaque_vector_int_2: 2 } & float2;\r\nexport type int3 = [int, int, int] & { _opaque_vector_int_3: 3 } & float3;\r\nexport type int4 = [int, int, int, int] & { _opaque_vector_int_4: 4 } & float4;\r\n\r\nexport type uint2 = [uint, uint] & { _opaque_vector_uint_2: 2 } & float2;\r\nexport type uint3 = [uint, uint, uint] & { _opaque_vector_uint_3: 3 } & float3;\r\nexport type uint4 = [uint, uint, uint, uint] & { _opaque_vector_uint_4: 4 } & float4;\r\n\r\nexport type uint8 = number & { _opaque_uint8: 1 };\r\n\r\ntype anyFloat = float2 | float3 | float4;\r\ntype anyInt = int2 | int3 | int4;\r\ntype anyUint = uint2 | uint3 | uint4;\r\n\r\ntype vector2 = float2 | int2 | uint2;\r\ntype vector3 = float3 | int3 | uint3;\r\ntype vector4 = float4 | int4 | uint4;\r\n\r\ntype vector = vector2 | vector3 | vector4;\r\n\r\ntype vectorOrScalar = vector | scalar;\r\n\r\nexport interface float2x2 extends Omit<[float, float, float, float], '__index'> {\r\n __matrix: 2;\r\n [index: int]: float;\r\n __index(index: number): [float, float];\r\n}\r\n\r\nexport interface float3x3\r\n extends Omit<[float, float, float, float, float, float, float, float, float], '__index'> {\r\n __matrix: 3;\r\n [index: int]: float;\r\n __index(index: number): [float, float, float];\r\n}\r\n\r\nexport interface float4x4\r\n extends Omit<\r\n [\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float\r\n ],\r\n '__index'\r\n > {\r\n __matrix: 4;\r\n [index: int]: float;\r\n __index(index: number): [float, float, float, float];\r\n}\r\n\r\nfunction isVector(v: vectorOrScalar): v is vector {\r\n return Array.isArray(v);\r\n}\r\n\r\nfunction isScalar(v: vectorOrScalar): v is scalar {\r\n return typeof v === 'number';\r\n}\r\n\r\nfunction isMatrix(v: number[]): v is float2x2 | float3x3 | float4x4 {\r\n return !!(v as any).__matrix;\r\n}\r\n\r\n/** @shadeup=glsl(!mat2(0)) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(): float2x2;\r\n/** @shadeup=glsl(mat2) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(m00: number, m01: number, m10: number, m11: number): float2x2;\r\n/** @shadeup=glsl(mat2) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(...args: float[]): float2x2 {\r\n let arr = [0, 0, 0, 0] as any as float2x2;\r\n if (args.length === 4) {\r\n arr = [...args] as any as float2x2;\r\n }\r\n\r\n applyMatrix2x2Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\n/** @shadeup=glsl(!mat3(0)) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(): float3x3;\r\n/** @shadeup=glsl(mat3) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(\r\n m00: number,\r\n m01: number,\r\n m02: number,\r\n m10: number,\r\n m11: number,\r\n m12: number,\r\n m20: number,\r\n m21: number,\r\n m22: number\r\n): float3x3;\r\n/** @shadeup=glsl(mat3) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(...args: float[]): float3x3 {\r\n let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0] as any as float3x3;\r\n if (args.length === 9) {\r\n arr = [...args] as any as float3x3;\r\n }\r\n\r\n applyMatrix3x3Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\nfunction applyMatrix4x4Methods(arr: float4x4): void {\r\n (arr as any).__matrix = 4;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 4], arr[index * 4 + 1], arr[index * 4 + 2], arr[index * 4 + 3]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 4 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 4 + index_inner] = op_fn(arr[index * 4 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float4) {\r\n arr[index * 4] = value[0];\r\n arr[index * 4 + 1] = value[1];\r\n arr[index * 4 + 2] = value[2];\r\n arr[index * 4 + 3] = value[3];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 4] = op_fn(arr[index * 4], value[0]);\r\n arr[index * 4 + 1] = op_fn(arr[index * 4 + 1], value[1]);\r\n arr[index * 4 + 2] = op_fn(arr[index * 4 + 2], value[2]);\r\n arr[index * 4 + 3] = op_fn(arr[index * 4 + 3], value[3]);\r\n };\r\n}\r\n(window as any).applyMatrix4x4Methods = applyMatrix4x4Methods;\r\n\r\nfunction applyMatrix3x3Methods(arr: float3x3): void {\r\n (arr as any).__matrix = 3;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 3], arr[index * 3 + 1], arr[index * 3 + 2]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 3 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 3 + index_inner] = op_fn(arr[index * 3 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float3) {\r\n arr[index * 3] = value[0];\r\n arr[index * 3 + 1] = value[1];\r\n arr[index * 3 + 2] = value[2];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 3] = op_fn(arr[index * 3], value[0]);\r\n arr[index * 3 + 1] = op_fn(arr[index * 3 + 1], value[1]);\r\n arr[index * 3 + 2] = op_fn(arr[index * 3 + 2], value[2]);\r\n };\r\n}\r\n\r\n(window as any).applyMatrix3x3Methods = applyMatrix3x3Methods;\r\n\r\nfunction applyMatrix2x2Methods(arr: float2x2): void {\r\n (arr as any).__matrix = 2;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 2], arr[index * 2 + 1]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 2 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 2 + index_inner] = op_fn(arr[index * 2 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float3) {\r\n arr[index * 2] = value[0];\r\n arr[index * 2 + 1] = value[1];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 2] = op_fn(arr[index * 2], value[0]);\r\n arr[index * 2 + 1] = op_fn(arr[index * 2 + 1], value[1]);\r\n };\r\n}\r\n\r\n(window as any).applyMatrix2x2Methods = applyMatrix2x2Methods;\r\n\r\n/** @shadeup=glsl(!mat4(0)) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(): float4x4;\r\n/** @shadeup=glsl(mat4) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(\r\n m00: number,\r\n m01: number,\r\n m02: number,\r\n m03: number,\r\n m10: number,\r\n m11: number,\r\n m12: number,\r\n m13: number,\r\n m20: number,\r\n m21: number,\r\n m22: number,\r\n m23: number,\r\n m30: number,\r\n m31: number,\r\n m32: number,\r\n m33: number\r\n): float4x4;\r\n/** @shadeup=glsl(mat4) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(...args: float[]): float4x4 {\r\n let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] as any as float4x4;\r\n if (args.length === 16) {\r\n arr = [...args] as any as float4x4;\r\n }\r\n\r\n applyMatrix4x4Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\n/** @shadeup=glsl(float) @shadeup=wgsl(f32) */\r\nexport function float(x: number): float {\r\n return x as float;\r\n}\r\n\r\n/** @shadeup=glsl(int) @shadeup=wgsl(i32) */\r\nexport function int(x: number): int {\r\n return (x | 0) as int;\r\n}\r\n\r\n/** @shadeup=glsl(uint) @shadeup=wgsl(u32) */\r\nexport function uint(x: number): uint {\r\n return (x >>> 0) as uint;\r\n}\r\n\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(x: number, y: number): float2;\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(xy: vector2): float2;\r\n\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(...args: (vectorOrScalar | number)[]): float2 {\r\n return args.flat() as float2;\r\n}\r\n\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(x: number, y: number, z: number): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(xy: vector2, z: number): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(x: number, yz: vector2): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(xyz: vector3): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(...args: (vectorOrScalar | number)[]): float3 {\r\n return args.flat() as float3;\r\n}\r\n\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, y: number, z: number, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, yz: vector2, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xy: vector2, z: number, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, y: number, zw: vector2): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xy: vector2, zw: vector2): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xyz: vector3, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, yzw: vector3): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xyzw: int4): float4;\r\nexport function float4(xyzw: float4): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(...args: (vectorOrScalar | number)[]): float4 {\r\n return args.flat() as float4;\r\n}\r\n\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(x: number, y: number): int2;\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(xy: vector2): int2;\r\n\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(...args: (vectorOrScalar | number)[]): int2 {\r\n return args.flat().map((x) => x | 0) as int2;\r\n}\r\n\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(x: number, y: number, z: number): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(xy: vector2, z: number): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(x: number, yz: vector2): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(xyz: vector3): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(...args: (vectorOrScalar | number)[]): int3 {\r\n return args.flat().map((x) => x | 0) as int3;\r\n}\r\n\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, y: number, z: number, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, yz: vector2, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xy: vector2, z: number, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, y: number, zw: vector2): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xy: vector2, zw: vector2): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xyz: vector3, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, yzw: vector3): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xyzw: float4): int4;\r\nexport function int4(xyzw: int4): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(...args: (vectorOrScalar | number)[]): int4 {\r\n return args.flat().map((x) => x | 0) as int4;\r\n}\r\n\r\n/** @shadeup=glsl(uint2) @shadeup=wgsl(vec2) */\r\nexport function uint2(x: number, y: number): uint2;\r\n/** @shadeup=glsl(uint2) @shadeup=wgsl(vec2) */\r\nexport function uint2(xy: vector2): uint2;\r\nexport function uint2(...args: (vectorOrScalar | number)[]): uint2 {\r\n return args.flat().map((x) => x >>> 0) as uint2;\r\n}\r\n\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(x: number, y: number, z: number): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(xy: vector2, z: number): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(x: number, yz: vector2): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(xyz: vector3): uint3;\r\nexport function uint3(...args: (vectorOrScalar | number)[]): uint3 {\r\n return args.flat().map((x) => x >>> 0) as uint3;\r\n}\r\n\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, y: number, z: number, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, yz: vector2, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(xy: vector2, z: number, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, y: number, zw: vector2): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(xy: vector2, zw: vector2): uint4;\r\nexport function uint4(xyz: vector3, w: number): uint4;\r\nexport function uint4(x: number, yzw: vector3): uint4;\r\nexport function uint4(xyzw: float4): uint4;\r\nexport function uint4(xyzw: uint4): uint4;\r\nexport function uint4(...args: (vectorOrScalar | number)[]): uint4 {\r\n return args.flat().map((x) => x >>> 0) as uint4;\r\n}\r\n\r\nexport function uint8(x: number): uint8 {\r\n return ((x >>> 0) & 0xff) as uint8;\r\n}\r\n\r\nfunction componentMath(a: any, b: any, f: (a: number, b: number) => number): vectorOrScalar {\r\n let aIsScalar = isScalar(a);\r\n let bIsScalar = isScalar(b);\r\n if (aIsScalar && bIsScalar) {\r\n return f(a, b) as scalar;\r\n }\r\n if (!aIsScalar && !bIsScalar) {\r\n if (a.length !== b.length) {\r\n throw new Error('Cannot perform component-wise math on vectors of different lengths');\r\n }\r\n // return a.map((a, i) => f(a, b[i])) as vector;\r\n if (a.length == 2) {\r\n return [f(a[0], b[0]), f(a[1], b[1])] as vector;\r\n } else if (a.length == 3) {\r\n return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2])] as vector;\r\n } else if (a.length == 4) {\r\n return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2]), f(a[3], b[3])] as vector;\r\n }\r\n } else if (!aIsScalar && bIsScalar) {\r\n if (a.length == 2) {\r\n return [f(a[0], b), f(a[1], b)] as vector;\r\n } else if (a.length == 3) {\r\n return [f(a[0], b), f(a[1], b), f(a[2], b)] as vector;\r\n } else if (a.length == 4) {\r\n return [f(a[0], b), f(a[1], b), f(a[2], b), f(a[3], b)] as vector;\r\n }\r\n } else if (!bIsScalar && aIsScalar) {\r\n if (b.length == 2) {\r\n return [f(a, b[0]), f(a, b[1])] as vector;\r\n } else if (b.length == 3) {\r\n return [f(a, b[0]), f(a, b[1]), f(a, b[2])] as vector;\r\n } else if (b.length == 4) {\r\n return [f(a, b[0]), f(a, b[1]), f(a, b[2]), f(a, b[3])] as vector;\r\n }\r\n }\r\n\r\n throw new Error('Cannot perform component-wise math on a scalar and a vector');\r\n}\r\n\r\nfunction componentMathSingular(a: vectorOrScalar, f: (a: number) => number): vectorOrScalar {\r\n if (isScalar(a)) {\r\n return f(a) as scalar;\r\n }\r\n if (isVector(a)) {\r\n return a.map((a, i) => f(a)) as vector;\r\n }\r\n\r\n throw new Error('Cannot perform component-wise math on a scalar and a vector');\r\n}\r\n\r\ntype cCallCb = (a: number, b: number) => number;\r\ntype cCallCbSingle = (a: number) => number;\r\n\r\nfunction cCall(cb: cCallCb, a: scalar, b: scalar): scalar;\r\nfunction cCall(cb: cCallCb, a: vector, b: scalar): vector;\r\nfunction cCall(cb: cCallCb, a: vector2, b: vector2): vector2;\r\nfunction cCall(cb: cCallCb, a: vector3, b: vector3): vector3;\r\nfunction cCall(cb: cCallCb, a: vector4, b: vector4): vector4;\r\nfunction cCall(cb: cCallCb, a: vectorOrScalar, b: vectorOrScalar): vectorOrScalar {\r\n return componentMath(a, b, (a, b) => a + b);\r\n}\r\n\r\nexport type vectorOverload_2to1_3to3 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float3;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int3;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float3;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float3;\r\n};\r\nexport type vectorOverload_2to1_3to3_4to4 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float3;\r\n (a: float4, b: int4): float4;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float3;\r\n (a: int4, b: float4): float4;\r\n};\r\nexport type vectorOverload_2to1_3to1_4to1 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float;\r\n (a: float4, b: float4): float;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int;\r\n (a: int4, b: int4): int;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float;\r\n (a: float4, b: int4): float;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float;\r\n (a: int4, b: float4): float;\r\n};\r\n\r\nexport type componentOverload = {\r\n (a: int, b: int): int;\r\n (a: int2, b: int2): int2;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n\r\n (a: int, b: float): float;\r\n (a: float, b: int): float;\r\n\r\n (a: float, b: float): float;\r\n\r\n (a: float2, b: float): float2;\r\n (a: float3, b: float): float3;\r\n (a: float4, b: float): float4;\r\n\r\n (a: int2, b: int): int2;\r\n (a: int3, b: int): int3;\r\n (a: int4, b: int): int4;\r\n\r\n (a: int2, b: float): float2;\r\n (a: int3, b: float): float3;\r\n (a: int4, b: float): float4;\r\n\r\n (a: float2, b: int): float2;\r\n (a: float3, b: int): float3;\r\n (a: float4, b: int): float4;\r\n (a: float2, b: float): float2;\r\n\r\n (a: float, b: float2): float2;\r\n (a: float, b: float3): float3;\r\n (a: float, b: float4): float4;\r\n\r\n (a: int, b: int2): int2;\r\n (a: int, b: int3): int3;\r\n (a: int, b: int4): int4;\r\n\r\n (a: float, b: int2): float2;\r\n (a: float, b: int3): float3;\r\n (a: float, b: int4): float4;\r\n\r\n (a: int, b: float2): float2;\r\n (a: int, b: float3): float3;\r\n (a: int, b: float4): float4;\r\n\r\n (a: float2, b: float2): float2;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n\r\n (a: float2, b: int2): float2;\r\n (a: float3, b: int3): float3;\r\n (a: float4, b: int4): float4;\r\n\r\n (a: int2, b: float2): float2;\r\n (a: int3, b: float3): float3;\r\n (a: int4, b: float4): float4;\r\n\r\n (a: uint, b: uint): uint;\r\n (a: uint2, b: uint2): uint2;\r\n (a: uint3, b: uint3): uint3;\r\n (a: uint4, b: uint4): uint4;\r\n};\r\n\r\nexport type componentOverloadMatch = {\r\n (a: uint, b: uint): uint;\r\n (a: uint2, b: uint2): uint2;\r\n (a: uint3, b: uint3): uint3;\r\n (a: uint4, b: uint4): uint4;\r\n (a: uint2, b: uint): uint2;\r\n (a: uint3, b: uint): uint3;\r\n (a: uint4, b: uint): uint4;\r\n\r\n (a: int, b: int): int;\r\n (a: int2, b: int2): int2;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n (a: int2, b: int): int2;\r\n (a: int3, b: int): int3;\r\n (a: int4, b: int): int4;\r\n\r\n (a: float, b: float): float;\r\n (a: float2, b: float2): float2;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n (a: float2, b: float): float2;\r\n (a: float3, b: float): float3;\r\n (a: float4, b: float): float4;\r\n};\r\n\r\nexport type componentOverloadSingular = {\r\n (a: int): int;\r\n (a: float): float;\r\n\r\n (a: float2): float2;\r\n (a: float3): float3;\r\n (a: float4): float4;\r\n\r\n (a: int2): int2;\r\n (a: int3): int3;\r\n (a: int4): int4;\r\n\r\n (a: uint): uint;\r\n (a: uint2): uint2;\r\n (a: uint3): uint3;\r\n (a: uint4): uint4;\r\n};\r\n\r\nexport type componentOverloadSingularFloat = {\r\n // (a: int): int;\r\n (a: float): float;\r\n\r\n (a: float2): float2;\r\n (a: float3): float3;\r\n (a: float4): float4;\r\n\r\n // (a: int2): int2;\r\n // (a: int3): int3;\r\n // (a: int4): int4;\r\n};\r\n\r\nexport type componentOverloadMatrix = {\r\n (a: float2x2, b: float2): float2;\r\n (a: float3x3, b: float3): float3;\r\n (a: float4x4, b: float4): float4;\r\n\r\n (a: float2, b: float2x2): float2;\r\n (a: float3, b: float3x3): float3;\r\n (a: float4, b: float4x4): float4;\r\n\r\n (a: float2x2, b: float2x2): float2x2;\r\n (a: float3x3, b: float3x3): float3x3;\r\n (a: float4x4, b: float4x4): float4x4;\r\n\r\n (a: float2x2, b: float): float2x2;\r\n (a: float3x3, b: float): float3x3;\r\n (a: float4x4, b: float): float4x4;\r\n\r\n (a: float, b: float2x2): float2x2;\r\n (a: float, b: float3x3): float3x3;\r\n (a: float, b: float4x4): float4x4;\r\n};\r\n\r\nfunction componentOp(cb: cCallCb): componentOverload;\r\n\r\nfunction componentOp(cb: cCallCb) {\r\n return (a: any, b: any) => componentMath(a, b, cb);\r\n}\r\n\r\nfunction componentOpMatch(cb: cCallCb): componentOverloadMatch;\r\nfunction componentOpMatch(cb: cCallCb) {\r\n return (a: any, b: any) => componentMath(a, b, cb);\r\n}\r\n\r\nfunction componentOpSingular(cb: cCallCbSingle): componentOverloadSingular;\r\n\r\nfunction componentOpSingular(cb: cCallCbSingle) {\r\n return (a: any) => componentMathSingular(a, cb);\r\n}\r\n\r\nfunction componentOpSingularFloat(cb: cCallCbSingle): componentOverloadSingularFloat;\r\n\r\nfunction componentOpSingularFloat(cb: cCallCbSingle) {\r\n return (a: any) => componentMathSingular(a, cb);\r\n}\r\n\r\n/** @shadeup=univ(!$0$ + $1$)*/\r\nexport const add: componentOverload & ((a: string, b: string) => string) = (\r\n a: any,\r\n b: any\r\n): any => {\r\n if (typeof a === 'string' && typeof b === 'string') {\r\n return `${a}${b}`;\r\n } else {\r\n let addOp: (a: any, b: any) => any = componentOp((a, b) => a + b);\r\n let v: any = addOp(a, b);\r\n return v;\r\n }\r\n};\r\n\r\n/** @shadeup=univ(!$0$ - $1$)*/\r\nexport const sub = componentOp((a, b) => a - b);\r\n\r\ntype matrix = float2x2 | float3x3 | float4x4;\r\n\r\nfunction matrixMul(a: matrix, b: matrix): matrix {\r\n // Multiply two square matrices of the same dimension row-major\r\n\r\n let dimension = a.__matrix;\r\n\r\n let out: float2x2 | float3x3 | float4x4;\r\n if (dimension === 2) {\r\n out = float2x2();\r\n } else if (dimension === 3) {\r\n out = float3x3();\r\n } else if (dimension === 4) {\r\n var a00 = a[0 * 4 + 0];\r\n var a01 = a[0 * 4 + 1];\r\n var a02 = a[0 * 4 + 2];\r\n var a03 = a[0 * 4 + 3];\r\n var a10 = a[1 * 4 + 0];\r\n var a11 = a[1 * 4 + 1];\r\n var a12 = a[1 * 4 + 2];\r\n var a13 = a[1 * 4 + 3];\r\n var a20 = a[2 * 4 + 0];\r\n var a21 = a[2 * 4 + 1];\r\n var a22 = a[2 * 4 + 2];\r\n var a23 = a[2 * 4 + 3];\r\n var a30 = a[3 * 4 + 0];\r\n var a31 = a[3 * 4 + 1];\r\n var a32 = a[3 * 4 + 2];\r\n var a33 = a[3 * 4 + 3];\r\n var b00 = b[0 * 4 + 0];\r\n var b01 = b[0 * 4 + 1];\r\n var b02 = b[0 * 4 + 2];\r\n var b03 = b[0 * 4 + 3];\r\n var b10 = b[1 * 4 + 0];\r\n var b11 = b[1 * 4 + 1];\r\n var b12 = b[1 * 4 + 2];\r\n var b13 = b[1 * 4 + 3];\r\n var b20 = b[2 * 4 + 0];\r\n var b21 = b[2 * 4 + 1];\r\n var b22 = b[2 * 4 + 2];\r\n var b23 = b[2 * 4 + 3];\r\n var b30 = b[3 * 4 + 0];\r\n var b31 = b[3 * 4 + 1];\r\n var b32 = b[3 * 4 + 2];\r\n var b33 = b[3 * 4 + 3];\r\n return float4x4(\r\n b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30,\r\n b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31,\r\n b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32,\r\n b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33,\r\n b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30,\r\n b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31,\r\n b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32,\r\n b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33,\r\n b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30,\r\n b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31,\r\n b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32,\r\n b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33,\r\n b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30,\r\n b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31,\r\n b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32,\r\n b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33\r\n );\r\n out = float4x4();\r\n }\r\n\r\n for (let i = 0; i < dimension; i++) {\r\n for (let j = 0; j < dimension; j++) {\r\n let sum: float = float(0);\r\n for (let k = 0; k < dimension; k++) {\r\n sum += float(a[i * dimension + k] * b[k * dimension + j]);\r\n }\r\n out[i * dimension + j] = sum;\r\n }\r\n }\r\n\r\n return out;\r\n\r\n if (a.__matrix === 2 && b.__matrix === 2) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a10 = a[2];\r\n let a11 = a[3];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b10 = b[2];\r\n let b11 = b[3];\r\n\r\n let v = float2x2(\r\n a00 * b00 + a01 * b10,\r\n a00 * b01 + a01 * b11,\r\n a10 * b00 + a11 * b10,\r\n a10 * b01 + a11 * b11\r\n );\r\n\r\n return v;\r\n } else if (a.__matrix === 3 && b.__matrix === 3) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a02 = a[2];\r\n let a10 = a[3];\r\n let a11 = a[4];\r\n let a12 = a[5];\r\n let a20 = a[6];\r\n let a21 = a[7];\r\n let a22 = a[8];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b02 = b[2];\r\n let b10 = b[3];\r\n let b11 = b[4];\r\n let b12 = b[5];\r\n let b20 = b[6];\r\n let b21 = b[7];\r\n let b22 = b[8];\r\n\r\n let v = float3x3(\r\n a00 * b00 + a01 * b10 + a02 * b20,\r\n a00 * b01 + a01 * b11 + a02 * b21,\r\n a00 * b02 + a01 * b12 + a02 * b22,\r\n a10 * b00 + a11 * b10 + a12 * b20,\r\n a10 * b01 + a11 * b11 + a12 * b21,\r\n a10 * b02 + a11 * b12 + a12 * b22,\r\n a20 * b00 + a21 * b10 + a22 * b20,\r\n a20 * b01 + a21 * b11 + a22 * b21,\r\n a20 * b02 + a21 * b12 + a22 * b22\r\n );\r\n return v;\r\n } else if (a.__matrix === 4 && b.__matrix === 4) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a02 = a[2];\r\n let a03 = a[3];\r\n let a10 = a[4];\r\n let a11 = a[5];\r\n let a12 = a[6];\r\n let a13 = a[7];\r\n let a20 = a[8];\r\n let a21 = a[9];\r\n let a22 = a[10];\r\n let a23 = a[11];\r\n let a30 = a[12];\r\n let a31 = a[13];\r\n let a32 = a[14];\r\n let a33 = a[15];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b02 = b[2];\r\n let b03 = b[3];\r\n let b10 = b[4];\r\n let b11 = b[5];\r\n let b12 = b[6];\r\n let b13 = b[7];\r\n let b20 = b[8];\r\n let b21 = b[9];\r\n let b22 = b[10];\r\n let b23 = b[11];\r\n let b30 = b[12];\r\n let b31 = b[13];\r\n let b32 = b[14];\r\n let b33 = b[15];\r\n\r\n let v = float4x4(\r\n a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30,\r\n a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31,\r\n a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32,\r\n a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33,\r\n a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30,\r\n a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31,\r\n a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32,\r\n a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33,\r\n a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30,\r\n a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31,\r\n a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32,\r\n a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33,\r\n a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30,\r\n a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31,\r\n a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32,\r\n a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33\r\n );\r\n\r\n return v;\r\n } else {\r\n throw new Error('Invalid matrix multiplication');\r\n }\r\n}\r\n\r\nfunction matrixInversefloat2x2(m: float2x2): float2x2 {\r\n let a = m.__index(0).__index(0),\r\n b = m.__index(1).__index(0),\r\n c = m.__index(0).__index(1),\r\n d = m.__index(1).__index(1);\r\n let det = a * d - b * c;\r\n if (det === 0) {\r\n throw new Error('Matrix determinant is zero');\r\n }\r\n let detInv = 1.0 / det;\r\n return float2x2(d * detInv, -b * detInv, -c * detInv, a * detInv);\r\n}\r\nfunction matrixInversefloat3x3(m: float3x3): float3x3 {\r\n let n11 = m.__index(0).__index(0),\r\n n12 = m.__index(1).__index(0),\r\n n13 = m.__index(2).__index(0);\r\n let n21 = m.__index(0).__index(1),\r\n n22 = m.__index(1).__index(1),\r\n n23 = m.__index(2).__index(1);\r\n let n31 = m.__index(0).__index(2),\r\n n32 = m.__index(1).__index(2),\r\n n33 = m.__index(2).__index(2);\r\n let t11 = n33 * n22 - n32 * n23,\r\n t12 = n32 * n13 - n33 * n12,\r\n t13 = n23 * n12 - n22 * n13;\r\n let det = n11 * t11 + n21 * t12 + n31 * t13;\r\n if (det === 0) {\r\n throw new Error('Invalid matrix inverse');\r\n }\r\n let detInv = 1 / det;\r\n let v = float3x3(\r\n t11 * detInv,\r\n (n31 * n23 - n33 * n21) * detInv,\r\n (n32 * n21 - n31 * n22) * detInv,\r\n t12 * detInv,\r\n (n33 * n11 - n31 * n13) * detInv,\r\n (n31 * n12 - n32 * n11) * detInv,\r\n t13 * detInv,\r\n (n21 * n13 - n23 * n11) * detInv,\r\n (n22 * n11 - n21 * n12) * detInv\r\n );\r\n return v;\r\n}\r\nfunction matrixInversefloat4x4(m: float4x4): float4x4 {\r\n var m00 = m[0 * 4 + 0];\r\n var m01 = m[0 * 4 + 1];\r\n var m02 = m[0 * 4 + 2];\r\n var m03 = m[0 * 4 + 3];\r\n var m10 = m[1 * 4 + 0];\r\n var m11 = m[1 * 4 + 1];\r\n var m12 = m[1 * 4 + 2];\r\n var m13 = m[1 * 4 + 3];\r\n var m20 = m[2 * 4 + 0];\r\n var m21 = m[2 * 4 + 1];\r\n var m22 = m[2 * 4 + 2];\r\n var m23 = m[2 * 4 + 3];\r\n var m30 = m[3 * 4 + 0];\r\n var m31 = m[3 * 4 + 1];\r\n var m32 = m[3 * 4 + 2];\r\n var m33 = m[3 * 4 + 3];\r\n var tmp_0 = m22 * m33;\r\n var tmp_1 = m32 * m23;\r\n var tmp_2 = m12 * m33;\r\n var tmp_3 = m32 * m13;\r\n var tmp_4 = m12 * m23;\r\n var tmp_5 = m22 * m13;\r\n var tmp_6 = m02 * m33;\r\n var tmp_7 = m32 * m03;\r\n var tmp_8 = m02 * m23;\r\n var tmp_9 = m22 * m03;\r\n var tmp_10 = m02 * m13;\r\n var tmp_11 = m12 * m03;\r\n var tmp_12 = m20 * m31;\r\n var tmp_13 = m30 * m21;\r\n var tmp_14 = m10 * m31;\r\n var tmp_15 = m30 * m11;\r\n var tmp_16 = m10 * m21;\r\n var tmp_17 = m20 * m11;\r\n var tmp_18 = m00 * m31;\r\n var tmp_19 = m30 * m01;\r\n var tmp_20 = m00 * m21;\r\n var tmp_21 = m20 * m01;\r\n var tmp_22 = m00 * m11;\r\n var tmp_23 = m10 * m01;\r\n\r\n var t0 = tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31 - (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);\r\n var t1 = tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31 - (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);\r\n var t2 = tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31 - (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);\r\n var t3 = tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21 - (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);\r\n\r\n var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);\r\n if (d === 0) {\r\n throw new Error('Invalid matrix inverse');\r\n }\r\n return float4x4(\r\n d * t0,\r\n d * t1,\r\n d * t2,\r\n d * t3,\r\n d * (tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30 - (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30)),\r\n d * (tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30 - (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30)),\r\n d * (tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30 - (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30)),\r\n d * (tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20 - (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20)),\r\n d * (tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33 - (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33)),\r\n d * (tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33 - (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33)),\r\n d * (tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33 - (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33)),\r\n d * (tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23 - (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23)),\r\n d * (tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12 - (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22)),\r\n d * (tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22 - (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02)),\r\n d * (tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02 - (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12)),\r\n d * (tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12 - (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02))\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat2x2(m: float2x2): float2x2 {\r\n return float2x2(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1)\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat3x3(m: float3x3): float3x3 {\r\n return float3x3(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(2).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1),\r\n m.__index(2).__index(1),\r\n m.__index(0).__index(2),\r\n m.__index(1).__index(2),\r\n m.__index(2).__index(2)\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat4x4(m: float4x4): float4x4 {\r\n return float4x4(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(2).__index(0),\r\n m.__index(3).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1),\r\n m.__index(2).__index(1),\r\n m.__index(3).__index(1),\r\n m.__index(0).__index(2),\r\n m.__index(1).__index(2),\r\n m.__index(2).__index(2),\r\n m.__index(3).__index(2),\r\n m.__index(0).__index(3),\r\n m.__index(1).__index(3),\r\n m.__index(2).__index(3),\r\n m.__index(3).__index(3)\r\n );\r\n}\r\n\r\nfunction matrixMul2x2float2(a: float2x2, b: float2): float2 {\r\n let c: number[] = [0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 2; j++) {\r\n for (let i = 0; i < 2; i++) {\r\n c[i] += a[j * 2 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float2;\r\n}\r\n\r\nfunction matrixMul3x3float3(a: float3x3, b: float3): float3 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 3; i++) {\r\n for (let j = 0; j < 3; j++) {\r\n c[i] += a[j * 3 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float3;\r\n}\r\n\r\nfunction matrixMul4x4float4(a: float4x4, b: float4): float4 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 4; j++) {\r\n for (let i = 0; i < 4; i++) {\r\n c[i] += a[j * 4 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float4;\r\n}\r\n\r\nfunction matrixMulfloat22x2(a: float2, b: float2x2): float2 {\r\n let c: number[] = [0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 2; j++) {\r\n for (let i = 0; i < 2; i++) {\r\n c[i] += a[j] * b[i * 2 + j];\r\n }\r\n }\r\n\r\n return c as float2;\r\n}\r\n\r\nfunction matrixMulfloat33x3(a: float3, b: float3x3): float3 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 3; i++) {\r\n for (let j = 0; j < 3; j++) {\r\n c[i] += a[j] * b[i * 3 + j];\r\n }\r\n }\r\n\r\n return c as float3;\r\n}\r\n\r\nfunction matrixMulfloat44x4(a: float4, b: float4x4): float4 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 4; i++) {\r\n for (let j = 0; j < 4; j++) {\r\n c[i] += a[j] * b[i * 4 + j];\r\n }\r\n }\r\n\r\n return c as float4;\r\n}\r\n\r\nlet mulFunc: (a: any, b: any) => any = componentOp((a, b) => a * b);\r\n\r\n/** @shadeup=univ(#matrix_inverse)*/\r\nexport function inverse(a: float2x2): float2x2;\r\nexport function inverse(a: float3x3): float3x3;\r\nexport function inverse(a: float4x4): float4x4;\r\nexport function inverse(a: float2x2 | float3x3 | float4x4): float2x2 | float3x3 | float4x4 {\r\n if (a.__matrix == 2) {\r\n return matrixInversefloat2x2(a as float2x2);\r\n } else if (a.__matrix == 3) {\r\n return matrixInversefloat3x3(a as float3x3);\r\n } else if (a.__matrix == 4) {\r\n return matrixInversefloat4x4(a as float4x4);\r\n }\r\n}\r\n\r\n/** @shadeup=univ(#matrix_transpose)*/\r\nexport function transpose(a: float2x2): float2x2;\r\nexport function transpose(a: float3x3): float3x3;\r\nexport function transpose(a: float4x4): float4x4;\r\nexport function transpose(a: float2x2 | float3x3 | float4x4): float2x2 | float3x3 | float4x4 {\r\n if (a.__matrix == 2) {\r\n return matrixTransposefloat2x2(a as float2x2);\r\n } else if (a.__matrix == 3) {\r\n return matrixTransposefloat3x3(a as float3x3);\r\n } else if (a.__matrix == 4) {\r\n return matrixTransposefloat4x4(a as float4x4);\r\n }\r\n}\r\n\r\n/** @shadeup=univ(!$0$ * $1$)*/\r\nexport const mul: componentOverload & componentOverloadMatrix = (a: any, b: any): any => {\r\n if (isMatrix(a) || isMatrix(b)) {\r\n if (isMatrix(a) && isMatrix(b)) {\r\n return matrixMul(a, b);\r\n } else {\r\n if (isMatrix(a) && typeof b == 'number') {\r\n return componentMath(b as scalar, a as any, (a, b) => a * b);\r\n } else if (isMatrix(b) && typeof a == 'number') {\r\n return componentMath(a as scalar, b as any, (a, b) => a * b);\r\n } else {\r\n if (isMatrix(a)) {\r\n if (a.length == 4) {\r\n return matrixMul2x2float2(a as float2x2, b as float2);\r\n } else if (a.length == 9) {\r\n return matrixMul3x3float3(a as float3x3, b as float3);\r\n } else if (a.length == 16) {\r\n return matrixMul4x4float4(a as float4x4, b as float4);\r\n }\r\n } else if (isMatrix(b)) {\r\n if (b.length == 4) {\r\n return matrixMulfloat22x2(a as float2, b as float2x2);\r\n } else if (b.length == 9) {\r\n return matrixMulfloat33x3(a as float3, b as float3x3);\r\n } else if (b.length == 16) {\r\n return matrixMulfloat44x4(a as float4, b as float4x4);\r\n }\r\n }\r\n }\r\n }\r\n } else {\r\n return mulFunc(a, b);\r\n }\r\n};\r\n\r\n/** @shadeup=univ(!$0$ / $1$)*/\r\nexport const div = componentOp((a, b) => a / b);\r\n\r\n/** @shadeup=glsl(!$0$ ** $1$) @shadeup=wgsl(!pow($0$, $1$))*/\r\nexport const pow = componentOp((a, b) => Math.pow(a, b));\r\n\r\n/** @shadeup=wgsl(!$0$ % $1$) @shadeup=glsl(!mod($0$, $1$))*/\r\nexport const mod = componentOpMatch((a, b) => a - b * Math.floor(a / b));\r\n\r\n/** @shadeup=univ(!$0$ & $1$)*/\r\nexport const bitand = componentOp((a, b) => a & b);\r\n\r\n/** @shadeup=univ(!$0$ | $1$)*/\r\nexport const bitor = componentOp((a, b) => a | b);\r\n\r\n/** @shadeup=univ(!$0$ ^ $1$)*/\r\nexport const bitxor = componentOp((a, b) => a ^ b);\r\n\r\n/** @shadeup=glsl(!$0$ << $1$) @shadeup=wgsl(!$0$ << u32($1$))*/\r\nexport const lshift = componentOp((a, b) => a << b);\r\n\r\n/** @shadeup=glsl(!$0$ >> $1$) @shadeup=wgsl(!$0$ >> u32($1$))*/\r\nexport const rshift = componentOp((a, b) => a >> b);\r\n\r\n/** @shadeup=univ(!~$0$)*/\r\nexport const bitnot = componentOpSingular((a) => ~a);\r\n\r\n/** @shadeup=univ(!-($0$))*/\r\nexport const negate = componentOpSingular((a) => -a);\r\n\r\n/** @shadeup=univ(!+($0$))*/\r\nexport const positive = componentOpSingular((a) => Math.abs(a));\r\n\r\n/** @shadeup=univ(abs)*/\r\nexport const abs = componentOpSingular((a) => Math.abs(a));\r\n\r\n/** @shadeup=glsl(floor) @shadeup=wgsl(!floor(f32(1.0) * $0$))*/\r\nexport const floor = componentOpSingular(Math.floor);\r\n\r\n/** @shadeup=glsl(ceil) @shadeup=wgsl(!ceil(f32(1.0) * $0$))*/\r\nexport const ceil = componentOpSingular(Math.ceil);\r\n\r\n/** @shadeup=univ(round)*/\r\nexport const round = componentOpSingular(Math.round);\r\n\r\n/** @shadeup=univ(sign)*/\r\nexport const sign = componentOpSingular(Math.sign);\r\n\r\n/** @shadeup=univ(cos) */\r\nexport const cos = componentOpSingular(Math.cos);\r\n\r\n/** @shadeup=univ(sin) */\r\nexport const sin = componentOpSingularFloat(Math.sin);\r\n\r\n/** @shadeup=univ(tan) */\r\nexport const tan = componentOpSingular(Math.tan);\r\n\r\n/** @shadeup=univ(acos) */\r\nexport const acos = componentOpSingular(Math.acos);\r\n\r\n/** @shadeup=univ(asin) */\r\nexport const asin = componentOpSingular(Math.asin);\r\n\r\n/** @shadeup=univ(atan) */\r\nexport const atan = componentOpSingular(Math.atan);\r\n\r\n/** @shadeup=univ(atan2) */\r\nexport const atan2: (dy: float, dx: float) => float = Math.atan2 as any;\r\n\r\n/** @shadeup=univ(cosh) */\r\nexport const cosh = componentOpSingular(Math.cosh);\r\n\r\n/** @shadeup=univ(sinh) */\r\nexport const sinh = componentOpSingular(Math.sinh);\r\n\r\n/** @shadeup=univ(tanh) */\r\nexport const tanh = componentOpSingular(Math.tanh);\r\n\r\n/** @shadeup=univ(acosh) */\r\nexport const acosh = componentOpSingular(Math.acosh);\r\n\r\n/** @shadeup=univ(asinh) */\r\nexport const asinh = componentOpSingular(Math.asinh);\r\n\r\n/** @shadeup=univ(atanh) */\r\nexport const atanh = componentOpSingular(Math.atanh);\r\n\r\n/** @shadeup=univ(exp) */\r\nexport const exp = componentOpSingular(Math.exp);\r\n\r\n/** @shadeup=univ(log) */\r\nexport const log = componentOpSingular(Math.log);\r\n\r\n/** @shadeup=univ(log2) */\r\nexport const log2 = componentOpSingular(Math.log2);\r\n\r\n/** @shadeup=univ(log10) */\r\nexport const log10 = componentOpSingular(Math.log10);\r\n\r\n/** @shadeup=univ(sqrt) */\r\nexport const sqrt = componentOpSingular(Math.sqrt);\r\n\r\n/** @shadeup=univ(inversesqrt) */\r\nexport const inversesqrt = componentOpSingular((a) => 1 / Math.sqrt(a));\r\n\r\n/** @shadeup=univ(fract)*/\r\nexport const frac = componentOpSingular((a) => a - Math.floor(a));\r\n\r\nexport function wrap(x: float, low: float, high: float): float {\r\n if (lt(x, low)) {\r\n let rng = sub(high, low);\r\n let s1 = sub(low, x);\r\n let ms = mod(s1, rng);\r\n return sub(high, ms);\r\n } else if (gte(x, high)) {\r\n let rng = sub(high, low);\r\n let s1 = sub(x, high);\r\n let ms = mod(s1, rng);\r\n return add(low, ms);\r\n } else {\r\n return x;\r\n }\r\n // return add(mod(sub(x, low), sub(high, low)), low) as T;\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\n\r\nexport function rand(seed?: float): float {\r\n if (typeof seed === 'number') {\r\n return frac(mul(sin(mul(seed, float(91.3458))), float(47453.5453))) as float;\r\n } else {\r\n return Math.random() as float;\r\n }\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\nexport function rand2(seed: float2): float {\r\n return frac(mul(sin(dot(seed, float2(12.9898, 4.1414))), float(43758.5453)));\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\nexport function rand3(seed: float3): float {\r\n return rand2(add(swizzle(seed, 'xy'), rand(swizzle(seed, 'z'))));\r\n}\r\n\r\n// export function remap(x: float, low1: float, high1: float, low2: float, high2: float): float {\r\n// return add(low2, mul(div(sub(x, low1), sub(high1, low1)), sub(high2, low2)));\r\n// }\r\n\r\nexport function pingpong(x: float, length: float): float {\r\n const t = mod(x, mul(length, float(2)));\r\n return sub(length, abs(sub(t, length)));\r\n}\r\n\r\nfunction vectorMath_2to1_3to3(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => vector3\r\n): vectorOverload_2to1_3to3 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\n\r\nfunction vectorMath_2to1_3to3_4to4(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => vector3,\r\n cb4: (a: vector4, b: vector4) => vector4\r\n): vectorOverload_2to1_3to3_4to4 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return cb4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\nfunction vectorMath_2to1_3to1_4to1(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => scalar,\r\n cb4: (a: vector4, b: vector4) => scalar\r\n): vectorOverload_2to1_3to1_4to1 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return cb4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\n\r\nfunction cross2(a: float2, b: float2): any {\r\n return a[0] * b[1] - a[1] * b[0];\r\n}\r\n\r\nfunction cross3(a: float3, b: float3): any {\r\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\r\n}\r\n\r\nexport const cross = vectorMath_2to1_3to3(cross2, cross3);\r\n\r\nfunction dot2(a: float2, b: float2): any {\r\n return a[0] * b[0] + a[1] * b[1];\r\n}\r\n\r\nfunction dot3(a: float3, b: float3): any {\r\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\r\n}\r\n\r\nfunction dot4(a: float4, b: float4): any {\r\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\r\n}\r\n\r\n/** @shadeup=univ(dot)*/\r\nexport const dot = vectorMath_2to1_3to1_4to1(dot2, dot3, dot4);\r\n\r\nfunction lerp1(a: float, b: float, t: float): float {\r\n return (a + (b - a) * t) as float;\r\n}\r\n\r\nfunction lerp2(a: float2, b: float2, t: float): float2 {\r\n return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t)] as float2;\r\n}\r\n\r\nfunction lerp3(a: float3, b: float3, t: float): float3 {\r\n return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t)] as float3;\r\n}\r\n\r\nfunction lerp4(a: float4, b: float4, t: float): float4 {\r\n return [\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t)\r\n ] as float4;\r\n}\r\n\r\nfunction lerp2x2(a: float2x2, b: float2x2, t: float): float2x2 {\r\n return float2x2(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t)\r\n );\r\n}\r\n\r\nfunction lerp3x3(a: float3x3, b: float3x3, t: float): float3x3 {\r\n return float3x3(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t),\r\n lerp1(a[4], b[4], t),\r\n lerp1(a[5], b[5], t),\r\n lerp1(a[6], b[6], t),\r\n lerp1(a[7], b[7], t),\r\n lerp1(a[8], b[8], t)\r\n );\r\n}\r\n\r\nfunction lerp4x4(a: float4x4, b: float4x4, t: float): float4x4 {\r\n return float4x4(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t),\r\n lerp1(a[4], b[4], t),\r\n lerp1(a[5], b[5], t),\r\n lerp1(a[6], b[6], t),\r\n lerp1(a[7], b[7], t),\r\n lerp1(a[8], b[8], t),\r\n lerp1(a[9], b[9], t),\r\n lerp1(a[10], b[10], t),\r\n lerp1(a[11], b[11], t),\r\n lerp1(a[12], b[12], t),\r\n lerp1(a[13], b[13], t),\r\n lerp1(a[14], b[14], t),\r\n lerp1(a[15], b[15], t)\r\n );\r\n}\r\n\r\n/** @shadeup=univ(mix)*/\r\nexport function lerp(a: float, b: float, t: float): float;\r\nexport function lerp(a: float2, b: float2, t: float): float2;\r\nexport function lerp(a: float3, b: float3, t: float): float3;\r\nexport function lerp(a: float4, b: float4, t: float): float4;\r\nexport function lerp(a: float2x2, b: float2x2, t: float): float2x2;\r\nexport function lerp(a: float3x3, b: float3x3, t: float): float3x3;\r\nexport function lerp(a: float4x4, b: float4x4, t: float): float4x4;\r\n/** @shadeup=univ(mix)*/\r\nexport function lerp(a: any, b: any, t: float): any {\r\n if (typeof a === 'number' && typeof b === 'number' && typeof t === 'number') {\r\n return lerp1(a as float, b as float, t);\r\n } else if (isMatrix(a) && isMatrix(b)) {\r\n if (a.length === 4 && b.length === 4) {\r\n return lerp2x2(a as float2x2, b as float2x2, t);\r\n } else if (a.length === 9 && b.length === 9) {\r\n return lerp3x3(a as float3x3, b as float3x3, t);\r\n } else if (a.length === 16 && b.length === 16) {\r\n return lerp4x4(a as float4x4, b as float4x4, t);\r\n } else {\r\n throw new Error('Invalid matrix length');\r\n }\r\n } else if (a.length === 2 && b.length === 2 && typeof t === 'number') {\r\n return lerp2(a, b, t as float);\r\n } else if (a.length === 3 && b.length === 3 && typeof t === 'number') {\r\n return lerp3(a, b, t);\r\n } else if (a.length === 4 && b.length === 4 && typeof t === 'number') {\r\n return lerp4(a, b, t);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(!bilerp_`0`($0$, $1$, $2$, $3$, $4$, $5$)) */\r\nexport function bilerp(a: float, b: float, c: float, d: float, u: float, v: float): float;\r\nexport function bilerp(a: float2, b: float2, c: float2, d: float2, u: float, v: float): float2;\r\nexport function bilerp(a: float3, b: float3, c: float3, d: float3, u: float, v: float): float3;\r\nexport function bilerp(a: float4, b: float4, c: float4, d: float4, u: float, v: float): float4;\r\nexport function bilerp(\r\n a: float2x2,\r\n b: float2x2,\r\n c: float2x2,\r\n d: float2x2,\r\n u: float,\r\n v: float\r\n): float2x2;\r\nexport function bilerp(\r\n a: float3x3,\r\n b: float3x3,\r\n c: float3x3,\r\n d: float3x3,\r\n u: float,\r\n v: float\r\n): float3x3;\r\nexport function bilerp(\r\n a: float4x4,\r\n b: float4x4,\r\n c: float4x4,\r\n d: float4x4,\r\n u: float,\r\n v: float\r\n): float4x4;\r\n/** @shadeup=univ(!bilerp_`0`($0$, $1$, $2$, $3$, $4$, $5$)) */\r\nexport function bilerp(a: any, b: any, c: any, d: any, u: float, v: float): any {\r\n return lerp(lerp(a, b, u), lerp(c, d, u), v);\r\n}\r\n\r\n/** @shadeup=univ(length)*/\r\nexport function length(a: float): float;\r\nexport function length(a: float2): float;\r\nexport function length(a: float3): float;\r\nexport function length(a: float4): float;\r\n/** @shadeup=univ(length)*/\r\nexport function length(a: any): any {\r\n if (typeof a === 'number') {\r\n return Math.abs(a);\r\n } else if (a.length === 2) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2));\r\n } else if (a.length === 3) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2));\r\n } else if (a.length === 4) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2));\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(distance)*/\r\nexport function dist(a: float, b: float): float;\r\nexport function dist(a: float2, b: float2): float;\r\nexport function dist(a: float3, b: float3): float;\r\nexport function dist(a: float4, b: float4): float;\r\nexport function dist(a: T, b: T): float {\r\n return length(sub(a, b));\r\n}\r\n\r\n/** @shadeup=univ(distance)*/\r\nexport const distance = dist;\r\n\r\n/** @shadeup=univ(normalize)*/\r\nexport function normalize(a: float2): float2;\r\nexport function normalize(a: float3): float3;\r\nexport function normalize(a: float4): float4;\r\n/** @shadeup=univ(normalize)*/\r\nexport function normalize(a: any): any {\r\n if (a.length === 2) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l];\r\n } else if (a.length === 3) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l, a[2] / l];\r\n } else if (a.length === 4) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l, a[2] / l, a[3] / l];\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(reflect)*/\r\nexport function reflect(a: float2, b: float2): float2;\r\nexport function reflect(a: float3, b: float3): float3;\r\nexport function reflect(a: float4, b: float4): float4;\r\n/** @shadeup=univ(reflect)*/\r\nexport function reflect(a: any, b: any): any {\r\n if (a.length === 2 && b.length === 2) {\r\n return reflect2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return reflect3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return reflect4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\nfunction reflect2(b, a) {\r\n let dot = dot2(a, b);\r\n return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1]];\r\n}\r\n\r\nfunction reflect3(b, a) {\r\n let dot = dot3(a, b);\r\n return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1], b[2] - 2 * dot * a[2]];\r\n}\r\n\r\nfunction reflect4(b, a) {\r\n let dot = dot4(a, b);\r\n return [\r\n b[0] - 2 * dot * a[0],\r\n b[1] - 2 * dot * a[1],\r\n b[2] - 2 * dot * a[2],\r\n b[3] - 2 * dot * a[3]\r\n ];\r\n}\r\n\r\n/** @shadeup=univ(refract)*/\r\nexport function refract(a: float2, b: float2, eta: float): float2;\r\nexport function refract(a: float3, b: float3, eta: float): float3;\r\nexport function refract(a: float4, b: float4, eta: float): float4;\r\n/** @shadeup=univ(refract)*/\r\nexport function refract(a: any, b: any, eta: number): any {\r\n if (a.length === 2 && b.length === 2) {\r\n return refract2(a, b, eta);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return refract3(a, b, eta);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return refract4(a, b, eta);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\nfunction refract2(b, a, eta) {\r\n let dot = dot2(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1]\r\n ];\r\n}\r\n\r\nfunction refract3(b, a, eta) {\r\n let dot = dot3(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1],\r\n eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2]\r\n ];\r\n}\r\n\r\nfunction refract4(b, a, eta) {\r\n let dot = dot4(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0, 0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1],\r\n eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2],\r\n eta * b[3] - (eta * dot + Math.sqrt(k)) * a[3]\r\n ];\r\n}\r\n\r\n/** @shadeup=univ(degrees)*/\r\nexport function degrees(a: float): float {\r\n return float((a * 180) / Math.PI);\r\n}\r\n\r\n/** @shadeup=univ(radians)*/\r\nexport function radians(a: float): float {\r\n return float((a * Math.PI) / 180);\r\n}\r\n\r\n/** @shadeup=univ(step)*/\r\nexport function step(edge: float, x: float): float;\r\nexport function step(edge: int, x: float): float;\r\nexport function step(edge: T, x: T): T;\r\nexport function step(edge: float, x: T): T;\r\nexport function step(edge: int, x: T): T;\r\n/** @shadeup=univ(step)*/\r\nexport function step(edge: any, x: any): any {\r\n if (typeof edge === 'number') {\r\n if (typeof x === 'number') {\r\n return x < edge ? 0 : 1;\r\n } else {\r\n return x.map((v) => (v < edge ? 0 : 1));\r\n }\r\n } else {\r\n if (typeof x === 'number') {\r\n return edge.map((v) => (x < v ? 0 : 1));\r\n } else {\r\n return edge.map((v, i) => (x[i] < v ? 0 : 1));\r\n }\r\n }\r\n}\r\n\r\nfunction _smoothstep(a, b, x) {\r\n let t = clamp((x - a) / (b - a), 0, 1);\r\n return t * t * (3 - 2 * t);\r\n}\r\n\r\n/** @shadeup=univ(smoothstep)*/\r\nexport function smoothstep(a: float, b: float, x: float): float;\r\nexport function smoothstep(a: float2, b: float2, x: float2): float2;\r\nexport function smoothstep(a: float3, b: float3, x: float3): float3;\r\nexport function smoothstep(a: float4, b: float4, x: float4): float4;\r\n/** @shadeup=univ(smoothstep)*/\r\nexport function smoothstep(a: any, b: any, x: any): any {\r\n if (typeof a === 'number' && typeof b === 'number' && typeof x === 'number') {\r\n return _smoothstep(a, b, x);\r\n } else if (typeof a === 'number' && typeof b === 'number') {\r\n return x.map((v) => _smoothstep(a, b, v));\r\n } else {\r\n return a.map((v, i) => _smoothstep(v, b[i], x[i]));\r\n }\r\n}\r\n\r\nfunction componentReduce(vectors: vector[], cb: (a: scalar[]) => scalar) {\r\n let result: scalar[] = [];\r\n for (let i = 0; i < vectors[0].length; i++) {\r\n result.push(cb(vectors.map((v) => v[i])));\r\n }\r\n return result;\r\n}\r\n\r\n/** @shadeup=univ(min)*/\r\n\r\nexport function min(a: int, ...b: int[]): int;\r\nexport function min(a: int2, ...b: int2[]): int2;\r\nexport function min(a: int3, ...b: int3[]): int3;\r\nexport function min(a: int4, ...b: int4[]): int4;\r\nexport function min(a: float, ...b: float[]): float;\r\nexport function min(a: float2, ...b: float2[]): float2;\r\nexport function min(a: float3, ...b: float3[]): float3;\r\nexport function min(a: float4, ...b: float4[]): float4;\r\n\r\nexport function min(a: float, b: T): T;\r\nexport function min(a: T, b: float): T;\r\nexport function min(a: int, b: T): T;\r\nexport function min(a: T, b: int): T;\r\n\r\n/** @shadeup=univ(min)*/\r\nexport function min(...args: T[]): T {\r\n if (args.length == 1) {\r\n if (Array.isArray(args[0])) {\r\n return Math.min(...args[0]) as T;\r\n } else {\r\n return args[0];\r\n }\r\n } else {\r\n if (Array.isArray(args[0]) && !Array.isArray(args[1])) {\r\n let minTo = args[1] as float;\r\n return args[0].map((v) => Math.min(v, minTo)) as T;\r\n } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) {\r\n let minFrom = args[0] as float;\r\n return args[1].map((v) => Math.min(minFrom, v)) as T;\r\n } else if (Array.isArray(args[0])) {\r\n return componentReduce(args as vector[], (a) => Math.min(...a) as scalar) as T;\r\n } else {\r\n return Math.min(...(args as number[])) as T;\r\n }\r\n }\r\n}\r\n\r\n/** @shadeup=univ(max)*/\r\n\r\nexport function max(a: int, ...b: int[]): int;\r\nexport function max(a: float, ...b: int[]): float;\r\nexport function max(a: int, ...b: float[]): float;\r\nexport function max(a: int2, ...b: int2[]): int2;\r\nexport function max(a: int3, ...b: int3[]): int3;\r\nexport function max(a: int4, ...b: int4[]): int4;\r\nexport function max(a: float, ...b: float[]): float;\r\nexport function max(a: float2, ...b: float2[]): float2;\r\nexport function max(a: float3, ...b: float3[]): float3;\r\nexport function max(a: float4, ...b: float4[]): float4;\r\n\r\nexport function max(a: float, b: T): T;\r\nexport function max(a: T, b: float): T;\r\nexport function max(a: int, b: T): T;\r\nexport function max(a: T, b: int): T;\r\n/** @shadeup=univ(max)*/\r\nexport function max(...args: T[]): T {\r\n if (args.length == 1) {\r\n if (Array.isArray(args[0])) {\r\n return Math.max(...args[0]) as T;\r\n } else {\r\n return args[0];\r\n }\r\n } else {\r\n if (Array.isArray(args[0]) && !Array.isArray(args[1])) {\r\n let maxTo = args[1] as float;\r\n return args[0].map((v) => Math.max(v, maxTo)) as T;\r\n } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) {\r\n let maxFrom = args[0] as float;\r\n return args[1].map((v) => Math.max(maxFrom, v)) as T;\r\n } else if (Array.isArray(args[0])) {\r\n return componentReduce(args as vector[], (a) => Math.max(...a) as scalar) as T;\r\n } else {\r\n return Math.max(...(args as number[])) as T;\r\n }\r\n }\r\n}\r\n\r\n/** @shadeup=univ(clamp)*/\r\nexport function clamp(arg: int, min: int, max: int): int;\r\nexport function clamp(arg: int2, min: int, max: int): int2;\r\nexport function clamp(arg: int3, min: int, max: int): int3;\r\nexport function clamp(arg: int4, min: int, max: int): int4;\r\n\r\nexport function clamp(arg: int2, min: int2, max: int2): int2;\r\nexport function clamp(arg: int3, min: int3, max: int3): int3;\r\nexport function clamp(arg: int4, min: int3, max: int3): int4;\r\n\r\nexport function clamp(arg: float, min: float, max: float): float;\r\nexport function clamp(arg: float2, min: float, max: float): float2;\r\nexport function clamp(arg: float3, min: float, max: float): float3;\r\nexport function clamp(arg: float4, min: float, max: float): float4;\r\n\r\nexport function clamp(arg: float2, min: float2, max: float2): float2;\r\nexport function clamp(arg: float3, min: float3, max: float3): float3;\r\nexport function clamp(arg: float4, min: float4, max: float4): float4;\r\n/** @shadeup=univ(clamp)*/\r\nexport function clamp(arg: any, min: any, max: any): any {\r\n if (Array.isArray(arg)) {\r\n if (Array.isArray(min) && Array.isArray(max)) {\r\n return arg.map((a, i) => Math.min(Math.max(a, min[i]), max[i]));\r\n } else {\r\n return arg.map((a) => Math.min(Math.max(a, min), max));\r\n }\r\n } else {\r\n return Math.min(Math.max(arg, min), max);\r\n }\r\n}\r\n\r\n/** @shadeup=glsl(!clamp($0$, 0.0, 1.0)) @shadeup=wgsl(saturate)*/\r\nexport function saturate(arg: float): float;\r\nexport function saturate(arg: float2): float2;\r\nexport function saturate(arg: float3): float3;\r\nexport function saturate(arg: float4): float4;\r\n/** @shadeup=glsl(!clamp($0$, 0.0, 1.0)) @shadeup=wgsl(saturate) */\r\nexport function saturate(arg: any): any {\r\n return clamp(arg, float(0), float(1));\r\n}\r\n\r\n/** @shadeup=univ(!($0$ == $1$))*/\r\nexport function eq(a: T, b: T): bool;\r\nexport function eq(a: any, b: any): bool {\r\n let ta = typeof a;\r\n let tb = typeof b;\r\n if (ta != tb) {\r\n return false;\r\n } else if (\r\n (ta == 'number' && tb == 'number') ||\r\n (ta == 'string' && tb == 'string') ||\r\n (ta == 'boolean' && tb == 'boolean') ||\r\n (ta == 'undefined' && tb == 'undefined')\r\n ) {\r\n return a == b;\r\n } else if (ta == 'object' && tb == 'object') {\r\n if (Array.isArray(a) && Array.isArray(b)) {\r\n if (a.length != b.length) {\r\n return false;\r\n }\r\n for (let i = 0; i < a.length; i++) {\r\n if (!eq(a[i], b[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n } else {\r\n return a == b;\r\n }\r\n }\r\n}\r\n\r\n/** @shadeup=univ(!($0$ != $1$))*/\r\nexport const neq = (a, b) => !eq(a, b);\r\n\r\n/** @shadeup=univ(!($0$ < $1$))*/\r\nexport const lt = (a: scalar, b: scalar) => a < b;\r\n\r\n/** @shadeup=univ(!($0$ <= $1$))*/\r\nexport const lte = (a: scalar, b: scalar) => a <= b;\r\n\r\n/** @shadeup=univ(!($0$ > $1$))*/\r\nexport const gt = (a: scalar, b: scalar) => a > b;\r\n\r\n/** @shadeup=univ(!($0$ >= $1$))*/\r\nexport const gte = (a: scalar, b: scalar) => a >= b;\r\n\r\n/** @shadeup=univ(!($0$ && $1$))*/\r\nexport const and = (a: boolean, b: boolean) => a && b;\r\n\r\n/** @shadeup=univ(!($0$ || $1$))*/\r\nexport const or = (a: boolean, b: boolean) => a || b;\r\n\r\n/** @shadeup=univ(!(!$0$))*/\r\nexport const not = (a: boolean) => !a;\r\n\r\n/** @shadeup=univ(~)*/\r\nexport function makeVector(x: int, y: int): int2;\r\nexport function makeVector(x: float, y: int): float2;\r\nexport function makeVector(x: int, y: float): float2;\r\nexport function makeVector(x: float, y: float): float2;\r\n\r\nexport function makeVector(x: int, y: int, z: int): int3;\r\nexport function makeVector(xy: int2, z: int): int3;\r\nexport function makeVector(x: int, yz: int2): int3;\r\n\r\nexport function makeVector(x: float, y: int, z: int): float3;\r\nexport function makeVector(x: int, y: float, z: int): float3;\r\nexport function makeVector(x: int, y: int, z: float): float3;\r\nexport function makeVector(x: float, y: float, z: int): float3;\r\nexport function makeVector(x: float, y: int, z: float): float3;\r\nexport function makeVector(x: int, y: float, z: float): float3;\r\nexport function makeVector(x: float, y: float, z: float): float3;\r\nexport function makeVector(xy: float2, z: float): float3;\r\nexport function makeVector(x: float, yz: float2): float3;\r\nexport function makeVector(xy: int2, z: float): float3;\r\nexport function makeVector(x: int, yz: float2): float3;\r\nexport function makeVector(xy: float2, z: int): float3;\r\nexport function makeVector(x: float, yz: int2): float3;\r\n\r\nexport function makeVector(x: int, y: int, z: int, w: int): int4;\r\nexport function makeVector(xyz: int3, w: int): int4;\r\nexport function makeVector(x: int, yzw: int3): int4;\r\n\r\nexport function makeVector(x: int, y: int, zw: int2): int4;\r\nexport function makeVector(xy: int2, z: int, w: int): int4;\r\nexport function makeVector(x: int, yz: int2, w: int): int4;\r\n\r\nexport function makeVector(xy: int2, zw: int2): int4;\r\n\r\nexport function makeVector(x: float, y: int, z: int, w: int): float4;\r\nexport function makeVector(x: int, y: float, z: int, w: int): float4;\r\nexport function makeVector(x: int, y: int, z: float, w: int): float4;\r\nexport function makeVector(x: int, y: int, z: int, w: float): float4;\r\nexport function makeVector(x: float, y: float, z: int, w: int): float4;\r\nexport function makeVector(x: float, y: int, z: float, w: int): float4;\r\nexport function makeVector(x: float, y: int, z: int, w: float): float4;\r\nexport function makeVector(x: int, y: float, z: float, w: int): float4;\r\nexport function makeVector(x: int, y: float, z: int, w: float): float4;\r\nexport function makeVector(x: int, y: int, z: float, w: float): float4;\r\nexport function makeVector(x: float, y: float, z: float, w: int): float4;\r\nexport function makeVector(x: float, y: float, z: int, w: float): float4;\r\nexport function makeVector(x: float, y: int, z: float, w: float): float4;\r\nexport function makeVector(x: int, y: float, z: float, w: float): float4;\r\nexport function makeVector(xyz: float3, w: float): float4;\r\nexport function makeVector(x: float, yzw: float3): float4;\r\nexport function makeVector(xyz: int3, w: float): float4;\r\nexport function makeVector(x: int, yzw: float3): float4;\r\nexport function makeVector(xyz: float3, w: int): float4;\r\nexport function makeVector(x: float, yzw: int3): float4;\r\nexport function makeVector(x: float, yz: float2, w: int): float4;\r\nexport function makeVector(x: float, yz: int2, w: float): float4;\r\nexport function makeVector(x: int, yz: float2, w: float): float4;\r\nexport function makeVector(x: float, y: float, zw: float2): float4;\r\nexport function makeVector(x: float, y: int, zw: float2): float4;\r\nexport function makeVector(x: float, y: int, zw: int2): float4;\r\nexport function makeVector(x: int, y: float, zw: float2): float4;\r\nexport function makeVector(x: int, y: float, zw: int2): float4;\r\nexport function makeVector(x: int, y: int, zw: float2): float4;\r\nexport function makeVector(x: float, y: float, z: float, w: float): float4;\r\nexport function makeVector(xy: float2, z: float, w: float): float4;\r\nexport function makeVector(x: float, yz: float2, w: float): float4;\r\nexport function makeVector(x: float, y: float, zw: float2): float4;\r\nexport function makeVector(xy: int2, z: float, w: float): float4;\r\nexport function makeVector(x: int, yz: float2, w: float): float4;\r\nexport function makeVector(x: int, y: float, zw: float2): float4;\r\nexport function makeVector(xy: float2, z: int, w: float): float4;\r\nexport function makeVector(x: float, yz: int2, w: float): float4;\r\nexport function makeVector(x: float, y: int, zw: float2): float4;\r\nexport function makeVector(xy: int2, z: float, w: int): float4;\r\nexport function makeVector(x: int, yz: float2, w: int): float4;\r\nexport function makeVector(x: int, y: float, zw: int2): float4;\r\nexport function makeVector(xy: float2, z: int, w: int): float4;\r\nexport function makeVector(x: float, yz: int2, w: int): float4;\r\nexport function makeVector(x: float, y: int, zw: int2): float4;\r\nexport function makeVector(xy: int2, z: int, w: float): float4;\r\nexport function makeVector(x: int, yz: int2, w: float): float4;\r\nexport function makeVector(x: int, y: int, zw: float2): float4;\r\nexport function makeVector(xy: int2, z: int, w: int): int4;\r\n/** @shadeup=univ()*/\r\nexport function makeVector() {\r\n let out = [];\r\n for (let i = 0; i < arguments.length; i++) {\r\n let a = arguments[i];\r\n if (typeof a === 'number') {\r\n out.push(a);\r\n } else {\r\n for (let j = 0; j < a.length; j++) {\r\n out.push(a[j]);\r\n }\r\n }\r\n }\r\n return out;\r\n\r\n throw new Error('Invalid vector length');\r\n}\r\n\r\n// add('test', int(1));\r\n\r\ntype swizChar = 'x' | 'y' | 'z' | 'w' | 'r' | 'g' | 'b' | 'a';\r\ntype swizStr4 = `${swizChar}${swizChar}${swizChar}${swizChar}`;\r\ntype swizStr3 = `${swizChar}${swizChar}${swizChar}`;\r\ntype swizStr2 = `${swizChar}${swizChar}`;\r\ntype swizStr1 = `${swizChar}`;\r\ntype swizStr4Ord = `xyzw` | `rgba` | `xxxx` | `rrrr`;\r\ntype swizStr3Ord = `xyz` | `rgb` | `xxx` | `rrr`;\r\ntype swizStr2Ord = `xy` | `rg` | `xx` | `rr`;\r\ntype swizStr1Ord = `x` | `r`;\r\n\r\nconst swizIndex: { [key: string]: number } = {\r\n x: 0,\r\n y: 1,\r\n z: 2,\r\n w: 3,\r\n r: 0,\r\n g: 1,\r\n b: 2,\r\n a: 3\r\n};\r\n\r\nconst getSwizIndexFast = (swiz: string) => {\r\n switch (swiz) {\r\n case 'x':\r\n return 0;\r\n case 'y':\r\n return 1;\r\n case 'z':\r\n return 2;\r\n case 'w':\r\n return 3;\r\n case 'r':\r\n return 0;\r\n case 'g':\r\n return 1;\r\n case 'b':\r\n return 2;\r\n case 'a':\r\n return 3;\r\n }\r\n};\r\n\r\n/** @shadeup=shader */\r\nexport function testDocComment() {\r\n return 1;\r\n}\r\n\r\n/** @shadeup=univ(~)*/\r\nexport function swizzle(v: T, swiz: S, assign?: T): int4;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): uint4;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): float4;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): int3;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): uint3;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): float3;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): int2;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): uint2;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): float2;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): int;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): uint;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: T): float;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: int4): int4;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: uint4\r\n): uint4;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: float4\r\n): float4;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: int3): int3;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: uint3\r\n): uint3;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: float3\r\n): float3;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: int2): int2;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: uint2\r\n): uint2;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: float2\r\n): float2;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: int): int;\r\n\r\nexport function swizzle(v: T, swiz: S, assign?: uint): uint;\r\n\r\nexport function swizzle(\r\n v: T,\r\n swiz: S,\r\n assign?: float\r\n): float;\r\n\r\nexport function swizzle(v: T, swiz: A, assign?: T): T[A];\r\n\r\nexport function swizzle(v: any, swiz: string, assign?: any) {\r\n if (typeof v === 'number') {\r\n if (swiz.length === 1) {\r\n return v;\r\n } else if (swiz.length === 2) {\r\n return [v, v];\r\n } else if (swiz.length === 3) {\r\n return [v, v, v];\r\n } else if (swiz.length === 4) {\r\n return [v, v, v, v];\r\n }\r\n } else if (Array.isArray(v)) {\r\n if (typeof assign !== 'undefined') {\r\n for (let i = 0; i < swiz.length; i++) {\r\n v[getSwizIndexFast(swiz[i])] = assign[i] ?? assign;\r\n }\r\n return v;\r\n }\r\n if (swiz.length === 1) {\r\n return v[getSwizIndexFast(swiz)];\r\n } else if (swiz.length === 2) {\r\n return [v[getSwizIndexFast(swiz[0])], v[getSwizIndexFast(swiz[1])]];\r\n } else if (swiz.length === 3) {\r\n return [\r\n v[getSwizIndexFast(swiz[0])],\r\n v[getSwizIndexFast(swiz[1])],\r\n v[getSwizIndexFast(swiz[2])]\r\n ];\r\n } else if (swiz.length === 4) {\r\n return [\r\n v[getSwizIndexFast(swiz[0])],\r\n v[getSwizIndexFast(swiz[1])],\r\n v[getSwizIndexFast(swiz[2])],\r\n v[getSwizIndexFast(swiz[3])]\r\n ];\r\n }\r\n } else {\r\n return (v as any)[swiz];\r\n }\r\n}\r\n\r\nexport function intifyVector(v: vector) {\r\n if (typeof v === 'number') {\r\n return v;\r\n } else if (Array.isArray(v)) {\r\n return v.map((v) => v | 0);\r\n } else {\r\n return v;\r\n }\r\n}\r\n\r\nimport { FM as FastMath } from './static-math';\r\nexport const FM = FastMath;\r\n\r\n// type f32 = number & { __float: never };\r\n// type i32 = number & { __int: never };\r\n// type num = f32 | i32;\r\n\r\n// function f32(a: number): f32 {\r\n// return a as f32;\r\n// }\r\n\r\n// function i32(a: number): i32 {\r\n// return a as i32;\r\n// }\r\n\r\n// type numeric2 =
(a: A, b: B) => (A extends f32 ? f32 : (B extends f32 ? f32 : i32));\r\n// type numeric3 = (a: A, b: B, c: C) => (A extends f32 ? f32 : (B extends f32 ? f32 : (C extends f32 ? f32 : i32)));\r\n\r\n// export const abc: numeric2 = (a, b, c) => a + b + c;\r\n\r\n// abc(f32(1), i32(2));\r\n\r\nexport class atomic_internal {\r\n private __type: T;\r\n private __value: number;\r\n constructor(value: T) {\r\n this.__value = value;\r\n }\r\n\r\n private $mutate?: (to: value) => void;\r\n\r\n /** @shadeup=univ(!atomicLoad(&$self$))*/\r\n load(): T {\r\n return this.__value as T;\r\n }\r\n /** @shadeup=univ(!atomicStore(&$self$, $0$))*/\r\n store(value: T): void {\r\n this.__value = value as any;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n }\r\n\r\n /** @shadeup=univ(!atomicAdd(&$self$, $0$))*/\r\n add(value: T): T {\r\n let old = this.__value;\r\n this.__value += value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicSub(&$self$, $0$))*/\r\n sub(value: T): T {\r\n let old = this.__value;\r\n this.__value -= value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicMax(&$self$, $0$))*/\r\n max(value: T): T {\r\n let old = this.__value;\r\n this.__value = Math.max(value, this.__value);\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicMin(&$self$, $0$))*/\r\n min(value: T): T {\r\n let old = this.__value;\r\n this.__value = Math.min(value, this.__value);\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicAnd(&$self$, $0$))*/\r\n and(value: T): T {\r\n let old = this.__value;\r\n this.__value = value & this.__value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicOr(&$self$, $0$))*/\r\n or(value: T): T {\r\n let old = this.__value;\r\n this.__value = value | this.__value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicXor(&$self$, $0$))*/\r\n xor(value: T): T {\r\n let old = this.__value;\r\n this.__value = value ^ this.__value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicExchange(&$self$, $0$))*/\r\n exchange(value: T): T {\r\n let old = this.__value;\r\n this.__value = value;\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return old as T;\r\n }\r\n /** @shadeup=univ(!atomicCompareExchangeWeak(&$self$, $0$, $1$))*/\r\n compareExchangeWeak(compare: T, value: T): __atomic_compare_exchange_result {\r\n let old = this.__value;\r\n if (old == compare) {\r\n this.__value = value;\r\n }\r\n if (this.$mutate) this.$mutate(this.__value);\r\n return {\r\n old_value: old as T,\r\n exchanged: old == compare\r\n };\r\n }\r\n}\r\n\r\nexport type __atomic_compare_exchange_result = {\r\n old_value: T;\r\n exchanged: boolean;\r\n};\r\n\r\nexport type atomic = atomic_internal;\r\n\r\nexport function atomic(value: T): atomic {\r\n return new atomic_internal(value);\r\n}\r\n\r\n(window as any).makeAtomic = atomic;\r\n\r\n/**\r\n * Executes a control barrier synchronization function that affects memory and atomic operations in the workgroup address space.\r\n *\r\n * See: https://www.w3.org/TR/WGSL/#workgroupBarrier-builtin\r\n *\r\n * @shadeup=univ(!workgroupBarrier())\r\n */\r\nexport function workgroupBarrier() {}\r\n\r\n/**\r\n * Executes a storage barrier synchronization function that affects memory and atomic operations in the workgroup address space.\r\n *\r\n * See: https://www.w3.org/TR/WGSL/#storageBarrier-builtin\r\n *\r\n * @shadeup=univ(!storageBarrier())\r\n */\r\nexport function storageBarrier() {}\r\n\r\n/**\r\n * See: https://www.w3.org/TR/WGSL/#workgroupUniformLoad-builtin\r\n *\r\n * @shadeup=univ(!workgroupUniformLoad(&$0$))\r\n */\r\nexport function workgroupUniformLoad(p: T): T {\r\n return p;\r\n}\r\n\r\n/**\r\n * Discards the current fragment.\r\n *\r\n * A discard statement converts the invocation into a helper invocation and throws away the fragment. The discard statement must only be used in a fragment shader stage.\r\n *\r\n * See: https://www.w3.org/TR/WGSL/#discard-statement\r\n *\r\n * @shadeup=univ(!discard;)\r\n */\r\nexport function discard() {}\r\n\r\n/**\r\n * Returns the derivative of the input value with respect to the window-space x coordinate.\r\n * @param value - The input value.\r\n * @returns The derivative of the input value with respect to the window-space x coordinate.\r\n * @shadeup=glsl(!dFdx($0$))\r\n * @shadeup=wgsl(!dpdx($0$))\r\n */\r\nexport function ddx(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * Returns the derivative of the input value with respect to the window-space y coordinate.\r\n * @param value - The input value.\r\n *\r\n * @returns The derivative of the input value with respect to the window-space y coordinate.\r\n * @shadeup=glsl(!dFdy($0$))\r\n * @shadeup=wgsl(!dpdy($0$))\r\n */\r\nexport function ddy(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!dFdxFine($0$))\r\n * @shadeup=wgsl(!dpdxFine($0$))\r\n */\r\nexport function ddxFine(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!dFdyFine($0$))\r\n * @shadeup=wgsl(!dpdyFine($0$))\r\n */\r\nexport function ddyFine(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!dFdxCoarse($0$))\r\n * @shadeup=wgsl(!dpdxCoarse($0$))\r\n */\r\nexport function ddxCoarse(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!dFdyCoarse($0$))\r\n * @shadeup=wgsl(!dpdyCoarse($0$))\r\n */\r\nexport function ddyCoarse(value: T): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!bitcast<$[0]$>($0$))\r\n */\r\nexport function bitcast(value: scalar): T {\r\n return 0 as T;\r\n}\r\n\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack4x8snorm($0$))\r\n */\r\nexport function pack4x8snorm(value: float4): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack4x8unorm($0$))\r\n */\r\nexport function pack4x8unorm(value: float4): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack2x16snorm($0$))\r\n */\r\nexport function pack2x16snorm(value: float2): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack2x16unorm($0$))\r\n */\r\nexport function pack2x16unorm(value: float2): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!pack2x16float($0$))\r\n */\r\nexport function pack2x16float(value: float2): uint {\r\n return uint(0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack4x8snorm($0$))\r\n */\r\nexport function unpack4x8snorm(value: uint): float4 {\r\n return float4(0, 0, 0, 0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack4x8unorm($0$))\r\n */\r\nexport function unpack4x8unorm(value: uint): float4 {\r\n return float4(0, 0, 0, 0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack2x16snorm($0$))\r\n */\r\nexport function unpack2x16snorm(value: uint): float2 {\r\n return float2(0, 0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack2x16unorm($0$))\r\n */\r\nexport function unpack2x16unorm(value: uint): float2 {\r\n return float2(0, 0);\r\n}\r\n/**\r\n * @shadeup=glsl(!$0$)\r\n * @shadeup=wgsl(!unpack2x16float($0$))\r\n */\r\nexport function unpack2x16float(value: uint): float2 {\r\n return float2(0, 0);\r\n}\r\n"; const stdStaticMath = "\n///\n/// GENERATED\n/// DO NOT EDIT THIS FILE\n/// see generate-static-math.ts\n///\nexport const FM = {\n add_1_1(a: number, b: number): number { return a + b; },\n add_2_1(a: [number, number], b: number): [number, number] { return [a[0] + b, a[1] + b]; },\n add_1_2(a: number, b: [number, number]): [number, number] { return [a + b[0], a + b[1]]; },\n add_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] + b[0], a[1] + b[1]]; },\n add_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] + b, a[1] + b, a[2] + b]; },\n add_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a + b[0], a + b[1], a + b[2]]; },\n add_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; },\n add_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] + b, a[1] + b, a[2] + b, a[3] + b]; },\n add_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a + b[0], a + b[1], a + b[2], a + b[3]]; },\n add_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]]; },\n sub_1_1(a: number, b: number): number { return a - b; },\n sub_2_1(a: [number, number], b: number): [number, number] { return [a[0] - b, a[1] - b]; },\n sub_1_2(a: number, b: [number, number]): [number, number] { return [a - b[0], a - b[1]]; },\n sub_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] - b[0], a[1] - b[1]]; },\n sub_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] - b, a[1] - b, a[2] - b]; },\n sub_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a - b[0], a - b[1], a - b[2]]; },\n sub_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; },\n sub_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] - b, a[1] - b, a[2] - b, a[3] - b]; },\n sub_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a - b[0], a - b[1], a - b[2], a - b[3]]; },\n sub_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]]; },\n div_1_1(a: number, b: number): number { return a / b; },\n div_2_1(a: [number, number], b: number): [number, number] { return [a[0] / b, a[1] / b]; },\n div_1_2(a: number, b: [number, number]): [number, number] { return [a / b[0], a / b[1]]; },\n div_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] / b[0], a[1] / b[1]]; },\n div_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] / b, a[1] / b, a[2] / b]; },\n div_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a / b[0], a / b[1], a / b[2]]; },\n div_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] / b[0], a[1] / b[1], a[2] / b[2]]; },\n div_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] / b, a[1] / b, a[2] / b, a[3] / b]; },\n div_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a / b[0], a / b[1], a / b[2], a / b[3]]; },\n div_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]]; },\n mul_1_1(a: number, b: number): number { return a * b; },\n mul_2_1(a: [number, number], b: number): [number, number] { return [a[0] * b, a[1] * b]; },\n mul_1_2(a: number, b: [number, number]): [number, number] { return [a * b[0], a * b[1]]; },\n mul_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] * b[0], a[1] * b[1]]; },\n mul_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] * b, a[1] * b, a[2] * b]; },\n mul_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a * b[0], a * b[1], a * b[2]]; },\n mul_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] * b[0], a[1] * b[1], a[2] * b[2]]; },\n mul_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] * b, a[1] * b, a[2] * b, a[3] * b]; },\n mul_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a * b[0], a * b[1], a * b[2], a * b[3]]; },\n mul_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]]; },\n mod_1_1(a: number, b: number): number { return a % b; },\n mod_2_1(a: [number, number], b: number): [number, number] { return [a[0] % b, a[1] % b]; },\n mod_1_2(a: number, b: [number, number]): [number, number] { return [a % b[0], a % b[1]]; },\n mod_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] % b[0], a[1] % b[1]]; },\n mod_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] % b, a[1] % b, a[2] % b]; },\n mod_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a % b[0], a % b[1], a % b[2]]; },\n mod_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] % b[0], a[1] % b[1], a[2] % b[2]]; },\n mod_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] % b, a[1] % b, a[2] % b, a[3] % b]; },\n mod_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a % b[0], a % b[1], a % b[2], a % b[3]]; },\n mod_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] % b[0], a[1] % b[1], a[2] % b[2], a[3] % b[3]]; },\n bitand_1_1(a: number, b: number): number { return a & b; },\n bitand_2_1(a: [number, number], b: number): [number, number] { return [a[0] & b, a[1] & b]; },\n bitand_1_2(a: number, b: [number, number]): [number, number] { return [a & b[0], a & b[1]]; },\n bitand_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] & b[0], a[1] & b[1]]; },\n bitand_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] & b, a[1] & b, a[2] & b]; },\n bitand_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a & b[0], a & b[1], a & b[2]]; },\n bitand_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] & b[0], a[1] & b[1], a[2] & b[2]]; },\n bitand_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] & b, a[1] & b, a[2] & b, a[3] & b]; },\n bitand_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a & b[0], a & b[1], a & b[2], a & b[3]]; },\n bitand_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] & b[0], a[1] & b[1], a[2] & b[2], a[3] & b[3]]; },\n bitor_1_1(a: number, b: number): number { return a | b; },\n bitor_2_1(a: [number, number], b: number): [number, number] { return [a[0] | b, a[1] | b]; },\n bitor_1_2(a: number, b: [number, number]): [number, number] { return [a | b[0], a | b[1]]; },\n bitor_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] | b[0], a[1] | b[1]]; },\n bitor_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] | b, a[1] | b, a[2] | b]; },\n bitor_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a | b[0], a | b[1], a | b[2]]; },\n bitor_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] | b[0], a[1] | b[1], a[2] | b[2]]; },\n bitor_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] | b, a[1] | b, a[2] | b, a[3] | b]; },\n bitor_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a | b[0], a | b[1], a | b[2], a | b[3]]; },\n bitor_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] | b[0], a[1] | b[1], a[2] | b[2], a[3] | b[3]]; },\n bitxor_1_1(a: number, b: number): number { return a ^ b; },\n bitxor_2_1(a: [number, number], b: number): [number, number] { return [a[0] ^ b, a[1] ^ b]; },\n bitxor_1_2(a: number, b: [number, number]): [number, number] { return [a ^ b[0], a ^ b[1]]; },\n bitxor_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] ^ b[0], a[1] ^ b[1]]; },\n bitxor_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] ^ b, a[1] ^ b, a[2] ^ b]; },\n bitxor_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a ^ b[0], a ^ b[1], a ^ b[2]]; },\n bitxor_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2]]; },\n bitxor_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] ^ b, a[1] ^ b, a[2] ^ b, a[3] ^ b]; },\n bitxor_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a ^ b[0], a ^ b[1], a ^ b[2], a ^ b[3]]; },\n bitxor_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]; },\n lshift_1_1(a: number, b: number): number { return a << b; },\n lshift_2_1(a: [number, number], b: number): [number, number] { return [a[0] << b, a[1] << b]; },\n lshift_1_2(a: number, b: [number, number]): [number, number] { return [a << b[0], a << b[1]]; },\n lshift_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] << b[0], a[1] << b[1]]; },\n lshift_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] << b, a[1] << b, a[2] << b]; },\n lshift_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a << b[0], a << b[1], a << b[2]]; },\n lshift_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] << b[0], a[1] << b[1], a[2] << b[2]]; },\n lshift_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] << b, a[1] << b, a[2] << b, a[3] << b]; },\n lshift_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a << b[0], a << b[1], a << b[2], a << b[3]]; },\n lshift_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] << b[0], a[1] << b[1], a[2] << b[2], a[3] << b[3]]; },\n rshift_1_1(a: number, b: number): number { return a >> b; },\n rshift_2_1(a: [number, number], b: number): [number, number] { return [a[0] >> b, a[1] >> b]; },\n rshift_1_2(a: number, b: [number, number]): [number, number] { return [a >> b[0], a >> b[1]]; },\n rshift_2_2(a: [number, number], b: [number, number]): [number, number] { return [a[0] >> b[0], a[1] >> b[1]]; },\n rshift_3_1(a: [number, number, number], b: number): [number, number, number] { return [a[0] >> b, a[1] >> b, a[2] >> b]; },\n rshift_1_3(a: number, b: [number, number, number]): [number, number, number] { return [a >> b[0], a >> b[1], a >> b[2]]; },\n rshift_3_3(a: [number, number, number], b: [number, number, number]): [number, number, number] { return [a[0] >> b[0], a[1] >> b[1], a[2] >> b[2]]; },\n rshift_4_1(a: [number, number, number, number], b: number): [number, number, number, number] { return [a[0] >> b, a[1] >> b, a[2] >> b, a[3] >> b]; },\n rshift_1_4(a: number, b: [number, number, number, number]): [number, number, number, number] { return [a >> b[0], a >> b[1], a >> b[2], a >> b[3]]; },\n rshift_4_4(a: [number, number, number, number], b: [number, number, number, number]): [number, number, number, number] { return [a[0] >> b[0], a[1] >> b[1], a[2] >> b[2], a[3] >> b[3]]; },\n bitnot_1(a: number): number { return ~a; },\n bitnot_2(a: [number, number]): [number, number] { return [~a[0], ~a[1]]; },\n bitnot_3(a: [number, number, number]): [number, number, number] { return [~a[0], ~a[1], ~a[2]]; },\n bitnot_4(a: [number, number, number, number]): [number, number, number, number] { return [~a[0], ~a[1], ~a[2], ~a[3]]; },\n negate_1(a: number): number { return -a; },\n negate_2(a: [number, number]): [number, number] { return [-a[0], -a[1]]; },\n negate_3(a: [number, number, number]): [number, number, number] { return [-a[0], -a[1], -a[2]]; },\n negate_4(a: [number, number, number, number]): [number, number, number, number] { return [-a[0], -a[1], -a[2], -a[3]]; },\n positive_1(a: number): number { return Math.abs(a); },\n positive_2(a: [number, number]): [number, number] { return [Math.abs(a[0]), Math.abs(a[1])]; },\n positive_3(a: [number, number, number]): [number, number, number] { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])]; },\n positive_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2]), Math.abs(a[3])]; },\n abs_1(a: number): number { return Math.abs(a); },\n abs_2(a: [number, number]): [number, number] { return [Math.abs(a[0]), Math.abs(a[1])]; },\n abs_3(a: [number, number, number]): [number, number, number] { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])]; },\n abs_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2]), Math.abs(a[3])]; },\n floor_1(a: number): number { return Math.floor(a); },\n floor_2(a: [number, number]): [number, number] { return [Math.floor(a[0]), Math.floor(a[1])]; },\n floor_3(a: [number, number, number]): [number, number, number] { return [Math.floor(a[0]), Math.floor(a[1]), Math.floor(a[2])]; },\n floor_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.floor(a[0]), Math.floor(a[1]), Math.floor(a[2]), Math.floor(a[3])]; },\n ceil_1(a: number): number { return Math.ceil(a); },\n ceil_2(a: [number, number]): [number, number] { return [Math.ceil(a[0]), Math.ceil(a[1])]; },\n ceil_3(a: [number, number, number]): [number, number, number] { return [Math.ceil(a[0]), Math.ceil(a[1]), Math.ceil(a[2])]; },\n ceil_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.ceil(a[0]), Math.ceil(a[1]), Math.ceil(a[2]), Math.ceil(a[3])]; },\n round_1(a: number): number { return Math.round(a); },\n round_2(a: [number, number]): [number, number] { return [Math.round(a[0]), Math.round(a[1])]; },\n round_3(a: [number, number, number]): [number, number, number] { return [Math.round(a[0]), Math.round(a[1]), Math.round(a[2])]; },\n round_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.round(a[0]), Math.round(a[1]), Math.round(a[2]), Math.round(a[3])]; },\n sign_1(a: number): number { return Math.sign(a); },\n sign_2(a: [number, number]): [number, number] { return [Math.sign(a[0]), Math.sign(a[1])]; },\n sign_3(a: [number, number, number]): [number, number, number] { return [Math.sign(a[0]), Math.sign(a[1]), Math.sign(a[2])]; },\n sign_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.sign(a[0]), Math.sign(a[1]), Math.sign(a[2]), Math.sign(a[3])]; },\n cos_1(a: number): number { return Math.cos(a); },\n cos_2(a: [number, number]): [number, number] { return [Math.cos(a[0]), Math.cos(a[1])]; },\n cos_3(a: [number, number, number]): [number, number, number] { return [Math.cos(a[0]), Math.cos(a[1]), Math.cos(a[2])]; },\n cos_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.cos(a[0]), Math.cos(a[1]), Math.cos(a[2]), Math.cos(a[3])]; },\n sin_1(a: number): number { return Math.sin(a); },\n sin_2(a: [number, number]): [number, number] { return [Math.sin(a[0]), Math.sin(a[1])]; },\n sin_3(a: [number, number, number]): [number, number, number] { return [Math.sin(a[0]), Math.sin(a[1]), Math.sin(a[2])]; },\n sin_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.sin(a[0]), Math.sin(a[1]), Math.sin(a[2]), Math.sin(a[3])]; },\n tan_1(a: number): number { return Math.tan(a); },\n tan_2(a: [number, number]): [number, number] { return [Math.tan(a[0]), Math.tan(a[1])]; },\n tan_3(a: [number, number, number]): [number, number, number] { return [Math.tan(a[0]), Math.tan(a[1]), Math.tan(a[2])]; },\n tan_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.tan(a[0]), Math.tan(a[1]), Math.tan(a[2]), Math.tan(a[3])]; },\n acos_1(a: number): number { return Math.acos(a); },\n acos_2(a: [number, number]): [number, number] { return [Math.acos(a[0]), Math.acos(a[1])]; },\n acos_3(a: [number, number, number]): [number, number, number] { return [Math.acos(a[0]), Math.acos(a[1]), Math.acos(a[2])]; },\n acos_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.acos(a[0]), Math.acos(a[1]), Math.acos(a[2]), Math.acos(a[3])]; },\n asin_1(a: number): number { return Math.asin(a); },\n asin_2(a: [number, number]): [number, number] { return [Math.asin(a[0]), Math.asin(a[1])]; },\n asin_3(a: [number, number, number]): [number, number, number] { return [Math.asin(a[0]), Math.asin(a[1]), Math.asin(a[2])]; },\n asin_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.asin(a[0]), Math.asin(a[1]), Math.asin(a[2]), Math.asin(a[3])]; },\n atan_1(a: number): number { return Math.atan(a); },\n atan_2(a: [number, number]): [number, number] { return [Math.atan(a[0]), Math.atan(a[1])]; },\n atan_3(a: [number, number, number]): [number, number, number] { return [Math.atan(a[0]), Math.atan(a[1]), Math.atan(a[2])]; },\n atan_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.atan(a[0]), Math.atan(a[1]), Math.atan(a[2]), Math.atan(a[3])]; },\n cosh_1(a: number): number { return Math.cosh(a); },\n cosh_2(a: [number, number]): [number, number] { return [Math.cosh(a[0]), Math.cosh(a[1])]; },\n cosh_3(a: [number, number, number]): [number, number, number] { return [Math.cosh(a[0]), Math.cosh(a[1]), Math.cosh(a[2])]; },\n cosh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.cosh(a[0]), Math.cosh(a[1]), Math.cosh(a[2]), Math.cosh(a[3])]; },\n sinh_1(a: number): number { return Math.sinh(a); },\n sinh_2(a: [number, number]): [number, number] { return [Math.sinh(a[0]), Math.sinh(a[1])]; },\n sinh_3(a: [number, number, number]): [number, number, number] { return [Math.sinh(a[0]), Math.sinh(a[1]), Math.sinh(a[2])]; },\n sinh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.sinh(a[0]), Math.sinh(a[1]), Math.sinh(a[2]), Math.sinh(a[3])]; },\n tanh_1(a: number): number { return Math.tanh(a); },\n tanh_2(a: [number, number]): [number, number] { return [Math.tanh(a[0]), Math.tanh(a[1])]; },\n tanh_3(a: [number, number, number]): [number, number, number] { return [Math.tanh(a[0]), Math.tanh(a[1]), Math.tanh(a[2])]; },\n tanh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.tanh(a[0]), Math.tanh(a[1]), Math.tanh(a[2]), Math.tanh(a[3])]; },\n acosh_1(a: number): number { return Math.acosh(a); },\n acosh_2(a: [number, number]): [number, number] { return [Math.acosh(a[0]), Math.acosh(a[1])]; },\n acosh_3(a: [number, number, number]): [number, number, number] { return [Math.acosh(a[0]), Math.acosh(a[1]), Math.acosh(a[2])]; },\n acosh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.acosh(a[0]), Math.acosh(a[1]), Math.acosh(a[2]), Math.acosh(a[3])]; },\n asinh_1(a: number): number { return Math.asinh(a); },\n asinh_2(a: [number, number]): [number, number] { return [Math.asinh(a[0]), Math.asinh(a[1])]; },\n asinh_3(a: [number, number, number]): [number, number, number] { return [Math.asinh(a[0]), Math.asinh(a[1]), Math.asinh(a[2])]; },\n asinh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.asinh(a[0]), Math.asinh(a[1]), Math.asinh(a[2]), Math.asinh(a[3])]; },\n atanh_1(a: number): number { return Math.atanh(a); },\n atanh_2(a: [number, number]): [number, number] { return [Math.atanh(a[0]), Math.atanh(a[1])]; },\n atanh_3(a: [number, number, number]): [number, number, number] { return [Math.atanh(a[0]), Math.atanh(a[1]), Math.atanh(a[2])]; },\n atanh_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.atanh(a[0]), Math.atanh(a[1]), Math.atanh(a[2]), Math.atanh(a[3])]; },\n exp_1(a: number): number { return Math.exp(a); },\n exp_2(a: [number, number]): [number, number] { return [Math.exp(a[0]), Math.exp(a[1])]; },\n exp_3(a: [number, number, number]): [number, number, number] { return [Math.exp(a[0]), Math.exp(a[1]), Math.exp(a[2])]; },\n exp_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.exp(a[0]), Math.exp(a[1]), Math.exp(a[2]), Math.exp(a[3])]; },\n log_1(a: number): number { return Math.log(a); },\n log_2(a: [number, number]): [number, number] { return [Math.log(a[0]), Math.log(a[1])]; },\n log_3(a: [number, number, number]): [number, number, number] { return [Math.log(a[0]), Math.log(a[1]), Math.log(a[2])]; },\n log_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.log(a[0]), Math.log(a[1]), Math.log(a[2]), Math.log(a[3])]; },\n log2_1(a: number): number { return Math.log2(a); },\n log2_2(a: [number, number]): [number, number] { return [Math.log2(a[0]), Math.log2(a[1])]; },\n log2_3(a: [number, number, number]): [number, number, number] { return [Math.log2(a[0]), Math.log2(a[1]), Math.log2(a[2])]; },\n log2_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.log2(a[0]), Math.log2(a[1]), Math.log2(a[2]), Math.log2(a[3])]; },\n log10_1(a: number): number { return Math.log10(a); },\n log10_2(a: [number, number]): [number, number] { return [Math.log10(a[0]), Math.log10(a[1])]; },\n log10_3(a: [number, number, number]): [number, number, number] { return [Math.log10(a[0]), Math.log10(a[1]), Math.log10(a[2])]; },\n log10_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.log10(a[0]), Math.log10(a[1]), Math.log10(a[2]), Math.log10(a[3])]; },\n sqrt_1(a: number): number { return Math.sqrt(a); },\n sqrt_2(a: [number, number]): [number, number] { return [Math.sqrt(a[0]), Math.sqrt(a[1])]; },\n sqrt_3(a: [number, number, number]): [number, number, number] { return [Math.sqrt(a[0]), Math.sqrt(a[1]), Math.sqrt(a[2])]; },\n sqrt_4(a: [number, number, number, number]): [number, number, number, number] { return [Math.sqrt(a[0]), Math.sqrt(a[1]), Math.sqrt(a[2]), Math.sqrt(a[3])]; },\n int_2_1_1(a: number, b: number): [number, number] { return [a|0, b|0]; },\n int_2_2(a: [number, number]): [number, number] { return [a[0]|0, a[1]|0]; },\n int_3_1_1_1(a: number, b: number, c: number): [number, number, number] { return [a|0, b|0, c|0]; },\n int_3_2_1(a: [number, number], b: number): [number, number, number] { return [a[0]|0, a[1]|0, b|0]; },\n int_3_1_2(a: number, b: [number, number]): [number, number, number] { return [a|0, b[0]|0, b[1]|0]; },\n int_3_3(a: [number, number, number]): [number, number, number] { return [a[0]|0, a[1]|0, a[2]|0]; },\n int_4_1_1_1_1(a: number, b: number, c: number, d: number): [number, number, number, number] { return [a|0, b|0, c|0, d|0]; },\n int_4_2_1_1(a: [number, number], b: number, c: number): [number, number, number, number] { return [a[0]|0, a[1]|0, b|0, c|0]; },\n int_4_1_2_1(a: number, b: [number, number], c: number): [number, number, number, number] { return [a|0, b[0]|0, b[1]|0, c|0]; },\n int_4_1_1_2(a: number, b: number, c: [number, number]): [number, number, number, number] { return [a|0, b|0, c[0]|0, c[1]|0]; },\n int_4_3_1(a: [number, number, number], b: number): [number, number, number, number] { return [a[0]|0, a[1]|0, a[2]|0, b|0]; },\n int_4_1_3(a: number, b: [number, number, number]): [number, number, number, number] { return [a|0, b[0]|0, b[1]|0, b[2]|0]; },\n int_4_2_2(a: [number, number], b: [number, number]): [number, number, number, number] { return [a[0]|0, a[1]|0, b[0]|0, b[1]|0]; },\n int_4_4(a: [number, number, number, number]): [number, number, number, number] { return [a[0]|0, a[1]|0, a[2]|0, a[3]|0]; },\n float_2_1_1(a: number, b: number): [number, number] { return [a, b]; },\n float_2_2(a: [number, number]): [number, number] { return [a[0], a[1]]; },\n float_3_1_1_1(a: number, b: number, c: number): [number, number, number] { return [a, b, c]; },\n float_3_2_1(a: [number, number], b: number): [number, number, number] { return [a[0], a[1], b]; },\n float_3_1_2(a: number, b: [number, number]): [number, number, number] { return [a, b[0], b[1]]; },\n float_3_3(a: [number, number, number]): [number, number, number] { return [a[0], a[1], a[2]]; },\n float_4_1_1_1_1(a: number, b: number, c: number, d: number): [number, number, number, number] { return [a, b, c, d]; },\n float_4_2_1_1(a: [number, number], b: number, c: number): [number, number, number, number] { return [a[0], a[1], b, c]; },\n float_4_1_2_1(a: number, b: [number, number], c: number): [number, number, number, number] { return [a, b[0], b[1], c]; },\n float_4_1_1_2(a: number, b: number, c: [number, number]): [number, number, number, number] { return [a, b, c[0], c[1]]; },\n float_4_3_1(a: [number, number, number], b: number): [number, number, number, number] { return [a[0], a[1], a[2], b]; },\n float_4_1_3(a: number, b: [number, number, number]): [number, number, number, number] { return [a, b[0], b[1], b[2]]; },\n float_4_2_2(a: [number, number], b: [number, number]): [number, number, number, number] { return [a[0], a[1], b[0], b[1]]; },\n float_4_4(a: [number, number, number, number]): [number, number, number, number] { return [a[0], a[1], a[2], a[3]]; },\n uint_2_1_1(a: number, b: number): [number, number] { return [a>>>0, b>>>0]; },\n uint_2_2(a: [number, number]): [number, number] { return [a[0]>>>0, a[1]>>>0]; },\n uint_3_1_1_1(a: number, b: number, c: number): [number, number, number] { return [a>>>0, b>>>0, c>>>0]; },\n uint_3_2_1(a: [number, number], b: number): [number, number, number] { return [a[0]>>>0, a[1]>>>0, b>>>0]; },\n uint_3_1_2(a: number, b: [number, number]): [number, number, number] { return [a>>>0, b[0]>>>0, b[1]>>>0]; },\n uint_3_3(a: [number, number, number]): [number, number, number] { return [a[0]>>>0, a[1]>>>0, a[2]>>>0]; },\n uint_4_1_1_1_1(a: number, b: number, c: number, d: number): [number, number, number, number] { return [a>>>0, b>>>0, c>>>0, d>>>0]; },\n uint_4_2_1_1(a: [number, number], b: number, c: number): [number, number, number, number] { return [a[0]>>>0, a[1]>>>0, b>>>0, c>>>0]; },\n uint_4_1_2_1(a: number, b: [number, number], c: number): [number, number, number, number] { return [a>>>0, b[0]>>>0, b[1]>>>0, c>>>0]; },\n uint_4_1_1_2(a: number, b: number, c: [number, number]): [number, number, number, number] { return [a>>>0, b>>>0, c[0]>>>0, c[1]>>>0]; },\n uint_4_3_1(a: [number, number, number], b: number): [number, number, number, number] { return [a[0]>>>0, a[1]>>>0, a[2]>>>0, b>>>0]; },\n uint_4_1_3(a: number, b: [number, number, number]): [number, number, number, number] { return [a>>>0, b[0]>>>0, b[1]>>>0, b[2]>>>0]; },\n uint_4_2_2(a: [number, number], b: [number, number]): [number, number, number, number] { return [a[0]>>>0, a[1]>>>0, b[0]>>>0, b[1]>>>0]; },\n uint_4_4(a: [number, number, number, number]): [number, number, number, number] { return [a[0]>>>0, a[1]>>>0, a[2]>>>0, a[3]>>>0]; },\n}\n"; const stdAll = `/**__SHADEUP_STRUCT_INJECTION_HOOK__*/\r export const __dummy = 1;\r \r import {\r bool,\r float,\r float2,\r float3,\r float4,\r int,\r int2,\r int3,\r int4,\r uint,\r uint3,\r atomic\r } from '/std_math';\r // import { Mesh } from '/_std/mesh';\r \r export class Mesh {\r private vertices: float3[] = [];\r private triangles: int[] = [];\r private normals: float3[] = [];\r private tangents: float3[] = [];\r private bitangents: float3[] = [];\r private uvs: float2[] = [];\r private colors: float4[] = [];\r symbol: Symbol;\r \r constructor(prefils: {\r vertices?: float3[];\r triangles?: int[];\r normals?: float3[];\r tangents?: float3[];\r bitangents?: float3[];\r uvs?: float2[];\r colors?: float4[];\r }) {\r this.symbol = Symbol();\r if (prefils.vertices) this.vertices = prefils.vertices;\r if (prefils.triangles) this.triangles = prefils.triangles;\r if (prefils.normals) this.normals = prefils.normals;\r if (prefils.tangents) this.tangents = prefils.tangents;\r if (prefils.bitangents) this.bitangents = prefils.bitangents;\r if (prefils.uvs) this.uvs = prefils.uvs;\r if (prefils.colors) this.colors = prefils.colors;\r }\r \r getVertices() {\r return this.vertices;\r }\r \r getTriangles() {\r return this.triangles;\r }\r \r getNormals() {\r return this.normals;\r }\r \r getTangents() {\r return this.tangents;\r }\r \r getBitangents() {\r return this.bitangents;\r }\r \r getUVs() {\r return this.uvs;\r }\r \r getColors() {\r return this.colors;\r }\r }\r \r declare global {\r const localEngineContext: any;\r }\r \r export const getShadeupLocalContext = (): any => {\r if (typeof localEngineContext !== 'undefined') {\r return localEngineContext;\r } else {\r return window;\r }\r };\r \r /**\r * Prints a set of value(s) to the console. Values will be converted to strings before printing.\r *\r * @param args Any number of values to print to the console\r */\r export function print(...args: any[]) {\r console.log(...args);\r if (typeof getShadeupLocalContext()['__shadeup_print'] === 'function') {\r getShadeupLocalContext()['__shadeup_print'](...args);\r }\r }\r \r /**\r * Flushes (executes) all queued compute or draw calls\r * @shadeup=tag(async) @shadeup=noemit_gpu\r */\r export async function flush() {\r if (typeof getShadeupLocalContext()['flushAdapter'] === 'function') {\r return await getShadeupLocalContext()['flushAdapter']();\r }\r }\r \r /**\r * Displays a single value in the stats panel at the top right\r *\r * @param name key for this stat (e.g. "fps")\r * @param value any value\r */\r export function stat(name: string, value: any) {\r if (typeof getShadeupLocalContext()['__shadeup_stat'] === 'function') {\r getShadeupLocalContext()['__shadeup_stat'](name, value);\r }\r }\r \r /**\r * Display a graph of a numeric value over time\r *\r * @param name key for this stat (e.g. "fps")\r * @param value any numeric value\r * @param sampleRate how often should the graph be updated (e.g. 1 = every call, 2 = every second call, etc.)\r */\r export function statGraph(name: string, value: float, sampleRate: int = 1) {\r if (typeof getShadeupLocalContext()['__shadeup_statGraph'] === 'function') {\r getShadeupLocalContext()['__shadeup_statGraph'](name, value);\r }\r }\r \r // type InferPayload1 = {\r // data: [T];\r // callback: (a: { attachment0: T }) => void;\r // };\r \r // type InferPayload2 = {\r // data: [T, I];\r // callback: (a: { attachment0: T; attachment1: I }) => void;\r // };\r \r // function infer(payload: InferPayload1 | InferPayload2);\r // function infer(a: any) {}\r \r // infer({\r // data: [67],\r // callback: (a) => {\r // a[0];\r // }\r // });\r \r type FnPass = (a: T) => void;\r \r function infer(fn: (a: I, b: O) => void): shader {\r return fn as shader;\r }\r \r // export function drawAlt(keys: shader) {}\r // export function draw(fullScreenPixelShader: shader): void;\r // export function draw(\r // first: Mesh | any | shader,\r // second?: shader,\r // third?: shader\r // ) {\r // if ('vertices' in first && second && third) {\r // __shadeup_dispatch_draw_geometry(first, second, third);\r // } else if (first && !second && !third) {\r // __shadeup_dispatch_draw(first as shader);\r // }\r // }\r \r // draw(makeShader('', (a, b) => {}));\r // drawAlt(\r // makeShader(\r // '000004808000091289258019303699031390005438610',\r // /**@shadeup=shader*/ (__in, __out) => {\r // __out.color;\r // }\r // )\r // );\r // /**\r // *\r // */\r export function compute(workgroups: int3, computeShader: shader) {\r getShadeupLocalContext().__shadeup_dispatch_compute(workgroups, computeShader);\r }\r \r // function draww(s: shader<{ abc: 123 }, { test: 123 }>) {}\r \r // type x = { x: T };\r \r // function makeTex(a: T): x {\r // return { x: a };\r // }\r // draw({\r // vertex: shader('abc', (__in, __out) => {}),\r // attachments: [\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 }),\r // makeTex({ abc: 123 })\r // ],\r // mesh: new Mesh(),\r // fragment: shader('abc', (__in, __out) => {\r // //__out.attachment0\r // })\r // });\r \r export function globalVarInit(\r fileName: string,\r varName: string,\r initFn: () => T,\r getterFn: any\r ): T {\r if (!getShadeupLocalContext()['shadeup_globals']) {\r getShadeupLocalContext()['shadeup_globals'] = {};\r }\r \r if (!getShadeupLocalContext()['shadeup_globals'][fileName]) {\r getShadeupLocalContext()['shadeup_globals'][fileName] = {};\r }\r \r // Disable caching for now\r const cache = false;\r if (!(varName in getShadeupLocalContext()['shadeup_globals'][fileName]) || !cache) {\r getShadeupLocalContext()['shadeup_globals'][fileName][varName] = initFn();\r }\r getShadeupLocalContext()['shadeup_globals'][fileName]['$getter_' + varName] = getterFn;\r return getShadeupLocalContext()['shadeup_globals'][fileName][varName] as T;\r }\r \r export function globalVarGet(fileName, varName) {\r if (varName == 'env' || varName == 'PLATFORM_WEBGPU' || varName == 'PLATFORM_WEBGL') {\r return getShadeupLocalContext()[varName];\r }\r \r return getShadeupLocalContext()['shadeup_globals'][fileName]['$getter_' + varName]();\r }\r \r interface ToString {\r toString(): string;\r }\r \r type HashableType =\r | string\r | float\r | int\r | bool\r | float2\r | float3\r | float4\r | int2\r | int3\r | int4\r | ToString;\r \r export function hashableTypeToString(k: HashableType) {\r if (typeof k == 'number') {\r return k.toString();\r } else if (typeof k == 'object') {\r if (Array.isArray(k)) {\r return k.map(hashableTypeToString).join(',');\r } else {\r return k.toString();\r }\r } else {\r return k.toString();\r }\r }\r \r declare global {\r const PLATFORM_WEBGPU: boolean;\r const PLATFORM_WEBGL: boolean;\r \r interface Array {\r len(): int;\r push(...items: T[]): void;\r pop(): T;\r \r last(): T;\r first(): T;\r \r append(items: T[]): void;\r remove(index: int): void;\r \r indexOf(item: T): int;\r \r __index(index: int | uint): T;\r \r __index_assign(index: int | uint, value: T): void;\r __index_assign_op(op_fn: (a: T, b: T) => T, index: int | uint, value: T): void;\r \r [index: number]: T;\r }\r }\r \r Array.prototype.len = function () {\r return this.length;\r };\r \r Array.prototype.last = function () {\r return this[this.length - 1];\r };\r \r Array.prototype.first = function () {\r return this[0];\r };\r \r Array.prototype.append = function (items: any[]) {\r for (let i = 0; i < items.length; i++) {\r this.push(items[i]);\r }\r };\r \r Array.prototype.remove = function (index: int) {\r this.splice(index, 1);\r };\r \r Array.prototype.__index = function (index: int) {\r return this[index];\r };\r \r Array.prototype.__index_assign = function (index: int, value: any) {\r this[index] = value;\r };\r \r Array.prototype.__index_assign_op = function (\r op_fn: (a: any, b: any) => any,\r index: int,\r value: any\r ) {\r this[index] = op_fn(this[index], value);\r };\r \r /** @shadeup=tag(async) */\r export function sleep(seconds: float) {\r return new Promise((resolve) => setTimeout(resolve, seconds * 1000));\r }\r \r export type array = Array;\r export function array(count: number, initializer: any = null): array {\r let arr = new Array(count);\r if (initializer) {\r for (let i = 0; i < count; i++) {\r arr[i] = initializer;\r }\r }\r return arr;\r }\r \r export class map {\r pairs: Map = new Map();\r \r constructor(entries?: [K, V][]) {\r if (entries)\r for (let e of entries) {\r this.__index_assign(e[0], e[1]);\r }\r }\r \r __index(key: K): V {\r if (!this.pairs.has(hashableTypeToString(key))) {\r throw new Error('Key not found: ' + hashableTypeToString(key));\r }\r \r return this.pairs.get(hashableTypeToString(key))[1];\r }\r \r __index_assign(key: K, value: V) {\r this.pairs.set(hashableTypeToString(key), [key, value]);\r }\r \r __index_assign_op(op_fn: (a: V, b: V) => V, key: K, value: V) {\r this.pairs.set(hashableTypeToString(key), [key, op_fn(this.__index(key), value)]);\r }\r \r delete(key: K) {\r this.pairs.delete(hashableTypeToString(key));\r }\r \r has(key: K): bool {\r return this.pairs.has(hashableTypeToString(key));\r }\r \r keys(): K[] {\r return Array.from(this.pairs.values()).map((k) => k[0]);\r }\r \r values(): V[] {\r return Array.from(this.pairs.values()).map((k) => k[1]);\r }\r \r static new(entries?: [K, V][]): map {\r return new map(entries);\r }\r }\r \r export function __makeMap(initial: { [key: number]: V }): map;\r export function __makeMap(initial: { [key: string]: V }): map;\r export function __makeMap(initial: { [key: string | number]: V }): map {\r return new map(Object.entries(initial));\r }\r \r export function __deepClone(value: any) {\r if (typeof value == 'object') {\r if (Array.isArray(value)) {\r let res = new Array(value.length);\r for (let i = 0; i < value.length; i++) {\r res[i] = __deepClone(value[i]);\r }\r return res;\r } else {\r if (value && typeof value.clone == 'function') {\r return value.clone();\r } else {\r return value;\r }\r }\r } else {\r return value;\r }\r }\r \r export interface Spatial2d {\r getPosition(): float2;\r getBoundsMin(): float2;\r getBoundsMax(): float2;\r getRadius(): float;\r \r setPosition(pos: float2): void;\r }\r \r export interface Spatial3d {\r getPosition(): float3;\r getBoundsMin(): float3;\r getBoundsMax(): float3;\r getRadius(): float;\r \r setPosition(pos: float3): void;\r }\r \r export class time {\r /** Saves the current time with a key of name */\r static start(name?: string) {\r performance.mark((name ?? '_default') + '_start');\r }\r \r /** Returns the difference in milliseconds between a start with the same key */\r static stop(name?: string): float {\r performance.mark((name ?? '_default') + '_end');\r \r let res = performance.measure(\r (name ?? '_default') + '_diff',\r (name ?? '_default') + '_start',\r (name ?? '_default') + '_end'\r );\r \r return res.duration;\r }\r \r /**\r * This returns a decimal resolution time in milliseconds since the page started. Useful for measuring time differences\r *\r * This uses performance.now() under the hood:\r * The performance.now() method returns a high resolution timestamp in milliseconds. It represents the time elapsed since Performance.timeOrigin\r */\r static now(): float {\r return performance.now();\r }\r }\r `; const globalDTS = "/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n\r\n/// \r\n\r\n/// \r\n/// \r\n\r\n/////////////////////////////\r\n/// ECMAScript APIs\r\n/////////////////////////////\r\n\r\ntype float = number & { _opaque_float: 2 };\r\ntype int = number & { _opaque_int: 1 } & float;\r\n\r\ndeclare var NaN: number;\r\ndeclare var Infinity: number;\r\n\r\n/**\r\n * Converts a string to an integer.\r\n * @param string A string to convert into a number.\r\n * @param radix A value between 2 and 36 that specifies the base of the number in `string`.\r\n * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\r\n * All other strings are considered decimal.\r\n */\r\ndeclare function parseInt(string: string, radix?: number): number;\r\n\r\n/**\r\n * Converts a string to a floating-point number.\r\n * @param string A string that contains a floating-point number.\r\n */\r\ndeclare function parseFloat(string: string): number;\r\n\r\n/**\r\n * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).\r\n * @param number A numeric value.\r\n */\r\ndeclare function isNaN(number: number): boolean;\r\n\r\n/**\r\n * Determines whether a supplied number is finite.\r\n * @param number Any numeric value.\r\n */\r\ndeclare function isFinite(number: number): boolean;\r\n\r\n/**\r\n * Gets the unencoded version of an encoded Uniform Resource Identifier (URI).\r\n * @param encodedURI A value representing an encoded URI.\r\n */\r\ndeclare function decodeURI(encodedURI: string): string;\r\n\r\n/**\r\n * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).\r\n * @param encodedURIComponent A value representing an encoded URI component.\r\n */\r\ndeclare function decodeURIComponent(encodedURIComponent: string): string;\r\n\r\n/**\r\n * Encodes a text string as a valid Uniform Resource Identifier (URI)\r\n * @param uri A value representing an unencoded URI.\r\n */\r\ndeclare function encodeURI(uri: string): string;\r\n\r\n/**\r\n * Encodes a text string as a valid component of a Uniform Resource Identifier (URI).\r\n * @param uriComponent A value representing an unencoded URI component.\r\n */\r\ndeclare function encodeURIComponent(uriComponent: string | number | boolean): string;\r\n\r\n/**\r\n * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.\r\n * @deprecated A legacy feature for browser compatibility\r\n * @param string A string value\r\n */\r\ndeclare function escape(string: string): string;\r\n\r\n/**\r\n * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents.\r\n * @deprecated A legacy feature for browser compatibility\r\n * @param string A string value\r\n */\r\ndeclare function unescape(string: string): string;\r\n\r\ninterface Symbol {\r\n /** Returns a string representation of an object. */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): symbol;\r\n}\r\n\r\ndeclare type PropertyKey = string | number | symbol;\r\n\r\ninterface PropertyDescriptor {\r\n configurable?: boolean;\r\n enumerable?: boolean;\r\n value?: any;\r\n writable?: boolean;\r\n get?(): any;\r\n set?(v: any): void;\r\n}\r\n\r\ninterface PropertyDescriptorMap {\r\n [key: PropertyKey]: PropertyDescriptor;\r\n}\r\n\r\ninterface Object {\r\n /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */\r\n constructor: Function;\r\n\r\n /** Returns a string representation of an object. */\r\n toString(): string;\r\n\r\n /** Returns a date converted to a string using the current locale. */\r\n toLocaleString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Object;\r\n\r\n /**\r\n * Determines whether an object has a property with the specified name.\r\n * @param v A property name.\r\n */\r\n hasOwnProperty(v: PropertyKey): boolean;\r\n\r\n /**\r\n * Determines whether an object exists in another object's prototype chain.\r\n * @param v Another object whose prototype chain is to be checked.\r\n */\r\n isPrototypeOf(v: Object): boolean;\r\n\r\n /**\r\n * Determines whether a specified property is enumerable.\r\n * @param v A property name.\r\n */\r\n propertyIsEnumerable(v: PropertyKey): boolean;\r\n}\r\n\r\ninterface ObjectConstructor {\r\n new (value?: any): Object;\r\n (): any;\r\n (value: any): any;\r\n\r\n /** A reference to the prototype for a class of objects. */\r\n readonly prototype: Object;\r\n\r\n /**\r\n * Returns the prototype of an object.\r\n * @param o The object that references the prototype.\r\n */\r\n getPrototypeOf(o: any): any;\r\n\r\n /**\r\n * Gets the own property descriptor of the specified object.\r\n * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.\r\n * @param o Object that contains the property.\r\n * @param p Name of the property.\r\n */\r\n getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined;\r\n\r\n /**\r\n * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly\r\n * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions.\r\n * @param o Object that contains the own properties.\r\n */\r\n getOwnPropertyNames(o: any): string[];\r\n\r\n /**\r\n * Creates an object that has the specified prototype or that has null prototype.\r\n * @param o Object to use as a prototype. May be null.\r\n */\r\n create(o: object | null): any;\r\n\r\n /**\r\n * Creates an object that has the specified prototype, and that optionally contains specified properties.\r\n * @param o Object to use as a prototype. May be null\r\n * @param properties JavaScript object that contains one or more property descriptors.\r\n */\r\n create(o: object | null, properties: PropertyDescriptorMap & ThisType): any;\r\n\r\n /**\r\n * Adds a property to an object, or modifies attributes of an existing property.\r\n * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object.\r\n * @param p The property name.\r\n * @param attributes Descriptor for the property. It can be for a data property or an accessor property.\r\n */\r\n defineProperty(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType): T;\r\n\r\n /**\r\n * Adds one or more properties to an object, and/or modifies attributes of existing properties.\r\n * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object.\r\n * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property.\r\n */\r\n defineProperties(o: T, properties: PropertyDescriptorMap & ThisType): T;\r\n\r\n /**\r\n * Prevents the modification of attributes of existing properties, and prevents the addition of new properties.\r\n * @param o Object on which to lock the attributes.\r\n */\r\n seal(o: T): T;\r\n\r\n /**\r\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\r\n * @param f Object on which to lock the attributes.\r\n */\r\n freeze(f: T): T;\r\n\r\n /**\r\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\r\n * @param o Object on which to lock the attributes.\r\n */\r\n freeze<\r\n T extends { [idx: string]: U | null | undefined | object },\r\n U extends string | bigint | number | boolean | symbol\r\n >(\r\n o: T\r\n ): Readonly;\r\n\r\n /**\r\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\r\n * @param o Object on which to lock the attributes.\r\n */\r\n freeze(o: T): Readonly;\r\n\r\n /**\r\n * Prevents the addition of new properties to an object.\r\n * @param o Object to make non-extensible.\r\n */\r\n preventExtensions(o: T): T;\r\n\r\n /**\r\n * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object.\r\n * @param o Object to test.\r\n */\r\n isSealed(o: any): boolean;\r\n\r\n /**\r\n * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object.\r\n * @param o Object to test.\r\n */\r\n isFrozen(o: any): boolean;\r\n\r\n /**\r\n * Returns a value that indicates whether new properties can be added to an object.\r\n * @param o Object to test.\r\n */\r\n isExtensible(o: any): boolean;\r\n\r\n /**\r\n * Returns the names of the enumerable string properties and methods of an object.\r\n * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.\r\n */\r\n keys(o: object): string[];\r\n}\r\n\r\n/**\r\n * Provides functionality common to all JavaScript objects.\r\n */\r\ndeclare var Object: ObjectConstructor;\r\n\r\n/**\r\n * Creates a new function.\r\n */\r\ninterface Function {\r\n /**\r\n * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.\r\n * @param thisArg The object to be used as the this object.\r\n * @param argArray A set of arguments to be passed to the function.\r\n */\r\n apply(this: Function, thisArg: any, argArray?: any): any;\r\n\r\n /**\r\n * Calls a method of an object, substituting another object for the current object.\r\n * @param thisArg The object to be used as the current object.\r\n * @param argArray A list of arguments to be passed to the method.\r\n */\r\n call(this: Function, thisArg: any, ...argArray: any[]): any;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg An object to which the this keyword can refer inside the new function.\r\n * @param argArray A list of arguments to be passed to the new function.\r\n */\r\n bind(this: Function, thisArg: any, ...argArray: any[]): any;\r\n\r\n /** Returns a string representation of a function. */\r\n toString(): string;\r\n\r\n prototype: any;\r\n readonly length: int;\r\n\r\n // Non-standard extensions\r\n arguments: any;\r\n caller: Function;\r\n}\r\n\r\ninterface FunctionConstructor {\r\n /**\r\n * Creates a new function.\r\n * @param args A list of arguments the function accepts.\r\n */\r\n new (...args: string[]): Function;\r\n (...args: string[]): Function;\r\n readonly prototype: Function;\r\n}\r\n\r\ndeclare var Function: FunctionConstructor;\r\n\r\n/**\r\n * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.\r\n */\r\ntype ThisParameterType = T extends (this: infer U, ...args: never) => any ? U : unknown;\r\n\r\n/**\r\n * Removes the 'this' parameter from a function type.\r\n */\r\ntype OmitThisParameter = unknown extends ThisParameterType\r\n ? T\r\n : T extends (...args: infer A) => infer R\r\n ? (...args: A) => R\r\n : T;\r\n\r\ninterface CallableFunction extends Function {\r\n /**\r\n * Calls the function with the specified object as the this value and the elements of specified array as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n */\r\n apply(this: (this: T) => R, thisArg: T): R;\r\n\r\n /**\r\n * Calls the function with the specified object as the this value and the elements of specified array as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args An array of argument values to be passed to the function.\r\n */\r\n apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R;\r\n\r\n /**\r\n * Calls the function with the specified object as the this value and the specified rest arguments as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args Argument values to be passed to the function.\r\n */\r\n call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg The object to be used as the this object.\r\n */\r\n bind(this: T, thisArg: ThisParameterType): OmitThisParameter;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args Arguments to bind to the parameters of the function.\r\n */\r\n bind(\r\n this: (this: T, ...args: [...A, ...B]) => R,\r\n thisArg: T,\r\n ...args: A\r\n ): (...args: B) => R;\r\n}\r\n\r\ninterface NewableFunction extends Function {\r\n /**\r\n * Calls the function with the specified object as the this value and the elements of specified array as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n */\r\n apply(this: new () => T, thisArg: T): void;\r\n /**\r\n * Calls the function with the specified object as the this value and the elements of specified array as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args An array of argument values to be passed to the function.\r\n */\r\n apply(this: new (...args: A) => T, thisArg: T, args: A): void;\r\n\r\n /**\r\n * Calls the function with the specified object as the this value and the specified rest arguments as the arguments.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args Argument values to be passed to the function.\r\n */\r\n call(this: new (...args: A) => T, thisArg: T, ...args: A): void;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg The object to be used as the this object.\r\n */\r\n bind(this: T, thisArg: any): T;\r\n\r\n /**\r\n * For a given function, creates a bound function that has the same body as the original function.\r\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\r\n * @param thisArg The object to be used as the this object.\r\n * @param args Arguments to bind to the parameters of the function.\r\n */\r\n bind(\r\n this: new (...args: [...A, ...B]) => R,\r\n thisArg: any,\r\n ...args: A\r\n ): new (...args: B) => R;\r\n}\r\n\r\ninterface IArguments {\r\n [index: number]: any;\r\n length: int;\r\n callee: Function;\r\n}\r\n\r\ninterface String {\r\n /** Returns a string representation of a string. */\r\n toString(): string;\r\n\r\n /**\r\n * Returns the character at the specified index.\r\n * @param pos The zero-based index of the desired character.\r\n */\r\n charAt(pos: number): string;\r\n\r\n /**\r\n * Returns the Unicode value of the character at the specified location.\r\n * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.\r\n */\r\n charCodeAt(index: number): number;\r\n\r\n /**\r\n * Returns a string that contains the concatenation of two or more strings.\r\n * @param strings The strings to append to the end of the string.\r\n */\r\n concat(...strings: string[]): string;\r\n\r\n /**\r\n * Returns the position of the first occurrence of a substring.\r\n * @param searchString The substring to search for in the string\r\n * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.\r\n */\r\n indexOf(searchString: string, position?: number): number;\r\n\r\n /**\r\n * Returns the last occurrence of a substring in the string.\r\n * @param searchString The substring to search for.\r\n * @param position The index at which to begin searching. If omitted, the search begins at the end of the string.\r\n */\r\n lastIndexOf(searchString: string, position?: number): number;\r\n\r\n /**\r\n * Determines whether two strings are equivalent in the current locale.\r\n * @param that String to compare to target string\r\n */\r\n localeCompare(that: string): number;\r\n\r\n /**\r\n * Matches a string with a regular expression, and returns an array containing the results of that search.\r\n * @param regexp A variable name or string literal containing the regular expression pattern and flags.\r\n */\r\n match(regexp: string | RegExp): RegExpMatchArray | null;\r\n\r\n /**\r\n * Replaces text in a string, using a regular expression or search string.\r\n * @param searchValue A string or regular expression to search for.\r\n * @param replaceValue A string containing the text to replace. When the {@linkcode searchValue} is a `RegExp`, all matches are replaced if the `g` flag is set (or only those matches at the beginning, if the `y` flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.\r\n */\r\n replace(searchValue: string | RegExp, replaceValue: string): string;\r\n\r\n /**\r\n * Replaces text in a string, using a regular expression or search string.\r\n * @param searchValue A string to search for.\r\n * @param replacer A function that returns the replacement text.\r\n */\r\n replace(\r\n searchValue: string | RegExp,\r\n replacer: (substring: string, ...args: any[]) => string\r\n ): string;\r\n\r\n /**\r\n * Finds the first substring match in a regular expression search.\r\n * @param regexp The regular expression pattern and applicable flags.\r\n */\r\n search(regexp: string | RegExp): number;\r\n\r\n /**\r\n * Returns a section of a string.\r\n * @param start The index to the beginning of the specified portion of stringObj.\r\n * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.\r\n * If this value is not specified, the substring continues to the end of stringObj.\r\n */\r\n slice(start?: number, end?: number): string;\r\n\r\n /**\r\n * Split a string into substrings using the specified separator and return them as an array.\r\n * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.\r\n * @param limit A value used to limit the number of elements returned in the array.\r\n */\r\n split(separator: string | RegExp, limit?: number): string[];\r\n\r\n /**\r\n * Returns the substring at the specified location within a String object.\r\n * @param start The zero-based index number indicating the beginning of the substring.\r\n * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.\r\n * If end is omitted, the characters from start through the end of the original string are returned.\r\n */\r\n substring(start: number, end?: number): string;\r\n\r\n /** Converts all the alphabetic characters in a string to lowercase. */\r\n toLowerCase(): string;\r\n\r\n /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */\r\n toLocaleLowerCase(locales?: string | string[]): string;\r\n\r\n /** Converts all the alphabetic characters in a string to uppercase. */\r\n toUpperCase(): string;\r\n\r\n /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */\r\n toLocaleUpperCase(locales?: string | string[]): string;\r\n\r\n /** Removes the leading and trailing white space and line terminator characters from a string. */\r\n trim(): string;\r\n\r\n /** Returns the length of a String object. */\r\n readonly length: int;\r\n\r\n // IE extensions\r\n /**\r\n * Gets a substring beginning at the specified location and having the specified length.\r\n * @deprecated A legacy feature for browser compatibility\r\n * @param from The starting position of the desired substring. The index of the first character in the string is zero.\r\n * @param length The number of characters to include in the returned substring.\r\n */\r\n substr(from: number, length?: number): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): string;\r\n\r\n readonly [index: number]: string;\r\n}\r\n\r\ninterface StringConstructor {\r\n new (value?: any): String;\r\n (value?: any): string;\r\n readonly prototype: String;\r\n fromCharCode(...codes: number[]): string;\r\n}\r\n\r\n/**\r\n * Allows manipulation and formatting of text strings and determination and location of substrings within strings.\r\n */\r\ndeclare var String: StringConstructor;\r\n\r\ninterface Boolean {\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): boolean;\r\n}\r\n\r\ninterface BooleanConstructor {\r\n new (value?: any): Boolean;\r\n (value?: T): boolean;\r\n readonly prototype: Boolean;\r\n}\r\n\r\ndeclare var Boolean: BooleanConstructor;\r\n\r\ninterface Number {\r\n /**\r\n * Returns a string representation of an object.\r\n * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.\r\n */\r\n toString(radix?: number): string;\r\n\r\n /**\r\n * Returns a string representing a number in fixed-point notation.\r\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\r\n */\r\n toFixed(fractionDigits?: number): string;\r\n\r\n /**\r\n * Returns a string containing a number represented in exponential notation.\r\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\r\n */\r\n toExponential(fractionDigits?: number): string;\r\n\r\n /**\r\n * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.\r\n * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.\r\n */\r\n toPrecision(precision?: number): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): number;\r\n}\r\n\r\ninterface NumberConstructor {\r\n new (value?: any): Number;\r\n (value?: any): number;\r\n readonly prototype: Number;\r\n\r\n /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */\r\n readonly MAX_VALUE: number;\r\n\r\n /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */\r\n readonly MIN_VALUE: number;\r\n\r\n /**\r\n * A value that is not a number.\r\n * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function.\r\n */\r\n readonly NaN: number;\r\n\r\n /**\r\n * A value that is less than the largest negative number that can be represented in JavaScript.\r\n * JavaScript displays NEGATIVE_INFINITY values as -infinity.\r\n */\r\n readonly NEGATIVE_INFINITY: number;\r\n\r\n /**\r\n * A value greater than the largest number that can be represented in JavaScript.\r\n * JavaScript displays POSITIVE_INFINITY values as infinity.\r\n */\r\n readonly POSITIVE_INFINITY: number;\r\n}\r\n\r\n/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */\r\ndeclare var Number: NumberConstructor;\r\n\r\ninterface TemplateStringsArray extends ReadonlyArray {\r\n readonly raw: readonly string[];\r\n}\r\n\r\n/**\r\n * The type of `import.meta`.\r\n *\r\n * If you need to declare that a given property exists on `import.meta`,\r\n * this type may be augmented via interface merging.\r\n */\r\ninterface ImportMeta {}\r\n\r\n/**\r\n * The type for the optional second argument to `import()`.\r\n *\r\n * If your host environment supports additional options, this type may be\r\n * augmented via interface merging.\r\n */\r\ninterface ImportCallOptions {\r\n assert?: ImportAssertions;\r\n}\r\n\r\n/**\r\n * The type for the `assert` property of the optional second argument to `import()`.\r\n */\r\ninterface ImportAssertions {\r\n [key: string]: string;\r\n}\r\n\r\ninterface Math {\r\n /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */\r\n readonly E: number;\r\n /** The natural logarithm of 10. */\r\n readonly LN10: number;\r\n /** The natural logarithm of 2. */\r\n readonly LN2: number;\r\n /** The base-2 logarithm of e. */\r\n readonly LOG2E: number;\r\n /** The base-10 logarithm of e. */\r\n readonly LOG10E: number;\r\n /** Pi. This is the ratio of the circumference of a circle to its diameter. */\r\n readonly PI: number;\r\n /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */\r\n readonly SQRT1_2: number;\r\n /** The square root of 2. */\r\n readonly SQRT2: number;\r\n /**\r\n * Returns the absolute value of a number (the value without regard to whether it is positive or negative).\r\n * For example, the absolute value of -5 is the same as the absolute value of 5.\r\n * @param x A numeric expression for which the absolute value is needed.\r\n */\r\n abs(x: number): number;\r\n /**\r\n * Returns the arc cosine (or inverse cosine) of a number.\r\n * @param x A numeric expression.\r\n */\r\n acos(x: number): number;\r\n /**\r\n * Returns the arcsine of a number.\r\n * @param x A numeric expression.\r\n */\r\n asin(x: number): number;\r\n /**\r\n * Returns the arctangent of a number.\r\n * @param x A numeric expression for which the arctangent is needed.\r\n */\r\n atan(x: number): number;\r\n /**\r\n * Returns the angle (in radians) from the X axis to a point.\r\n * @param y A numeric expression representing the cartesian y-coordinate.\r\n * @param x A numeric expression representing the cartesian x-coordinate.\r\n */\r\n atan2(y: number, x: number): number;\r\n /**\r\n * Returns the smallest integer greater than or equal to its numeric argument.\r\n * @param x A numeric expression.\r\n */\r\n ceil(x: number): number;\r\n /**\r\n * Returns the cosine of a number.\r\n * @param x A numeric expression that contains an angle measured in radians.\r\n */\r\n cos(x: number): number;\r\n /**\r\n * Returns e (the base of natural logarithms) raised to a power.\r\n * @param x A numeric expression representing the power of e.\r\n */\r\n exp(x: number): number;\r\n /**\r\n * Returns the greatest integer less than or equal to its numeric argument.\r\n * @param x A numeric expression.\r\n */\r\n floor(x: number): number;\r\n /**\r\n * Returns the natural logarithm (base e) of a number.\r\n * @param x A numeric expression.\r\n */\r\n log(x: number): number;\r\n /**\r\n * Returns the larger of a set of supplied numeric expressions.\r\n * @param values Numeric expressions to be evaluated.\r\n */\r\n max(...values: number[]): number;\r\n /**\r\n * Returns the smaller of a set of supplied numeric expressions.\r\n * @param values Numeric expressions to be evaluated.\r\n */\r\n min(...values: number[]): number;\r\n /**\r\n * Returns the value of a base expression taken to a specified power.\r\n * @param x The base value of the expression.\r\n * @param y The exponent value of the expression.\r\n */\r\n pow(x: number, y: number): number;\r\n /** Returns a pseudorandom number between 0 and 1. */\r\n random(): number;\r\n /**\r\n * Returns a supplied numeric expression rounded to the nearest integer.\r\n * @param x The value to be rounded to the nearest integer.\r\n */\r\n round(x: number): number;\r\n /**\r\n * Returns the sine of a number.\r\n * @param x A numeric expression that contains an angle measured in radians.\r\n */\r\n sin(x: number): number;\r\n /**\r\n * Returns the square root of a number.\r\n * @param x A numeric expression.\r\n */\r\n sqrt(x: number): number;\r\n /**\r\n * Returns the tangent of a number.\r\n * @param x A numeric expression that contains an angle measured in radians.\r\n */\r\n tan(x: number): number;\r\n}\r\n/** An intrinsic object that provides basic mathematics functionality and constants. */\r\ndeclare var Math: Math;\r\n\r\n/** Enables basic storage and retrieval of dates and times. */\r\ninterface Date {\r\n /** Returns a string representation of a date. The format of the string depends on the locale. */\r\n toString(): string;\r\n /** Returns a date as a string value. */\r\n toDateString(): string;\r\n /** Returns a time as a string value. */\r\n toTimeString(): string;\r\n /** Returns a value as a string value appropriate to the host environment's current locale. */\r\n toLocaleString(): string;\r\n /** Returns a date as a string value appropriate to the host environment's current locale. */\r\n toLocaleDateString(): string;\r\n /** Returns a time as a string value appropriate to the host environment's current locale. */\r\n toLocaleTimeString(): string;\r\n /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */\r\n valueOf(): number;\r\n /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */\r\n getTime(): number;\r\n /** Gets the year, using local time. */\r\n getFullYear(): number;\r\n /** Gets the year using Universal Coordinated Time (UTC). */\r\n getUTCFullYear(): number;\r\n /** Gets the month, using local time. */\r\n getMonth(): number;\r\n /** Gets the month of a Date object using Universal Coordinated Time (UTC). */\r\n getUTCMonth(): number;\r\n /** Gets the day-of-the-month, using local time. */\r\n getDate(): number;\r\n /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */\r\n getUTCDate(): number;\r\n /** Gets the day of the week, using local time. */\r\n getDay(): number;\r\n /** Gets the day of the week using Universal Coordinated Time (UTC). */\r\n getUTCDay(): number;\r\n /** Gets the hours in a date, using local time. */\r\n getHours(): number;\r\n /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */\r\n getUTCHours(): number;\r\n /** Gets the minutes of a Date object, using local time. */\r\n getMinutes(): number;\r\n /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */\r\n getUTCMinutes(): number;\r\n /** Gets the seconds of a Date object, using local time. */\r\n getSeconds(): number;\r\n /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */\r\n getUTCSeconds(): number;\r\n /** Gets the milliseconds of a Date, using local time. */\r\n getMilliseconds(): number;\r\n /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */\r\n getUTCMilliseconds(): number;\r\n /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */\r\n getTimezoneOffset(): number;\r\n /**\r\n * Sets the date and time value in the Date object.\r\n * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.\r\n */\r\n setTime(time: number): number;\r\n /**\r\n * Sets the milliseconds value in the Date object using local time.\r\n * @param ms A numeric value equal to the millisecond value.\r\n */\r\n setMilliseconds(ms: number): number;\r\n /**\r\n * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).\r\n * @param ms A numeric value equal to the millisecond value.\r\n */\r\n setUTCMilliseconds(ms: number): number;\r\n\r\n /**\r\n * Sets the seconds value in the Date object using local time.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setSeconds(sec: number, ms?: number): number;\r\n /**\r\n * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setUTCSeconds(sec: number, ms?: number): number;\r\n /**\r\n * Sets the minutes value in the Date object using local time.\r\n * @param min A numeric value equal to the minutes value.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setMinutes(min: number, sec?: number, ms?: number): number;\r\n /**\r\n * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).\r\n * @param min A numeric value equal to the minutes value.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setUTCMinutes(min: number, sec?: number, ms?: number): number;\r\n /**\r\n * Sets the hour value in the Date object using local time.\r\n * @param hours A numeric value equal to the hours value.\r\n * @param min A numeric value equal to the minutes value.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setHours(hours: number, min?: number, sec?: number, ms?: number): number;\r\n /**\r\n * Sets the hours value in the Date object using Universal Coordinated Time (UTC).\r\n * @param hours A numeric value equal to the hours value.\r\n * @param min A numeric value equal to the minutes value.\r\n * @param sec A numeric value equal to the seconds value.\r\n * @param ms A numeric value equal to the milliseconds value.\r\n */\r\n setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;\r\n /**\r\n * Sets the numeric day-of-the-month value of the Date object using local time.\r\n * @param date A numeric value equal to the day of the month.\r\n */\r\n setDate(date: number): number;\r\n /**\r\n * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).\r\n * @param date A numeric value equal to the day of the month.\r\n */\r\n setUTCDate(date: number): number;\r\n /**\r\n * Sets the month value in the Date object using local time.\r\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\r\n * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.\r\n */\r\n setMonth(month: number, date?: number): number;\r\n /**\r\n * Sets the month value in the Date object using Universal Coordinated Time (UTC).\r\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\r\n * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.\r\n */\r\n setUTCMonth(month: number, date?: number): number;\r\n /**\r\n * Sets the year of the Date object using local time.\r\n * @param year A numeric value for the year.\r\n * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.\r\n * @param date A numeric value equal for the day of the month.\r\n */\r\n setFullYear(year: number, month?: number, date?: number): number;\r\n /**\r\n * Sets the year value in the Date object using Universal Coordinated Time (UTC).\r\n * @param year A numeric value equal to the year.\r\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.\r\n * @param date A numeric value equal to the day of the month.\r\n */\r\n setUTCFullYear(year: number, month?: number, date?: number): number;\r\n /** Returns a date converted to a string using Universal Coordinated Time (UTC). */\r\n toUTCString(): string;\r\n /** Returns a date as a string value in ISO format. */\r\n toISOString(): string;\r\n /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */\r\n toJSON(key?: any): string;\r\n}\r\n\r\ninterface DateConstructor {\r\n new (): Date;\r\n new (value: number | string): Date;\r\n /**\r\n * Creates a new Date.\r\n * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.\r\n * @param monthIndex The month as a number between 0 and 11 (January to December).\r\n * @param date The date as a number between 1 and 31.\r\n * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour.\r\n * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes.\r\n * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds.\r\n * @param ms A number from 0 to 999 that specifies the milliseconds.\r\n */\r\n new (\r\n year: number,\r\n monthIndex: number,\r\n date?: number,\r\n hours?: number,\r\n minutes?: number,\r\n seconds?: number,\r\n ms?: number\r\n ): Date;\r\n (): string;\r\n readonly prototype: Date;\r\n /**\r\n * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.\r\n * @param s A date string\r\n */\r\n parse(s: string): number;\r\n /**\r\n * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.\r\n * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.\r\n * @param monthIndex The month as a number between 0 and 11 (January to December).\r\n * @param date The date as a number between 1 and 31.\r\n * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour.\r\n * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes.\r\n * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds.\r\n * @param ms A number from 0 to 999 that specifies the milliseconds.\r\n */\r\n UTC(\r\n year: number,\r\n monthIndex: number,\r\n date?: number,\r\n hours?: number,\r\n minutes?: number,\r\n seconds?: number,\r\n ms?: number\r\n ): number;\r\n /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC). */\r\n now(): number;\r\n}\r\n\r\ndeclare var Date: DateConstructor;\r\n\r\ninterface RegExpMatchArray extends Array {\r\n /**\r\n * The index of the search at which the result was found.\r\n */\r\n index?: number;\r\n /**\r\n * A copy of the search string.\r\n */\r\n input?: string;\r\n /**\r\n * The first match. This will always be present because `null` will be returned if there are no matches.\r\n */\r\n 0: string;\r\n}\r\n\r\ninterface RegExpExecArray extends Array {\r\n /**\r\n * The index of the search at which the result was found.\r\n */\r\n index: number;\r\n /**\r\n * A copy of the search string.\r\n */\r\n input: string;\r\n /**\r\n * The first match. This will always be present because `null` will be returned if there are no matches.\r\n */\r\n 0: string;\r\n}\r\n\r\ninterface RegExp {\r\n /**\r\n * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.\r\n * @param string The String object or string literal on which to perform the search.\r\n */\r\n exec(string: string): RegExpExecArray | null;\r\n\r\n /**\r\n * Returns a Boolean value that indicates whether or not a pattern exists in a searched string.\r\n * @param string String on which to perform the search.\r\n */\r\n test(string: string): boolean;\r\n\r\n /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */\r\n readonly source: string;\r\n\r\n /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */\r\n readonly global: boolean;\r\n\r\n /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */\r\n readonly ignoreCase: boolean;\r\n\r\n /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */\r\n readonly multiline: boolean;\r\n\r\n lastIndex: number;\r\n\r\n // Non-standard extensions\r\n /** @deprecated A legacy feature for browser compatibility */\r\n compile(pattern: string, flags?: string): this;\r\n}\r\n\r\ninterface RegExpConstructor {\r\n new (pattern: RegExp | string): RegExp;\r\n new (pattern: string, flags?: string): RegExp;\r\n (pattern: RegExp | string): RegExp;\r\n (pattern: string, flags?: string): RegExp;\r\n readonly prototype: RegExp;\r\n\r\n // Non-standard extensions\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $1: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $2: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $3: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $4: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $5: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $6: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $7: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $8: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $9: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n input: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n $_: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n lastMatch: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n '$&': string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n lastParen: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n '$+': string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n leftContext: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n '$`': string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n rightContext: string;\r\n /** @deprecated A legacy feature for browser compatibility */\r\n \"$'\": string;\r\n}\r\n\r\ndeclare var RegExp: RegExpConstructor;\r\n\r\ninterface Error {\r\n name: string;\r\n message: string;\r\n stack?: string;\r\n}\r\n\r\ninterface ErrorConstructor {\r\n new (message?: string): Error;\r\n (message?: string): Error;\r\n readonly prototype: Error;\r\n}\r\n\r\ndeclare var Error: ErrorConstructor;\r\n\r\ninterface EvalError extends Error {}\r\n\r\ninterface EvalErrorConstructor extends ErrorConstructor {\r\n new (message?: string): EvalError;\r\n (message?: string): EvalError;\r\n readonly prototype: EvalError;\r\n}\r\n\r\ndeclare var EvalError: EvalErrorConstructor;\r\n\r\ninterface RangeError extends Error {}\r\n\r\ninterface RangeErrorConstructor extends ErrorConstructor {\r\n new (message?: string): RangeError;\r\n (message?: string): RangeError;\r\n readonly prototype: RangeError;\r\n}\r\n\r\ndeclare var RangeError: RangeErrorConstructor;\r\n\r\ninterface ReferenceError extends Error {}\r\n\r\ninterface ReferenceErrorConstructor extends ErrorConstructor {\r\n new (message?: string): ReferenceError;\r\n (message?: string): ReferenceError;\r\n readonly prototype: ReferenceError;\r\n}\r\n\r\ndeclare var ReferenceError: ReferenceErrorConstructor;\r\n\r\ninterface SyntaxError extends Error {}\r\n\r\ninterface SyntaxErrorConstructor extends ErrorConstructor {\r\n new (message?: string): SyntaxError;\r\n (message?: string): SyntaxError;\r\n readonly prototype: SyntaxError;\r\n}\r\n\r\ndeclare var SyntaxError: SyntaxErrorConstructor;\r\n\r\ninterface TypeError extends Error {}\r\n\r\ninterface TypeErrorConstructor extends ErrorConstructor {\r\n new (message?: string): TypeError;\r\n (message?: string): TypeError;\r\n readonly prototype: TypeError;\r\n}\r\n\r\ndeclare var TypeError: TypeErrorConstructor;\r\n\r\ninterface URIError extends Error {}\r\n\r\ninterface URIErrorConstructor extends ErrorConstructor {\r\n new (message?: string): URIError;\r\n (message?: string): URIError;\r\n readonly prototype: URIError;\r\n}\r\n\r\ndeclare var URIError: URIErrorConstructor;\r\n\r\ninterface JSON {\r\n /**\r\n * Converts a JavaScript Object Notation (JSON) string into an object.\r\n * @param text A valid JSON string.\r\n * @param reviver A function that transforms the results. This function is called for each member of the object.\r\n * If a member contains nested objects, the nested objects are transformed before the parent object is.\r\n */\r\n parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;\r\n /**\r\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\r\n * @param value A JavaScript value, usually an object or array, to be converted.\r\n * @param replacer A function that transforms the results.\r\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\r\n */\r\n stringify(\r\n value: any,\r\n replacer?: (this: any, key: string, value: any) => any,\r\n space?: string | number\r\n ): string;\r\n /**\r\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\r\n * @param value A JavaScript value, usually an object or array, to be converted.\r\n * @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.\r\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\r\n */\r\n stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;\r\n}\r\n\r\n/**\r\n * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.\r\n */\r\ndeclare var JSON: JSON;\r\n\r\n/////////////////////////////\r\n/// ECMAScript Array API (specially handled by compiler)\r\n/////////////////////////////\r\n\r\ninterface ReadonlyArray {\r\n /**\r\n * Gets the length of the array. This is a number one higher than the highest element defined in an array.\r\n */\r\n readonly length: int;\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n /**\r\n * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.\r\n */\r\n toLocaleString(): string;\r\n /**\r\n * Combines two or more arrays.\r\n * @param items Additional items to add to the end of array1.\r\n */\r\n concat(...items: ConcatArray[]): T[];\r\n /**\r\n * Combines two or more arrays.\r\n * @param items Additional items to add to the end of array1.\r\n */\r\n concat(...items: (T | ConcatArray)[]): T[];\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): T[];\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\r\n */\r\n indexOf(searchElement: T, fromIndex?: number): number;\r\n /**\r\n * Returns the index of the last occurrence of a specified value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\r\n */\r\n lastIndexOf(searchElement: T, fromIndex?: number): number;\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: T, index: number, array: readonly T[]) => value is S,\r\n thisArg?: any\r\n ): this is readonly S[];\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: T, index: number, array: readonly T[]) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: T, index: number, array: readonly T[]) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void;\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[];\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: T, index: number, array: readonly T[]) => value is S,\r\n thisArg?: any\r\n ): S[];\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[];\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T\r\n ): T;\r\n reduce(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T,\r\n initialValue: T\r\n ): T;\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U,\r\n initialValue: U\r\n ): U;\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T\r\n ): T;\r\n reduceRight(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T,\r\n initialValue: T\r\n ): T;\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n readonly [n: number]: T;\r\n}\r\n\r\ninterface ConcatArray {\r\n readonly length: int;\r\n readonly [n: number]: T;\r\n join(separator?: string): string;\r\n slice(start?: number, end?: number): T[];\r\n}\r\n\r\ninterface Array {\r\n /**\r\n * Gets or sets the length of the array. This is a number one higher than the highest index in the array.\r\n */\r\n length: int;\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n /**\r\n * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.\r\n */\r\n toLocaleString(): string;\r\n /**\r\n * Removes the last element from an array and returns it.\r\n * If the array is empty, undefined is returned and the array is not modified.\r\n */\r\n pop(): T | undefined;\r\n /**\r\n * Appends new elements to the end of an array, and returns the new length of the array.\r\n * @param items New elements to add to the array.\r\n */\r\n push(...items: T[]): number;\r\n /**\r\n * Combines two or more arrays.\r\n * This method returns a new array without modifying any existing arrays.\r\n * @param items Additional arrays and/or items to add to the end of the array.\r\n */\r\n concat(...items: ConcatArray[]): T[];\r\n /**\r\n * Combines two or more arrays.\r\n * This method returns a new array without modifying any existing arrays.\r\n * @param items Additional arrays and/or items to add to the end of the array.\r\n */\r\n concat(...items: (T | ConcatArray)[]): T[];\r\n /**\r\n * Adds all the elements of an array into a string, separated by the specified separator string.\r\n * @param separator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n /**\r\n * Reverses the elements in an array in place.\r\n * This method mutates the array and returns a reference to the same array.\r\n */\r\n reverse(): T[];\r\n /**\r\n * Removes the first element from an array and returns it.\r\n * If the array is empty, undefined is returned and the array is not modified.\r\n */\r\n shift(): T | undefined;\r\n /**\r\n * Returns a copy of a section of an array.\r\n * For both start and end, a negative index can be used to indicate an offset from the end of the array.\r\n * For example, -2 refers to the second to last element of the array.\r\n * @param start The beginning index of the specified portion of the array.\r\n * If start is undefined, then the slice begins at index 0.\r\n * @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n * If end is undefined, then the slice extends to the end of the array.\r\n */\r\n slice(start?: number, end?: number): T[];\r\n /**\r\n * Sorts an array in place.\r\n * This method mutates the array and returns a reference to the same array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: T, b: T) => number): this;\r\n /**\r\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\r\n * @param start The zero-based location in the array from which to start removing elements.\r\n * @param deleteCount The number of elements to remove.\r\n * @returns An array containing the elements that were deleted.\r\n */\r\n splice(start: number, deleteCount?: number): T[];\r\n /**\r\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\r\n * @param start The zero-based location in the array from which to start removing elements.\r\n * @param deleteCount The number of elements to remove.\r\n * @param items Elements to insert into the array in place of the deleted elements.\r\n * @returns An array containing the elements that were deleted.\r\n */\r\n splice(start: number, deleteCount: number, ...items: T[]): T[];\r\n /**\r\n * Inserts new elements at the start of an array, and returns the new length of the array.\r\n * @param items Elements to insert at the start of the array.\r\n */\r\n unshift(...items: T[]): number;\r\n /**\r\n * Returns the index of the first occurrence of a value in an array, or -1 if it is not present.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\r\n */\r\n indexOf(searchElement: T, fromIndex?: number): number;\r\n /**\r\n * Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.\r\n */\r\n lastIndexOf(searchElement: T, fromIndex?: number): number;\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: T, index: number, array: T[]) => value is S,\r\n thisArg?: any\r\n ): this is S[];\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: T, index: number, array: T[]) => value is S,\r\n thisArg?: any\r\n ): S[];\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\r\n reduce(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T,\r\n initialValue: T\r\n ): T;\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U,\r\n initialValue: U\r\n ): U;\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T\r\n ): T;\r\n reduceRight(\r\n callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T,\r\n initialValue: T\r\n ): T;\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n [n: number]: T;\r\n}\r\n\r\ninterface ArrayConstructor {\r\n new (arrayLength?: number): any[];\r\n new (arraylength: int): T[];\r\n new (...items: T[]): T[];\r\n (arrayLength?: number): any[];\r\n (arraylength: int): T[];\r\n (...items: T[]): T[];\r\n isArray(arg: any): arg is any[];\r\n readonly prototype: any[];\r\n}\r\n\r\ndeclare var Array: ArrayConstructor;\r\n\r\ninterface TypedPropertyDescriptor {\r\n enumerable?: boolean;\r\n configurable?: boolean;\r\n writable?: boolean;\r\n value?: T;\r\n get?: () => T;\r\n set?: (value: T) => void;\r\n}\r\n\r\ndeclare type PromiseConstructorLike = new (\r\n executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void\r\n) => PromiseLike;\r\n\r\ninterface PromiseLike {\r\n /**\r\n * Attaches callbacks for the resolution and/or rejection of the Promise.\r\n * @param onfulfilled The callback to execute when the Promise is resolved.\r\n * @param onrejected The callback to execute when the Promise is rejected.\r\n * @returns A Promise for the completion of which ever callback is executed.\r\n */\r\n then(\r\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null,\r\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null\r\n ): PromiseLike;\r\n}\r\n\r\n/**\r\n * Represents the completion of an asynchronous operation\r\n */\r\ninterface Promise {\r\n /**\r\n * Attaches callbacks for the resolution and/or rejection of the Promise.\r\n * @param onfulfilled The callback to execute when the Promise is resolved.\r\n * @param onrejected The callback to execute when the Promise is rejected.\r\n * @returns A Promise for the completion of which ever callback is executed.\r\n */\r\n then(\r\n onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null,\r\n onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null\r\n ): Promise;\r\n\r\n /**\r\n * Attaches a callback for only the rejection of the Promise.\r\n * @param onrejected The callback to execute when the Promise is rejected.\r\n * @returns A Promise for the completion of the callback.\r\n */\r\n catch(\r\n onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null\r\n ): Promise;\r\n}\r\n\r\n/**\r\n * Recursively unwraps the \"awaited type\" of a type. Non-promise \"thenables\" should resolve to `never`. This emulates the behavior of `await`.\r\n */\r\ntype Awaited = T extends null | undefined\r\n ? T // special case for `null | undefined` when not in `--strictNullChecks` mode\r\n : T extends object & { then(onfulfilled: infer F, ...args: infer _): any } // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped\r\n ? F extends (value: infer V, ...args: infer _) => any // if the argument to `then` is callable, extracts the first argument\r\n ? Awaited // recursively unwrap the value\r\n : never // the argument to `then` was not callable\r\n : T; // non-object or non-thenable\r\n\r\ninterface ArrayLike {\r\n readonly length: int;\r\n readonly [n: number]: T;\r\n}\r\n\r\n/**\r\n * Make all properties in T optional\r\n */\r\ntype Partial = {\r\n [P in keyof T]?: T[P];\r\n};\r\n\r\n/**\r\n * Make all properties in T required\r\n */\r\ntype Required = {\r\n [P in keyof T]-?: T[P];\r\n};\r\n\r\n/**\r\n * Make all properties in T readonly\r\n */\r\ntype Readonly = {\r\n readonly [P in keyof T]: T[P];\r\n};\r\n\r\n/**\r\n * From T, pick a set of properties whose keys are in the union K\r\n */\r\ntype Pick = {\r\n [P in K]: T[P];\r\n};\r\n\r\n/**\r\n * Construct a type with a set of properties K of type T\r\n */\r\ntype Record = {\r\n [P in K]: T;\r\n};\r\n\r\n/**\r\n * Exclude from T those types that are assignable to U\r\n */\r\ntype Exclude = T extends U ? never : T;\r\n\r\n/**\r\n * Extract from T those types that are assignable to U\r\n */\r\ntype Extract = T extends U ? T : never;\r\n\r\n/**\r\n * Construct a type with the properties of T except for those in type K.\r\n */\r\ntype Omit = Pick>;\r\n\r\n/**\r\n * Exclude null and undefined from T\r\n */\r\ntype NonNullable = T & {};\r\n\r\n/**\r\n * Obtain the parameters of a function type in a tuple\r\n */\r\ntype Parameters any> = T extends (...args: infer P) => any ? P : never;\r\n\r\n/**\r\n * Obtain the parameters of a constructor function type in a tuple\r\n */\r\ntype ConstructorParameters any> = T extends abstract new (\r\n ...args: infer P\r\n) => any\r\n ? P\r\n : never;\r\n\r\n/**\r\n * Obtain the return type of a function type\r\n */\r\ntype ReturnType any> = T extends (...args: any) => infer R ? R : any;\r\n\r\n/**\r\n * Obtain the return type of a constructor function type\r\n */\r\ntype InstanceType any> = T extends abstract new (\r\n ...args: any\r\n) => infer R\r\n ? R\r\n : any;\r\n\r\n/**\r\n * Convert string literal type to uppercase\r\n */\r\ntype Uppercase = intrinsic;\r\n\r\n/**\r\n * Convert string literal type to lowercase\r\n */\r\ntype Lowercase = intrinsic;\r\n\r\n/**\r\n * Convert first character of string literal type to uppercase\r\n */\r\ntype Capitalize = intrinsic;\r\n\r\n/**\r\n * Convert first character of string literal type to lowercase\r\n */\r\ntype Uncapitalize = intrinsic;\r\n\r\n/**\r\n * Marker for contextual 'this' type\r\n */\r\ninterface ThisType {}\r\n\r\n/**\r\n * Represents a raw buffer of binary data, which is used to store data for the\r\n * different typed arrays. ArrayBuffers cannot be read from or written to directly,\r\n * but can be passed to a typed array or DataView Object to interpret the raw\r\n * buffer as needed.\r\n */\r\ninterface ArrayBuffer {\r\n /**\r\n * Read-only. The length of the ArrayBuffer (in bytes).\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * Returns a section of an ArrayBuffer.\r\n */\r\n slice(begin: number, end?: number): ArrayBuffer;\r\n}\r\n\r\n/**\r\n * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.\r\n */\r\ninterface ArrayBufferTypes {\r\n ArrayBuffer: ArrayBuffer;\r\n}\r\ntype ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];\r\n\r\ninterface ArrayBufferConstructor {\r\n readonly prototype: ArrayBuffer;\r\n new (bytelength: int): ArrayBuffer;\r\n isView(arg: any): arg is ArrayBufferView;\r\n}\r\ndeclare var ArrayBuffer: ArrayBufferConstructor;\r\n\r\ninterface ArrayBufferView {\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n byteOffset: number;\r\n}\r\n\r\ninterface DataView {\r\n readonly buffer: ArrayBuffer;\r\n readonly bytelength: int;\r\n readonly byteOffset: number;\r\n /**\r\n * Gets the Float32 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getFloat32(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Gets the Float64 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getFloat64(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Gets the Int8 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n */\r\n getInt8(byteOffset: number): number;\r\n\r\n /**\r\n * Gets the Int16 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getInt16(byteOffset: number, littleEndian?: boolean): number;\r\n /**\r\n * Gets the Int32 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getInt32(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Gets the Uint8 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n */\r\n getUint8(byteOffset: number): number;\r\n\r\n /**\r\n * Gets the Uint16 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getUint16(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Gets the Uint32 value at the specified byte offset from the start of the view. There is\r\n * no alignment constraint; multi-byte values may be fetched from any offset.\r\n * @param byteOffset The place in the buffer at which the value should be retrieved.\r\n * @param littleEndian If false or undefined, a big-endian value should be read.\r\n */\r\n getUint32(byteOffset: number, littleEndian?: boolean): number;\r\n\r\n /**\r\n * Stores an Float32 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Float64 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Int8 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n */\r\n setInt8(byteOffset: number, value: number): void;\r\n\r\n /**\r\n * Stores an Int16 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setInt16(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Int32 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setInt32(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Uint8 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n */\r\n setUint8(byteOffset: number, value: number): void;\r\n\r\n /**\r\n * Stores an Uint16 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setUint16(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n\r\n /**\r\n * Stores an Uint32 value at the specified byte offset from the start of the view.\r\n * @param byteOffset The place in the buffer at which the value should be set.\r\n * @param value The value to set.\r\n * @param littleEndian If false or undefined, a big-endian value should be written.\r\n */\r\n setUint32(byteOffset: number, value: number, littleEndian?: boolean): void;\r\n}\r\n\r\ninterface DataViewConstructor {\r\n readonly prototype: DataView;\r\n new (\r\n buffer: ArrayBufferLike & { BYTES_PER_ELEMENT?: never },\r\n byteOffset?: number,\r\n byteLength?: number\r\n ): DataView;\r\n}\r\ndeclare var DataView: DataViewConstructor;\r\n\r\n/**\r\n * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested\r\n * number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Int8Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Int8Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Int8Array) => any,\r\n thisArg?: any\r\n ): Int8Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Int8Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Int8Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Int8Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Int8Array) => number,\r\n thisArg?: any\r\n ): Int8Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int8Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Int8Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Int8Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Int8Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Int8Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Int8Array;\r\n\r\n [index: number]: number;\r\n}\r\ninterface Int8ArrayConstructor {\r\n readonly prototype: Int8Array;\r\n new (length: int): Int8Array;\r\n new (array: ArrayLike | ArrayBufferLike): Int8Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Int8Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Int8Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array;\r\n}\r\ndeclare var Int8Array: Int8ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Uint8Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Uint8Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Uint8Array) => any,\r\n thisArg?: any\r\n ): Uint8Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Uint8Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Uint8Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Uint8Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Uint8Array) => number,\r\n thisArg?: any\r\n ): Uint8Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Uint8Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Uint8Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Uint8Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Uint8Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Uint8Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Uint8ArrayConstructor {\r\n readonly prototype: Uint8Array;\r\n new (length: int): Uint8Array;\r\n new (array: ArrayLike | ArrayBufferLike): Uint8Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Uint8Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Uint8Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array;\r\n}\r\ndeclare var Uint8Array: Uint8ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.\r\n * If the requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Uint8ClampedArray {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Uint8ClampedArray) => any,\r\n thisArg?: any\r\n ): Uint8ClampedArray;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number,\r\n thisArg?: any\r\n ): Uint8ClampedArray;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint8ClampedArray\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Uint8ClampedArray;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Uint8ClampedArray;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Uint8ClampedArray;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Uint8ClampedArray;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Uint8ClampedArrayConstructor {\r\n readonly prototype: Uint8ClampedArray;\r\n new (length: int): Uint8ClampedArray;\r\n new (array: ArrayLike | ArrayBufferLike): Uint8ClampedArray;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Uint8ClampedArray;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Uint8ClampedArray;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(\r\n arrayLike: ArrayLike,\r\n mapfn: (v: T, k: number) => number,\r\n thisArg?: any\r\n ): Uint8ClampedArray;\r\n}\r\ndeclare var Uint8ClampedArray: Uint8ClampedArrayConstructor;\r\n\r\n/**\r\n * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Int16Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Int16Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Int16Array) => any,\r\n thisArg?: any\r\n ): Int16Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Int16Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Int16Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Int16Array) => void,\r\n thisArg?: any\r\n ): void;\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Int16Array) => number,\r\n thisArg?: any\r\n ): Int16Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int16Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Int16Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Int16Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Int16Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Int16Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Int16Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Int16ArrayConstructor {\r\n readonly prototype: Int16Array;\r\n new (length: int): Int16Array;\r\n new (array: ArrayLike | ArrayBufferLike): Int16Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Int16Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Int16Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array;\r\n}\r\ndeclare var Int16Array: Int16ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Uint16Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Uint16Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Uint16Array) => any,\r\n thisArg?: any\r\n ): Uint16Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Uint16Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Uint16Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Uint16Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Uint16Array) => number,\r\n thisArg?: any\r\n ): Uint16Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint16Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Uint16Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Uint16Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Uint16Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Uint16Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Uint16Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Uint16ArrayConstructor {\r\n readonly prototype: Uint16Array;\r\n new (length: int): Uint16Array;\r\n new (array: ArrayLike | ArrayBufferLike): Uint16Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Uint16Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Uint16Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array;\r\n}\r\ndeclare var Uint16Array: Uint16ArrayConstructor;\r\n/**\r\n * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Int32Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Int32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Int32Array) => any,\r\n thisArg?: any\r\n ): Int32Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Int32Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Int32Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Int32Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Int32Array) => number,\r\n thisArg?: any\r\n ): Int32Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Int32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Int32Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Int32Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Int32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Int32Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Int32Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Int32ArrayConstructor {\r\n readonly prototype: Int32Array;\r\n new (length: int): Int32Array;\r\n new (array: ArrayLike | ArrayBufferLike): Int32Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Int32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Int32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array;\r\n}\r\ndeclare var Int32Array: Int32ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the\r\n * requested number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Uint32Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Uint32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Uint32Array) => any,\r\n thisArg?: any\r\n ): Uint32Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Uint32Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Uint32Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Uint32Array) => void,\r\n thisArg?: any\r\n ): void;\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Uint32Array) => number,\r\n thisArg?: any\r\n ): Uint32Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Uint32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Uint32Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Uint32Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Uint32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Uint32Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Uint32Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Uint32ArrayConstructor {\r\n readonly prototype: Uint32Array;\r\n new (length: int): Uint32Array;\r\n new (array: ArrayLike | ArrayBufferLike): Uint32Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Uint32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Uint32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array;\r\n}\r\ndeclare var Uint32Array: Uint32ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number\r\n * of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Float32Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Float32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Float32Array) => any,\r\n thisArg?: any\r\n ): Float32Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Float32Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Float32Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Float32Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Float32Array) => number,\r\n thisArg?: any\r\n ): Float32Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float32Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Float32Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Float32Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Float32Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Float32Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Float32Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Float32ArrayConstructor {\r\n readonly prototype: Float32Array;\r\n new (length: int): Float32Array;\r\n new (array: ArrayLike | ArrayBufferLike): Float32Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Float32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Float32Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array;\r\n}\r\ndeclare var Float32Array: Float32ArrayConstructor;\r\n\r\n/**\r\n * A typed array of 64-bit float values. The contents are initialized to 0. If the requested\r\n * number of bytes could not be allocated an exception is raised.\r\n */\r\ninterface Float64Array {\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * The ArrayBuffer instance referenced by the array.\r\n */\r\n readonly buffer: ArrayBufferLike;\r\n\r\n /**\r\n * The length in bytes of the array.\r\n */\r\n readonly bytelength: int;\r\n\r\n /**\r\n * The offset in bytes of the array.\r\n */\r\n readonly byteOffset: number;\r\n\r\n /**\r\n * Returns the this object after copying a section of the array identified by start and end\r\n * to the same array starting at position target\r\n * @param target If target is negative, it is treated as length+target where length is the\r\n * length of the array.\r\n * @param start If start is negative, it is treated as length+start. If end is negative, it\r\n * is treated as length+end. If start is omitted, `0` is used.\r\n * @param end If not specified, length of the this object is used as its default value.\r\n */\r\n copyWithin(target: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Determines whether all the members of an array satisfy the specified test.\r\n * @param predicate A function that accepts up to three arguments. The every method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value false, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n every(\r\n predicate: (value: number, index: number, array: Float64Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array\r\n * @param value value to fill array section with\r\n * @param start index to start filling the array at. If start is negative, it is treated as\r\n * length+start where length is the length of the array.\r\n * @param end index to stop filling the array at. If end is negative, it is treated as\r\n * length+end.\r\n */\r\n fill(value: number, start?: number, end?: number): this;\r\n\r\n /**\r\n * Returns the elements of an array that meet the condition specified in a callback function.\r\n * @param predicate A function that accepts up to three arguments. The filter method calls\r\n * the predicate function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n filter(\r\n predicate: (value: number, index: number, array: Float64Array) => any,\r\n thisArg?: any\r\n ): Float64Array;\r\n\r\n /**\r\n * Returns the value of the first element in the array where predicate is true, and undefined\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found, find\r\n * immediately returns that element value. Otherwise, find returns undefined.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n find(\r\n predicate: (value: number, index: number, obj: Float64Array) => boolean,\r\n thisArg?: any\r\n ): number | undefined;\r\n\r\n /**\r\n * Returns the index of the first element in the array where predicate is true, and -1\r\n * otherwise.\r\n * @param predicate find calls predicate once for each element of the array, in ascending\r\n * order, until it finds one where predicate returns true. If such an element is found,\r\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\r\n * @param thisArg If provided, it will be used as the this value for each invocation of\r\n * predicate. If it is not provided, undefined is used instead.\r\n */\r\n findIndex(\r\n predicate: (value: number, index: number, obj: Float64Array) => boolean,\r\n thisArg?: any\r\n ): number;\r\n\r\n /**\r\n * Performs the specified action for each element in an array.\r\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n forEach(\r\n callbackfn: (value: number, index: number, array: Float64Array) => void,\r\n thisArg?: any\r\n ): void;\r\n\r\n /**\r\n * Returns the index of the first occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n indexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * Adds all the elements of an array separated by the specified separator string.\r\n * @param separator A string used to separate one element of an array from the next in the\r\n * resulting String. If omitted, the array elements are separated with a comma.\r\n */\r\n join(separator?: string): string;\r\n\r\n /**\r\n * Returns the index of the last occurrence of a value in an array.\r\n * @param searchElement The value to locate in the array.\r\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\r\n * search starts at index 0.\r\n */\r\n lastIndexOf(searchElement: number, fromIndex?: number): number;\r\n\r\n /**\r\n * The length of the array.\r\n */\r\n readonly length: int;\r\n\r\n /**\r\n * Calls a defined callback function on each element of an array, and returns an array that\r\n * contains the results.\r\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n map(\r\n callbackfn: (value: number, index: number, array: Float64Array) => number,\r\n thisArg?: any\r\n ): Float64Array;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => number\r\n ): number;\r\n reduce(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array. The return value of\r\n * the callback function is the accumulated result, and is provided as an argument in the next\r\n * call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\r\n * callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduce(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an\r\n * argument instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => number\r\n ): number;\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: number,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => number,\r\n initialValue: number\r\n ): number;\r\n\r\n /**\r\n * Calls the specified callback function for all the elements in an array, in descending order.\r\n * The return value of the callback function is the accumulated result, and is provided as an\r\n * argument in the next call to the callback function.\r\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\r\n * the callbackfn function one time for each element in the array.\r\n * @param initialValue If initialValue is specified, it is used as the initial value to start\r\n * the accumulation. The first call to the callbackfn function provides this value as an argument\r\n * instead of an array value.\r\n */\r\n reduceRight(\r\n callbackfn: (\r\n previousValue: U,\r\n currentValue: number,\r\n currentIndex: number,\r\n array: Float64Array\r\n ) => U,\r\n initialValue: U\r\n ): U;\r\n\r\n /**\r\n * Reverses the elements in an Array.\r\n */\r\n reverse(): Float64Array;\r\n\r\n /**\r\n * Sets a value or an array of values.\r\n * @param array A typed or untyped array of values to set.\r\n * @param offset The index in the current array at which the values are to be written.\r\n */\r\n set(array: ArrayLike, offset?: number): void;\r\n\r\n /**\r\n * Returns a section of an array.\r\n * @param start The beginning of the specified portion of the array.\r\n * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.\r\n */\r\n slice(start?: number, end?: number): Float64Array;\r\n\r\n /**\r\n * Determines whether the specified callback function returns true for any element of an array.\r\n * @param predicate A function that accepts up to three arguments. The some method calls\r\n * the predicate function for each element in the array until the predicate returns a value\r\n * which is coercible to the Boolean value true, or until the end of the array.\r\n * @param thisArg An object to which the this keyword can refer in the predicate function.\r\n * If thisArg is omitted, undefined is used as the this value.\r\n */\r\n some(\r\n predicate: (value: number, index: number, array: Float64Array) => unknown,\r\n thisArg?: any\r\n ): boolean;\r\n\r\n /**\r\n * Sorts an array.\r\n * @param compareFn Function used to determine the order of the elements. It is expected to return\r\n * a negative value if first argument is less than second argument, zero if they're equal and a positive\r\n * value otherwise. If omitted, the elements are sorted in ascending order.\r\n * ```ts\r\n * [11,2,22,1].sort((a, b) => a - b)\r\n * ```\r\n */\r\n sort(compareFn?: (a: number, b: number) => number): this;\r\n\r\n /**\r\n * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements\r\n * at begin, inclusive, up to end, exclusive.\r\n * @param begin The index of the beginning of the array.\r\n * @param end The index of the end of the array.\r\n */\r\n subarray(begin?: number, end?: number): Float64Array;\r\n\r\n /**\r\n * Converts a number to a string by using the current locale.\r\n */\r\n toLocaleString(): string;\r\n\r\n /**\r\n * Returns a string representation of an array.\r\n */\r\n toString(): string;\r\n\r\n /** Returns the primitive value of the specified object. */\r\n valueOf(): Float64Array;\r\n\r\n [index: number]: number;\r\n}\r\n\r\ninterface Float64ArrayConstructor {\r\n readonly prototype: Float64Array;\r\n new (length: int): Float64Array;\r\n new (array: ArrayLike | ArrayBufferLike): Float64Array;\r\n new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array;\r\n\r\n /**\r\n * The size in bytes of each element in the array.\r\n */\r\n readonly BYTES_PER_ELEMENT: number;\r\n\r\n /**\r\n * Returns a new array from a set of elements.\r\n * @param items A set of elements to include in the new array object.\r\n */\r\n of(...items: number[]): Float64Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n */\r\n from(arrayLike: ArrayLike): Float64Array;\r\n\r\n /**\r\n * Creates an array from an array-like or iterable object.\r\n * @param arrayLike An array-like or iterable object to convert to an array.\r\n * @param mapfn A mapping function to call on every element of the array.\r\n * @param thisArg Value of 'this' used to invoke the mapfn.\r\n */\r\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array;\r\n}\r\ndeclare var Float64Array: Float64ArrayConstructor;\r\n\r\n/////////////////////////////\r\n/// ECMAScript Internationalization API\r\n/////////////////////////////\r\n\r\ndeclare namespace Intl {\r\n interface CollatorOptions {\r\n usage?: 'sort' | 'search' | undefined;\r\n localeMatcher?: 'lookup' | 'best fit' | undefined;\r\n numeric?: boolean | undefined;\r\n caseFirst?: 'upper' | 'lower' | 'false' | undefined;\r\n sensitivity?: 'base' | 'accent' | 'case' | 'variant' | undefined;\r\n collation?:\r\n | 'big5han'\r\n | 'compat'\r\n | 'dict'\r\n | 'direct'\r\n | 'ducet'\r\n | 'emoji'\r\n | 'eor'\r\n | 'gb2312'\r\n | 'phonebk'\r\n | 'phonetic'\r\n | 'pinyin'\r\n | 'reformed'\r\n | 'searchjl'\r\n | 'stroke'\r\n | 'trad'\r\n | 'unihan'\r\n | 'zhuyin'\r\n | undefined;\r\n ignorePunctuation?: boolean | undefined;\r\n }\r\n\r\n interface ResolvedCollatorOptions {\r\n locale: string;\r\n usage: string;\r\n sensitivity: string;\r\n ignorePunctuation: boolean;\r\n collation: string;\r\n caseFirst: string;\r\n numeric: boolean;\r\n }\r\n\r\n interface Collator {\r\n compare(x: string, y: string): number;\r\n resolvedOptions(): ResolvedCollatorOptions;\r\n }\r\n var Collator: {\r\n new (locales?: string | string[], options?: CollatorOptions): Collator;\r\n (locales?: string | string[], options?: CollatorOptions): Collator;\r\n supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[];\r\n };\r\n\r\n interface NumberFormatOptions {\r\n localeMatcher?: string | undefined;\r\n style?: string | undefined;\r\n currency?: string | undefined;\r\n currencySign?: string | undefined;\r\n useGrouping?: boolean | undefined;\r\n minimumIntegerDigits?: number | undefined;\r\n minimumFractionDigits?: number | undefined;\r\n maximumFractionDigits?: number | undefined;\r\n minimumSignificantDigits?: number | undefined;\r\n maximumSignificantDigits?: number | undefined;\r\n }\r\n\r\n interface ResolvedNumberFormatOptions {\r\n locale: string;\r\n numberingSystem: string;\r\n style: string;\r\n currency?: string;\r\n minimumIntegerDigits: number;\r\n minimumFractionDigits: number;\r\n maximumFractionDigits: number;\r\n minimumSignificantDigits?: number;\r\n maximumSignificantDigits?: number;\r\n useGrouping: boolean;\r\n }\r\n\r\n interface NumberFormat {\r\n format(value: number): string;\r\n resolvedOptions(): ResolvedNumberFormatOptions;\r\n }\r\n var NumberFormat: {\r\n new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\r\n (locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\r\n supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[];\r\n readonly prototype: NumberFormat;\r\n };\r\n\r\n interface DateTimeFormatOptions {\r\n localeMatcher?: 'best fit' | 'lookup' | undefined;\r\n weekday?: 'long' | 'short' | 'narrow' | undefined;\r\n era?: 'long' | 'short' | 'narrow' | undefined;\r\n year?: 'numeric' | '2-digit' | undefined;\r\n month?: 'numeric' | '2-digit' | 'long' | 'short' | 'narrow' | undefined;\r\n day?: 'numeric' | '2-digit' | undefined;\r\n hour?: 'numeric' | '2-digit' | undefined;\r\n minute?: 'numeric' | '2-digit' | undefined;\r\n second?: 'numeric' | '2-digit' | undefined;\r\n timeZoneName?:\r\n | 'short'\r\n | 'long'\r\n | 'shortOffset'\r\n | 'longOffset'\r\n | 'shortGeneric'\r\n | 'longGeneric'\r\n | undefined;\r\n formatMatcher?: 'best fit' | 'basic' | undefined;\r\n hour12?: boolean | undefined;\r\n timeZone?: string | undefined;\r\n }\r\n\r\n interface ResolvedDateTimeFormatOptions {\r\n locale: string;\r\n calendar: string;\r\n numberingSystem: string;\r\n timeZone: string;\r\n hour12?: boolean;\r\n weekday?: string;\r\n era?: string;\r\n year?: string;\r\n month?: string;\r\n day?: string;\r\n hour?: string;\r\n minute?: string;\r\n second?: string;\r\n timeZoneName?: string;\r\n }\r\n\r\n interface DateTimeFormat {\r\n format(date?: Date | number): string;\r\n resolvedOptions(): ResolvedDateTimeFormatOptions;\r\n }\r\n var DateTimeFormat: {\r\n new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\r\n (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\r\n supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[];\r\n readonly prototype: DateTimeFormat;\r\n };\r\n}\r\n\r\ninterface String {\r\n /**\r\n * Determines whether two strings are equivalent in the current or specified locale.\r\n * @param that String to compare to target string\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.\r\n * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.\r\n */\r\n localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number;\r\n}\r\n\r\ninterface Number {\r\n /**\r\n * Converts a number to a string by using the current or specified locale.\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\r\n * @param options An object that contains one or more properties that specify comparison options.\r\n */\r\n toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;\r\n}\r\n\r\ninterface Date {\r\n /**\r\n * Converts a date and time to a string by using the current or specified locale.\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\r\n * @param options An object that contains one or more properties that specify comparison options.\r\n */\r\n toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\r\n /**\r\n * Converts a date to a string by using the current or specified locale.\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\r\n * @param options An object that contains one or more properties that specify comparison options.\r\n */\r\n toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\r\n\r\n /**\r\n * Converts a time to a string by using the current or specified locale.\r\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\r\n * @param options An object that contains one or more properties that specify comparison options.\r\n */\r\n toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\r\n}\r\n"; const simpleFunctions = [ ["add", "+"], ["sub", "-"], ["div", "/"], ["mul", "*"], ["mod", "%"], ["bitand", "&"], ["bitor", "|"], ["bitxor", "^"], ["lshift", "<<"], ["rshift", ">>"] ]; const singleFunctions = [ ["bitnot", (a) => `~${a}`], ["negate", (a) => `-${a}`], ["positive", "Math.abs"], ["abs", "Math.abs"], ["floor", "Math.floor"], ["ceil", "Math.ceil"], ["round", "Math.round"], ["sign", "Math.sign"], ["cos", "Math.cos"], ["sin", "Math.sin"], ["tan", "Math.tan"], ["acos", "Math.acos"], ["asin", "Math.asin"], ["atan", "Math.atan"], ["cosh", "Math.cosh"], ["sinh", "Math.sinh"], ["tanh", "Math.tanh"], ["acosh", "Math.acosh"], ["asinh", "Math.asinh"], ["atanh", "Math.atanh"], ["exp", "Math.exp"], ["log", "Math.log"], ["log2", "Math.log2"], ["log10", "Math.log10"], ["sqrt", "Math.sqrt"] ]; const makeVectors = [ ["int", "|0"], ["float", ""], ["uint", ">>>0"] ]; const simpleFuncMap = new Map(simpleFunctions); const singleFuncMap = new Map(singleFunctions); const makeVectorsMap = new Map(makeVectors); function getTypeFallback(checker, t) { let n = (t.aliasSymbol || t.getSymbol())?.escapedName; if (!n && t.intrinsicName) n = t.intrinsicName; if (typeof n !== "string") { let props = t.getApparentProperties(); if (props.length > 0) { for (let p of props) { if (p.escapedName.toString() === "_opaque_int") return "int"; if (p.escapedName.toString() === "_opaque_float") return "float"; if (p.escapedName.toString() === "_opaque_uint") return "uint"; } } let btype = t.getBaseTypes(); if (btype && btype.length > 0) { for (let b of btype) { let tn = getTypeFallback(checker, b); if (tn) return tn; } return null; } } else { return n; } } function getVectorLen(checker, type2) { let typeFall = getTypeFallback(checker, type2); if (type2.flags & (ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike | ts.TypeFlags.NumberLiteral) || typeFall == "int" || typeFall == "float" || typeFall == "uint") { return 1; } else if (typeFall == "int2" || typeFall == "float2" || typeFall == "uint2") { return 2; } else if (typeFall == "int3" || typeFall == "float3" || typeFall == "uint3") { return 3; } else if (typeFall == "int4" || typeFall == "float4" || typeFall == "uint4") { return 4; } return 0; } function isArrayType(type2, checker) { return checker.isTupleType(type2) || checker.isArrayType(type2); } const updateIntegerMixing = (getChecker) => (context2) => { let [checker, env2, loads] = getChecker(); loads.clear(); env2.libraries.clear(); return (rootNode) => { const { factory: factory2 } = context2; function visit(node2) { if (!node2) { return node2; } if (ts.isCallExpression(node2)) { let sig = checker.getResolvedSignature(node2); let returnType = checker.getReturnTypeOfSignature(sig); let symbol = returnType.aliasSymbol || returnType.getSymbol(); let expressionText = node2.expression.getText(); let ops = { gte: ts.SyntaxKind.GreaterThanEqualsToken, lte: ts.SyntaxKind.LessThanEqualsToken, gt: ts.SyntaxKind.GreaterThanToken, lt: ts.SyntaxKind.LessThanToken, eq: ts.SyntaxKind.EqualsEqualsToken, neq: ts.SyntaxKind.ExclamationEqualsToken, and: ts.SyntaxKind.AmpersandAmpersandToken, or: ts.SyntaxKind.BarBarToken }; if (expressionText == "physics.engine2d") { env2.libraries.add("rapier2d"); } if (expressionText == "physics.engine3d") { env2.libraries.add("rapier3d"); } if (expressionText == "load") { if (!loads.has(rootNode.fileName)) { loads.set(rootNode.fileName, []); } if (node2.arguments.length > 0 && ts.isStringLiteral(node2.arguments[0])) { let realId = env2.assetMappings.get(node2.arguments[0].text); loads.get(rootNode.fileName).push(node2.arguments[0].text); if (realId) return factory2.createCallExpression(factory2.createIdentifier("load"), void 0, [ factory2.createStringLiteral(realId[0]) ]); } return node2; } if (expressionText.endsWith("__index")) { let innerExpr = node2.expression; if (ts.isPropertyAccessExpression(innerExpr)) { let left = innerExpr.expression; let leftType = checker.getTypeAtLocation(left); let leftStr = checker.typeToString(leftType); if (isArrayType(leftType, checker)) { return factory2.createElementAccessExpression(visit(left), visit(node2.arguments[0])); } if (leftStr == "buffer") { return factory2.createElementAccessExpression( factory2.createPropertyAccessExpression(visit(left), "floatArray"), visit(node2.arguments[0]) ); } else if (leftStr == "buffer") { return factory2.createElementAccessExpression( factory2.createPropertyAccessExpression(visit(left), "intArray"), visit(node2.arguments[0]) ); } else if (leftStr == "buffer") { return factory2.createElementAccessExpression( factory2.createPropertyAccessExpression(visit(left), "uintArray"), visit(node2.arguments[0]) ); } else if (!leftType.getProperty("__index")) { console.log("Optim no __index", leftStr, leftType); return factory2.createElementAccessExpression(visit(left), visit(node2.arguments[0])); } } } if (expressionText.startsWith("__.") && ops[expressionText.replace("__.", "")]) { if (node2.arguments.length != 2) { return visit(node2.arguments[0]); } else { let left = node2.arguments[0]; let right = node2.arguments[1]; let leftLen = getVectorLen(checker, checker.getTypeAtLocation(left)); let rightLen = getVectorLen(checker, checker.getTypeAtLocation(right)); if (leftLen == 1 && rightLen == 1) { return factory2.createBinaryExpression( visit(node2.arguments[0]), ops[expressionText.replace("__.", "")], visit(node2.arguments[1]) ); } } } if (simpleFuncMap.has(expressionText.replace("__.", ""))) { let left = node2.arguments[0]; let right = node2.arguments[1]; let leftLen = getVectorLen(checker, checker.getTypeAtLocation(left)); let rightLen = getVectorLen(checker, checker.getTypeAtLocation(right)); if (leftLen == 1 && rightLen == 1) { let funcDef = simpleFuncMap.get(expressionText.replace("__.", "")); if (typeof funcDef == "string") { let tokenKinds = { "+": ts.SyntaxKind.PlusToken, "-": ts.SyntaxKind.MinusToken, "/": ts.SyntaxKind.SlashToken, "*": ts.SyntaxKind.AsteriskToken, "%": ts.SyntaxKind.PercentToken, "&": ts.SyntaxKind.AmpersandToken, "|": ts.SyntaxKind.BarToken, "^": ts.SyntaxKind.CaretToken, "<<": ts.SyntaxKind.LessThanLessThanToken, ">>": ts.SyntaxKind.GreaterThanGreaterThanToken }; return factory2.createBinaryExpression( visit(left), factory2.createToken(tokenKinds[funcDef]), visit(right) ); } } if (leftLen > 0 && rightLen > 0) { let leftHoist = factory2.createTempVariable(context2.hoistVariableDeclaration, true); let rightHoist = factory2.createTempVariable(context2.hoistVariableDeclaration, true); let leftAss = factory2.createAssignment(leftHoist, visit(left)); let rightAss = factory2.createAssignment(rightHoist, visit(right)); let tokenKinds = { mul: ts.SyntaxKind.AsteriskToken, div: ts.SyntaxKind.SlashToken, add: ts.SyntaxKind.PlusToken, sub: ts.SyntaxKind.MinusToken, mod: ts.SyntaxKind.PercentToken, and: ts.SyntaxKind.AmpersandToken, or: ts.SyntaxKind.BarToken, xor: ts.SyntaxKind.CaretToken, lshift: ts.SyntaxKind.LessThanLessThanToken, rshift: ts.SyntaxKind.GreaterThanGreaterThanToken }; let innerElems = []; if (leftLen == rightLen) { for (let i = 0; i < leftLen; i++) { innerElems.push( factory2.createBinaryExpression( factory2.createElementAccessExpression( leftHoist, factory2.createNumericLiteral(i) ), factory2.createToken(tokenKinds[expressionText.replace("__.", "")]), factory2.createElementAccessExpression( rightHoist, factory2.createNumericLiteral(i) ) ) ); } } else if (leftLen == 1) { for (let i = 0; i < rightLen; i++) { innerElems.push( factory2.createBinaryExpression( leftHoist, factory2.createToken(tokenKinds[expressionText.replace("__.", "")]), factory2.createElementAccessExpression( rightHoist, factory2.createNumericLiteral(i) ) ) ); } } else if (rightLen == 1) { for (let i = 0; i < leftLen; i++) { innerElems.push( factory2.createBinaryExpression( factory2.createElementAccessExpression( leftHoist, factory2.createNumericLiteral(i) ), factory2.createToken(tokenKinds[expressionText.replace("__.", "")]), rightHoist ) ); } } let expr = factory2.createArrayLiteralExpression(innerElems); return factory2.createCommaListExpression([leftAss, rightAss, expr]); } } if (singleFuncMap.has(expressionText.replace("__.", ""))) { let left = node2.arguments[0]; let leftLen = getVectorLen(checker, checker.getTypeAtLocation(left)); let funcDef = singleFuncMap.get(expressionText.replace("__.", "")); if (leftLen == 1) { if (typeof funcDef == "string") { return factory2.createCallExpression( factory2.createIdentifier(funcDef), [], [visit(left)] ); } } if (leftLen > 0) { if (typeof funcDef == "string") { let leftHoist = factory2.createTempVariable(context2.hoistVariableDeclaration, true); let leftAss = factory2.createAssignment(leftHoist, visit(left)); let innerElems = []; for (let i = 0; i < leftLen; i++) { innerElems.push( factory2.createCallExpression( factory2.createIdentifier(funcDef), [], [ factory2.createElementAccessExpression( leftHoist, factory2.createNumericLiteral(i) ) ] ) ); } let expr = factory2.createArrayLiteralExpression(innerElems); return factory2.createCommaListExpression([leftAss, expr]); } else { return factory2.createParenthesizedExpression( factory2.createCallExpression( factory2.createPropertyAccessExpression( factory2.createPropertyAccessExpression( factory2.createIdentifier("__"), factory2.createIdentifier("FM") ), factory2.createIdentifier(expressionText.replace("__.", "") + `_${leftLen}`) ), [], [visit(left)] ) ); } } } if (expressionText == "__.swizzle" && node2.arguments.length == 2) { let index = { x: 0, y: 1, z: 2, w: 3, r: 0, g: 1, b: 2, a: 3 }; let vecLen = getVectorLen(checker, checker.getTypeAtLocation(node2.arguments[0])); if (vecLen != 0) { let swizzleLiteral = node2.arguments[1]; let swiz = ""; if (ts.isStringLiteral(swizzleLiteral)) { swiz = swizzleLiteral.text; } if (swiz.length == 1) { return factory2.createElementAccessExpression( visit(node2.arguments[0]), factory2.createNumericLiteral(index[swiz]) ); } let temp = factory2.createTempVariable(context2.hoistVariableDeclaration, true); let tempAss = factory2.createAssignment(temp, visit(node2.arguments[0])); let elems = []; for (let i = 0; i < swiz.length; i++) { if (vecLen == 1) { elems.push(temp); } else { elems.push( factory2.createElementAccessExpression( temp, factory2.createNumericLiteral(index[swiz[i]]) ) ); } } return factory2.createCommaListExpression([ tempAss, factory2.createArrayLiteralExpression(elems) ]); } } if (expressionText.startsWith("__.") && makeVectorsMap.has(expressionText.replace("__.", "").replace(/\d/g, ""))) { let arg_lengths = node2.arguments.map( (x) => getVectorLen(checker, checker.getTypeAtLocation(x)) ); let matches = expressionText.match(/\d/g); if (matches) { let targetLen = matches[0]; let targetName = expressionText.replace("__.", "").replace(/\d/g, ""); return factory2.createCallExpression( factory2.createPropertyAccessExpression( factory2.createPropertyAccessExpression( factory2.createIdentifier("__"), factory2.createIdentifier("FM") ), factory2.createIdentifier(targetName + `_${targetLen}_${arg_lengths.join("_")}`) ), [], node2.arguments.map((x) => ts.visitEachChild(x, visit, context2)) ); } else { if (expressionText == "__.float") { return ts.visitEachChild(node2.arguments[0], visit, context2); } else if (expressionText == "__.int") { return factory2.createParenthesizedExpression( factory2.createBinaryExpression( ts.visitEachChild(node2.arguments[0], visit, context2), factory2.createToken(ts.SyntaxKind.BarToken), factory2.createNumericLiteral("0") ) ); } else if (expressionText == "__.uint") { return factory2.createParenthesizedExpression( factory2.createBinaryExpression( ts.visitEachChild(node2.arguments[0], visit, context2), factory2.createToken(ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken), factory2.createNumericLiteral("0") ) ); } } } if (symbol && symbol.name == "int") { return factory2.createParenthesizedExpression( factory2.createBinaryExpression( ts.visitEachChild(node2, visit, context2), factory2.createToken(ts.SyntaxKind.BarToken), factory2.createNumericLiteral("0") ) ); } else if (symbol && (symbol.name == "int2" || symbol.name == "int3" || symbol.name == "int4")) { return factory2.createCallExpression( factory2.createPropertyAccessExpression( factory2.createIdentifier("__"), factory2.createIdentifier("intifyVector") ), [], [ts.visitEachChild(node2, visit, context2)] ); } } return ts.visitEachChild(node2, visit, context2); } rootNode = ts.visitNode(rootNode, visit); return rootNode; }; }; const updateClassStructure = (getChecker) => (context2) => { let checker = getChecker(); return (rootNode) => { const { factory: factory2 } = context2; function visit(node2) { if (ts.isClassDeclaration(node2)) { return [ factory2.updateClassDeclaration( node2, node2.modifiers, node2.name, node2.typeParameters, node2.heritageClauses, [ ...node2.members.map((m) => ts.visitEachChild(m, visit, context2)), factory2.createMethodDeclaration( void 0, void 0, factory2.createIdentifier("_getStructure"), void 0, void 0, [], void 0, factory2.createBlock( [ factory2.createReturnStatement( factory2.createCallExpression( factory2.createPropertyAccessExpression( factory2.createIdentifier("JSON"), "parse" ), void 0, [ factory2.createStringLiteral( JSON.stringify( translateType(checker, checker.getTypeAtLocation(node2), true) ) ) ] ) ) ], true ) ) ] ), factory2.createCallExpression( factory2.createIdentifier("__shadeup_register_struct"), void 0, [ factory2.createCallExpression( factory2.createPropertyAccessExpression(factory2.createIdentifier("JSON"), "parse"), void 0, [ factory2.createStringLiteral( JSON.stringify(translateType(checker, checker.getTypeAtLocation(node2), true)) ) ] ), factory2.createIdentifier(node2.name.text) ] ) ]; } else if (ts.isCallExpression(node2)) { let symbol = checker.getSymbolAtLocation(node2.expression); if (symbol && symbol.name == "buffer") { let isInScope = false; let sym = checker.getTypeAtLocation(node2.typeArguments[0]).getSymbol(); if (sym) { let syms = checker.getSymbolsInScope( node2, ts.SymbolFlags.Alias | ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Type ); for (let s of syms) { if (s == sym) { isInScope = true; break; } } } return factory2.updateCallExpression(node2, node2.expression, node2.typeArguments, [ ...node2.arguments, factory2.createObjectLiteralExpression([ factory2.createSpreadAssignment( factory2.createCallExpression( factory2.createPropertyAccessExpression(factory2.createIdentifier("JSON"), "parse"), void 0, [ factory2.createStringLiteral( JSON.stringify( translateType( checker, checker.getTypeAtLocation(node2.typeArguments[0]), true ) ) ) ] ) ), ...isInScope ? [ factory2.createPropertyAssignment( "__type", factory2.createIdentifier( checker.getTypeAtLocation(node2.typeArguments[0]).getSymbol().getName() ) ) ] : [] ]) ]); } } return ts.visitEachChild(node2, visit, context2); } return ts.visitNode(rootNode, visit); }; }; const updateAsyncCalls = (getChecker) => (context2) => { let [checker, env2] = getChecker(); return (rootNode) => { const { factory: factory2 } = context2; function visit(node2) { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let graphNodeName = getFunctionNodeName(funcDeclar); let graphNode = env2.tagGraph.getNode(graphNodeName); if (graphNode) { if (!isInShader$1(node2) && !isInRoot(node2)) { if (graphNode.tags.includes("async")) { return factory2.createAwaitExpression(ts.visitEachChild(node2, visit, context2)); } } } } } if (node2.expression && ts.isIdentifier(node2.expression) && node2.expression.text.startsWith("shader_start_shd_")) { let inner = node2.arguments[0]; if (ts.isAsExpression(inner)) { inner = inner.expression; } if (ts.isCallExpression(inner) && inner.arguments[0]) { let shaderKey = inner.arguments[0]; if (ts.isStringLiteral(shaderKey)) { let key = shaderKey.text; let file = env2.files.find((x) => x.path == rootNode.fileName); let shader = file.shaders.find((x) => x.glsl.key == "shd_" + key); if (shader) { let params = []; for (let param of Object.keys(shader.glsl.locals)) { shader.glsl.locals[param]; let symbols = checker.getSymbolsInScope(node2, ts.SymbolFlags.Variable); let symbol = symbols.find((x) => x.name == param); let findInside = (node22) => { if (ts.isIdentifier(node22) && checker.getSymbolAtLocation(node22) == symbol) { return node22; } return ts.forEachChild(node22, findInside); }; let found = findInside(inner.arguments[1]); if (found) { params.push([`_ext_uniform_local_${param}`, found]); } else { params.push([`_ext_uniform_local_${param}`, factory2.createIdentifier(param)]); } } for (let param of Object.keys(shader.glsl.globals)) { let u = shader.glsl.globals[param]; params.push([ `_ext_uniform_global_${param}`, factory2.createCallExpression( factory2.createIdentifier("globalVarGet"), void 0, [ factory2.createStringLiteral(cleanName(u.fileName)), factory2.createStringLiteral(param) ] ) ]); } let innerArg = inner.arguments[1]; if (ts.isAsExpression(innerArg)) { innerArg = innerArg.expression; } if (ts.isParenthesizedExpression(innerArg)) { innerArg = innerArg.expression; } if (!ts.isArrowFunction(innerArg)) { throw new Error("Expected arrow function"); } let arrow = innerArg; let mods = ts.getModifiers(arrow) || []; return factory2.createCallExpression( factory2.createIdentifier("__shadeup_make_shader_inst"), [], [ ...[ factory2.createStringLiteral(shader.glsl.key), factory2.createObjectLiteralExpression( params.map(([name, value]) => factory2.createPropertyAssignment(name, value)) ), factory2.updateArrowFunction( arrow, [...mods, factory2.createModifier(ts.SyntaxKind.AsyncKeyword)], arrow.typeParameters, arrow.parameters, arrow.type, arrow.equalsGreaterThanToken, arrow.body ) ], ...inner.arguments.length == 3 ? [inner.arguments[2]] : [] ] ); } } } } } if (ts.isFunctionDeclaration(node2)) { let graphNodeName = getFunctionNodeName(node2, rootNode); let graphNode = env2.tagGraph.getNode(graphNodeName); if (graphNode) { if (graphNode.tags.includes("async")) { let mods = ts.getModifiers(node2) || []; return factory2.updateFunctionDeclaration( node2, [...mods, factory2.createModifier(ts.SyntaxKind.AsyncKeyword)], node2.asteriskToken, node2.name, node2.typeParameters, node2.parameters, node2.type, ts.visitEachChild(node2.body, visit, context2) ); } } } if (ts.isClassDeclaration(node2)) { ts.forEachChild(node2, (n) => { if (ts.isMethodDeclaration(n)) { let graphNodeName = getFunctionNodeName(n, rootNode); let graphNode = env2.tagGraph.getNode(graphNodeName); if (graphNode) { if (graphNode.tags.includes("async")) { let mods = ts.getModifiers(node2) || []; return factory2.updateMethodDeclaration( n, [...mods, factory2.createModifier(ts.SyntaxKind.AsyncKeyword)], n.asteriskToken, n.name, n.questionToken, n.typeParameters, n.parameters, n.type, ts.visitEachChild(n.body, visit, context2) ); } } } }); } return ts.visitEachChild(node2, visit, context2); } return ts.visitNode(rootNode, visit); }; }; async function makeTypescriptEnvironment(shadeupEnv) { const shouldCache = false; let fsMap = await vfs.createDefaultMapFromCDN( { target: ts.ScriptTarget.ES2015, lib: ["es5", "es2015", "es2015.promise"] }, "3.7.3", shouldCache, ts ); fsMap = /* @__PURE__ */ new Map(); fsMap.set("/file.ts", ""); fsMap.set("/std_math.ts", stdMath); fsMap.set("/static-math.ts", stdStaticMath); fsMap.set("/std___std_all.ts", stdAll); fsMap.set("/global.d.ts", globalDTS); const system = vfs.createSystem(fsMap); system.$fsMap = fsMap; system.writeFile("/std___std_all.ts", stdAll); system.writeFile("/std_math.ts", stdMath); system.writeFile("/static-math.ts", stdStaticMath); system.writeFile("/global.d.ts", globalDTS); const compilerOpts = { module: ts.ModuleKind.AMD, removeComments: false, lib: ["es5"], //noImplicitUseStrict: true, alwaysStrict: true, strictNullChecks: true, strictFunctionTypes: true, strictBindCallApply: true, strictPropertyInitialization: true, noImplicitThis: true, strict: true, noImplicitAny: true, noImplicitReturns: true, declaration: shadeupEnv.options?.declaration ?? false }; if (shadeupEnv.options.esnext) ; let transformers = { before: [ updateIntegerMixing(() => [ env2.languageService.getProgram().getTypeChecker(), shadeupEnv, shadeupEnv.loads ]), updateAsyncCalls(() => [env2.languageService.getProgram().getTypeChecker(), shadeupEnv]), // updateAsyncArrows(() => [env.languageService.getProgram().getTypeChecker(), shadeupEnv]), updateClassStructure(() => env2.languageService.getProgram().getTypeChecker()) ] }; const env2 = vfs.createVirtualTypeScriptEnvironment( system, Object.keys(fsMap), ts, compilerOpts, transformers ); env2.createFile("/std___std_all.ts", stdAll); env2.createFile("/std_math.ts", stdMath); env2.createFile("/static-math.ts", stdStaticMath); env2.createFile("/global.d.ts", globalDTS); return { env: env2, fsMap, system }; } var DIFF_DELETE = -1; var DIFF_INSERT = 1; var DIFF_EQUAL = 0; function diff_main(text1, text2, cursor_pos, _fix_unicode) { if (text1 === text2) { if (text1) { return [[DIFF_EQUAL, text1]]; } return []; } if (cursor_pos != null) { var editdiff = find_cursor_edit_diff(text1, text2, cursor_pos); if (editdiff) { return editdiff; } } var commonlength = diff_commonPrefix(text1, text2); var commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); commonlength = diff_commonSuffix(text1, text2); var commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text2 = text2.substring(0, text2.length - commonlength); var diffs = diff_compute_(text1, text2); if (commonprefix) { diffs.unshift([DIFF_EQUAL, commonprefix]); } if (commonsuffix) { diffs.push([DIFF_EQUAL, commonsuffix]); } diff_cleanupMerge(diffs, _fix_unicode); return diffs; } function diff_compute_(text1, text2) { var diffs; if (!text1) { return [[DIFF_INSERT, text2]]; } if (!text2) { return [[DIFF_DELETE, text1]]; } var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; var i = longtext.indexOf(shorttext); if (i !== -1) { diffs = [ [DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)] ]; if (text1.length > text2.length) { diffs[0][0] = diffs[2][0] = DIFF_DELETE; } return diffs; } if (shorttext.length === 1) { return [ [DIFF_DELETE, text1], [DIFF_INSERT, text2] ]; } var hm = diff_halfMatch_(text1, text2); if (hm) { var text1_a = hm[0]; var text1_b = hm[1]; var text2_a = hm[2]; var text2_b = hm[3]; var mid_common = hm[4]; var diffs_a = diff_main(text1_a, text2_a); var diffs_b = diff_main(text1_b, text2_b); return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); } return diff_bisect_(text1, text2); } function diff_bisect_(text1, text2) { var text1_length = text1.length; var text2_length = text2.length; var max_d = Math.ceil((text1_length + text2_length) / 2); var v_offset = max_d; var v_length = 2 * max_d; var v1 = new Array(v_length); var v2 = new Array(v_length); for (var x = 0; x < v_length; x++) { v1[x] = -1; v2[x] = -1; } v1[v_offset + 1] = 0; v2[v_offset + 1] = 0; var delta = text1_length - text2_length; var front = delta % 2 !== 0; var k1start = 0; var k1end = 0; var k2start = 0; var k2end = 0; for (var d = 0; d < max_d; d++) { for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { var k1_offset = v_offset + k1; var x1; if (k1 === -d || k1 !== d && v1[k1_offset - 1] < v1[k1_offset + 1]) { x1 = v1[k1_offset + 1]; } else { x1 = v1[k1_offset - 1] + 1; } var y1 = x1 - k1; while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) === text2.charAt(y1)) { x1++; y1++; } v1[k1_offset] = x1; if (x1 > text1_length) { k1end += 2; } else if (y1 > text2_length) { k1start += 2; } else if (front) { var k2_offset = v_offset + delta - k1; if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) { var x2 = text1_length - v2[k2_offset]; if (x1 >= x2) { return diff_bisectSplit_(text1, text2, x1, y1); } } } } for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { var k2_offset = v_offset + k2; var x2; if (k2 === -d || k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1]) { x2 = v2[k2_offset + 1]; } else { x2 = v2[k2_offset - 1] + 1; } var y2 = x2 - k2; while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) === text2.charAt(text2_length - y2 - 1)) { x2++; y2++; } v2[k2_offset] = x2; if (x2 > text1_length) { k2end += 2; } else if (y2 > text2_length) { k2start += 2; } else if (!front) { var k1_offset = v_offset + delta - k2; if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] !== -1) { var x1 = v1[k1_offset]; var y1 = v_offset + x1 - k1_offset; x2 = text1_length - x2; if (x1 >= x2) { return diff_bisectSplit_(text1, text2, x1, y1); } } } } } return [ [DIFF_DELETE, text1], [DIFF_INSERT, text2] ]; } function diff_bisectSplit_(text1, text2, x, y) { var text1a = text1.substring(0, x); var text2a = text2.substring(0, y); var text1b = text1.substring(x); var text2b = text2.substring(y); var diffs = diff_main(text1a, text2a); var diffsb = diff_main(text1b, text2b); return diffs.concat(diffsb); } function diff_commonPrefix(text1, text2) { if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { return 0; } var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } if (is_surrogate_pair_start(text1.charCodeAt(pointermid - 1))) { pointermid--; } return pointermid; } function diff_commonSuffix(text1, text2) { if (!text1 || !text2 || text1.slice(-1) !== text2.slice(-1)) { return 0; } var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } if (is_surrogate_pair_end(text1.charCodeAt(text1.length - pointermid))) { pointermid--; } return pointermid; } function diff_halfMatch_(text1, text2) { var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; } function diff_halfMatchI_(longtext2, shorttext2, i) { var seed = longtext2.substring(i, i + Math.floor(longtext2.length / 4)); var j = -1; var best_common = ""; var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; while ((j = shorttext2.indexOf(seed, j + 1)) !== -1) { var prefixLength = diff_commonPrefix(longtext2.substring(i), shorttext2.substring(j)); var suffixLength = diff_commonSuffix(longtext2.substring(0, i), shorttext2.substring(0, j)); if (best_common.length < suffixLength + prefixLength) { best_common = shorttext2.substring(j - suffixLength, j) + shorttext2.substring(j, j + prefixLength); best_longtext_a = longtext2.substring(0, i - suffixLength); best_longtext_b = longtext2.substring(i + prefixLength); best_shorttext_a = shorttext2.substring(0, j - suffixLength); best_shorttext_b = shorttext2.substring(j + prefixLength); } } if (best_common.length * 2 >= longtext2.length) { return [best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common]; } else { return null; } } var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); var hm; if (!hm1 && !hm2) { return null; } else if (!hm2) { hm = hm1; } else if (!hm1) { hm = hm2; } else { hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } var text1_a, text1_b, text2_a, text2_b; if (text1.length > text2.length) { text1_a = hm[0]; text1_b = hm[1]; text2_a = hm[2]; text2_b = hm[3]; } else { text2_a = hm[0]; text2_b = hm[1]; text1_a = hm[2]; text1_b = hm[3]; } var mid_common = hm[4]; return [text1_a, text1_b, text2_a, text2_b, mid_common]; } function diff_cleanupMerge(diffs, fix_unicode) { diffs.push([DIFF_EQUAL, ""]); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ""; var text_insert = ""; var commonlength; while (pointer < diffs.length) { if (pointer < diffs.length - 1 && !diffs[pointer][1]) { diffs.splice(pointer, 1); continue; } switch (diffs[pointer][0]) { case DIFF_INSERT: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: var previous_equality = pointer - count_insert - count_delete - 1; if (fix_unicode) { if (previous_equality >= 0 && ends_with_pair_start(diffs[previous_equality][1])) { var stray = diffs[previous_equality][1].slice(-1); diffs[previous_equality][1] = diffs[previous_equality][1].slice(0, -1); text_delete = stray + text_delete; text_insert = stray + text_insert; if (!diffs[previous_equality][1]) { diffs.splice(previous_equality, 1); pointer--; var k = previous_equality - 1; if (diffs[k] && diffs[k][0] === DIFF_INSERT) { count_insert++; text_insert = diffs[k][1] + text_insert; k--; } if (diffs[k] && diffs[k][0] === DIFF_DELETE) { count_delete++; text_delete = diffs[k][1] + text_delete; k--; } previous_equality = k; } } if (starts_with_pair_end(diffs[pointer][1])) { var stray = diffs[pointer][1].charAt(0); diffs[pointer][1] = diffs[pointer][1].slice(1); text_delete += stray; text_insert += stray; } } if (pointer < diffs.length - 1 && !diffs[pointer][1]) { diffs.splice(pointer, 1); break; } if (text_delete.length > 0 || text_insert.length > 0) { if (text_delete.length > 0 && text_insert.length > 0) { commonlength = diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if (previous_equality >= 0) { diffs[previous_equality][1] += text_insert.substring(0, commonlength); } else { diffs.splice(0, 0, [DIFF_EQUAL, text_insert.substring(0, commonlength)]); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } commonlength = diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring(0, text_insert.length - commonlength); text_delete = text_delete.substring(0, text_delete.length - commonlength); } } var n = count_insert + count_delete; if (text_delete.length === 0 && text_insert.length === 0) { diffs.splice(pointer - n, n); pointer = pointer - n; } else if (text_delete.length === 0) { diffs.splice(pointer - n, n, [DIFF_INSERT, text_insert]); pointer = pointer - n + 1; } else if (text_insert.length === 0) { diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete]); pointer = pointer - n + 1; } else { diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete], [DIFF_INSERT, text_insert]); pointer = pointer - n + 2; } } if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } } if (diffs[diffs.length - 1][1] === "") { diffs.pop(); } var changes = false; pointer = 1; while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } if (changes) { diff_cleanupMerge(diffs, fix_unicode); } } function is_surrogate_pair_start(charCode) { return charCode >= 55296 && charCode <= 56319; } function is_surrogate_pair_end(charCode) { return charCode >= 56320 && charCode <= 57343; } function starts_with_pair_end(str) { return is_surrogate_pair_end(str.charCodeAt(0)); } function ends_with_pair_start(str) { return is_surrogate_pair_start(str.charCodeAt(str.length - 1)); } function remove_empty_tuples(tuples) { var ret = []; for (var i = 0; i < tuples.length; i++) { if (tuples[i][1].length > 0) { ret.push(tuples[i]); } } return ret; } function make_edit_splice(before, oldMiddle, newMiddle, after) { if (ends_with_pair_start(before) || starts_with_pair_end(after)) { return null; } return remove_empty_tuples([ [DIFF_EQUAL, before], [DIFF_DELETE, oldMiddle], [DIFF_INSERT, newMiddle], [DIFF_EQUAL, after] ]); } function find_cursor_edit_diff(oldText, newText, cursor_pos) { var oldRange = typeof cursor_pos === "number" ? { index: cursor_pos, length: 0 } : cursor_pos.oldRange; var newRange = typeof cursor_pos === "number" ? null : cursor_pos.newRange; var oldLength = oldText.length; var newLength = newText.length; if (oldRange.length === 0 && (newRange === null || newRange.length === 0)) { var oldCursor = oldRange.index; var oldBefore = oldText.slice(0, oldCursor); var oldAfter = oldText.slice(oldCursor); var maybeNewCursor = newRange ? newRange.index : null; editBefore: { var newCursor = oldCursor + newLength - oldLength; if (maybeNewCursor !== null && maybeNewCursor !== newCursor) { break editBefore; } if (newCursor < 0 || newCursor > newLength) { break editBefore; } var newBefore = newText.slice(0, newCursor); var newAfter = newText.slice(newCursor); if (newAfter !== oldAfter) { break editBefore; } var prefixLength = Math.min(oldCursor, newCursor); var oldPrefix = oldBefore.slice(0, prefixLength); var newPrefix = newBefore.slice(0, prefixLength); if (oldPrefix !== newPrefix) { break editBefore; } var oldMiddle = oldBefore.slice(prefixLength); var newMiddle = newBefore.slice(prefixLength); return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldAfter); } editAfter: { if (maybeNewCursor !== null && maybeNewCursor !== oldCursor) { break editAfter; } var cursor = oldCursor; var newBefore = newText.slice(0, cursor); var newAfter = newText.slice(cursor); if (newBefore !== oldBefore) { break editAfter; } var suffixLength = Math.min(oldLength - cursor, newLength - cursor); var oldSuffix = oldAfter.slice(oldAfter.length - suffixLength); var newSuffix = newAfter.slice(newAfter.length - suffixLength); if (oldSuffix !== newSuffix) { break editAfter; } var oldMiddle = oldAfter.slice(0, oldAfter.length - suffixLength); var newMiddle = newAfter.slice(0, newAfter.length - suffixLength); return make_edit_splice(oldBefore, oldMiddle, newMiddle, oldSuffix); } } if (oldRange.length > 0 && newRange && newRange.length === 0) { replaceRange: { var oldPrefix = oldText.slice(0, oldRange.index); var oldSuffix = oldText.slice(oldRange.index + oldRange.length); var prefixLength = oldPrefix.length; var suffixLength = oldSuffix.length; if (newLength < prefixLength + suffixLength) { break replaceRange; } var newPrefix = newText.slice(0, prefixLength); var newSuffix = newText.slice(newLength - suffixLength); if (oldPrefix !== newPrefix || oldSuffix !== newSuffix) { break replaceRange; } var oldMiddle = oldText.slice(prefixLength, oldLength - suffixLength); var newMiddle = newText.slice(prefixLength, newLength - suffixLength); return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldSuffix); } } return null; } function diff(text1, text2, cursor_pos) { return diff_main(text1, text2, cursor_pos, true); } diff.INSERT = DIFF_INSERT; diff.DELETE = DIFF_DELETE; diff.EQUAL = DIFF_EQUAL; Array.prototype.enumerate = function() { let i = 0; let rv = []; for (let item of this) rv.push([i++, item]); return rv; }; Array.prototype.filter_map = function(fn) { return this.map(fn).filter((n) => n !== null); }; Array.prototype.max_by_key = function(fn) { const max2 = (self2) => { return Math.max.apply(null, self2); }; return max2(this.map(fn)); }; Array.prototype.chain = function(that) { return this.concat(that); }; Number.prototype.saturating_sub = function(n) { return this.valueOf() - n; }; Number.prototype.max = function(n) { return Math.max(this.valueOf(), n); }; Number.prototype.min = function(n) { return Math.min(this.valueOf(), n); }; class Option { static from(obj) { if (obj === void 0 || obj === null) return none(); return some(obj); } } class Some { constructor(value) { this.value = value; } map(fn) { return some(fn(this.value)); } map_or(d, fn) { return fn(this.value); } filter(fn) { if (fn(this.value)) return some(this.value); return none(); } or(d) { return this; } iter() { return [this.value]; } unwrap() { return this.value; } unwrap_or_else(d) { return this.unwrap(); } is_some() { return true; } is_none() { return false; } equal(other) { if (other.is_some()) return this.value === other.value; return false; } static is(o) { return o instanceof Some; } } class None { map(fn) { return none(); } map_or(d, fn) { return d; } filter(fn) { return none(); } or(d) { return d; } iter() { return []; } unwrap() { throw new Error("Unwrapped None"); } unwrap_or_else(d) { return d(); } is_some() { return false; } is_none() { return true; } equal(other) { return other.is_none(); } static is(o) { return o instanceof None; } } const some = (value) => { return new Some(value); }; const none = () => { return new None(); }; const isOption = (o) => { return o instanceof Some || o instanceof None; }; class Ok { constructor(value) { this.value = value; } map(fn) { return ok(fn(this.value)); } map_or(d, fn) { return ok(fn(this.value)); } or(d) { return this; } is_ok() { return true; } is_err() { return false; } unwrap() { return this.value; } unwrap_or_else(d) { return d(this.value); } static is(o) { return o instanceof Ok; } } class Err { constructor(value) { this.value = value; } map(fn) { return ok(fn(this.value)); } map_or(d, fn) { return ok(d); } or(d) { return d; } unwrap() { return this.value; } unwrap_or_else(d) { return d(this.value); } is_ok() { return false; } is_err() { return true; } static is(o) { return o instanceof Err; } } const ok = (value) => { return new Ok(value); }; const err = (value) => { return new Err(value); }; const isResult = (o) => { return o instanceof Ok || o instanceof Err; }; function binary_search_by_key(arr, x, fn) { let start = 0, end = arr.length - 1, mid, val; while (start < end) { mid = Math.floor((start + end) / 2); val = fn(arr[mid]); if (val === x) return ok(mid); else if (val < x) start = mid + 1; else end = mid - 1; } return err(get_sorted_index(arr, x, fn)); } function get_sorted_index(arr, x, fn) { let low = 0, high = arr.length; while (low < high) { let mid = low + high >>> 1; if (x > fn(arr[mid])) low = mid + 1; else high = mid; } return low; } function range(start, end) { let rv = []; while (start < end) { rv.push(start); start++; } return rv; } function* rangeIter(start, end) { while (start < end) { yield start; start++; } return; } const max = (self2) => { if (self2.length === 0) return void 0; return Math.max.apply(null, self2); }; const bton = (b) => b === true ? 1 : 0; function sort_by_key(arr, fn) { arr.sort((a, b) => { return fn(a) - fn(b); }); } function min_by_key(arr, fn) { let res = [Infinity, null]; for (let val of arr) { if (fn(val) < res[0]) { res = [fn(val), val]; } } return Option.from(res[1]); } const isString = (o) => typeof o === "string"; const isNumber = (o) => typeof o === "number"; const isBoolean = (o) => typeof o === "boolean"; const isCallback = (maybeFunction) => typeof maybeFunction === "function"; class Display { constructor(value) { this.value = typeof value === "string" ? value : value.value; } fg(color) { if (isOption(color)) { let func = color.is_some() ? color.unwrap() : (a) => a; this.value = func(this.value); } else if (isCallback(color)) { this.value = color(this.value); } return this; } bg(color) { if (isOption(color)) { let func = color.is_some() ? color.unwrap() : (a) => a; this.value = func(this.value); } else if (isCallback(color)) { this.value = color(this.value); } return this; } chars() { return this.value; } map(fn) { return new Display(fn(this.value)); } display() { return this.value; } toString() { return this.value; } unwrap_or_else(d) { return this.value ?? d(); } static { this.is = (o) => o instanceof Display; } } const isDisplay = Display.is; class Span { constructor(_start, _end) { this._start = _start; this._end = _end; } /// Get the identifier of the source that this span refers to. source() { return this.SourceId; } set start(value) { this._start = value; } get start() { return this._start; } set end(value) { this._end = value; } get end() { return this._end; } /// Get the length of this span (difference between the start of the span and the end of the span). len() { return this.end.saturating_sub(this.start); } /// Determine whether the span contains the given offset. contains(offset) { return range(this.start, this.end).includes(offset); } static { this.is = (o) => o instanceof Span; } static from(o) { if (isNumber(o[0]) && isNumber(o[1])) return new Span(o[0], o[1]); if (isString(o[0]) && Range.is(o[1])) { const s = new Span(o[1].start, o[1].end); s.SourceId = o[0]; return s; } throw new Error(`Invalid SpanInit`); } } Span.is; class Range extends Span { constructor() { super(...arguments); this.SourceId = null; } source() { return this.SourceId; } len() { return Math.abs(this.start - this.end); } contains(item) { return item >= this.start && item < this.end; } static is(o) { return o instanceof Range; } static from(o) { if (isNumber(o[0]) && isNumber(o[1])) return new Span(o[0], o[1]); if (isString(o[0]) && Range.is(o[1])) { const s = new Range(o[1].start, o[1].end); s.SourceId = o[0]; return s; } throw new Error(`Invalid SpanInit`); } static new(start, end) { return new Range(start, end); } } function ValueError(message) { var err2 = new Error(message); err2.name = "ValueError"; return err2; } function create(transformers) { return function(template) { var args = Array.prototype.slice.call(arguments, 1); var idx = 0; var state = "UNDEFINED"; return template.replace( /([{}])\1|[{](.*?)(?:!(.+?))?[}]/g, function(match2, literal, _key, xf) { if (literal != null) { return literal; } var key = _key; if (key.length > 0) { if (state === "IMPLICIT") { throw ValueError("cannot switch from implicit to explicit numbering"); } state = "EXPLICIT"; } else { if (state === "EXPLICIT") { throw ValueError("cannot switch from explicit to implicit numbering"); } state = "IMPLICIT"; key = String(idx); idx += 1; } var path = key.split("."); var value = (/^\d+$/.test(path[0]) ? path : ["0"].concat(path)).reduce( function(maybe, key2) { return maybe.reduce(function(_, x) { return x != null && key2 in Object(x) ? [typeof x[key2] === "function" ? x[key2]() : x[key2]] : []; }, []); }, [args] ).reduce(function(_, x) { return x; }, ""); if (xf == null) { return value; } else if (Object.prototype.hasOwnProperty.call(transformers, xf)) { return transformers[xf](value); } else { throw ValueError('no transformer named "' + xf + '"'); } } ); }; } var format$1 = create({}); format$1.create = create; format$1.extend = function(prototype, transformers) { var $format = create(transformers); prototype.format = function() { var args = Array.prototype.slice.call(arguments); args.unshift(this); return $format.apply(global, args); }; }; const stringFormatter = () => new class { constructor() { this.flags = 0; this.fill = ""; this.align = "Left"; this.width = none(); this.precision = none(); this.buf = mkStringWriter(); } unwrap() { return this.buf.unwrap(); } }(); class Show { constructor(self2) { this.self = self2; } fmt(f) { if (isOption(this.self)) { this.self.map((x) => new Show(x).fmt(f)); return; } if (isResult(this.self)) { this.self.map((x) => new Show(x).fmt(f)); return; } if (typeof this.self === "string") { write(f.buf, "{}", this.self); return; } if (Array.isArray(this.self) && this.self.length === 2) { if (isCallback(this.self[1])) { for (let x of this.self[0]) { const func = this.self[1]; func(f, x); } } else { for (let _ of range(0, this.self[1])) { write(f.buf, "{}", this.self[0]); } } } else { const x = this.self[0]; write(f.buf, "{}", x); return; } } static { this.is = (o) => o instanceof Show; } } const isShow = Show.is; function write(w, ...args) { w.write_fmt(format(...args.map(fromRust))); } function format(...args) { const [head, ...rest] = args.map(fromRust); return format$1(head, ...rest); } function fromRust(node2) { if (isDisplay(node2)) { return node2.display(); } if (isShow(node2)) { let f = stringFormatter(); node2.fmt(f); return f.unwrap(); } if (isOption(node2)) { return node2.unwrap_or_else(() => ""); } if (isResult(node2)) { return node2.unwrap_or_else(() => "<(Unwrap Err)>"); } return node2.toString(); } function writeln(w, ...args) { let val = format(...args.map(fromRust)); w.write_fmt(val); w.write_fmt("\n"); } function eprintln(...args) { console.error(format(...args)); } class StdoutWriter { write_str(s) { throw new Error("Function not implemented"); } write_char(c2) { throw new Error("Function not implemented"); } write_fmt(...args) { console.log(format(...args)); return ok(null); } } class StderrWriter { write_str(s) { throw new Error("Function not implemented"); } write_char(c2) { throw new Error("Function not implemented"); } write_fmt(...args) { process.stderr.write(format(...args)); return ok(null); } } class StringWriter { constructor() { this.value = []; } write_str(s) { this.value.push(s); return ok(null); } write_char(c2) { this.value.push(c2); return ok(null); } write_fmt(...args) { this.value.push(format(...args)); return ok(null); } map(fn) { return fn(this.unwrap()); } unwrap() { return this.value.join(""); } } const stdoutWriter = new StdoutWriter(); const stderrWriter = new StderrWriter(); const mkStringWriter = () => new StringWriter(); const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`; const styles$1 = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], gray: [90, 39], // Alias of `blackBright` grey: [90, 39], // Alias of `blackBright` redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgGray: [100, 49], // Alias of `bgBlackBright` bgGrey: [100, 49], // Alias of `bgBlackBright` bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; Object.keys(styles$1.modifier); const foregroundColorNames = Object.keys(styles$1.color); const backgroundColorNames = Object.keys(styles$1.bgColor); [...foregroundColorNames, ...backgroundColorNames]; function assembleStyles() { const codes = /* @__PURE__ */ new Map(); for (const [groupName, group] of Object.entries(styles$1)) { for (const [styleName, style] of Object.entries(group)) { styles$1[styleName] = { open: `\x1B[${style[0]}m`, close: `\x1B[${style[1]}m` }; group[styleName] = styles$1[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles$1, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles$1, "codes", { value: codes, enumerable: false }); styles$1.color.close = "\x1B[39m"; styles$1.bgColor.close = "\x1B[49m"; styles$1.color.ansi = wrapAnsi16(); styles$1.color.ansi256 = wrapAnsi256(); styles$1.color.ansi16m = wrapAnsi16m(); styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); Object.defineProperties(styles$1, { rgbToAnsi256: { value(red, green, blue) { if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round((red - 8) / 247 * 24) + 232; } return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); }, enumerable: false }, hexToRgb: { value(hex) { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map((character) => character + character).join(""); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ integer >> 16 & 255, integer >> 8 & 255, integer & 255 /* eslint-enable no-bitwise */ ]; }, enumerable: false }, hexToAnsi256: { value: (hex) => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)), enumerable: false }, ansi256ToAnsi: { value(code) { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = ((code - 232) * 10 + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = remainder % 6 / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false }, rgbToAnsi: { value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)), enumerable: false }, hexToAnsi: { value: (hex) => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)), enumerable: false } }); return styles$1; } const ansiStyles = assembleStyles(); const env = { FORCE_COLOR: "false" }; let flagForceColor; function envForceColor() { if ("FORCE_COLOR" in env) { if (env.FORCE_COLOR === "true") { return 1; } if (env.FORCE_COLOR === "false") { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== void 0) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if ("TF_BUILD" in env && "AGENT_NAME" in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === void 0) { return 0; } const min = forceColor || 0; if (env.TERM === "dumb") { return min; } if ("CI" in env) { if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) { return 3; } if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some( (sign) => sign in env ) || env.CI_NAME === "codeship") { return 1; } return min; } if ("TEAMCITY_VERSION" in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === "truecolor") { return 3; } if (env.TERM === "xterm-kitty") { return 3; } if ("TERM_PROGRAM" in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); switch (env.TERM_PROGRAM) { case "iTerm.app": { return version >= 3 ? 3 : 2; } case "Apple_Terminal": { return 2; } } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ("COLORTERM" in env) { return 1; } return min; } function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options }); return translateLevel(level); } const supportsColor = { stdout: createSupportsColor({ isTTY: false }), stderr: createSupportsColor({ isTTY: false }) }; function stringReplaceAll(string, substring, replacer) { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ""; do { returnValue += string.slice(endIndex, index) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { let endIndex = 0; let returnValue = ""; do { const gotCR = string[index - 1] === "\r"; returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix; endIndex = index + 1; index = string.indexOf("\n", endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } const { stdout: stdoutColor, stderr: stderrColor } = supportsColor; const GENERATOR = Symbol("GENERATOR"); const STYLER = Symbol("STYLER"); const IS_EMPTY = Symbol("IS_EMPTY"); const levelMapping = ["ansi", "ansi", "ansi256", "ansi16m"]; const styles = /* @__PURE__ */ Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error("The `level` option should be an integer from 0 to 3"); } const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === void 0 ? colorLevel : options.level; }; const chalkFactory = (options) => { const chalk2 = (...strings) => strings.join(" "); applyOptions(chalk2, options); Object.setPrototypeOf(chalk2, createChalk.prototype); return chalk2; }; function createChalk(options) { return chalkFactory(options); } Object.setPrototypeOf(createChalk.prototype, Function.prototype); for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder( this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY] ); Object.defineProperty(this, styleName, { value: builder }); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this[STYLER], true); Object.defineProperty(this, "visible", { value: builder }); return builder; } }; const getModelAnsi = (model, level, type2, ...arguments_) => { if (model === "rgb") { if (level === "ansi16m") { return ansiStyles[type2].ansi16m(...arguments_); } if (level === "ansi256") { return ansiStyles[type2].ansi256(ansiStyles.rgbToAnsi256(...arguments_)); } return ansiStyles[type2].ansi(ansiStyles.rgbToAnsi(...arguments_)); } if (model === "hex") { return getModelAnsi("rgb", level, type2, ...ansiStyles.hexToRgb(...arguments_)); } return ansiStyles[type2][model](...arguments_); }; const usedModels = ["rgb", "hex", "ansi256"]; for (const model of usedModels) { styles[model] = { get() { const { level } = this; return function(...arguments_) { const styler = createStyler( getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansiStyles.color.close, this[STYLER] ); return createBuilder(this, styler, this[IS_EMPTY]); }; } }; const bgModel = "bg" + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const { level } = this; return function(...arguments_) { const styler = createStyler( getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansiStyles.bgColor.close, this[STYLER] ); return createBuilder(this, styler, this[IS_EMPTY]); }; } }; } const proto = Object.defineProperties(() => { }, { ...styles, level: { enumerable: true, get() { return this[GENERATOR].level; }, set(level) { this[GENERATOR].level = level; } } }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === void 0) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self2, _styler, _isEmpty) => { const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")); Object.setPrototypeOf(builder, proto); builder[GENERATOR] = self2; builder[STYLER] = _styler; builder[IS_EMPTY] = _isEmpty; return builder; }; const applyStyle = (self2, string) => { if (self2.level <= 0 || !string) { return self2[IS_EMPTY] ? "" : string; } let styler = self2[STYLER]; if (styler === void 0) { return string; } const { openAll, closeAll } = styler; if (string.includes("\x1B")) { while (styler !== void 0) { string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } const lfIndex = string.indexOf("\n"); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; Object.defineProperties(createChalk.prototype, styles); const chalk = createChalk(); createChalk({ level: stderrColor ? stderrColor.level : 0 }); const c = chalk; const colors = { blue: c.blue, green: c.green, red: c.red, yellow: c.yellow }; ({ blue: c.bgBlue, green: c.bgGreen, red: c.bgRed, yellow: c.bgYellow }); class Color { static { this.Fixed = Fixed; } } function Fixed(n) { return c.ansi256(n); } class Config { constructor(cross_gap, label_attach, compact, underlines, multiline_arrows, color, tab_width, char_set) { this.cross_gap = cross_gap; this.label_attach = label_attach; this.compact = compact; this.underlines = underlines; this.multiline_arrows = multiline_arrows; this.color = color; this.tab_width = tab_width; this.char_set = char_set; } static default() { return new Config( true, "Middle", false, true, true, true, 4, "Unicode" /* Unicode */ ); } /// When label lines cross one-another, should there be a gap? /// /// The alternative to this is to insert crossing characters. However, these interact poorly with label colours. /// /// If unspecified, this defaults to [`false`]. with_cross_gap(cross_gap) { this.cross_gap = cross_gap; return this; } /// Where should inline labels attach to their spans? /// /// If unspecified, this defaults to [`LabelAttach.Middle`]. with_label_attach(label_attach) { this.label_attach = label_attach; return this; } /// Should the report remove gaps to minimise used space? /// /// If unspecified, this defaults to [`false`]. with_compact(compact) { this.compact = compact; return this; } /// Should underlines be used for label span where possible? /// /// If unspecified, this defaults to [`true`]. with_underlines(underlines) { this.underlines = underlines; return this; } /// Should arrows be used to point to the bounds of multi-line spans? /// /// If unspecified, this defaults to [`true`]. with_multiline_arrows(multiline_arrows) { this.multiline_arrows = multiline_arrows; return this; } /// Should colored output should be enabled? /// /// If unspecified, this defaults to [`true`]. with_color(color) { this.color = color; return this; } /// How many characters width should tab characters be? /// /// If unspecified, this defaults to `4`. with_tab_width(tab_width) { this.tab_width = tab_width; return this; } /// What character set should be used to display dynamic elements such as boxes and arrows? /// /// If unspecified, this defaults to [`CharSet.Unicode`]. with_char_set(char_set) { this.char_set = char_set; return this; } error_color() { return some(colors.red).filter(() => this.color); } warning_color() { return some(colors.yellow).filter(() => this.color); } advice_color() { return some(Fixed(147)).filter(() => this.color); } margin_color() { return some(Fixed(246)).filter(() => this.color); } unimportant_color() { return some(Fixed(249)).filter(() => this.color); } note_color() { return some(Fixed(115)).filter(() => this.color); } // Find the character that should be drawn and the number of times it should be drawn for each char char_width(c2, col) { if (c2 === " ") { let tab_end = (col / this.tab_width + 1) * this.tab_width; return [new Display(" "), tab_end - col]; } if (c2.match(/[\s]/)) return [new Display(" "), 1]; return [new Display(c2), 1]; } } var LabelAttach = /* @__PURE__ */ ((LabelAttach2) => { LabelAttach2["Start"] = "Start"; LabelAttach2["Middle"] = "Middle"; LabelAttach2["End"] = "End"; return LabelAttach2; })(LabelAttach || {}); var CharSet = /* @__PURE__ */ ((CharSet2) => { CharSet2["Unicode"] = "Unicode"; CharSet2["Ascii"] = "Ascii"; return CharSet2; })(CharSet || {}); class Label { /// Create a new [`Label`]. constructor(span) { this.span = span; this.msg = none(); this.color = none(); this.order = 0; this.priority = 0; } /// Give this label a message. with_message(msg) { this.msg = some(msg); return this; } /// Give this label a highlight colour. with_color(color) { this.color = some(color); return this; } /// Specify the order of this label relative to other labels. /// /// Lower values correspond to this label having an earlier order. /// /// If unspecified, labels default to an order of `0`. /// /// When labels are displayed after a line the crate needs to decide which labels should be displayed first. By /// Default, the orders labels based on where their associated line meets the text (see [`LabelAttach`]). /// Additionally, multi-line labels are ordered before inline labels. You can this this function to override this /// behaviour. with_order(order) { this.order = order; return this; } /// Specify the priority of this label relative to other labels. /// /// Higher values correspond to this label having a higher priority. /// /// If unspecified, labels default to a priority of `0`. /// /// Label spans can overlap. When this happens, the crate needs to decide which labels to prioritise for various /// purposes such as highlighting. By default, spans with a smaller length get a higher priority. You can this this /// function to override this behaviour. with_priority(priority) { this.priority = priority; return this; } last_offset() { return this.span.end.saturating_sub(1).max(this.span.start); } static { this.from = Label.new; } static new(obj) { return new Label(Range.from(obj)); } static is(other) { return other instanceof Label; } } var assert$1 = { exports: {} }; var errors = {}; var util = {}; var types = {}; var shams$1 = function hasSymbols2() { if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { return false; } if (typeof Symbol.iterator === "symbol") { return true; } var obj = {}; var sym = Symbol("test"); var symObj = Object(sym); if (typeof sym === "string") { return false; } if (Object.prototype.toString.call(sym) !== "[object Symbol]") { return false; } if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === "function") { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; var hasSymbols$1 = shams$1; var shams = function hasToStringTagShams() { return hasSymbols$1() && !!Symbol.toStringTag; }; var hasSymbols; var hasRequiredHasSymbols; function requireHasSymbols() { if (hasRequiredHasSymbols) return hasSymbols; hasRequiredHasSymbols = 1; var origSymbol = typeof Symbol !== "undefined" && Symbol; var hasSymbolSham = shams$1; hasSymbols = function hasNativeSymbols() { if (typeof origSymbol !== "function") { return false; } if (typeof Symbol !== "function") { return false; } if (typeof origSymbol("foo") !== "symbol") { return false; } if (typeof Symbol("bar") !== "symbol") { return false; } return hasSymbolSham(); }; return hasSymbols; } var implementation$3; var hasRequiredImplementation$3; function requireImplementation$3() { if (hasRequiredImplementation$3) return implementation$3; hasRequiredImplementation$3 = 1; var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; var slice = Array.prototype.slice; var toStr2 = Object.prototype.toString; var funcType = "[object Function]"; implementation$3 = function bind(that) { var target = this; if (typeof target !== "function" || toStr2.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function() { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push("$" + i); } bound = Function("binder", "return function (" + boundArgs.join(",") + "){ return binder.apply(this,arguments); }")(binder); if (target.prototype) { var Empty = function Empty2() { }; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; return implementation$3; } var functionBind; var hasRequiredFunctionBind; function requireFunctionBind() { if (hasRequiredFunctionBind) return functionBind; hasRequiredFunctionBind = 1; var implementation2 = requireImplementation$3(); functionBind = Function.prototype.bind || implementation2; return functionBind; } var src; var hasRequiredSrc; function requireSrc() { if (hasRequiredSrc) return src; hasRequiredSrc = 1; var bind = requireFunctionBind(); src = bind.call(Function.call, Object.prototype.hasOwnProperty); return src; } var getIntrinsic; var hasRequiredGetIntrinsic; function requireGetIntrinsic() { if (hasRequiredGetIntrinsic) return getIntrinsic; hasRequiredGetIntrinsic = 1; var undefined$1; var $SyntaxError = SyntaxError; var $Function = Function; var $TypeError = TypeError; var getEvalledConstructor = function(expressionSyntax) { try { return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); } catch (e) { } }; var $gOPD2 = Object.getOwnPropertyDescriptor; if ($gOPD2) { try { $gOPD2({}, ""); } catch (e) { $gOPD2 = null; } } var throwTypeError = function() { throw new $TypeError(); }; var ThrowTypeError = $gOPD2 ? function() { try { arguments.callee; return throwTypeError; } catch (calleeThrows) { try { return $gOPD2(arguments, "callee").get; } catch (gOPDthrows) { return throwTypeError; } } }() : throwTypeError; var hasSymbols2 = requireHasSymbols()(); var getProto2 = Object.getPrototypeOf || function(x) { return x.__proto__; }; var needsEval = {}; var TypedArray = typeof Uint8Array === "undefined" ? undefined$1 : getProto2(Uint8Array); var INTRINSICS = { "%AggregateError%": typeof AggregateError === "undefined" ? undefined$1 : AggregateError, "%Array%": Array, "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined$1 : ArrayBuffer, "%ArrayIteratorPrototype%": hasSymbols2 ? getProto2([][Symbol.iterator]()) : undefined$1, "%AsyncFromSyncIteratorPrototype%": undefined$1, "%AsyncFunction%": needsEval, "%AsyncGenerator%": needsEval, "%AsyncGeneratorFunction%": needsEval, "%AsyncIteratorPrototype%": needsEval, "%Atomics%": typeof Atomics === "undefined" ? undefined$1 : Atomics, "%BigInt%": typeof BigInt === "undefined" ? undefined$1 : BigInt, "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined$1 : BigInt64Array, "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined$1 : BigUint64Array, "%Boolean%": Boolean, "%DataView%": typeof DataView === "undefined" ? undefined$1 : DataView, "%Date%": Date, "%decodeURI%": decodeURI, "%decodeURIComponent%": decodeURIComponent, "%encodeURI%": encodeURI, "%encodeURIComponent%": encodeURIComponent, "%Error%": Error, "%eval%": eval, // eslint-disable-line no-eval "%EvalError%": EvalError, "%Float32Array%": typeof Float32Array === "undefined" ? undefined$1 : Float32Array, "%Float64Array%": typeof Float64Array === "undefined" ? undefined$1 : Float64Array, "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined$1 : FinalizationRegistry, "%Function%": $Function, "%GeneratorFunction%": needsEval, "%Int8Array%": typeof Int8Array === "undefined" ? undefined$1 : Int8Array, "%Int16Array%": typeof Int16Array === "undefined" ? undefined$1 : Int16Array, "%Int32Array%": typeof Int32Array === "undefined" ? undefined$1 : Int32Array, "%isFinite%": isFinite, "%isNaN%": isNaN, "%IteratorPrototype%": hasSymbols2 ? getProto2(getProto2([][Symbol.iterator]())) : undefined$1, "%JSON%": typeof JSON === "object" ? JSON : undefined$1, "%Map%": typeof Map === "undefined" ? undefined$1 : Map, "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols2 ? undefined$1 : getProto2((/* @__PURE__ */ new Map())[Symbol.iterator]()), "%Math%": Math, "%Number%": Number, "%Object%": Object, "%parseFloat%": parseFloat, "%parseInt%": parseInt, "%Promise%": typeof Promise === "undefined" ? undefined$1 : Promise, "%Proxy%": typeof Proxy === "undefined" ? undefined$1 : Proxy, "%RangeError%": RangeError, "%ReferenceError%": ReferenceError, "%Reflect%": typeof Reflect === "undefined" ? undefined$1 : Reflect, "%RegExp%": RegExp, "%Set%": typeof Set === "undefined" ? undefined$1 : Set, "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols2 ? undefined$1 : getProto2((/* @__PURE__ */ new Set())[Symbol.iterator]()), "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined$1 : SharedArrayBuffer, "%String%": String, "%StringIteratorPrototype%": hasSymbols2 ? getProto2(""[Symbol.iterator]()) : undefined$1, "%Symbol%": hasSymbols2 ? Symbol : undefined$1, "%SyntaxError%": $SyntaxError, "%ThrowTypeError%": ThrowTypeError, "%TypedArray%": TypedArray, "%TypeError%": $TypeError, "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined$1 : Uint8Array, "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined$1 : Uint8ClampedArray, "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined$1 : Uint16Array, "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined$1 : Uint32Array, "%URIError%": URIError, "%WeakMap%": typeof WeakMap === "undefined" ? undefined$1 : WeakMap, "%WeakRef%": typeof WeakRef === "undefined" ? undefined$1 : WeakRef, "%WeakSet%": typeof WeakSet === "undefined" ? undefined$1 : WeakSet }; try { null.error; } catch (e) { var errorProto = getProto2(getProto2(e)); INTRINSICS["%Error.prototype%"] = errorProto; } var doEval = function doEval2(name) { var value; if (name === "%AsyncFunction%") { value = getEvalledConstructor("async function () {}"); } else if (name === "%GeneratorFunction%") { value = getEvalledConstructor("function* () {}"); } else if (name === "%AsyncGeneratorFunction%") { value = getEvalledConstructor("async function* () {}"); } else if (name === "%AsyncGenerator%") { var fn = doEval2("%AsyncGeneratorFunction%"); if (fn) { value = fn.prototype; } } else if (name === "%AsyncIteratorPrototype%") { var gen = doEval2("%AsyncGenerator%"); if (gen) { value = getProto2(gen.prototype); } } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], "%ArrayPrototype%": ["Array", "prototype"], "%ArrayProto_entries%": ["Array", "prototype", "entries"], "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], "%ArrayProto_keys%": ["Array", "prototype", "keys"], "%ArrayProto_values%": ["Array", "prototype", "values"], "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], "%BooleanPrototype%": ["Boolean", "prototype"], "%DataViewPrototype%": ["DataView", "prototype"], "%DatePrototype%": ["Date", "prototype"], "%ErrorPrototype%": ["Error", "prototype"], "%EvalErrorPrototype%": ["EvalError", "prototype"], "%Float32ArrayPrototype%": ["Float32Array", "prototype"], "%Float64ArrayPrototype%": ["Float64Array", "prototype"], "%FunctionPrototype%": ["Function", "prototype"], "%Generator%": ["GeneratorFunction", "prototype"], "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], "%Int8ArrayPrototype%": ["Int8Array", "prototype"], "%Int16ArrayPrototype%": ["Int16Array", "prototype"], "%Int32ArrayPrototype%": ["Int32Array", "prototype"], "%JSONParse%": ["JSON", "parse"], "%JSONStringify%": ["JSON", "stringify"], "%MapPrototype%": ["Map", "prototype"], "%NumberPrototype%": ["Number", "prototype"], "%ObjectPrototype%": ["Object", "prototype"], "%ObjProto_toString%": ["Object", "prototype", "toString"], "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], "%PromisePrototype%": ["Promise", "prototype"], "%PromiseProto_then%": ["Promise", "prototype", "then"], "%Promise_all%": ["Promise", "all"], "%Promise_reject%": ["Promise", "reject"], "%Promise_resolve%": ["Promise", "resolve"], "%RangeErrorPrototype%": ["RangeError", "prototype"], "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], "%RegExpPrototype%": ["RegExp", "prototype"], "%SetPrototype%": ["Set", "prototype"], "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], "%StringPrototype%": ["String", "prototype"], "%SymbolPrototype%": ["Symbol", "prototype"], "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], "%TypedArrayPrototype%": ["TypedArray", "prototype"], "%TypeErrorPrototype%": ["TypeError", "prototype"], "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], "%URIErrorPrototype%": ["URIError", "prototype"], "%WeakMapPrototype%": ["WeakMap", "prototype"], "%WeakSetPrototype%": ["WeakSet", "prototype"] }; var bind = requireFunctionBind(); var hasOwn = requireSrc(); var $concat = bind.call(Function.call, Array.prototype.concat); var $spliceApply = bind.call(Function.apply, Array.prototype.splice); var $replace = bind.call(Function.call, String.prototype.replace); var $strSlice = bind.call(Function.call, String.prototype.slice); var $exec = bind.call(Function.call, RegExp.prototype.exec); var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; var stringToPath = function stringToPath2(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === "%" && last !== "%") { throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); } else if (last === "%" && first !== "%") { throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); } var result = []; $replace(string, rePropName, function(match2, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match2; }); return result; }; var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = "%" + alias[0] + "%"; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) { value = doEval(intrinsicName); } if (typeof value === "undefined" && !allowMissing) { throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); } return { alias, name: intrinsicName, value }; } throw new $SyntaxError("intrinsic " + name + " does not exist!"); }; getIntrinsic = function GetIntrinsic2(name, allowMissing) { if (typeof name !== "string" || name.length === 0) { throw new $TypeError("intrinsic name must be a non-empty string"); } if (arguments.length > 1 && typeof allowMissing !== "boolean") { throw new $TypeError('"allowMissing" argument must be a boolean'); } if ($exec(/^%?[^%]*%?$/, name) === null) { throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); } var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { throw new $SyntaxError("property names with quotes must have matching quotes"); } if (part === "constructor" || !isOwn) { skipFurtherCaching = true; } intrinsicBaseName += "." + part; intrinsicRealName = "%" + intrinsicBaseName + "%"; if (hasOwn(INTRINSICS, intrinsicRealName)) { value = INTRINSICS[intrinsicRealName]; } else if (value != null) { if (!(part in value)) { if (!allowMissing) { throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); } return void 0; } if ($gOPD2 && i + 1 >= parts.length) { var desc = $gOPD2(value, part); isOwn = !!desc; if (isOwn && "get" in desc && !("originalValue" in desc.get)) { value = desc.get; } else { value = value[part]; } } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) { INTRINSICS[intrinsicRealName] = value; } } } return value; }; return getIntrinsic; } var callBind$1 = { exports: {} }; var hasRequiredCallBind; function requireCallBind() { if (hasRequiredCallBind) return callBind$1.exports; hasRequiredCallBind = 1; (function(module2) { var bind = requireFunctionBind(); var GetIntrinsic2 = requireGetIntrinsic(); var $apply = GetIntrinsic2("%Function.prototype.apply%"); var $call = GetIntrinsic2("%Function.prototype.call%"); var $reflectApply = GetIntrinsic2("%Reflect.apply%", true) || bind.call($call, $apply); var $gOPD2 = GetIntrinsic2("%Object.getOwnPropertyDescriptor%", true); var $defineProperty = GetIntrinsic2("%Object.defineProperty%", true); var $max = GetIntrinsic2("%Math.max%"); if ($defineProperty) { try { $defineProperty({}, "a", { value: 1 }); } catch (e) { $defineProperty = null; } } module2.exports = function callBind2(originalFunction) { var func = $reflectApply(bind, $call, arguments); if ($gOPD2 && $defineProperty) { var desc = $gOPD2(func, "length"); if (desc.configurable) { $defineProperty( func, "length", { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } ); } } return func; }; var applyBind = function applyBind2() { return $reflectApply(bind, $apply, arguments); }; if ($defineProperty) { $defineProperty(module2.exports, "apply", { value: applyBind }); } else { module2.exports.apply = applyBind; } })(callBind$1); return callBind$1.exports; } var GetIntrinsic$1 = requireGetIntrinsic(); var callBind = requireCallBind(); var $indexOf$1 = callBind(GetIntrinsic$1("String.prototype.indexOf")); var callBound$3 = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic$1(name, !!allowMissing); if (typeof intrinsic === "function" && $indexOf$1(name, ".prototype.") > -1) { return callBind(intrinsic); } return intrinsic; }; var hasToStringTag$4 = shams(); var callBound$2 = callBound$3; var $toString$2 = callBound$2("Object.prototype.toString"); var isStandardArguments = function isArguments2(value) { if (hasToStringTag$4 && value && typeof value === "object" && Symbol.toStringTag in value) { return false; } return $toString$2(value) === "[object Arguments]"; }; var isLegacyArguments = function isArguments2(value) { if (isStandardArguments(value)) { return true; } return value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && $toString$2(value) !== "[object Array]" && $toString$2(value.callee) === "[object Function]"; }; var supportsStandardArguments = function() { return isStandardArguments(arguments); }(); isStandardArguments.isLegacyArguments = isLegacyArguments; var isArguments$1 = supportsStandardArguments ? isStandardArguments : isLegacyArguments; var toStr$2 = Object.prototype.toString; var fnToStr$1 = Function.prototype.toString; var isFnRegex = /^\s*(?:function)?\*/; var hasToStringTag$3 = shams(); var getProto = Object.getPrototypeOf; var getGeneratorFunc = function() { if (!hasToStringTag$3) { return false; } try { return Function("return function*() {}")(); } catch (e) { } }; var GeneratorFunction; var isGeneratorFunction = function isGeneratorFunction2(fn) { if (typeof fn !== "function") { return false; } if (isFnRegex.test(fnToStr$1.call(fn))) { return true; } if (!hasToStringTag$3) { var str = toStr$2.call(fn); return str === "[object GeneratorFunction]"; } if (!getProto) { return false; } if (typeof GeneratorFunction === "undefined") { var generatorFunc = getGeneratorFunc(); GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; } return getProto(fn) === GeneratorFunction; }; var fnToStr = Function.prototype.toString; var reflectApply = typeof Reflect === "object" && Reflect !== null && Reflect.apply; var badArrayLike; var isCallableMarker; if (typeof reflectApply === "function" && typeof Object.defineProperty === "function") { try { badArrayLike = Object.defineProperty({}, "length", { get: function() { throw isCallableMarker; } }); isCallableMarker = {}; reflectApply(function() { throw 42; }, null, badArrayLike); } catch (_) { if (_ !== isCallableMarker) { reflectApply = null; } } } else { reflectApply = null; } var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr$1 = Object.prototype.toString; var objectClass = "[object Object]"; var fnClass = "[object Function]"; var genClass = "[object GeneratorFunction]"; var ddaClass = "[object HTMLAllCollection]"; var ddaClass2 = "[object HTML document.all class]"; var ddaClass3 = "[object HTMLCollection]"; var hasToStringTag$2 = typeof Symbol === "function" && !!Symbol.toStringTag; var isIE68 = !(0 in [,]); var isDDA = function isDocumentDotAll() { return false; }; if (typeof document === "object") { var all = document.all; if (toStr$1.call(all) === toStr$1.call(document.all)) { isDDA = function isDocumentDotAll(value) { if ((isIE68 || !value) && (typeof value === "undefined" || typeof value === "object")) { try { var str = toStr$1.call(value); return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null; } catch (e) { } } return false; }; } } var isCallable$1 = reflectApply ? function isCallable2(value) { if (isDDA(value)) { return true; } if (!value) { return false; } if (typeof value !== "function" && typeof value !== "object") { return false; } try { reflectApply(value, null, badArrayLike); } catch (e) { if (e !== isCallableMarker) { return false; } } return !isES6ClassFn(value) && tryFunctionObject(value); } : function isCallable2(value) { if (isDDA(value)) { return true; } if (!value) { return false; } if (typeof value !== "function" && typeof value !== "object") { return false; } if (hasToStringTag$2) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr$1.call(value); if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass)) { return false; } return tryFunctionObject(value); }; var isCallable = isCallable$1; var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var forEachArray = function forEachArray2(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; var forEachString = function forEachString2(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; var forEachObject = function forEachObject2(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; var forEach$2 = function forEach2(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError("iterator must be a function"); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (toStr.call(list) === "[object Array]") { forEachArray(list, iterator, receiver); } else if (typeof list === "string") { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; var forEach_1 = forEach$2; var possibleNames = [ "BigInt64Array", "BigUint64Array", "Float32Array", "Float64Array", "Int16Array", "Int32Array", "Int8Array", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray" ]; var g$2 = typeof globalThis === "undefined" ? commonjsGlobal : globalThis; var availableTypedArrays$2 = function availableTypedArrays2() { var out = []; for (var i = 0; i < possibleNames.length; i++) { if (typeof g$2[possibleNames[i]] === "function") { out[out.length] = possibleNames[i]; } } return out; }; var GetIntrinsic = requireGetIntrinsic(); var $gOPD = GetIntrinsic("%Object.getOwnPropertyDescriptor%", true); if ($gOPD) { try { $gOPD([], "length"); } catch (e) { $gOPD = null; } } var gopd = $gOPD; var forEach$1 = forEach_1; var availableTypedArrays$1 = availableTypedArrays$2; var callBound$1 = callBound$3; var $toString$1 = callBound$1("Object.prototype.toString"); var hasToStringTag$1 = shams(); var gOPD$1 = gopd; var g$1 = typeof globalThis === "undefined" ? commonjsGlobal : globalThis; var typedArrays$1 = availableTypedArrays$1(); var $indexOf = callBound$1("Array.prototype.indexOf", true) || function indexOf(array, value) { for (var i = 0; i < array.length; i += 1) { if (array[i] === value) { return i; } } return -1; }; var $slice$1 = callBound$1("String.prototype.slice"); var toStrTags$1 = {}; var getPrototypeOf$1 = Object.getPrototypeOf; if (hasToStringTag$1 && gOPD$1 && getPrototypeOf$1) { forEach$1(typedArrays$1, function(typedArray) { var arr = new g$1[typedArray](); if (Symbol.toStringTag in arr) { var proto2 = getPrototypeOf$1(arr); var descriptor = gOPD$1(proto2, Symbol.toStringTag); if (!descriptor) { var superProto = getPrototypeOf$1(proto2); descriptor = gOPD$1(superProto, Symbol.toStringTag); } toStrTags$1[typedArray] = descriptor.get; } }); } var tryTypedArrays$1 = function tryAllTypedArrays(value) { var anyTrue = false; forEach$1(toStrTags$1, function(getter, typedArray) { if (!anyTrue) { try { anyTrue = getter.call(value) === typedArray; } catch (e) { } } }); return anyTrue; }; var isTypedArray$1 = function isTypedArray2(value) { if (!value || typeof value !== "object") { return false; } if (!hasToStringTag$1 || !(Symbol.toStringTag in value)) { var tag = $slice$1($toString$1(value), 8, -1); return $indexOf(typedArrays$1, tag) > -1; } if (!gOPD$1) { return false; } return tryTypedArrays$1(value); }; var forEach = forEach_1; var availableTypedArrays = availableTypedArrays$2; var callBound = callBound$3; var gOPD = gopd; var $toString = callBound("Object.prototype.toString"); var hasToStringTag = shams(); var g = typeof globalThis === "undefined" ? commonjsGlobal : globalThis; var typedArrays = availableTypedArrays(); var $slice = callBound("String.prototype.slice"); var toStrTags = {}; var getPrototypeOf = Object.getPrototypeOf; if (hasToStringTag && gOPD && getPrototypeOf) { forEach(typedArrays, function(typedArray) { if (typeof g[typedArray] === "function") { var arr = new g[typedArray](); if (Symbol.toStringTag in arr) { var proto2 = getPrototypeOf(arr); var descriptor = gOPD(proto2, Symbol.toStringTag); if (!descriptor) { var superProto = getPrototypeOf(proto2); descriptor = gOPD(superProto, Symbol.toStringTag); } toStrTags[typedArray] = descriptor.get; } } }); } var tryTypedArrays = function tryAllTypedArrays(value) { var foundName = false; forEach(toStrTags, function(getter, typedArray) { if (!foundName) { try { var name = getter.call(value); if (name === typedArray) { foundName = name; } } catch (e) { } } }); return foundName; }; var isTypedArray = isTypedArray$1; var whichTypedArray = function whichTypedArray2(value) { if (!isTypedArray(value)) { return false; } if (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); } return tryTypedArrays(value); }; (function(exports3) { var isArgumentsObject = isArguments$1; var isGeneratorFunction$1 = isGeneratorFunction; var whichTypedArray$1 = whichTypedArray; var isTypedArray2 = isTypedArray$1; function uncurryThis(f) { return f.call.bind(f); } var BigIntSupported = typeof BigInt !== "undefined"; var SymbolSupported = typeof Symbol !== "undefined"; var ObjectToString = uncurryThis(Object.prototype.toString); var numberValue = uncurryThis(Number.prototype.valueOf); var stringValue = uncurryThis(String.prototype.valueOf); var booleanValue = uncurryThis(Boolean.prototype.valueOf); if (BigIntSupported) { var bigIntValue = uncurryThis(BigInt.prototype.valueOf); } if (SymbolSupported) { var symbolValue = uncurryThis(Symbol.prototype.valueOf); } function checkBoxedPrimitive(value, prototypeValueOf) { if (typeof value !== "object") { return false; } try { prototypeValueOf(value); return true; } catch (e) { return false; } } exports3.isArgumentsObject = isArgumentsObject; exports3.isGeneratorFunction = isGeneratorFunction$1; exports3.isTypedArray = isTypedArray2; function isPromise(input) { return typeof Promise !== "undefined" && input instanceof Promise || input !== null && typeof input === "object" && typeof input.then === "function" && typeof input.catch === "function"; } exports3.isPromise = isPromise; function isArrayBufferView(value) { if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { return ArrayBuffer.isView(value); } return isTypedArray2(value) || isDataView(value); } exports3.isArrayBufferView = isArrayBufferView; function isUint8Array(value) { return whichTypedArray$1(value) === "Uint8Array"; } exports3.isUint8Array = isUint8Array; function isUint8ClampedArray(value) { return whichTypedArray$1(value) === "Uint8ClampedArray"; } exports3.isUint8ClampedArray = isUint8ClampedArray; function isUint16Array(value) { return whichTypedArray$1(value) === "Uint16Array"; } exports3.isUint16Array = isUint16Array; function isUint32Array(value) { return whichTypedArray$1(value) === "Uint32Array"; } exports3.isUint32Array = isUint32Array; function isInt8Array(value) { return whichTypedArray$1(value) === "Int8Array"; } exports3.isInt8Array = isInt8Array; function isInt16Array(value) { return whichTypedArray$1(value) === "Int16Array"; } exports3.isInt16Array = isInt16Array; function isInt32Array(value) { return whichTypedArray$1(value) === "Int32Array"; } exports3.isInt32Array = isInt32Array; function isFloat32Array(value) { return whichTypedArray$1(value) === "Float32Array"; } exports3.isFloat32Array = isFloat32Array; function isFloat64Array(value) { return whichTypedArray$1(value) === "Float64Array"; } exports3.isFloat64Array = isFloat64Array; function isBigInt64Array(value) { return whichTypedArray$1(value) === "BigInt64Array"; } exports3.isBigInt64Array = isBigInt64Array; function isBigUint64Array(value) { return whichTypedArray$1(value) === "BigUint64Array"; } exports3.isBigUint64Array = isBigUint64Array; function isMapToString(value) { return ObjectToString(value) === "[object Map]"; } isMapToString.working = typeof Map !== "undefined" && isMapToString(/* @__PURE__ */ new Map()); function isMap(value) { if (typeof Map === "undefined") { return false; } return isMapToString.working ? isMapToString(value) : value instanceof Map; } exports3.isMap = isMap; function isSetToString(value) { return ObjectToString(value) === "[object Set]"; } isSetToString.working = typeof Set !== "undefined" && isSetToString(/* @__PURE__ */ new Set()); function isSet(value) { if (typeof Set === "undefined") { return false; } return isSetToString.working ? isSetToString(value) : value instanceof Set; } exports3.isSet = isSet; function isWeakMapToString(value) { return ObjectToString(value) === "[object WeakMap]"; } isWeakMapToString.working = typeof WeakMap !== "undefined" && isWeakMapToString(/* @__PURE__ */ new WeakMap()); function isWeakMap(value) { if (typeof WeakMap === "undefined") { return false; } return isWeakMapToString.working ? isWeakMapToString(value) : value instanceof WeakMap; } exports3.isWeakMap = isWeakMap; function isWeakSetToString(value) { return ObjectToString(value) === "[object WeakSet]"; } isWeakSetToString.working = typeof WeakSet !== "undefined" && isWeakSetToString(/* @__PURE__ */ new WeakSet()); function isWeakSet(value) { return isWeakSetToString(value); } exports3.isWeakSet = isWeakSet; function isArrayBufferToString(value) { return ObjectToString(value) === "[object ArrayBuffer]"; } isArrayBufferToString.working = typeof ArrayBuffer !== "undefined" && isArrayBufferToString(new ArrayBuffer()); function isArrayBuffer(value) { if (typeof ArrayBuffer === "undefined") { return false; } return isArrayBufferToString.working ? isArrayBufferToString(value) : value instanceof ArrayBuffer; } exports3.isArrayBuffer = isArrayBuffer; function isDataViewToString(value) { return ObjectToString(value) === "[object DataView]"; } isDataViewToString.working = typeof ArrayBuffer !== "undefined" && typeof DataView !== "undefined" && isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)); function isDataView(value) { if (typeof DataView === "undefined") { return false; } return isDataViewToString.working ? isDataViewToString(value) : value instanceof DataView; } exports3.isDataView = isDataView; var SharedArrayBufferCopy = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : void 0; function isSharedArrayBufferToString(value) { return ObjectToString(value) === "[object SharedArrayBuffer]"; } function isSharedArrayBuffer(value) { if (typeof SharedArrayBufferCopy === "undefined") { return false; } if (typeof isSharedArrayBufferToString.working === "undefined") { isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); } return isSharedArrayBufferToString.working ? isSharedArrayBufferToString(value) : value instanceof SharedArrayBufferCopy; } exports3.isSharedArrayBuffer = isSharedArrayBuffer; function isAsyncFunction(value) { return ObjectToString(value) === "[object AsyncFunction]"; } exports3.isAsyncFunction = isAsyncFunction; function isMapIterator(value) { return ObjectToString(value) === "[object Map Iterator]"; } exports3.isMapIterator = isMapIterator; function isSetIterator(value) { return ObjectToString(value) === "[object Set Iterator]"; } exports3.isSetIterator = isSetIterator; function isGeneratorObject(value) { return ObjectToString(value) === "[object Generator]"; } exports3.isGeneratorObject = isGeneratorObject; function isWebAssemblyCompiledModule(value) { return ObjectToString(value) === "[object WebAssembly.Module]"; } exports3.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; function isNumberObject(value) { return checkBoxedPrimitive(value, numberValue); } exports3.isNumberObject = isNumberObject; function isStringObject(value) { return checkBoxedPrimitive(value, stringValue); } exports3.isStringObject = isStringObject; function isBooleanObject(value) { return checkBoxedPrimitive(value, booleanValue); } exports3.isBooleanObject = isBooleanObject; function isBigIntObject(value) { return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); } exports3.isBigIntObject = isBigIntObject; function isSymbolObject(value) { return SymbolSupported && checkBoxedPrimitive(value, symbolValue); } exports3.isSymbolObject = isSymbolObject; function isBoxedPrimitive(value) { return isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value); } exports3.isBoxedPrimitive = isBoxedPrimitive; function isAnyArrayBuffer(value) { return typeof Uint8Array !== "undefined" && (isArrayBuffer(value) || isSharedArrayBuffer(value)); } exports3.isAnyArrayBuffer = isAnyArrayBuffer; ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function(method) { Object.defineProperty(exports3, method, { enumerable: false, value: function() { throw new Error(method + " is not supported in userland"); } }); }); })(types); var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === "object" && typeof arg.copy === "function" && typeof arg.fill === "function" && typeof arg.readUInt8 === "function"; }; var inherits_browser = { exports: {} }; if (typeof Object.create === "function") { inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function() { }; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } var inherits_browserExports = inherits_browser.exports; (function(exports3) { var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors2(obj) { var keys = Object.keys(obj); var descriptors = {}; for (var i = 0; i < keys.length; i++) { descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); } return descriptors; }; var formatRegExp = /%[sdj%]/g; exports3.format = function(f) { if (!isString2(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(" "); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x2) { if (x2 === "%%") return "%"; if (i >= len) return x2; switch (x2) { case "%s": return String(args[i++]); case "%d": return Number(args[i++]); case "%j": try { return JSON.stringify(args[i++]); } catch (_) { return "[Circular]"; } default: return x2; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += " " + x; } else { str += " " + inspect(x); } } return str; }; exports3.deprecate = function(fn, msg) { if (typeof process !== "undefined" && process.noDeprecation === true) { return fn; } if (typeof process === "undefined") { return function() { return exports3.deprecate(fn, msg).apply(this, arguments); }; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnvRegex = /^$/; if (process.env.NODE_DEBUG) { var debugEnv = process.env.NODE_DEBUG; debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase(); debugEnvRegex = new RegExp("^" + debugEnv + "$", "i"); } exports3.debuglog = function(set) { set = set.toUpperCase(); if (!debugs[set]) { if (debugEnvRegex.test(set)) { var pid = process.pid; debugs[set] = function() { var msg = exports3.format.apply(exports3, arguments); console.error("%s %d: %s", set, pid, msg); }; } else { debugs[set] = function() { }; } } return debugs[set]; }; function inspect(obj, opts) { var ctx = { seen: [], stylize: stylizeNoColor }; if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean2(opts)) { ctx.showHidden = opts; } else if (opts) { exports3._extend(ctx, opts); } if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports3.inspect = inspect; inspect.colors = { "bold": [1, 22], "italic": [3, 23], "underline": [4, 24], "inverse": [7, 27], "white": [37, 39], "grey": [90, 39], "black": [30, 39], "blue": [34, 39], "cyan": [36, 39], "green": [32, 39], "magenta": [35, 39], "red": [31, 39], "yellow": [33, 39] }; inspect.styles = { "special": "cyan", "number": "yellow", "boolean": "yellow", "undefined": "grey", "null": "bold", "string": "green", "date": "magenta", // "name": intentionally not styling "regexp": "red" }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m"; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports3.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString2(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) { return formatError(value); } if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ": " + value.name : ""; return ctx.stylize("[Function" + name + "]", "special"); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), "date"); } if (isError(value)) { return formatError(value); } } var base = "", array = false, braces = ["{", "}"]; if (isArray(value)) { array = true; braces = ["[", "]"]; } if (isFunction(value)) { var n = value.name ? ": " + value.name : ""; base = " [Function" + n + "]"; } if (isRegExp(value)) { base = " " + RegExp.prototype.toString.call(value); } if (isDate(value)) { base = " " + Date.prototype.toUTCString.call(value); } if (isError(value)) { base = " " + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); } else { return ctx.stylize("[Object]", "special"); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize("undefined", "undefined"); if (isString2(value)) { var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; return ctx.stylize(simple, "string"); } if (isNumber2(value)) return ctx.stylize("" + value, "number"); if (isBoolean2(value)) return ctx.stylize("" + value, "boolean"); if (isNull(value)) return ctx.stylize("null", "null"); } function formatError(value) { return "[" + Error.prototype.toString.call(value) + "]"; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty2(value, String(i))) { output.push(formatProperty( ctx, value, recurseTimes, visibleKeys, String(i), true )); } else { output.push(""); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty( ctx, value, recurseTimes, visibleKeys, key, true )); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize("[Getter/Setter]", "special"); } else { str = ctx.stylize("[Getter]", "special"); } } else { if (desc.set) { str = ctx.stylize("[Setter]", "special"); } } if (!hasOwnProperty2(visibleKeys, key)) { name = "[" + key + "]"; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf("\n") > -1) { if (array) { str = str.split("\n").map(function(line) { return " " + line; }).join("\n").slice(2); } else { str = "\n" + str.split("\n").map(function(line) { return " " + line; }).join("\n"); } } } else { str = ctx.stylize("[Circular]", "special"); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify("" + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.slice(1, -1); name = ctx.stylize(name, "name"); } else { name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, "string"); } } return name + ": " + str; } function reduceToSingleString(output, base, braces) { var length = output.reduce(function(prev, cur) { if (cur.indexOf("\n") >= 0) ; return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1; }, 0); if (length > 60) { return braces[0] + (base === "" ? "" : base + "\n ") + " " + output.join(",\n ") + " " + braces[1]; } return braces[0] + base + " " + output.join(", ") + " " + braces[1]; } exports3.types = types; function isArray(ar) { return Array.isArray(ar); } exports3.isArray = isArray; function isBoolean2(arg) { return typeof arg === "boolean"; } exports3.isBoolean = isBoolean2; function isNull(arg) { return arg === null; } exports3.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports3.isNullOrUndefined = isNullOrUndefined; function isNumber2(arg) { return typeof arg === "number"; } exports3.isNumber = isNumber2; function isString2(arg) { return typeof arg === "string"; } exports3.isString = isString2; function isSymbol(arg) { return typeof arg === "symbol"; } exports3.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports3.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === "[object RegExp]"; } exports3.isRegExp = isRegExp; exports3.types.isRegExp = isRegExp; function isObject(arg) { return typeof arg === "object" && arg !== null; } exports3.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === "[object Date]"; } exports3.isDate = isDate; exports3.types.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error); } exports3.isError = isError; exports3.types.isNativeError = isError; function isFunction(arg) { return typeof arg === "function"; } exports3.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol typeof arg === "undefined"; } exports3.isPrimitive = isPrimitive; exports3.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? "0" + n.toString(10) : n.toString(10); } var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; function timestamp() { var d = /* @__PURE__ */ new Date(); var time = [ pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds()) ].join(":"); return [d.getDate(), months[d.getMonth()], time].join(" "); } exports3.log = function() { console.log("%s - %s", timestamp(), exports3.format.apply(exports3, arguments)); }; exports3.inherits = inherits_browserExports; exports3._extend = function(origin, add) { if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty2(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : void 0; exports3.promisify = function promisify(original) { if (typeof original !== "function") throw new TypeError('The "original" argument must be of type Function'); if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { var fn = original[kCustomPromisifiedSymbol]; if (typeof fn !== "function") { throw new TypeError('The "util.promisify.custom" argument must be of type Function'); } Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return fn; } function fn() { var promiseResolve, promiseReject; var promise = new Promise(function(resolve, reject) { promiseResolve = resolve; promiseReject = reject; }); var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } args.push(function(err2, value) { if (err2) { promiseReject(err2); } else { promiseResolve(value); } }); try { original.apply(this, args); } catch (err2) { promiseReject(err2); } return promise; } Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return Object.defineProperties( fn, getOwnPropertyDescriptors(original) ); }; exports3.promisify.custom = kCustomPromisifiedSymbol; function callbackifyOnRejected(reason, cb) { if (!reason) { var newReason = new Error("Promise was rejected with a falsy value"); newReason.reason = reason; reason = newReason; } return cb(reason); } function callbackify(original) { if (typeof original !== "function") { throw new TypeError('The "original" argument must be of type Function'); } function callbackified() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== "function") { throw new TypeError("The last argument must be of type Function"); } var self2 = this; var cb = function() { return maybeCb.apply(self2, arguments); }; original.apply(this, args).then( function(ret) { process.nextTick(cb.bind(null, null, ret)); }, function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)); } ); } Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); Object.defineProperties( callbackified, getOwnPropertyDescriptors(original) ); return callbackified; } exports3.callbackify = callbackify; })(util); var hasRequiredErrors; function requireErrors() { if (hasRequiredErrors) return errors; hasRequiredErrors = 1; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof2(obj2) { return typeof obj2; }; } else { _typeof = function _typeof2(obj2) { return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self2, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self2); } function _assertThisInitialized(self2) { if (self2 === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self2; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o2) { return o2.__proto__ || Object.getPrototypeOf(o2); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var codes = {}; var assert2; var util$12; function createErrorType(code, message, Base) { if (!Base) { Base = Error; } function getMessage(arg1, arg2, arg3) { if (typeof message === "string") { return message; } else { return message(arg1, arg2, arg3); } } var NodeError = /* @__PURE__ */ function(_Base) { _inherits(NodeError2, _Base); function NodeError2(arg1, arg2, arg3) { var _this; _classCallCheck(this, NodeError2); _this = _possibleConstructorReturn(this, _getPrototypeOf(NodeError2).call(this, getMessage(arg1, arg2, arg3))); _this.code = code; return _this; } return NodeError2; }(Base); codes[code] = NodeError; } function oneOf(expected, thing) { if (Array.isArray(expected)) { var len = expected.length; expected = expected.map(function(i) { return String(i); }); if (len > 2) { return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1]; } else if (len === 2) { return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); } else { return "of ".concat(thing, " ").concat(expected[0]); } } else { return "of ".concat(thing, " ").concat(String(expected)); } } function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } function endsWith(str, search, this_len) { if (this_len === void 0 || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } function includes(str, search, start) { if (typeof start !== "number") { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType("ERR_AMBIGUOUS_ARGUMENT", 'The "%s" argument is ambiguous. %s', TypeError); createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { if (assert2 === void 0) assert2 = requireAssert(); assert2(typeof name === "string", "'name' must be a string"); var determiner; if (typeof expected === "string" && startsWith(expected, "not ")) { determiner = "must not be"; expected = expected.replace(/^not /, ""); } else { determiner = "must be"; } var msg; if (endsWith(name, " argument")) { msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, "type")); } else { var type2 = includes(name, ".") ? "property" : "argument"; msg = 'The "'.concat(name, '" ').concat(type2, " ").concat(determiner, " ").concat(oneOf(expected, "type")); } msg += ". Received type ".concat(_typeof(actual)); return msg; }, TypeError); createErrorType("ERR_INVALID_ARG_VALUE", function(name, value) { var reason = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "is invalid"; if (util$12 === void 0) util$12 = util; var inspected = util$12.inspect(value); if (inspected.length > 128) { inspected = "".concat(inspected.slice(0, 128), "..."); } return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); }, TypeError); createErrorType("ERR_INVALID_RETURN_VALUE", function(input, name, value) { var type2; if (value && value.constructor && value.constructor.name) { type2 = "instance of ".concat(value.constructor.name); } else { type2 = "type ".concat(_typeof(value)); } return "Expected ".concat(input, ' to be returned from the "').concat(name, '"') + " function but got ".concat(type2, "."); }, TypeError); createErrorType("ERR_MISSING_ARGS", function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (assert2 === void 0) assert2 = requireAssert(); assert2(args.length > 0, "At least one arg needs to be specified"); var msg = "The "; var len = args.length; args = args.map(function(a) { return '"'.concat(a, '"'); }); switch (len) { case 1: msg += "".concat(args[0], " argument"); break; case 2: msg += "".concat(args[0], " and ").concat(args[1], " arguments"); break; default: msg += args.slice(0, len - 1).join(", "); msg += ", and ".concat(args[len - 1], " arguments"); break; } return "".concat(msg, " must be specified"); }, TypeError); errors.codes = codes; return errors; } var assertion_error; var hasRequiredAssertion_error; function requireAssertion_error() { if (hasRequiredAssertion_error) return assertion_error; hasRequiredAssertion_error = 1; function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === "function") { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self2, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self2); } function _assertThisInitialized(self2) { if (self2 === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self2; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0; _wrapNativeSuper = function _wrapNativeSuper2(Class2) { if (Class2 === null || !_isNativeFunction(Class2)) return Class2; if (typeof Class2 !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class2)) return _cache.get(Class2); _cache.set(Class2, Wrapper); } function Wrapper() { return _construct(Class2, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class2.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class2); }; return _wrapNativeSuper(Class); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function() { })); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct2(Parent2, args2, Class2) { var a = [null]; a.push.apply(a, args2); var Constructor = Function.bind.apply(Parent2, a); var instance = new Constructor(); if (Class2) _setPrototypeOf(instance, Class2.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o2) { return o2.__proto__ || Object.getPrototypeOf(o2); }; return _getPrototypeOf(o); } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof2(obj2) { return typeof obj2; }; } else { _typeof = function _typeof2(obj2) { return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; }; } return _typeof(obj); } var _require = util, inspect = _require.inspect; var _require2 = requireErrors(), ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; function endsWith(str, search, this_len) { if (this_len === void 0 || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } function repeat(str, count2) { count2 = Math.floor(count2); if (str.length == 0 || count2 == 0) return ""; var maxCount = str.length * count2; count2 = Math.floor(Math.log(count2) / Math.log(2)); while (count2) { str += str; count2--; } str += str.substring(0, maxCount - str.length); return str; } var blue = ""; var green = ""; var red = ""; var white = ""; var kReadableOperator = { deepStrictEqual: "Expected values to be strictly deep-equal:", strictEqual: "Expected values to be strictly equal:", strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', deepEqual: "Expected values to be loosely deep-equal:", equal: "Expected values to be loosely equal:", notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', notStrictEqual: 'Expected "actual" to be strictly unequal to:', notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', notEqual: 'Expected "actual" to be loosely unequal to:', notIdentical: "Values identical but not reference-equal:" }; var kMaxShortLength = 10; function copyError(source) { var keys = Object.keys(source); var target = Object.create(Object.getPrototypeOf(source)); keys.forEach(function(key) { target[key] = source[key]; }); Object.defineProperty(target, "message", { value: source.message }); return target; } function inspectValue(val) { return inspect(val, { compact: false, customInspect: false, depth: 1e3, maxArrayLength: Infinity, // Assert compares only enumerable properties (with a few exceptions). showHidden: false, // Having a long line as error is better than wrapping the line for // comparison for now. // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we // have meta information about the inspected properties (i.e., know where // in what line the property starts and ends). breakLength: Infinity, // Assert does not detect proxies currently. showProxy: false, sorted: true, // Inspect getters as we also check them when comparing entries. getters: true }); } function createErrDiff(actual, expected, operator) { var other = ""; var res = ""; var lastPos = 0; var end = ""; var skipped = false; var actualInspected = inspectValue(actual); var actualLines = actualInspected.split("\n"); var expectedLines = inspectValue(expected).split("\n"); var i = 0; var indicator = ""; if (operator === "strictEqual" && _typeof(actual) === "object" && _typeof(expected) === "object" && actual !== null && expected !== null) { operator = "strictEqualObject"; } if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { var inputLength = actualLines[0].length + expectedLines[0].length; if (inputLength <= kMaxShortLength) { if ((_typeof(actual) !== "object" || actual === null) && (_typeof(expected) !== "object" || expected === null) && (actual !== 0 || expected !== 0)) { return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); } } else if (operator !== "strictEqualObject") { var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; if (inputLength < maxLength) { while (actualLines[0][i] === expectedLines[0][i]) { i++; } if (i > 2) { indicator = "\n ".concat(repeat(" ", i), "^"); i = 0; } } } } var a = actualLines[actualLines.length - 1]; var b = expectedLines[expectedLines.length - 1]; while (a === b) { if (i++ < 2) { end = "\n ".concat(a).concat(end); } else { other = a; } actualLines.pop(); expectedLines.pop(); if (actualLines.length === 0 || expectedLines.length === 0) break; a = actualLines[actualLines.length - 1]; b = expectedLines[expectedLines.length - 1]; } var maxLines = Math.max(actualLines.length, expectedLines.length); if (maxLines === 0) { var _actualLines = actualInspected.split("\n"); if (_actualLines.length > 30) { _actualLines[26] = "".concat(blue, "...").concat(white); while (_actualLines.length > 27) { _actualLines.pop(); } } return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join("\n"), "\n"); } if (i > 3) { end = "\n".concat(blue, "...").concat(white).concat(end); skipped = true; } if (other !== "") { end = "\n ".concat(other).concat(end); other = ""; } var printedLines = 0; var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); for (i = 0; i < maxLines; i++) { var cur = i - lastPos; if (actualLines.length < i + 1) { if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(expectedLines[i - 2]); printedLines++; } res += "\n ".concat(expectedLines[i - 1]); printedLines++; } lastPos = i; other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); printedLines++; } else if (expectedLines.length < i + 1) { if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(actualLines[i - 2]); printedLines++; } res += "\n ".concat(actualLines[i - 1]); printedLines++; } lastPos = i; res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); printedLines++; } else { var expectedLine = expectedLines[i]; var actualLine = actualLines[i]; var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ",") || actualLine.slice(0, -1) !== expectedLine); if (divergingLines && endsWith(expectedLine, ",") && expectedLine.slice(0, -1) === actualLine) { divergingLines = false; actualLine += ","; } if (divergingLines) { if (cur > 1 && i > 2) { if (cur > 4) { res += "\n".concat(blue, "...").concat(white); skipped = true; } else if (cur > 3) { res += "\n ".concat(actualLines[i - 2]); printedLines++; } res += "\n ".concat(actualLines[i - 1]); printedLines++; } lastPos = i; res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); printedLines += 2; } else { res += other; other = ""; if (cur === 1 || i === 0) { res += "\n ".concat(actualLine); printedLines++; } } } if (printedLines > 20 && i < maxLines - 2) { return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white); } } return "".concat(msg).concat(skipped ? skippedMsg : "", "\n").concat(res).concat(other).concat(end).concat(indicator); } var AssertionError = /* @__PURE__ */ function(_Error) { _inherits(AssertionError2, _Error); function AssertionError2(options) { var _this; _classCallCheck(this, AssertionError2); if (_typeof(options) !== "object" || options === null) { throw new ERR_INVALID_ARG_TYPE("options", "Object", options); } var message = options.message, operator = options.operator, stackStartFn = options.stackStartFn; var actual = options.actual, expected = options.expected; var limit = Error.stackTraceLimit; Error.stackTraceLimit = 0; if (message != null) { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, String(message))); } else { if (process.stderr && process.stderr.isTTY) { if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) { blue = "\x1B[34m"; green = "\x1B[32m"; white = "\x1B[39m"; red = "\x1B[31m"; } else { blue = ""; green = ""; white = ""; red = ""; } } if (_typeof(actual) === "object" && actual !== null && _typeof(expected) === "object" && expected !== null && "stack" in actual && actual instanceof Error && "stack" in expected && expected instanceof Error) { actual = copyError(actual); expected = copyError(expected); } if (operator === "deepStrictEqual" || operator === "strictEqual") { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, createErrDiff(actual, expected, operator))); } else if (operator === "notDeepStrictEqual" || operator === "notStrictEqual") { var base = kReadableOperator[operator]; var res = inspectValue(actual).split("\n"); if (operator === "notStrictEqual" && _typeof(actual) === "object" && actual !== null) { base = kReadableOperator.notStrictEqualObject; } if (res.length > 30) { res[26] = "".concat(blue, "...").concat(white); while (res.length > 27) { res.pop(); } } if (res.length === 1) { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, "".concat(base, " ").concat(res[0]))); } else { _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, "".concat(base, "\n\n").concat(res.join("\n"), "\n"))); } } else { var _res = inspectValue(actual); var other = ""; var knownOperators = kReadableOperator[operator]; if (operator === "notDeepEqual" || operator === "notEqual") { _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); if (_res.length > 1024) { _res = "".concat(_res.slice(0, 1021), "..."); } } else { other = "".concat(inspectValue(expected)); if (_res.length > 512) { _res = "".concat(_res.slice(0, 509), "..."); } if (other.length > 512) { other = "".concat(other.slice(0, 509), "..."); } if (operator === "deepEqual" || operator === "equal") { _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); } else { other = " ".concat(operator, " ").concat(other); } } _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError2).call(this, "".concat(_res).concat(other))); } } Error.stackTraceLimit = limit; _this.generatedMessage = !message; Object.defineProperty(_assertThisInitialized(_this), "name", { value: "AssertionError [ERR_ASSERTION]", enumerable: false, writable: true, configurable: true }); _this.code = "ERR_ASSERTION"; _this.actual = actual; _this.expected = expected; _this.operator = operator; if (Error.captureStackTrace) { Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); } _this.stack; _this.name = "AssertionError"; return _possibleConstructorReturn(_this); } _createClass(AssertionError2, [{ key: "toString", value: function toString() { return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); } }, { key: inspect.custom, value: function value(recurseTimes, ctx) { return inspect(this, _objectSpread({}, ctx, { customInspect: false, depth: 0 })); } }]); return AssertionError2; }(_wrapNativeSuper(Error)); assertion_error = AssertionError; return assertion_error; } var es6ObjectAssign; var hasRequiredEs6ObjectAssign; function requireEs6ObjectAssign() { if (hasRequiredEs6ObjectAssign) return es6ObjectAssign; hasRequiredEs6ObjectAssign = 1; function assign(target, firstSource) { if (target === void 0 || target === null) { throw new TypeError("Cannot convert first argument to object"); } var to = Object(target); for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === void 0 || nextSource === null) { continue; } var keysArray = Object.keys(Object(nextSource)); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { var nextKey = keysArray[nextIndex]; var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== void 0 && desc.enumerable) { to[nextKey] = nextSource[nextKey]; } } } return to; } function polyfill2() { if (!Object.assign) { Object.defineProperty(Object, "assign", { enumerable: false, configurable: true, writable: true, value: assign }); } } es6ObjectAssign = { assign, polyfill: polyfill2 }; return es6ObjectAssign; } var isArguments; var hasRequiredIsArguments; function requireIsArguments() { if (hasRequiredIsArguments) return isArguments; hasRequiredIsArguments = 1; var toStr2 = Object.prototype.toString; isArguments = function isArguments2(value) { var str = toStr2.call(value); var isArgs = str === "[object Arguments]"; if (!isArgs) { isArgs = str !== "[object Array]" && value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && toStr2.call(value.callee) === "[object Function]"; } return isArgs; }; return isArguments; } var implementation$2; var hasRequiredImplementation$2; function requireImplementation$2() { if (hasRequiredImplementation$2) return implementation$2; hasRequiredImplementation$2 = 1; var keysShim; if (!Object.keys) { var has = Object.prototype.hasOwnProperty; var toStr2 = Object.prototype.toString; var isArgs = requireIsArguments(); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, "toString"); var hasProtoEnumBug = isEnumerable.call(function() { }, "prototype"); var dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ]; var equalsConstructorPrototype = function(o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $onmozfullscreenchange: true, $onmozfullscreenerror: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = function() { if (typeof window === "undefined") { return false; } for (var k in window) { try { if (!excludedKeys["$" + k] && has.call(window, k) && window[k] !== null && typeof window[k] === "object") { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }(); var equalsConstructorPrototypeIfNotBuggy = function(o) { if (typeof window === "undefined" || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; keysShim = function keys(object) { var isObject = object !== null && typeof object === "object"; var isFunction = toStr2.call(object) === "[object Function]"; var isArguments2 = isArgs(object); var isString2 = isObject && toStr2.call(object) === "[object String]"; var theKeys = []; if (!isObject && !isFunction && !isArguments2) { throw new TypeError("Object.keys called on a non-object"); } var skipProto = hasProtoEnumBug && isFunction; if (isString2 && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments2 && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === "prototype") && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === "constructor") && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } implementation$2 = keysShim; return implementation$2; } var objectKeys; var hasRequiredObjectKeys; function requireObjectKeys() { if (hasRequiredObjectKeys) return objectKeys; hasRequiredObjectKeys = 1; var slice = Array.prototype.slice; var isArgs = requireIsArguments(); var origKeys = Object.keys; var keysShim = origKeys ? function keys(o) { return origKeys(o); } : requireImplementation$2(); var originalKeys = Object.keys; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = function() { var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2); if (!keysWorksWithArguments) { Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; objectKeys = keysShim; return objectKeys; } var hasPropertyDescriptors_1; var hasRequiredHasPropertyDescriptors; function requireHasPropertyDescriptors() { if (hasRequiredHasPropertyDescriptors) return hasPropertyDescriptors_1; hasRequiredHasPropertyDescriptors = 1; var GetIntrinsic2 = requireGetIntrinsic(); var $defineProperty = GetIntrinsic2("%Object.defineProperty%", true); var hasPropertyDescriptors = function hasPropertyDescriptors2() { if ($defineProperty) { try { $defineProperty({}, "a", { value: 1 }); return true; } catch (e) { return false; } } return false; }; hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { if (!hasPropertyDescriptors()) { return null; } try { return $defineProperty([], "length", { value: 1 }).length !== 1; } catch (e) { return true; } }; hasPropertyDescriptors_1 = hasPropertyDescriptors; return hasPropertyDescriptors_1; } var defineProperties_1; var hasRequiredDefineProperties; function requireDefineProperties() { if (hasRequiredDefineProperties) return defineProperties_1; hasRequiredDefineProperties = 1; var keys = requireObjectKeys(); var hasSymbols2 = typeof Symbol === "function" && typeof Symbol("foo") === "symbol"; var toStr2 = Object.prototype.toString; var concat = Array.prototype.concat; var origDefineProperty = Object.defineProperty; var isFunction = function(fn) { return typeof fn === "function" && toStr2.call(fn) === "[object Function]"; }; var hasPropertyDescriptors = requireHasPropertyDescriptors()(); var supportsDescriptors = origDefineProperty && hasPropertyDescriptors; var defineProperty = function(object, name, value, predicate) { if (name in object) { if (predicate === true) { if (object[name] === value) { return; } } else if (!isFunction(predicate) || !predicate()) { return; } } if (supportsDescriptors) { origDefineProperty(object, name, { configurable: true, enumerable: false, value, writable: true }); } else { object[name] = value; } }; var defineProperties = function(object, map2) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map2); if (hasSymbols2) { props = concat.call(props, Object.getOwnPropertySymbols(map2)); } for (var i = 0; i < props.length; i += 1) { defineProperty(object, props[i], map2[props[i]], predicates[props[i]]); } }; defineProperties.supportsDescriptors = !!supportsDescriptors; defineProperties_1 = defineProperties; return defineProperties_1; } var implementation$1; var hasRequiredImplementation$1; function requireImplementation$1() { if (hasRequiredImplementation$1) return implementation$1; hasRequiredImplementation$1 = 1; var numberIsNaN = function(value) { return value !== value; }; implementation$1 = function is(a, b) { if (a === 0 && b === 0) { return 1 / a === 1 / b; } if (a === b) { return true; } if (numberIsNaN(a) && numberIsNaN(b)) { return true; } return false; }; return implementation$1; } var polyfill$1; var hasRequiredPolyfill$1; function requirePolyfill$1() { if (hasRequiredPolyfill$1) return polyfill$1; hasRequiredPolyfill$1 = 1; var implementation2 = requireImplementation$1(); polyfill$1 = function getPolyfill() { return typeof Object.is === "function" ? Object.is : implementation2; }; return polyfill$1; } var shim$1; var hasRequiredShim$1; function requireShim$1() { if (hasRequiredShim$1) return shim$1; hasRequiredShim$1 = 1; var getPolyfill = requirePolyfill$1(); var define2 = requireDefineProperties(); shim$1 = function shimObjectIs() { var polyfill2 = getPolyfill(); define2(Object, { is: polyfill2 }, { is: function testObjectIs() { return Object.is !== polyfill2; } }); return polyfill2; }; return shim$1; } var objectIs; var hasRequiredObjectIs; function requireObjectIs() { if (hasRequiredObjectIs) return objectIs; hasRequiredObjectIs = 1; var define2 = requireDefineProperties(); var callBind2 = requireCallBind(); var implementation2 = requireImplementation$1(); var getPolyfill = requirePolyfill$1(); var shim2 = requireShim$1(); var polyfill2 = callBind2(getPolyfill(), Object); define2(polyfill2, { getPolyfill, implementation: implementation2, shim: shim2 }); objectIs = polyfill2; return objectIs; } var implementation; var hasRequiredImplementation; function requireImplementation() { if (hasRequiredImplementation) return implementation; hasRequiredImplementation = 1; implementation = function isNaN2(value) { return value !== value; }; return implementation; } var polyfill; var hasRequiredPolyfill; function requirePolyfill() { if (hasRequiredPolyfill) return polyfill; hasRequiredPolyfill = 1; var implementation2 = requireImplementation(); polyfill = function getPolyfill() { if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN("a")) { return Number.isNaN; } return implementation2; }; return polyfill; } var shim; var hasRequiredShim; function requireShim() { if (hasRequiredShim) return shim; hasRequiredShim = 1; var define2 = requireDefineProperties(); var getPolyfill = requirePolyfill(); shim = function shimNumberIsNaN() { var polyfill2 = getPolyfill(); define2(Number, { isNaN: polyfill2 }, { isNaN: function testIsNaN() { return Number.isNaN !== polyfill2; } }); return polyfill2; }; return shim; } var isNan; var hasRequiredIsNan; function requireIsNan() { if (hasRequiredIsNan) return isNan; hasRequiredIsNan = 1; var callBind2 = requireCallBind(); var define2 = requireDefineProperties(); var implementation2 = requireImplementation(); var getPolyfill = requirePolyfill(); var shim2 = requireShim(); var polyfill2 = callBind2(getPolyfill(), Number); define2(polyfill2, { getPolyfill, implementation: implementation2, shim: shim2 }); isNan = polyfill2; return isNan; } var comparisons; var hasRequiredComparisons; function requireComparisons() { if (hasRequiredComparisons) return comparisons; hasRequiredComparisons = 1; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = void 0; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err2) { _d = true; _e = err2; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof2(obj2) { return typeof obj2; }; } else { _typeof = function _typeof2(obj2) { return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; }; } return _typeof(obj); } var regexFlagsSupported = /a/g.flags !== void 0; var arrayFromSet = function arrayFromSet2(set) { var array = []; set.forEach(function(value) { return array.push(value); }); return array; }; var arrayFromMap = function arrayFromMap2(map2) { var array = []; map2.forEach(function(value, key) { return array.push([key, value]); }); return array; }; var objectIs2 = Object.is ? Object.is : requireObjectIs(); var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function() { return []; }; var numberIsNaN = Number.isNaN ? Number.isNaN : requireIsNan(); function uncurryThis(f) { return f.call.bind(f); } var hasOwnProperty2 = uncurryThis(Object.prototype.hasOwnProperty); var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); var objectToString = uncurryThis(Object.prototype.toString); var _require$types = util.types, isAnyArrayBuffer = _require$types.isAnyArrayBuffer, isArrayBufferView = _require$types.isArrayBufferView, isDate = _require$types.isDate, isMap = _require$types.isMap, isRegExp = _require$types.isRegExp, isSet = _require$types.isSet, isNativeError = _require$types.isNativeError, isBoxedPrimitive = _require$types.isBoxedPrimitive, isNumberObject = _require$types.isNumberObject, isStringObject = _require$types.isStringObject, isBooleanObject = _require$types.isBooleanObject, isBigIntObject = _require$types.isBigIntObject, isSymbolObject = _require$types.isSymbolObject, isFloat32Array = _require$types.isFloat32Array, isFloat64Array = _require$types.isFloat64Array; function isNonIndex(key) { if (key.length === 0 || key.length > 10) return true; for (var i = 0; i < key.length; i++) { var code = key.charCodeAt(i); if (code < 48 || code > 57) return true; } return key.length === 10 && key >= Math.pow(2, 32); } function getOwnNonIndexProperties(value) { return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); } /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a, b) { if (a === b) { return 0; } var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) { return -1; } if (y < x) { return 1; } return 0; } var kStrict = true; var kLoose = false; var kNoIterator = 0; var kIsArray = 1; var kIsSet = 2; var kIsMap = 3; function areSimilarRegExps(a, b) { return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); } function areSimilarFloatArrays(a, b) { if (a.byteLength !== b.byteLength) { return false; } for (var offset = 0; offset < a.byteLength; offset++) { if (a[offset] !== b[offset]) { return false; } } return true; } function areSimilarTypedArrays(a, b) { if (a.byteLength !== b.byteLength) { return false; } return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; } function areEqualArrayBuffers(buf1, buf2) { return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; } function isEqualBoxedPrimitive(val1, val2) { if (isNumberObject(val1)) { return isNumberObject(val2) && objectIs2(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); } if (isStringObject(val1)) { return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); } if (isBooleanObject(val1)) { return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); } if (isBigIntObject(val1)) { return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); } return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); } function innerDeepEqual(val1, val2, strict, memos) { if (val1 === val2) { if (val1 !== 0) return true; return strict ? objectIs2(val1, val2) : true; } if (strict) { if (_typeof(val1) !== "object") { return typeof val1 === "number" && numberIsNaN(val1) && numberIsNaN(val2); } if (_typeof(val2) !== "object" || val1 === null || val2 === null) { return false; } if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { return false; } } else { if (val1 === null || _typeof(val1) !== "object") { if (val2 === null || _typeof(val2) !== "object") { return val1 == val2; } return false; } if (val2 === null || _typeof(val2) !== "object") { return false; } } var val1Tag = objectToString(val1); var val2Tag = objectToString(val2); if (val1Tag !== val2Tag) { return false; } if (Array.isArray(val1)) { if (val1.length !== val2.length) { return false; } var keys1 = getOwnNonIndexProperties(val1); var keys2 = getOwnNonIndexProperties(val2); if (keys1.length !== keys2.length) { return false; } return keyCheck(val1, val2, strict, memos, kIsArray, keys1); } if (val1Tag === "[object Object]") { if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) { return false; } } if (isDate(val1)) { if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { return false; } } else if (isRegExp(val1)) { if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { return false; } } else if (isNativeError(val1) || val1 instanceof Error) { if (val1.message !== val2.message || val1.name !== val2.name) { return false; } } else if (isArrayBufferView(val1)) { if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { if (!areSimilarFloatArrays(val1, val2)) { return false; } } else if (!areSimilarTypedArrays(val1, val2)) { return false; } var _keys = getOwnNonIndexProperties(val1); var _keys2 = getOwnNonIndexProperties(val2); if (_keys.length !== _keys2.length) { return false; } return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); } else if (isSet(val1)) { if (!isSet(val2) || val1.size !== val2.size) { return false; } return keyCheck(val1, val2, strict, memos, kIsSet); } else if (isMap(val1)) { if (!isMap(val2) || val1.size !== val2.size) { return false; } return keyCheck(val1, val2, strict, memos, kIsMap); } else if (isAnyArrayBuffer(val1)) { if (!areEqualArrayBuffers(val1, val2)) { return false; } } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { return false; } return keyCheck(val1, val2, strict, memos, kNoIterator); } function getEnumerables(val, keys) { return keys.filter(function(k) { return propertyIsEnumerable(val, k); }); } function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { if (arguments.length === 5) { aKeys = Object.keys(val1); var bKeys = Object.keys(val2); if (aKeys.length !== bKeys.length) { return false; } } var i = 0; for (; i < aKeys.length; i++) { if (!hasOwnProperty2(val2, aKeys[i])) { return false; } } if (strict && arguments.length === 5) { var symbolKeysA = objectGetOwnPropertySymbols(val1); if (symbolKeysA.length !== 0) { var count2 = 0; for (i = 0; i < symbolKeysA.length; i++) { var key = symbolKeysA[i]; if (propertyIsEnumerable(val1, key)) { if (!propertyIsEnumerable(val2, key)) { return false; } aKeys.push(key); count2++; } else if (propertyIsEnumerable(val2, key)) { return false; } } var symbolKeysB = objectGetOwnPropertySymbols(val2); if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count2) { return false; } } else { var _symbolKeysB = objectGetOwnPropertySymbols(val2); if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { return false; } } } if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { return true; } if (memos === void 0) { memos = { val1: /* @__PURE__ */ new Map(), val2: /* @__PURE__ */ new Map(), position: 0 }; } else { var val2MemoA = memos.val1.get(val1); if (val2MemoA !== void 0) { var val2MemoB = memos.val2.get(val2); if (val2MemoB !== void 0) { return val2MemoA === val2MemoB; } } memos.position++; } memos.val1.set(val1, memos.position); memos.val2.set(val2, memos.position); var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); memos.val1.delete(val1); memos.val2.delete(val2); return areEq; } function setHasEqualElement(set, val1, strict, memo) { var setValues = arrayFromSet(set); for (var i = 0; i < setValues.length; i++) { var val2 = setValues[i]; if (innerDeepEqual(val1, val2, strict, memo)) { set.delete(val2); return true; } } return false; } function findLooseMatchingPrimitives(prim) { switch (_typeof(prim)) { case "undefined": return null; case "object": return void 0; case "symbol": return false; case "string": prim = +prim; case "number": if (numberIsNaN(prim)) { return false; } } return true; } function setMightHaveLoosePrim(a, b, prim) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) return altValue; return b.has(altValue) && !a.has(altValue); } function mapMightHaveLoosePrim(a, b, prim, item, memo) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) { return altValue; } var curB = b.get(altValue); if (curB === void 0 && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { return false; } return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); } function setEquiv(a, b, strict, memo) { var set = null; var aValues = arrayFromSet(a); for (var i = 0; i < aValues.length; i++) { var val = aValues[i]; if (_typeof(val) === "object" && val !== null) { if (set === null) { set = /* @__PURE__ */ new Set(); } set.add(val); } else if (!b.has(val)) { if (strict) return false; if (!setMightHaveLoosePrim(a, b, val)) { return false; } if (set === null) { set = /* @__PURE__ */ new Set(); } set.add(val); } } if (set !== null) { var bValues = arrayFromSet(b); for (var _i = 0; _i < bValues.length; _i++) { var _val = bValues[_i]; if (_typeof(_val) === "object" && _val !== null) { if (!setHasEqualElement(set, _val, strict, memo)) return false; } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) { return false; } } return set.size === 0; } return true; } function mapHasEqualEntry(set, map2, key1, item1, strict, memo) { var setValues = arrayFromSet(set); for (var i = 0; i < setValues.length; i++) { var key2 = setValues[i]; if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map2.get(key2), strict, memo)) { set.delete(key2); return true; } } return false; } function mapEquiv(a, b, strict, memo) { var set = null; var aEntries = arrayFromMap(a); for (var i = 0; i < aEntries.length; i++) { var _aEntries$i = _slicedToArray(aEntries[i], 2), key = _aEntries$i[0], item1 = _aEntries$i[1]; if (_typeof(key) === "object" && key !== null) { if (set === null) { set = /* @__PURE__ */ new Set(); } set.add(key); } else { var item2 = b.get(key); if (item2 === void 0 && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) { if (strict) return false; if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; if (set === null) { set = /* @__PURE__ */ new Set(); } set.add(key); } } } if (set !== null) { var bEntries = arrayFromMap(b); for (var _i2 = 0; _i2 < bEntries.length; _i2++) { var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), key = _bEntries$_i[0], item = _bEntries$_i[1]; if (_typeof(key) === "object" && key !== null) { if (!mapHasEqualEntry(set, a, key, item, strict, memo)) return false; } else if (!strict && (!a.has(key) || !innerDeepEqual(a.get(key), item, false, memo)) && !mapHasEqualEntry(set, a, key, item, false, memo)) { return false; } } return set.size === 0; } return true; } function objEquiv(a, b, strict, keys, memos, iterationType) { var i = 0; if (iterationType === kIsSet) { if (!setEquiv(a, b, strict, memos)) { return false; } } else if (iterationType === kIsMap) { if (!mapEquiv(a, b, strict, memos)) { return false; } } else if (iterationType === kIsArray) { for (; i < a.length; i++) { if (hasOwnProperty2(a, i)) { if (!hasOwnProperty2(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { return false; } } else if (hasOwnProperty2(b, i)) { return false; } else { var keysA = Object.keys(a); for (; i < keysA.length; i++) { var key = keysA[i]; if (!hasOwnProperty2(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { return false; } } if (keysA.length !== Object.keys(b).length) { return false; } return true; } } } for (i = 0; i < keys.length; i++) { var _key = keys[i]; if (!innerDeepEqual(a[_key], b[_key], strict, memos)) { return false; } } return true; } function isDeepEqual(val1, val2) { return innerDeepEqual(val1, val2, kLoose); } function isDeepStrictEqual(val1, val2) { return innerDeepEqual(val1, val2, kStrict); } comparisons = { isDeepEqual, isDeepStrictEqual }; return comparisons; } var hasRequiredAssert; function requireAssert() { if (hasRequiredAssert) return assert$1.exports; hasRequiredAssert = 1; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof2(obj2) { return typeof obj2; }; } else { _typeof = function _typeof2(obj2) { return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = requireErrors(), _require$codes = _require.codes, ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; var AssertionError = requireAssertion_error(); var _require2 = util, inspect = _require2.inspect; var _require$types = util.types, isPromise = _require$types.isPromise, isRegExp = _require$types.isRegExp; var objectAssign = Object.assign ? Object.assign : requireEs6ObjectAssign().assign; var objectIs2 = Object.is ? Object.is : requireObjectIs(); var isDeepEqual; var isDeepStrictEqual; function lazyLoadComparison() { var comparison = requireComparisons(); isDeepEqual = comparison.isDeepEqual; isDeepStrictEqual = comparison.isDeepStrictEqual; } var warned = false; var assert2 = assert$1.exports = ok2; var NO_EXCEPTION_SENTINEL = {}; function innerFail(obj) { if (obj.message instanceof Error) throw obj.message; throw new AssertionError(obj); } function fail(actual, expected, message, operator, stackStartFn) { var argsLen = arguments.length; var internalMessage; if (argsLen === 0) { internalMessage = "Failed"; } else if (argsLen === 1) { message = actual; actual = void 0; } else { if (warned === false) { warned = true; var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console); warn("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.", "DeprecationWarning", "DEP0094"); } if (argsLen === 2) operator = "!="; } if (message instanceof Error) throw message; var errArgs = { actual, expected, operator: operator === void 0 ? "fail" : operator, stackStartFn: stackStartFn || fail }; if (message !== void 0) { errArgs.message = message; } var err2 = new AssertionError(errArgs); if (internalMessage) { err2.message = internalMessage; err2.generatedMessage = true; } throw err2; } assert2.fail = fail; assert2.AssertionError = AssertionError; function innerOk(fn, argLen, value, message) { if (!value) { var generatedMessage = false; if (argLen === 0) { generatedMessage = true; message = "No value argument passed to `assert.ok()`"; } else if (message instanceof Error) { throw message; } var err2 = new AssertionError({ actual: value, expected: true, message, operator: "==", stackStartFn: fn }); err2.generatedMessage = generatedMessage; throw err2; } } function ok2() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } innerOk.apply(void 0, [ok2, args.length].concat(args)); } assert2.ok = ok2; assert2.equal = function equal(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (actual != expected) { innerFail({ actual, expected, message, operator: "==", stackStartFn: equal }); } }; assert2.notEqual = function notEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (actual == expected) { innerFail({ actual, expected, message, operator: "!=", stackStartFn: notEqual }); } }; assert2.deepEqual = function deepEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (isDeepEqual === void 0) lazyLoadComparison(); if (!isDeepEqual(actual, expected)) { innerFail({ actual, expected, message, operator: "deepEqual", stackStartFn: deepEqual }); } }; assert2.notDeepEqual = function notDeepEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (isDeepEqual === void 0) lazyLoadComparison(); if (isDeepEqual(actual, expected)) { innerFail({ actual, expected, message, operator: "notDeepEqual", stackStartFn: notDeepEqual }); } }; assert2.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (isDeepEqual === void 0) lazyLoadComparison(); if (!isDeepStrictEqual(actual, expected)) { innerFail({ actual, expected, message, operator: "deepStrictEqual", stackStartFn: deepStrictEqual }); } }; assert2.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (isDeepEqual === void 0) lazyLoadComparison(); if (isDeepStrictEqual(actual, expected)) { innerFail({ actual, expected, message, operator: "notDeepStrictEqual", stackStartFn: notDeepStrictEqual }); } } assert2.strictEqual = function strictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (!objectIs2(actual, expected)) { innerFail({ actual, expected, message, operator: "strictEqual", stackStartFn: strictEqual }); } }; assert2.notStrictEqual = function notStrictEqual(actual, expected, message) { if (arguments.length < 2) { throw new ERR_MISSING_ARGS("actual", "expected"); } if (objectIs2(actual, expected)) { innerFail({ actual, expected, message, operator: "notStrictEqual", stackStartFn: notStrictEqual }); } }; var Comparison = function Comparison2(obj, keys, actual) { var _this = this; _classCallCheck(this, Comparison2); keys.forEach(function(key) { if (key in obj) { if (actual !== void 0 && typeof actual[key] === "string" && isRegExp(obj[key]) && obj[key].test(actual[key])) { _this[key] = actual[key]; } else { _this[key] = obj[key]; } } }); }; function compareExceptionKey(actual, expected, key, message, keys, fn) { if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { if (!message) { var a = new Comparison(actual, keys); var b = new Comparison(expected, keys, actual); var err2 = new AssertionError({ actual: a, expected: b, operator: "deepStrictEqual", stackStartFn: fn }); err2.actual = actual; err2.expected = expected; err2.operator = fn.name; throw err2; } innerFail({ actual, expected, message, operator: fn.name, stackStartFn: fn }); } } function expectedException(actual, expected, msg, fn) { if (typeof expected !== "function") { if (isRegExp(expected)) return expected.test(actual); if (arguments.length === 2) { throw new ERR_INVALID_ARG_TYPE("expected", ["Function", "RegExp"], expected); } if (_typeof(actual) !== "object" || actual === null) { var err2 = new AssertionError({ actual, expected, message: msg, operator: "deepStrictEqual", stackStartFn: fn }); err2.operator = fn.name; throw err2; } var keys = Object.keys(expected); if (expected instanceof Error) { keys.push("name", "message"); } else if (keys.length === 0) { throw new ERR_INVALID_ARG_VALUE("error", expected, "may not be an empty object"); } if (isDeepEqual === void 0) lazyLoadComparison(); keys.forEach(function(key) { if (typeof actual[key] === "string" && isRegExp(expected[key]) && expected[key].test(actual[key])) { return; } compareExceptionKey(actual, expected, key, msg, keys, fn); }); return true; } if (expected.prototype !== void 0 && actual instanceof expected) { return true; } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function getActual(fn) { if (typeof fn !== "function") { throw new ERR_INVALID_ARG_TYPE("fn", "Function", fn); } try { fn(); } catch (e) { return e; } return NO_EXCEPTION_SENTINEL; } function checkIsPromise(obj) { return isPromise(obj) || obj !== null && _typeof(obj) === "object" && typeof obj.then === "function" && typeof obj.catch === "function"; } function waitForActual(promiseFn) { return Promise.resolve().then(function() { var resultPromise; if (typeof promiseFn === "function") { resultPromise = promiseFn(); if (!checkIsPromise(resultPromise)) { throw new ERR_INVALID_RETURN_VALUE("instance of Promise", "promiseFn", resultPromise); } } else if (checkIsPromise(promiseFn)) { resultPromise = promiseFn; } else { throw new ERR_INVALID_ARG_TYPE("promiseFn", ["Function", "Promise"], promiseFn); } return Promise.resolve().then(function() { return resultPromise; }).then(function() { return NO_EXCEPTION_SENTINEL; }).catch(function(e) { return e; }); }); } function expectsError(stackStartFn, actual, error, message) { if (typeof error === "string") { if (arguments.length === 4) { throw new ERR_INVALID_ARG_TYPE("error", ["Object", "Error", "Function", "RegExp"], error); } if (_typeof(actual) === "object" && actual !== null) { if (actual.message === error) { throw new ERR_AMBIGUOUS_ARGUMENT("error/message", 'The error message "'.concat(actual.message, '" is identical to the message.')); } } else if (actual === error) { throw new ERR_AMBIGUOUS_ARGUMENT("error/message", 'The error "'.concat(actual, '" is identical to the message.')); } message = error; error = void 0; } else if (error != null && _typeof(error) !== "object" && typeof error !== "function") { throw new ERR_INVALID_ARG_TYPE("error", ["Object", "Error", "Function", "RegExp"], error); } if (actual === NO_EXCEPTION_SENTINEL) { var details = ""; if (error && error.name) { details += " (".concat(error.name, ")"); } details += message ? ": ".concat(message) : "."; var fnType = stackStartFn.name === "rejects" ? "rejection" : "exception"; innerFail({ actual: void 0, expected: error, operator: stackStartFn.name, message: "Missing expected ".concat(fnType).concat(details), stackStartFn }); } if (error && !expectedException(actual, error, message, stackStartFn)) { throw actual; } } function expectsNoError(stackStartFn, actual, error, message) { if (actual === NO_EXCEPTION_SENTINEL) return; if (typeof error === "string") { message = error; error = void 0; } if (!error || expectedException(actual, error)) { var details = message ? ": ".concat(message) : "."; var fnType = stackStartFn.name === "doesNotReject" ? "rejection" : "exception"; innerFail({ actual, expected: error, operator: stackStartFn.name, message: "Got unwanted ".concat(fnType).concat(details, "\n") + 'Actual message: "'.concat(actual && actual.message, '"'), stackStartFn }); } throw actual; } assert2.throws = function throws(promiseFn) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args)); }; assert2.rejects = function rejects(promiseFn) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return waitForActual(promiseFn).then(function(result) { return expectsError.apply(void 0, [rejects, result].concat(args)); }); }; assert2.doesNotThrow = function doesNotThrow(fn) { for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); }; assert2.doesNotReject = function doesNotReject(fn) { for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { args[_key5 - 1] = arguments[_key5]; } return waitForActual(fn).then(function(result) { return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); }); }; assert2.ifError = function ifError(err2) { if (err2 !== null && err2 !== void 0) { var message = "ifError got unwanted exception: "; if (_typeof(err2) === "object" && typeof err2.message === "string") { if (err2.message.length === 0 && err2.constructor) { message += err2.constructor.name; } else { message += err2.message; } } else { message += inspect(err2); } var newErr = new AssertionError({ actual: err2, expected: null, operator: "ifError", message, stackStartFn: ifError }); var origStack = err2.stack; if (typeof origStack === "string") { var tmp2 = origStack.split("\n"); tmp2.shift(); var tmp1 = newErr.stack.split("\n"); for (var i = 0; i < tmp2.length; i++) { var pos = tmp1.indexOf(tmp2[i]); if (pos !== -1) { tmp1 = tmp1.slice(0, pos); break; } } newErr.stack = "".concat(tmp1.join("\n"), "\n").concat(tmp2.join("\n")); } throw newErr; } }; function strict() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } innerOk.apply(void 0, [strict, args.length].concat(args)); } assert2.strict = objectAssign(strict, assert2, { equal: assert2.strictEqual, deepEqual: assert2.deepStrictEqual, notEqual: assert2.notStrictEqual, notDeepEqual: assert2.notDeepStrictEqual }); assert2.strict.strict = assert2.strict; return assert$1.exports; } var assertExports = requireAssert(); const assert = /* @__PURE__ */ getDefaultExportFromCjs(assertExports); class Characters { static unicode() { return { hbar: "─", vbar: "│", xbar: "┼", vbar_break: "·", vbar_gap: "⋮", uarrow: "▲", rarrow: "▶", ltop: "╭", mtop: "┬", rtop: "╮", lbot: "╰", mbot: "┴", rbot: "╯", lbox: "[", rbox: "]", lcross: "├", rcross: "┤", underbar: "┬", underline: "─" }; } static ascii() { return { hbar: "-", vbar: "|", xbar: "+", vbar_break: "*", vbar_gap: ":", uarrow: "^", rarrow: ">", ltop: ",", mtop: "v", rtop: ".", lbot: "`", mbot: "^", rbot: "'", lbox: "[", rbox: "]", lcross: "|", rcross: "|", underbar: "|", underline: "^" }; } } var LabelKind = /* @__PURE__ */ ((LabelKind2) => { LabelKind2["Inline"] = "Inline"; LabelKind2["Multiline"] = "Multiline"; return LabelKind2; })(LabelKind || {}); class LabelInfo { constructor(kind, label) { this.kind = kind; this.label = label; } } class ReportBuilder { constructor(kind, code, msg, note, help, location, labels, config) { this.kind = kind; this.code = code; this.msg = msg; this.note = note; this.help = help; this.location = location; this.labels = labels; this.config = config; } /// Give this report a numerical code that may be used to more precisely look up the error in documentation. with_code(code) { this.code = some(code.toString().padStart(2, "0")); return this; } /// Set the message of this report. set_message(msg) { this.msg = some(msg); } /// Add a message to this report. with_message(msg) { this.msg = some(msg); return this; } /// Set the note of this report. set_note(note) { this.note = some(note); } /// Set the note of this report. with_note(note) { this.set_note(note); return this; } /// Set the help message of this report. set_help(note) { this.help = some(note); } /// Set the help message of this report. with_help(note) { this.set_help(note); return this; } /// Add a label to the report. add_label(label) { this.labels.push(label); } /// Add multiple labels to the report. add_labels(labels) { this.labels.push(...labels); } /// Add a label to the report. with_label(label) { this.add_label(label); return this; } /// Use the given [`Config`] to determine diagnostic attributes. with_config(config) { this.config = config; return this; } /// Finish building the [`Report`]. finish() { const r = new Report( this.kind, this.code, this.msg, this.note, this.help, this.location, this.labels, this.config ); return r; } } class ReportKind { constructor(...args) { } fmt(f) { if (this instanceof ReportKind.Error) return write(f.buf, "Error"); if (this instanceof ReportKind.Warning) return write(f.buf, "Warning"); if (this instanceof ReportKind.Advice) return write(f.buf, "Advice"); if (this instanceof ReportKind.Custom) return write(f.buf, "{}", this.s); throw "invalid ReportKind"; } static { this.Error = class Error extends ReportKind { }; } static { this.Warning = class Warning extends ReportKind { }; } static { this.Advice = class Advice extends ReportKind { }; } static { this.Custom = class Custom extends ReportKind { constructor(s, color) { super(); this.s = s; this.color = color; } }; } } class Cache { static from(init) { if (Source.is(init)) return init; if (FnCache.is(init)) return init; const [id, source] = init; return new IdSource(source.lines(), source.len(), init); } } class Line { constructor(_offset, _len, _chars) { this._offset = _offset; this._len = _len; this._chars = _chars; } /// Get the offset of this line in the original [`Source`] (i.e: the number of characters that precede it). offset() { return this._offset; } /// Get the character length of this line. len() { return this._len; } /// Get the offset span of this line in the original [`Source`]. span() { return new Range(this.offset(), this.offset() + this.len()); } /// Return an iterator over the characters in the line, excluding trailing whitespace. chars() { return this._chars; } } class Source { constructor(_lines, _len) { this._lines = _lines; this._len = _len; } /// Generate a [`Source`] from the given [`str`]. /// /// Note that this function can be expensive for long strings. Use an implementor of [`Cache`] where possible. static from(s, ...args) { let offset = 0; const lines = s.split("\n").map((line) => { let l = new Line( offset, line.length + 1, // line.chars().count() + 1, line.trimEnd() ); offset += l.len(); return l; }); return new Source(lines, offset); } /// Get the length of the total number of characters in the source. len() { return this._len; } /// Return an iterator over the characters in the source. chars() { return this.lines().map((l) => l.chars()).flat(); } /// Get access to a specific, zero-indexed [`Line`]. line(idx) { const line = this.lines()[idx]; return line === void 0 ? none() : some(line); } /// Return an iterator over the [`Line`]s in this source. lines() { return this._lines; } /// Get the line that the given offset appears on, and the line/column numbers of the offset. /// /// Note that the line/column numbers are zero-indexed. get_offset_line(offset) { if (offset <= this.len()) { let idx = binary_search_by_key(this.lines(), offset, (line2) => line2.offset()).unwrap_or_else( (idx2) => Math.max(0, idx2.saturating_sub(1)) ); let line = this.lines()[idx]; assert( line && offset >= line.offset(), format("offset = {}, line.offset = {}, idx = {}", offset, line?.offset() ?? Infinity, idx) ); const os = line.offset(); return some([line, idx, offset - os]); } else { return none(); } } /// Get the range of lines that this span runs across. /// /// The resulting range is guaranteed to contain valid line indices (i.e: those that can be used for /// [`Source::line`]). get_line_range(span) { let start = this.get_offset_line(span.start).map_or(0, ([_, l, __]) => l); let end = this.get_offset_line(span.end.saturating_sub(1).max(span.start)).map_or( this.lines().length, ([_, l, __]) => l + 1 ); return new Range(start, end); } fetch(_) { return ok(this); } display(_) { return none(); } static is(other) { return other instanceof Source; } } class IdSource extends Source { constructor(_lines, _len, data) { super(_lines, _len); this.data = data; } fetch(id) { return id === this.data[0] ? ok(this.data[1]) : err(format("Failed to fetch source '{}'", id)); } display(id) { return some(new Display(id)); } } class FnCache { constructor(sources2, get) { this.sources = sources2; this.get = get; } /// Create a new [`FnCache`] with the given fetch function. static new(get) { return new FnCache(/* @__PURE__ */ new Map(), get); } /// Pre-insert a selection of [`Source`]s into this cache. with_sources(sources2) { for (let [id, src2] of sources2) { this.sources.set(id, src2); } return this; } fetch(id) { const entry = this.sources.get(id); if (entry !== void 0) return ok(entry); const source = Source.from(this.get(id)); this.sources.set(id, source); return ok(source); } display(id) { return some(id); } static is(other) { return other instanceof FnCache; } } class SourceGroup { constructor(src_id, span, labels) { this.src_id = src_id; this.span = span; this.labels = labels; } } class Report { constructor(kind, code, msg, note, help, location, labels, config) { this.kind = kind; this.code = code; this.msg = msg; this.note = note; this.help = help; this.location = location; this.labels = labels; this.config = config; } /// Begin building a new [`Report`]. static build(kind, src_id, offset) { const builder = new ReportBuilder( kind, none(), none(), none(), none(), [Option.from(src_id), offset], [], Config.default() ); return builder; } /// Write this diagnostic out to `stderr`. eprint(init) { const cache = Cache.from(init); this.write(cache, stderrWriter); } /// Write this diagnostic out to `stdout`. /// /// In most cases, [`Report::eprint`] is the /// ['more correct'](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) function to use. print(init) { const cache = Cache.from(init); this.write(cache, stdoutWriter); } printTo(init, writer) { const cache = Cache.from(init); this.write(cache, writer); } get_source_groups(cache) { let groups = []; for (let label of this.labels) { let src_display = cache.display(label.span.source()); let res = cache.fetch(label.span.source()); if (res.is_err()) { console.error("Unable to fetch source '{}': {}", src_display, res.unwrap()); continue; } let src2 = res.unwrap(); assert(label.span.start <= label.span.end, "Label start is after its end"); let start_line = src2.get_offset_line(label.span.start).map(([_, l, __]) => l); let end_line = src2.get_offset_line(label.span.end.saturating_sub(1).max(label.span.start)).map(([_, l, __]) => l); let label_info = new LabelInfo( start_line.equal(end_line) ? LabelKind.Inline : LabelKind.Multiline, label ); const group = groups.find((g2) => g2.src_id === label.span.source()); if (group) { group.span.start = group.span.start.min(label.span.start); group.span.end = group.span.end.max(label.span.end); group.labels.push(label_info); } else { groups.push( new SourceGroup(label.span.source(), new Range(label.span.start, label.span.end), [ label_info ]) ); } } return groups; } /// Write this diagnostic to an implementor of [`Write`]. /// /// If you wish to write to `stderr` or `stdout`, you can do so via [`Report::eprint`] or [`Report::print`] respectively. write(cache, w) { let draw = match(this.config.char_set, [ [CharSet.Unicode, () => Characters.unicode()], [CharSet.Ascii, () => Characters.ascii()] ]); let code = this.code ? format("[E{}] ", this.code) : ""; let id = format("{}{}:", code, this.kind.name); let kind_color = match(this.kind, [ [ReportKind.Error, () => this.config.error_color()], [ReportKind.Warning, () => this.config.warning_color()], [ReportKind.Advice, () => this.config.advice_color()], [ReportKind.Custom, (kind) => kind.color] ]); writeln(w, "{} {}", new Display(id).fg(kind_color), new Show(this.msg)); let groups = this.get_source_groups(cache); let filtered_groups = groups.filter_map(({ span, src_id }) => { let src_name = cache.display(src_id).map((d) => d.toString()).unwrap_or_else(() => ""); let res = cache.fetch(src_id); if (res.is_err()) { eprintln("Unable to fetch source {}: {}", src_name, res.unwrap()); return null; } let src2 = res.unwrap(); let line_range = src2.get_line_range(span); let iter = rangeIter(1, Infinity); iter = map(iter, (x) => Math.pow(10, x)); iter = take_while(iter, (x) => { const d = Math.floor(line_range.end / x); return d !== 0; }); const cnt = count(iter); return cnt + 1; }); let line_no_width = max(filtered_groups) ?? 0; let groups_len = groups.length; for (let [group_idx, { src_id, span, labels }] of enumerate(groups)) { let src_name = cache.display(src_id).map((d) => d.toString()).unwrap_or_else(() => ""); let res = cache.fetch(src_id); if (res.is_err()) { eprintln("Unable to fetch source {}: {}", src_name, res.unwrap()); continue; } let src2 = res.unwrap(); let line_range = src2.get_line_range(span); let location = src_id === this.location[0] ? this.location[1] : labels[0].label.span.start; let [line_no, col_no] = src2.get_offset_line(location).map(([_, idx, col]) => [format("{}", idx + 1), format("{}", col + 1)]).unwrap_or_else(() => ["?", "?"]); let line_ref = format(":{}:{}", line_no, col_no); writeln( w, "{}{}{}{}{}{}{}", new Show([" ", line_no_width + 2]), new Display(group_idx === 0 ? draw.ltop : draw.lcross).fg(this.config.margin_color()), new Display(draw.hbar).fg(this.config.margin_color()), new Display(draw.lbox).fg(this.config.margin_color()), src_name, line_ref, new Display(draw.rbox).fg(this.config.margin_color()) ); if (!this.config.compact) { writeln( w, "{}{}", new Show([" ", line_no_width + 2]), new Display(draw.vbar).fg(this.config.margin_color()) ); } class LineLabel { constructor(col, label, multi, draw_msg) { this.col = col; this.label = label; this.multi = multi; this.draw_msg = draw_msg; this.col = Math.floor(col); } } let multi_labels = []; for (let label_info of labels) { if (label_info.kind === LabelKind.Multiline) { multi_labels.push(label_info.label); } } multi_labels.sort((a, b) => b.span.len() - a.span.len()); let write_margin = (w2, idx, is_line, is_ellipsis2, draw_labels, report_row, line_labels, margin_label) => { let line_no_margin; if (is_line && !is_ellipsis2) { let line_no2 = format("{}", idx + 1); line_no_margin = format( "{}{} {}", new Show([" ", line_no_width - line_no2.length]), line_no2, draw.vbar ); } else { line_no_margin = format( "{}{}", new Show([" ", line_no_width + 1]), is_ellipsis2 ? draw.vbar_gap : draw.vbar_break ); } write( w2, " {}{}", new Display(line_no_margin).fg(this.config.margin_color()), new Show(some(" ").filter(() => !this.config.compact)) ); if (draw_labels) { for (let col of range(0, multi_labels.length + bton(multi_labels.length > 0))) { let corner = none(); let hbar = none(); let vbar = none(); let margin_ptr = none(); let multi_label = Option.from(multi_labels[col]); let line_span = src2.line(idx).unwrap().span(); for (let [i, label] of enumerate( multi_labels.slice(0, (col + 1).min(multi_labels.length)) )) { let margin = margin_label.filter((m) => label === m.label); if (label.span.start <= line_span.end && label.span.end > line_span.start) { let is_parent = i !== col; let is_start = line_span.contains(label.span.start); let is_end = line_span.contains(label.last_offset()); if (margin.filter(() => is_line).is_some()) { let _margin = margin.filter(() => is_line); margin_ptr = some([_margin.unwrap(), is_start]); } else if (!is_start && (!is_end || is_line)) { vbar = vbar.or(some(label).filter(() => !is_parent)); } else { if (report_row.is_some() && report_row.map_or(false, (o) => isNumber(o[0]) && isBoolean(o[1]))) { let [_report_row, is_arrow] = report_row.unwrap(); let label_row = Option.from( line_labels.enumerate().find(([_, l]) => label === l.label) ).map_or(0, ([r, _]) => r); if (_report_row === label_row) { if (margin.is_some()) { vbar = some(margin.unwrap().label).filter(() => col === i); if (is_start) { continue; } } if (is_arrow) { hbar = some(label); if (!is_parent) { corner = some([label, is_start]); } } else if (!is_start) { vbar = vbar.or(some(label).filter(() => !is_parent)); } } else { vbar = vbar.or( some(label).filter( () => !is_parent && !!(bton(is_start) ^ bton(_report_row < label_row)) ) ); } } } } } if (margin_ptr.is_some() && margin_ptr.map_or(false, (o) => Label.is(o[0]) && isBoolean(o[1])) && is_line) { let [margin, _is_start] = margin_ptr.unwrap(); if (_is_start) { let is_col = multi_label.map_or(false, (ml) => ml === margin.label); let is_limit = col + 1 === multi_labels.length; if (!is_col && !is_limit) { hbar = hbar.or(some(margin.label)); } } } hbar = hbar.filter( (l) => margin_label.map_or(true, (margin) => margin.label !== l) || !is_line ); const getCorners = () => { if (corner.is_some() && Array.isArray(corner.unwrap()) && Label.is(corner.unwrap()[0]) && isBoolean(corner.unwrap()[1])) { let [label, is_start] = corner.unwrap(); return [ new Display(is_start ? draw.ltop : draw.lbot).fg(label.color), new Display(draw.hbar).fg(label.color) ]; } else if (hbar.filter(() => vbar.is_some() && !this.config.cross_gap).is_some()) { let label = hbar.filter(() => vbar.is_some() && !this.config.cross_gap).unwrap(); return [ new Display(draw.xbar).fg(label.color), new Display(draw.hbar).fg(label.color) ]; } else if (hbar.is_some()) { let label = hbar.unwrap(); const d = new Display(draw.hbar).fg(label.color); return [d, d]; } else if (vbar.is_some()) { let label = vbar.unwrap(); let vb = new Display(is_ellipsis2 ? draw.vbar_gap : draw.vbar); return [vb.fg(label.color), new Display(" ").fg(none())]; } else if (margin_ptr.is_some() && is_line) { let [margin, is_start] = margin_ptr.unwrap(); let is_col = multi_label.map_or(false, (ml) => ml === margin.label); let is_limit = col === multi_labels.length; return [ new Display( is_limit ? draw.rarrow : is_col ? is_start ? draw.ltop : draw.lcross : draw.hbar ).fg(margin.label.color), new Display(!is_limit ? draw.hbar : " ").fg(margin.label.color) ]; } else { const d = new Display(" ").fg(none()); return [d, d]; } }; let [a, b] = getCorners(); write(w2, "{}", a); if (!this.config.compact) { write(w2, "{}", b); } } } }; let is_ellipsis = false; for (let idx of range(line_range.start, line_range.end)) { if (src2.line(idx).is_none()) { continue; } let line = src2.line(idx).unwrap(); const f_labels = multi_labels.enumerate().filter_map(([_i, label]) => { let is_start = line.span().contains(label.span.start); let is_end = line.span().contains(label.last_offset()); if (is_start) { return new LineLabel(label.span.start - line.offset(), label, true, false); } else if (is_end) { return new LineLabel(label.last_offset() - line.offset(), label, true, true); } else { return null; } }); let margin_label = min_by_key(f_labels, (ll) => ll.col); let line_labels = multi_labels.enumerate().filter_map(([_i, label]) => { let is_start = line.span().contains(label.span.start); let is_end = line.span().contains(label.last_offset()); if (is_start && margin_label.map_or(true, (m) => label !== m.label)) { return new LineLabel( label.span.start - line.offset(), label, true, false // Multi-line spans don;t have their messages drawn at the start ); } else if (is_end) { return new LineLabel( label.last_offset() - line.offset(), label, true, true // Multi-line spans have their messages drawn at the end ); } else { return null; } }); for (let label_info of labels.filter( (l) => l.label.span.start >= line.span().start && l.label.span.end <= line.span().end )) { if (label_info.kind === LabelKind.Inline) { let col = match(this.config.label_attach, [ [LabelAttach.Start, () => label_info.label.span.start], [ LabelAttach.Middle, () => (label_info.label.span.start + label_info.label.span.end) / 2 ], [LabelAttach.End, () => label_info.label.last_offset()] ]); line_labels.push( new LineLabel( col.max(label_info.label.span.start) - line.offset(), label_info.label, false, true ) ); } } if (line_labels.length === 0 && margin_label.is_none()) { let within_label = multi_labels.some((label) => label.span.contains(line.span().start)); if (!is_ellipsis && within_label) { is_ellipsis = true; } else { if (!this.config.compact && !is_ellipsis) { write_margin(w, idx, false, is_ellipsis, false, none(), [], none()); write(w, "\n"); } is_ellipsis = true; continue; } } else { is_ellipsis = false; } sort_by_key(line_labels, (ll) => ll.label.order); sort_by_key(line_labels, (ll) => ll.col); sort_by_key(line_labels, (ll) => bton(!ll.label.span.start)); let arrow_end_space = this.config.compact ? 1 : 2; let arrow_len = line_labels.reduce((l, ll) => { return ll.multi ? line.len() : l.max(ll.label.span.end.saturating_sub(line.offset())); }, 0) + arrow_end_space; let get_vbar = (col, row) => Option.from( line_labels.enumerate().filter( ([_, ll]) => ll.label.msg.is_some() && margin_label.map_or(true, (m) => ll.label !== m.label) ).find( ([j, ll]) => ll.col === col && (row <= j && !ll.multi || row <= j && ll.multi) ) ).map(([_, ll]) => ll); let get_highlight = (col) => min_by_key( margin_label.iter().map((ll) => ll.label).chain(multi_labels.map((l) => l)).chain(line_labels.map((l) => l.label)).filter((l) => l.span.contains(line.offset() + col)), // Prioritise displaying smaller spans // .min_by_key((l: any) => [-l.priority, l.span.len()]); // .min_by_key(l => l.span.len())); (l) => -l.priority + l.span.len() ); let get_underline = (col) => min_by_key( line_labels.filter((ll) => { return this.config.underlines && // Underlines only occur for inline spans (highlighting can occur for all spans) !ll.multi && ll.label.span.contains(line.offset() + col); }), // Prioritise displaying smaller spans // .min_by_key(ll => [-ll.label.priority, ll.label.span.len()]); // .min_by_key(ll => ll.label.span.len())); // ll => -ll.label.priority + ll.label.span.len()); (ll) => ll.label.span.len() ); write_margin(w, idx, true, is_ellipsis, true, none(), line_labels, margin_label); if (!is_ellipsis) { for (let [col, _c] of enumerate(line.chars())) { let highlight = get_highlight(col); let color = highlight.is_some() ? highlight.unwrap().color : this.config.unimportant_color(); let [c2, width] = this.config.char_width(_c, col); for (let _ of range(0, width)) { write(w, "{}", new Display(c2).fg(color)); } } } write(w, "\n"); for (let row of range(0, line_labels.length)) { let line_label = line_labels[row]; if (!this.config.compact) { write_margin( w, idx, false, is_ellipsis, true, some([row, false]), line_labels, margin_label ); let chars2 = line.chars(); let { next: next2 } = makeIter(chars2); for (let col of range(0, arrow_len)) { let width = next2().map_or(1, (c22) => this.config.char_width(c22, col)[1]); let vbar = get_vbar(col, row); let underline = get_underline(col).filter(() => row === 0); const getCTailOuter = () => { if (vbar.is_some()) { let vbar_ll = vbar.unwrap(); const getCTailInner = () => { if (underline.is_some()) { if (vbar_ll.label.span.len() <= 1) { return [draw.underbar, draw.underline]; } else if (line.offset() + col === vbar_ll.label.span.start) { return [draw.ltop, draw.underbar]; } else if (line.offset() + col === vbar_ll.label.last_offset()) { return [draw.rtop, draw.underbar]; } else { return [draw.underbar, draw.underline]; } } else if (vbar_ll.multi && row === 0 && this.config.multiline_arrows) { return [draw.uarrow, new Display(" ")]; } else { return [draw.vbar, new Display(" ")]; } }; let [c22, tail2] = getCTailInner(); return [ new Display(c22).fg(vbar_ll.label.color), new Display(tail2).fg(vbar_ll.label.color) ]; } else if (underline.is_some()) { let underline_ll = underline.unwrap(); return [ new Display(draw.underline).fg(underline_ll.label.color), new Display(draw.underline).fg(underline_ll.label.color) ]; } else { return [new Display(" ").fg(none()), new Display(" ").fg(none())]; } }; let [c2, tail] = getCTailOuter(); for (let i of range(0, width)) { write(w, "{}", i === 0 ? c2 : tail); } } write(w, "\n"); } write_margin( w, idx, false, is_ellipsis, true, some([row, true]), line_labels, margin_label ); let chars = line.chars(); let { next } = makeIter(chars); for (let col of range(0, arrow_len)) { let n = next(); let width = n.map_or(1, (c22) => this.config.char_width(c22, col)[1]); let is_hbar = ((col > line_label.col ? 1 : 0) ^ (line_label.multi ? 1 : 0) || line_label.label.msg.is_some() && line_label.draw_msg && col > line_label.col) && line_label.label.msg.is_some(); const getctail = () => { if (col === line_label.col && line_label.label.msg.is_some() && margin_label.map_or(true, (m) => line_label.label != m.label)) { return [ new Display( line_label.multi ? line_label.draw_msg ? draw.mbot : draw.rbot : draw.lbot ).fg(line_label.label.color), new Display(draw.hbar).fg(line_label.label.color) ]; } else if (get_vbar(col, row).filter(() => col != line_label.col || line_label.label.msg.is_some()).is_some()) { let vbar_ll = get_vbar(col, row).filter(() => col != line_label.col || line_label.label.msg.is_some()).unwrap(); if (!this.config.cross_gap && is_hbar) { return [ new Display(draw.xbar).fg(line_label.label.color), new Display(" ").fg(line_label.label.color) ]; } else if (is_hbar) { let d = new Display(draw.hbar).fg(line_label.label.color); return [d, d]; } else { return [ new Display( vbar_ll.multi && row === 0 && this.config.compact ? draw.uarrow : draw.vbar ).fg(vbar_ll.label.color), new Display(" ").fg(line_label.label.color) ]; } } else if (is_hbar) { let d = new Display(draw.hbar).fg(line_label.label.color); return [d, d]; } else { let d = new Display(" ").fg(none()); return [d, d]; } }; let [c2, tail] = getctail(); if (width > 0) { write(w, "{}", c2); } for (let _ of range(1, width)) { write(w, "{}", tail); } } if (line_label.draw_msg) { write(w, " {}", new Show(line_label.label.msg)); } write(w, "\n"); } } let is_final_group = group_idx + 1 === groups_len; if (this.help.is_some() && is_final_group) { let note = this.help.unwrap(); if (!this.config.compact) { write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, "\n"); } write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, "{}: {}\n", new Display("Help").fg(this.config.note_color()), note); } if (this.note.is_some() && is_final_group) { let note = this.note.unwrap(); if (!this.config.compact) { write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, "\n"); } write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, "{}: {}\n", new Display("Note").fg(this.config.note_color()), note); } if (!this.config.compact) { if (is_final_group) { let final_margin = format("{}{}", new Show([draw.hbar, line_no_width + 2]), draw.rbot); writeln(w, "{}", new Display(final_margin).fg(this.config.margin_color())); } else { writeln( w, "{}{}", new Show([" ", line_no_width + 2]), new Display(draw.vbar).fg(this.config.margin_color()) ); } } } if (groups_len === 0) { if (this.help.is_some()) { let note = this.help.unwrap(); if (!this.config.compact) { write(w, "\n"); } write(w, "{}: {}\n", new Display("Help").fg(this.config.note_color()), note); } if (this.note.is_some()) { let note = this.note.unwrap(); if (!this.config.compact) { write(w, "\n"); } write(w, "{}: {}\n", new Display("Note").fg(this.config.note_color()), note); } } } } function match(kind, matchers) { for (let [type2, then] of matchers) { if (kind === type2) return then(kind); } return null; } function* enumerate(groups) { for (let i = 0; i < groups.length; i++) yield [i, groups[i]]; return; } function* map(a, f) { let value = a.next(); while (value.done === false) { yield f(value.value); value = a.next(); } } function* take_while(a, p) { let current = a.next(); while (current.done === false) { if (p(current.value)) yield current.value; else break; current = a.next(); } } function to_array(a) { let result = []; let current = a.next(); while (current.done === false) { result.push(current.value); current = a.next(); } return result; } function count(a) { return to_array(a).length; } function makeIter(arr) { let cursor = 0; let next = () => { const res = arr[cursor++]; if (res === void 0) return none(); return some(res); }; return { next, cursor }; } var ansi_up = {}; (function(exports3) { (function(root, factory2) { if (typeof exports3.nodeName !== "string") { factory2(exports3); } else { var exp = {}; factory2(exp); root.AnsiUp = exp.default; } })(commonjsGlobal, function(exports4) { var __makeTemplateObject2 = this && this.__makeTemplateObject || function(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var PacketKind; (function(PacketKind2) { PacketKind2[PacketKind2["EOS"] = 0] = "EOS"; PacketKind2[PacketKind2["Text"] = 1] = "Text"; PacketKind2[PacketKind2["Incomplete"] = 2] = "Incomplete"; PacketKind2[PacketKind2["ESC"] = 3] = "ESC"; PacketKind2[PacketKind2["Unknown"] = 4] = "Unknown"; PacketKind2[PacketKind2["SGR"] = 5] = "SGR"; PacketKind2[PacketKind2["OSCURL"] = 6] = "OSCURL"; })(PacketKind || (PacketKind = {})); var AnsiUp2 = function() { function AnsiUp3() { this.VERSION = "5.1.0"; this.setup_palettes(); this._use_classes = false; this.bold = false; this.italic = false; this.underline = false; this.fg = this.bg = null; this._buffer = ""; this._url_whitelist = { "http": 1, "https": 1 }; } Object.defineProperty(AnsiUp3.prototype, "use_classes", { get: function() { return this._use_classes; }, set: function(arg) { this._use_classes = arg; }, enumerable: false, configurable: true }); Object.defineProperty(AnsiUp3.prototype, "url_whitelist", { get: function() { return this._url_whitelist; }, set: function(arg) { this._url_whitelist = arg; }, enumerable: false, configurable: true }); AnsiUp3.prototype.setup_palettes = function() { var _this = this; this.ansi_colors = [ [ { rgb: [0, 0, 0], class_name: "ansi-black" }, { rgb: [187, 0, 0], class_name: "ansi-red" }, { rgb: [0, 187, 0], class_name: "ansi-green" }, { rgb: [187, 187, 0], class_name: "ansi-yellow" }, { rgb: [0, 0, 187], class_name: "ansi-blue" }, { rgb: [187, 0, 187], class_name: "ansi-magenta" }, { rgb: [0, 187, 187], class_name: "ansi-cyan" }, { rgb: [255, 255, 255], class_name: "ansi-white" } ], [ { rgb: [85, 85, 85], class_name: "ansi-bright-black" }, { rgb: [255, 85, 85], class_name: "ansi-bright-red" }, { rgb: [0, 255, 0], class_name: "ansi-bright-green" }, { rgb: [255, 255, 85], class_name: "ansi-bright-yellow" }, { rgb: [85, 85, 255], class_name: "ansi-bright-blue" }, { rgb: [255, 85, 255], class_name: "ansi-bright-magenta" }, { rgb: [85, 255, 255], class_name: "ansi-bright-cyan" }, { rgb: [255, 255, 255], class_name: "ansi-bright-white" } ] ]; this.palette_256 = []; this.ansi_colors.forEach(function(palette) { palette.forEach(function(rec) { _this.palette_256.push(rec); }); }); var levels = [0, 95, 135, 175, 215, 255]; for (var r = 0; r < 6; ++r) { for (var g2 = 0; g2 < 6; ++g2) { for (var b = 0; b < 6; ++b) { var col = { rgb: [levels[r], levels[g2], levels[b]], class_name: "truecolor" }; this.palette_256.push(col); } } } var grey_level = 8; for (var i = 0; i < 24; ++i, grey_level += 10) { var gry = { rgb: [grey_level, grey_level, grey_level], class_name: "truecolor" }; this.palette_256.push(gry); } }; AnsiUp3.prototype.escape_txt_for_html = function(txt) { return txt.replace(/[&<>"']/gm, function(str) { if (str === "&") return "&"; if (str === "<") return "<"; if (str === ">") return ">"; if (str === '"') return """; if (str === "'") return "'"; }); }; AnsiUp3.prototype.append_buffer = function(txt) { var str = this._buffer + txt; this._buffer = str; }; AnsiUp3.prototype.get_next_packet = function() { var pkt = { kind: PacketKind.EOS, text: "", url: "" }; var len = this._buffer.length; if (len == 0) return pkt; var pos = this._buffer.indexOf("\x1B"); if (pos == -1) { pkt.kind = PacketKind.Text; pkt.text = this._buffer; this._buffer = ""; return pkt; } if (pos > 0) { pkt.kind = PacketKind.Text; pkt.text = this._buffer.slice(0, pos); this._buffer = this._buffer.slice(pos); return pkt; } if (pos == 0) { if (len == 1) { pkt.kind = PacketKind.Incomplete; return pkt; } var next_char = this._buffer.charAt(1); if (next_char != "[" && next_char != "]") { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } if (next_char == "[") { if (!this._csi_regex) { this._csi_regex = rgx(__makeTemplateObject2(["\n ^ # beginning of line\n #\n # First attempt\n (?: # legal sequence\n \x1B[ # CSI\n ([<-?]?) # private-mode char\n ([d;]*) # any digits or semicolons\n ([ -/]? # an intermediate modifier\n [@-~]) # the command\n )\n | # alternate (second attempt)\n (?: # illegal sequence\n \x1B[ # CSI\n [ -~]* # anything legal\n ([\0-:]) # anything illegal\n )\n "], ["\n ^ # beginning of line\n #\n # First attempt\n (?: # legal sequence\n \\x1b\\[ # CSI\n ([\\x3c-\\x3f]?) # private-mode char\n ([\\d;]*) # any digits or semicolons\n ([\\x20-\\x2f]? # an intermediate modifier\n [\\x40-\\x7e]) # the command\n )\n | # alternate (second attempt)\n (?: # illegal sequence\n \\x1b\\[ # CSI\n [\\x20-\\x7e]* # anything legal\n ([\\x00-\\x1f:]) # anything illegal\n )\n "])); } var match2 = this._buffer.match(this._csi_regex); if (match2 === null) { pkt.kind = PacketKind.Incomplete; return pkt; } if (match2[4]) { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } if (match2[1] != "" || match2[3] != "m") pkt.kind = PacketKind.Unknown; else pkt.kind = PacketKind.SGR; pkt.text = match2[2]; var rpos = match2[0].length; this._buffer = this._buffer.slice(rpos); return pkt; } if (next_char == "]") { if (len < 4) { pkt.kind = PacketKind.Incomplete; return pkt; } if (this._buffer.charAt(2) != "8" || this._buffer.charAt(3) != ";") { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } if (!this._osc_st) { this._osc_st = rgxG(__makeTemplateObject2(["\n (?: # legal sequence\n (\x1B\\) # ESC | # alternate\n (\x07) # BEL (what xterm did)\n )\n | # alternate (second attempt)\n ( # illegal sequence\n [\0-] # anything illegal\n | # alternate\n [\b-] # anything illegal\n | # alternate\n [-] # anything illegal\n )\n "], ["\n (?: # legal sequence\n (\\x1b\\\\) # ESC \\\n | # alternate\n (\\x07) # BEL (what xterm did)\n )\n | # alternate (second attempt)\n ( # illegal sequence\n [\\x00-\\x06] # anything illegal\n | # alternate\n [\\x08-\\x1a] # anything illegal\n | # alternate\n [\\x1c-\\x1f] # anything illegal\n )\n "])); } this._osc_st.lastIndex = 0; { var match_1 = this._osc_st.exec(this._buffer); if (match_1 === null) { pkt.kind = PacketKind.Incomplete; return pkt; } if (match_1[3]) { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } } { var match_2 = this._osc_st.exec(this._buffer); if (match_2 === null) { pkt.kind = PacketKind.Incomplete; return pkt; } if (match_2[3]) { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } } if (!this._osc_regex) { this._osc_regex = rgx(__makeTemplateObject2(["\n ^ # beginning of line\n #\n \x1B]8; # OSC Hyperlink\n [ -:<-~]* # params (excluding ;)\n ; # end of params\n ([!-~]{0,512}) # URL capture\n (?: # ST\n (?:\x1B\\) # ESC | # alternate\n (?:\x07) # BEL (what xterm did)\n )\n ([ -~]+) # TEXT capture\n \x1B]8;; # OSC Hyperlink End\n (?: # ST\n (?:\x1B\\) # ESC | # alternate\n (?:\x07) # BEL (what xterm did)\n )\n "], ["\n ^ # beginning of line\n #\n \\x1b\\]8; # OSC Hyperlink\n [\\x20-\\x3a\\x3c-\\x7e]* # params (excluding ;)\n ; # end of params\n ([\\x21-\\x7e]{0,512}) # URL capture\n (?: # ST\n (?:\\x1b\\\\) # ESC \\\n | # alternate\n (?:\\x07) # BEL (what xterm did)\n )\n ([\\x20-\\x7e]+) # TEXT capture\n \\x1b\\]8;; # OSC Hyperlink End\n (?: # ST\n (?:\\x1b\\\\) # ESC \\\n | # alternate\n (?:\\x07) # BEL (what xterm did)\n )\n "])); } var match2 = this._buffer.match(this._osc_regex); if (match2 === null) { pkt.kind = PacketKind.ESC; pkt.text = this._buffer.slice(0, 1); this._buffer = this._buffer.slice(1); return pkt; } pkt.kind = PacketKind.OSCURL; pkt.url = match2[1]; pkt.text = match2[2]; var rpos = match2[0].length; this._buffer = this._buffer.slice(rpos); return pkt; } } }; AnsiUp3.prototype.ansi_to_html = function(txt) { this.append_buffer(txt); var blocks = []; while (true) { var packet = this.get_next_packet(); if (packet.kind == PacketKind.EOS || packet.kind == PacketKind.Incomplete) break; if (packet.kind == PacketKind.ESC || packet.kind == PacketKind.Unknown) continue; if (packet.kind == PacketKind.Text) blocks.push(this.transform_to_html(this.with_state(packet))); else if (packet.kind == PacketKind.SGR) this.process_ansi(packet); else if (packet.kind == PacketKind.OSCURL) blocks.push(this.process_hyperlink(packet)); } return blocks.join(""); }; AnsiUp3.prototype.with_state = function(pkt) { return { bold: this.bold, italic: this.italic, underline: this.underline, fg: this.fg, bg: this.bg, text: pkt.text }; }; AnsiUp3.prototype.process_ansi = function(pkt) { var sgr_cmds = pkt.text.split(";"); while (sgr_cmds.length > 0) { var sgr_cmd_str = sgr_cmds.shift(); var num = parseInt(sgr_cmd_str, 10); if (isNaN(num) || num === 0) { this.fg = this.bg = null; this.bold = false; this.italic = false; this.underline = false; } else if (num === 1) { this.bold = true; } else if (num === 3) { this.italic = true; } else if (num === 4) { this.underline = true; } else if (num === 22) { this.bold = false; } else if (num === 23) { this.italic = false; } else if (num === 24) { this.underline = false; } else if (num === 39) { this.fg = null; } else if (num === 49) { this.bg = null; } else if (num >= 30 && num < 38) { this.fg = this.ansi_colors[0][num - 30]; } else if (num >= 40 && num < 48) { this.bg = this.ansi_colors[0][num - 40]; } else if (num >= 90 && num < 98) { this.fg = this.ansi_colors[1][num - 90]; } else if (num >= 100 && num < 108) { this.bg = this.ansi_colors[1][num - 100]; } else if (num === 38 || num === 48) { if (sgr_cmds.length > 0) { var is_foreground = num === 38; var mode_cmd = sgr_cmds.shift(); if (mode_cmd === "5" && sgr_cmds.length > 0) { var palette_index = parseInt(sgr_cmds.shift(), 10); if (palette_index >= 0 && palette_index <= 255) { if (is_foreground) this.fg = this.palette_256[palette_index]; else this.bg = this.palette_256[palette_index]; } } if (mode_cmd === "2" && sgr_cmds.length > 2) { var r = parseInt(sgr_cmds.shift(), 10); var g2 = parseInt(sgr_cmds.shift(), 10); var b = parseInt(sgr_cmds.shift(), 10); if (r >= 0 && r <= 255 && (g2 >= 0 && g2 <= 255) && (b >= 0 && b <= 255)) { var c2 = { rgb: [r, g2, b], class_name: "truecolor" }; if (is_foreground) this.fg = c2; else this.bg = c2; } } } } } }; AnsiUp3.prototype.transform_to_html = function(fragment) { var txt = fragment.text; if (txt.length === 0) return txt; txt = this.escape_txt_for_html(txt); if (!fragment.bold && !fragment.italic && !fragment.underline && fragment.fg === null && fragment.bg === null) return txt; var styles2 = []; var classes = []; var fg = fragment.fg; var bg = fragment.bg; if (fragment.bold) styles2.push("font-weight:bold"); if (fragment.italic) styles2.push("font-style:italic"); if (fragment.underline) styles2.push("text-decoration:underline"); if (!this._use_classes) { if (fg) styles2.push("color:rgb(" + fg.rgb.join(",") + ")"); if (bg) styles2.push("background-color:rgb(" + bg.rgb + ")"); } else { if (fg) { if (fg.class_name !== "truecolor") { classes.push(fg.class_name + "-fg"); } else { styles2.push("color:rgb(" + fg.rgb.join(",") + ")"); } } if (bg) { if (bg.class_name !== "truecolor") { classes.push(bg.class_name + "-bg"); } else { styles2.push("background-color:rgb(" + bg.rgb.join(",") + ")"); } } } var class_string = ""; var style_string = ""; if (classes.length) class_string = ' class="' + classes.join(" ") + '"'; if (styles2.length) style_string = ' style="' + styles2.join(";") + '"'; return "" + txt + ""; }; AnsiUp3.prototype.process_hyperlink = function(pkt) { var parts = pkt.url.split(":"); if (parts.length < 1) return ""; if (!this._url_whitelist[parts[0]]) return ""; var result = '' + this.escape_txt_for_html(pkt.text) + ""; return result; }; return AnsiUp3; }(); function rgx(tmplObj) { var regexText = tmplObj.raw[0]; var wsrgx = /^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm; var txt2 = regexText.replace(wsrgx, ""); return new RegExp(txt2); } function rgxG(tmplObj) { var regexText = tmplObj.raw[0]; var wsrgx = /^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm; var txt2 = regexText.replace(wsrgx, ""); return new RegExp(txt2, "g"); } Object.defineProperty(exports4, "__esModule", { value: true }); exports4.default = AnsiUp2; }); })(ansi_up); const AnsiUp = /* @__PURE__ */ getDefaultExportFromCjs(ansi_up); function nicerError(e) { if (e.code == 1070) { return "Static/public methods are not supported on traits"; } return e.messageText.toString(); } class TagNode { constructor(name, tsNode) { this.tsNode = tsNode; this.name = name; this.tags = []; this.edges = []; this.edgesOther = []; } } class TagGraph { constructor() { this.nodes = []; } addNode(name, tsNode) { let node2 = this.nodes.find((node22) => node22.name === name); if (!node2) { node2 = new TagNode(name, tsNode); this.nodes.push(node2); } } addEdge(from, to) { let fromNode = this.nodes.find((node2) => node2.name === from); if (!fromNode) { fromNode = new TagNode(from); this.nodes.push(fromNode); } let toNode = this.nodes.find((node2) => node2.name === to); if (!toNode) { toNode = new TagNode(to); this.nodes.push(toNode); } fromNode.edges.push(toNode); toNode.edgesOther.push(fromNode); } addTag(name, tag) { let node2 = this.nodes.find((node22) => node22.name === name); if (!node2) { node2 = new TagNode(name); this.nodes.push(node2); } node2.tags.push(tag); } getNode(name) { return this.nodes.find((node2) => node2.name === name); } resolveTagSourceChain(name, tag) { const node2 = this.getNode(name); if (!node2) return []; const chain = [name]; const visited = /* @__PURE__ */ new Set(); const queue = [node2]; while (queue.length > 0) { const node22 = queue.shift(); if (visited.has(node22.name)) continue; visited.add(node22.name); let nodeWithTag = null; for (const edge of node22.edgesOther) { if (edge.tags.includes(tag)) { nodeWithTag = edge; break; } } if (nodeWithTag) { chain.push(nodeWithTag.name); queue.push(nodeWithTag); } else { return chain; } } return []; } propagateTags() { let changed = true; while (changed) { changed = false; for (const node2 of this.nodes) { for (const edge of node2.edges) { for (const tag of node2.tags) { if (!edge.tags.includes(tag)) { edge.tags.push(tag); changed = true; } } } } } } } const quickCache = { "/file.ts": { outputFiles: [ { name: "/file.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/std___std_all"], function (require, exports, std___std_all_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n var globalVarGet = std___std_all_1.globalVarGet;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/std_math.ts": { outputFiles: [ { name: "/std_math.js", writeByteOrderMark: false, text: `var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; define(["require", "exports", "./static-math"], function (require, exports, static_math_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unpack2x16float = exports.unpack2x16unorm = exports.unpack2x16snorm = exports.unpack4x8unorm = exports.unpack4x8snorm = exports.pack2x16float = exports.pack2x16unorm = exports.pack2x16snorm = exports.pack4x8unorm = exports.pack4x8snorm = exports.bitcast = exports.ddyCoarse = exports.ddxCoarse = exports.ddyFine = exports.ddxFine = exports.ddy = exports.ddx = exports.discard = exports.workgroupUniformLoad = exports.storageBarrier = exports.workgroupBarrier = exports.atomic = exports.atomic_internal = exports.FM = exports.intifyVector = exports.swizzle = exports.testDocComment = exports.makeVector = exports.not = exports.or = exports.and = exports.gte = exports.gt = exports.lte = exports.lt = exports.neq = exports.eq = exports.saturate = exports.clamp = exports.max = exports.min = exports.smoothstep = exports.step = exports.radians = exports.degrees = exports.refract = exports.reflect = exports.normalize = exports.distance = exports.dist = exports.length = exports.bilerp = exports.lerp = exports.dot = exports.cross = exports.pingpong = exports.rand3 = exports.rand2 = exports.rand = exports.wrap = exports.frac = exports.inversesqrt = exports.sqrt = exports.log10 = exports.log2 = exports.log = exports.exp = exports.atanh = exports.asinh = exports.acosh = exports.tanh = exports.sinh = exports.cosh = exports.atan2 = exports.atan = exports.asin = exports.acos = exports.tan = exports.sin = exports.cos = exports.sign = exports.round = exports.ceil = exports.floor = exports.abs = exports.positive = exports.negate = exports.bitnot = exports.rshift = exports.lshift = exports.bitxor = exports.bitor = exports.bitand = exports.mod = exports.pow = exports.div = exports.mul = exports.transpose = exports.inverse = exports.sub = exports.add = exports.uint8 = exports.uint4 = exports.uint3 = exports.uint2 = exports.int4 = exports.int3 = exports.int2 = exports.float4 = exports.float3 = exports.float2 = exports.uint = exports.int = exports.float = exports.float4x4 = exports.float3x3 = exports.float2x2 = void 0; function isVector(v) { return Array.isArray(v); } function isScalar(v) { return typeof v === 'number'; } function isMatrix(v) { return !!v.__matrix; } /** @shadeup=glsl(mat2) @shadeup=wgsl(mat2x2) */ function float2x2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var arr = [0, 0, 0, 0]; if (args.length === 4) { arr = __spreadArray([], args, true); } applyMatrix2x2Methods(arr); return arr; } exports.float2x2 = float2x2; /** @shadeup=glsl(mat3) @shadeup=wgsl(mat3x3) */ function float3x3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var arr = [0, 0, 0, 0, 0, 0, 0, 0, 0]; if (args.length === 9) { arr = __spreadArray([], args, true); } applyMatrix3x3Methods(arr); return arr; } exports.float3x3 = float3x3; function applyMatrix4x4Methods(arr) { arr.__matrix = 4; arr.__index = function (index) { var out_arr = [arr[index * 4], arr[index * 4 + 1], arr[index * 4 + 2], arr[index * 4 + 3]]; out_arr.__index = function (index_inner) { return out_arr[index_inner]; }; out_arr.__index_assign = function (index_inner, value) { arr[index * 4 + index_inner] = value; }; out_arr.__index_assign_op = function (op_fn, index_inner, value) { arr[index * 4 + index_inner] = op_fn(arr[index * 4 + index_inner], value); }; return out_arr; }; arr.__index_assign = function (index, value) { arr[index * 4] = value[0]; arr[index * 4 + 1] = value[1]; arr[index * 4 + 2] = value[2]; arr[index * 4 + 3] = value[3]; }; arr.__index_assign_op = function (op_fn, index, value) { arr[index * 4] = op_fn(arr[index * 4], value[0]); arr[index * 4 + 1] = op_fn(arr[index * 4 + 1], value[1]); arr[index * 4 + 2] = op_fn(arr[index * 4 + 2], value[2]); arr[index * 4 + 3] = op_fn(arr[index * 4 + 3], value[3]); }; } window.applyMatrix4x4Methods = applyMatrix4x4Methods; function applyMatrix3x3Methods(arr) { arr.__matrix = 3; arr.__index = function (index) { var out_arr = [arr[index * 3], arr[index * 3 + 1], arr[index * 3 + 2]]; out_arr.__index = function (index_inner) { return out_arr[index_inner]; }; out_arr.__index_assign = function (index_inner, value) { arr[index * 3 + index_inner] = value; }; out_arr.__index_assign_op = function (op_fn, index_inner, value) { arr[index * 3 + index_inner] = op_fn(arr[index * 3 + index_inner], value); }; return out_arr; }; arr.__index_assign = function (index, value) { arr[index * 3] = value[0]; arr[index * 3 + 1] = value[1]; arr[index * 3 + 2] = value[2]; }; arr.__index_assign_op = function (op_fn, index, value) { arr[index * 3] = op_fn(arr[index * 3], value[0]); arr[index * 3 + 1] = op_fn(arr[index * 3 + 1], value[1]); arr[index * 3 + 2] = op_fn(arr[index * 3 + 2], value[2]); }; } window.applyMatrix3x3Methods = applyMatrix3x3Methods; function applyMatrix2x2Methods(arr) { arr.__matrix = 2; arr.__index = function (index) { var out_arr = [arr[index * 2], arr[index * 2 + 1]]; out_arr.__index = function (index_inner) { return out_arr[index_inner]; }; out_arr.__index_assign = function (index_inner, value) { arr[index * 2 + index_inner] = value; }; out_arr.__index_assign_op = function (op_fn, index_inner, value) { arr[index * 2 + index_inner] = op_fn(arr[index * 2 + index_inner], value); }; return out_arr; }; arr.__index_assign = function (index, value) { arr[index * 2] = value[0]; arr[index * 2 + 1] = value[1]; }; arr.__index_assign_op = function (op_fn, index, value) { arr[index * 2] = op_fn(arr[index * 2], value[0]); arr[index * 2 + 1] = op_fn(arr[index * 2 + 1], value[1]); }; } window.applyMatrix2x2Methods = applyMatrix2x2Methods; /** @shadeup=glsl(mat4) @shadeup=wgsl(mat4x4) */ function float4x4() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; if (args.length === 16) { arr = __spreadArray([], args, true); } applyMatrix4x4Methods(arr); return arr; } exports.float4x4 = float4x4; /** @shadeup=glsl(float) @shadeup=wgsl(f32) */ function float(x) { return x; } exports.float = float; /** @shadeup=glsl(int) @shadeup=wgsl(i32) */ function int(x) { return (x | 0); } exports.int = int; /** @shadeup=glsl(uint) @shadeup=wgsl(u32) */ function uint(x) { return (x >>> 0); } exports.uint = uint; /** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */ function float2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat(); } exports.float2 = float2; /** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */ function float3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat(); } exports.float3 = float3; /** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */ function float4() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat(); } exports.float4 = float4; /** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */ function int2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x | 0; }); } exports.int2 = int2; /** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */ function int3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x | 0; }); } exports.int3 = int3; /** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */ function int4() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x | 0; }); } exports.int4 = int4; function uint2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x >>> 0; }); } exports.uint2 = uint2; function uint3() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x >>> 0; }); } exports.uint3 = uint3; function uint4() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return args.flat().map(function (x) { return x >>> 0; }); } exports.uint4 = uint4; function uint8(x) { return ((x >>> 0) & 0xff); } exports.uint8 = uint8; function componentMath(a, b, f) { var aIsScalar = isScalar(a); var bIsScalar = isScalar(b); if (aIsScalar && bIsScalar) { return f(a, b); } if (!aIsScalar && !bIsScalar) { if (a.length !== b.length) { throw new Error('Cannot perform component-wise math on vectors of different lengths'); } // return a.map((a, i) => f(a, b[i])) as vector; if (a.length == 2) { return [f(a[0], b[0]), f(a[1], b[1])]; } else if (a.length == 3) { return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2])]; } else if (a.length == 4) { return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2]), f(a[3], b[3])]; } } else if (!aIsScalar && bIsScalar) { if (a.length == 2) { return [f(a[0], b), f(a[1], b)]; } else if (a.length == 3) { return [f(a[0], b), f(a[1], b), f(a[2], b)]; } else if (a.length == 4) { return [f(a[0], b), f(a[1], b), f(a[2], b), f(a[3], b)]; } } else if (!bIsScalar && aIsScalar) { if (b.length == 2) { return [f(a, b[0]), f(a, b[1])]; } else if (b.length == 3) { return [f(a, b[0]), f(a, b[1]), f(a, b[2])]; } else if (b.length == 4) { return [f(a, b[0]), f(a, b[1]), f(a, b[2]), f(a, b[3])]; } } throw new Error('Cannot perform component-wise math on a scalar and a vector'); } function componentMathSingular(a, f) { if (isScalar(a)) { return f(a); } if (isVector(a)) { return a.map(function (a, i) { return f(a); }); } throw new Error('Cannot perform component-wise math on a scalar and a vector'); } function cCall(cb, a, b) { return componentMath(a, b, function (a, b) { return a + b; }); } function componentOp(cb) { return function (a, b) { return componentMath(a, b, cb); }; } function componentOpMatch(cb) { return function (a, b) { return componentMath(a, b, cb); }; } function componentOpSingular(cb) { return function (a) { return componentMathSingular(a, cb); }; } function componentOpSingularFloat(cb) { return function (a) { return componentMathSingular(a, cb); }; } /** @shadeup=univ(!$0$ + $1$)*/ var add = function (a, b) { if (typeof a === 'string' && typeof b === 'string') { return "".concat(a).concat(b); } else { var addOp = componentOp(function (a, b) { return a + b; }); var v = addOp(a, b); return v; } }; exports.add = add; /** @shadeup=univ(!$0$ - $1$)*/ exports.sub = componentOp(function (a, b) { return a - b; }); function matrixMul(a, b) { // Multiply two square matrices of the same dimension row-major var dimension = a.__matrix; var out; if (dimension === 2) { out = float2x2(); } else if (dimension === 3) { out = float3x3(); } else if (dimension === 4) { var a00 = a[0 * 4 + 0]; var a01 = a[0 * 4 + 1]; var a02 = a[0 * 4 + 2]; var a03 = a[0 * 4 + 3]; var a10 = a[1 * 4 + 0]; var a11 = a[1 * 4 + 1]; var a12 = a[1 * 4 + 2]; var a13 = a[1 * 4 + 3]; var a20 = a[2 * 4 + 0]; var a21 = a[2 * 4 + 1]; var a22 = a[2 * 4 + 2]; var a23 = a[2 * 4 + 3]; var a30 = a[3 * 4 + 0]; var a31 = a[3 * 4 + 1]; var a32 = a[3 * 4 + 2]; var a33 = a[3 * 4 + 3]; var b00 = b[0 * 4 + 0]; var b01 = b[0 * 4 + 1]; var b02 = b[0 * 4 + 2]; var b03 = b[0 * 4 + 3]; var b10 = b[1 * 4 + 0]; var b11 = b[1 * 4 + 1]; var b12 = b[1 * 4 + 2]; var b13 = b[1 * 4 + 3]; var b20 = b[2 * 4 + 0]; var b21 = b[2 * 4 + 1]; var b22 = b[2 * 4 + 2]; var b23 = b[2 * 4 + 3]; var b30 = b[3 * 4 + 0]; var b31 = b[3 * 4 + 1]; var b32 = b[3 * 4 + 2]; var b33 = b[3 * 4 + 3]; return float4x4(b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30, b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31, b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32, b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33, b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30, b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31, b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32, b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33, b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30, b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31, b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32, b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33, b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30, b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31, b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32, b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33); out = float4x4(); } for (var i = 0; i < dimension; i++) { for (var j = 0; j < dimension; j++) { var sum = float(0); for (var k = 0; k < dimension; k++) { sum += float(a[i * dimension + k] * b[k * dimension + j]); } out[i * dimension + j] = sum; } } return out; if (a.__matrix === 2 && b.__matrix === 2) { var a00_1 = a[0]; var a01_1 = a[1]; var a10_1 = a[2]; var a11_1 = a[3]; var b00_1 = b[0]; var b01_1 = b[1]; var b10_1 = b[2]; var b11_1 = b[3]; var v = float2x2(a00_1 * b00_1 + a01_1 * b10_1, a00_1 * b01_1 + a01_1 * b11_1, a10_1 * b00_1 + a11_1 * b10_1, a10_1 * b01_1 + a11_1 * b11_1); return v; } else if (a.__matrix === 3 && b.__matrix === 3) { var a00_2 = a[0]; var a01_2 = a[1]; var a02_1 = a[2]; var a10_2 = a[3]; var a11_2 = a[4]; var a12_1 = a[5]; var a20_1 = a[6]; var a21_1 = a[7]; var a22_1 = a[8]; var b00_2 = b[0]; var b01_2 = b[1]; var b02_1 = b[2]; var b10_2 = b[3]; var b11_2 = b[4]; var b12_1 = b[5]; var b20_1 = b[6]; var b21_1 = b[7]; var b22_1 = b[8]; var v = float3x3(a00_2 * b00_2 + a01_2 * b10_2 + a02_1 * b20_1, a00_2 * b01_2 + a01_2 * b11_2 + a02_1 * b21_1, a00_2 * b02_1 + a01_2 * b12_1 + a02_1 * b22_1, a10_2 * b00_2 + a11_2 * b10_2 + a12_1 * b20_1, a10_2 * b01_2 + a11_2 * b11_2 + a12_1 * b21_1, a10_2 * b02_1 + a11_2 * b12_1 + a12_1 * b22_1, a20_1 * b00_2 + a21_1 * b10_2 + a22_1 * b20_1, a20_1 * b01_2 + a21_1 * b11_2 + a22_1 * b21_1, a20_1 * b02_1 + a21_1 * b12_1 + a22_1 * b22_1); return v; } else if (a.__matrix === 4 && b.__matrix === 4) { var a00_3 = a[0]; var a01_3 = a[1]; var a02_2 = a[2]; var a03_1 = a[3]; var a10_3 = a[4]; var a11_3 = a[5]; var a12_2 = a[6]; var a13_1 = a[7]; var a20_2 = a[8]; var a21_2 = a[9]; var a22_2 = a[10]; var a23_1 = a[11]; var a30_1 = a[12]; var a31_1 = a[13]; var a32_1 = a[14]; var a33_1 = a[15]; var b00_3 = b[0]; var b01_3 = b[1]; var b02_2 = b[2]; var b03_1 = b[3]; var b10_3 = b[4]; var b11_3 = b[5]; var b12_2 = b[6]; var b13_1 = b[7]; var b20_2 = b[8]; var b21_2 = b[9]; var b22_2 = b[10]; var b23_1 = b[11]; var b30_1 = b[12]; var b31_1 = b[13]; var b32_1 = b[14]; var b33_1 = b[15]; var v = float4x4(a00_3 * b00_3 + a01_3 * b10_3 + a02_2 * b20_2 + a03_1 * b30_1, a00_3 * b01_3 + a01_3 * b11_3 + a02_2 * b21_2 + a03_1 * b31_1, a00_3 * b02_2 + a01_3 * b12_2 + a02_2 * b22_2 + a03_1 * b32_1, a00_3 * b03_1 + a01_3 * b13_1 + a02_2 * b23_1 + a03_1 * b33_1, a10_3 * b00_3 + a11_3 * b10_3 + a12_2 * b20_2 + a13_1 * b30_1, a10_3 * b01_3 + a11_3 * b11_3 + a12_2 * b21_2 + a13_1 * b31_1, a10_3 * b02_2 + a11_3 * b12_2 + a12_2 * b22_2 + a13_1 * b32_1, a10_3 * b03_1 + a11_3 * b13_1 + a12_2 * b23_1 + a13_1 * b33_1, a20_2 * b00_3 + a21_2 * b10_3 + a22_2 * b20_2 + a23_1 * b30_1, a20_2 * b01_3 + a21_2 * b11_3 + a22_2 * b21_2 + a23_1 * b31_1, a20_2 * b02_2 + a21_2 * b12_2 + a22_2 * b22_2 + a23_1 * b32_1, a20_2 * b03_1 + a21_2 * b13_1 + a22_2 * b23_1 + a23_1 * b33_1, a30_1 * b00_3 + a31_1 * b10_3 + a32_1 * b20_2 + a33_1 * b30_1, a30_1 * b01_3 + a31_1 * b11_3 + a32_1 * b21_2 + a33_1 * b31_1, a30_1 * b02_2 + a31_1 * b12_2 + a32_1 * b22_2 + a33_1 * b32_1, a30_1 * b03_1 + a31_1 * b13_1 + a32_1 * b23_1 + a33_1 * b33_1); return v; } else { throw new Error('Invalid matrix multiplication'); } } function matrixInversefloat2x2(m) { var a = m.__index(0)[0], b = m.__index(1)[0], c = m.__index(0)[1], d = m.__index(1)[1]; var det = a * d - b * c; if (det === 0) { throw new Error('Matrix determinant is zero'); } var detInv = 1.0 / det; return float2x2(d * detInv, -b * detInv, -c * detInv, a * detInv); } function matrixInversefloat3x3(m) { var n11 = m.__index(0)[0], n12 = m.__index(1)[0], n13 = m.__index(2)[0]; var n21 = m.__index(0)[1], n22 = m.__index(1)[1], n23 = m.__index(2)[1]; var n31 = m.__index(0)[2], n32 = m.__index(1)[2], n33 = m.__index(2)[2]; var t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13; var det = n11 * t11 + n21 * t12 + n31 * t13; if (det === 0) { throw new Error('Invalid matrix inverse'); } var detInv = 1 / det; var v = float3x3(t11 * detInv, (n31 * n23 - n33 * n21) * detInv, (n32 * n21 - n31 * n22) * detInv, t12 * detInv, (n33 * n11 - n31 * n13) * detInv, (n31 * n12 - n32 * n11) * detInv, t13 * detInv, (n21 * n13 - n23 * n11) * detInv, (n22 * n11 - n21 * n12) * detInv); return v; } function matrixInversefloat4x4(m) { var m00 = m[0 * 4 + 0]; var m01 = m[0 * 4 + 1]; var m02 = m[0 * 4 + 2]; var m03 = m[0 * 4 + 3]; var m10 = m[1 * 4 + 0]; var m11 = m[1 * 4 + 1]; var m12 = m[1 * 4 + 2]; var m13 = m[1 * 4 + 3]; var m20 = m[2 * 4 + 0]; var m21 = m[2 * 4 + 1]; var m22 = m[2 * 4 + 2]; var m23 = m[2 * 4 + 3]; var m30 = m[3 * 4 + 0]; var m31 = m[3 * 4 + 1]; var m32 = m[3 * 4 + 2]; var m33 = m[3 * 4 + 3]; var tmp_0 = m22 * m33; var tmp_1 = m32 * m23; var tmp_2 = m12 * m33; var tmp_3 = m32 * m13; var tmp_4 = m12 * m23; var tmp_5 = m22 * m13; var tmp_6 = m02 * m33; var tmp_7 = m32 * m03; var tmp_8 = m02 * m23; var tmp_9 = m22 * m03; var tmp_10 = m02 * m13; var tmp_11 = m12 * m03; var tmp_12 = m20 * m31; var tmp_13 = m30 * m21; var tmp_14 = m10 * m31; var tmp_15 = m30 * m11; var tmp_16 = m10 * m21; var tmp_17 = m20 * m11; var tmp_18 = m00 * m31; var tmp_19 = m30 * m01; var tmp_20 = m00 * m21; var tmp_21 = m20 * m01; var tmp_22 = m00 * m11; var tmp_23 = m10 * m01; var t0 = tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31 - (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31); var t1 = tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31 - (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31); var t2 = tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31 - (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31); var t3 = tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21 - (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21); var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3); if (d === 0) { throw new Error('Invalid matrix inverse'); } return float4x4(d * t0, d * t1, d * t2, d * t3, d * (tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30 - (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30)), d * (tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30 - (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30)), d * (tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30 - (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30)), d * (tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20 - (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20)), d * (tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33 - (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33)), d * (tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33 - (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33)), d * (tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33 - (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33)), d * (tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23 - (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23)), d * (tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12 - (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22)), d * (tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22 - (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02)), d * (tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02 - (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12)), d * (tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12 - (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02))); } function matrixTransposefloat2x2(m) { return float2x2(m.__index(0)[0], m.__index(1)[0], m.__index(0)[1], m.__index(1)[1]); } function matrixTransposefloat3x3(m) { return float3x3(m.__index(0)[0], m.__index(1)[0], m.__index(2)[0], m.__index(0)[1], m.__index(1)[1], m.__index(2)[1], m.__index(0)[2], m.__index(1)[2], m.__index(2)[2]); } function matrixTransposefloat4x4(m) { return float4x4(m.__index(0)[0], m.__index(1)[0], m.__index(2)[0], m.__index(3)[0], m.__index(0)[1], m.__index(1)[1], m.__index(2)[1], m.__index(3)[1], m.__index(0)[2], m.__index(1)[2], m.__index(2)[2], m.__index(3)[2], m.__index(0)[3], m.__index(1)[3], m.__index(2)[3], m.__index(3)[3]); } function matrixMul2x2float2(a, b) { var c = [0, 0]; for (var j = 0; j < 2; j++) { for (var i = 0; i < 2; i++) { c[i] += a[j * 2 + i] * b[j]; } } return c; } function matrixMul3x3float3(a, b) { var c = [0, 0, 0]; for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { c[i] += a[j * 3 + i] * b[j]; } } return c; } function matrixMul4x4float4(a, b) { var c = [0, 0, 0, 0]; for (var j = 0; j < 4; j++) { for (var i = 0; i < 4; i++) { c[i] += a[j * 4 + i] * b[j]; } } return c; } function matrixMulfloat22x2(a, b) { var c = [0, 0]; for (var j = 0; j < 2; j++) { for (var i = 0; i < 2; i++) { c[i] += a[j] * b[i * 2 + j]; } } return c; } function matrixMulfloat33x3(a, b) { var c = [0, 0, 0]; for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { c[i] += a[j] * b[i * 3 + j]; } } return c; } function matrixMulfloat44x4(a, b) { var c = [0, 0, 0, 0]; for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { c[i] += a[j] * b[i * 4 + j]; } } return c; } var mulFunc = componentOp(function (a, b) { return a * b; }); function inverse(a) { if (a.__matrix == 2) { return matrixInversefloat2x2(a); } else if (a.__matrix == 3) { return matrixInversefloat3x3(a); } else if (a.__matrix == 4) { return matrixInversefloat4x4(a); } } exports.inverse = inverse; function transpose(a) { if (a.__matrix == 2) { return matrixTransposefloat2x2(a); } else if (a.__matrix == 3) { return matrixTransposefloat3x3(a); } else if (a.__matrix == 4) { return matrixTransposefloat4x4(a); } } exports.transpose = transpose; /** @shadeup=univ(!$0$ * $1$)*/ var mul = function (a, b) { if (isMatrix(a) || isMatrix(b)) { if (isMatrix(a) && isMatrix(b)) { return matrixMul(a, b); } else { if (isMatrix(a) && typeof b == 'number') { return componentMath(b, a, function (a, b) { return a * b; }); } else if (isMatrix(b) && typeof a == 'number') { return componentMath(a, b, function (a, b) { return a * b; }); } else { if (isMatrix(a)) { if (a.length == 4) { return matrixMul2x2float2(a, b); } else if (a.length == 9) { return matrixMul3x3float3(a, b); } else if (a.length == 16) { return matrixMul4x4float4(a, b); } } else if (isMatrix(b)) { if (b.length == 4) { return matrixMulfloat22x2(a, b); } else if (b.length == 9) { return matrixMulfloat33x3(a, b); } else if (b.length == 16) { return matrixMulfloat44x4(a, b); } } } } } else { return mulFunc(a, b); } }; exports.mul = mul; /** @shadeup=univ(!$0$ / $1$)*/ exports.div = componentOp(function (a, b) { return a / b; }); /** @shadeup=glsl(!$0$ ** $1$) @shadeup=wgsl(!pow($0$, $1$))*/ exports.pow = componentOp(function (a, b) { return Math.pow(a, b); }); /** @shadeup=wgsl(!$0$ % $1$) @shadeup=glsl(!mod($0$, $1$))*/ exports.mod = componentOpMatch(function (a, b) { return a - b * Math.floor(a / b); }); /** @shadeup=univ(!$0$ & $1$)*/ exports.bitand = componentOp(function (a, b) { return a & b; }); /** @shadeup=univ(!$0$ | $1$)*/ exports.bitor = componentOp(function (a, b) { return a | b; }); /** @shadeup=univ(!$0$ ^ $1$)*/ exports.bitxor = componentOp(function (a, b) { return a ^ b; }); /** @shadeup=glsl(!$0$ << $1$) @shadeup=wgsl(!$0$ << u32($1$))*/ exports.lshift = componentOp(function (a, b) { return a << b; }); /** @shadeup=glsl(!$0$ >> $1$) @shadeup=wgsl(!$0$ >> u32($1$))*/ exports.rshift = componentOp(function (a, b) { return a >> b; }); /** @shadeup=univ(!~$0$)*/ exports.bitnot = componentOpSingular(function (a) { return ~a; }); /** @shadeup=univ(!-($0$))*/ exports.negate = componentOpSingular(function (a) { return -a; }); /** @shadeup=univ(!+($0$))*/ exports.positive = componentOpSingular(function (a) { return Math.abs(a); }); /** @shadeup=univ(abs)*/ exports.abs = componentOpSingular(function (a) { return Math.abs(a); }); /** @shadeup=glsl(floor) @shadeup=wgsl(!floor(f32(1.0) * $0$))*/ exports.floor = componentOpSingular(Math.floor); /** @shadeup=glsl(ceil) @shadeup=wgsl(!ceil(f32(1.0) * $0$))*/ exports.ceil = componentOpSingular(Math.ceil); /** @shadeup=univ(round)*/ exports.round = componentOpSingular(Math.round); /** @shadeup=univ(sign)*/ exports.sign = componentOpSingular(Math.sign); /** @shadeup=univ(cos) */ exports.cos = componentOpSingular(Math.cos); /** @shadeup=univ(sin) */ exports.sin = componentOpSingularFloat(Math.sin); /** @shadeup=univ(tan) */ exports.tan = componentOpSingular(Math.tan); /** @shadeup=univ(acos) */ exports.acos = componentOpSingular(Math.acos); /** @shadeup=univ(asin) */ exports.asin = componentOpSingular(Math.asin); /** @shadeup=univ(atan) */ exports.atan = componentOpSingular(Math.atan); /** @shadeup=univ(atan2) */ exports.atan2 = Math.atan2; /** @shadeup=univ(cosh) */ exports.cosh = componentOpSingular(Math.cosh); /** @shadeup=univ(sinh) */ exports.sinh = componentOpSingular(Math.sinh); /** @shadeup=univ(tanh) */ exports.tanh = componentOpSingular(Math.tanh); /** @shadeup=univ(acosh) */ exports.acosh = componentOpSingular(Math.acosh); /** @shadeup=univ(asinh) */ exports.asinh = componentOpSingular(Math.asinh); /** @shadeup=univ(atanh) */ exports.atanh = componentOpSingular(Math.atanh); /** @shadeup=univ(exp) */ exports.exp = componentOpSingular(Math.exp); /** @shadeup=univ(log) */ exports.log = componentOpSingular(Math.log); /** @shadeup=univ(log2) */ exports.log2 = componentOpSingular(Math.log2); /** @shadeup=univ(log10) */ exports.log10 = componentOpSingular(Math.log10); /** @shadeup=univ(sqrt) */ exports.sqrt = componentOpSingular(Math.sqrt); /** @shadeup=univ(inversesqrt) */ exports.inversesqrt = componentOpSingular(function (a) { return 1 / Math.sqrt(a); }); /** @shadeup=univ(fract)*/ exports.frac = componentOpSingular(function (a) { return a - Math.floor(a); }); function wrap(x, low, high) { if ((0, exports.lt)(x, low)) { var rng = high - low; var s1 = low - x; var ms = s1 % rng; return high - ms; } else if ((0, exports.gte)(x, high)) { var rng = high - low; var s1 = x - high; var ms = s1 % rng; return low + ms; } else { return x; } // return add(mod(sub(x, low), sub(high, low)), low) as T; } exports.wrap = wrap; /** * Returns a deterministic (same seed = same output) random float between 0-1 * * **Note:** See the noise package for more advanced random functions */ function rand(seed) { if (typeof seed === 'number') { return (0, exports.frac)(Math.sin(seed * float(91.3458)) * float(47453.5453)); } else { return Math.random(); } } exports.rand = rand; /** * Returns a deterministic (same seed = same output) random float between 0-1 * * **Note:** See the noise package for more advanced random functions */ function rand2(seed) { return (0, exports.frac)(Math.sin((0, exports.dot)(seed, float2(12.9898, 4.1414))) * float(43758.5453)); } exports.rand2 = rand2; /** * Returns a deterministic (same seed = same output) random float between 0-1 * * **Note:** See the noise package for more advanced random functions */ function rand3(seed) { var _a, _b; return rand2((_a = swizzle(seed, 'xy'), _b = rand(swizzle(seed, 'z')), [_a[0] + _b, _a[1] + _b])); } exports.rand3 = rand3; // export function remap(x: float, low1: float, high1: float, low2: float, high2: float): float { // return add(low2, mul(div(sub(x, low1), sub(high1, low1)), sub(high2, low2))); // } function pingpong(x, length) { var t = x % (length * float(2)); return length - Math.abs(t - length); } exports.pingpong = pingpong; function vectorMath_2to1_3to3(cb2, cb3) { return function (a, b) { if (a.length === 2 && b.length === 2) { return cb2(a, b); } else if (a.length === 3 && b.length === 3) { return cb3(a, b); } else { throw new Error('Invalid vector length'); } }; } function vectorMath_2to1_3to3_4to4(cb2, cb3, cb4) { return function (a, b) { if (a.length === 2 && b.length === 2) { return cb2(a, b); } else if (a.length === 3 && b.length === 3) { return cb3(a, b); } else if (a.length === 4 && b.length === 4) { return cb4(a, b); } else { throw new Error('Invalid vector length'); } }; } function vectorMath_2to1_3to1_4to1(cb2, cb3, cb4) { return function (a, b) { if (a.length === 2 && b.length === 2) { return cb2(a, b); } else if (a.length === 3 && b.length === 3) { return cb3(a, b); } else if (a.length === 4 && b.length === 4) { return cb4(a, b); } else { throw new Error('Invalid vector length'); } }; } function cross2(a, b) { return a[0] * b[1] - a[1] * b[0]; } function cross3(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; } exports.cross = vectorMath_2to1_3to3(cross2, cross3); function dot2(a, b) { return a[0] * b[0] + a[1] * b[1]; } function dot3(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } function dot4(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } /** @shadeup=univ(dot)*/ exports.dot = vectorMath_2to1_3to1_4to1(dot2, dot3, dot4); function lerp1(a, b, t) { return (a + (b - a) * t); } function lerp2(a, b, t) { return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t)]; } function lerp3(a, b, t) { return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t)]; } function lerp4(a, b, t) { return [ lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t), lerp1(a[3], b[3], t) ]; } function lerp2x2(a, b, t) { return float2x2(lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t), lerp1(a[3], b[3], t)); } function lerp3x3(a, b, t) { return float3x3(lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t), lerp1(a[3], b[3], t), lerp1(a[4], b[4], t), lerp1(a[5], b[5], t), lerp1(a[6], b[6], t), lerp1(a[7], b[7], t), lerp1(a[8], b[8], t)); } function lerp4x4(a, b, t) { return float4x4(lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t), lerp1(a[3], b[3], t), lerp1(a[4], b[4], t), lerp1(a[5], b[5], t), lerp1(a[6], b[6], t), lerp1(a[7], b[7], t), lerp1(a[8], b[8], t), lerp1(a[9], b[9], t), lerp1(a[10], b[10], t), lerp1(a[11], b[11], t), lerp1(a[12], b[12], t), lerp1(a[13], b[13], t), lerp1(a[14], b[14], t), lerp1(a[15], b[15], t)); } /** @shadeup=univ(mix)*/ function lerp(a, b, t) { if (typeof a === 'number' && typeof b === 'number' && typeof t === 'number') { return lerp1(a, b, t); } else if (isMatrix(a) && isMatrix(b)) { if (a.length === 4 && b.length === 4) { return lerp2x2(a, b, t); } else if (a.length === 9 && b.length === 9) { return lerp3x3(a, b, t); } else if (a.length === 16 && b.length === 16) { return lerp4x4(a, b, t); } else { throw new Error('Invalid matrix length'); } } else if (a.length === 2 && b.length === 2 && typeof t === 'number') { return lerp2(a, b, t); } else if (a.length === 3 && b.length === 3 && typeof t === 'number') { return lerp3(a, b, t); } else if (a.length === 4 && b.length === 4 && typeof t === 'number') { return lerp4(a, b, t); } else { throw new Error('Invalid vector length'); } } exports.lerp = lerp; /** @shadeup=univ(!bilerp_\`0\`($0$, $1$, $2$, $3$, $4$, $5$)) */ function bilerp(a, b, c, d, u, v) { return lerp(lerp(a, b, u), lerp(c, d, u), v); } exports.bilerp = bilerp; /** @shadeup=univ(length)*/ function length(a) { if (typeof a === 'number') { return Math.abs(a); } else if (a.length === 2) { return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2)); } else if (a.length === 3) { return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2)); } else if (a.length === 4) { return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2)); } else { throw new Error('Invalid vector length'); } } exports.length = length; function dist(a, b) { return length((0, exports.sub)(a, b)); } exports.dist = dist; /** @shadeup=univ(distance)*/ exports.distance = dist; /** @shadeup=univ(normalize)*/ function normalize(a) { if (a.length === 2) { var l = length(a); return [a[0] / l, a[1] / l]; } else if (a.length === 3) { var l = length(a); return [a[0] / l, a[1] / l, a[2] / l]; } else if (a.length === 4) { var l = length(a); return [a[0] / l, a[1] / l, a[2] / l, a[3] / l]; } else { throw new Error('Invalid vector length'); } } exports.normalize = normalize; /** @shadeup=univ(reflect)*/ function reflect(a, b) { if (a.length === 2 && b.length === 2) { return reflect2(a, b); } else if (a.length === 3 && b.length === 3) { return reflect3(a, b); } else if (a.length === 4 && b.length === 4) { return reflect4(a, b); } else { throw new Error('Invalid vector length'); } } exports.reflect = reflect; function reflect2(b, a) { var dot = dot2(a, b); return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1]]; } function reflect3(b, a) { var dot = dot3(a, b); return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1], b[2] - 2 * dot * a[2]]; } function reflect4(b, a) { var dot = dot4(a, b); return [ b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1], b[2] - 2 * dot * a[2], b[3] - 2 * dot * a[3] ]; } /** @shadeup=univ(refract)*/ function refract(a, b, eta) { if (a.length === 2 && b.length === 2) { return refract2(a, b, eta); } else if (a.length === 3 && b.length === 3) { return refract3(a, b, eta); } else if (a.length === 4 && b.length === 4) { return refract4(a, b, eta); } else { throw new Error('Invalid vector length'); } } exports.refract = refract; function refract2(b, a, eta) { var dot = dot2(a, b); var k = 1 - eta * eta * (1 - dot * dot); return k < 0 ? [0, 0] : [ eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0], eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1] ]; } function refract3(b, a, eta) { var dot = dot3(a, b); var k = 1 - eta * eta * (1 - dot * dot); return k < 0 ? [0, 0, 0] : [ eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0], eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1], eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2] ]; } function refract4(b, a, eta) { var dot = dot4(a, b); var k = 1 - eta * eta * (1 - dot * dot); return k < 0 ? [0, 0, 0, 0] : [ eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0], eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1], eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2], eta * b[3] - (eta * dot + Math.sqrt(k)) * a[3] ]; } /** @shadeup=univ(degrees)*/ function degrees(a) { return float((a * 180) / Math.PI); } exports.degrees = degrees; /** @shadeup=univ(radians)*/ function radians(a) { return float((a * Math.PI) / 180); } exports.radians = radians; /** @shadeup=univ(step)*/ function step(edge, x) { if (typeof edge === 'number') { if (typeof x === 'number') { return x < edge ? 0 : 1; } else { return x.map(function (v) { return (v < edge ? 0 : 1); }); } } else { if (typeof x === 'number') { return edge.map(function (v) { return (x < v ? 0 : 1); }); } else { return edge.map(function (v, i) { return (x[i] < v ? 0 : 1); }); } } } exports.step = step; function _smoothstep(a, b, x) { var t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); } /** @shadeup=univ(smoothstep)*/ function smoothstep(a, b, x) { if (typeof a === 'number' && typeof b === 'number' && typeof x === 'number') { return _smoothstep(a, b, x); } else if (typeof a === 'number' && typeof b === 'number') { return x.map(function (v) { return _smoothstep(a, b, v); }); } else { return a.map(function (v, i) { return _smoothstep(v, b[i], x[i]); }); } } exports.smoothstep = smoothstep; function componentReduce(vectors, cb) { var result = []; var _loop_1 = function (i) { result.push(cb(vectors.map(function (v) { return v[i]; }))); }; for (var i = 0; i < vectors[0].length; i++) { _loop_1(i); } return result; } /** @shadeup=univ(min)*/ function min() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (args.length == 1) { if (Array.isArray(args[0])) { return Math.min.apply(Math, args[0]); } else { return args[0]; } } else { if (Array.isArray(args[0]) && !Array.isArray(args[1])) { var minTo_1 = args[1]; return args[0].map(function (v) { return Math.min(v, minTo_1); }); } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) { var minFrom_1 = args[0]; return args[1].map(function (v) { return Math.min(minFrom_1, v); }); } else if (Array.isArray(args[0])) { return componentReduce(args, function (a) { return Math.min.apply(Math, a); }); } else { return Math.min.apply(Math, args); } } } exports.min = min; /** @shadeup=univ(max)*/ function max() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (args.length == 1) { if (Array.isArray(args[0])) { return Math.max.apply(Math, args[0]); } else { return args[0]; } } else { if (Array.isArray(args[0]) && !Array.isArray(args[1])) { var maxTo_1 = args[1]; return args[0].map(function (v) { return Math.max(v, maxTo_1); }); } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) { var maxFrom_1 = args[0]; return args[1].map(function (v) { return Math.max(maxFrom_1, v); }); } else if (Array.isArray(args[0])) { return componentReduce(args, function (a) { return Math.max.apply(Math, a); }); } else { return Math.max.apply(Math, args); } } } exports.max = max; /** @shadeup=univ(clamp)*/ function clamp(arg, min, max) { if (Array.isArray(arg)) { if (Array.isArray(min) && Array.isArray(max)) { return arg.map(function (a, i) { return Math.min(Math.max(a, min[i]), max[i]); }); } else { return arg.map(function (a) { return Math.min(Math.max(a, min), max); }); } } else { return Math.min(Math.max(arg, min), max); } } exports.clamp = clamp; /** @shadeup=glsl(!clamp($0$, 0.0, 1.0)) @shadeup=wgsl(saturate) */ function saturate(arg) { return clamp(arg, float(0), float(1)); } exports.saturate = saturate; function eq(a, b) { var ta = typeof a; var tb = typeof b; if (ta != tb) { return false; } else if ((ta == 'number' && tb == 'number') || (ta == 'string' && tb == 'string') || (ta == 'boolean' && tb == 'boolean') || (ta == 'undefined' && tb == 'undefined')) { return a == b; } else if (ta == 'object' && tb == 'object') { if (Array.isArray(a) && Array.isArray(b)) { if (a.length != b.length) { return false; } for (var i = 0; i < a.length; i++) { if (!eq(a[i], b[i])) { return false; } } return true; } else { return a == b; } } } exports.eq = eq; /** @shadeup=univ(!($0$ != $1$))*/ var neq = function (a, b) { return !eq(a, b); }; exports.neq = neq; /** @shadeup=univ(!($0$ < $1$))*/ var lt = function (a, b) { return a < b; }; exports.lt = lt; /** @shadeup=univ(!($0$ <= $1$))*/ var lte = function (a, b) { return a <= b; }; exports.lte = lte; /** @shadeup=univ(!($0$ > $1$))*/ var gt = function (a, b) { return a > b; }; exports.gt = gt; /** @shadeup=univ(!($0$ >= $1$))*/ var gte = function (a, b) { return a >= b; }; exports.gte = gte; /** @shadeup=univ(!($0$ && $1$))*/ var and = function (a, b) { return a && b; }; exports.and = and; /** @shadeup=univ(!($0$ || $1$))*/ var or = function (a, b) { return a || b; }; exports.or = or; /** @shadeup=univ(!(!$0$))*/ var not = function (a) { return !a; }; exports.not = not; /** @shadeup=univ()*/ function makeVector() { var out = []; for (var i = 0; i < arguments.length; i++) { var a = arguments[i]; if (typeof a === 'number') { out.push(a); } else { for (var j = 0; j < a.length; j++) { out.push(a[j]); } } } return out; throw new Error('Invalid vector length'); } exports.makeVector = makeVector; var swizIndex = { x: 0, y: 1, z: 2, w: 3, r: 0, g: 1, b: 2, a: 3 }; var getSwizIndexFast = function (swiz) { switch (swiz) { case 'x': return 0; case 'y': return 1; case 'z': return 2; case 'w': return 3; case 'r': return 0; case 'g': return 1; case 'b': return 2; case 'a': return 3; } }; /** @shadeup=shader */ function testDocComment() { return 1; } exports.testDocComment = testDocComment; function swizzle(v, swiz, assign) { var _a; if (typeof v === 'number') { if (swiz.length === 1) { return v; } else if (swiz.length === 2) { return [v, v]; } else if (swiz.length === 3) { return [v, v, v]; } else if (swiz.length === 4) { return [v, v, v, v]; } } else if (Array.isArray(v)) { if (typeof assign !== 'undefined') { for (var i = 0; i < swiz.length; i++) { v[getSwizIndexFast(swiz[i])] = (_a = assign[i]) !== null && _a !== void 0 ? _a : assign; } return v; } if (swiz.length === 1) { return v[getSwizIndexFast(swiz)]; } else if (swiz.length === 2) { return [v[getSwizIndexFast(swiz[0])], v[getSwizIndexFast(swiz[1])]]; } else if (swiz.length === 3) { return [ v[getSwizIndexFast(swiz[0])], v[getSwizIndexFast(swiz[1])], v[getSwizIndexFast(swiz[2])] ]; } else if (swiz.length === 4) { return [ v[getSwizIndexFast(swiz[0])], v[getSwizIndexFast(swiz[1])], v[getSwizIndexFast(swiz[2])], v[getSwizIndexFast(swiz[3])] ]; } } else { return v[swiz]; } } exports.swizzle = swizzle; function intifyVector(v) { if (typeof v === 'number') { return v; } else if (Array.isArray(v)) { return v.map(function (v) { return v | 0; }); } else { return v; } } exports.intifyVector = intifyVector; exports.FM = static_math_1.FM; // type f32 = number & { __float: never }; // type i32 = number & { __int: never }; // type num = f32 | i32; // function f32(a: number): f32 { // return a as f32; // } // function i32(a: number): i32 { // return a as i32; // } // type numeric2 = (a: A, b: B) => (A extends f32 ? f32 : (B extends f32 ? f32 : i32)); // type numeric3 = (a: A, b: B, c: C) => (A extends f32 ? f32 : (B extends f32 ? f32 : (C extends f32 ? f32 : i32))); // export const abc: numeric2 = (a, b, c) => a + b + c; // abc(f32(1), i32(2)); var atomic_internal = /** @class */ (function () { function atomic_internal(value) { this.__value = value; } /** @shadeup=univ(!atomicLoad(&$self$))*/ atomic_internal.prototype.load = function () { return this.__value; }; /** @shadeup=univ(!atomicStore(&$self$, $0$))*/ atomic_internal.prototype.store = function (value) { this.__value = value; if (this.$mutate) this.$mutate(this.__value); }; /** @shadeup=univ(!atomicAdd(&$self$, $0$))*/ atomic_internal.prototype.add = function (value) { var old = this.__value; this.__value += value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicSub(&$self$, $0$))*/ atomic_internal.prototype.sub = function (value) { var old = this.__value; this.__value -= value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicMax(&$self$, $0$))*/ atomic_internal.prototype.max = function (value) { var old = this.__value; this.__value = Math.max(value, this.__value); if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicMin(&$self$, $0$))*/ atomic_internal.prototype.min = function (value) { var old = this.__value; this.__value = Math.min(value, this.__value); if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicAnd(&$self$, $0$))*/ atomic_internal.prototype.and = function (value) { var old = this.__value; this.__value = value & this.__value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicOr(&$self$, $0$))*/ atomic_internal.prototype.or = function (value) { var old = this.__value; this.__value = value | this.__value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicXor(&$self$, $0$))*/ atomic_internal.prototype.xor = function (value) { var old = this.__value; this.__value = value ^ this.__value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicExchange(&$self$, $0$))*/ atomic_internal.prototype.exchange = function (value) { var old = this.__value; this.__value = value; if (this.$mutate) this.$mutate(this.__value); return old; }; /** @shadeup=univ(!atomicCompareExchangeWeak(&$self$, $0$, $1$))*/ atomic_internal.prototype.compareExchangeWeak = function (compare, value) { var old = this.__value; if (old == compare) { this.__value = value; } if (this.$mutate) this.$mutate(this.__value); return { old_value: old, exchanged: old == compare }; }; atomic_internal.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_math_ts_71052_atomic_internal\\",\\"fields\\":[[\\"__type\\",{\\"type\\":\\"unknown\\"}],[\\"__value\\",null],[\\"$mutate\\",{\\"type\\":\\"unknown\\"}]]}"); }; return atomic_internal; }()); exports.atomic_internal = atomic_internal; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_math_ts_71052_atomic_internal\\",\\"fields\\":[[\\"__type\\",{\\"type\\":\\"unknown\\"}],[\\"__value\\",null],[\\"$mutate\\",{\\"type\\":\\"unknown\\"}]]}"), atomic_internal) function atomic(value) { return new atomic_internal(value); } exports.atomic = atomic; window.makeAtomic = atomic; /** * Executes a control barrier synchronization function that affects memory and atomic operations in the workgroup address space. * * See: https://www.w3.org/TR/WGSL/#workgroupBarrier-builtin * * @shadeup=univ(!workgroupBarrier()) */ function workgroupBarrier() { } exports.workgroupBarrier = workgroupBarrier; /** * Executes a storage barrier synchronization function that affects memory and atomic operations in the workgroup address space. * * See: https://www.w3.org/TR/WGSL/#storageBarrier-builtin * * @shadeup=univ(!storageBarrier()) */ function storageBarrier() { } exports.storageBarrier = storageBarrier; /** * See: https://www.w3.org/TR/WGSL/#workgroupUniformLoad-builtin * * @shadeup=univ(!workgroupUniformLoad(&$0$)) */ function workgroupUniformLoad(p) { return p; } exports.workgroupUniformLoad = workgroupUniformLoad; /** * Discards the current fragment. * * A discard statement converts the invocation into a helper invocation and throws away the fragment. The discard statement must only be used in a fragment shader stage. * * See: https://www.w3.org/TR/WGSL/#discard-statement * * @shadeup=univ(!discard;) */ function discard() { } exports.discard = discard; /** * Returns the derivative of the input value with respect to the window-space x coordinate. * @param value - The input value. * @returns The derivative of the input value with respect to the window-space x coordinate. * @shadeup=glsl(!dFdx($0$)) * @shadeup=wgsl(!dpdx($0$)) */ function ddx(value) { return 0; } exports.ddx = ddx; /** * Returns the derivative of the input value with respect to the window-space y coordinate. * @param value - The input value. * * @returns The derivative of the input value with respect to the window-space y coordinate. * @shadeup=glsl(!dFdy($0$)) * @shadeup=wgsl(!dpdy($0$)) */ function ddy(value) { return 0; } exports.ddy = ddy; /** * @shadeup=glsl(!dFdxFine($0$)) * @shadeup=wgsl(!dpdxFine($0$)) */ function ddxFine(value) { return 0; } exports.ddxFine = ddxFine; /** * @shadeup=glsl(!dFdyFine($0$)) * @shadeup=wgsl(!dpdyFine($0$)) */ function ddyFine(value) { return 0; } exports.ddyFine = ddyFine; /** * @shadeup=glsl(!dFdxCoarse($0$)) * @shadeup=wgsl(!dpdxCoarse($0$)) */ function ddxCoarse(value) { return 0; } exports.ddxCoarse = ddxCoarse; /** * @shadeup=glsl(!dFdyCoarse($0$)) * @shadeup=wgsl(!dpdyCoarse($0$)) */ function ddyCoarse(value) { return 0; } exports.ddyCoarse = ddyCoarse; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!bitcast<$[0]$>($0$)) */ function bitcast(value) { return 0; } exports.bitcast = bitcast; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack4x8snorm($0$)) */ function pack4x8snorm(value) { return uint(0); } exports.pack4x8snorm = pack4x8snorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack4x8unorm($0$)) */ function pack4x8unorm(value) { return uint(0); } exports.pack4x8unorm = pack4x8unorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack2x16snorm($0$)) */ function pack2x16snorm(value) { return uint(0); } exports.pack2x16snorm = pack2x16snorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack2x16unorm($0$)) */ function pack2x16unorm(value) { return uint(0); } exports.pack2x16unorm = pack2x16unorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!pack2x16float($0$)) */ function pack2x16float(value) { return uint(0); } exports.pack2x16float = pack2x16float; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack4x8snorm($0$)) */ function unpack4x8snorm(value) { return float4(0, 0, 0, 0); } exports.unpack4x8snorm = unpack4x8snorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack4x8unorm($0$)) */ function unpack4x8unorm(value) { return float4(0, 0, 0, 0); } exports.unpack4x8unorm = unpack4x8unorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack2x16snorm($0$)) */ function unpack2x16snorm(value) { return float2(0, 0); } exports.unpack2x16snorm = unpack2x16snorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack2x16unorm($0$)) */ function unpack2x16unorm(value) { return float2(0, 0); } exports.unpack2x16unorm = unpack2x16unorm; /** * @shadeup=glsl(!$0$) * @shadeup=wgsl(!unpack2x16float($0$)) */ function unpack2x16float(value) { return float2(0, 0); } exports.unpack2x16float = unpack2x16float; }); ` } ], emitSkipped: false, diagnostics: [] }, "/static-math.ts": { outputFiles: [ { name: "/static-math.js", writeByteOrderMark: false, text: 'define(["require", "exports"], function (require, exports) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.FM = void 0;\n ///\n /// GENERATED\n /// DO NOT EDIT THIS FILE\n /// see generate-static-math.ts\n ///\n exports.FM = {\n add_1_1: function (a, b) { return a + b; },\n add_2_1: function (a, b) { return [a[0] + b, a[1] + b]; },\n add_1_2: function (a, b) { return [a + b[0], a + b[1]]; },\n add_2_2: function (a, b) { return [a[0] + b[0], a[1] + b[1]]; },\n add_3_1: function (a, b) { return [a[0] + b, a[1] + b, a[2] + b]; },\n add_1_3: function (a, b) { return [a + b[0], a + b[1], a + b[2]]; },\n add_3_3: function (a, b) { return [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; },\n add_4_1: function (a, b) { return [a[0] + b, a[1] + b, a[2] + b, a[3] + b]; },\n add_1_4: function (a, b) { return [a + b[0], a + b[1], a + b[2], a + b[3]]; },\n add_4_4: function (a, b) { return [a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]]; },\n sub_1_1: function (a, b) { return a - b; },\n sub_2_1: function (a, b) { return [a[0] - b, a[1] - b]; },\n sub_1_2: function (a, b) { return [a - b[0], a - b[1]]; },\n sub_2_2: function (a, b) { return [a[0] - b[0], a[1] - b[1]]; },\n sub_3_1: function (a, b) { return [a[0] - b, a[1] - b, a[2] - b]; },\n sub_1_3: function (a, b) { return [a - b[0], a - b[1], a - b[2]]; },\n sub_3_3: function (a, b) { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; },\n sub_4_1: function (a, b) { return [a[0] - b, a[1] - b, a[2] - b, a[3] - b]; },\n sub_1_4: function (a, b) { return [a - b[0], a - b[1], a - b[2], a - b[3]]; },\n sub_4_4: function (a, b) { return [a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]]; },\n div_1_1: function (a, b) { return a / b; },\n div_2_1: function (a, b) { return [a[0] / b, a[1] / b]; },\n div_1_2: function (a, b) { return [a / b[0], a / b[1]]; },\n div_2_2: function (a, b) { return [a[0] / b[0], a[1] / b[1]]; },\n div_3_1: function (a, b) { return [a[0] / b, a[1] / b, a[2] / b]; },\n div_1_3: function (a, b) { return [a / b[0], a / b[1], a / b[2]]; },\n div_3_3: function (a, b) { return [a[0] / b[0], a[1] / b[1], a[2] / b[2]]; },\n div_4_1: function (a, b) { return [a[0] / b, a[1] / b, a[2] / b, a[3] / b]; },\n div_1_4: function (a, b) { return [a / b[0], a / b[1], a / b[2], a / b[3]]; },\n div_4_4: function (a, b) { return [a[0] / b[0], a[1] / b[1], a[2] / b[2], a[3] / b[3]]; },\n mul_1_1: function (a, b) { return a * b; },\n mul_2_1: function (a, b) { return [a[0] * b, a[1] * b]; },\n mul_1_2: function (a, b) { return [a * b[0], a * b[1]]; },\n mul_2_2: function (a, b) { return [a[0] * b[0], a[1] * b[1]]; },\n mul_3_1: function (a, b) { return [a[0] * b, a[1] * b, a[2] * b]; },\n mul_1_3: function (a, b) { return [a * b[0], a * b[1], a * b[2]]; },\n mul_3_3: function (a, b) { return [a[0] * b[0], a[1] * b[1], a[2] * b[2]]; },\n mul_4_1: function (a, b) { return [a[0] * b, a[1] * b, a[2] * b, a[3] * b]; },\n mul_1_4: function (a, b) { return [a * b[0], a * b[1], a * b[2], a * b[3]]; },\n mul_4_4: function (a, b) { return [a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]]; },\n mod_1_1: function (a, b) { return a % b; },\n mod_2_1: function (a, b) { return [a[0] % b, a[1] % b]; },\n mod_1_2: function (a, b) { return [a % b[0], a % b[1]]; },\n mod_2_2: function (a, b) { return [a[0] % b[0], a[1] % b[1]]; },\n mod_3_1: function (a, b) { return [a[0] % b, a[1] % b, a[2] % b]; },\n mod_1_3: function (a, b) { return [a % b[0], a % b[1], a % b[2]]; },\n mod_3_3: function (a, b) { return [a[0] % b[0], a[1] % b[1], a[2] % b[2]]; },\n mod_4_1: function (a, b) { return [a[0] % b, a[1] % b, a[2] % b, a[3] % b]; },\n mod_1_4: function (a, b) { return [a % b[0], a % b[1], a % b[2], a % b[3]]; },\n mod_4_4: function (a, b) { return [a[0] % b[0], a[1] % b[1], a[2] % b[2], a[3] % b[3]]; },\n bitand_1_1: function (a, b) { return a & b; },\n bitand_2_1: function (a, b) { return [a[0] & b, a[1] & b]; },\n bitand_1_2: function (a, b) { return [a & b[0], a & b[1]]; },\n bitand_2_2: function (a, b) { return [a[0] & b[0], a[1] & b[1]]; },\n bitand_3_1: function (a, b) { return [a[0] & b, a[1] & b, a[2] & b]; },\n bitand_1_3: function (a, b) { return [a & b[0], a & b[1], a & b[2]]; },\n bitand_3_3: function (a, b) { return [a[0] & b[0], a[1] & b[1], a[2] & b[2]]; },\n bitand_4_1: function (a, b) { return [a[0] & b, a[1] & b, a[2] & b, a[3] & b]; },\n bitand_1_4: function (a, b) { return [a & b[0], a & b[1], a & b[2], a & b[3]]; },\n bitand_4_4: function (a, b) { return [a[0] & b[0], a[1] & b[1], a[2] & b[2], a[3] & b[3]]; },\n bitor_1_1: function (a, b) { return a | b; },\n bitor_2_1: function (a, b) { return [a[0] | b, a[1] | b]; },\n bitor_1_2: function (a, b) { return [a | b[0], a | b[1]]; },\n bitor_2_2: function (a, b) { return [a[0] | b[0], a[1] | b[1]]; },\n bitor_3_1: function (a, b) { return [a[0] | b, a[1] | b, a[2] | b]; },\n bitor_1_3: function (a, b) { return [a | b[0], a | b[1], a | b[2]]; },\n bitor_3_3: function (a, b) { return [a[0] | b[0], a[1] | b[1], a[2] | b[2]]; },\n bitor_4_1: function (a, b) { return [a[0] | b, a[1] | b, a[2] | b, a[3] | b]; },\n bitor_1_4: function (a, b) { return [a | b[0], a | b[1], a | b[2], a | b[3]]; },\n bitor_4_4: function (a, b) { return [a[0] | b[0], a[1] | b[1], a[2] | b[2], a[3] | b[3]]; },\n bitxor_1_1: function (a, b) { return a ^ b; },\n bitxor_2_1: function (a, b) { return [a[0] ^ b, a[1] ^ b]; },\n bitxor_1_2: function (a, b) { return [a ^ b[0], a ^ b[1]]; },\n bitxor_2_2: function (a, b) { return [a[0] ^ b[0], a[1] ^ b[1]]; },\n bitxor_3_1: function (a, b) { return [a[0] ^ b, a[1] ^ b, a[2] ^ b]; },\n bitxor_1_3: function (a, b) { return [a ^ b[0], a ^ b[1], a ^ b[2]]; },\n bitxor_3_3: function (a, b) { return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2]]; },\n bitxor_4_1: function (a, b) { return [a[0] ^ b, a[1] ^ b, a[2] ^ b, a[3] ^ b]; },\n bitxor_1_4: function (a, b) { return [a ^ b[0], a ^ b[1], a ^ b[2], a ^ b[3]]; },\n bitxor_4_4: function (a, b) { return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]; },\n lshift_1_1: function (a, b) { return a << b; },\n lshift_2_1: function (a, b) { return [a[0] << b, a[1] << b]; },\n lshift_1_2: function (a, b) { return [a << b[0], a << b[1]]; },\n lshift_2_2: function (a, b) { return [a[0] << b[0], a[1] << b[1]]; },\n lshift_3_1: function (a, b) { return [a[0] << b, a[1] << b, a[2] << b]; },\n lshift_1_3: function (a, b) { return [a << b[0], a << b[1], a << b[2]]; },\n lshift_3_3: function (a, b) { return [a[0] << b[0], a[1] << b[1], a[2] << b[2]]; },\n lshift_4_1: function (a, b) { return [a[0] << b, a[1] << b, a[2] << b, a[3] << b]; },\n lshift_1_4: function (a, b) { return [a << b[0], a << b[1], a << b[2], a << b[3]]; },\n lshift_4_4: function (a, b) { return [a[0] << b[0], a[1] << b[1], a[2] << b[2], a[3] << b[3]]; },\n rshift_1_1: function (a, b) { return a >> b; },\n rshift_2_1: function (a, b) { return [a[0] >> b, a[1] >> b]; },\n rshift_1_2: function (a, b) { return [a >> b[0], a >> b[1]]; },\n rshift_2_2: function (a, b) { return [a[0] >> b[0], a[1] >> b[1]]; },\n rshift_3_1: function (a, b) { return [a[0] >> b, a[1] >> b, a[2] >> b]; },\n rshift_1_3: function (a, b) { return [a >> b[0], a >> b[1], a >> b[2]]; },\n rshift_3_3: function (a, b) { return [a[0] >> b[0], a[1] >> b[1], a[2] >> b[2]]; },\n rshift_4_1: function (a, b) { return [a[0] >> b, a[1] >> b, a[2] >> b, a[3] >> b]; },\n rshift_1_4: function (a, b) { return [a >> b[0], a >> b[1], a >> b[2], a >> b[3]]; },\n rshift_4_4: function (a, b) { return [a[0] >> b[0], a[1] >> b[1], a[2] >> b[2], a[3] >> b[3]]; },\n bitnot_1: function (a) { return ~a; },\n bitnot_2: function (a) { return [~a[0], ~a[1]]; },\n bitnot_3: function (a) { return [~a[0], ~a[1], ~a[2]]; },\n bitnot_4: function (a) { return [~a[0], ~a[1], ~a[2], ~a[3]]; },\n negate_1: function (a) { return -a; },\n negate_2: function (a) { return [-a[0], -a[1]]; },\n negate_3: function (a) { return [-a[0], -a[1], -a[2]]; },\n negate_4: function (a) { return [-a[0], -a[1], -a[2], -a[3]]; },\n positive_1: function (a) { return Math.abs(a); },\n positive_2: function (a) { return [Math.abs(a[0]), Math.abs(a[1])]; },\n positive_3: function (a) { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])]; },\n positive_4: function (a) { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2]), Math.abs(a[3])]; },\n abs_1: function (a) { return Math.abs(a); },\n abs_2: function (a) { return [Math.abs(a[0]), Math.abs(a[1])]; },\n abs_3: function (a) { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2])]; },\n abs_4: function (a) { return [Math.abs(a[0]), Math.abs(a[1]), Math.abs(a[2]), Math.abs(a[3])]; },\n floor_1: function (a) { return Math.floor(a); },\n floor_2: function (a) { return [Math.floor(a[0]), Math.floor(a[1])]; },\n floor_3: function (a) { return [Math.floor(a[0]), Math.floor(a[1]), Math.floor(a[2])]; },\n floor_4: function (a) { return [Math.floor(a[0]), Math.floor(a[1]), Math.floor(a[2]), Math.floor(a[3])]; },\n ceil_1: function (a) { return Math.ceil(a); },\n ceil_2: function (a) { return [Math.ceil(a[0]), Math.ceil(a[1])]; },\n ceil_3: function (a) { return [Math.ceil(a[0]), Math.ceil(a[1]), Math.ceil(a[2])]; },\n ceil_4: function (a) { return [Math.ceil(a[0]), Math.ceil(a[1]), Math.ceil(a[2]), Math.ceil(a[3])]; },\n round_1: function (a) { return Math.round(a); },\n round_2: function (a) { return [Math.round(a[0]), Math.round(a[1])]; },\n round_3: function (a) { return [Math.round(a[0]), Math.round(a[1]), Math.round(a[2])]; },\n round_4: function (a) { return [Math.round(a[0]), Math.round(a[1]), Math.round(a[2]), Math.round(a[3])]; },\n sign_1: function (a) { return Math.sign(a); },\n sign_2: function (a) { return [Math.sign(a[0]), Math.sign(a[1])]; },\n sign_3: function (a) { return [Math.sign(a[0]), Math.sign(a[1]), Math.sign(a[2])]; },\n sign_4: function (a) { return [Math.sign(a[0]), Math.sign(a[1]), Math.sign(a[2]), Math.sign(a[3])]; },\n cos_1: function (a) { return Math.cos(a); },\n cos_2: function (a) { return [Math.cos(a[0]), Math.cos(a[1])]; },\n cos_3: function (a) { return [Math.cos(a[0]), Math.cos(a[1]), Math.cos(a[2])]; },\n cos_4: function (a) { return [Math.cos(a[0]), Math.cos(a[1]), Math.cos(a[2]), Math.cos(a[3])]; },\n sin_1: function (a) { return Math.sin(a); },\n sin_2: function (a) { return [Math.sin(a[0]), Math.sin(a[1])]; },\n sin_3: function (a) { return [Math.sin(a[0]), Math.sin(a[1]), Math.sin(a[2])]; },\n sin_4: function (a) { return [Math.sin(a[0]), Math.sin(a[1]), Math.sin(a[2]), Math.sin(a[3])]; },\n tan_1: function (a) { return Math.tan(a); },\n tan_2: function (a) { return [Math.tan(a[0]), Math.tan(a[1])]; },\n tan_3: function (a) { return [Math.tan(a[0]), Math.tan(a[1]), Math.tan(a[2])]; },\n tan_4: function (a) { return [Math.tan(a[0]), Math.tan(a[1]), Math.tan(a[2]), Math.tan(a[3])]; },\n acos_1: function (a) { return Math.acos(a); },\n acos_2: function (a) { return [Math.acos(a[0]), Math.acos(a[1])]; },\n acos_3: function (a) { return [Math.acos(a[0]), Math.acos(a[1]), Math.acos(a[2])]; },\n acos_4: function (a) { return [Math.acos(a[0]), Math.acos(a[1]), Math.acos(a[2]), Math.acos(a[3])]; },\n asin_1: function (a) { return Math.asin(a); },\n asin_2: function (a) { return [Math.asin(a[0]), Math.asin(a[1])]; },\n asin_3: function (a) { return [Math.asin(a[0]), Math.asin(a[1]), Math.asin(a[2])]; },\n asin_4: function (a) { return [Math.asin(a[0]), Math.asin(a[1]), Math.asin(a[2]), Math.asin(a[3])]; },\n atan_1: function (a) { return Math.atan(a); },\n atan_2: function (a) { return [Math.atan(a[0]), Math.atan(a[1])]; },\n atan_3: function (a) { return [Math.atan(a[0]), Math.atan(a[1]), Math.atan(a[2])]; },\n atan_4: function (a) { return [Math.atan(a[0]), Math.atan(a[1]), Math.atan(a[2]), Math.atan(a[3])]; },\n cosh_1: function (a) { return Math.cosh(a); },\n cosh_2: function (a) { return [Math.cosh(a[0]), Math.cosh(a[1])]; },\n cosh_3: function (a) { return [Math.cosh(a[0]), Math.cosh(a[1]), Math.cosh(a[2])]; },\n cosh_4: function (a) { return [Math.cosh(a[0]), Math.cosh(a[1]), Math.cosh(a[2]), Math.cosh(a[3])]; },\n sinh_1: function (a) { return Math.sinh(a); },\n sinh_2: function (a) { return [Math.sinh(a[0]), Math.sinh(a[1])]; },\n sinh_3: function (a) { return [Math.sinh(a[0]), Math.sinh(a[1]), Math.sinh(a[2])]; },\n sinh_4: function (a) { return [Math.sinh(a[0]), Math.sinh(a[1]), Math.sinh(a[2]), Math.sinh(a[3])]; },\n tanh_1: function (a) { return Math.tanh(a); },\n tanh_2: function (a) { return [Math.tanh(a[0]), Math.tanh(a[1])]; },\n tanh_3: function (a) { return [Math.tanh(a[0]), Math.tanh(a[1]), Math.tanh(a[2])]; },\n tanh_4: function (a) { return [Math.tanh(a[0]), Math.tanh(a[1]), Math.tanh(a[2]), Math.tanh(a[3])]; },\n acosh_1: function (a) { return Math.acosh(a); },\n acosh_2: function (a) { return [Math.acosh(a[0]), Math.acosh(a[1])]; },\n acosh_3: function (a) { return [Math.acosh(a[0]), Math.acosh(a[1]), Math.acosh(a[2])]; },\n acosh_4: function (a) { return [Math.acosh(a[0]), Math.acosh(a[1]), Math.acosh(a[2]), Math.acosh(a[3])]; },\n asinh_1: function (a) { return Math.asinh(a); },\n asinh_2: function (a) { return [Math.asinh(a[0]), Math.asinh(a[1])]; },\n asinh_3: function (a) { return [Math.asinh(a[0]), Math.asinh(a[1]), Math.asinh(a[2])]; },\n asinh_4: function (a) { return [Math.asinh(a[0]), Math.asinh(a[1]), Math.asinh(a[2]), Math.asinh(a[3])]; },\n atanh_1: function (a) { return Math.atanh(a); },\n atanh_2: function (a) { return [Math.atanh(a[0]), Math.atanh(a[1])]; },\n atanh_3: function (a) { return [Math.atanh(a[0]), Math.atanh(a[1]), Math.atanh(a[2])]; },\n atanh_4: function (a) { return [Math.atanh(a[0]), Math.atanh(a[1]), Math.atanh(a[2]), Math.atanh(a[3])]; },\n exp_1: function (a) { return Math.exp(a); },\n exp_2: function (a) { return [Math.exp(a[0]), Math.exp(a[1])]; },\n exp_3: function (a) { return [Math.exp(a[0]), Math.exp(a[1]), Math.exp(a[2])]; },\n exp_4: function (a) { return [Math.exp(a[0]), Math.exp(a[1]), Math.exp(a[2]), Math.exp(a[3])]; },\n log_1: function (a) { return Math.log(a); },\n log_2: function (a) { return [Math.log(a[0]), Math.log(a[1])]; },\n log_3: function (a) { return [Math.log(a[0]), Math.log(a[1]), Math.log(a[2])]; },\n log_4: function (a) { return [Math.log(a[0]), Math.log(a[1]), Math.log(a[2]), Math.log(a[3])]; },\n log2_1: function (a) { return Math.log2(a); },\n log2_2: function (a) { return [Math.log2(a[0]), Math.log2(a[1])]; },\n log2_3: function (a) { return [Math.log2(a[0]), Math.log2(a[1]), Math.log2(a[2])]; },\n log2_4: function (a) { return [Math.log2(a[0]), Math.log2(a[1]), Math.log2(a[2]), Math.log2(a[3])]; },\n log10_1: function (a) { return Math.log10(a); },\n log10_2: function (a) { return [Math.log10(a[0]), Math.log10(a[1])]; },\n log10_3: function (a) { return [Math.log10(a[0]), Math.log10(a[1]), Math.log10(a[2])]; },\n log10_4: function (a) { return [Math.log10(a[0]), Math.log10(a[1]), Math.log10(a[2]), Math.log10(a[3])]; },\n sqrt_1: function (a) { return Math.sqrt(a); },\n sqrt_2: function (a) { return [Math.sqrt(a[0]), Math.sqrt(a[1])]; },\n sqrt_3: function (a) { return [Math.sqrt(a[0]), Math.sqrt(a[1]), Math.sqrt(a[2])]; },\n sqrt_4: function (a) { return [Math.sqrt(a[0]), Math.sqrt(a[1]), Math.sqrt(a[2]), Math.sqrt(a[3])]; },\n int_2_1_1: function (a, b) { return [a | 0, b | 0]; },\n int_2_2: function (a) { return [a[0] | 0, a[1] | 0]; },\n int_3_1_1_1: function (a, b, c) { return [a | 0, b | 0, c | 0]; },\n int_3_2_1: function (a, b) { return [a[0] | 0, a[1] | 0, b | 0]; },\n int_3_1_2: function (a, b) { return [a | 0, b[0] | 0, b[1] | 0]; },\n int_3_3: function (a) { return [a[0] | 0, a[1] | 0, a[2] | 0]; },\n int_4_1_1_1_1: function (a, b, c, d) { return [a | 0, b | 0, c | 0, d | 0]; },\n int_4_2_1_1: function (a, b, c) { return [a[0] | 0, a[1] | 0, b | 0, c | 0]; },\n int_4_1_2_1: function (a, b, c) { return [a | 0, b[0] | 0, b[1] | 0, c | 0]; },\n int_4_1_1_2: function (a, b, c) { return [a | 0, b | 0, c[0] | 0, c[1] | 0]; },\n int_4_3_1: function (a, b) { return [a[0] | 0, a[1] | 0, a[2] | 0, b | 0]; },\n int_4_1_3: function (a, b) { return [a | 0, b[0] | 0, b[1] | 0, b[2] | 0]; },\n int_4_2_2: function (a, b) { return [a[0] | 0, a[1] | 0, b[0] | 0, b[1] | 0]; },\n int_4_4: function (a) { return [a[0] | 0, a[1] | 0, a[2] | 0, a[3] | 0]; },\n float_2_1_1: function (a, b) { return [a, b]; },\n float_2_2: function (a) { return [a[0], a[1]]; },\n float_3_1_1_1: function (a, b, c) { return [a, b, c]; },\n float_3_2_1: function (a, b) { return [a[0], a[1], b]; },\n float_3_1_2: function (a, b) { return [a, b[0], b[1]]; },\n float_3_3: function (a) { return [a[0], a[1], a[2]]; },\n float_4_1_1_1_1: function (a, b, c, d) { return [a, b, c, d]; },\n float_4_2_1_1: function (a, b, c) { return [a[0], a[1], b, c]; },\n float_4_1_2_1: function (a, b, c) { return [a, b[0], b[1], c]; },\n float_4_1_1_2: function (a, b, c) { return [a, b, c[0], c[1]]; },\n float_4_3_1: function (a, b) { return [a[0], a[1], a[2], b]; },\n float_4_1_3: function (a, b) { return [a, b[0], b[1], b[2]]; },\n float_4_2_2: function (a, b) { return [a[0], a[1], b[0], b[1]]; },\n float_4_4: function (a) { return [a[0], a[1], a[2], a[3]]; },\n uint_2_1_1: function (a, b) { return [a >>> 0, b >>> 0]; },\n uint_2_2: function (a) { return [a[0] >>> 0, a[1] >>> 0]; },\n uint_3_1_1_1: function (a, b, c) { return [a >>> 0, b >>> 0, c >>> 0]; },\n uint_3_2_1: function (a, b) { return [a[0] >>> 0, a[1] >>> 0, b >>> 0]; },\n uint_3_1_2: function (a, b) { return [a >>> 0, b[0] >>> 0, b[1] >>> 0]; },\n uint_3_3: function (a) { return [a[0] >>> 0, a[1] >>> 0, a[2] >>> 0]; },\n uint_4_1_1_1_1: function (a, b, c, d) { return [a >>> 0, b >>> 0, c >>> 0, d >>> 0]; },\n uint_4_2_1_1: function (a, b, c) { return [a[0] >>> 0, a[1] >>> 0, b >>> 0, c >>> 0]; },\n uint_4_1_2_1: function (a, b, c) { return [a >>> 0, b[0] >>> 0, b[1] >>> 0, c >>> 0]; },\n uint_4_1_1_2: function (a, b, c) { return [a >>> 0, b >>> 0, c[0] >>> 0, c[1] >>> 0]; },\n uint_4_3_1: function (a, b) { return [a[0] >>> 0, a[1] >>> 0, a[2] >>> 0, b >>> 0]; },\n uint_4_1_3: function (a, b) { return [a >>> 0, b[0] >>> 0, b[1] >>> 0, b[2] >>> 0]; },\n uint_4_2_2: function (a, b) { return [a[0] >>> 0, a[1] >>> 0, b[0] >>> 0, b[1] >>> 0]; },\n uint_4_4: function (a) { return [a[0] >>> 0, a[1] >>> 0, a[2] >>> 0, a[3] >>> 0]; },\n };\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/std___std_all.ts": { outputFiles: [ { name: "/std___std_all.js", writeByteOrderMark: false, text: `var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.time = exports.__deepClone = exports.__makeMap = exports.map = exports.array = exports.sleep = exports.hashableTypeToString = exports.globalVarGet = exports.globalVarInit = exports.compute = exports.statGraph = exports.stat = exports.flush = exports.print = exports.getShadeupLocalContext = exports.Mesh = exports.__dummy = void 0; /**__SHADEUP_STRUCT_INJECTION_HOOK__*/ exports.__dummy = 1; // import { Mesh } from '/_std/mesh'; var Mesh = /** @class */ (function () { function Mesh(prefils) { this.vertices = []; this.triangles = []; this.normals = []; this.tangents = []; this.bitangents = []; this.uvs = []; this.colors = []; this.symbol = Symbol(); if (prefils.vertices) this.vertices = prefils.vertices; if (prefils.triangles) this.triangles = prefils.triangles; if (prefils.normals) this.normals = prefils.normals; if (prefils.tangents) this.tangents = prefils.tangents; if (prefils.bitangents) this.bitangents = prefils.bitangents; if (prefils.uvs) this.uvs = prefils.uvs; if (prefils.colors) this.colors = prefils.colors; } Mesh.prototype.getVertices = function () { return this.vertices; }; Mesh.prototype.getTriangles = function () { return this.triangles; }; Mesh.prototype.getNormals = function () { return this.normals; }; Mesh.prototype.getTangents = function () { return this.tangents; }; Mesh.prototype.getBitangents = function () { return this.bitangents; }; Mesh.prototype.getUVs = function () { return this.uvs; }; Mesh.prototype.getColors = function () { return this.colors; }; Mesh.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_245_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",{\\"type\\":\\"unknown\\"}]]}"); }; return Mesh; }()); exports.Mesh = Mesh; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_245_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",{\\"type\\":\\"unknown\\"}]]}"), Mesh) var getShadeupLocalContext = function () { if (typeof localEngineContext !== 'undefined') { return localEngineContext; } else { return window; } }; exports.getShadeupLocalContext = getShadeupLocalContext; /** * Prints a set of value(s) to the console. Values will be converted to strings before printing. * * @param args Any number of values to print to the console */ function print() { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } console.log.apply(console, args); if (typeof (0, exports.getShadeupLocalContext)()['__shadeup_print'] === 'function') { (_a = (0, exports.getShadeupLocalContext)())['__shadeup_print'].apply(_a, args); } } exports.print = print; /** * Flushes (executes) all queued compute or draw calls * @shadeup=tag(async) @shadeup=noemit_gpu */ function flush() { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!(typeof (0, exports.getShadeupLocalContext)()['flushAdapter'] === 'function')) return [3 /*break*/, 2]; return [4 /*yield*/, (0, exports.getShadeupLocalContext)()['flushAdapter']()]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [2 /*return*/]; } }); }); } exports.flush = flush; /** * Displays a single value in the stats panel at the top right * * @param name key for this stat (e.g. "fps") * @param value any value */ function stat(name, value) { if (typeof (0, exports.getShadeupLocalContext)()['__shadeup_stat'] === 'function') { (0, exports.getShadeupLocalContext)()['__shadeup_stat'](name, value); } } exports.stat = stat; /** * Display a graph of a numeric value over time * * @param name key for this stat (e.g. "fps") * @param value any numeric value * @param sampleRate how often should the graph be updated (e.g. 1 = every call, 2 = every second call, etc.) */ function statGraph(name, value, sampleRate) { if (sampleRate === void 0) { sampleRate = 1; } if (typeof (0, exports.getShadeupLocalContext)()['__shadeup_statGraph'] === 'function') { (0, exports.getShadeupLocalContext)()['__shadeup_statGraph'](name, value); } } exports.statGraph = statGraph; function infer(fn) { return fn; } // export function drawAlt(keys: shader) {} // export function draw(fullScreenPixelShader: shader): void; // export function draw( // first: Mesh | any | shader, // second?: shader, // third?: shader // ) { // if ('vertices' in first && second && third) { // __shadeup_dispatch_draw_geometry(first, second, third); // } else if (first && !second && !third) { // __shadeup_dispatch_draw(first as shader); // } // } // draw(makeShader('', (a, b) => {})); // drawAlt( // makeShader( // '000004808000091289258019303699031390005438610', // /**@shadeup=shader*/ (__in, __out) => { // __out.color; // } // ) // ); // /** // * // */ function compute(workgroups, computeShader) { (0, exports.getShadeupLocalContext)().__shadeup_dispatch_compute(workgroups, computeShader); } exports.compute = compute; // function draww(s: shader<{ abc: 123 }, { test: 123 }>) {} // type x = { x: T }; // function makeTex(a: T): x { // return { x: a }; // } // draw({ // vertex: shader('abc', (__in, __out) => {}), // attachments: [ // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }), // makeTex({ abc: 123 }) // ], // mesh: new Mesh(), // fragment: shader('abc', (__in, __out) => { // //__out.attachment0 // }) // }); function globalVarInit(fileName, varName, initFn, getterFn) { if (!(0, exports.getShadeupLocalContext)()['shadeup_globals']) { (0, exports.getShadeupLocalContext)()['shadeup_globals'] = {}; } if (!(0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName]) { (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName] = {}; } // Disable caching for now var cache = false; if (!(varName in (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName]) || !cache) { (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName][varName] = initFn(); } (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName]['$getter_' + varName] = getterFn; return (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName][varName]; } exports.globalVarInit = globalVarInit; function globalVarGet(fileName, varName) { if (varName == 'env' || varName == 'PLATFORM_WEBGPU' || varName == 'PLATFORM_WEBGL') { return (0, exports.getShadeupLocalContext)()[varName]; } return (0, exports.getShadeupLocalContext)()['shadeup_globals'][fileName]['$getter_' + varName](); } exports.globalVarGet = globalVarGet; function hashableTypeToString(k) { if (typeof k == 'number') { return k.toString(); } else if (typeof k == 'object') { if (Array.isArray(k)) { return k.map(hashableTypeToString).join(','); } else { return k.toString(); } } else { return k.toString(); } } exports.hashableTypeToString = hashableTypeToString; Array.prototype.len = function () { return this.length; }; Array.prototype.last = function () { return this[this.length - 1]; }; Array.prototype.first = function () { return this[0]; }; Array.prototype.append = function (items) { for (var i = 0; i < items.length; i++) { this.push(items[i]); } }; Array.prototype.remove = function (index) { this.splice(index, 1); }; Array.prototype.__index = function (index) { return this[index]; }; Array.prototype.__index_assign = function (index, value) { this[index] = value; }; Array.prototype.__index_assign_op = function (op_fn, index, value) { this[index] = op_fn(this[index], value); }; /** @shadeup=tag(async) */ function sleep(seconds) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, new Promise(function (resolve) { return setTimeout(resolve, seconds * 1000); })]; }); }); } exports.sleep = sleep; function array(count, initializer) { if (initializer === void 0) { initializer = null; } var arr = new Array(count); if (initializer) { for (var i = 0; i < count; i++) { arr[i] = initializer; } } return arr; } exports.array = array; var map = /** @class */ (function () { function map(entries) { this.pairs = new Map(); if (entries) for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { var e = entries_1[_i]; this.__index_assign(e[0], e[1]); } } map.prototype.__index = function (key) { if (!this.pairs.has(hashableTypeToString(key))) { throw new Error('Key not found: ' + hashableTypeToString(key)); } return this.pairs.get(hashableTypeToString(key))[1]; }; map.prototype.__index_assign = function (key, value) { this.pairs.set(hashableTypeToString(key), [key, value]); }; map.prototype.__index_assign_op = function (op_fn, key, value) { this.pairs.set(hashableTypeToString(key), [key, op_fn(this.__index(key), value)]); }; map.prototype.delete = function (key) { this.pairs.delete(hashableTypeToString(key)); }; map.prototype.has = function (key) { return this.pairs.has(hashableTypeToString(key)); }; map.prototype.keys = function () { return Array.from(this.pairs.values()).map(function (k) { return k[0]; }); }; map.prototype.values = function () { return Array.from(this.pairs.values()).map(function (k) { return k[1]; }); }; map.new = function (entries) { return new map(entries); }; map.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_8545_map\\",\\"fields\\":[[\\"pairs\\",null]]}"); }; return map; }()); exports.map = map; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_8545_map\\",\\"fields\\":[[\\"pairs\\",null]]}"), map) function __makeMap(initial) { return new map(Object.entries(initial)); } exports.__makeMap = __makeMap; function __deepClone(value) { if (typeof value == 'object') { if (Array.isArray(value)) { var res = new Array(value.length); for (var i = 0; i < value.length; i++) { res[i] = __deepClone(value[i]); } return res; } else { if (value && typeof value.clone == 'function') { return value.clone(); } else { return value; } } } else { return value; } } exports.__deepClone = __deepClone; var time = /** @class */ (function () { function time() { } /** Saves the current time with a key of name */ time.start = function (name) { performance.mark((name !== null && name !== void 0 ? name : '_default') + '_start'); }; /** Returns the difference in milliseconds between a start with the same key */ time.stop = function (name) { performance.mark((name !== null && name !== void 0 ? name : '_default') + '_end'); var res = performance.measure((name !== null && name !== void 0 ? name : '_default') + '_diff', (name !== null && name !== void 0 ? name : '_default') + '_start', (name !== null && name !== void 0 ? name : '_default') + '_end'); return res.duration; }; /** * This returns a decimal resolution time in milliseconds since the page started. Useful for measuring time differences * * This uses performance.now() under the hood: * The performance.now() method returns a high resolution timestamp in milliseconds. It represents the time elapsed since Performance.timeOrigin */ time.now = function () { return performance.now(); }; time.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_10778_time\\",\\"fields\\":[]}"); }; return time; }()); exports.time = time; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_std_i_iistd_all_ts_10778_time\\",\\"fields\\":[]}"), time) }); ` } ], emitSkipped: false, diagnostics: [] }, "/std.ts": { outputFiles: [ { name: "/std.js", writeByteOrderMark: false, text: 'var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\ndefine(["require", "exports", "/_std/ui", "/_std/mesh", "/_std/sdf", "/_std/geo", "/_std/native"], function (require, exports, ui_1, mesh_1, sdf_1, geo_1, native_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.geo = exports.sdf = exports.Mesh = exports.mesh = exports.ui = void 0;\n Object.defineProperty(exports, "ui", { enumerable: true, get: function () { return ui_1.ui; } });\n Object.defineProperty(exports, "mesh", { enumerable: true, get: function () { return mesh_1.mesh; } });\n Object.defineProperty(exports, "Mesh", { enumerable: true, get: function () { return mesh_1.Mesh; } });\n Object.defineProperty(exports, "sdf", { enumerable: true, get: function () { return sdf_1.sdf; } });\n Object.defineProperty(exports, "geo", { enumerable: true, get: function () { return geo_1.geo; } });\n __exportStar(native_1, exports);\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/ui.ts": { outputFiles: [ { name: "/_std/ui.js", writeByteOrderMark: false, text: `define(["require", "exports", "/_std/context"], function (require, exports, context_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ui = void 0; var ui; (function (ui) { function puck(position) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_PUCK(position); } ui.puck = puck; function draggable(position, radius) { if (radius === void 0) { radius = 10; } return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_PUCK(position, radius, true); } ui.draggable = draggable; function textbox(value) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('textbox', value); } ui.textbox = textbox; function slider(value, min, max) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_SLIDER(value, { min: min, max: max }); } ui.slider = slider; function label(text) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('label', text); } ui.label = label; function checkbox(value) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('checkbox', value); } ui.checkbox = checkbox; function combo(value, options) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('combo', value, { options: options }); } ui.combo = combo; function group(text) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('group', text); } ui.group = group; function button(text) { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('button', false, { text: text }); } ui.button = button; function pop() { return (0, context_1.getShadeupLocalContext)()._SHADEUP_UI_CONTROL('pop'); } ui.pop = pop; })(ui = exports.ui || (exports.ui = {})); }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/native.ts": { outputFiles: [ { name: "/_std/native.js", writeByteOrderMark: false, text: `define(["require", "exports", "/_std/common", "/_std/context"], function (require, exports, common_1, context_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.KeyboardInputState = exports.MouseInputState = exports.FrameContext = exports.shadeupMakeTextureFromUrl = void 0; function shadeupMakeTextureFromUrl(url) { return (0, context_1.getShadeupLocalContext)()['shadeupMakeTextureFromUrlNative'](url); } exports.shadeupMakeTextureFromUrl = shadeupMakeTextureFromUrl; var FrameContext = /** @class */ (function () { function FrameContext() { /** Mouse/touch screen input state for this frame */ this.mouse = new MouseInputState(); /** Keyboard input state for this frame */ this.keyboard = new KeyboardInputState(); /** Controllable camera (Hold right click and use WASD to move) */ this.camera = new common_1.Camera(); this.camera2d = new common_1.Camera2d(); } FrameContext.prototype.configureCamera = function (options) { }; /** * Use external values from the host JavaScript environment. */ FrameContext.prototype.input = function (key, defaultValue) { return defaultValue; }; /** * Send values to the host JavaScript environment. */ FrameContext.prototype.output = function (key, value) { }; FrameContext.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_387_FrameContext\\",\\"fields\\":[[\\"deltaTime\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"time\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"screenSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frame\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"mouse\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_1719_MouseInputState\\",\\"fields\\":[[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"button\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"clicked\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"dragging\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"wheel\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"velocity\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"focused\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}]]}],[\\"keyboard\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_3334_KeyboardInputState\\",\\"fields\\":[[\\"backspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"tab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"enter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"capsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"escape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"space\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"home\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"printScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"insert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"delete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"contextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"scrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"semicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"equal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"comma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"minus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"period\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"slash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"quote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedTab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedCapsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEscape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSpace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedHome\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPrintScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedInsert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDelete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedContextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedScrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSemicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEqual\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedComma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMinus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPeriod\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSlash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedQuote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowVector\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}]]}],[\\"camera\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_10837_Camera\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"rotation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"width\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"height\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"fov\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"near\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"far\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}],[\\"camera2d\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_9812_Camera2d\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"zoom\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}]]}"); }; return FrameContext; }()); exports.FrameContext = FrameContext; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_387_FrameContext\\",\\"fields\\":[[\\"deltaTime\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"time\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"screenSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frame\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"mouse\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_1719_MouseInputState\\",\\"fields\\":[[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"button\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"clicked\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"dragging\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"wheel\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"velocity\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"focused\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}]]}],[\\"keyboard\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_3334_KeyboardInputState\\",\\"fields\\":[[\\"backspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"tab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"enter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"capsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"escape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"space\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"home\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"printScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"insert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"delete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"contextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"scrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"semicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"equal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"comma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"minus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"period\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"slash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"quote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedTab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedCapsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEscape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSpace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedHome\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPrintScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedInsert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDelete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedContextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedScrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSemicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEqual\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedComma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMinus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPeriod\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSlash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedQuote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowVector\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}]]}],[\\"camera\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_10837_Camera\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"rotation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"width\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"height\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"fov\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"near\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"far\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}],[\\"camera2d\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_9812_Camera2d\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"zoom\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}]]}"), FrameContext) var MouseInputState = /** @class */ (function () { function MouseInputState() { /** , Some("Mouse button down state for buttons 0-3 (left, middle, right */ this.button = [false, false, false]; /** Mouse button pressed state for buttons 0-3 (left, middle, right) */ this.clicked = [false, false, false]; } MouseInputState.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_1719_MouseInputState\\",\\"fields\\":[[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"button\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"clicked\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"dragging\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"wheel\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"velocity\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"focused\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}]]}"); }; return MouseInputState; }()); exports.MouseInputState = MouseInputState; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_1719_MouseInputState\\",\\"fields\\":[[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"startUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaUv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"deltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"frameDeltaScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"button\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"clicked\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"},\\"staticSize\\":3}],[\\"dragging\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"wheel\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"velocity\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"focused\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}]]}"), MouseInputState) var KeyboardInputState = /** @class */ (function () { function KeyboardInputState() { } KeyboardInputState.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_3334_KeyboardInputState\\",\\"fields\\":[[\\"backspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"tab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"enter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"capsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"escape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"space\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"home\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"printScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"insert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"delete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"contextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"scrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"semicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"equal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"comma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"minus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"period\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"slash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"quote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedTab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedCapsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEscape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSpace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedHome\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPrintScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedInsert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDelete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedContextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedScrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSemicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEqual\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedComma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMinus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPeriod\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSlash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedQuote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowVector\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}]]}"); }; return KeyboardInputState; }()); exports.KeyboardInputState = KeyboardInputState; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_native_ts_3334_KeyboardInputState\\",\\"fields\\":[[\\"backspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"tab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"enter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"shiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"controlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"altRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"capsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"escape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"space\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"home\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"printScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"insert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"delete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"digit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"keyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"metaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"contextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"f12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"numLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"scrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"semicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"equal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"comma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"minus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"period\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"slash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"backslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"bracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"quote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackspace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedTab\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnter\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedShiftRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedControlRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedAltRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPause\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedCapsLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEscape\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSpace\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPageDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedHome\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowUp\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedArrowDown\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPrintScreen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedInsert\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDelete\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedDigit9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyA\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyB\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyC\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyD\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyE\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyF\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyG\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyH\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyI\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyJ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyK\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyL\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyM\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyN\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyO\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyP\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyQ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyR\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyS\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyT\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyU\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyV\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyW\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyX\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyY\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedKeyZ\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMetaRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedContextMenu\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad0\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpad9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadMultiply\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadAdd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadSubtract\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDecimal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumpadDivide\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF1\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF2\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF3\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF4\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF5\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF6\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF7\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF8\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF9\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF10\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF11\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedF12\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedNumLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedScrollLock\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSemicolon\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedEqual\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedComma\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedMinus\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedPeriod\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedSlash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackquote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketLeft\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBackslash\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedBracketRight\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pressedQuote\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"arrowVector\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}]]}"), KeyboardInputState) }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/paint.ts": { outputFiles: [ { name: "/_std/paint.js", writeByteOrderMark: false, text: `define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PaintingContext = void 0; var PaintingContext = /** @class */ (function () { function PaintingContext(canvas, gl) { var _this = this; this.markDirtyCallback = function () { }; this.__ctx = null; this.__gl = null; this.__offscreen_canvas = null; this.__program = null; this.stagedChanges = false; this.dirty = false; this.fastPoints = false; this.fastPointsBuffer = null; this.__currentColor = null; this.pointsCounter = 0; this.cacheSize = [0, 0]; if (!gl) return; this.__gl = gl; this.__canvas = canvas; this.__offscreen_canvas = document.createElement('canvas'); this.__offscreen_canvas.width = canvas.width; this.__offscreen_canvas.height = canvas.height; // document.body.appendChild(this.__offscreen_canvas); this.__ctx = this.__offscreen_canvas.getContext('2d', { willReadFrequently: true }); this.__offscreen_canvas.style.position = 'absolute'; this.__offscreen_canvas.style.zIndex = '10'; // document.body.appendChild(this.__offscreen_canvas); this.__setColor([0, 0, 0, 1]); gl.addEventListener('context', function (toContext) { if (toContext == 'draw') { _this.flush(); } }); gl.addEventListener('flush', function () { _this.flush(); }); } PaintingContext.prototype.flush = function () { if (!this.__gl) return; if (!this.__canvas) return; if (!this.__offscreen_canvas) return; if (!this.stagedChanges) return; if (this.fastPoints) this.flushPoints(); this.__gl.drawImage(this.__offscreen_canvas); this.stagedChanges = false; if (this.__offscreen_canvas.width != this.__canvas.width || this.__offscreen_canvas.height != this.__canvas.height) { this.__offscreen_canvas.width = this.__canvas.width; this.__offscreen_canvas.height = this.__canvas.height; } this.pointsCounter = 0; }; PaintingContext.prototype.__beforeDraw = function () { var _a; if (!this.__offscreen_canvas) return; if (!this.__ctx) return; if (!this.__canvas) return; this.markDirtyCallback(); (_a = this.__gl) === null || _a === void 0 ? void 0 : _a.activatePaintContext(); if (!this.stagedChanges) { this.__ctx.clearRect(0, 0, this.__canvas.width, this.__canvas.height); this.__ctx.drawImage(this.__canvas, 0, 0); var color = this.__currentColor; this.__ctx.fillStyle = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); this.__ctx.strokeStyle = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); } }; PaintingContext.prototype.__afterDraw = function () { var gl = this.__gl; this.dirty = true; this.stagedChanges = true; }; PaintingContext.prototype.__setColor = function (color) { if (!this.__ctx || !color) return; if (this.__currentColor && this.__currentColor[0] == color[0] && this.__currentColor[1] == color[1] && this.__currentColor[2] == color[2] && this.__currentColor[3] == color[3]) return; this.__ctx.strokeStyle = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); this.__ctx.fillStyle = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); this.__currentColor = [color[0], color[1], color[2], color[3]]; }; PaintingContext.prototype.fillRect = function (pos, size, color) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.fillRect(pos[0], pos[1], size[0], size[1]); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.fillCircle = function (pos, radius, color) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.fillArc = function (pos, radius, startAngle, endAngle, color) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.line = function (pos1, pos2, color, width) { if (width === void 0) { width = 1; } if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.moveTo(pos1[0], pos1[1]); this.__ctx.lineTo(pos2[0], pos2[1]); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.circle = function (pos, radius, color, width) { if (width === void 0) { width = 1; } if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.arc = function (pos, radius, startAngle, endAngle, color, width) { if (width === void 0) { width = 1; } if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.text = function (pos, text, color) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.fillText(text, pos[0], pos[1]); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.startPath = function (pos) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__ctx.beginPath(); this.__ctx.moveTo(pos[0], pos[1]); }; PaintingContext.prototype.lineTo = function (pos) { if (!this.__ctx) return; this.__ctx.lineTo(pos[0], pos[1]); }; PaintingContext.prototype.strokePath = function (color, width) { if (width === void 0) { width = 1; } if (!this.__ctx) return; this.__ctx.lineWidth = width; this.__setColor(color); this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.fillPath = function (color) { if (!this.__ctx) return; this.__setColor(color); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.setStrokeWidth = function (width) { if (!this.__ctx) return; this.__ctx.lineWidth = width; }; PaintingContext.prototype.setFont = function (font) { if (!this.__ctx) return; this.__ctx.font = font; }; PaintingContext.prototype.setFontSize = function (size) { if (!this.__ctx) return; this.__ctx.font = "".concat(size, "px ").concat(this.__ctx.font.split(' ').slice(1).join(' ')); }; PaintingContext.prototype.setTextAlign = function (align) { if (!this.__ctx) return; this.__ctx.textAlign = align; }; PaintingContext.prototype.setTextBaseline = function (baseline) { if (!this.__ctx) return; this.__ctx.textBaseline = baseline; }; PaintingContext.prototype.setLineCap = function (cap) { if (!this.__ctx) return; this.__ctx.lineCap = cap; }; PaintingContext.prototype.setLineJoin = function (join) { if (!this.__ctx) return; this.__ctx.lineJoin = join; }; PaintingContext.prototype.setMiterLimit = function (limit) { if (!this.__ctx) return; this.__ctx.miterLimit = limit; }; PaintingContext.prototype.setShadowColor = function (color) { if (!this.__ctx) return; this.__ctx.shadowColor = "rgba(".concat(color[0] * 255, ", ").concat(color[1] * 255, ", ").concat(color[2] * 255, ", ").concat(color[3], ")"); }; PaintingContext.prototype.setShadowBlur = function (blur) { if (!this.__ctx) return; this.__ctx.shadowBlur = blur; }; PaintingContext.prototype.setShadowOffset = function (offset) { if (!this.__ctx) return; this.__ctx.shadowOffsetX = offset[0]; this.__ctx.shadowOffsetY = offset[1]; }; PaintingContext.prototype.setGlobalAlpha = function (alpha) { if (!this.__ctx) return; this.__ctx.globalAlpha = alpha; }; PaintingContext.prototype.setGlobalCompositeOperation = function (op) { if (!this.__ctx) return; this.__ctx.globalCompositeOperation = op; }; PaintingContext.prototype.setImageSmoothingEnabled = function (enabled) { if (!this.__ctx) return; this.__ctx.imageSmoothingEnabled = enabled; }; PaintingContext.prototype.setImageSmoothingQuality = function (quality) { if (!this.__ctx) return; this.__ctx.imageSmoothingQuality = quality; }; PaintingContext.prototype.setLineDash = function (dash) { if (!this.__ctx) return; this.__ctx.setLineDash(dash); }; PaintingContext.prototype.setLineDashOffset = function (offset) { if (!this.__ctx) return; this.__ctx.lineDashOffset = offset; }; PaintingContext.prototype.setTransform = function (a, b, c, d, e, f) { if (!this.__ctx) return; this.__ctx.setTransform(a, b, c, d, e, f); }; PaintingContext.prototype.resetTransform = function () { if (!this.__ctx) return; this.__ctx.resetTransform(); }; PaintingContext.prototype.scale = function (v) { if (!this.__ctx) return; this.__ctx.scale(v[0], v[1]); }; PaintingContext.prototype.rotate = function (angle) { if (!this.__ctx) return; this.__ctx.rotate(angle); }; PaintingContext.prototype.translate = function (v) { if (!this.__ctx) return; this.__ctx.translate(v[0], v[1]); }; PaintingContext.prototype.flushPoints = function () { if (!this.__ctx) return; if (!this.fastPoints) return; if (!this.fastPointsBuffer) return; this.__ctx.putImageData(this.fastPointsBuffer, 0, 0); this.fastPoints = false; this.fastPointsBuffer = null; this.pointsCounter = 0; }; PaintingContext.prototype.point = function (pos, color) { if (!this.__ctx) return; this.pointsCounter++; this.__beforeDraw(); if (this.pointsCounter > 10) { if (!this.fastPoints) { this.fastPoints = true; this.cacheSize = [this.__offscreen_canvas.width, this.__offscreen_canvas.height]; this.fastPointsBuffer = this.__ctx.getImageData(0, 0, this.cacheSize[0], this.cacheSize[1]); } if (!this.fastPointsBuffer) return; var x = Math.floor(pos[0]); var y = Math.floor(pos[1]); var index = (y * this.cacheSize[0] + x) * 4; if (!color) { color = this.__currentColor; } var oldColorx = this.fastPointsBuffer.data[index] / 255; var oldColory = this.fastPointsBuffer.data[index + 1] / 255; var oldColorz = this.fastPointsBuffer.data[index + 2] / 255; var oldColora = this.fastPointsBuffer.data[index + 3] / 255; this.fastPointsBuffer.data[index] = color[0] * 255 * color[3] + oldColorx * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 1] = color[1] * 255 * color[3] + oldColory * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 2] = color[2] * 255 * color[3] + oldColorz * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 3] = color[3] * 255 + oldColora * 255 * (1 - color[3]); } else { this.__setColor(color); this.__ctx.fillRect(pos[0], pos[1], 1, 1); } this.__afterDraw(); }; PaintingContext.prototype.vector = function (pos, dir, color, width) { if (color === void 0) { color = [0.9803921568627451, 0.8, 0.08235294117647059, 1]; } if (width === void 0) { width = 4; } if (!this.__ctx || (dir[0] == 0 && dir[1] == 0)) return; this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.setStrokeWidth(width); this.__ctx.moveTo(pos[0], pos[1]); this.__ctx.lineCap = 'round'; this.__ctx.lineTo(pos[0] + dir[0], pos[1] + dir[1]); this.__ctx.stroke(); this.__ctx.beginPath(); this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]); // Arrows var arrowSize = 20; var arrowAngle = Math.PI / 5; var dirAngle = Math.atan2(dir[1], dir[0]) + Math.PI; var arrow1 = [ Math.cos(dirAngle + arrowAngle) * arrowSize, Math.sin(dirAngle + arrowAngle) * arrowSize ]; var arrow2 = [ Math.cos(dirAngle - arrowAngle) * arrowSize, Math.sin(dirAngle - arrowAngle) * arrowSize ]; this.__ctx.lineTo(pos[0] + dir[0] + arrow1[0], pos[1] + dir[1] + arrow1[1]); this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]); this.__ctx.lineTo(pos[0] + dir[0] + arrow2[0], pos[1] + dir[1] + arrow2[1]); this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype.grid = function (center, count, gap, color, width) { if (color === void 0) { color = [0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1]; } if (width === void 0) { width = 2; } if (!this.__ctx) return; this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.setStrokeWidth(width); var start = [ center[0] - (count[0] / 2) * gap[0], center[1] - (count[1] / 2) * gap[1] ]; for (var i = 0; i <= count[0]; i++) { this.__ctx.moveTo(start[0] + i * gap[0], start[1]); this.__ctx.lineTo(start[0] + i * gap[0], start[1] + count[1] * gap[1]); } for (var i = 0; i <= count[1]; i++) { this.__ctx.moveTo(start[0], start[1] + i * gap[1]); this.__ctx.lineTo(start[0] + count[0] * gap[0], start[1] + i * gap[1]); } this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; }; PaintingContext.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_paint_ts_225_PaintingContext\\",\\"fields\\":[[\\"markDirtyCallback\\",{\\"type\\":\\"unknown\\"}],[\\"__ctx\\",null],[\\"__gl\\",null],[\\"__offscreen_canvas\\",null],[\\"__program\\",null],[\\"stagedChanges\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPoints\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPointsBuffer\\",null],[\\"__currentColor\\",null],[\\"pointsCounter\\",null],[\\"cacheSize\\",{\\"type\\":\\"array\\",\\"staticSize\\":2}]]}"); }; return PaintingContext; }()); exports.PaintingContext = PaintingContext; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_paint_ts_225_PaintingContext\\",\\"fields\\":[[\\"markDirtyCallback\\",{\\"type\\":\\"unknown\\"}],[\\"__ctx\\",null],[\\"__gl\\",null],[\\"__offscreen_canvas\\",null],[\\"__program\\",null],[\\"stagedChanges\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPoints\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPointsBuffer\\",null],[\\"__currentColor\\",null],[\\"pointsCounter\\",null],[\\"cacheSize\\",{\\"type\\":\\"array\\",\\"staticSize\\":2}]]}"), PaintingContext) }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/buffer.ts": { outputFiles: [ { name: "/_std/buffer.js", writeByteOrderMark: false, text: `var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; define(["require", "exports", "/_std/context", "/std_math"], function (require, exports, context_1, std_math_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buffer = exports.buffer_internal = void 0; var __ = { intifyVector: std_math_1.intifyVector }; var buffer_internal = /** @class */ (function () { function buffer_internal(size, typeName, structure) { var _this = this; this.__opaque_buffer = true; this.structArray = null; this.floatArray = null; this.intArray = null; this.uintArray = null; this.arrayBuffer = null; this.vectorSize = 0; this.platformPayload = null; this.adapter = null; this.dirty = false; this.pendingWrites = 0; this.cpuReadDirty = false; this.cpuWriteDirty = false; this.elementCount = 0; this.elementBytes = 0; this.structured = false; this.watchMutation = false; this.symbol = Symbol(); this.adapter = (0, context_1.getShadeupLocalContext)().shadeupGetGraphicsAdapter(); this.typeName = typeName; if (structure) { if (structure.name && !structure.name.startsWith('atomic')) { this.typeName = structure.name; } } this.elementCount = size; this.elementBytes = 4; if (typeName == 'float4' || typeName == 'float3' || typeName == 'float2' || typeName == 'float') { this.vectorSize = 1; this.fastIndex = function (index) { return _this.floatArray[index]; }; this.fastIndexAssign = function (index, value) { _this.floatArray[index] = value; }; if (typeName == 'float4') { this.vectorSize = 4; this.fastIndex = function (index) { return (0, std_math_1.float4)(_this.floatArray[index * 4], _this.floatArray[index * 4 + 1], _this.floatArray[index * 4 + 2], _this.floatArray[index * 4 + 3]); }; this.fastIndexAssign = function (index, value) { _this.floatArray[index * 4] = value[0]; _this.floatArray[index * 4 + 1] = value[1]; _this.floatArray[index * 4 + 2] = value[2]; _this.floatArray[index * 4 + 3] = value[3]; }; } if (typeName == 'float3') { this.vectorSize = 3; this.fastIndex = function (index) { return (0, std_math_1.float3)(_this.floatArray[index * 3], _this.floatArray[index * 3 + 1], _this.floatArray[index * 3 + 2]); }; this.fastIndexAssign = function (index, value) { _this.floatArray[index * 3] = value[0]; _this.floatArray[index * 3 + 1] = value[1]; _this.floatArray[index * 3 + 2] = value[2]; }; } if (typeName == 'float2') { this.vectorSize = 2; this.fastIndex = function (index) { return (0, std_math_1.float2)(_this.floatArray[index * 2], _this.floatArray[index * 2 + 1]); }; this.fastIndexAssign = function (index, value) { _this.floatArray[index * 2] = value[0]; _this.floatArray[index * 2 + 1] = value[1]; }; } this.floatArray = new Float32Array(size * this.vectorSize); this.arrayBuffer = this.floatArray.buffer; } else if (typeName == 'int4' || typeName == 'int3' || typeName == 'int2' || typeName == 'int') { this.vectorSize = 1; this.fastIndex = function (index) { return _this.intArray[index]; }; this.fastIndexAssign = function (index, value) { _this.intArray[index] = value; }; if (typeName == 'int4') { this.vectorSize = 4; this.fastIndex = function (index) { return __.intifyVector((0, std_math_1.int4)(_this.intArray[index * 4], _this.intArray[index * 4 + 1], _this.intArray[index * 4 + 2], _this.intArray[index * 4 + 3])); }; this.fastIndexAssign = function (index, value) { _this.intArray[index * 4] = value[0]; _this.intArray[index * 4 + 1] = value[1]; _this.intArray[index * 4 + 2] = value[2]; _this.intArray[index * 4 + 3] = value[3]; }; } if (typeName == 'int3') { this.vectorSize = 3; this.fastIndex = function (index) { return __.intifyVector((0, std_math_1.int3)(_this.intArray[index * 3], _this.intArray[index * 3 + 1], _this.intArray[index * 3 + 2])); }; this.fastIndexAssign = function (index, value) { _this.intArray[index * 3] = value[0]; _this.intArray[index * 3 + 1] = value[1]; _this.intArray[index * 3 + 2] = value[2]; }; } if (typeName == 'int2') { this.vectorSize = 2; this.fastIndex = function (index) { return __.intifyVector((0, std_math_1.int2)(_this.intArray[index * 2], _this.intArray[index * 2 + 1])); }; this.fastIndexAssign = function (index, value) { _this.intArray[index * 2] = value[0]; _this.intArray[index * 2 + 1] = value[1]; }; } this.intArray = new Int32Array(size * this.vectorSize); this.arrayBuffer = this.intArray.buffer; } else if (typeName == 'uint4' || typeName == 'uint3' || typeName == 'uint2' || typeName == 'uint') { this.vectorSize = 1; this.fastIndex = function (index) { return _this.uintArray[index]; }; this.fastIndexAssign = function (index, value) { _this.uintArray[index] = value; }; if (typeName == 'uint4') { this.vectorSize = 4; this.fastIndex = function (index) { return (0, std_math_1.uint4)(_this.uintArray[index * 4], _this.uintArray[index * 4 + 1], _this.uintArray[index * 4 + 2], _this.uintArray[index * 4 + 3]); }; this.fastIndexAssign = function (index, value) { _this.uintArray[index * 4] = value[0]; _this.uintArray[index * 4 + 1] = value[1]; _this.uintArray[index * 4 + 2] = value[2]; _this.uintArray[index * 4 + 3] = value[3]; }; } if (typeName == 'uint3') { this.vectorSize = 3; this.fastIndex = function (index) { return (0, std_math_1.uint3)(_this.uintArray[index * 3], _this.uintArray[index * 3 + 1], _this.uintArray[index * 3 + 2]); }; this.fastIndexAssign = function (index, value) { _this.uintArray[index * 3] = value[0]; _this.uintArray[index * 3 + 1] = value[1]; _this.uintArray[index * 3 + 2] = value[2]; }; } if (typeName == 'uint2') { this.vectorSize = 2; this.fastIndex = function (index) { return (0, std_math_1.uint2)(_this.uintArray[index * 2], _this.uintArray[index * 2 + 1]); }; this.fastIndexAssign = function (index, value) { _this.uintArray[index * 2] = value[0]; _this.uintArray[index * 2 + 1] = value[1]; }; } this.uintArray = new Uint32Array(size * this.vectorSize); this.arrayBuffer = this.uintArray.buffer; } else { this.structured = true; if (typeName.startsWith('atomic<')) { // this.structArray = new Array(size); this.arrayBuffer = new ArrayBuffer(size * 4); this.watchMutation = true; this.vectorSize = 1; this.elementBytes = 4; this.elementCount = size; for (var i = 0; i < size; i++) { // this.structArray[i] = atomic(0) as T; } if (typeName == 'atomic') { this.uintArray = new Uint32Array(this.arrayBuffer); this.fastIndex = function (index) { return (0, std_math_1.atomic)(_this.uintArray[index]); }; this.fastIndexAssign = function (index, value) { _this.uintArray[index] = value.__value; }; } else { this.intArray = new Int32Array(this.arrayBuffer); this.fastIndex = function (index) { return (0, std_math_1.atomic)(_this.intArray[index]); }; this.fastIndexAssign = function (index, value) { _this.intArray[index] = value.__value; }; } } else { var elementSize_1 = this.adapter.getValueSize(structure); var realSize = elementSize_1 * size; this.elementCount = size; this.elementBytes = elementSize_1; this.arrayBuffer = new ArrayBuffer(realSize); this.fastIndex = function (index) { return _this.adapter.readStructuredBuffer(structure, _this.arrayBuffer, index * elementSize_1); }; this.fastIndexAssign = function (index, value) { _this.cpuWriteDirty = true; _this.adapter.writeStructuredBuffer(structure, value, _this.arrayBuffer, index * (elementSize_1 / 4)); }; } } this.__index = function (index) { // await this.download(); if (_this.watchMutation) { var data = _this.fastIndex(index); data.$mutate = function (to) { _this.cpuWriteDirty = true; if (to !== undefined) { if (_this.intArray) { _this.intArray[index] = to; } else { _this.uintArray[index] = to; } } }; return data; } else { return _this.fastIndex(index); } }; this.__index_assign = function (index, value) { // await this.download(); _this.cpuWriteDirty = true; _this.fastIndexAssign(index, value); }; this.__index_assign_op = function (op_fn, index, value) { // await this.download(); _this.cpuWriteDirty = true; _this.fastIndexAssign(index, op_fn(_this.fastIndex(index), value)); }; } buffer_internal.prototype.destroy = function () { this.adapter.destroyBuffer(this); }; buffer_internal.prototype.__index = function (index) { // this.download(); // return this.fastIndex(index); return null; }; buffer_internal.prototype.__index_assign = function (index, value) { // this.download(); // this.cpuWriteDirty = true; // this.fastIndexAssign(index, value); }; buffer_internal.prototype.__index_assign_op = function (op_fn, index, value) { // this.download(); // this.cpuWriteDirty = true; // this.fastIndexAssign(index, op_fn(this.fastIndex(index), value)); }; buffer_internal.prototype.len = function () { return this.elementCount; }; /** * Returns the underlying cpu buffer as a typed array. * * > [!NOTE] * > This is considerably faster than using the raw index [] operator. * * > [!NOTE] * > If the buffer contents are structured (atomic, or a struct), this will return a normal array * * \`\`\`shadeup * let buf = buffer(); * let data = buf.getData(); * * for (let i = 0; i < data.length; i += 4) { * // Do something with data[i] * } * \`\`\` */ buffer_internal.prototype.getData = function () { var _a, _b, _c; if (this.structured) { return this.structArray; } else { return (_c = (_b = (_a = this.floatArray) !== null && _a !== void 0 ? _a : this.intArray) !== null && _b !== void 0 ? _b : this.uintArray) !== null && _c !== void 0 ? _c : new Uint8Array(0); } }; buffer_internal.prototype.write = function (other) { if (!this.adapter) return; this.adapter.copyBufferToBuffer(other, this); }; /** @shadeup=tag(async) @shadeup=noemit_gpu */ buffer_internal.prototype.download = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.adapter) return [2 /*return*/]; if (this.pendingWrites > 0) { (0, context_1.getShadeupLocalContext)().flushAdapter(); } if (!this.cpuReadDirty) return [3 /*break*/, 2]; this.cpuReadDirty = false; return [4 /*yield*/, this.adapter.downloadBuffer(this)]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); }; buffer_internal.prototype.downloadAsync = function () { return this['download'](); }; /** @shadeup=noemit_gpu */ buffer_internal.prototype.upload = function () { if (!this.adapter) return; if (this.cpuWriteDirty) { this.cpuWriteDirty = false; this.adapter.uploadBuffer(this); } }; buffer_internal.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_buffer_ts_317_buffer_internal\\",\\"fields\\":[[\\"__opaque_buffer\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"structArray\\",null],[\\"floatArray\\",null],[\\"intArray\\",null],[\\"uintArray\\",null],[\\"arrayBuffer\\",null],[\\"vectorSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"typeName\\",null],[\\"platformPayload\\",null],[\\"adapter\\",null],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pendingWrites\\",null],[\\"cpuReadDirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"cpuWriteDirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"elementCount\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"elementBytes\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"structured\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastIndex\\",{\\"type\\":\\"unknown\\"}],[\\"fastIndexAssign\\",{\\"type\\":\\"unknown\\"}],[\\"watchMutation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"symbol\\",{\\"type\\":\\"unknown\\"}]]}"); }; return buffer_internal; }()); exports.buffer_internal = buffer_internal; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_buffer_ts_317_buffer_internal\\",\\"fields\\":[[\\"__opaque_buffer\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"structArray\\",null],[\\"floatArray\\",null],[\\"intArray\\",null],[\\"uintArray\\",null],[\\"arrayBuffer\\",null],[\\"vectorSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"typeName\\",null],[\\"platformPayload\\",null],[\\"adapter\\",null],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"pendingWrites\\",null],[\\"cpuReadDirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"cpuWriteDirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"elementCount\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"elementBytes\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"structured\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastIndex\\",{\\"type\\":\\"unknown\\"}],[\\"fastIndexAssign\\",{\\"type\\":\\"unknown\\"}],[\\"watchMutation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"symbol\\",{\\"type\\":\\"unknown\\"}]]}"), buffer_internal) function buffer(e1, typeName, structure) { if (typeof e1 === 'number') { var size = e1; var buf = new buffer_internal(size, typeName, structure); return buf; } else { var data = e1; var buf = new buffer_internal(data.length, typeName, structure); for (var i = 0; i < data.length; i++) { buf.fastIndexAssign(i, data[i]); } return buf; } } exports.buffer = buffer; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/texture.ts": { outputFiles: [ { name: "/_std/texture.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/_std/context"], function (require, exports, context_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.texture3d = exports.texture3d_internal_empty = exports.texture2d = exports.texture2d_internal_empty = void 0;\n var texture2d_internal_empty = /** @class */ (function () {\n function texture2d_internal_empty() {\n this.__opaque_texture2d = true;\n this.size = [0, 0];\n this.paint = null;\n }\n /** @shadeup=glsl(!texture($self$, $0$)) */\n texture2d_internal_empty.prototype.__index = function (index) {\n return null;\n };\n texture2d_internal_empty.prototype.__index_assign = function (index, value) {\n return null;\n };\n texture2d_internal_empty.prototype.getFast = function (index) {\n return null;\n };\n texture2d_internal_empty.prototype.setFast = function (index, value) {\n return null;\n };\n /** @shadeup=tag(async) */\n texture2d_internal_empty.prototype.download = function () { };\n texture2d_internal_empty.prototype.downloadAsync = function () {\n return null;\n };\n /**\n * Returns the underlying cpu buffer as a typed array.\n *\n * Note that this is considerably faster than using the raw index [] operator.\n *\n * ```shadeup\n * let tex = texture2d();\n * let data = tex.getData();\n *\n * for (let i = 0; i < data.length; i += 4) {\n * let r = data[i];\n * let g = data[i + 1];\n * let b = data[i + 2];\n * let a = data[i + 3];\n *\n * // Do something with the pixel\n * }\n * ```\n */\n texture2d_internal_empty.prototype.getData = function () {\n return new Uint32Array(0);\n };\n texture2d_internal_empty.prototype.upload = function () { };\n texture2d_internal_empty.prototype.sample = function (position) { };\n texture2d_internal_empty.prototype.clear = function (color) {\n if (color === void 0) { color = \'auto\'; }\n };\n texture2d_internal_empty.prototype.flush = function () { };\n /** Release the texture */\n texture2d_internal_empty.prototype.destroy = function () { };\n texture2d_internal_empty.prototype._getStructure = function () {\n return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_texture_ts_434_texture2d_internal_empty\\",\\"fields\\":[[\\"__opaque_texture2d\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"size\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"paint\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_paint_ts_225_PaintingContext\\",\\"fields\\":[[\\"markDirtyCallback\\",{\\"type\\":\\"unknown\\"}],[\\"__ctx\\",null],[\\"__gl\\",null],[\\"__offscreen_canvas\\",null],[\\"__program\\",null],[\\"stagedChanges\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPoints\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPointsBuffer\\",null],[\\"__currentColor\\",null],[\\"pointsCounter\\",null],[\\"cacheSize\\",{\\"type\\":\\"array\\",\\"staticSize\\":2}]]}],[\\"draw\\",{\\"type\\":\\"unknown\\"}],[\\"drawIndexed\\",{\\"type\\":\\"unknown\\"}],[\\"drawAdvanced\\",{\\"type\\":\\"unknown\\"}],[\\"drawInstanced\\",{\\"type\\":\\"unknown\\"}]]}");\n };\n return texture2d_internal_empty;\n }());\n exports.texture2d_internal_empty = texture2d_internal_empty;\n __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_texture_ts_434_texture2d_internal_empty\\",\\"fields\\":[[\\"__opaque_texture2d\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"size\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"paint\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_paint_ts_225_PaintingContext\\",\\"fields\\":[[\\"markDirtyCallback\\",{\\"type\\":\\"unknown\\"}],[\\"__ctx\\",null],[\\"__gl\\",null],[\\"__offscreen_canvas\\",null],[\\"__program\\",null],[\\"stagedChanges\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"dirty\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPoints\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"fastPointsBuffer\\",null],[\\"__currentColor\\",null],[\\"pointsCounter\\",null],[\\"cacheSize\\",{\\"type\\":\\"array\\",\\"staticSize\\":2}]]}],[\\"draw\\",{\\"type\\":\\"unknown\\"}],[\\"drawIndexed\\",{\\"type\\":\\"unknown\\"}],[\\"drawAdvanced\\",{\\"type\\":\\"unknown\\"}],[\\"drawInstanced\\",{\\"type\\":\\"unknown\\"}]]}"), texture2d_internal_empty)\n function texture2d(size, format, type) {\n return (0, context_1.getShadeupLocalContext)().shadeupMakeTextureInternal(size, format, type);\n }\n exports.texture2d = texture2d;\n var texture3d_internal_empty = /** @class */ (function () {\n function texture3d_internal_empty() {\n this.__opaque_texture3d = true;\n this.size = [0, 0, 0];\n }\n /** @shadeup=glsl(!texture($self$, $0$)) */\n texture3d_internal_empty.prototype.__index = function (index) {\n return null;\n };\n texture3d_internal_empty.prototype.__index_assign = function (index, value) { };\n texture3d_internal_empty.prototype.sample = function (position) { };\n texture3d_internal_empty.prototype._getStructure = function () {\n return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_texture_ts_2584_texture3d_internal_empty\\",\\"fields\\":[[\\"__opaque_texture3d\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"size\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}]]}");\n };\n return texture3d_internal_empty;\n }());\n exports.texture3d_internal_empty = texture3d_internal_empty;\n __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_texture_ts_2584_texture3d_internal_empty\\",\\"fields\\":[[\\"__opaque_texture3d\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"bool\\"}],[\\"size\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}]]}"), texture3d_internal_empty)\n function texture3d(size, type) {\n return (0, context_1.getShadeupLocalContext)().shadeupMakeTextureInternal(size, type);\n }\n exports.texture3d = texture3d;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/drawIndexed.ts": { outputFiles: [ { name: "/_std/drawIndexed.js", writeByteOrderMark: false, text: `define(["require", "exports", "/_std/context", "/_std/buffer", "/std_math"], function (require, exports, context_1, buffer_1, std_math_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.computeIndirect = exports.drawAttributes = exports.drawCount = exports.drawAlt2 = exports.drawFullscreen = exports.draw = exports.drawAdvanced = exports.makeShader = exports.ShaderOutput = exports.ShaderInput = exports.shader_start_shd_ = exports.drawIndirect = exports.drawIndexedIndirect = exports.drawInstancedIndexed = exports.drawInstanced = exports.drawIndexed = void 0; function drawIndexed(indexBuffer, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_indexed(indexBuffer, vertexShader, pixelShader); } exports.drawIndexed = drawIndexed; function drawInstanced(mesh, instanceCount, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_instanced(mesh, instanceCount, vertexShader, pixelShader); } exports.drawInstanced = drawInstanced; function drawInstancedIndexed(indexBuffer, instanceCount, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_instanced_indexed(indexBuffer, instanceCount, vertexShader, pixelShader); } exports.drawInstancedIndexed = drawInstancedIndexed; function drawIndexedIndirect(indirectBuffer, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_indexed_indirect(indirectBuffer, vertexShader, pixelShader); } exports.drawIndexedIndirect = drawIndexedIndirect; function drawIndirect(mesh, indirectBuffer, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_indirect(mesh, indirectBuffer, vertexShader, pixelShader); } exports.drawIndirect = drawIndirect; function shader_start_shd_(s, groupSize) { return s; } exports.shader_start_shd_ = shader_start_shd_; /**@shadeup=struct*/ var ShaderInput = /** @class */ (function () { function ShaderInput() { /** Interpolated world position (available in fragment, and vertex) */ this.position = (0, std_math_1.float3)(0, 0, 0); /** Interpolated normal (fragment), Source mesh normal (vertex) */ this.normal = (0, std_math_1.float3)(0, 0, 0); /** Interpolated tangent (fragment), Source mesh tangent (vertex) */ this.tangent = (0, std_math_1.float3)(0, 0, 0); /** Interpolated bitangent (fragment), Source mesh bitangent (vertex) */ this.bitangent = (0, std_math_1.float3)(0, 0, 0); /** Vertex shader output position */ this.clipPosition = (0, std_math_1.float4)(0, 0, 0, 0); this.realPosition = (0, std_math_1.float4)(0, 0, 0, 0); /** UV channel 0 input (available in fragment, and vertex) */ this.uv = (0, std_math_1.float2)(0, 0); /** Screen position in pixels (available in fragment, and vertex) */ this.screen = (0, std_math_1.float2)(0, 0); /** Interpolated vertex color (available in fragment, and vertex) */ this.color = (0, std_math_1.float4)(0, 0, 0, 0); /** Group ID (available in compute) */ this.groupId = __.intifyVector((0, std_math_1.int3)(0, 0, 0)); /** Group size (available in compute) */ this.groupSize = __.intifyVector((0, std_math_1.int3)(0, 0, 0)); /** Global id (groupId * groupSize + localId) (available in compute) */ this.globalId = __.intifyVector((0, std_math_1.int3)(0, 0, 0)); /** Local id (available in compute) */ this.localId = __.intifyVector((0, std_math_1.int3)(0, 0, 0)); /** Instance index (available in fragment, and vertex) */ this.instanceIndex = 0; /** Vertex index (available in vertex) */ this.vertexIndex = 0; } /** @shadeup=noemit_gpu */ ShaderInput.prototype.attr = function (index, interpolation) { return null; }; ShaderInput.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"ShaderInput\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"tangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"bitangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"clipPosition\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"realPosition\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"groupId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"groupSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"globalId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"localId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"instanceIndex\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"vertexIndex\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}]]}"); }; return ShaderInput; }()); exports.ShaderInput = ShaderInput; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"ShaderInput\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"tangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"bitangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"clipPosition\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"realPosition\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"screen\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"groupId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"groupSize\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"globalId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"localId\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int3\\"}],[\\"instanceIndex\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"vertexIndex\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}]]}"), ShaderInput) /**@shadeup=struct*/ var ShaderOutput = /** @class */ (function () { function ShaderOutput() { /** Vertex output position */ this.position = (0, std_math_1.float4)(0, 0, 0, 0); /** Vertex output normal */ this.normal = (0, std_math_1.float3)(0, 0, 0); /** Vertex output tangent */ this.tangent = (0, std_math_1.float3)(0, 0, 0); /** Vertex output bitangent */ this.bitangent = (0, std_math_1.float3)(0, 0, 0); /** UV channel 0 output */ this.uv = (0, std_math_1.float2)(0, 0); /** Pixel color output */ this.color = (0, std_math_1.float4)(0, 0, 0, 0); } /** @shadeup=noemit_gpu */ ShaderOutput.prototype.attr = function (index, value, interpolation) { }; ShaderOutput.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"ShaderOutput\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"tangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"bitangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}]]}"); }; return ShaderOutput; }()); exports.ShaderOutput = ShaderOutput; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"ShaderOutput\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"tangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"bitangent\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"uv\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}]]}"), ShaderOutput) /** @shadeup=shader */ function makeShader(key, fn) { return fn; } exports.makeShader = makeShader; function drawAdvanced(descriptor) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_advanced(descriptor); } exports.drawAdvanced = drawAdvanced; function draw(first, second, third) { if ('vertices' in first && second && third) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_geometry(first, second, third); } else if (first && !second && !third) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw(first); } } exports.draw = draw; function drawFullscreen(first, second, third) { if ('vertices' in first && second && third) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_geometry(first, second, third); } else if (first && !second && !third) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw(first); } } exports.drawFullscreen = drawFullscreen; function drawAlt2(fullScreenPixelShader) { } exports.drawAlt2 = drawAlt2; function drawCount(triCount, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader); } exports.drawCount = drawCount; function drawAttributes(indexBuffer, buffers, vertexShader, pixelShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_attributes(indexBuffer, buffer_1.buffer, vertexShader, pixelShader); } exports.drawAttributes = drawAttributes; function computeIndirect(indirectBuffer, indirectOffset, computeShader) { (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_compute_indirect(indirectBuffer, indirectOffset, computeShader); } exports.computeIndirect = computeIndirect; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/drawAttributes.ts": { outputFiles: [ { name: "/_std/drawAttributes.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/_std/context", "/_std/buffer"], function (require, exports, context_1, buffer_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.drawAttributes = void 0;\n function drawAttributes(indexBuffer, buffers, vertexShader, pixelShader) {\n (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_attributes(indexBuffer, buffer_1.buffer, vertexShader, pixelShader);\n }\n exports.drawAttributes = drawAttributes;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/drawCount.ts": { outputFiles: [ { name: "/_std/drawCount.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/_std/context"], function (require, exports, context_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n exports.drawCount = void 0;\n function drawCount(triCount, vertexShader, pixelShader) {\n (0, context_1.getShadeupLocalContext)().__shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader);\n }\n exports.drawCount = drawCount;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/physics.ts": { outputFiles: [ { name: "/_std/physics.js", writeByteOrderMark: false, text: `define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.physics = exports.PhysicsEngine3d = exports.PhysicsEngine2d = exports.PhysicsRigidBody2d = exports.PhysicsRayCastResult2d = exports.PhysicsCollider2d = void 0; var PhysicsCollider2d = /** @class */ (function () { function PhysicsCollider2d(rapier, world, collider) { this.rapier = rapier; this.world = world; this.collider = collider; } PhysicsCollider2d.prototype.setTranslation = function (position) { this.collider.setTranslation(toVec2(position)); }; PhysicsCollider2d.prototype.setRotation = function (rotation) { this.collider.setRotation(rotation); }; PhysicsCollider2d.prototype.setSensor = function (isSensor) { this.collider.setSensor(isSensor); }; PhysicsCollider2d.prototype.setCollisionGroups = function (groups) { this.collider.setCollisionGroups(groups); }; PhysicsCollider2d.prototype.setCollidesWith = function (groups) { this.collider.setActiveCollisionTypes(groups); }; PhysicsCollider2d.prototype.setFriction = function (friction) { this.collider.setFriction(friction); }; PhysicsCollider2d.prototype.setRestitution = function (restitution) { this.collider.setRestitution(restitution); }; PhysicsCollider2d.prototype.setDensity = function (density) { this.collider.setDensity(density); }; PhysicsCollider2d.prototype.setMass = function (mass) { this.collider.setMass(mass); }; PhysicsCollider2d.prototype.setRadius = function (radius) { this.collider.setRadius(radius); }; PhysicsCollider2d.prototype.setHalfExtents = function (halfExtents) { this.collider.setHalfExtents(toVec2(halfExtents)); }; PhysicsCollider2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_232_PhysicsCollider2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null],[\\"collider\\",null]]}"); }; return PhysicsCollider2d; }()); exports.PhysicsCollider2d = PhysicsCollider2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_232_PhysicsCollider2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null],[\\"collider\\",null]]}"), PhysicsCollider2d) function toVec2(v) { return { x: v[0], y: v[1] }; } function toVec3(v) { return { x: v[0], y: v[1], z: v[2] }; } var PhysicsRayCastResult2d = /** @class */ (function () { function PhysicsRayCastResult2d(rapier, result) { this.rapier = rapier; this.result = result; } PhysicsRayCastResult2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_1662_PhysicsRayCastResult2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"result\\",null]]}"); }; return PhysicsRayCastResult2d; }()); exports.PhysicsRayCastResult2d = PhysicsRayCastResult2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_1662_PhysicsRayCastResult2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"result\\",null]]}"), PhysicsRayCastResult2d) var PhysicsRigidBody2d = /** @class */ (function () { function PhysicsRigidBody2d(rapier, world, body) { this.rapier = rapier; this.world = world; this.body = body; } PhysicsRigidBody2d.prototype.addBallCollider = function (radius) { var colDesc = this.rapier.ColliderDesc.ball(radius); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addBoxCollider = function (halfExtents) { var colDesc = this.rapier.ColliderDesc.cuboid(halfExtents[0], halfExtents[1]); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addCapsuleCollider = function (radius, halfHeight) { var colDesc = this.rapier.ColliderDesc.capsule(radius, halfHeight); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addTriangleCollider = function (a, b, c) { var colDesc = this.rapier.ColliderDesc.triangle(toVec2(a), toVec2(b), toVec2(c)); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addConvexCollider = function (points) { var floatarr = new Float32Array(points.length * 2); for (var i = 0; i < points.length; i++) { floatarr[i * 2 + 0] = points[i][0]; floatarr[i * 2 + 1] = points[i][1]; } var colDesc = this.rapier.ColliderDesc.convexHull(floatarr); if (!colDesc) throw new Error('Failed to create convex hull collider'); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.addHeightfieldCollider = function (heights, scale) { var arr = new Float32Array(heights.length); for (var i = 0; i < heights.length; i++) { arr[i] = heights[i]; } var colDesc = this.rapier.ColliderDesc.heightfield(arr, toVec2(scale)); var col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); }; PhysicsRigidBody2d.prototype.setTranslation = function (position) { this.body.setTranslation(toVec2(position), true); }; PhysicsRigidBody2d.prototype.setRotation = function (rotation) { this.body.setRotation(rotation, true); }; PhysicsRigidBody2d.prototype.setVelocity = function (velocity) { this.body.setLinvel(toVec2(velocity), true); }; PhysicsRigidBody2d.prototype.setAngularVelocity = function (velocity) { this.body.setAngvel(velocity, true); }; PhysicsRigidBody2d.prototype.addForce = function (force) { this.body.addForce(toVec2(force), true); }; PhysicsRigidBody2d.prototype.addForceAtPoint = function (force, point) { this.body.addForceAtPoint(toVec2(force), toVec2(point), true); }; PhysicsRigidBody2d.prototype.addTorque = function (torque) { this.body.addTorque(torque, true); }; PhysicsRigidBody2d.prototype.setAdditionalMass = function (mass) { this.body.setAdditionalMass(mass, true); }; PhysicsRigidBody2d.prototype.setEnabled = function (enabled) { this.body.setEnabled(enabled); }; PhysicsRigidBody2d.prototype.sleep = function () { this.body.sleep(); }; PhysicsRigidBody2d.prototype.wakeUp = function () { this.body.wakeUp(); }; PhysicsRigidBody2d.prototype.setGravityScale = function (scale) { this.body.setGravityScale(scale, true); }; PhysicsRigidBody2d.prototype.setLinearDamping = function (damping) { this.body.setLinearDamping(damping); }; PhysicsRigidBody2d.prototype.setAngularDamping = function (damping) { this.body.setAngularDamping(damping); }; PhysicsRigidBody2d.prototype.isSleeping = function () { return this.body.isSleeping(); }; PhysicsRigidBody2d.prototype.mass = function () { return this.body.mass(); }; PhysicsRigidBody2d.prototype.translation = function () { var t = this.body.translation(); return [t.x, t.y]; }; PhysicsRigidBody2d.prototype.rotation = function () { return this.body.rotation(); }; PhysicsRigidBody2d.prototype.velocity = function () { var t = this.body.linvel(); return [t.x, t.y]; }; PhysicsRigidBody2d.prototype.angularVelocity = function () { return this.body.angvel(); }; PhysicsRigidBody2d.prototype.isMoving = function () { return this.body.isMoving(); }; PhysicsRigidBody2d.prototype.collider = function (index) { var collider = this.body.collider(index); if (!collider) throw new Error('Failed to get collider'); return new PhysicsCollider2d(this.rapier, this.world, collider); }; PhysicsRigidBody2d.prototype.applyImpulse = function (impulse) { this.body.applyImpulse(toVec2(impulse), true); }; PhysicsRigidBody2d.prototype.applyTorqueImpulse = function (impulse) { this.body.applyTorqueImpulse(impulse, true); }; PhysicsRigidBody2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_1904_PhysicsRigidBody2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null],[\\"body\\",null]]}"); }; return PhysicsRigidBody2d; }()); exports.PhysicsRigidBody2d = PhysicsRigidBody2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_1904_PhysicsRigidBody2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null],[\\"body\\",null]]}"), PhysicsRigidBody2d) var PhysicsEngine2d = /** @class */ (function () { function PhysicsEngine2d(rapier) { this.rapier = rapier; this.world = new rapier.World(new rapier.Vector2(0.0, -9.81)); } PhysicsEngine2d.prototype.step = function () { this.world.step(); }; PhysicsEngine2d.prototype.createRigidBody = function (position, rotation, mode) { var rbDesc = mode == 'dynamic' ? this.rapier.RigidBodyDesc.dynamic() : mode == 'fixed' ? this.rapier.RigidBodyDesc.fixed() : this.rapier.RigidBodyDesc.dynamic(); rbDesc.setTranslation(position[0], position[1]); rbDesc.setRotation(rotation); var rb = this.world.createRigidBody(rbDesc); return new PhysicsRigidBody2d(this.rapier, this.world, rb); }; PhysicsEngine2d.prototype.bodies = function () { var bodies = this.world.bodies; var result = []; for (var i = 0; i < bodies.len(); i++) { result.push(new PhysicsRigidBody2d(this.rapier, this.world, bodies.get(i))); } return result; }; PhysicsEngine2d.prototype.castRay = function (start, end, maxi) { var result = this.world.castRay(new this.rapier.Ray(toVec2(start), toVec2(end)), maxi, true); if (!result) return null; return new PhysicsRigidBody2d(this.rapier, this.world, result.collider.parent()); }; PhysicsEngine2d.prototype.setGravity = function (gravity) { this.world.gravity = toVec2(gravity); }; PhysicsEngine2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_6278_PhysicsEngine2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null]]}"); }; return PhysicsEngine2d; }()); exports.PhysicsEngine2d = PhysicsEngine2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_6278_PhysicsEngine2d\\",\\"fields\\":[[\\"rapier\\",null],[\\"world\\",null]]}"), PhysicsEngine2d) var PhysicsEngine3d = /** @class */ (function () { function PhysicsEngine3d() { } PhysicsEngine3d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_7687_PhysicsEngine3d\\",\\"fields\\":[]}"); }; return PhysicsEngine3d; }()); exports.PhysicsEngine3d = PhysicsEngine3d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_physics_ts_7687_PhysicsEngine3d\\",\\"fields\\":[]}"), PhysicsEngine3d) var physics; (function (physics) { function engine2d() { return new PhysicsEngine2d(window.RAPIER_2D); } physics.engine2d = engine2d; })(physics = exports.physics || (exports.physics = {})); }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/context.ts": { outputFiles: [ { name: "/_std/context.js", writeByteOrderMark: false, text: `define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getShadeupLocalContext = void 0; var getShadeupLocalContext = function () { if (typeof localEngineContext !== 'undefined') { return localEngineContext; } else { return window; } }; exports.getShadeupLocalContext = getShadeupLocalContext; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/mesh.ts": { outputFiles: [ { name: "/_std/mesh.js", writeByteOrderMark: false, text: `var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; define(["require", "exports", "/std_math", "/std_math", "/std___std_all", "/_std/common"], function (require, exports, __, std_math_1, std___std_all_1, common_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Model = exports.ModelPart = exports.Material = exports.mesh = exports.Mesh = void 0; __ = __importStar(__); var globalVarGet = std___std_all_1.globalVarGet; var Mesh = /** @class */ (function () { function Mesh(data) { var _a, _b, _c, _d, _e, _f, _g, _h; this.vertices = ((_a = data.vertices) !== null && _a !== void 0 ? _a : []); this.triangles = ((_b = data.triangles) !== null && _b !== void 0 ? _b : []); this.normals = ((_c = data.normals) !== null && _c !== void 0 ? _c : []); this.tangents = ((_d = data.tangents) !== null && _d !== void 0 ? _d : []); this.bitangents = ((_e = data.bitangents) !== null && _e !== void 0 ? _e : []); this.uvs = ((_f = data.uvs) !== null && _f !== void 0 ? _f : []); this.colors = ((_g = data.colors) !== null && _g !== void 0 ? _g : []); this.symbol = ((_h = data.symbol) !== null && _h !== void 0 ? _h : null); } Mesh.prototype.rect = function (size) { var shader_self_temp = this; var index = (this.vertices.len() | 0); this.vertices.push(__.makeVector((__.FM.negate_1(size[0])) / (2 | 0), (__.FM.negate_1(size[1])) / (2 | 0), (0 | 0))); this.vertices.push(__.makeVector(size[0] / (2 | 0), (__.FM.negate_1(size[1])) / (2 | 0), (0 | 0))); this.vertices.push(__.makeVector(size[0] / (2 | 0), size[1] / (2 | 0), (0 | 0))); this.vertices.push(__.makeVector((__.FM.negate_1(size[0])) / (2 | 0), size[1] / (2 | 0), (0 | 0))); this.triangles.push(index + (2 | 0)); this.triangles.push(index + (1 | 0)); this.triangles.push(index + (0 | 0)); this.triangles.push(index + (0 | 0)); this.triangles.push(index + (3 | 0)); this.triangles.push(index + (2 | 0)); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((1 | 0), (1 | 0)))); }; Mesh.prototype.quad = function (position, direction, right, size) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9; var shader_self_temp = this; var up = (0, std_math_1.normalize)((0, std_math_1.cross)(right, direction)); var halfSize = (_a = size, _b = 2.0, [_a[0] / _b, _a[1] / _b]); var index = (this.vertices.len() | 0); this.vertices.push((_c = (_e = position, _f = (_g = right, _h = (__.FM.negate_1(halfSize[0])), [_g[0] * _h, _g[1] * _h, _g[2] * _h]), [_e[0] + _f[0], _e[1] + _f[1], _e[2] + _f[2]]), _d = (_j = up, _k = halfSize[1], [_j[0] * _k, _j[1] * _k, _j[2] * _k]), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]])); this.vertices.push((_l = (_o = position, _p = (_q = right, _r = halfSize[0], [_q[0] * _r, _q[1] * _r, _q[2] * _r]), [_o[0] + _p[0], _o[1] + _p[1], _o[2] + _p[2]]), _m = (_s = up, _t = halfSize[1], [_s[0] * _t, _s[1] * _t, _s[2] * _t]), [_l[0] + _m[0], _l[1] + _m[1], _l[2] + _m[2]])); this.vertices.push((_u = (_w = position, _x = (_y = right, _z = halfSize[0], [_y[0] * _z, _y[1] * _z, _y[2] * _z]), [_w[0] + _x[0], _w[1] + _x[1], _w[2] + _x[2]]), _v = (_0 = up, _1 = (__.FM.negate_1(halfSize[1])), [_0[0] * _1, _0[1] * _1, _0[2] * _1]), [_u[0] + _v[0], _u[1] + _v[1], _u[2] + _v[2]])); this.vertices.push((_2 = (_4 = position, _5 = (_6 = right, _7 = (__.FM.negate_1(halfSize[0])), [_6[0] * _7, _6[1] * _7, _6[2] * _7]), [_4[0] + _5[0], _4[1] + _5[1], _4[2] + _5[2]]), _3 = (_8 = up, _9 = (__.FM.negate_1(halfSize[1])), [_8[0] * _9, _8[1] * _9, _8[2] * _9]), [_2[0] + _3[0], _2[1] + _3[1], _2[2] + _3[2]])); this.triangles.push(index + (0 | 0)); this.triangles.push(index + (1 | 0)); this.triangles.push(index + (2 | 0)); this.triangles.push(index + (2 | 0)); this.triangles.push(index + (3 | 0)); this.triangles.push(index + (0 | 0)); this.normals.push(direction); this.normals.push(direction); this.normals.push(direction); this.normals.push(direction); this.tangents.push(right); this.tangents.push(right); this.tangents.push(right); this.tangents.push(right); this.bitangents.push(up); this.bitangents.push(up); this.bitangents.push(up); this.bitangents.push(up); this.uvs.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0)))); this.uvs.push(__.intifyVector(__.makeVector((1 | 0), (1 | 0)))); }; Mesh.prototype.box = function (size) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; var shader_self_temp = this; var halfSize = (_a = size, _b = 2.0, [_a[0] / _b, _a[1] / _b, _a[2] / _b]); var UP = __.makeVector((0 | 0), 1.0, (0 | 0)); var DOWN = __.makeVector((0 | 0), (__.FM.negate_1(1.0)), (0 | 0)); var LEFT = __.makeVector((__.FM.negate_1(1.0)), (0 | 0), (0 | 0)); var RIGHT = __.makeVector(1.0, (0 | 0), (0 | 0)); var FORWARD = __.makeVector((0 | 0), (0 | 0), 1.0); var BACK = __.makeVector((0 | 0), (0 | 0), (__.FM.negate_1(1.0))); // Up this.quad((_c = UP, _d = halfSize[1], [_c[0] * _d, _c[1] * _d, _c[2] * _d]), UP, LEFT, __.makeVector(size[0], size[2])); // Down this.quad((_e = DOWN, _f = halfSize[1], [_e[0] * _f, _e[1] * _f, _e[2] * _f]), DOWN, RIGHT, __.makeVector(size[0], size[2])); // Left this.quad((_g = LEFT, _h = halfSize[0], [_g[0] * _h, _g[1] * _h, _g[2] * _h]), LEFT, BACK, __.makeVector(size[2], size[1])); // Right this.quad((_j = RIGHT, _k = halfSize[0], [_j[0] * _k, _j[1] * _k, _j[2] * _k]), RIGHT, FORWARD, __.makeVector(size[2], size[1])); // Forward this.quad((_l = FORWARD, _m = halfSize[2], [_l[0] * _m, _l[1] * _m, _l[2] * _m]), FORWARD, LEFT, __.makeVector(size[0], size[1])); // Back this.quad((_o = BACK, _p = halfSize[2], [_o[0] * _p, _o[1] * _p, _o[2] * _p]), BACK, RIGHT, __.makeVector(size[0], size[1])); }; Mesh.prototype.rectAt = function (minPos, maxPos) { var _a, _b; var shader_self_temp = this; this.rect((_a = maxPos, _b = minPos, [_a[0] - _b[0], _a[1] - _b[1]])); this.translate(__.makeVector(minPos, (0 | 0))); }; Mesh.prototype.circle = function (pos, radius, vertices) { if (vertices === void 0) { vertices = (32 | 0); } }; Mesh.prototype.uvSphere = function (pos, radius, vertices, rings) { if (vertices === void 0) { vertices = (32 | 0); } if (rings === void 0) { rings = (16 | 0); } var shader_self_temp = this; var index = (this.vertices.len() | 0); var verticesPerRing = vertices + (1 | 0); for (var i = (0 | 0); i <= rings; i++) { var y = i / rings; var angleY = y * common_1.PI; var posY = Math.cos(angleY); var radiusY = Math.sin(angleY); for (var j = (0 | 0); j <= vertices; j++) { var x = j / vertices; var angleX = x * common_1.PI * (2 | 0); var posX = Math.cos(angleX); var posZ = Math.sin(angleX); this.vertices.push(__.makeVector(posX * radiusY * radius, posY * radius, posZ * radiusY * radius)); this.normals.push((0, std_math_1.normalize)(__.makeVector(posX * radiusY, posY, posZ * radiusY))); var tangent = (0, std_math_1.normalize)(__.makeVector(posZ, (0 | 0), (__.FM.negate_1(posX)))); var bitangent = (0, std_math_1.normalize)((0, std_math_1.cross)(this.normals[(this.normals.len() | 0) - (1 | 0)], tangent)); this.tangents.push(tangent); this.bitangents.push(bitangent); this.uvs.push(__.makeVector(x, y)); } } for (var i = (0 | 0); i < rings; i++) { for (var j = (0 | 0); j < vertices; j++) { var i0 = i * verticesPerRing + j; var i1 = i0 + (1 | 0); var i2 = i0 + verticesPerRing; var i3 = i2 + (1 | 0); this.triangles.push(index + i0); this.triangles.push(index + i1); this.triangles.push(index + i2); this.triangles.push(index + i2); this.triangles.push(index + i1); this.triangles.push(index + i3); } } this.translate(pos); }; Mesh.prototype.icoSphere = function (pos, radius, subdivisions) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v; if (subdivisions === void 0) { subdivisions = (1 | 0); } var shader_self_temp = this; var index = (this.vertices.len() | 0); var t = (1.0 + Math.sqrt(5.0)) / 2.0; var vertices = [__.makeVector((__.FM.negate_1((1 | 0))), t, (0 | 0)), __.makeVector((1 | 0), t, (0 | 0)), __.makeVector((__.FM.negate_1((1 | 0))), (__.FM.negate_1(t)), (0 | 0)), __.makeVector((1 | 0), (__.FM.negate_1(t)), (0 | 0)), __.makeVector((0 | 0), (__.FM.negate_1((1 | 0))), t), __.makeVector((0 | 0), (1 | 0), t), __.makeVector((0 | 0), (__.FM.negate_1((1 | 0))), (__.FM.negate_1(t))), __.makeVector((0 | 0), (1 | 0), (__.FM.negate_1(t))), __.makeVector(t, (0 | 0), (__.FM.negate_1((1 | 0)))), __.makeVector(t, (0 | 0), (1 | 0)), __.makeVector((__.FM.negate_1(t)), (0 | 0), (__.FM.negate_1((1 | 0)))), __.makeVector((__.FM.negate_1(t)), (0 | 0), (1 | 0))]; var triangles = [__.intifyVector(__.makeVector((0 | 0), (11 | 0), (5 | 0))), __.intifyVector(__.makeVector((0 | 0), (5 | 0), (1 | 0))), __.intifyVector(__.makeVector((0 | 0), (1 | 0), (7 | 0))), __.intifyVector(__.makeVector((0 | 0), (7 | 0), (10 | 0))), __.intifyVector(__.makeVector((0 | 0), (10 | 0), (11 | 0))), __.intifyVector(__.makeVector((1 | 0), (5 | 0), (9 | 0))), __.intifyVector(__.makeVector((5 | 0), (11 | 0), (4 | 0))), __.intifyVector(__.makeVector((11 | 0), (10 | 0), (2 | 0))), __.intifyVector(__.makeVector((10 | 0), (7 | 0), (6 | 0))), __.intifyVector(__.makeVector((7 | 0), (1 | 0), (8 | 0))), __.intifyVector(__.makeVector((3 | 0), (9 | 0), (4 | 0))), __.intifyVector(__.makeVector((3 | 0), (4 | 0), (2 | 0))), __.intifyVector(__.makeVector((3 | 0), (2 | 0), (6 | 0))), __.intifyVector(__.makeVector((3 | 0), (6 | 0), (8 | 0))), __.intifyVector(__.makeVector((3 | 0), (8 | 0), (9 | 0))), __.intifyVector(__.makeVector((4 | 0), (9 | 0), (5 | 0))), __.intifyVector(__.makeVector((2 | 0), (4 | 0), (11 | 0))), __.intifyVector(__.makeVector((6 | 0), (2 | 0), (10 | 0))), __.intifyVector(__.makeVector((8 | 0), (6 | 0), (7 | 0))), __.intifyVector(__.makeVector((9 | 0), (8 | 0), (1 | 0)))]; for (var i = (0 | 0); i < (vertices.len() | 0); i++) { this.vertices.push((_a = (0, std_math_1.normalize)(vertices[i]), _b = radius, [_a[0] * _b, _a[1] * _b, _a[2] * _b])); } for (var i = (0 | 0); i < (triangles.len() | 0); i++) { this.triangles.push(index + triangles[i][0]); this.triangles.push(index + triangles[i][1]); this.triangles.push(index + triangles[i][2]); } for (var i = (0 | 0); i < subdivisions; i++) { var newTriangles = []; for (var j = (0 | 0); j < (this.triangles.len() | 0); j = j + (3 | 0)) { var i0 = this.triangles[j + (0 | 0)]; var i1 = this.triangles[j + (1 | 0)]; var i2 = this.triangles[j + (2 | 0)]; var v0 = this.vertices[i0]; var v1 = this.vertices[i1]; var v2 = this.vertices[i2]; var v3 = (0, std_math_1.normalize)((_c = (_e = v0, _f = v1, [_e[0] + _f[0], _e[1] + _f[1], _e[2] + _f[2]]), _d = 2.0, [_c[0] / _d, _c[1] / _d, _c[2] / _d])); var v4 = (0, std_math_1.normalize)((_g = (_j = v1, _k = v2, [_j[0] + _k[0], _j[1] + _k[1], _j[2] + _k[2]]), _h = 2.0, [_g[0] / _h, _g[1] / _h, _g[2] / _h])); var v5 = (0, std_math_1.normalize)((_l = (_o = v2, _p = v0, [_o[0] + _p[0], _o[1] + _p[1], _o[2] + _p[2]]), _m = 2.0, [_l[0] / _m, _l[1] / _m, _l[2] / _m])); var i3 = (this.vertices.len() | 0); var i4 = i3 + (1 | 0); var i5 = i3 + (2 | 0); this.vertices.push((_q = v3, _r = radius, [_q[0] * _r, _q[1] * _r, _q[2] * _r])); this.vertices.push((_s = v4, _t = radius, [_s[0] * _t, _s[1] * _t, _s[2] * _t])); this.vertices.push((_u = v5, _v = radius, [_u[0] * _v, _u[1] * _v, _u[2] * _v])); newTriangles.push(i0, i3, i5); newTriangles.push(i3, i1, i4); newTriangles.push(i3, i4, i5); newTriangles.push(i5, i4, i2); } this.triangles = newTriangles; } for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { var normal = (0, std_math_1.normalize)(this.vertices[i]); var tangent = (0, std_math_1.normalize)(__.makeVector(normal[2], (0 | 0), (__.FM.negate_1(normal[0])))); var bitangent = (0, std_math_1.normalize)((0, std_math_1.cross)(normal, tangent)); this.normals.push(normal); this.tangents.push(tangent); this.bitangents.push(bitangent); } for (var i = (0 | 0); i < (this.triangles.len() | 0); i = i + (3 | 0)) { var i0 = this.triangles[i + (0 | 0)]; var i1 = this.triangles[i + (1 | 0)]; var i2 = this.triangles[i + (2 | 0)]; var v0 = this.vertices[i0]; var v1 = this.vertices[i1]; var v2 = this.vertices[i2]; var uv0 = __.FM.float_2_1_1(__.add((0, std_math_1.atan2)(v0[2], v0[0]) / common_1.PI / 2.0, 0.5), __.add(Math.asin(v0[1]) / common_1.PI, 0.5)); var uv1 = __.FM.float_2_1_1(__.add((0, std_math_1.atan2)(v1[2], v1[0]) / common_1.PI / 2.0, 0.5), __.add(Math.asin(v1[1]) / common_1.PI, 0.5)); var uv2 = __.FM.float_2_1_1(__.add((0, std_math_1.atan2)(v2[2], v2[0]) / common_1.PI / 2.0, 0.5), __.add(Math.asin(v2[1]) / common_1.PI, 0.5)); this.uvs.push(uv0); this.uvs.push(uv1); this.uvs.push(uv2); } this.translate(pos); }; Mesh.prototype.cylinder = function (pos, radius, height, vertices) { if (vertices === void 0) { vertices = (32 | 0); } var shader_self_temp = this; this.translate(pos); }; Mesh.prototype.capsule = function (pos, radius, height, vertices) { if (vertices === void 0) { vertices = (32 | 0); } var shader_self_temp = this; this.translate(pos); }; Mesh.prototype.cone = function (pos, radius, height, vertices) { if (vertices === void 0) { vertices = (32 | 0); } var shader_self_temp = this; var index = (this.vertices.len() | 0); this.translate(pos); }; Mesh.prototype.plane = function (pos, size, subdivisions) { var _a, _b; if (subdivisions === void 0) { subdivisions = __.intifyVector(__.makeVector((2 | 0), (2 | 0))); } var shader_self_temp = this; var index = (this.vertices.len() | 0); var halfSize = (_a = size, _b = 2.0, [_a[0] / _b, _a[1] / _b]); for (var i = (0 | 0); i <= subdivisions[0]; i++) { var x = i / __.swizzle(subdivisions, 'x'); var posX = x * size[0] - halfSize[0]; for (var j = (0 | 0); j <= subdivisions[1]; j++) { var y = j / __.swizzle(subdivisions, 'y'); var posY = y * size[1] - halfSize[1]; this.vertices.push(__.makeVector(posX, (0 | 0), posY)); this.normals.push(__.intifyVector(__.makeVector((0 | 0), (1 | 0), (0 | 0)))); this.tangents.push(__.intifyVector(__.makeVector((1 | 0), (0 | 0), (0 | 0)))); this.bitangents.push(__.intifyVector(__.makeVector((0 | 0), (0 | 0), (1 | 0)))); this.uvs.push(__.makeVector(x, y)); } } for (var i = (0 | 0); i < subdivisions[0]; i++) { for (var j = (0 | 0); j < subdivisions[1]; j++) { var i0 = i * (subdivisions[1] + (1 | 0)) + j; var i1 = i0 + (1 | 0); var i2 = i0 + subdivisions[1] + (1 | 0); var i3 = i2 + (1 | 0); this.triangles.push(index + i0); this.triangles.push(index + i1); this.triangles.push(index + i2); this.triangles.push(index + i2); this.triangles.push(index + i1); this.triangles.push(index + i3); } } this.translate(pos); }; Mesh.prototype.translate = function (pos) { var shader_self_temp = this; for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { this.vertices.__index_assign_op(__.add, i, pos); } return this; }; Mesh.prototype.rotate = function (quaternion) { var shader_self_temp = this; for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { this.vertices.__index_assign(i, common_1.quat.rotate(quaternion, this.vertices[i])); } for (var i = (0 | 0); i < (this.normals.len() | 0); i++) { this.normals.__index_assign(i, common_1.quat.rotate(quaternion, this.normals[i])); } return this; }; Mesh.prototype.transform = function (matrix) { var _a, _b; var shader_self_temp = this; for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { this.vertices.__index_assign(i, (_a = (__.mul(__.makeVector(this.vertices[i], (1 | 0)), matrix)), [_a[0], _a[1], _a[2]])); } for (var i = (0 | 0); i < (this.normals.len() | 0); i++) { this.normals.__index_assign(i, (_b = (__.mul(__.makeVector(this.normals[i], (1 | 0)), matrix)), [_b[0], _b[1], _b[2]])); } return this; }; Mesh.prototype.scale = function (scale) { var shader_self_temp = this; for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { this.vertices.__index_assign_op(__.mul, i, scale); } return this; }; Mesh.prototype.bounds = function () { var _a, _b, _c, _d; var shader_self_temp = this; var mn = (_a = 0.0, [_a, _a, _a]); var mx = (_b = 0.0, [_b, _b, _b]); for (var i = (0 | 0); i < (this.vertices.len() | 0); i++) { mn = (0, std_math_1.min)(mn, this.vertices[i]); mx = (0, std_math_1.max)(mx, this.vertices[i]); } return _c = mx, _d = mn, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]; }; Mesh.prototype.center = function () { var _a, _b; var shader_self_temp = this; var bounds = this.bounds(); return _a = bounds, _b = 2.0, [_a[0] / _b, _a[1] / _b, _a[2] / _b]; }; Mesh.new = function () { return new Mesh({ vertices: [], triangles: [], tangents: [], bitangents: [], normals: [], uvs: [], colors: [] }); }; Mesh.prototype.append = function (other) { var shader_self_temp = this; var oldVertices = (this.vertices.len() | 0); var oldTriangles = (this.triangles.len() | 0); this.vertices.append(other.vertices); this.triangles.append(other.triangles); this.normals.append(other.normals); this.tangents.append(other.tangents); this.bitangents.append(other.bitangents); this.uvs.append(other.uvs); this.colors.append(other.colors); for (var i = oldTriangles; i < (this.triangles.len() | 0); i++) { this.triangles.__index_assign_op(__.add, i, oldVertices); } }; Mesh.prototype.getVertices = function () { var shader_self_temp = this; return this.vertices; }; Mesh.prototype.getTriangles = function () { var shader_self_temp = this; return this.triangles; }; Mesh.prototype.getNormals = function () { var shader_self_temp = this; return this.normals; }; Mesh.prototype.getTangents = function () { var shader_self_temp = this; return this.tangents; }; Mesh.prototype.getBitangents = function () { var shader_self_temp = this; return this.bitangents; }; Mesh.prototype.getUVs = function () { var shader_self_temp = this; return this.uvs; }; Mesh.prototype.getColors = function () { var shader_self_temp = this; return this.colors; }; Mesh.prototype.setVertices = function (vertices) { var shader_self_temp = this; this.vertices = vertices; }; Mesh.prototype.setTriangles = function (triangles) { var shader_self_temp = this; this.triangles = triangles; }; Mesh.prototype.setNormals = function (normals) { var shader_self_temp = this; this.normals = normals; }; Mesh.prototype.setTangents = function (tangents) { var shader_self_temp = this; this.tangents = tangents; }; Mesh.prototype.setBitangents = function (bitangents) { var shader_self_temp = this; this.bitangents = bitangents; }; Mesh.prototype.setUVs = function (uvs) { var shader_self_temp = this; this.uvs = uvs; }; Mesh.prototype.setColors = function (colors) { var shader_self_temp = this; this.colors = colors; }; Mesh.prototype.clone = function () { return new Mesh({ vertices: (0, std___std_all_1.__deepClone)(this.vertices), triangles: (0, std___std_all_1.__deepClone)(this.triangles), normals: (0, std___std_all_1.__deepClone)(this.normals), tangents: (0, std___std_all_1.__deepClone)(this.tangents), bitangents: (0, std___std_all_1.__deepClone)(this.bitangents), uvs: (0, std___std_all_1.__deepClone)(this.uvs), colors: (0, std___std_all_1.__deepClone)(this.colors), symbol: (0, std___std_all_1.__deepClone)(this.symbol), }); }; Mesh.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}"); }; return Mesh; }()); exports.Mesh = Mesh; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}"), Mesh) ; /* impl Mesh */ var mesh = /** @class */ (function () { function mesh(data) { } mesh.rect = function (pos, size) { var _a, _b; var g = Mesh.new(); g.rectAt(pos, (_a = pos, _b = size, [_a[0] + _b[0], _a[1] + _b[1]])); return g; }; mesh.box = function (pos, size) { var g = Mesh.new(); g.box(size); g.translate(pos); return g; }; mesh.uvSphere = function (pos, radius, vertices, rings) { if (vertices === void 0) { vertices = (32 | 0); } if (rings === void 0) { rings = (16 | 0); } var g = Mesh.new(); g.uvSphere(pos, radius, vertices, rings); return g; }; mesh.icoSphere = function (pos, radius, subdivisions) { if (subdivisions === void 0) { subdivisions = (1 | 0); } var g = Mesh.new(); g.icoSphere(pos, radius, subdivisions); return g; }; mesh.plane = function (pos, size, subdivisions) { if (subdivisions === void 0) { subdivisions = __.intifyVector(__.makeVector((2 | 0), (2 | 0))); } var g = Mesh.new(); g.plane(pos, size, subdivisions); return g; }; /** * Returns a [-1, 1] position for a given index. */ mesh.triangleFromIndex = function (index) { if (index == (0 | 0)) { return __.FM.float_2_1_1(__.negate((1 | 0)), __.int(1)); } else if (index == (1 | 0)) { return __.FM.float_2_1_1(__.int(1), __.int(1)); } else if (index == (2 | 0)) { return __.FM.float_2_1_1(__.int(0), __.negate((1 | 0))); } else { return __.FM.float_2_1_1(__.int(0), __.int(0)); } }; mesh.circleFromIndex = function (vertexIndex, vertices) { vertexIndex = vertices - vertexIndex; var numSlices = vertices / (3 | 0); var sliceIndex = Math.floor(vertexIndex / vertices * numSlices); var incAngle = common_1.PI * 2.0 / numSlices; var baseAngle = incAngle * sliceIndex; if (vertexIndex % (3 | 0) == (0 | 0)) { return __.FM.float_2_1_1(__.int(0), __.int(0)); } else if (vertexIndex % (3 | 0) == (1 | 0)) { return __.FM.float_2_1_1((0, std_math_1.cos)(baseAngle), (0, std_math_1.sin)(baseAngle)); } else { return __.FM.float_2_1_1((0, std_math_1.cos)(baseAngle + incAngle), (0, std_math_1.sin)(baseAngle + incAngle)); } }; mesh.rectFromIndex = function (index, vertices) { var _a, _b, _c, _d, _e, _f; var x = index % vertices; var y = index / vertices; return _a = (_c = (_e = __.FM.float_2_1_1(x, y), _f = vertices, [_e[0] / _f, _e[1] / _f]), _d = 2.0, [_c[0] * _d, _c[1] * _d]), _b = 1.0, [_a[0] - _b, _a[1] - _b]; }; mesh.empty = function (numVerts) { var _a, _b, _c, _d, _e, _f; if (numVerts === void 0) { numVerts = (0 | 0); } var g = Mesh.new(); if (numVerts > (0 | 0)) { g.setVertices((0, std___std_all_1.array)(numVerts, (_a = (0 | 0), [_a, _a, _a]))); g.setNormals((0, std___std_all_1.array)(numVerts, (_b = (0 | 0), [_b, _b, _b]))); g.setTangents((0, std___std_all_1.array)(numVerts, (_c = (0 | 0), [_c, _c, _c]))); g.setBitangents((0, std___std_all_1.array)(numVerts, (_d = (0 | 0), [_d, _d, _d]))); g.setUVs((0, std___std_all_1.array)(numVerts, (_e = (0 | 0), [_e, _e]))); g.setColors((0, std___std_all_1.array)(numVerts, (_f = (0 | 0), [_f, _f, _f, _f]))); var tris = (0, std___std_all_1.array)(numVerts, (0 | 0)); for (var i = (0 | 0); i < numVerts; i++) { tris.__index_assign(i, i); } g.setTriangles(tris); } return g; }; mesh.join = function (mesh1, mesh2) { var g = Mesh.new(); g.append(mesh1); g.append(mesh2); return g; }; // pub fn cylinder(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.cylinder(pos, radius, height, vertices); // return g; // } // pub fn capsule(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.capsule(pos, radius, height, vertices); // return g; // } // pub fn cone(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.cone(pos, radius, height, vertices); // return g; // } mesh.prototype.clone = function () { return new mesh({}); }; mesh.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_19895_mesh\\",\\"fields\\":[]}"); }; return mesh; }()); exports.mesh = mesh; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_19895_mesh\\",\\"fields\\":[]}"), mesh) ; /* impl mesh */ var Material = /** @class */ (function () { function Material(data) { var _a, _b, _c, _d, _e, _f, _g; this.baseColor = ((_a = data.baseColor) !== null && _a !== void 0 ? _a : __.FM.float_4_1_1_1_1(0.0, 0.0, 0.0, 0.0)); this.color = ((_b = data.color) !== null && _b !== void 0 ? _b : null); this.normal = ((_c = data.normal) !== null && _c !== void 0 ? _c : null); this.normalScale = ((_d = data.normalScale) !== null && _d !== void 0 ? _d : __.FM.float_2_1_1(0.0, 0.0)); this.roughness = ((_e = data.roughness) !== null && _e !== void 0 ? _e : null); this.emissive = ((_f = data.emissive) !== null && _f !== void 0 ? _f : null); this.metallic = ((_g = data.metallic) !== null && _g !== void 0 ? _g : null); } Material.prototype.clone = function () { return new Material({ baseColor: (0, std___std_all_1.__deepClone)(this.baseColor), color: (0, std___std_all_1.__deepClone)(this.color), normal: (0, std___std_all_1.__deepClone)(this.normal), normalScale: (0, std___std_all_1.__deepClone)(this.normalScale), roughness: (0, std___std_all_1.__deepClone)(this.roughness), emissive: (0, std___std_all_1.__deepClone)(this.emissive), metallic: (0, std___std_all_1.__deepClone)(this.metallic), }); }; Material.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}"); }; return Material; }()); exports.Material = Material; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}"), Material) ; var ModelPart = /** @class */ (function () { function ModelPart(data) { var _a, _b, _c; this.mesh = ((_a = data.mesh) !== null && _a !== void 0 ? _a : new Mesh({})); this.material = ((_b = data.material) !== null && _b !== void 0 ? _b : new Material({})); this.transform = ((_c = data.transform) !== null && _c !== void 0 ? _c : __.float4x4(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)); } ModelPart.prototype.clone = function () { return new ModelPart({ mesh: (0, std___std_all_1.__deepClone)(this.mesh), material: (0, std___std_all_1.__deepClone)(this.material), transform: (0, std___std_all_1.__deepClone)(this.transform), }); }; ModelPart.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_24666_ModelPart\\",\\"fields\\":[[\\"mesh\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}],[\\"material\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}],[\\"transform\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4x4\\"}]]}"); }; return ModelPart; }()); exports.ModelPart = ModelPart; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_24666_ModelPart\\",\\"fields\\":[[\\"mesh\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}],[\\"material\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}],[\\"transform\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4x4\\"}]]}"), ModelPart) ; var Model = /** @class */ (function () { function Model(data) { var _a; this.parts = ((_a = data.parts) !== null && _a !== void 0 ? _a : []); } Model.prototype.clone = function () { return new Model({ parts: (0, std___std_all_1.__deepClone)(this.parts), }); }; Model.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_25266_Model\\",\\"fields\\":[[\\"parts\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_24666_ModelPart\\",\\"fields\\":[[\\"mesh\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}],[\\"material\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}],[\\"transform\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4x4\\"}]]},\\"staticSize\\":1}]]}"); }; return Model; }()); exports.Model = Model; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_25266_Model\\",\\"fields\\":[[\\"parts\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_24666_ModelPart\\",\\"fields\\":[[\\"mesh\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_1759_Mesh\\",\\"fields\\":[[\\"vertices\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"triangles\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"},\\"staticSize\\":1}],[\\"normals\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"tangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"bitangents\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"},\\"staticSize\\":1}],[\\"uvs\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"},\\"staticSize\\":1}],[\\"colors\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"},\\"staticSize\\":1}],[\\"symbol\\",null]]}],[\\"material\\",{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_mesh_ts_23437_Material\\",\\"fields\\":[[\\"baseColor\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"color\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normal\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"normalScale\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"roughness\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"emissive\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}],[\\"metallic\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"texture2d\\"}]]}],[\\"transform\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4x4\\"}]]},\\"staticSize\\":1}]]}"), Model) ; window.SHD_Mesh = Mesh; window.SHD_Model = Model; window.SHD_ModelPart = ModelPart; window.SHD_Material = Material; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/textures.ts": { outputFiles: [ { name: "/_std/textures.js", writeByteOrderMark: false, text: 'define(["require", "exports", "/std___std_all"], function (require, exports, std___std_all_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n var globalVarGet = std___std_all_1.globalVarGet;\n});\n' } ], emitSkipped: false, diagnostics: [] }, "/_std/common.ts": { outputFiles: [ { name: "/_std/common.js", writeByteOrderMark: false, text: `var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; define(["require", "exports", "/std_math", "/std_math", "/std___std_all", "/_std/buffer", "/_std/ui", "/_std/texture"], function (require, exports, __, std_math_1, std___std_all_1, buffer_1, ui_1, texture_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.wrap4 = exports.wrap3 = exports.wrap2 = exports.color = exports.remap1 = exports.remap = exports.tan1 = exports.cos1 = exports.sin1 = exports.hexFromColor = exports.hex = exports.cmykFromColor = exports.cmyk = exports.rgbaFromColor = exports.rgbFromColor = exports.rgba = exports.rgb = exports.hsvaFromColor = exports.hsvFromColor = exports.hsva = exports.hsv = exports.hslaFromColor = exports.hslFromColor = exports.hsla = exports.hsl = exports.screenAA = exports.matrix = exports.noise = exports.reverseMortonCode2 = exports.randColor2 = exports.randColor = exports.mortonCode2 = exports.spatial = exports.bezier = exports.Camera = exports.Camera2d = exports.quat = exports.ui = exports.texture3d = exports.texture2d = exports.buffer = exports.PI = exports.pixelToClip = void 0; __ = __importStar(__); var globalVarGet = std___std_all_1.globalVarGet; Object.defineProperty(exports, "buffer", { enumerable: true, get: function () { return buffer_1.buffer; } }); Object.defineProperty(exports, "ui", { enumerable: true, get: function () { return ui_1.ui; } }); Object.defineProperty(exports, "texture2d", { enumerable: true, get: function () { return texture_1.texture2d; } }); Object.defineProperty(exports, "texture3d", { enumerable: true, get: function () { return texture_1.texture3d; } }); function pixelToClip(pixelPosition) { var _a, _b, _c, _d, _e, _f, _g; var zeroToOne = (_a = pixelPosition, _b = env.screenSize, [_a[0] / _b[0], _a[1] / _b[1]]); var zeroToTwo = (_c = zeroToOne, _d = 2.0, [_c[0] * _d, _c[1] * _d]); var clipSpace = (_e = zeroToTwo, _f = (_g = 1.0, [_g, _g]), [_e[0] - _f[0], _e[1] - _f[1]]); return __.makeVector(clipSpace[0], clipSpace[1] * (__.FM.negate_1(1.0))); } exports.pixelToClip = pixelToClip; ; /** * Value of PI to 35 decimal places. */ var PI = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PI", function () { return 3.14159265358979323846264338327950288; }, function () { return PI; }); exports.PI = PI; var quat = /** @class */ (function () { function quat(data) { } /** * Creates a quaternion from an angle and axis. */ quat.fromAngleAxis = function (angle, axis) { return __.FM.float_4_3_1(__.mul(axis, Math.sin(angle * 0.5)), (0, std_math_1.cos)(angle * 0.5)); }; /** * Multiplies two quaternions and returns the result. */ quat.mul = function (a, b) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; return __.FM.float_4_3_1(__.add((_a = (_c = (_e = b, [_e[0], _e[1], _e[2]]), _d = a[3], [_c[0] * _d, _c[1] * _d, _c[2] * _d]), _b = (_f = (_h = a, [_h[0], _h[1], _h[2]]), _g = b[3], [_f[0] * _g, _f[1] * _g, _f[2] * _g]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]), (0, std_math_1.cross)((_j = a, [_j[0], _j[1], _j[2]]), (_k = b, [_k[0], _k[1], _k[2]]))), __.sub(a[3] * b[3], (0, std_math_1.dot)((_l = a, [_l[0], _l[1], _l[2]]), (_m = b, [_m[0], _m[1], _m[2]])))); }; /** * Rotates a vector by a quaternion and returns the rotated vector. */ quat.rotate = function (quaternion, vector) { var _a; var q = quat.mul(quat.mul(quaternion, __.FM.float_4_3_1(vector, __.int(0))), quat.conjugate(quaternion)); return _a = q, [_a[0], _a[1], _a[2]]; }; /** * Returns the conjugate of the input quaternion. * * The conjugate of a quaternion number is a quaternion with the same magnitudes but with the sign of the imaginary parts changed */ quat.conjugate = function (quaternion) { var _a; return __.FM.float_4_3_1(__.negate((_a = quaternion, [_a[0], _a[1], _a[2]])), __.swizzle(quaternion, 'w')); }; /** * Returns the inverse of the input quaternion. */ quat.inverse = function (quaternion) { var _a, _b; return _a = quat.conjugate(quaternion), _b = (0, std_math_1.dot)(quaternion, quaternion), [_a[0] / _b, _a[1] / _b, _a[2] / _b, _a[3] / _b]; }; /** * Generates a quaternion that rotates from one direction to another via the shortest path. */ quat.fromToRotation = function (from, to) { var _a; var q = (_a = 0.0, [_a, _a, _a, _a]); var d = (0, std_math_1.dot)(from, to); if (d < (__.FM.negate_1(0.999999))) { var right = __.FM.float_3_1_1_1(__.int(1), __.int(0), __.int(0)); var up = __.FM.float_3_1_1_1(__.int(0), __.int(1), __.int(0)); var tmp = (0, std_math_1.cross)(right, from); if ((0, std_math_1.length)(tmp) < 0.000001) { tmp = (0, std_math_1.cross)(up, from); } tmp = (0, std_math_1.normalize)(tmp); q = quat.fromAngleAxis(PI, tmp); } else if (d > 0.999999) { q = __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(1)); } else { q = __.FM.float_4_3_1((0, std_math_1.cross)(from, to), __.add((1 | 0), d)); q = (0, std_math_1.normalize)(q); } return q; }; quat.diff = function (a, b) { var _a, _b; return _a = a, _b = quat.inverse(b), [_a[0] * _b[0], _a[1] * _b[1], _a[2] * _b[2], _a[3] * _b[3]]; }; /** * Generates lookAt quaternion. */ quat.lookAt = function (forward, up) { var right = (0, std_math_1.normalize)((0, std_math_1.cross)(forward, up)); up = (0, std_math_1.normalize)((0, std_math_1.cross)(forward, right)); var m00 = right[0]; var m01 = right[1]; var m02 = right[2]; var m10 = up[0]; var m11 = up[1]; var m12 = up[2]; var m20 = forward[0]; var m21 = forward[1]; var m22 = forward[2]; var num8 = (m00 + m11) + m22; var q = __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(1)); if (num8 > 0.0) { var num = Math.sqrt(num8 + 1.0); var w_1 = num * 0.5; num = 0.5 / num; var x_1 = (m12 - m21) * num; var y_1 = (m20 - m02) * num; var z_1 = (m01 - m10) * num; return __.FM.float_4_1_1_1_1(x_1, y_1, z_1, w_1); } if (__.and((m00 >= m11), (m00 >= m22))) { var num7 = Math.sqrt(((1.0 + m00) - m11) - m22); var num4 = 0.5 / num7; var x_2 = 0.5 * num7; var y_2 = (m01 + m10) * num4; var z_2 = (m02 + m20) * num4; var w_2 = (m12 - m21) * num4; return __.FM.float_4_1_1_1_1(x_2, y_2, z_2, w_2); } if (m11 > m22) { var num6 = Math.sqrt(((1.0 + m11) - m00) - m22); var num3 = 0.5 / num6; var x_3 = (m10 + m01) * num3; var y_3 = 0.5 * num6; var z_3 = (m21 + m12) * num3; var w_3 = (m20 - m02) * num3; return __.FM.float_4_1_1_1_1(x_3, y_3, z_3, w_3); } var num5 = Math.sqrt(((1.0 + m22) - m00) - m11); var num2 = 0.5 / num5; var x = (m20 + m02) * num2; var y = (m21 + m12) * num2; var z = 0.5 * num5; var w = (m01 - m10) * num2; return __.FM.float_4_1_1_1_1(x, y, z, w); }; /** * Smooth interpolation between two quaternions. */ quat.slerp = function (a, b, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; if ((0, std_math_1.length)(a) == 0.0) { if ((0, std_math_1.length)(b) == 0.0) { return __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(1)); } return b; } else if ((0, std_math_1.length)(b) == 0.0) { return a; } var cosHalfAngle = a[3] * b[3] + (0, std_math_1.dot)((_a = a, [_a[0], _a[1], _a[2]]), (_b = b, [_b[0], _b[1], _b[2]])); if (__.or(cosHalfAngle >= 1.0, cosHalfAngle <= (__.FM.negate_1(1.0)))) { return a; } else if (cosHalfAngle < 0.0) { b = (_c = b, _d = (__.FM.negate_1(1.0)), [_c[0] * _d, _c[1] * _d, _c[2] * _d, _c[3] * _d]); cosHalfAngle = (__.FM.negate_1(cosHalfAngle)); } var blendA = 0.0; var blendB = 0.0; if (cosHalfAngle < 0.99) { var halfAngle = Math.acos(cosHalfAngle); var sinHalfAngle = Math.sin(halfAngle); var oneOverSinHalfAngle = 1.0 / sinHalfAngle; blendA = Math.sin(halfAngle * (1.0 - t)) * oneOverSinHalfAngle; blendB = Math.sin(halfAngle * t) * oneOverSinHalfAngle; } else { blendA = 1.0 - t; blendB = t; } var result = __.FM.float_4_3_1(__.add((_e = blendA, _f = (_g = a, [_g[0], _g[1], _g[2]]), [_e * _f[0], _e * _f[1], _e * _f[2]]), (_h = blendB, _j = (_k = b, [_k[0], _k[1], _k[2]]), [_h * _j[0], _h * _j[1], _h * _j[2]])), __.add(blendA * a[3], blendB * b[3])); if ((0, std_math_1.length)(result) > 0.0) { return (0, std_math_1.normalize)(result); } return __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(1)); }; /** * Converts quaternion to matrix. */ quat.toMatrix = function (quaternion) { var x = quaternion[0]; var y = quaternion[1]; var z = quaternion[2]; var w = quaternion[3]; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var xy = x * y2; var xz = x * z2; var yy = y * y2; var yz = y * z2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; var m = __.float4x4(1.0 - (yy + zz), xy + wz, xz - wy, (0 | 0), xy - wz, 1.0 - (xx + zz), yz + wx, (0 | 0), xz + wy, yz - wx, 1.0 - (xx + yy), (0 | 0), (0 | 0), (0 | 0), (0 | 0), 1.0); return m; }; quat.fromEulerAngles = function (angles) { var cr = Math.cos(angles[0] * 0.5); var sr = Math.sin(angles[0] * 0.5); var cp = Math.cos(angles[1] * 0.5); var sp = Math.sin(angles[1] * 0.5); var cy = Math.cos(angles[2] * 0.5); var sy = Math.sin(angles[2] * 0.5); return __.FM.float_4_1_1_1_1(__.sub(sr * cp * cy, cr * sp * sy), __.add(cr * sp * cy, sr * cp * sy), __.sub(cr * cp * sy, sr * sp * cy), __.add(cr * cp * cy, sr * sp * sy)); }; quat.prototype.clone = function () { return new quat({}); }; quat.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_2304_quat\\",\\"fields\\":[]}"); }; return quat; }()); exports.quat = quat; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_2304_quat\\",\\"fields\\":[]}"), quat) ; /* impl quat */ window.shadeupQuat = quat; var Camera2d = /** @class */ (function () { function Camera2d(data) { var _a, _b; this.position = ((_a = data.position) !== null && _a !== void 0 ? _a : __.FM.float_2_1_1(__.int(0), __.int(0))); this.zoom = ((_b = data.zoom) !== null && _b !== void 0 ? _b : (1 | 0)); } Camera2d.prototype.transform = function (position) { var _a, _b, _c, _d; var shader_self_temp = this; return _a = (_c = position, _d = this.position, [_c[0] - _d[0], _c[1] - _d[1]]), _b = this.zoom, [_a[0] * _b, _a[1] * _b]; }; /** * Moves and zooms the camera to fit the given size. (centers the camera in the viewport) */ Camera2d.prototype.fit = function (size) { var _a, _b, _c, _d, _e, _f; var shader_self_temp = this; var zoom = (1 | 0) / (0, std_math_1.min)(env.screenSize[0] / size[0], env.screenSize[1] / size[1]); var position = (_a = (_c = env.screenSize, _d = (_e = size, _f = ((1 | 0) / zoom), [_e[0] * _f, _e[1] * _f]), [_c[0] - _d[0], _c[1] - _d[1]]), _b = (2 | 0), [_a[0] / _b, _a[1] / _b]); this.position = position; this.zoom = zoom; }; Camera2d.prototype.clone = function () { return new Camera2d({ position: (0, std___std_all_1.__deepClone)(this.position), zoom: (0, std___std_all_1.__deepClone)(this.zoom), }); }; Camera2d.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_9812_Camera2d\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"zoom\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"); }; return Camera2d; }()); exports.Camera2d = Camera2d; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_9812_Camera2d\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"zoom\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"), Camera2d) ; /* impl Camera2d */ var Camera = /** @class */ (function () { function Camera(data) { var _a, _b, _c, _d, _e, _f, _g; this.position = ((_a = data.position) !== null && _a !== void 0 ? _a : __.FM.float_3_1_1_1(__.int(0), __.int(0), __.int(0))); this.rotation = ((_b = data.rotation) !== null && _b !== void 0 ? _b : __.FM.float_4_1_1_1_1(__.int(1), __.int(0), __.int(0), __.int(0))); this.width = ((_c = data.width) !== null && _c !== void 0 ? _c : (1920 | 0)); this.height = ((_d = data.height) !== null && _d !== void 0 ? _d : (1080 | 0)); this.fov = ((_e = data.fov) !== null && _e !== void 0 ? _e : (90 | 0)); this.near = ((_f = data.near) !== null && _f !== void 0 ? _f : (1 | 0)); this.far = ((_g = data.far) !== null && _g !== void 0 ? _g : (100000 | 0)); } Camera.prototype.getRay = function (screen) { var shader_self_temp = this; var aspect = this.width / this.height; var x = screen[0]; var y = screen[1]; var Px = ((2 | 0) * ((x + 0.5) / this.width) - (1 | 0)) * Math.tan(this.fov / (2 | 0) * PI / (180 | 0)) * aspect; var Py = ((1 | 0) - (2 | 0) * ((y + 0.5) / this.height)) * Math.tan(this.fov / (2 | 0) * PI / (180 | 0)); return quat.rotate(this.rotation, (0, std_math_1.normalize)(__.makeVector(Px, Py, (__.FM.negate_1((1 | 0)))))); }; Camera.prototype.getTransformToViewMatrix = function (position, scale, rotation) { var shader_self_temp = this; var rotationMatrix = quat.toMatrix(rotation); var translationMatrix = __.float4x4(scale[0], (0 | 0), (0 | 0), (0 | 0), (0 | 0), scale[1], (0 | 0), (0 | 0), (0 | 0), (0 | 0), scale[2], (0 | 0), position[0], position[1], position[2], (1 | 0)); return __.mul(__.mul(__.mul(this.getPerspectiveMatrix(), this.getWorldToViewMatrix()), translationMatrix), rotationMatrix); }; Camera.prototype.getCombinedMatrix = function () { var shader_self_temp = this; return __.mul(this.getPerspectiveMatrix(), this.getWorldToViewMatrix()); }; Camera.prototype.getCombinedMatrixReverseZ = function () { var shader_self_temp = this; return __.mul(this.getPerspectiveMatrixReverseZ(), this.getWorldToViewMatrix()); }; Camera.prototype.getWorldToViewMatrix = function () { var shader_self_temp = this; var rotationMatrix = quat.toMatrix(this.rotation); var translationMatrix = __.float4x4((1 | 0), (0 | 0), (0 | 0), (0 | 0), (0 | 0), (1 | 0), (0 | 0), (0 | 0), (0 | 0), (0 | 0), (1 | 0), (0 | 0), this.position[0], this.position[1], this.position[2], (1 | 0)); return (0, std_math_1.inverse)(__.mul(translationMatrix, rotationMatrix)); }; Camera.prototype.getPerspectiveMatrixReverseZ = function () { var shader_self_temp = this; return matrix.perspectiveReverseZ(this.fov, this.width / this.height, this.near); }; Camera.prototype.getPerspectiveMatrix = function () { var shader_self_temp = this; return matrix.perspective(this.fov, this.width / this.height, this.near, this.far); // // let matrix = float4x4(); // let far = self.far; // let near = self.near; // let aspect = self.width / self.height; // let fovRad = radians(self.fov); // let tanFov = tan( fovRad * 0.5 ); // // matrix[0][0] = ; // // matrix[1][1] = 1.0 / tanFov; // // matrix[2][2] = -((far + near)/(far - near)); // // matrix[3][2] = -((2*(near*far))/(far - near)); // // matrix[2][3] = -1; // // matrix[3][3] = 0; // let matrix = float4x4( // 1.0 / (tanFov * aspect), 0, 0, 0, // 0, 1.0 / tanFov, 0, 0, // 0, 0, -((far + near)/(far - near)), -1, // 0, 0, -((2*(near*far))/(far - near)), 0 // ); // return matrix; }; Camera.prototype.getOrthographicMatrix = function () { var shader_self_temp = this; var matrix = __.float4x4(); var far = this.far; var near = this.near; var w = 1.0 / this.width; var h = 1.0 / this.height; matrix.__index((0 | 0)).__index_assign((0 | 0), w); matrix.__index((1 | 0)).__index_assign((1 | 0), h); matrix.__index((2 | 0)).__index_assign((2 | 0), (__.FM.negate_1((2.0 / (far - near))))); matrix.__index((2 | 0)).__index_assign((3 | 0), ((far + near) / (far - near))); //matrix[2][2] = -((far + near)/(far - near)); //matrix[3][2] = -((2*(near*far))/(far - near)); matrix.__index((3 | 0)).__index_assign((3 | 0), 1.0); return matrix; }; Camera.prototype.clone = function () { return new Camera({ position: (0, std___std_all_1.__deepClone)(this.position), rotation: (0, std___std_all_1.__deepClone)(this.rotation), width: (0, std___std_all_1.__deepClone)(this.width), height: (0, std___std_all_1.__deepClone)(this.height), fov: (0, std___std_all_1.__deepClone)(this.fov), near: (0, std___std_all_1.__deepClone)(this.near), far: (0, std___std_all_1.__deepClone)(this.far), }); }; Camera.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_10837_Camera\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"rotation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"width\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"height\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"fov\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"near\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"far\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"); }; return Camera; }()); exports.Camera = Camera; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_10837_Camera\\",\\"fields\\":[[\\"position\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float3\\"}],[\\"rotation\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"width\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"height\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"fov\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"near\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"far\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"), Camera) ; /* impl Camera */ window._makeCamera = Camera; window._makeCamera2d = Camera2d; function easeA(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; } function easeB(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; } function easeC(aA1) { return 3.0 * aA1; } function calcBezier(aT, aA1, aA2) { return ((easeA(aA1, aA2) * aT + easeB(aA1, aA2)) * aT + easeC(aA1)) * aT; } function getSlope(aT, aA1, aA2) { return 3.0 * easeA(aA1, aA2) * aT * aT + 2.0 * easeB(aA1, aA2) * aT + easeC(aA1); } // fn getTForX(aX: float, aA1: float, aA2: float) -> float { // let aGuessT = aX; // for (let i = 0; i <= 10; i++) { // let currentSlope = bezSlope(aGuessT, aA1, aA2); // if (currentSlope == 0.0) { // return aGuessT; // } // let currentX = calcBezier(aGuessT, aA1, aA2) - aX; // aGuessT -= currentX / currentSlope; // } // return aGuessT; // } var NEWTON_ITERATIONS = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "NEWTON_ITERATIONS", function () { return (4 | 0); }, function () { return NEWTON_ITERATIONS; }) | 0); var NEWTON_MIN_SLOPE = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "NEWTON_MIN_SLOPE", function () { return 0.02; }, function () { return NEWTON_MIN_SLOPE; }); var SUBDIVISION_PRECISION = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "SUBDIVISION_PRECISION", function () { return 0.0000001; }, function () { return SUBDIVISION_PRECISION; }); var SUBDIVISION_MAX_ITERATIONS = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "SUBDIVISION_MAX_ITERATIONS", function () { return (10 | 0); }, function () { return SUBDIVISION_MAX_ITERATIONS; }) | 0); var kSplineTableSize = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "kSplineTableSize", function () { return (11 | 0); }, function () { return kSplineTableSize; }) | 0); var kSampleStepSize = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "kSampleStepSize", function () { return 1.0 / __.sub(kSplineTableSize, (1 | 0)); }, function () { return kSampleStepSize; }); function getTForX(aX, mX1, mX2) { var mSampleValues = (0, std___std_all_1.array)((11 | 0), (0 | 0)); for (var i = (0 | 0); i < kSplineTableSize; i++) { mSampleValues.__index_assign(i, calcBezier(i * kSampleStepSize, mX1, mX2)); } // Find interval where t lies var intervalStart = 0.0; var currentSample = (1 | 0); var lastSample = kSplineTableSize - (1 | 0); for (var dummy = (0 | 0); __.and(currentSample != lastSample, mSampleValues[currentSample] <= aX); currentSample++) { intervalStart = intervalStart + kSampleStepSize; } currentSample--; // t now lies between *currentSample and *currentSample+1 // Interpolate to provide an initial guess for t var csamp = mSampleValues[currentSample]; var dst = (aX - csamp) / (mSampleValues[currentSample + (1 | 0)] - csamp); var guessForT = intervalStart + dst * kSampleStepSize; // Check the slope to see what strategy to use. If the slope is too small // Newton-Raphson iteration won't converge on a root so we use bisection // instead. var initialSlope = getSlope(guessForT, mX1, mX2); if (initialSlope >= NEWTON_MIN_SLOPE) { return newtonRaphsonIterate(aX, guessForT, mX1, mX2); } else if (initialSlope == 0.0) { return guessForT; } else { return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize); } } function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { for (var i = (0 | 0); i < NEWTON_ITERATIONS; i++) { // We're trying to find where f(t) = aX, // so we're actually looking for a root for: CalcBezier(t) - aX var currentX = calcBezier(aGuessT, mX1, mX2) - aX; var currentSlope = getSlope(aGuessT, mX1, mX2); if (currentSlope == 0.0) return aGuessT; aGuessT = aGuessT - currentX / currentSlope; } return aGuessT; } function binarySubdivide(aX, aA, aB) { var currentX = 0.0; var currentT = 0.0; var i = (0 | 0); var mX1 = aA; var mX2 = aB; while ((true)) { i++; if (__.and(Math.abs(currentX) > SUBDIVISION_PRECISION, i < SUBDIVISION_MAX_ITERATIONS)) { currentT = aA + (aB - aA) / 2.0; currentX = calcBezier(currentT, mX1, mX2) - aX; if (currentX > 0.0) { aB = currentT; } else { aA = currentT; } } else { break; } } return currentT; } var bezier = /** @class */ (function () { function bezier(data) { } bezier.cubic2 = function (a, b, c, d, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; return _a = (_c = (_e = (_g = __.pow((1.0 - t), (3 | 0)), _h = a, [_g * _h[0], _g * _h[1]]), _f = (_j = 3.0 * __.pow((1.0 - t), (2 | 0)) * t, _k = b, [_j * _k[0], _j * _k[1]]), [_e[0] + _f[0], _e[1] + _f[1]]), _d = (_l = 3.0 * (1.0 - t) * __.pow(t, (2 | 0)), _m = c, [_l * _m[0], _l * _m[1]]), [_c[0] + _d[0], _c[1] + _d[1]]), _b = (_o = __.pow(t, (3 | 0)), _p = d, [_o * _p[0], _o * _p[1]]), [_a[0] + _b[0], _a[1] + _b[1]]; }; bezier.cubic3 = function (a, b, c, d, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; return _a = (_c = (_e = (_g = __.pow((1.0 - t), (3 | 0)), _h = a, [_g * _h[0], _g * _h[1], _g * _h[2]]), _f = (_j = 3.0 * __.pow((1.0 - t), (2 | 0)) * t, _k = b, [_j * _k[0], _j * _k[1], _j * _k[2]]), [_e[0] + _f[0], _e[1] + _f[1], _e[2] + _f[2]]), _d = (_l = 3.0 * (1.0 - t) * __.pow(t, (2 | 0)), _m = c, [_l * _m[0], _l * _m[1], _l * _m[2]]), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]]), _b = (_o = __.pow(t, (3 | 0)), _p = d, [_o * _p[0], _o * _p[1], _o * _p[2]]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]; }; bezier.quadratic2 = function (a, b, c, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; return _a = (_c = (_e = __.pow((1.0 - t), (2 | 0)), _f = a, [_e * _f[0], _e * _f[1]]), _d = (_g = 2.0 * (1.0 - t) * t, _h = b, [_g * _h[0], _g * _h[1]]), [_c[0] + _d[0], _c[1] + _d[1]]), _b = (_j = __.pow(t, (2 | 0)), _k = c, [_j * _k[0], _j * _k[1]]), [_a[0] + _b[0], _a[1] + _b[1]]; }; bezier.quadratic3 = function (a, b, c, t) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; return _a = (_c = (_e = __.pow((1.0 - t), (2 | 0)), _f = a, [_e * _f[0], _e * _f[1], _e * _f[2]]), _d = (_g = 2.0 * (1.0 - t) * t, _h = b, [_g * _h[0], _g * _h[1], _g * _h[2]]), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]]), _b = (_j = __.pow(t, (2 | 0)), _k = c, [_j * _k[0], _j * _k[1], _j * _k[2]]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]; }; /** * 3d triangle patch evaulation with barycentric coordinates. */ bezier.patch = function (a, ab, b, bc, c, ca, barycentricT) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15; var s = barycentricT[0]; var t = barycentricT[1]; var u = barycentricT[2]; return _a = (_c = (_e = (_g = (_j = (_l = (_o = 1.0, _p = c, [_o * _p[0], _o * _p[1], _o * _p[2]]), _m = (s * s), [_l[0] * _m, _l[1] * _m, _l[2] * _m]), _k = (_q = (_s = (_u = 2.0, _v = bc, [_u * _v[0], _u * _v[1], _u * _v[2]]), _t = s, [_s[0] * _t, _s[1] * _t, _s[2] * _t]), _r = t, [_q[0] * _r, _q[1] * _r, _q[2] * _r]), [_j[0] + _k[0], _j[1] + _k[1], _j[2] + _k[2]]), _h = (_w = (_y = (_0 = 2.0, _1 = ca, [_0 * _1[0], _0 * _1[1], _0 * _1[2]]), _z = s, [_y[0] * _z, _y[1] * _z, _y[2] * _z]), _x = u, [_w[0] * _x, _w[1] * _x, _w[2] * _x]), [_g[0] + _h[0], _g[1] + _h[1], _g[2] + _h[2]]), _f = (_2 = (_4 = 1.0, _5 = b, [_4 * _5[0], _4 * _5[1], _4 * _5[2]]), _3 = (t * t), [_2[0] * _3, _2[1] * _3, _2[2] * _3]), [_e[0] + _f[0], _e[1] + _f[1], _e[2] + _f[2]]), _d = (_6 = (_8 = (_10 = 2.0, _11 = ab, [_10 * _11[0], _10 * _11[1], _10 * _11[2]]), _9 = t, [_8[0] * _9, _8[1] * _9, _8[2] * _9]), _7 = u, [_6[0] * _7, _6[1] * _7, _6[2] * _7]), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]]), _b = (_12 = (_14 = 1.0, _15 = a, [_14 * _15[0], _14 * _15[1], _14 * _15[2]]), _13 = (u * u), [_12[0] * _13, _12[1] * _13, _12[2] * _13]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]; }; bezier.easing = function (controlA, controlB, t) { return calcBezier(getTForX(t, controlA[0], controlB[0]), controlA[1], controlB[1]); }; bezier.prototype.clone = function () { return new bezier({}); }; bezier.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_20500_bezier\\",\\"fields\\":[]}"); }; return bezier; }()); exports.bezier = bezier; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_20500_bezier\\",\\"fields\\":[]}"), bezier) ; /* impl bezier */ /** * Provides space related utilities like z-order curves and quadtrees. */ var spatial = /** @class */ (function () { function spatial(data) { } spatial.cantorPair = function (v) { return ((v[0] + v[1]) * (v[0] + v[1] + (1 | 0))) / (2 | 0) + v[1]; }; spatial.cantorUnpair = function (v) { var w = Math.floor((Math.sqrt(8.0 * v + 1.0) - 1.0) / 2.0); var t = (w * w + w) / 2.0; var y = v - t; var x = w - y; return __.FM.int_2_1_1(x, y); }; spatial.hilbertRotate = function (n, b, r) { var x = b[0]; var y = b[1]; if (r[1] == (0 | 0)) { if (r[0] == (1 | 0)) { x = n - (1 | 0) - x; y = n - (1 | 0) - y; } var t = x; x = y; y = t; } return __.FM.int_2_1_1(x, y); }; spatial.hilbertUncurve = function (n, v) { var x = v[0]; var y = v[1]; var rx = (0 | 0); var ry = (0 | 0); var s = (0 | 0); var d = (0 | 0); for (s = n / (2 | 0); s > (0 | 0); s = s / (2 | 0)) { rx = ((x & s) > (0 | 0)) ? (1 | 0) : (0 | 0); ry = ((y & s) > (0 | 0)) ? (1 | 0) : (0 | 0); d = d + s * s * (((3 | 0) * rx) ^ ry); var o = __.intifyVector(spatial.hilbertRotate(n, __.intifyVector(__.makeVector(x, y)), __.intifyVector(__.makeVector(rx, ry)))); x = o[0]; y = o[1]; } return d; }; spatial.hilbertCurve = function (n, v) { var rx = (0 | 0); var ry = (0 | 0); var t = v; var x = (0 | 0); var y = (0 | 0); for (var s = (1 | 0); s < n; s = s * (2 | 0)) { rx = (1 | 0) & (t / (2 | 0)); ry = (1 | 0) & (t ^ rx); var o = __.intifyVector(spatial.hilbertRotate(s, __.intifyVector(__.makeVector(x, y)), __.intifyVector(__.makeVector(rx, ry)))); x = o[0]; y = o[1]; x = x + s * rx; y = y + s * ry; t = t / (4 | 0); } return __.FM.int_2_1_1(x, y); }; spatial.mortonDecode = function (p) { return __.FM.uint_2_1_1(reverseMortonCode2(p), reverseMortonCode2(p >> (1 >>> 0))); }; spatial.mortonEncode = function (p) { return (__.bitor(mortonCode2(p[0]), (mortonCode2(p[1]) << (1 >>> 0))) >>> 0); }; spatial.prototype.clone = function () { return new spatial({}); }; spatial.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_23054_spatial\\",\\"fields\\":[]}"); }; return spatial; }()); exports.spatial = spatial; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_23054_spatial\\",\\"fields\\":[]}"), spatial) ; /* impl spatial */ function mortonCode2(x) { x = x & (0x0000ffff >>> 0); var n8 = (8 >>> 0); var n4 = (4 >>> 0); var n2 = (2 >>> 0); var n1 = (1 >>> 0); x = (x ^ (x << n8)) & (0x00ff00ff >>> 0); x = (x ^ (x << n4)) & (0x0f0f0f0f >>> 0); x = (x ^ (x << n2)) & (0x33333333 >>> 0); x = (x ^ (x << n1)) & (0x55555555 >>> 0); return x; } exports.mortonCode2 = mortonCode2; ; function randColor(seed) { return __.FM.float_4_1_1_1_1((0, std_math_1.rand2)(__.makeVector(seed, (5 | 0))), (0, std_math_1.rand2)(__.makeVector(seed, (1 | 0))), (0, std_math_1.rand2)(__.makeVector(seed, (4 | 0))), __.int(1)); } exports.randColor = randColor; ; function randColor2(seed) { return __.FM.float_4_1_1_1_1((0, std_math_1.rand3)(__.makeVector(seed, (5 | 0))), (0, std_math_1.rand3)(__.makeVector(seed, (1 | 0))), (0, std_math_1.rand3)(__.makeVector(seed, (4 | 0))), __.int(1)); } exports.randColor2 = randColor2; ; function reverseMortonCode2(x) { x = x & (0x55555555 >>> 0); x = (x ^ (x >> (1 >>> 0))) & (0x33333333 >>> 0); x = (x ^ (x >> (2 >>> 0))) & (0x0f0f0f0f >>> 0); x = (x ^ (x >> (4 >>> 0))) & (0x00ff00ff >>> 0); x = (x ^ (x >> (8 >>> 0))) & (0x0000ffff >>> 0); return x; } exports.reverseMortonCode2 = reverseMortonCode2; ; var noise = /** @class */ (function () { function noise(data) { } noise.gaussian3 = function (v) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17; var p = v; var a = (_a = p, [Math.floor(_a[0]), Math.floor(_a[1]), Math.floor(_a[2])]); var d = (_b = p, _c = a, [_b[0] - _c[0], _b[1] - _c[1], _b[2] - _c[2]]); d = (_d = (_f = d, _g = d, [_f[0] * _g[0], _f[1] * _g[1], _f[2] * _g[2]]), _e = (_h = 3.0, _j = (_k = 2.0, _l = d, [_k * _l[0], _k * _l[1], _k * _l[2]]), [_h - _j[0], _h - _j[1], _h - _j[2]]), [_d[0] * _e[0], _d[1] * _e[1], _d[2] * _e[2]]); var b = (_m = (_p = a, [_p[0], _p[0], _p[1], _p[1]]), _o = __.FM.float_4_1_1_1_1(__.float(0.0), __.float(1.0), __.float(0.0), __.float(1.0)), [_m[0] + _o[0], _m[1] + _o[1], _m[2] + _o[2], _m[3] + _o[3]]); var k1 = perm((_q = b, [_q[0], _q[1], _q[0], _q[1]])); var k2 = perm((_r = (_t = k1, [_t[0], _t[1], _t[0], _t[1]]), _s = (_u = b, [_u[2], _u[2], _u[3], _u[3]]), [_r[0] + _s[0], _r[1] + _s[1], _r[2] + _s[2], _r[3] + _s[3]])); var c = (_v = k2, _w = (_x = a, [_x[2], _x[2], _x[2], _x[2]]), [_v[0] + _w[0], _v[1] + _w[1], _v[2] + _w[2], _v[3] + _w[3]]); var k3 = perm(c); var k4 = perm((_y = c, _z = 1.0, [_y[0] + _z, _y[1] + _z, _y[2] + _z, _y[3] + _z])); var o1 = (0, std_math_1.frac)((_0 = k3, _1 = (1.0 / 41.0), [_0[0] * _1, _0[1] * _1, _0[2] * _1, _0[3] * _1])); var o2 = (0, std_math_1.frac)((_2 = k4, _3 = (1.0 / 41.0), [_2[0] * _3, _2[1] * _3, _2[2] * _3, _2[3] * _3])); var o3 = (_4 = (_6 = o2, _7 = d[2], [_6[0] * _7, _6[1] * _7, _6[2] * _7, _6[3] * _7]), _5 = (_8 = o1, _9 = (1.0 - d[2]), [_8[0] * _9, _8[1] * _9, _8[2] * _9, _8[3] * _9]), [_4[0] + _5[0], _4[1] + _5[1], _4[2] + _5[2], _4[3] + _5[3]]); var o4 = (_10 = (_12 = (_14 = o3, [_14[1], _14[3]]), _13 = d[0], [_12[0] * _13, _12[1] * _13]), _11 = (_15 = (_17 = o3, [_17[0], _17[2]]), _16 = (1.0 - d[0]), [_15[0] * _16, _15[1] * _16]), [_10[0] + _11[0], _10[1] + _11[1]]); return o4[1] * d[1] + o4[0] * (1.0 - d[1]); }; noise.gaussian2 = function (v) { return noise.gaussian3(__.makeVector(v, (0 | 0))); }; noise.noise1 = function (x) { var i = Math.floor(x); var f = (0, std_math_1.frac)(x); var u = f * f * (3.0 - 2.0 * f); return (0, std_math_1.lerp)(hash(i), hash(i + 1.0), u); }; noise.noise2 = function (x) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; var i = (_a = x, [Math.floor(_a[0]), Math.floor(_a[1])]); var f = (0, std_math_1.frac)(x); // Four corners in 2D of a tile var a = hash2(i); var b = hash2((_b = i, _c = __.FM.float_2_1_1(__.float(1.0), __.float(0.0)), [_b[0] + _c[0], _b[1] + _c[1]])); var c = hash2((_d = i, _e = __.FM.float_2_1_1(__.float(0.0), __.float(1.0)), [_d[0] + _e[0], _d[1] + _e[1]])); var d = hash2((_f = i, _g = __.FM.float_2_1_1(__.float(1.0), __.float(1.0)), [_f[0] + _g[0], _f[1] + _g[1]])); // Simple 2D lerp using smoothstep envelope between the values. // return float3(lerp(lerp(a, b, smoothstep(0.0, 1.0, f.x)), // lerp(c, d, smoothstep(0.0, 1.0, f.x)), // smoothstep(0.0, 1.0, f.y))); // Same code, with the clamps in smoothstep and common subexpressions // optimized away. var u = (_h = (_k = f, _l = f, [_k[0] * _l[0], _k[1] * _l[1]]), _j = (_m = 3.0, _o = (_p = 2.0, _q = f, [_p * _q[0], _p * _q[1]]), [_m - _o[0], _m - _o[1]]), [_h[0] * _j[0], _h[1] * _j[1]]); return (0, std_math_1.lerp)(a, b, u[0]) + (c - a) * u[1] * (1.0 - u[0]) + (d - b) * u[0] * u[1]; }; noise.fmb1 = function (x) { var v = 0.0; var a = 0.5; var shift = __.int(100); for (var i = (0 | 0); i < (5 | 0); i++) { v = v + a * noise.noise1(x); x = x * 2.0 + shift; a = a * 0.5; } return v; }; noise.fbm2 = function (x) { var _a, _b, _c, _d; var v = 0.0; var a = 0.5; var shift = __.FM.float_2_2(__.swizzle((100 | 0), "xy")); // Rotate to reduce axial bias var rot = __.float2x2(Math.cos(0.5), Math.sin(0.5), (__.FM.negate_1(Math.sin(0.5))), Math.cos(0.50)); for (var i = (0 | 0); i < (5 | 0); i++) { v = v + a * noise.noise2(x); x = (_a = (_c = __.mul(rot, x), _d = 2.0, [_c[0] * _d, _c[1] * _d]), _b = shift, [_a[0] + _b[0], _a[1] + _b[1]]); a = a * 0.5; } return v; }; noise.fbm3 = function (x) { var _a, _b, _c, _d; var v = 0.0; var a = 0.5; var shift = __.FM.float_3_3(__.swizzle((100 | 0), "xyz")); for (var i = (0 | 0); i < (5 | 0); i++) { v = v + a * noise.noise3(x); x = (_a = (_c = x, _d = 2.0, [_c[0] * _d, _c[1] * _d, _c[2] * _d]), _b = shift, [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]]); a = a * 0.5; } return v; }; noise.noise3 = function (x) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; var step = __.FM.float_3_1_1_1(__.int(110), __.int(241), __.int(171)); var i = (_a = x, [Math.floor(_a[0]), Math.floor(_a[1]), Math.floor(_a[2])]); var f = (0, std_math_1.frac)(x); // For performance, compute the base input to a 1D hash from the integer part of the argument and the // incremental change to the 1D based on the 3D -> 1D wrapping var n = (0, std_math_1.dot)(i, step); var u = (_b = (_d = f, _e = f, [_d[0] * _e[0], _d[1] * _e[1], _d[2] * _e[2]]), _c = (_f = 3.0, _g = (_h = 2.0, _j = f, [_h * _j[0], _h * _j[1], _h * _j[2]]), [_f - _g[0], _f - _g[1], _f - _g[2]]), [_b[0] * _c[0], _b[1] * _c[1], _b[2] * _c[2]]); return (0, std_math_1.lerp)((0, std_math_1.lerp)((0, std_math_1.lerp)(hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(0), __.int(0), __.int(0)))), hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(1), __.int(0), __.int(0)))), u[0]), (0, std_math_1.lerp)(hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(0), __.int(1), __.int(0)))), hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(1), __.int(1), __.int(0)))), u[0]), u[1]), (0, std_math_1.lerp)((0, std_math_1.lerp)(hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(0), __.int(0), __.int(1)))), hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(1), __.int(0), __.int(1)))), u[0]), (0, std_math_1.lerp)(hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(0), __.int(1), __.int(1)))), hash(n + (0, std_math_1.dot)(step, __.FM.float_3_1_1_1(__.int(1), __.int(1), __.int(1)))), u[0]), u[1]), u[2]); }; noise.simplex2 = function (v) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28; var C = __.FM.float_4_1_1_1_1(__.float(0.211324865405187), __.float(0.366025403784439), __.negate(0.577350269189626), __.float(0.024390243902439)); var i = (_a = (_b = v, _c = (0, std_math_1.dot)(v, (_d = C, [_d[1], _d[1]])), [_b[0] + _c, _b[1] + _c]), [Math.floor(_a[0]), Math.floor(_a[1])]); var x0 = (_e = (_g = v, _h = i, [_g[0] - _h[0], _g[1] - _h[1]]), _f = (0, std_math_1.dot)(i, (_j = C, [_j[0], _j[0]])), [_e[0] + _f, _e[1] + _f]); var xv = (0, std_math_1.step)(x0[1], x0[0]); var i1 = __.FM.float_2_1_1(xv, __.sub(1.0, xv)); var x1 = (_k = (_m = x0, _o = (_p = C, [_p[0], _p[0]]), [_m[0] + _o[0], _m[1] + _o[1]]), _l = i1, [_k[0] - _l[0], _k[1] - _l[1]]); var x2 = (_q = x0, _r = (_s = C, [_s[2], _s[2]]), [_q[0] + _r[0], _q[1] + _r[1]]); i = mod289_2(i); var p = permute((_t = (_v = permute((_x = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'y'), __.float(1.0)), _y = i[1], [_x[0] + _y, _x[1] + _y, _x[2] + _y])), _w = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'x'), __.float(1.0)), [_v[0] + _w[0], _v[1] + _w[1], _v[2] + _w[2]]), _u = i[0], [_t[0] + _u, _t[1] + _u, _t[2] + _u])); var m = (0, std_math_1.max)((_z = (_1 = 0.5, [_1, _1, _1]), _0 = __.FM.float_3_1_1_1((0, std_math_1.dot)(x0, x0), (0, std_math_1.dot)(x1, x1), (0, std_math_1.dot)(x2, x2)), [_z[0] - _0[0], _z[1] - _0[1], _z[2] - _0[2]]), 0.0); m = (_2 = m, _3 = m, [_2[0] * _3[0], _2[1] * _3[1], _2[2] * _3[2]]); m = (_4 = m, _5 = m, [_4[0] * _5[0], _4[1] * _5[1], _4[2] * _5[2]]); var x = (_6 = (_8 = 2.0, _9 = (0, std_math_1.frac)((_10 = p, _11 = (_12 = C, [_12[3], _12[3], _12[3]]), [_10[0] * _11[0], _10[1] * _11[1], _10[2] * _11[2]])), [_8 * _9[0], _8 * _9[1], _8 * _9[2]]), _7 = 1.0, [_6[0] - _7, _6[1] - _7, _6[2] - _7]); var h = (_13 = (_15 = x, [Math.abs(_15[0]), Math.abs(_15[1]), Math.abs(_15[2])]), _14 = 0.5, [_13[0] - _14, _13[1] - _14, _13[2] - _14]); var ox = (_16 = (_17 = x, _18 = 0.5, [_17[0] + _18, _17[1] + _18, _17[2] + _18]), [Math.floor(_16[0]), Math.floor(_16[1]), Math.floor(_16[2])]); var a0 = (_19 = x, _20 = ox, [_19[0] - _20[0], _19[1] - _20[1], _19[2] - _20[2]]); // Normalise gradients implicitly by scaling m m = (_21 = m, _22 = taylorInvSqrt((_23 = (_25 = a0, _26 = a0, [_25[0] * _26[0], _25[1] * _26[1], _25[2] * _26[2]]), _24 = (_27 = h, _28 = h, [_27[0] * _28[0], _27[1] * _28[1], _27[2] * _28[2]]), [_23[0] + _24[0], _23[1] + _24[1], _23[2] + _24[2]])), [_21[0] * _22[0], _21[1] * _22[1], _21[2] * _22[2]]); // Compute final noise value at P var g = __.FM.float_3_1_1_1(__.add(a0[0] * x0[0], h[0] * x0[1]), __.add(a0[1] * x1[0], h[1] * x1[1]), __.add(a0[2] * x2[0], h[2] * x2[1])); return 130.0 * (0, std_math_1.dot)(m, g); }; noise.perlin2 = function (v) { var x = v[0]; var y = v[1]; var z = 0.0; if (x < (0 | 0)) { x = (__.FM.negate_1(x)); } if (y < (0 | 0)) { y = (__.FM.negate_1(y)); } if (z < (0 | 0)) { z = (__.FM.negate_1(z)); } var xi = ((0, std_math_1.floor)(x) | 0); var yi = ((0, std_math_1.floor)(y) | 0); var zi = ((0, std_math_1.floor)(z) | 0); var xf = x - xi; var yf = y - yi; var zf = z - zi; var rxf = 0.0; var ryf = 0.0; var r = 0.0; var ampl = 0.5; var n1 = 0.0; var n2 = 0.0; var n3 = 0.0; for (var o = (0 | 0); o < perlin_octaves; o++) { var of1 = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); rxf = scaled_cosine(xf); ryf = scaled_cosine(yf); n1 = perlin.floatArray[of1 & PERLIN_SIZE]; n1 = n1 + rxf * (perlin.floatArray[(of1 + (1 | 0)) & PERLIN_SIZE] - n1); n2 = perlin.floatArray[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n2 = n2 + rxf * (perlin.floatArray[(of1 + PERLIN_YWRAP + (1 | 0)) & PERLIN_SIZE] - n2); n1 = n1 + ryf * (n2 - n1); of1 = of1 + PERLIN_ZWRAP; n2 = perlin.floatArray[of1 & PERLIN_SIZE]; n2 = n2 + rxf * (perlin.floatArray[(of1 + (1 | 0)) & PERLIN_SIZE] - n2); n3 = perlin.floatArray[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n3 = n3 + rxf * (perlin.floatArray[(of1 + PERLIN_YWRAP + (1 | 0)) & PERLIN_SIZE] - n3); n2 = n2 + ryf * (n3 - n2); n1 = n1 + scaled_cosine(zf) * (n2 - n1); r = r + n1 * ampl; ampl = ampl * perlin_amp_falloff; xi = xi << (1 | 0); xf = xf * 2.0; yi = yi << (1 | 0); yf = yf * 2.0; zi = zi << (1 | 0); zf = zf * 2.0; if (xf >= 1.0) { xi++; xf = xf - 1.0; } if (yf >= 1.0) { yi++; yf = yf - 1.0; } if (zf >= 1.0) { zi++; zf = zf - 1.0; } } return r; }; noise.perlin3 = function (v) { var x = v[0]; var y = v[1]; var z = v[2]; if (x < (0 | 0)) { x = (__.FM.negate_1(x)); } if (y < (0 | 0)) { y = (__.FM.negate_1(y)); } if (z < (0 | 0)) { z = (__.FM.negate_1(z)); } var xi = ((0, std_math_1.floor)(x) | 0); var yi = ((0, std_math_1.floor)(y) | 0); var zi = ((0, std_math_1.floor)(z) | 0); var xf = x - xi; var yf = y - yi; var zf = z - zi; var rxf = 0.0; var ryf = 0.0; var r = 0.0; var ampl = 0.5; var n1 = 0.0; var n2 = 0.0; var n3 = 0.0; for (var o = (0 | 0); o < perlin_octaves; o++) { var of1 = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); rxf = scaled_cosine(xf); ryf = scaled_cosine(yf); n1 = perlin.floatArray[of1 & PERLIN_SIZE]; n1 = n1 + rxf * (perlin.floatArray[(of1 + (1 | 0)) & PERLIN_SIZE] - n1); n2 = perlin.floatArray[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n2 = n2 + rxf * (perlin.floatArray[(of1 + PERLIN_YWRAP + (1 | 0)) & PERLIN_SIZE] - n2); n1 = n1 + ryf * (n2 - n1); of1 = of1 + PERLIN_ZWRAP; n2 = perlin.floatArray[of1 & PERLIN_SIZE]; n2 = n2 + rxf * (perlin.floatArray[(of1 + (1 | 0)) & PERLIN_SIZE] - n2); n3 = perlin.floatArray[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n3 = n3 + rxf * (perlin.floatArray[(of1 + PERLIN_YWRAP + (1 | 0)) & PERLIN_SIZE] - n3); n2 = n2 + ryf * (n3 - n2); n1 = n1 + scaled_cosine(zf) * (n2 - n1); r = r + n1 * ampl; ampl = ampl * perlin_amp_falloff; xi = xi << (1 | 0); xf = xf * 2.0; yi = yi << (1 | 0); yf = yf * 2.0; zi = zi << (1 | 0); zf = zf * 2.0; if (xf >= 1.0) { xi++; xf = xf - 1.0; } if (yf >= 1.0) { yi++; yf = yf - 1.0; } if (zf >= 1.0) { zi++; zf = zf - 1.0; } } return r; }; /** * Returns 3 values: distance to closest cell, random value of closest cell, distance to closest edge. */ noise.voronoi2 = function (v) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z; var n = (_a = v, [Math.floor(_a[0]), Math.floor(_a[1])]); var minDist = 10.0; var toClose = (_b = 0.0, [_b, _b]); var closestCell = (_c = 0.0, [_c, _c]); for (var j = (__.FM.negate_1((1 | 0))); j <= (1 | 0); j++) { for (var i = (__.FM.negate_1((1 | 0))); i <= (1 | 0); i++) { var cell = (_d = n, _e = __.FM.float_2_1_1(i, j), [_d[0] + _e[0], _d[1] + _e[1]]); var cellPos = (_f = cell, _g = hash2(cell), [_f[0] + _g, _f[1] + _g]); var toCell = (_h = cellPos, _j = v, [_h[0] - _j[0], _h[1] - _j[1]]); var dst = (0, std_math_1.length)(toCell); if (dst < minDist) { minDist = dst; toClose = toCell; closestCell = cell; } } } var minEdge = 10.0; for (var j = (__.FM.negate_1((1 | 0))); j <= (1 | 0); j++) { for (var i = (__.FM.negate_1((1 | 0))); i <= (1 | 0); i++) { var cell = (_k = n, _l = __.FM.float_2_1_1(i, j), [_k[0] + _l[0], _k[1] + _l[1]]); var cellPos = (_m = cell, _o = hash2(cell), [_m[0] + _o, _m[1] + _o]); var toCell = (_p = cellPos, _q = v, [_p[0] - _q[0], _p[1] - _q[1]]); var diff = (_r = (_s = closestCell, _t = cell, [_s[0] - _t[0], _s[1] - _t[1]]), [Math.abs(_r[0]), Math.abs(_r[1])]); var isClosest = diff[0] + diff[1] < 0.1; if (__.not(isClosest)) { var toCenter = (_u = (_w = toClose, _x = toCell, [_w[0] + _x[0], _w[1] + _x[1]]), _v = 0.5, [_u[0] * _v, _u[1] * _v]); var cellDiff = (0, std_math_1.normalize)((_y = toCell, _z = toClose, [_y[0] - _z[0], _y[1] - _z[1]])); var edge = (0, std_math_1.dot)(toCenter, cellDiff); minEdge = (0, std_math_1.min)(minEdge, edge); } } } var random = hash2(closestCell); return __.FM.float_3_1_1_1(minDist, random, minEdge); }; noise.simplex3 = function (v) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56; var C = __.FM.float_4_1_1_1_1(__.float(0.138196601125011), __.float(0.276393202250021), __.float(0.414589803375032), __.negate(0.447213595499958)); var i = (_a = (_b = v, _c = (0, std_math_1.dot)(v, (_d = C, [_d[1], _d[1], _d[1]])), [_b[0] + _c, _b[1] + _c, _b[2] + _c]), [Math.floor(_a[0]), Math.floor(_a[1]), Math.floor(_a[2])]); var x0 = (_e = (_g = v, _h = i, [_g[0] - _h[0], _g[1] - _h[1], _g[2] - _h[2]]), _f = (0, std_math_1.dot)(i, (_j = C, [_j[0], _j[0], _j[0]])), [_e[0] + _f, _e[1] + _f, _e[2] + _f]); var g = (0, std_math_1.step)((_k = x0, [_k[1], _k[2], _k[0]]), (_l = x0, [_l[0], _l[1], _l[2]])); var l = (_m = 1.0, _o = g, [_m - _o[0], _m - _o[1], _m - _o[2]]); var i1 = (0, std_math_1.min)((_p = g, [_p[0], _p[1], _p[2]]), (_q = l, [_q[2], _q[0], _q[1]])); var i2 = (0, std_math_1.max)((_r = g, [_r[0], _r[1], _r[2]]), (_s = l, [_s[2], _s[0], _s[1]])); var x1 = (_t = (_v = x0, _w = i1, [_v[0] - _w[0], _v[1] - _w[1], _v[2] - _w[2]]), _u = (_x = 1.0, _y = (_z = C, [_z[0], _z[0], _z[0]]), [_x * _y[0], _x * _y[1], _x * _y[2]]), [_t[0] + _u[0], _t[1] + _u[1], _t[2] + _u[2]]); var x2 = (_0 = (_2 = x0, _3 = i2, [_2[0] - _3[0], _2[1] - _3[1], _2[2] - _3[2]]), _1 = (_4 = 2.0, _5 = (_6 = C, [_6[0], _6[0], _6[0]]), [_4 * _5[0], _4 * _5[1], _4 * _5[2]]), [_0[0] + _1[0], _0[1] + _1[1], _0[2] + _1[2]]); var x3 = (_7 = (_9 = x0, _10 = 1., [_9[0] - _10, _9[1] - _10, _9[2] - _10]), _8 = (_11 = 3.0, _12 = (_13 = C, [_13[0], _13[0], _13[0]]), [_11 * _12[0], _11 * _12[1], _11 * _12[2]]), [_7[0] + _8[0], _7[1] + _8[1], _7[2] + _8[2]]); i = mod289_3(i); var p = permute((_14 = (_16 = permute((_18 = (_20 = permute((_22 = i[2], _23 = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'z'), __.swizzle(i2, 'z')), [_22 + _23[0], _22 + _23[1], _22 + _23[2]])), _21 = i[1], [_20[0] + _21, _20[1] + _21, _20[2] + _21]), _19 = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'y'), __.swizzle(i2, 'y')), [_18[0] + _19[0], _18[1] + _19[1], _18[2] + _19[2]])), _17 = i[0], [_16[0] + _17, _16[1] + _17, _16[2] + _17]), _15 = __.FM.float_3_1_1_1(__.float(0.0), __.swizzle(i1, 'x'), __.swizzle(i2, 'x')), [_14[0] + _15[0], _14[1] + _15[1], _14[2] + _15[2]])); var m = (0, std_math_1.max)((_24 = 0.5, _25 = __.FM.float_3_1_1_1((0, std_math_1.dot)(x0, x0), (0, std_math_1.dot)(x1, x1), (0, std_math_1.dot)(x2, x2)), [_24 - _25[0], _24 - _25[1], _24 - _25[2]]), 0.0); m = (_26 = m, _27 = m, [_26[0] * _27[0], _26[1] * _27[1], _26[2] * _27[2]]); m = (_28 = m, _29 = m, [_28[0] * _29[0], _28[1] * _29[1], _28[2] * _29[2]]); var x = (_30 = (_32 = 2.0, _33 = (0, std_math_1.frac)((_34 = p, _35 = (_36 = C, [_36[3], _36[3], _36[3]]), [_34[0] * _35[0], _34[1] * _35[1], _34[2] * _35[2]])), [_32 * _33[0], _32 * _33[1], _32 * _33[2]]), _31 = 1.0, [_30[0] - _31, _30[1] - _31, _30[2] - _31]); var h = (_37 = (_39 = x, [Math.abs(_39[0]), Math.abs(_39[1]), Math.abs(_39[2])]), _38 = 0.5, [_37[0] - _38, _37[1] - _38, _37[2] - _38]); var ox = (_40 = (_41 = x, _42 = 0.5, [_41[0] + _42, _41[1] + _42, _41[2] + _42]), [Math.floor(_40[0]), Math.floor(_40[1]), Math.floor(_40[2])]); var a0 = (_43 = x, _44 = ox, [_43[0] - _44[0], _43[1] - _44[1], _43[2] - _44[2]]); // Normalise gradients implicitly by scaling m // Approximation of: m *= inversesqrt(a0 * a0 + h * h); m = (_45 = m, _46 = (_47 = 1.79284291400159, _48 = (_49 = 0.85373472095314, _50 = (_51 = (_53 = a0, _54 = a0, [_53[0] * _54[0], _53[1] * _54[1], _53[2] * _54[2]]), _52 = (_55 = h, _56 = h, [_55[0] * _56[0], _55[1] * _56[1], _55[2] * _56[2]]), [_51[0] + _52[0], _51[1] + _52[1], _51[2] + _52[2]]), [_49 * _50[0], _49 * _50[1], _49 * _50[2]]), [_47 - _48[0], _47 - _48[1], _47 - _48[2]]), [_45[0] * _46[0], _45[1] * _46[1], _45[2] * _46[2]]); // Compute final noise value at P var g2 = __.FM.float_3_1_1_1(__.add(a0[0] * x0[0], h[0] * x0[1]), __.add(a0[1] * x1[0], h[1] * x1[1]), __.add(a0[2] * x2[0], h[2] * x2[1])); return 130.0 * (0, std_math_1.dot)(m, g2); }; noise.prototype.clone = function () { return new noise({}); }; noise.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_26913_noise\\",\\"fields\\":[]}"); }; return noise; }()); exports.noise = noise; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_26913_noise\\",\\"fields\\":[]}"), noise) ; var PERLIN_YWRAPB = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_YWRAPB", function () { return (4 | 0); }, function () { return PERLIN_YWRAPB; }) | 0); var PERLIN_YWRAP = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_YWRAP", function () { return (1 | 0) << PERLIN_YWRAPB; }, function () { return PERLIN_YWRAP; }) | 0); var PERLIN_ZWRAPB = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_ZWRAPB", function () { return (8 | 0); }, function () { return PERLIN_ZWRAPB; }) | 0); var PERLIN_ZWRAP = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_ZWRAP", function () { return (1 | 0) << PERLIN_ZWRAPB; }, function () { return PERLIN_ZWRAP; }) | 0); var PERLIN_SIZE = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "PERLIN_SIZE", function () { return (4095 | 0); }, function () { return PERLIN_SIZE; }) | 0); var perlin_octaves = ((0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "perlin_octaves", function () { return (4 | 0); }, function () { return perlin_octaves; }) | 0); // default to medium smooth var perlin_amp_falloff = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "perlin_amp_falloff", function () { return 0.5; }, function () { return perlin_amp_falloff; }); // 50% reduction/octave function scaled_cosine(i) { return 0.5 * (1.0 - Math.cos(i * PI)); } var perlin = (0, std___std_all_1.globalVarInit)("_slash__std_slash_common_dot_ts", "perlin", function () { return (0, buffer_1.buffer)(PERLIN_SIZE + (1 | 0), "float", __assign({}, JSON.parse("{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}"))); }, function () { return perlin; }); for (var i = (0 | 0); i < PERLIN_SIZE + (1 | 0); i++) { perlin.__index_assign(i, (0, std_math_1.rand)(i)); } // // By Morgan McGuire @morgan3d, http://graphicscodex.com // function hash(n) { return (0, std_math_1.frac)(Math.sin(n) * (1e4 | 0)); } function hash2(p) { return (0, std_math_1.frac)((1e4 | 0) * Math.sin(17.0 * p[0] + p[1] * 0.1) * (0.1 + Math.abs(Math.sin(p[1] * 13.0 + p[0])))); } function hash3(p) { var h = (0, std_math_1.dot)(p, __.FM.float_3_1_1_1(__.float(127.1), __.float(311.7), __.float(74.7))); return (0, std_math_1.frac)(Math.sin(h) * 43758.5453123); } /* impl noise */ function mod289_1(x) { return x - Math.floor(x * (1.0 / 289.0)) * 289.0; } function mod289_4(x) { var _a, _b, _c, _d, _e, _f, _g; return _a = x, _b = (_c = (_e = (_f = x, _g = (1.0 / 289.0), [_f[0] * _g, _f[1] * _g, _f[2] * _g, _f[3] * _g]), [Math.floor(_e[0]), Math.floor(_e[1]), Math.floor(_e[2]), Math.floor(_e[3])]), _d = 289.0, [_c[0] * _d, _c[1] * _d, _c[2] * _d, _c[3] * _d]), [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2], _a[3] - _b[3]]; } function perm(x) { var _a, _b, _c, _d, _e, _f; return mod289_4((_a = (_c = (_e = x, _f = 34.0, [_e[0] * _f, _e[1] * _f, _e[2] * _f, _e[3] * _f]), _d = 1.0, [_c[0] + _d, _c[1] + _d, _c[2] + _d, _c[3] + _d]), _b = x, [_a[0] * _b[0], _a[1] * _b[1], _a[2] * _b[2], _a[3] * _b[3]])); } function mod289_3(x) { var _a, _b, _c, _d, _e, _f, _g; return _a = x, _b = (_c = (_e = (_f = x, _g = (1.0 / 289.0), [_f[0] * _g, _f[1] * _g, _f[2] * _g]), [Math.floor(_e[0]), Math.floor(_e[1]), Math.floor(_e[2])]), _d = 289.0, [_c[0] * _d, _c[1] * _d, _c[2] * _d]), [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]; } function mod289_2(x) { var _a, _b, _c, _d, _e, _f, _g; return _a = x, _b = (_c = (_e = (_f = x, _g = (1.0 / 289.0), [_f[0] * _g, _f[1] * _g]), [Math.floor(_e[0]), Math.floor(_e[1])]), _d = 289.0, [_c[0] * _d, _c[1] * _d]), [_a[0] - _b[0], _a[1] - _b[1]]; } function permute(x) { var _a, _b, _c, _d, _e, _f; return mod289_3((_a = (_c = (_e = x, _f = 34.0, [_e[0] * _f, _e[1] * _f, _e[2] * _f]), _d = 1.0, [_c[0] + _d, _c[1] + _d, _c[2] + _d]), _b = x, [_a[0] * _b[0], _a[1] * _b[1], _a[2] * _b[2]])); } function taylorInvSqrt(r) { var _a, _b, _c, _d; return _a = 1.79284291400159, _b = (_c = 0.85373472095314, _d = r, [_c * _d[0], _c * _d[1], _c * _d[2]]), [_a - _b[0], _a - _b[1], _a - _b[2]]; } var matrix = /** @class */ (function () { function matrix(data) { } matrix.lookAt = function (from, to, up) { var _a, _b, _c, _d; var zAxis = (0, std_math_1.normalize)((_a = from, _b = to, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]])); var xAxis = (0, std_math_1.normalize)((0, std_math_1.cross)(up, zAxis)); var yAxis = (0, std_math_1.normalize)((0, std_math_1.cross)(zAxis, xAxis)); var dst = __.float4x4(); dst.__index((0 | 0)).__index_assign((0 | 0), xAxis[0]); dst.__index((0 | 0)).__index_assign((1 | 0), yAxis[0]); dst.__index((0 | 0)).__index_assign((2 | 0), zAxis[0]); dst.__index((0 | 0)).__index_assign((3 | 0), (0 | 0)); dst.__index((1 | 0)).__index_assign((0 | 0), xAxis[1]); dst.__index((1 | 0)).__index_assign((1 | 0), yAxis[1]); dst.__index((1 | 0)).__index_assign((2 | 0), zAxis[1]); dst.__index((1 | 0)).__index_assign((3 | 0), (0 | 0)); dst.__index((2 | 0)).__index_assign((0 | 0), xAxis[2]); dst.__index((2 | 0)).__index_assign((1 | 0), yAxis[2]); dst.__index((2 | 0)).__index_assign((2 | 0), zAxis[2]); dst.__index((2 | 0)).__index_assign((3 | 0), (0 | 0)); dst.__index((3 | 0)).__index_assign((0 | 0), (__.FM.negate_1((xAxis[0] * from[0] + xAxis[1] * from[1] + xAxis[2] * from[2])))); dst.__index((3 | 0)).__index_assign((1 | 0), (__.FM.negate_1((yAxis[0] * from[0] + yAxis[1] * from[1] + yAxis[2] * from[2])))); dst.__index((3 | 0)).__index_assign((2 | 0), (__.FM.negate_1((zAxis[0] * from[0] + zAxis[1] * from[1] + zAxis[2] * from[2])))); dst.__index((3 | 0)).__index_assign((3 | 0), (1 | 0)); return dst; var forward = (0, std_math_1.normalize)((_c = from, _d = to, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]])); var right = (0, std_math_1.normalize)((0, std_math_1.cross)(up, forward)); var newup = (0, std_math_1.cross)(forward, right); var m = __.float4x4(); m.__index((0 | 0)).__index_assign((0 | 0), right[0]), m.__index((0 | 0)).__index_assign((1 | 0), right[1]), m.__index((0 | 0)).__index_assign((2 | 0), right[2]); m.__index((1 | 0)).__index_assign((0 | 0), newup[0]), m.__index((1 | 0)).__index_assign((1 | 0), newup[1]), m.__index((1 | 0)).__index_assign((2 | 0), newup[2]); m.__index((2 | 0)).__index_assign((0 | 0), forward[0]), m.__index((2 | 0)).__index_assign((1 | 0), forward[1]), m.__index((2 | 0)).__index_assign((2 | 0), forward[2]); m.__index((3 | 0)).__index_assign((0 | 0), from[0]), m.__index((3 | 0)).__index_assign((1 | 0), from[1]), m.__index((3 | 0)).__index_assign((2 | 0), from[2]); return m; }; matrix.perspective = function (fov, aspect, near, far) { // let scale = 1.0 / tan(fov * 0.5 * PI / 180); // let M = float4x4(); // M[0][0] = scale; //scale the x coordinates of the projected point // M[1][1] = scale * aspect; //scale the y coordinates of the projected point // M[2][2] = -far / (far - near); //used to remap z to [0,1] // M[3][2] = -far * near / (far - near); //used to remap z [0,1] // M[2][3] = -1; //set w = -z // M[3][3] = 0; //return M; var fovRad = (0, std_math_1.radians)(fov); var tanFov = Math.tan(fovRad * 0.5); var matrx = __.float4x4(1.0 / (tanFov * aspect), (0 | 0), (0 | 0), (0 | 0), (0 | 0), 1.0 / tanFov, (0 | 0), (0 | 0), (0 | 0), (0 | 0), (__.FM.negate_1(((far + near) / (far - near)))), (__.FM.negate_1((1 | 0))), (0 | 0), (0 | 0), (__.FM.negate_1((((2 | 0) * (near * far)) / (far - near)))), (0 | 0)); return matrx; }; matrix.perspectiveReverseZ = function (fov, aspect, near) { // let far = 10000000.0; // let M = float4x4(); // M[0][0] = scale; //scale the x coordinates of the projected point // M[1][1] = scale * aspect; //scale the y coordinates of the projected point // M[2][2] = (-far / (far - near)) * -1; //used to remap z to [0,1] // M[3][2] = -far * near / (far - near); //used to remap z [0,1] // M[2][3] = 0; //set w = -z // M[3][3] = 0; // return M; var matrx = __.mul(__.float4x4((1 | 0), (0 | 0), (0 | 0), (0 | 0), (0 | 0), (1 | 0), (0 | 0), (0 | 0), (0 | 0), (0 | 0), (__.FM.negate_1((1 | 0))), (0 | 0), (0 | 0), (0 | 0), (1 | 0), (1 | 0)), matrix.perspective(fov, aspect, near, 10000000.0)); return matrx; }; matrix.prototype.clone = function () { return new matrix({}); }; matrix.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_44684_matrix\\",\\"fields\\":[]}"); }; return matrix; }()); exports.matrix = matrix; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_44684_matrix\\",\\"fields\\":[]}"), matrix) ; /* impl matrix */ /** * Uses Super Sampling Anti Aliasing to smooth out the image. */ function screenAA(inScreenPos, gridSize, func) { var _a, _b, _c, _d, _e, _f, _g, _h; var weightSum = 0.0; var accumulatedColor = __.FM.float_4_1_1_1_1(__.int(0), __.int(0), __.int(0), __.int(0)); for (var y = (0 | 0); y < gridSize; y++) { for (var x = (0 | 0); x < gridSize; x++) { var offset = __.FM.float_2_1_1(__.div((x + 0.5 - gridSize * 0.5), gridSize), __.div((y + 0.5 - gridSize * 0.5), gridSize)); var weight = Math.exp((__.FM.negate_1((0, std_math_1.dot)(offset, offset))) * (5 | 0)); // Gaussian weight accumulatedColor = (_a = accumulatedColor, _b = (_c = func((_e = inScreenPos, _f = offset, [_e[0] + _f[0], _e[1] + _f[1]])), _d = weight, [_c[0] * _d, _c[1] * _d, _c[2] * _d, _c[3] * _d]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2], _a[3] + _b[3]]); weightSum = weightSum + weight; } } return _g = accumulatedColor, _h = weightSum, [_g[0] / _h, _g[1] / _h, _g[2] / _h, _g[3] / _h]; } exports.screenAA = screenAA; ; // Color conversion helpers // A color = float4 containing rgba values in the range [0, 1] // All functions have an extra alpha functon and a reverse // i.e. hsl, hsla, hslFromColor, hslaFromColor // fn hsl(v: float3) -> float4 function hsl(v) { return hsla(__.makeVector(v, (1 | 0))); } exports.hsl = hsl; ; function hsla(v) { var h = v[0]; var s = v[1]; var l = v[2]; var a = v[3]; var c = ((1 | 0) - Math.abs((2 | 0) * l - (1 | 0))) * s; var x = c * ((1 | 0) - Math.abs(((h / (60 | 0)) % (2 | 0)) - (1 | 0))); var m = l - c / (2 | 0); var r = 0.0; var g = 0.0; var b = 0.0; if (h < (60 | 0)) { r = c; g = x; b = (0 | 0); } else if (h < (120 | 0)) { r = x; g = c; b = (0 | 0); } else if (h < (180 | 0)) { r = (0 | 0); g = c; b = x; } else if (h < (240 | 0)) { r = (0 | 0); g = x; b = c; } else if (h < (300 | 0)) { r = x; g = (0 | 0); b = c; } else { r = c; g = (0 | 0); b = x; } return __.FM.float_4_1_1_1_1(__.add(r, m), __.add(g, m), __.add(b, m), a); } exports.hsla = hsla; ; function hslFromColor(c) { var r = c[0]; var g = c[1]; var b = c[2]; var a = c[3]; var mx = (0, std_math_1.max)(r, (0, std_math_1.max)(g, b)); var mn = (0, std_math_1.min)(r, (0, std_math_1.min)(g, b)); var h = 0.0; var s = 0.0; var l = (mx + mn) / (2 | 0); if (mx == mn) { h = (0 | 0); s = (0 | 0); } else { var d = mx - mn; s = (l > 0.5) ? d / ((2 | 0) - mx - mn) : d / (mx + mn); if (mx == r) { h = (g - b) / d + ((g < b) ? (6 | 0) : (0 | 0)); } else if (mx == g) { h = (b - r) / d + (2 | 0); } else if (mx == b) { h = (r - g) / d + (4 | 0); } h = h / (6 | 0); } return __.FM.float_3_1_1_1(__.mul(h, (360 | 0)), s, l); } exports.hslFromColor = hslFromColor; ; function hslaFromColor(c) { var hsl = hslFromColor(c); return __.FM.float_4_3_1(hsl, __.swizzle(c, 'a')); } exports.hslaFromColor = hslaFromColor; ; function hsv(v) { return hsva(__.makeVector(v, (1 | 0))); } exports.hsv = hsv; ; function hsva(val) { var h = val[0]; var s = val[1]; var v = val[2]; var a = val[3]; var c = v * s; var x = c * ((1 | 0) - Math.abs(h / (60 | 0) % (2 | 0) - (1 | 0))); var m = v - c; var r = 0.0; var g = 0.0; var b = 0.0; if (h < (60 | 0)) { r = c; g = x; b = (0 | 0); } else if (h < (120 | 0)) { r = x; g = c; b = (0 | 0); } else if (h < (180 | 0)) { r = (0 | 0); g = c; b = x; } else if (h < (240 | 0)) { r = (0 | 0); g = x; b = c; } else if (h < (300 | 0)) { r = x; g = (0 | 0); b = c; } else { r = c; g = (0 | 0); b = x; } return __.FM.float_4_1_1_1_1(__.add(r, m), __.add(g, m), __.add(b, m), a); } exports.hsva = hsva; ; function hsvFromColor(c) { var r = c[0]; var g = c[1]; var b = c[2]; var mx = (0, std_math_1.max)(r, (0, std_math_1.max)(g, b)); var mn = (0, std_math_1.min)(r, (0, std_math_1.min)(g, b)); var h = 0.0; var s = 0.0; var v = mx; var d = mx - mn; s = (mx == (0 | 0)) ? (0 | 0) : d / mx; if (mx == mn) { h = (0 | 0); } else { if (mx == r) { h = (g - b) / d + ((g < b) ? (6 | 0) : (0 | 0)); } else if (mx == g) { h = (b - r) / d + (2 | 0); } else if (mx == b) { h = (r - g) / d + (4 | 0); } h = h / (6 | 0); } return __.FM.float_3_1_1_1(__.mul(h, (360 | 0)), s, v); } exports.hsvFromColor = hsvFromColor; ; function hsvaFromColor(c) { var hsv = hsvFromColor(c); return __.FM.float_4_3_1(hsv, __.swizzle(c, 'a')); } exports.hsvaFromColor = hsvaFromColor; ; function rgb(v) { return __.FM.float_4_3_1(__.div(v, 255.0), __.int(1)); } exports.rgb = rgb; ; function rgba(v) { return __.FM.float_4_4(__.div(v, 255.0)); } exports.rgba = rgba; ; function rgbFromColor(c) { var _a, _b, _c; return _a = (_c = c, [_c[0], _c[1], _c[2]]), _b = 255.0, [_a[0] * _b, _a[1] * _b, _a[2] * _b]; } exports.rgbFromColor = rgbFromColor; ; function rgbaFromColor(c) { var _a, _b; return _a = c, _b = 255.0, [_a[0] * _b, _a[1] * _b, _a[2] * _b, _a[3] * _b]; } exports.rgbaFromColor = rgbaFromColor; ; function cmyk(v) { var c = v[0]; var m = v[1]; var y = v[2]; var k = v[3]; var r = (1 | 0) - (0, std_math_1.min)((1 | 0), c * ((1 | 0) - k) + k); var g = (1 | 0) - (0, std_math_1.min)((1 | 0), m * ((1 | 0) - k) + k); var b = (1 | 0) - (0, std_math_1.min)((1 | 0), y * ((1 | 0) - k) + k); return __.FM.float_4_1_1_1_1(r, g, b, __.int(1)); } exports.cmyk = cmyk; ; function cmykFromColor(c) { var r = c[0]; var g = c[1]; var b = c[2]; var k = (1 | 0) - (0, std_math_1.max)(r, (0, std_math_1.max)(g, b)); var c1 = ((1 | 0) - r - k) / ((1 | 0) - k); var m = ((1 | 0) - g - k) / ((1 | 0) - k); var y = ((1 | 0) - b - k) / ((1 | 0) - k); return __.FM.float_4_1_1_1_1(c1, m, y, k); } exports.cmykFromColor = cmykFromColor; ; function hex(v) { var r = (v >> (16 | 0)) & (0xFF | 0); var g = (v >> (8 | 0)) & (0xFF | 0); var b = v & (0xFF | 0); return __.FM.float_4_1_1_1_1(__.div(r, 255.0), __.div(g, 255.0), __.div(b, 255.0), __.float(1.0)); } exports.hex = hex; ; function hexFromColor(c) { var r = (__.mul(c[0], 255.0) | 0); var g = (__.mul(c[1], 255.0) | 0); var b = (__.mul(c[2], 255.0) | 0); return (r << (16 | 0)) | (g << (8 | 0)) | b; } exports.hexFromColor = hexFromColor; ; /** * Returns sin remapped to [0, 1] */ function sin1(v) { return (Math.sin(v) + (1 | 0)) * 0.5; } exports.sin1 = sin1; ; /** * Returns cos remapped to [0, 1] */ function cos1(v) { return (Math.cos(v) + (1 | 0)) * 0.5; } exports.cos1 = cos1; ; /** * Returns tan remapped to [0, 1] */ function tan1(v) { return (Math.tan(v) + (1 | 0)) * 0.5; } exports.tan1 = tan1; ; function remap(v, low1, high1, low2, high2) { return low2 + (v - low1) * (high2 - low2) / (high1 - low1); } exports.remap = remap; ; function remap1(v, low, high) { return remap(v, low, high, (0 | 0), (1 | 0)); } exports.remap1 = remap1; ; var color = /** @class */ (function () { function color(data) { } color.prototype.clone = function () { return new color({}); }; color.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_57436_color\\",\\"fields\\":[[\\"slate50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}]]}"); }; color.slate50 = __.FM.float_4_1_1_1_1(__.float(0.9725490196078431), __.float(0.9803921568627451), __.float(0.9882352941176471), __.int(1)); color.slate100 = __.FM.float_4_1_1_1_1(__.float(0.9450980392156862), __.float(0.9607843137254902), __.float(0.9764705882352941), __.int(1)); color.slate200 = __.FM.float_4_1_1_1_1(__.float(0.8862745098039215), __.float(0.9098039215686274), __.float(0.9411764705882353), __.int(1)); color.slate300 = __.FM.float_4_1_1_1_1(__.float(0.796078431372549), __.float(0.8352941176470589), __.float(0.8823529411764706), __.int(1)); color.slate400 = __.FM.float_4_1_1_1_1(__.float(0.5803921568627451), __.float(0.6392156862745098), __.float(0.7215686274509804), __.int(1)); color.slate500 = __.FM.float_4_1_1_1_1(__.float(0.39215686274509803), __.float(0.4549019607843137), __.float(0.5450980392156862), __.int(1)); color.slate600 = __.FM.float_4_1_1_1_1(__.float(0.2784313725490196), __.float(0.3333333333333333), __.float(0.4117647058823529), __.int(1)); color.slate700 = __.FM.float_4_1_1_1_1(__.float(0.2), __.float(0.2549019607843137), __.float(0.3333333333333333), __.int(1)); color.slate800 = __.FM.float_4_1_1_1_1(__.float(0.11764705882352941), __.float(0.1607843137254902), __.float(0.23137254901960785), __.int(1)); color.slate900 = __.FM.float_4_1_1_1_1(__.float(0.058823529411764705), __.float(0.09019607843137255), __.float(0.16470588235294117), __.int(1)); color.slate950 = __.FM.float_4_1_1_1_1(__.float(0.00784313725490196), __.float(0.023529411764705882), __.float(0.09019607843137255), __.int(1)); color.gray50 = __.FM.float_4_1_1_1_1(__.float(0.9764705882352941), __.float(0.9803921568627451), __.float(0.984313725490196), __.int(1)); color.gray100 = __.FM.float_4_1_1_1_1(__.float(0.9529411764705882), __.float(0.9568627450980393), __.float(0.9647058823529412), __.int(1)); color.gray200 = __.FM.float_4_1_1_1_1(__.float(0.8980392156862745), __.float(0.9058823529411765), __.float(0.9215686274509803), __.int(1)); color.gray300 = __.FM.float_4_1_1_1_1(__.float(0.8196078431372549), __.float(0.8352941176470589), __.float(0.8588235294117647), __.int(1)); color.gray400 = __.FM.float_4_1_1_1_1(__.float(0.611764705882353), __.float(0.6392156862745098), __.float(0.6862745098039216), __.int(1)); color.gray500 = __.FM.float_4_1_1_1_1(__.float(0.4196078431372549), __.float(0.4470588235294118), __.float(0.5019607843137255), __.int(1)); color.gray600 = __.FM.float_4_1_1_1_1(__.float(0.29411764705882354), __.float(0.3333333333333333), __.float(0.38823529411764707), __.int(1)); color.gray700 = __.FM.float_4_1_1_1_1(__.float(0.21568627450980393), __.float(0.2549019607843137), __.float(0.3176470588235294), __.int(1)); color.gray800 = __.FM.float_4_1_1_1_1(__.float(0.12156862745098039), __.float(0.1607843137254902), __.float(0.21568627450980393), __.int(1)); color.gray900 = __.FM.float_4_1_1_1_1(__.float(0.06666666666666667), __.float(0.09411764705882353), __.float(0.15294117647058825), __.int(1)); color.gray950 = __.FM.float_4_1_1_1_1(__.float(0.011764705882352941), __.float(0.027450980392156862), __.float(0.07058823529411765), __.int(1)); color.zinc50 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9803921568627451), __.float(0.9803921568627451), __.int(1)); color.zinc100 = __.FM.float_4_1_1_1_1(__.float(0.9568627450980393), __.float(0.9568627450980393), __.float(0.9607843137254902), __.int(1)); color.zinc200 = __.FM.float_4_1_1_1_1(__.float(0.8941176470588236), __.float(0.8941176470588236), __.float(0.9058823529411765), __.int(1)); color.zinc300 = __.FM.float_4_1_1_1_1(__.float(0.8313725490196079), __.float(0.8313725490196079), __.float(0.8470588235294118), __.int(1)); color.zinc400 = __.FM.float_4_1_1_1_1(__.float(0.6313725490196078), __.float(0.6313725490196078), __.float(0.6666666666666666), __.int(1)); color.zinc500 = __.FM.float_4_1_1_1_1(__.float(0.44313725490196076), __.float(0.44313725490196076), __.float(0.47843137254901963), __.int(1)); color.zinc600 = __.FM.float_4_1_1_1_1(__.float(0.3215686274509804), __.float(0.3215686274509804), __.float(0.3568627450980392), __.int(1)); color.zinc700 = __.FM.float_4_1_1_1_1(__.float(0.24705882352941178), __.float(0.24705882352941178), __.float(0.27450980392156865), __.int(1)); color.zinc800 = __.FM.float_4_1_1_1_1(__.float(0.15294117647058825), __.float(0.15294117647058825), __.float(0.16470588235294117), __.int(1)); color.zinc900 = __.FM.float_4_1_1_1_1(__.float(0.09411764705882353), __.float(0.09411764705882353), __.float(0.10588235294117647), __.int(1)); color.zinc950 = __.FM.float_4_1_1_1_1(__.float(0.03529411764705882), __.float(0.03529411764705882), __.float(0.043137254901960784), __.int(1)); color.neutral50 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9803921568627451), __.float(0.9803921568627451), __.int(1)); color.neutral100 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.9607843137254902), __.float(0.9607843137254902), __.int(1)); color.neutral200 = __.FM.float_4_1_1_1_1(__.float(0.8980392156862745), __.float(0.8980392156862745), __.float(0.8980392156862745), __.int(1)); color.neutral300 = __.FM.float_4_1_1_1_1(__.float(0.8313725490196079), __.float(0.8313725490196079), __.float(0.8313725490196079), __.int(1)); color.neutral400 = __.FM.float_4_1_1_1_1(__.float(0.6392156862745098), __.float(0.6392156862745098), __.float(0.6392156862745098), __.int(1)); color.neutral500 = __.FM.float_4_1_1_1_1(__.float(0.45098039215686275), __.float(0.45098039215686275), __.float(0.45098039215686275), __.int(1)); color.neutral600 = __.FM.float_4_1_1_1_1(__.float(0.3215686274509804), __.float(0.3215686274509804), __.float(0.3215686274509804), __.int(1)); color.neutral700 = __.FM.float_4_1_1_1_1(__.float(0.25098039215686274), __.float(0.25098039215686274), __.float(0.25098039215686274), __.int(1)); color.neutral800 = __.FM.float_4_1_1_1_1(__.float(0.14901960784313725), __.float(0.14901960784313725), __.float(0.14901960784313725), __.int(1)); color.neutral900 = __.FM.float_4_1_1_1_1(__.float(0.09019607843137255), __.float(0.09019607843137255), __.float(0.09019607843137255), __.int(1)); color.neutral950 = __.FM.float_4_1_1_1_1(__.float(0.0392156862745098), __.float(0.0392156862745098), __.float(0.0392156862745098), __.int(1)); color.stone50 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9803921568627451), __.float(0.9764705882352941), __.int(1)); color.stone100 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.9607843137254902), __.float(0.9568627450980393), __.int(1)); color.stone200 = __.FM.float_4_1_1_1_1(__.float(0.9058823529411765), __.float(0.8980392156862745), __.float(0.8941176470588236), __.int(1)); color.stone300 = __.FM.float_4_1_1_1_1(__.float(0.8392156862745098), __.float(0.8274509803921568), __.float(0.8196078431372549), __.int(1)); color.stone400 = __.FM.float_4_1_1_1_1(__.float(0.6588235294117647), __.float(0.6352941176470588), __.float(0.6196078431372549), __.int(1)); color.stone500 = __.FM.float_4_1_1_1_1(__.float(0.47058823529411764), __.float(0.44313725490196076), __.float(0.4235294117647059), __.int(1)); color.stone600 = __.FM.float_4_1_1_1_1(__.float(0.3411764705882353), __.float(0.3254901960784314), __.float(0.3058823529411765), __.int(1)); color.stone700 = __.FM.float_4_1_1_1_1(__.float(0.26666666666666666), __.float(0.25098039215686274), __.float(0.23529411764705882), __.int(1)); color.stone800 = __.FM.float_4_1_1_1_1(__.float(0.1607843137254902), __.float(0.1450980392156863), __.float(0.1411764705882353), __.int(1)); color.stone900 = __.FM.float_4_1_1_1_1(__.float(0.10980392156862745), __.float(0.09803921568627451), __.float(0.09019607843137255), __.int(1)); color.stone950 = __.FM.float_4_1_1_1_1(__.float(0.047058823529411764), __.float(0.0392156862745098), __.float(0.03529411764705882), __.int(1)); color.red50 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9490196078431372), __.float(0.9490196078431372), __.int(1)); color.red100 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.8862745098039215), __.float(0.8862745098039215), __.int(1)); color.red200 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.792156862745098), __.float(0.792156862745098), __.int(1)); color.red300 = __.FM.float_4_1_1_1_1(__.float(0.9882352941176471), __.float(0.6470588235294118), __.float(0.6470588235294118), __.int(1)); color.red400 = __.FM.float_4_1_1_1_1(__.float(0.9725490196078431), __.float(0.44313725490196076), __.float(0.44313725490196076), __.int(1)); color.red500 = __.FM.float_4_1_1_1_1(__.float(0.9372549019607843), __.float(0.26666666666666666), __.float(0.26666666666666666), __.int(1)); color.red600 = __.FM.float_4_1_1_1_1(__.float(0.8627450980392157), __.float(0.14901960784313725), __.float(0.14901960784313725), __.int(1)); color.red700 = __.FM.float_4_1_1_1_1(__.float(0.7254901960784313), __.float(0.10980392156862745), __.float(0.10980392156862745), __.int(1)); color.red800 = __.FM.float_4_1_1_1_1(__.float(0.6), __.float(0.10588235294117647), __.float(0.10588235294117647), __.int(1)); color.red900 = __.FM.float_4_1_1_1_1(__.float(0.4980392156862745), __.float(0.11372549019607843), __.float(0.11372549019607843), __.int(1)); color.red950 = __.FM.float_4_1_1_1_1(__.float(0.27058823529411763), __.float(0.0392156862745098), __.float(0.0392156862745098), __.int(1)); color.orange50 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.9686274509803922), __.float(0.9294117647058824), __.int(1)); color.orange100 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.9294117647058824), __.float(0.8352941176470589), __.int(1)); color.orange200 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.8431372549019608), __.float(0.6666666666666666), __.int(1)); color.orange300 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.7294117647058823), __.float(0.4549019607843137), __.int(1)); color.orange400 = __.FM.float_4_1_1_1_1(__.float(0.984313725490196), __.float(0.5725490196078431), __.float(0.23529411764705882), __.int(1)); color.orange500 = __.FM.float_4_1_1_1_1(__.float(0.9764705882352941), __.float(0.45098039215686275), __.float(0.08627450980392157), __.int(1)); color.orange600 = __.FM.float_4_1_1_1_1(__.float(0.9176470588235294), __.float(0.34509803921568627), __.float(0.047058823529411764), __.int(1)); color.orange700 = __.FM.float_4_1_1_1_1(__.float(0.7607843137254902), __.float(0.2549019607843137), __.float(0.047058823529411764), __.int(1)); color.orange800 = __.FM.float_4_1_1_1_1(__.float(0.6039215686274509), __.float(0.20392156862745098), __.float(0.07058823529411765), __.int(1)); color.orange900 = __.FM.float_4_1_1_1_1(__.float(0.48627450980392156), __.float(0.17647058823529413), __.float(0.07058823529411765), __.int(1)); color.orange950 = __.FM.float_4_1_1_1_1(__.float(0.2627450980392157), __.float(0.0784313725490196), __.float(0.027450980392156862), __.int(1)); color.amber50 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.984313725490196), __.float(0.9215686274509803), __.int(1)); color.amber100 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9529411764705882), __.float(0.7803921568627451), __.int(1)); color.amber200 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.9019607843137255), __.float(0.5411764705882353), __.int(1)); color.amber300 = __.FM.float_4_1_1_1_1(__.float(0.9882352941176471), __.float(0.8274509803921568), __.float(0.30196078431372547), __.int(1)); color.amber400 = __.FM.float_4_1_1_1_1(__.float(0.984313725490196), __.float(0.7490196078431373), __.float(0.1411764705882353), __.int(1)); color.amber500 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.6196078431372549), __.float(0.043137254901960784), __.int(1)); color.amber600 = __.FM.float_4_1_1_1_1(__.float(0.8509803921568627), __.float(0.4666666666666667), __.float(0.023529411764705882), __.int(1)); color.amber700 = __.FM.float_4_1_1_1_1(__.float(0.7058823529411765), __.float(0.3254901960784314), __.float(0.03529411764705882), __.int(1)); color.amber800 = __.FM.float_4_1_1_1_1(__.float(0.5725490196078431), __.float(0.25098039215686274), __.float(0.054901960784313725), __.int(1)); color.amber900 = __.FM.float_4_1_1_1_1(__.float(0.47058823529411764), __.float(0.20784313725490197), __.float(0.058823529411764705), __.int(1)); color.amber950 = __.FM.float_4_1_1_1_1(__.float(0.27058823529411763), __.float(0.10196078431372549), __.float(0.011764705882352941), __.int(1)); color.yellow50 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9882352941176471), __.float(0.9098039215686274), __.int(1)); color.yellow100 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9764705882352941), __.float(0.7647058823529411), __.int(1)); color.yellow200 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.9411764705882353), __.float(0.5411764705882353), __.int(1)); color.yellow300 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.8784313725490196), __.float(0.2784313725490196), __.int(1)); color.yellow400 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.8), __.float(0.08235294117647059), __.int(1)); color.yellow500 = __.FM.float_4_1_1_1_1(__.float(0.9176470588235294), __.float(0.7019607843137254), __.float(0.03137254901960784), __.int(1)); color.yellow600 = __.FM.float_4_1_1_1_1(__.float(0.792156862745098), __.float(0.5411764705882353), __.float(0.01568627450980392), __.int(1)); color.yellow700 = __.FM.float_4_1_1_1_1(__.float(0.6313725490196078), __.float(0.3843137254901961), __.float(0.027450980392156862), __.int(1)); color.yellow800 = __.FM.float_4_1_1_1_1(__.float(0.5215686274509804), __.float(0.30196078431372547), __.float(0.054901960784313725), __.int(1)); color.yellow900 = __.FM.float_4_1_1_1_1(__.float(0.44313725490196076), __.float(0.24705882352941178), __.float(0.07058823529411765), __.int(1)); color.yellow950 = __.FM.float_4_1_1_1_1(__.float(0.25882352941176473), __.float(0.12549019607843137), __.float(0.023529411764705882), __.int(1)); color.lime50 = __.FM.float_4_1_1_1_1(__.float(0.9686274509803922), __.float(0.996078431372549), __.float(0.9058823529411765), __.int(1)); color.lime100 = __.FM.float_4_1_1_1_1(__.float(0.9254901960784314), __.float(0.9882352941176471), __.float(0.796078431372549), __.int(1)); color.lime200 = __.FM.float_4_1_1_1_1(__.float(0.8509803921568627), __.float(0.9764705882352941), __.float(0.615686274509804), __.int(1)); color.lime300 = __.FM.float_4_1_1_1_1(__.float(0.7450980392156863), __.float(0.9490196078431372), __.float(0.39215686274509803), __.int(1)); color.lime400 = __.FM.float_4_1_1_1_1(__.float(0.6392156862745098), __.float(0.9019607843137255), __.float(0.20784313725490197), __.int(1)); color.lime500 = __.FM.float_4_1_1_1_1(__.float(0.5176470588235295), __.float(0.8), __.float(0.08627450980392157), __.int(1)); color.lime600 = __.FM.float_4_1_1_1_1(__.float(0.396078431372549), __.float(0.6392156862745098), __.float(0.050980392156862744), __.int(1)); color.lime700 = __.FM.float_4_1_1_1_1(__.float(0.30196078431372547), __.float(0.48627450980392156), __.float(0.058823529411764705), __.int(1)); color.lime800 = __.FM.float_4_1_1_1_1(__.float(0.24705882352941178), __.float(0.3843137254901961), __.float(0.07058823529411765), __.int(1)); color.lime900 = __.FM.float_4_1_1_1_1(__.float(0.21176470588235294), __.float(0.3254901960784314), __.float(0.0784313725490196), __.int(1)); color.lime950 = __.FM.float_4_1_1_1_1(__.float(0.10196078431372549), __.float(0.1803921568627451), __.float(0.0196078431372549), __.int(1)); color.green50 = __.FM.float_4_1_1_1_1(__.float(0.9411764705882353), __.float(0.9921568627450981), __.float(0.9568627450980393), __.int(1)); color.green100 = __.FM.float_4_1_1_1_1(__.float(0.8627450980392157), __.float(0.9882352941176471), __.float(0.9058823529411765), __.int(1)); color.green200 = __.FM.float_4_1_1_1_1(__.float(0.7333333333333333), __.float(0.9686274509803922), __.float(0.8156862745098039), __.int(1)); color.green300 = __.FM.float_4_1_1_1_1(__.float(0.5254901960784314), __.float(0.9372549019607843), __.float(0.6745098039215687), __.int(1)); color.green400 = __.FM.float_4_1_1_1_1(__.float(0.2901960784313726), __.float(0.8705882352941177), __.float(0.5019607843137255), __.int(1)); color.green500 = __.FM.float_4_1_1_1_1(__.float(0.13333333333333333), __.float(0.7725490196078432), __.float(0.3686274509803922), __.int(1)); color.green600 = __.FM.float_4_1_1_1_1(__.float(0.08627450980392157), __.float(0.6392156862745098), __.float(0.2901960784313726), __.int(1)); color.green700 = __.FM.float_4_1_1_1_1(__.float(0.08235294117647059), __.float(0.5019607843137255), __.float(0.23921568627450981), __.int(1)); color.green800 = __.FM.float_4_1_1_1_1(__.float(0.08627450980392157), __.float(0.396078431372549), __.float(0.20392156862745098), __.int(1)); color.green900 = __.FM.float_4_1_1_1_1(__.float(0.0784313725490196), __.float(0.3254901960784314), __.float(0.17647058823529413), __.int(1)); color.green950 = __.FM.float_4_1_1_1_1(__.float(0.0196078431372549), __.float(0.1803921568627451), __.float(0.08627450980392157), __.int(1)); color.emerald50 = __.FM.float_4_1_1_1_1(__.float(0.9254901960784314), __.float(0.9921568627450981), __.float(0.9607843137254902), __.int(1)); color.emerald100 = __.FM.float_4_1_1_1_1(__.float(0.8196078431372549), __.float(0.9803921568627451), __.float(0.8980392156862745), __.int(1)); color.emerald200 = __.FM.float_4_1_1_1_1(__.float(0.6549019607843137), __.float(0.9529411764705882), __.float(0.8156862745098039), __.int(1)); color.emerald300 = __.FM.float_4_1_1_1_1(__.float(0.43137254901960786), __.float(0.9058823529411765), __.float(0.7176470588235294), __.int(1)); color.emerald400 = __.FM.float_4_1_1_1_1(__.float(0.20392156862745098), __.float(0.8274509803921568), __.float(0.6), __.int(1)); color.emerald500 = __.FM.float_4_1_1_1_1(__.float(0.06274509803921569), __.float(0.7254901960784313), __.float(0.5058823529411764), __.int(1)); color.emerald600 = __.FM.float_4_1_1_1_1(__.float(0.0196078431372549), __.float(0.5882352941176471), __.float(0.4117647058823529), __.int(1)); color.emerald700 = __.FM.float_4_1_1_1_1(__.float(0.01568627450980392), __.float(0.47058823529411764), __.float(0.3411764705882353), __.int(1)); color.emerald800 = __.FM.float_4_1_1_1_1(__.float(0.023529411764705882), __.float(0.37254901960784315), __.float(0.27450980392156865), __.int(1)); color.emerald900 = __.FM.float_4_1_1_1_1(__.float(0.023529411764705882), __.float(0.3058823529411765), __.float(0.23137254901960785), __.int(1)); color.emerald950 = __.FM.float_4_1_1_1_1(__.float(0.00784313725490196), __.float(0.17254901960784313), __.float(0.13333333333333333), __.int(1)); color.teal50 = __.FM.float_4_1_1_1_1(__.float(0.9411764705882353), __.float(0.9921568627450981), __.float(0.9803921568627451), __.int(1)); color.teal100 = __.FM.float_4_1_1_1_1(__.float(0.8), __.float(0.984313725490196), __.float(0.9450980392156862), __.int(1)); color.teal200 = __.FM.float_4_1_1_1_1(__.float(0.6), __.float(0.9647058823529412), __.float(0.8941176470588236), __.int(1)); color.teal300 = __.FM.float_4_1_1_1_1(__.float(0.3686274509803922), __.float(0.9176470588235294), __.float(0.8313725490196079), __.int(1)); color.teal400 = __.FM.float_4_1_1_1_1(__.float(0.17647058823529413), __.float(0.8313725490196079), __.float(0.7490196078431373), __.int(1)); color.teal500 = __.FM.float_4_1_1_1_1(__.float(0.0784313725490196), __.float(0.7215686274509804), __.float(0.6509803921568628), __.int(1)); color.teal600 = __.FM.float_4_1_1_1_1(__.float(0.050980392156862744), __.float(0.5803921568627451), __.float(0.5333333333333333), __.int(1)); color.teal700 = __.FM.float_4_1_1_1_1(__.float(0.058823529411764705), __.float(0.4627450980392157), __.float(0.43137254901960786), __.int(1)); color.teal800 = __.FM.float_4_1_1_1_1(__.float(0.06666666666666667), __.float(0.3686274509803922), __.float(0.34901960784313724), __.int(1)); color.teal900 = __.FM.float_4_1_1_1_1(__.float(0.07450980392156863), __.float(0.3058823529411765), __.float(0.2901960784313726), __.int(1)); color.teal950 = __.FM.float_4_1_1_1_1(__.float(0.01568627450980392), __.float(0.1843137254901961), __.float(0.1803921568627451), __.int(1)); color.cyan50 = __.FM.float_4_1_1_1_1(__.float(0.9254901960784314), __.float(0.996078431372549), __.int(1), __.int(1)); color.cyan100 = __.FM.float_4_1_1_1_1(__.float(0.8117647058823529), __.float(0.9803921568627451), __.float(0.996078431372549), __.int(1)); color.cyan200 = __.FM.float_4_1_1_1_1(__.float(0.6470588235294118), __.float(0.9529411764705882), __.float(0.9882352941176471), __.int(1)); color.cyan300 = __.FM.float_4_1_1_1_1(__.float(0.403921568627451), __.float(0.9098039215686274), __.float(0.9764705882352941), __.int(1)); color.cyan400 = __.FM.float_4_1_1_1_1(__.float(0.13333333333333333), __.float(0.8274509803921568), __.float(0.9333333333333333), __.int(1)); color.cyan500 = __.FM.float_4_1_1_1_1(__.float(0.023529411764705882), __.float(0.7137254901960784), __.float(0.8313725490196079), __.int(1)); color.cyan600 = __.FM.float_4_1_1_1_1(__.float(0.03137254901960784), __.float(0.5686274509803921), __.float(0.6980392156862745), __.int(1)); color.cyan700 = __.FM.float_4_1_1_1_1(__.float(0.054901960784313725), __.float(0.4549019607843137), __.float(0.5647058823529412), __.int(1)); color.cyan800 = __.FM.float_4_1_1_1_1(__.float(0.08235294117647059), __.float(0.3686274509803922), __.float(0.4588235294117647), __.int(1)); color.cyan900 = __.FM.float_4_1_1_1_1(__.float(0.08627450980392157), __.float(0.3058823529411765), __.float(0.38823529411764707), __.int(1)); color.cyan950 = __.FM.float_4_1_1_1_1(__.float(0.03137254901960784), __.float(0.2), __.float(0.26666666666666666), __.int(1)); color.sky50 = __.FM.float_4_1_1_1_1(__.float(0.9411764705882353), __.float(0.9764705882352941), __.int(1), __.int(1)); color.sky100 = __.FM.float_4_1_1_1_1(__.float(0.8784313725490196), __.float(0.9490196078431372), __.float(0.996078431372549), __.int(1)); color.sky200 = __.FM.float_4_1_1_1_1(__.float(0.7294117647058823), __.float(0.9019607843137255), __.float(0.9921568627450981), __.int(1)); color.sky300 = __.FM.float_4_1_1_1_1(__.float(0.49019607843137253), __.float(0.8274509803921568), __.float(0.9882352941176471), __.int(1)); color.sky400 = __.FM.float_4_1_1_1_1(__.float(0.2196078431372549), __.float(0.7411764705882353), __.float(0.9725490196078431), __.int(1)); color.sky500 = __.FM.float_4_1_1_1_1(__.float(0.054901960784313725), __.float(0.6470588235294118), __.float(0.9137254901960784), __.int(1)); color.sky600 = __.FM.float_4_1_1_1_1(__.float(0.00784313725490196), __.float(0.5176470588235295), __.float(0.7803921568627451), __.int(1)); color.sky700 = __.FM.float_4_1_1_1_1(__.float(0.011764705882352941), __.float(0.4117647058823529), __.float(0.6313725490196078), __.int(1)); color.sky800 = __.FM.float_4_1_1_1_1(__.float(0.027450980392156862), __.float(0.34901960784313724), __.float(0.5215686274509804), __.int(1)); color.sky900 = __.FM.float_4_1_1_1_1(__.float(0.047058823529411764), __.float(0.2901960784313726), __.float(0.43137254901960786), __.int(1)); color.sky950 = __.FM.float_4_1_1_1_1(__.float(0.03137254901960784), __.float(0.1843137254901961), __.float(0.28627450980392155), __.int(1)); color.blue50 = __.FM.float_4_1_1_1_1(__.float(0.9372549019607843), __.float(0.9647058823529412), __.int(1), __.int(1)); color.blue100 = __.FM.float_4_1_1_1_1(__.float(0.8588235294117647), __.float(0.9176470588235294), __.float(0.996078431372549), __.int(1)); color.blue200 = __.FM.float_4_1_1_1_1(__.float(0.7490196078431373), __.float(0.8588235294117647), __.float(0.996078431372549), __.int(1)); color.blue300 = __.FM.float_4_1_1_1_1(__.float(0.5764705882352941), __.float(0.7725490196078432), __.float(0.9921568627450981), __.int(1)); color.blue400 = __.FM.float_4_1_1_1_1(__.float(0.3764705882352941), __.float(0.6470588235294118), __.float(0.9803921568627451), __.int(1)); color.blue500 = __.FM.float_4_1_1_1_1(__.float(0.23137254901960785), __.float(0.5098039215686274), __.float(0.9647058823529412), __.int(1)); color.blue600 = __.FM.float_4_1_1_1_1(__.float(0.1450980392156863), __.float(0.38823529411764707), __.float(0.9215686274509803), __.int(1)); color.blue700 = __.FM.float_4_1_1_1_1(__.float(0.11372549019607843), __.float(0.3058823529411765), __.float(0.8470588235294118), __.int(1)); color.blue800 = __.FM.float_4_1_1_1_1(__.float(0.11764705882352941), __.float(0.25098039215686274), __.float(0.6862745098039216), __.int(1)); color.blue900 = __.FM.float_4_1_1_1_1(__.float(0.11764705882352941), __.float(0.22745098039215686), __.float(0.5411764705882353), __.int(1)); color.blue950 = __.FM.float_4_1_1_1_1(__.float(0.09019607843137255), __.float(0.1450980392156863), __.float(0.32941176470588235), __.int(1)); color.indigo50 = __.FM.float_4_1_1_1_1(__.float(0.9333333333333333), __.float(0.9490196078431372), __.int(1), __.int(1)); color.indigo100 = __.FM.float_4_1_1_1_1(__.float(0.8784313725490196), __.float(0.9058823529411765), __.int(1), __.int(1)); color.indigo200 = __.FM.float_4_1_1_1_1(__.float(0.7803921568627451), __.float(0.8235294117647058), __.float(0.996078431372549), __.int(1)); color.indigo300 = __.FM.float_4_1_1_1_1(__.float(0.6470588235294118), __.float(0.7058823529411765), __.float(0.9882352941176471), __.int(1)); color.indigo400 = __.FM.float_4_1_1_1_1(__.float(0.5058823529411764), __.float(0.5490196078431373), __.float(0.9725490196078431), __.int(1)); color.indigo500 = __.FM.float_4_1_1_1_1(__.float(0.38823529411764707), __.float(0.4), __.float(0.9450980392156862), __.int(1)); color.indigo600 = __.FM.float_4_1_1_1_1(__.float(0.30980392156862746), __.float(0.27450980392156865), __.float(0.8980392156862745), __.int(1)); color.indigo700 = __.FM.float_4_1_1_1_1(__.float(0.2627450980392157), __.float(0.2196078431372549), __.float(0.792156862745098), __.int(1)); color.indigo800 = __.FM.float_4_1_1_1_1(__.float(0.21568627450980393), __.float(0.18823529411764706), __.float(0.6392156862745098), __.int(1)); color.indigo900 = __.FM.float_4_1_1_1_1(__.float(0.19215686274509805), __.float(0.1803921568627451), __.float(0.5058823529411764), __.int(1)); color.indigo950 = __.FM.float_4_1_1_1_1(__.float(0.11764705882352941), __.float(0.10588235294117647), __.float(0.29411764705882354), __.int(1)); color.violet50 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.9529411764705882), __.int(1), __.int(1)); color.violet100 = __.FM.float_4_1_1_1_1(__.float(0.9294117647058824), __.float(0.9137254901960784), __.float(0.996078431372549), __.int(1)); color.violet200 = __.FM.float_4_1_1_1_1(__.float(0.8666666666666667), __.float(0.8392156862745098), __.float(0.996078431372549), __.int(1)); color.violet300 = __.FM.float_4_1_1_1_1(__.float(0.7686274509803922), __.float(0.7098039215686275), __.float(0.9921568627450981), __.int(1)); color.violet400 = __.FM.float_4_1_1_1_1(__.float(0.6549019607843137), __.float(0.5450980392156862), __.float(0.9803921568627451), __.int(1)); color.violet500 = __.FM.float_4_1_1_1_1(__.float(0.5450980392156862), __.float(0.3607843137254902), __.float(0.9647058823529412), __.int(1)); color.violet600 = __.FM.float_4_1_1_1_1(__.float(0.48627450980392156), __.float(0.22745098039215686), __.float(0.9294117647058824), __.int(1)); color.violet700 = __.FM.float_4_1_1_1_1(__.float(0.42745098039215684), __.float(0.1568627450980392), __.float(0.8509803921568627), __.int(1)); color.violet800 = __.FM.float_4_1_1_1_1(__.float(0.3568627450980392), __.float(0.12941176470588237), __.float(0.7137254901960784), __.int(1)); color.violet900 = __.FM.float_4_1_1_1_1(__.float(0.2980392156862745), __.float(0.11372549019607843), __.float(0.5843137254901961), __.int(1)); color.violet950 = __.FM.float_4_1_1_1_1(__.float(0.1803921568627451), __.float(0.06274509803921569), __.float(0.396078431372549), __.int(1)); color.purple50 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9607843137254902), __.int(1), __.int(1)); color.purple100 = __.FM.float_4_1_1_1_1(__.float(0.9529411764705882), __.float(0.9098039215686274), __.int(1), __.int(1)); color.purple200 = __.FM.float_4_1_1_1_1(__.float(0.9137254901960784), __.float(0.8352941176470589), __.int(1), __.int(1)); color.purple300 = __.FM.float_4_1_1_1_1(__.float(0.8470588235294118), __.float(0.7058823529411765), __.float(0.996078431372549), __.int(1)); color.purple400 = __.FM.float_4_1_1_1_1(__.float(0.7529411764705882), __.float(0.5176470588235295), __.float(0.9882352941176471), __.int(1)); color.purple500 = __.FM.float_4_1_1_1_1(__.float(0.6588235294117647), __.float(0.3333333333333333), __.float(0.9686274509803922), __.int(1)); color.purple600 = __.FM.float_4_1_1_1_1(__.float(0.5764705882352941), __.float(0.2), __.float(0.9176470588235294), __.int(1)); color.purple700 = __.FM.float_4_1_1_1_1(__.float(0.49411764705882355), __.float(0.13333333333333333), __.float(0.807843137254902), __.int(1)); color.purple800 = __.FM.float_4_1_1_1_1(__.float(0.4196078431372549), __.float(0.12941176470588237), __.float(0.6588235294117647), __.int(1)); color.purple900 = __.FM.float_4_1_1_1_1(__.float(0.34509803921568627), __.float(0.10980392156862745), __.float(0.5294117647058824), __.int(1)); color.purple950 = __.FM.float_4_1_1_1_1(__.float(0.23137254901960785), __.float(0.027450980392156862), __.float(0.39215686274509803), __.int(1)); color.fuchsia50 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.9568627450980393), __.int(1), __.int(1)); color.fuchsia100 = __.FM.float_4_1_1_1_1(__.float(0.9803921568627451), __.float(0.9098039215686274), __.int(1), __.int(1)); color.fuchsia200 = __.FM.float_4_1_1_1_1(__.float(0.9607843137254902), __.float(0.8156862745098039), __.float(0.996078431372549), __.int(1)); color.fuchsia300 = __.FM.float_4_1_1_1_1(__.float(0.9411764705882353), __.float(0.6705882352941176), __.float(0.9882352941176471), __.int(1)); color.fuchsia400 = __.FM.float_4_1_1_1_1(__.float(0.9098039215686274), __.float(0.4745098039215686), __.float(0.9764705882352941), __.int(1)); color.fuchsia500 = __.FM.float_4_1_1_1_1(__.float(0.8509803921568627), __.float(0.27450980392156865), __.float(0.9372549019607843), __.int(1)); color.fuchsia600 = __.FM.float_4_1_1_1_1(__.float(0.7529411764705882), __.float(0.14901960784313725), __.float(0.8274509803921568), __.int(1)); color.fuchsia700 = __.FM.float_4_1_1_1_1(__.float(0.6352941176470588), __.float(0.10980392156862745), __.float(0.6862745098039216), __.int(1)); color.fuchsia800 = __.FM.float_4_1_1_1_1(__.float(0.5254901960784314), __.float(0.09803921568627451), __.float(0.5607843137254902), __.int(1)); color.fuchsia900 = __.FM.float_4_1_1_1_1(__.float(0.4392156862745098), __.float(0.10196078431372549), __.float(0.4588235294117647), __.int(1)); color.fuchsia950 = __.FM.float_4_1_1_1_1(__.float(0.2901960784313726), __.float(0.01568627450980392), __.float(0.3058823529411765), __.int(1)); color.pink50 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.9490196078431372), __.float(0.9725490196078431), __.int(1)); color.pink100 = __.FM.float_4_1_1_1_1(__.float(0.9882352941176471), __.float(0.9058823529411765), __.float(0.9529411764705882), __.int(1)); color.pink200 = __.FM.float_4_1_1_1_1(__.float(0.984313725490196), __.float(0.8117647058823529), __.float(0.9098039215686274), __.int(1)); color.pink300 = __.FM.float_4_1_1_1_1(__.float(0.9764705882352941), __.float(0.6588235294117647), __.float(0.8313725490196079), __.int(1)); color.pink400 = __.FM.float_4_1_1_1_1(__.float(0.9568627450980393), __.float(0.4470588235294118), __.float(0.7137254901960784), __.int(1)); color.pink500 = __.FM.float_4_1_1_1_1(__.float(0.9254901960784314), __.float(0.2823529411764706), __.float(0.6), __.int(1)); color.pink600 = __.FM.float_4_1_1_1_1(__.float(0.8588235294117647), __.float(0.15294117647058825), __.float(0.4666666666666667), __.int(1)); color.pink700 = __.FM.float_4_1_1_1_1(__.float(0.7450980392156863), __.float(0.09411764705882353), __.float(0.36470588235294116), __.int(1)); color.pink800 = __.FM.float_4_1_1_1_1(__.float(0.615686274509804), __.float(0.09019607843137255), __.float(0.30196078431372547), __.int(1)); color.pink900 = __.FM.float_4_1_1_1_1(__.float(0.5137254901960784), __.float(0.09411764705882353), __.float(0.2627450980392157), __.int(1)); color.pink950 = __.FM.float_4_1_1_1_1(__.float(0.3137254901960784), __.float(0.027450980392156862), __.float(0.1411764705882353), __.int(1)); color.rose50 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.9450980392156862), __.float(0.9490196078431372), __.int(1)); color.rose100 = __.FM.float_4_1_1_1_1(__.int(1), __.float(0.8941176470588236), __.float(0.9019607843137255), __.int(1)); color.rose200 = __.FM.float_4_1_1_1_1(__.float(0.996078431372549), __.float(0.803921568627451), __.float(0.8274509803921568), __.int(1)); color.rose300 = __.FM.float_4_1_1_1_1(__.float(0.9921568627450981), __.float(0.6431372549019608), __.float(0.6862745098039216), __.int(1)); color.rose400 = __.FM.float_4_1_1_1_1(__.float(0.984313725490196), __.float(0.44313725490196076), __.float(0.5215686274509804), __.int(1)); color.rose500 = __.FM.float_4_1_1_1_1(__.float(0.9568627450980393), __.float(0.24705882352941178), __.float(0.3686274509803922), __.int(1)); color.rose600 = __.FM.float_4_1_1_1_1(__.float(0.8823529411764706), __.float(0.11372549019607843), __.float(0.2823529411764706), __.int(1)); color.rose700 = __.FM.float_4_1_1_1_1(__.float(0.7450980392156863), __.float(0.07058823529411765), __.float(0.23529411764705882), __.int(1)); color.rose800 = __.FM.float_4_1_1_1_1(__.float(0.6235294117647059), __.float(0.07058823529411765), __.float(0.2235294117647059), __.int(1)); color.rose900 = __.FM.float_4_1_1_1_1(__.float(0.5333333333333333), __.float(0.07450980392156863), __.float(0.21568627450980393), __.int(1)); color.rose950 = __.FM.float_4_1_1_1_1(__.float(0.2980392156862745), __.float(0.0196078431372549), __.float(0.09803921568627451), __.int(1)); return color; }()); exports.color = color; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_common_ts_57436_color\\",\\"fields\\":[[\\"slate50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"slate950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"gray950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"zinc950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"neutral950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"stone950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"red950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"orange950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"amber950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"yellow950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"lime950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"green950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"emerald950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"teal950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"cyan950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"sky950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"blue950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"indigo950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"violet950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"purple950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"fuchsia950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"pink950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose50\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose100\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose200\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose300\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose400\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose500\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose600\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose700\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose800\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose900\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}],[\\"rose950\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float4\\"}]]}"), color) ; function wrap2(value, low, high) { return __.makeVector((0, std_math_1.wrap)(value[0], low, high), (0, std_math_1.wrap)(value[1], low, high)); } exports.wrap2 = wrap2; ; function wrap3(value, low, high) { return __.makeVector((0, std_math_1.wrap)(value[0], low, high), (0, std_math_1.wrap)(value[1], low, high), (0, std_math_1.wrap)(value[2], low, high)); } exports.wrap3 = wrap3; ; function wrap4(value, low, high) { return __.makeVector((0, std_math_1.wrap)(value[0], low, high), (0, std_math_1.wrap)(value[1], low, high), (0, std_math_1.wrap)(value[2], low, high), (0, std_math_1.wrap)(value[3], low, high)); } exports.wrap4 = wrap4; ; }); ` } ], emitSkipped: false, diagnostics: [] }, "/_std/sdf.ts": { outputFiles: [ { name: "/_std/sdf.js", writeByteOrderMark: false, text: `var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; define(["require", "exports", "/std_math", "/std_math", "/std___std_all"], function (require, exports, __, std_math_1, std___std_all_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sdf = void 0; __ = __importStar(__); var globalVarGet = std___std_all_1.globalVarGet; var sdf = /** @class */ (function () { function sdf(data) { } sdf.sphere = function (samplePosition, sphereCenter, radius) { var _a, _b; var p = (_a = samplePosition, _b = sphereCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var r = radius; return (0, std_math_1.length)(p) - r; }; sdf.box = function (samplePosition, boxCenter, boxSize) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = boxCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var s = boxSize; var q = (_c = (_e = p, [Math.abs(_e[0]), Math.abs(_e[1]), Math.abs(_e[2])]), _d = s, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); return (0, std_math_1.length)((0, std_math_1.max)(q, 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(q[0], (0, std_math_1.max)(q[1], q[2])), 0.0); }; sdf.roundBox = function (samplePosition, boxCenter, boxSize, cornerRadius) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = boxCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var s = boxSize; var r = cornerRadius; var q = (_c = (_e = p, [Math.abs(_e[0]), Math.abs(_e[1]), Math.abs(_e[2])]), _d = s, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); return (0, std_math_1.length)((0, std_math_1.max)(q, 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(q[0], (0, std_math_1.max)(q[1], q[2])), 0.0) - r; }; sdf.boxFrame = function (samplePosition, boxCenter, boxSize, frameThickness) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; var p = (_a = samplePosition, _b = boxCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var b = boxSize; var e = frameThickness; p = (_c = (_e = p, [Math.abs(_e[0]), Math.abs(_e[1]), Math.abs(_e[2])]), _d = b, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var q = (_f = (_h = (_j = p, _k = e, [_j[0] + _k, _j[1] + _k, _j[2] + _k]), [Math.abs(_h[0]), Math.abs(_h[1]), Math.abs(_h[2])]), _g = e, [_f[0] - _g, _f[1] - _g, _f[2] - _g]); return (0, std_math_1.min)((0, std_math_1.min)((0, std_math_1.length)((0, std_math_1.max)(__.FM.float_3_1_1_1(__.swizzle(p, 'x'), __.swizzle(q, 'y'), __.swizzle(q, 'z')), 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(p[0], (0, std_math_1.max)(q[1], q[2])), 0.0), (0, std_math_1.length)((0, std_math_1.max)(__.FM.float_3_1_1_1(__.swizzle(q, 'x'), __.swizzle(p, 'y'), __.swizzle(q, 'z')), 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(q[0], (0, std_math_1.max)(p[1], q[2])), 0.0)), (0, std_math_1.length)((0, std_math_1.max)(__.FM.float_3_1_1_1(__.swizzle(q, 'x'), __.swizzle(q, 'y'), __.swizzle(p, 'z')), 0.0)) + (0, std_math_1.min)((0, std_math_1.max)(q[0], (0, std_math_1.max)(q[1], p[2])), 0.0)); }; sdf.torus = function (samplePosition, torusCenter, torusSize) { var _a, _b, _c; var p = (_a = samplePosition, _b = torusCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var t = torusSize; var q = __.FM.float_2_1_1(__.sub((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), t[0]), __.swizzle(p, 'y')); return (0, std_math_1.length)(q) - t[1]; }; sdf.cappedTorus = function (samplePosition, torusCenter, torusSize, ra, rb) { var _a, _b, _c, _d, _e; var p1 = (_a = samplePosition, _b = torusCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var p = __.makeVector(Math.abs(p1[0]), (_c = p1, [_c[1], _c[2]])); var sc = torusSize; var k = (sc[1] * p[0] > sc[0] * p[1]) ? (0, std_math_1.dot)((_d = p, [_d[0], _d[1]]), sc) : (0, std_math_1.length)((_e = p, [_e[0], _e[1]])); return Math.sqrt((0, std_math_1.dot)(p, p) + ra * ra - 2.0 * ra * k) - rb; }; sdf.link = function (samplePosition, linkCenter, linkLength, r1, r2) { var _a, _b, _c; var p = (_a = samplePosition, _b = linkCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var le = linkLength; var q = __.FM.float_3_1_1_1(__.swizzle(p, 'x'), (0, std_math_1.max)(Math.abs(p[1]) - le, 0.0), __.swizzle(p, 'z')); return (0, std_math_1.length)(__.FM.float_2_1_1(__.sub((0, std_math_1.length)((_c = q, [_c[0], _c[1]])), r1), __.swizzle(q, 'z'))) - r2; }; sdf.infinteCylinder = function (samplePosition, cylinderCenter, cylinderSize) { var _a, _b, _c, _d, _e, _f; var p = (_a = samplePosition, _b = cylinderCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var c = cylinderSize; return (0, std_math_1.length)((_c = (_e = p, [_e[0], _e[2]]), _d = (_f = c, [_f[0], _f[1]]), [_c[0] - _d[0], _c[1] - _d[1]])) - c[2]; }; sdf.cone = function (samplePosition, coneCenter, c, coneHeight) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; var p = (_a = samplePosition, _b = coneCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = coneHeight; // c is the sin/cos of the angle, h is height // Alternatively pass q instead of (c,h), // which is the point at the base in 2D var q = (_c = h, _d = __.FM.float_2_1_1(__.div(c[0], c[1]), __.negate(1.0)), [_c * _d[0], _c * _d[1]]); var w = __.FM.float_2_1_1((0, std_math_1.length)((_e = p, [_e[0], _e[2]])), __.swizzle(p, 'y')); var a = (_f = w, _g = (_h = q, _j = (0, std_math_1.clamp)((0, std_math_1.dot)(w, q) / (0, std_math_1.dot)(q, q), 0.0, 1.0), [_h[0] * _j, _h[1] * _j]), [_f[0] - _g[0], _f[1] - _g[1]]); var b = (_k = w, _l = (_m = q, _o = __.FM.float_2_1_1((0, std_math_1.clamp)(w[0] / q[0], 0.0, 1.0), __.float(1.0)), [_m[0] * _o[0], _m[1] * _o[1]]), [_k[0] - _l[0], _k[1] - _l[1]]); var k = Math.sign(q[1]); var d = (0, std_math_1.min)((0, std_math_1.dot)(a, a), (0, std_math_1.dot)(b, b)); var s = (0, std_math_1.max)(k * (w[0] * q[1] - w[1] * q[0]), k * (w[1] - q[1])); return Math.sqrt(d) * Math.sign(s); }; sdf.plane = function (samplePosition, planeCenter, planeNormal, planeHeight) { var _a, _b; var p = (_a = samplePosition, _b = planeCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var n = planeNormal; var h = planeHeight; // n must be normalized return (0, std_math_1.dot)(p, n) + h; }; sdf.hexPrism = function (samplePosition, hexCenter, hexSize) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; var p = (_a = samplePosition, _b = hexCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = hexSize; var k = __.FM.float_3_1_1_1(__.negate(0.8660254), __.float(0.5), __.float(0.57735)); p = (_c = p, [Math.abs(_c[0]), Math.abs(_c[1]), Math.abs(_c[2])]); var dddd = (0, std_math_1.min)((0, std_math_1.dot)((_d = k, [_d[0], _d[1]]), (_e = p, [_e[0], _e[1]])), 0.0) * 2.0; p = (_f = p, _g = __.FM.float_3_2_1(__.mul(dddd, (_h = k, [_h[0], _h[1]])), __.float(0.0)), [_f[0] - _g[0], _f[1] - _g[1], _f[2] - _g[2]]); var d = __.FM.float_2_1_1(__.mul((0, std_math_1.length)((_j = (_l = p, [_l[0], _l[1]]), _k = __.FM.float_2_1_1((0, std_math_1.clamp)(p[0], (__.FM.negate_1(k[2])) * h[0], k[2] * h[0]), __.swizzle(h, 'x')), [_j[0] - _k[0], _j[1] - _k[1]])), Math.sign(p[1] - h[0])), __.sub(p[2], h[1])); return (0, std_math_1.min)((0, std_math_1.max)(d[0], d[1]), 0.0) + (0, std_math_1.length)((0, std_math_1.max)(d, 0.0)); }; sdf.triPrism = function (samplePosition, triCenter, triSize) { var _a, _b, _c; var p = (_a = samplePosition, _b = triCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = triSize; var q = (_c = p, [Math.abs(_c[0]), Math.abs(_c[1]), Math.abs(_c[2])]); return (0, std_math_1.max)(q[2] - h[1], (0, std_math_1.max)(q[0] * 0.866025 + p[1] * 0.5, (__.FM.negate_1(p[1]))) - h[0] * 0.5); }; sdf.capsuleLine = function (samplePosition, lineStart, lineEnd, capsuleRadius) { var _a, _b, _c, _d, _e, _f, _g, _h; var p = samplePosition; var a = lineStart; var b = lineEnd; var r = capsuleRadius; var pa = (_a = p, _b = a, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var ba = (_c = b, _d = a, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var h = (0, std_math_1.clamp)((0, std_math_1.dot)(pa, ba) / (0, std_math_1.dot)(ba, ba), 0.0, 1.0); return (0, std_math_1.length)((_e = pa, _f = (_g = ba, _h = h, [_g[0] * _h, _g[1] * _h, _g[2] * _h]), [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]])) - r; }; sdf.capsule = function (samplePosition, capsuleCenter, height, radius) { var _a, _b; var p1 = (_a = samplePosition, _b = capsuleCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var r = radius; var p = __.makeVector(p1[0], p1[1] - (0, std_math_1.clamp)(p1[1], 0.0, h), p1[2]); return (0, std_math_1.length)(p) - r; }; sdf.cylinder = function (samplePosition, cylinderCenter, height, radius) { var _a, _b, _c, _d, _e, _f; var p = (_a = samplePosition, _b = cylinderCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var r = radius; var d = (_c = (_e = __.FM.float_2_1_1((0, std_math_1.length)((_f = p, [_f[0], _f[2]])), __.swizzle(p, 'y')), [Math.abs(_e[0]), Math.abs(_e[1])]), _d = __.FM.float_2_1_1(r, h), [_c[0] - _d[0], _c[1] - _d[1]]); return (0, std_math_1.min)((0, std_math_1.max)(d[0], d[1]), 0.0) + (0, std_math_1.length)((0, std_math_1.max)(d, 0.0)); }; sdf.cylinderLine = function (samplePosition, lineStart, lineEnd, radius) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; var p = samplePosition; var a = lineStart; var b = lineEnd; var r = radius; var ba = (_a = b, _b = a, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var pa = (_c = p, _d = a, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var baba = (0, std_math_1.dot)(ba, ba); var paba = (0, std_math_1.dot)(pa, ba); var x = (0, std_math_1.length)((_e = (_g = pa, _h = baba, [_g[0] * _h, _g[1] * _h, _g[2] * _h]), _f = (_j = ba, _k = paba, [_j[0] * _k, _j[1] * _k, _j[2] * _k]), [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]])) - r * baba; var y = Math.abs(paba - baba * 0.5) - baba * 0.5; var x2 = x * x; var y2 = y * y * baba; var mxxy = (0, std_math_1.max)(x, y); var d = (mxxy < 0.0) ? (__.FM.negate_1((0, std_math_1.min)(x2, y2))) : (((x > 0.0) ? x2 : 0.0) + ((y > 0.0) ? y2 : 0.0)); return Math.sign(d) * Math.sqrt(Math.abs(d)) / baba; }; sdf.roundedCylinder = function (samplePosition, cylinderCenter, cylinderRadius, cornerRadius, height) { var _a, _b, _c; var p = (_a = samplePosition, _b = cylinderCenter, [_a[0] - _b, _a[1] - _b, _a[2] - _b]); var h = height; var ra = cylinderRadius; var rb = cornerRadius; var d = __.FM.float_2_1_1(__.add((0, std_math_1.length)((_c = p, [_c[0], _c[2]])) - 2.0 * ra, rb), __.sub(Math.abs(p[1]), h)); return (0, std_math_1.min)((0, std_math_1.max)(d[0], d[1]), 0.0) + (0, std_math_1.length)((0, std_math_1.max)(d, 0.0)) - rb; }; sdf.cappedCone = function (samplePosition, coneCenter, height, r1, r2) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; var p = (_a = samplePosition, _b = coneCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); var k1 = __.FM.float_2_1_1(r2, h); var k2 = __.FM.float_2_1_1(__.sub(r2, r1), __.mul(2.0, h)); var ca = __.FM.float_2_1_1(__.sub(q[0], (0, std_math_1.min)(q[0], (q[1] < 0.0) ? r1 : r2)), __.sub(Math.abs(q[1]), h)); var cb = (_d = (_f = q, _g = k1, [_f[0] - _g[0], _f[1] - _g[1]]), _e = (_h = k2, _j = (0, std_math_1.clamp)((0, std_math_1.dot)((_k = k1, _l = q, [_k[0] - _l[0], _k[1] - _l[1]]), k2) / dot2(k2), 0.0, 1.0), [_h[0] * _j, _h[1] * _j]), [_d[0] + _e[0], _d[1] + _e[1]]); var s = (__.and(cb[0] < 0.0, ca[1] < 0.0)) ? (__.FM.negate_1(1.0)) : 1.0; return s * Math.sqrt((0, std_math_1.min)(dot2(ca), dot2(cb))); }; sdf.solidAngle = function (samplePosition, solidCenter, size, radius) { var _a, _b, _c, _d, _e, _f, _g; var p = (_a = samplePosition, _b = solidCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var c = size; var ra = radius; // c is the sin/cos of the angle var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); var l = (0, std_math_1.length)(q) - ra; var m = (0, std_math_1.length)((_d = q, _e = (_f = c, _g = (0, std_math_1.clamp)((0, std_math_1.dot)(q, c), 0.0, ra), [_f[0] * _g, _f[1] * _g]), [_d[0] - _e[0], _d[1] - _e[1]])); return (0, std_math_1.max)(l, m * Math.sign(c[1] * q[0] - c[0] * q[1])); }; sdf.cutSphere = function (samplePosition, sphereCenter, radius, height) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = sphereCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var r = radius; // sampling independent computations (only depend on shape) var w = Math.sqrt(r * r - h * h); // sampling dependant computations var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); var s = (0, std_math_1.max)((h - r) * q[0] * q[0] + w * w * (h + r - 2.0 * q[1]), h * q[0] - w * q[1]); return (s < 0.0) ? (0, std_math_1.length)(q) - r : (q[0] < w) ? h - q[1] : (0, std_math_1.length)((_d = q, _e = __.FM.float_2_1_1(w, h), [_d[0] - _e[0], _d[1] - _e[1]])); }; sdf.cutHollowSphere = function (samplePosition, sphereCenter, radius, height, thickness) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = sphereCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var r = radius; var h = height; var t = thickness; // sampling independent computations (only depend on shape) var w = Math.sqrt(r * r - h * h); // sampling dependant computations var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); return ((h * q[0] < w * q[1]) ? (0, std_math_1.length)((_d = q, _e = __.FM.float_2_1_1(w, h), [_d[0] - _e[0], _d[1] - _e[1]])) : Math.abs((0, std_math_1.length)(q) - r)) - t; }; sdf.roundCone = function (samplePosition, coneCenter, coneRadius, cornerRadius, height) { var _a, _b, _c, _d, _e; var p = (_a = samplePosition, _b = coneCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var r1 = coneRadius; var r2 = cornerRadius; // sampling independent computations (only depend on shape) var b = (r1 - r2) / h; var a = Math.sqrt(1.0 - b * b); // sampling dependant computations var q = __.FM.float_2_1_1((0, std_math_1.length)((_c = p, [_c[0], _c[2]])), __.swizzle(p, 'y')); var k = (0, std_math_1.dot)(q, __.FM.float_2_1_1(__.negate(b), a)); if (k < 0.0) return (0, std_math_1.length)(q) - r1; if (k > a * h) return (0, std_math_1.length)((_d = q, _e = __.FM.float_2_1_1(__.float(0.0), h), [_d[0] - _e[0], _d[1] - _e[1]])) - r2; return (0, std_math_1.dot)(q, __.FM.float_2_1_1(a, b)) - r1; }; sdf.ellipsoid = function (samplePosition, center, radius) { var _a, _b, _c, _d, _e, _f, _g, _h; var p = (_a = samplePosition, _b = center, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var r = radius; var k0 = (0, std_math_1.length)((_c = p, _d = r, [_c[0] / _d[0], _c[1] / _d[1], _c[2] / _d[2]])); var k1 = (0, std_math_1.length)((_e = p, _f = (_g = r, _h = r, [_g[0] * _h[0], _g[1] * _h[1], _g[2] * _h[2]]), [_e[0] / _f[0], _e[1] / _f[1], _e[2] / _f[2]])); return k0 * (k0 - 1.0) / k1; }; sdf.rhombus = function (samplePosition, rhombusCenter, la, lb, height, ra) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; var p = (_a = samplePosition, _b = rhombusCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; p = (_c = p, [Math.abs(_c[0]), Math.abs(_c[1]), Math.abs(_c[2])]); var b = __.FM.float_2_1_1(la, lb); var f = (0, std_math_1.clamp)((ndot(b, (_d = b, _e = (_f = 2.0, _g = (_h = p, [_h[0], _h[2]]), [_f * _g[0], _f * _g[1]]), [_d[0] - _e[0], _d[1] - _e[1]]))) / (0, std_math_1.dot)(b, b), (__.FM.negate_1(1.0)), 1.0); var q = __.FM.float_2_1_1(__.sub((0, std_math_1.length)((_j = (_l = p, [_l[0], _l[2]]), _k = (_m = (_p = 0.5, _q = b, [_p * _q[0], _p * _q[1]]), _o = __.FM.float_2_1_1(__.sub(1.0, f), __.add(1.0, f)), [_m[0] * _o[0], _m[1] * _o[1]]), [_j[0] - _k[0], _j[1] - _k[1]])) * Math.sign(p[0] * b[1] + p[2] * b[0] - b[0] * b[1]), ra), __.sub(p[1], h)); return (0, std_math_1.min)((0, std_math_1.max)(q[0], q[1]), 0.0) + (0, std_math_1.length)((0, std_math_1.max)(q, 0.0)); }; sdf.octahedron = function (samplePosition, center, size) { var _a, _b, _c, _d, _e, _f, _g; var p = (_a = samplePosition, _b = center, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var s = size; p = (_c = p, [Math.abs(_c[0]), Math.abs(_c[1]), Math.abs(_c[2])]); var m = p[0] + p[1] + p[2] - s; var q = (_d = 0.0, [_d, _d, _d]); if (3.0 * p[0] < m) q = (_e = p, [_e[0], _e[1], _e[2]]); else if (3.0 * p[1] < m) q = (_f = p, [_f[1], _f[2], _f[0]]); else if (3.0 * p[2] < m) q = (_g = p, [_g[2], _g[0], _g[1]]); else return m * 0.57735027; var k = (0, std_math_1.clamp)(0.5 * (q[2] - q[1] + s), 0.0, s); return (0, std_math_1.length)(__.FM.float_3_1_1_1(__.swizzle(q, 'x'), __.add(q[1] - s, k), __.sub(q[2], k))); }; sdf.pyramid = function (samplePosition, pyramidCenter, height) { var _a, _b; var p1 = (_a = samplePosition, _b = pyramidCenter, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var h = height; var m2 = h * h + 0.25; var p2 = __.makeVector(Math.abs(p1[0]), p1[1], Math.abs(p1[2])); if (p1[2] > p1[0]) { p2 = __.makeVector(p2[2], p2[1], p2[0]); } p2 = __.makeVector(p2[0] - 0.5, p2[1], p2[2] - 0.5); var p = p2; var q = __.FM.float_3_1_1_1(__.swizzle(p, 'z'), __.sub(h * p[1], 0.5 * p[0]), __.add(h * p[0], 0.5 * p[1])); var s = (0, std_math_1.max)((__.FM.negate_1(q[0])), 0.0); var t = (0, std_math_1.clamp)((q[1] - 0.5 * p[2]) / (m2 + 0.25), 0.0, 1.0); var a = m2 * (q[0] + s) * (q[0] + s) + q[1] * q[1]; var b = m2 * (q[0] + 0.5 * t) * (q[0] + 0.5 * t) + (q[1] - m2 * t) * (q[1] - m2 * t); var d2 = (0, std_math_1.min)(q[1], (__.FM.negate_1(q[0])) * m2 - q[1] * 0.5) > 0.0 ? 0.0 : (0, std_math_1.min)(a, b); return Math.sqrt((d2 + q[2] * q[2]) / m2) * Math.sign((0, std_math_1.max)(q[2], (__.FM.negate_1(p[1])))); }; sdf.udTriangle = function (samplePosition, a, b, c) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z; var p = samplePosition; var ba = (_a = b, _b = a, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var pa = (_c = p, _d = a, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var cb = (_e = c, _f = b, [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]]); var pb = (_g = p, _h = b, [_g[0] - _h[0], _g[1] - _h[1], _g[2] - _h[2]]); var ac = (_j = a, _k = c, [_j[0] - _k[0], _j[1] - _k[1], _j[2] - _k[2]]); var pc = (_l = p, _m = c, [_l[0] - _m[0], _l[1] - _m[1], _l[2] - _m[2]]); var nor = (0, std_math_1.cross)(ba, ac); return Math.sqrt((Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(ba, nor), pa)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(cb, nor), pb)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(ac, nor), pc)) < 2.0) ? (0, std_math_1.min)((0, std_math_1.min)(dot3((_o = (_q = ba, _r = (0, std_math_1.clamp)((0, std_math_1.dot)(ba, pa) / dot3(ba), 0.0, 1.0), [_q[0] * _r, _q[1] * _r, _q[2] * _r]), _p = pa, [_o[0] - _p[0], _o[1] - _p[1], _o[2] - _p[2]])), dot3((_s = (_u = cb, _v = (0, std_math_1.clamp)((0, std_math_1.dot)(cb, pb) / dot3(cb), 0.0, 1.0), [_u[0] * _v, _u[1] * _v, _u[2] * _v]), _t = pb, [_s[0] - _t[0], _s[1] - _t[1], _s[2] - _t[2]]))), dot3((_w = (_y = ac, _z = (0, std_math_1.clamp)((0, std_math_1.dot)(ac, pc) / dot3(ac), 0.0, 1.0), [_y[0] * _z, _y[1] * _z, _y[2] * _z]), _x = pc, [_w[0] - _x[0], _w[1] - _x[1], _w[2] - _x[2]]))) : (0, std_math_1.dot)(nor, pa) * (0, std_math_1.dot)(nor, pa) / dot3(nor)); }; sdf.udQuad = function (samplePosition, a, b, c, d) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7; var p = samplePosition; var ba = (_a = b, _b = a, [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]); var pa = (_c = p, _d = a, [_c[0] - _d[0], _c[1] - _d[1], _c[2] - _d[2]]); var cb = (_e = c, _f = b, [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]]); var pb = (_g = p, _h = b, [_g[0] - _h[0], _g[1] - _h[1], _g[2] - _h[2]]); var dc = (_j = d, _k = c, [_j[0] - _k[0], _j[1] - _k[1], _j[2] - _k[2]]); var pc = (_l = p, _m = c, [_l[0] - _m[0], _l[1] - _m[1], _l[2] - _m[2]]); var ad = (_o = a, _p = d, [_o[0] - _p[0], _o[1] - _p[1], _o[2] - _p[2]]); var pd = (_q = p, _r = d, [_q[0] - _r[0], _q[1] - _r[1], _q[2] - _r[2]]); var nor = (0, std_math_1.cross)(ba, ad); return Math.sqrt((Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(ba, nor), pa)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(cb, nor), pb)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(dc, nor), pc)) + Math.sign((0, std_math_1.dot)((0, std_math_1.cross)(ad, nor), pd)) < 3.0) ? (0, std_math_1.min)((0, std_math_1.min)((0, std_math_1.min)(dot3((_s = (_u = ba, _v = (0, std_math_1.clamp)((0, std_math_1.dot)(ba, pa) / dot3(ba), 0.0, 1.0), [_u[0] * _v, _u[1] * _v, _u[2] * _v]), _t = pa, [_s[0] - _t[0], _s[1] - _t[1], _s[2] - _t[2]])), dot3((_w = (_y = cb, _z = (0, std_math_1.clamp)((0, std_math_1.dot)(cb, pb) / dot3(cb), 0.0, 1.0), [_y[0] * _z, _y[1] * _z, _y[2] * _z]), _x = pb, [_w[0] - _x[0], _w[1] - _x[1], _w[2] - _x[2]]))), dot3((_0 = (_2 = dc, _3 = (0, std_math_1.clamp)((0, std_math_1.dot)(dc, pc) / dot3(dc), 0.0, 1.0), [_2[0] * _3, _2[1] * _3, _2[2] * _3]), _1 = pc, [_0[0] - _1[0], _0[1] - _1[1], _0[2] - _1[2]]))), dot3((_4 = (_6 = ad, _7 = (0, std_math_1.clamp)((0, std_math_1.dot)(ad, pd) / dot3(ad), 0.0, 1.0), [_6[0] * _7, _6[1] * _7, _6[2] * _7]), _5 = pd, [_4[0] - _5[0], _4[1] - _5[1], _4[2] - _5[2]]))) : (0, std_math_1.dot)(nor, pa) * (0, std_math_1.dot)(nor, pa) / dot3(nor)); }; /** * Returns the intersection of two SDFs * = max(a, b) */ sdf.intersect = function (a, b) { return (0, std_math_1.max)(a, b); }; /** * Returns the union of two SDFs * = min(a, b) */ sdf.union = function (a, b) { return (0, std_math_1.min)(a, b); }; sdf.subtract = function (a, b) { return (0, std_math_1.max)((__.FM.negate_1(a)), b); }; sdf.smoothIntersect = function (a, b, k) { var h = (0, std_math_1.clamp)(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return (0, std_math_1.lerp)(b, a, h) - k * h * (1.0 - h); }; /** * Smoothly joins two SDFs using blending distance k */ sdf.smoothUnion = function (a, b, k) { var d1 = a; var d2 = b; var h = (0, std_math_1.clamp)(0.5 + 0.5 * (d2 - d1) / k, 0.0, 1.0); return (0, std_math_1.lerp)(d2, d1, h) - k * h * (1.0 - h); }; sdf.smoothSubtract = function (a, b, k) { var d1 = a; var d2 = b; var h = (0, std_math_1.clamp)(0.5 - 0.5 * (d2 + d1) / k, 0.0, 1.0); return (0, std_math_1.lerp)(d2, (__.FM.negate_1(d1)), h) + k * h * (1.0 - h); }; /** * Blends between two SDFs using interpolation */ sdf.blend = function (a, b, t) { return t * a + ((1 | 0) - t) * b; }; sdf.round = function (a, r) { return a - r; }; /** * Carve out the interior of an SDF */ sdf.onion = function (a, thickness) { return Math.abs(a) - thickness; }; sdf.grad = function (p, sampler) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; var DELTA = 0.0001; return _a = __.FM.float_3_1_1_1(__.sub(sampler((_c = p, _d = __.FM.float_3_1_1_1(DELTA, __.float(0.0), __.float(0.0)), [_c[0] + _d[0], _c[1] + _d[1], _c[2] + _d[2]])), sampler((_e = p, _f = __.FM.float_3_1_1_1(DELTA, __.float(0.0), __.float(0.0)), [_e[0] - _f[0], _e[1] - _f[1], _e[2] - _f[2]]))), __.sub(sampler((_g = p, _h = __.FM.float_3_1_1_1(__.float(0.0), DELTA, __.float(0.0)), [_g[0] + _h[0], _g[1] + _h[1], _g[2] + _h[2]])), sampler((_j = p, _k = __.FM.float_3_1_1_1(__.float(0.0), DELTA, __.float(0.0)), [_j[0] - _k[0], _j[1] - _k[1], _j[2] - _k[2]]))), __.sub(sampler((_l = p, _m = __.FM.float_3_1_1_1(__.float(0.0), __.float(0.0), DELTA), [_l[0] + _m[0], _l[1] + _m[1], _l[2] + _m[2]])), sampler((_o = p, _p = __.FM.float_3_1_1_1(__.float(0.0), __.float(0.0), DELTA), [_o[0] - _p[0], _o[1] - _p[1], _o[2] - _p[2]])))), _b = (2.0 * DELTA), [_a[0] / _b, _a[1] / _b, _a[2] / _b]; }; /** * Poorly returns the closest point on the surface of an SDF * This is an inaccurate method */ sdf.closest = function (position, sampler) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y; var sep = 0.0001; var zero = ((0, std_math_1.min)(env.frame, (0 | 0)) | 0); var closest = position; var initialDist = sampler(position); var seed = (0 | 0); for (var j = (0 | 0); j < (200 | 0); j++) { var n = (_a = 0.0, [_a, _a, _a]); var distSum = 0.0; for (var i = zero; i < (4 | 0); i++) { var e = (_b = 0.5773, _c = (_d = (_f = 2.0, _g = __.FM.float_3_1_1_1((((i + (3 | 0)) >> (1 | 0)) & (1 | 0)), ((i >> (1 | 0)) & (1 | 0)), (i & (1 | 0))), [_f * _g[0], _f * _g[1], _f * _g[2]]), _e = 1.0, [_d[0] - _e, _d[1] - _e, _d[2] - _e]), [_b * _c[0], _b * _c[1], _b * _c[2]]); var d = sampler((_h = closest, _j = (_k = e, _l = sep, [_k[0] * _l, _k[1] * _l, _k[2] * _l]), [_h[0] + _j[0], _h[1] + _j[1], _h[2] + _j[2]])); distSum = distSum + d; n = (_m = n, _o = (_p = e, _q = d, [_p[0] * _q, _p[1] * _q, _p[2] * _q]), [_m[0] + _o[0], _m[1] + _o[1], _m[2] + _o[2]]); } closest = (_r = (_t = (_v = (_x = (0, std_math_1.normalize)(n), _y = distSum, [_x[0] * _y, _x[1] * _y, _x[2] * _y]), _w = (__.FM.negate_1((1 | 0))), [_v[0] * _w, _v[1] * _w, _v[2] * _w]), _u = 4.0, [_t[0] / _u, _t[1] / _u, _t[2] / _u]), _s = closest, [_r[0] + _s[0], _r[1] + _s[1], _r[2] + _s[2]]); if (distSum < 0.0001) { break; } } return closest; }; sdf.normal = function (position, sampler) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; var h = 0.1; var zero = ((0, std_math_1.min)(env.frame, (0 | 0)) | 0); var n = (_a = 0.0, [_a, _a, _a]); var distSum = 0.0; for (var i = zero; i < (4 | 0); i++) { var e = (_b = 0.5773, _c = (_d = (_f = 2.0, _g = __.FM.float_3_1_1_1((((i + (3 | 0)) >> (1 | 0)) & (1 | 0)), ((i >> (1 | 0)) & (1 | 0)), (i & (1 | 0))), [_f * _g[0], _f * _g[1], _f * _g[2]]), _e = 1.0, [_d[0] - _e, _d[1] - _e, _d[2] - _e]), [_b * _c[0], _b * _c[1], _b * _c[2]]); var d = sampler((_h = position, _j = (_k = e, _l = h, [_k[0] * _l, _k[1] * _l, _k[2] * _l]), [_h[0] + _j[0], _h[1] + _j[1], _h[2] + _j[2]])); distSum = distSum + d; n = (_m = n, _o = (_p = e, _q = d, [_p[0] * _q, _p[1] * _q, _p[2] * _q]), [_m[0] + _o[0], _m[1] + _o[1], _m[2] + _o[2]]); } return (0, std_math_1.normalize)(n); }; sdf.vizRings = function (d) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; if (false) { var color_1 = (_a = 1.0, _b = (_c = Math.sign(d), _d = __.FM.float_3_1_1_1(__.float(0.1), __.float(0.4), __.float(0.7)), [_c * _d[0], _c * _d[1], _c * _d[2]]), [_a - _b[0], _a - _b[1], _a - _b[2]]); color_1 = (_e = color_1, _f = 1.0 - Math.exp((__.FM.negate_1(4.0)) * Math.abs(d)), [_e[0] * _f, _e[1] * _f, _e[2] * _f]); color_1 = (_g = color_1, _h = 0.8 + 0.2 * Math.cos(140.0 * d), [_g[0] * _h, _g[1] * _h, _g[2] * _h]); color_1 = (0, std_math_1.lerp)(color_1, (_j = 1.0, [_j, _j, _j]), 1.0 - (0, std_math_1.smoothstep)(0.0, 0.015, Math.abs(d))); return __.makeVector(color_1, 1.0); } else { var size = (2 | 0); var fadeDist = (100 | 0); var v = (1 | 0) - (0, std_math_1.clamp)(d / fadeDist, (0 | 0), (1 | 0)); var color_2 = __.makeVector(0.4 * v, 0.6 * v, (1 | 0), (1 | 0)); var s = Math.sin(d / size); if (Math.abs(d) < (1 | 0)) { return __.FM.float_4_4(__.swizzle((1 | 0), "xyzw")); } else { return d > (0 | 0) ? (_k = color_2, _l = Math.ceil((1 | 0) - s), [_k[0] * _l, _k[1] * _l, _k[2] * _l, _k[3] * _l]) : (_m = color_2, _o = Math.ceil(s), [_m[0] * _o, _m[1] * _o, _m[2] * _o, _m[3] * _o]); } } }; sdf.march = function (position, direction, sampler) { var _a, _b, _c, _d; var maxDist = 100000.0; var minDist = 1.0; var dist = minDist; for (var i = (0 | 0); __.and(i < (256 | 0), dist < maxDist); i++) { var samp = sampler((_a = position, _b = (_c = direction, _d = dist, [_c[0] * _d, _c[1] * _d, _c[2] * _d]), [_a[0] + _b[0], _a[1] + _b[1], _a[2] + _b[2]])); dist = dist + samp; if (Math.abs(samp) < (0.00005 * dist)) { break; } } if (dist > maxDist) { dist = (__.FM.negate_1(1.0)); } return dist; }; /** * See: https://iquilezles.org/articles/distfunctions/ * Infinitely repeats an SDF with space in between. This returns an updated position * * Example: * \`\`\`shadeup * sdf::sphere(sdf::repeat(p, 100.xyz), 0.xyz, 50.0); * \`\`\` */ sdf.repeat = function (position, space) { var _a, _b, _c, _d, _e, _f, _g; var p = position; var s = space; return _a = p, _b = (_c = s, _d = (_e = (_f = p, _g = s, [_f[0] / _g[0], _f[1] / _g[1], _f[2] / _g[2]]), [Math.round(_e[0]), Math.round(_e[1]), Math.round(_e[2])]), [_c[0] * _d[0], _c[1] * _d[1], _c[2] * _d[2]]), [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]; }; /** * See: https://iquilezles.org/articles/distfunctions/ * Repeats an SDF with space in between upto the limit. This returns an updated position * * Example: * \`\`\`shadeup * sdf::sphere(sdf::repeatLimited(p, 100, 10.xyz), 0.xyz, 50.0); * \`\`\` */ sdf.repeatLimited = function (position, space, limit) { var _a, _b, _c, _d, _e, _f, _g; var p = position; var s = space; return _a = p, _b = (_c = s, _d = (0, std_math_1.clamp)((_e = (_f = p, _g = s, [_f[0] / _g, _f[1] / _g, _f[2] / _g]), [Math.round(_e[0]), Math.round(_e[1]), Math.round(_e[2])]), (__.FM.negate_3(limit)), limit), [_c * _d[0], _c * _d[1], _c * _d[2]]), [_a[0] - _b[0], _a[1] - _b[1], _a[2] - _b[2]]; }; sdf.prototype.clone = function () { return new sdf({}); }; sdf.prototype._getStructure = function () { return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_sdf_ts_1953_sdf\\",\\"fields\\":[]}"); }; return sdf; }()); exports.sdf = sdf; __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_sdf_ts_1953_sdf\\",\\"fields\\":[]}"), sdf) ; function dot2(v) { return (0, std_math_1.dot)(v, v); } function dot3(v) { return (0, std_math_1.dot)(v, v); } function ndot(a, b) { return a[0] * b[0] - a[1] * b[1]; } }); /* impl sdf */ ` } ], emitSkipped: false, diagnostics: [] }, "/_std/geo.ts": { outputFiles: [ { name: "/_std/geo.js", writeByteOrderMark: false, text: 'var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, "default", { enumerable: true, value: v });\n}) : function(o, v) {\n o["default"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\ndefine(["require", "exports", "/std_math", "/std___std_all"], function (require, exports, __, std___std_all_1) {\n "use strict";\n Object.defineProperty(exports, "__esModule", { value: true });\n __ = __importStar(__);\n var globalVarGet = std___std_all_1.globalVarGet;\n var GeoSegment = /** @class */ (function () {\n function GeoSegment(data) {\n var _a, _b, _c, _d, _e, _f;\n this.start = ((_a = data.start) !== null && _a !== void 0 ? _a : __.FM.float_2_1_1(0.0, 0.0));\n this.end = ((_b = data.end) !== null && _b !== void 0 ? _b : __.FM.float_2_1_1(0.0, 0.0));\n this.kind = ((_c = data.kind) !== null && _c !== void 0 ? _c : (0 | 0));\n this.arcRadius = ((_d = data.arcRadius) !== null && _d !== void 0 ? _d : 0.0);\n this.arcStart = ((_e = data.arcStart) !== null && _e !== void 0 ? _e : 0.0);\n this.arcEnd = ((_f = data.arcEnd) !== null && _f !== void 0 ? _f : 0.0);\n }\n GeoSegment.prototype.clone = function () {\n return new GeoSegment({\n start: (0, std___std_all_1.__deepClone)(this.start),\n end: (0, std___std_all_1.__deepClone)(this.end),\n kind: (0, std___std_all_1.__deepClone)(this.kind),\n arcRadius: (0, std___std_all_1.__deepClone)(this.arcRadius),\n arcStart: (0, std___std_all_1.__deepClone)(this.arcStart),\n arcEnd: (0, std___std_all_1.__deepClone)(this.arcEnd),\n });\n };\n GeoSegment.prototype._getStructure = function () {\n return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_1845_GeoSegment\\",\\"fields\\":[[\\"start\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"kind\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"arcRadius\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcStart\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}");\n };\n return GeoSegment;\n }());\n __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_1845_GeoSegment\\",\\"fields\\":[[\\"start\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"kind\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"arcRadius\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcStart\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]}"), GeoSegment)\n /**@shadeup=struct*/ var GeoPoly = /** @class */ (function () {\n function GeoPoly(data) {\n var _a;\n this.segments = ((_a = data.segments) !== null && _a !== void 0 ? _a : []);\n }\n GeoPoly.prototype.area = function () { return 0.0; };\n GeoPoly.prototype.perimeter = function () { return 0.0; };\n GeoPoly.prototype.discretize = function () { var shader_self_temp = this; return this.clone(); };\n GeoPoly.prototype.clone = function () {\n return new GeoPoly({\n segments: (0, std___std_all_1.__deepClone)(this.segments),\n });\n };\n GeoPoly.prototype._getStructure = function () {\n return JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_2763_GeoPoly\\",\\"fields\\":[[\\"segments\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_1845_GeoSegment\\",\\"fields\\":[[\\"start\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"kind\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"arcRadius\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcStart\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]},\\"staticSize\\":1}]]}");\n };\n return GeoPoly;\n }());\n __shadeup_register_struct(JSON.parse("{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_2763_GeoPoly\\",\\"fields\\":[[\\"segments\\",{\\"type\\":\\"array\\",\\"element\\":{\\"type\\":\\"struct\\",\\"name\\":\\"str_i_iistd_geo_ts_1845_GeoSegment\\",\\"fields\\":[[\\"start\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"end\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float2\\"}],[\\"kind\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"int\\"}],[\\"arcRadius\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcStart\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}],[\\"arcEnd\\",{\\"type\\":\\"primitive\\",\\"name\\":\\"float\\"}]]},\\"staticSize\\":1}]]}"), GeoPoly)\n});\n/* impl GeoPoly */\n' } ], emitSkipped: false, diagnostics: [] } }; function countLines(str) { let count2 = 0; for (let i = 0; i < str.length; i++) { if (str[i] === "\n") { count2++; } } return count2; } function indexToRowColumn(str, index) { let row = 0; let column = 0; for (let i = 0; i < index; i++) { if (str[i] === "\n") { row++; column = 0; } else { column++; } } return { row, column }; } function rowColumnToIndex(str, row, column) { let index = 0; let currentRow = 0; let currentColumn = 0; while (currentRow < row || currentColumn < column) { if (str[index] === "\n") { currentRow++; currentColumn = 0; } else { currentColumn++; } index++; } return index; } function getDiffRange(a, b) { let diffs = diff(a, b); if (diffs.length === 1) { return null; } let startIndex = 0; let oldEndIndex = a.length; let newEndIndex = b.length; let insertions = 0; let deletions = 0; let neutrals = 0; for (let i = 0; i < diffs.length; i++) { let diff2 = diffs[i]; if (diff2[0] === 1) { insertions++; } else if (diff2[0] === -1) { deletions++; } else if (diff2[0] === 0) { neutrals++; } if (insertions > 1 || deletions > 1 || neutrals > 1) { return null; } } for (let i = 0; i < diffs.length; i++) { let diff2 = diffs[i]; if (diff2[0] === 0) { startIndex += diff2[1].length; } else if (diff2[0] === -1) { oldEndIndex = startIndex + diff2[1].length; newEndIndex = startIndex; break; } else if (diff2[0] === 1) { newEndIndex = startIndex + diff2[1].length; oldEndIndex = startIndex; break; } } return { startIndex, oldEndIndex, newEndIndex, startPosition: indexToRowColumn(a, startIndex), oldEndPosition: indexToRowColumn(a, oldEndIndex), newEndPosition: indexToRowColumn(b, newEndIndex) }; } function getReplaceRange(a, b) { let diffs = diff(a, b); if (diffs.length === 1) { return { content: b, range: { start: 0, length: a.length } }; } let insertions = 0; let deletions = 0; let neutrals = 0; for (let i = 0; i < diffs.length; i++) { let diff2 = diffs[i]; if (diff2[0] === 1) { insertions++; } else if (diff2[0] === -1) { deletions++; } else if (diff2[0] === 0) { neutrals++; } if (insertions > 1 || deletions > 1 || neutrals > 1) { return { content: b, range: { start: 0, length: a.length } }; } } let startIndex = 0; let oldEndIndex = a.length; let newEndIndex = b.length; for (let i = 0; i < diffs.length; i++) { let diff2 = diffs[i]; if (diff2[0] === 0) { startIndex += diff2[1].length; } else if (diff2[0] === -1) { oldEndIndex = startIndex + diff2[1].length; newEndIndex = startIndex; } else if (diff2[0] === 1) { newEndIndex = startIndex + diff2[1].length; break; } } return { content: b.substring(startIndex, newEndIndex), range: { start: startIndex, length: oldEndIndex - startIndex } }; } function getFunctionNodeName(node2, sourceFile) { if (!sourceFile) { sourceFile = node2.getSourceFile(); } if (ts.isMethodDeclaration(node2)) { let parentName = node2.parent && ts.isClassDeclaration(node2.parent) ? node2.parent.name?.getText() : "not_class"; return sourceFile.fileName + ":" + parentName + ":" + node2.name?.getText(); } return sourceFile.fileName + ":" + node2.name?.getText(); } function canTypesBeCasted(a, b) { if (a === b) { return true; } if (a.startsWith("float") && b.startsWith("int") || a.startsWith("int") && b.startsWith("float")) { let aSize = parseInt(a[a.length - 1]); let bSize = parseInt(b[b.length - 1]); if (aSize == bSize) { return true; } } return false; } class ShadeupEnvironment { constructor(opts) { this.files = []; this.parser = null; this.tsEnv = null; this.loads = /* @__PURE__ */ new Map(); this.libraries = /* @__PURE__ */ new Set(); this.assetMappings = /* @__PURE__ */ new Map(); this.validationDiagnostics = /* @__PURE__ */ new Map(); this.graphValidationDiagnostics = /* @__PURE__ */ new Map(); this.options = { esnext: false }; this.emitLogs = true; this.stdEmitCache = /* @__PURE__ */ new Map(); if (opts) { this.options = opts; } } async init() { this.parser = await getShadeupParser(); this.tsEnv = await makeTypescriptEnvironment(this); { for (let k of Object.keys(quickCache)) { this.stdEmitCache.set(k, quickCache[k]); } } } setAssetMapping(assets) { console.log("Set asset mapping", assets); this.assetMappings = new Map(assets); } print(...args) { if (this.emitLogs) { console.log(...args); } } reset() { this.tagGraph = new TagGraph(); for (let f of this.files) { if (f.path == "/file.ts" || f.path.startsWith("/_std/")) continue; this.tsEnv.system.$fsMap.delete(f.path); } this.files = []; this.validationDiagnostics.clear(); this.graphValidationDiagnostics.clear(); } /** * Wipes out the tagGraph and rebuilds all and tags */ applyTags() { let checker = this.tsEnv?.env.languageService.getProgram().getTypeChecker(); let files2 = this.tsEnv.env.languageService.getProgram().getSourceFiles(); this.tagGraph = new TagGraph(); for (let file of files2) { ts.forEachChild(file, (node2) => { if (ts.isFunctionDeclaration(node2) || ts.isMethodDeclaration(node2)) { let name = getFunctionNodeName(node2); this.tagGraph.addNode(name, node2); let tags = findShadeupTags(node2); for (let tag of tags) { this.tagGraph.addTag(name, tag); } } if (ts.isClassDeclaration(node2)) { ts.forEachChild(node2, (child) => { if (ts.isMethodDeclaration(child)) { let name = getFunctionNodeName(child); this.tagGraph.addNode(name, child); let tags = findShadeupTags(child); for (let tag of tags) { this.tagGraph.addTag(name, tag); } } }); } }); } const visitNode = (node2) => { if (ts.isCallExpression(node2)) { let exprSmybol = checker.getSymbolAtLocation(node2.expression); if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) { exprSmybol = checker.getAliasedSymbol(exprSmybol); } if (exprSmybol) { let funcDeclar = exprSmybol.getDeclarations()?.[0]; if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) { let referencedFunctionName = getFunctionNodeName(funcDeclar); let callingFunction = closest( node2, (n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) ); if (callingFunction && (ts.isFunctionDeclaration(callingFunction) || ts.isMethodDeclaration(callingFunction))) { let callingFunctionName = getFunctionNodeName(callingFunction); this.tagGraph.addEdge(referencedFunctionName, callingFunctionName); } } } } ts.forEachChild(node2, visitNode); }; for (let file of files2) { ts.forEachChild(file, (node2) => { if (ts.isFunctionDeclaration(node2) || ts.isMethodDeclaration(node2)) { ts.forEachChild(node2, visitNode); } if (ts.isClassDeclaration(node2)) { ts.forEachChild(node2, (child) => { if (ts.isMethodDeclaration(child)) { ts.forEachChild(child, visitNode); } }); } }); } this.tagGraph.propagateTags(); } async regenerate(filePath) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let addedFiles = /* @__PURE__ */ new Set(); this.graphValidationDiagnostics.clear(); let now = performance.now(); let outputs = []; this.applyTags(); this.print("Tagged in ", performance.now() - now, "ms"); now = performance.now(); let checker = this.tsEnv.env.languageService.getProgram().getTypeChecker(); const addFile = (path) => { if (this.stdEmitCache.has(path)) { outputs.push(this.stdEmitCache.get(path)); return; } if (addedFiles.has(path)) { return; } console.log("Adding file ", path); addedFiles.add(path); let sourceFile = this.files.find((f) => f.path === path); let shaders = this.renderShaders(path); if (sourceFile) { sourceFile.shaders = shaders; } let out = this.tsEnv?.env.languageService.getEmitOutput(path); if (out) { let sf = this.tsEnv.env.getSourceFile(path); if (sourceFile) { this.graphValidationDiagnostics.set(path, validateGraph(this, sourceFile, sf, checker)); let outputCode = this.mixInShaders(sourceFile, out?.outputFiles[0].text); out.outputFiles[0].text = outputCode; } if (sf) { out.outputFiles[0].text = this.mixInStructs(sf, out.outputFiles[0].text); } if (this.loads.has(path)) { let jsOut = `__shadeup_register_loads(${JSON.stringify( this.loads.get(path).map((p) => { return this.assetMappings.get(p) || p; }) )});`; out.outputFiles[0].text = jsOut + out.outputFiles[0].text; } if (this.libraries.size > 0) { let jsOut = `__shadeup_register_libs(${JSON.stringify(Array.from(this.libraries))});`; out.outputFiles[0].text = jsOut + out.outputFiles[0].text; } if (path.startsWith("/_std/") || path == "/file.ts" || path == "/std_math.ts" || path == "/static-math.ts" || path == "/std___std_all.ts" || path == "/std.ts") { this.stdEmitCache.set(path, out); } outputs.push(out); } }; const addDir = (path) => { let files2 = this.tsEnv?.system.readDirectory(path); if (files2) { for (let f of files2) { let dirExists = this.tsEnv?.system.directoryExists(path + f); if (dirExists) { addDir(path + f.replace(/^\//, "") + "/"); } else { if (f.endsWith(".d.ts")) continue; let p = path + f.replace(/^\//, ""); try { addFile(p); } catch (e) { console.error(e); } } } } }; if (filePath) { await Promise.all( filePath.map(async (f) => { let sourceFile = this.tsEnv.env.getSourceFile(f); if (sourceFile) { let refs = this.tsEnv.env.languageService.getFileReferences(f); for (let dep of refs) { let shadeupFile = this.files.find((f2) => f2.path === dep.fileName); if (shadeupFile) { await this.writeFile( shadeupFile.path, shadeupFile.content, this.stdEmitCache.has(shadeupFile.path) ); try { addFile(dep.fileName); } catch (e) { console.error(e); } } } try { addFile(f); } catch (e) { console.error(e); } } }) ); } else { addDir("/"); } let s = outputs.map( (o) => o.outputFiles.map((oo) => ({ path: oo.name, contents: oo.text })) ).flat(); this.print("Regenerated in", performance.now() - now, "ms"); return s; } mixInShaders(file, code) { let finalPass = code; for (let pair of file.shaders) { let shader = pair.glsl; let params = []; let paramsTyped = []; for (let param of Object.keys(shader.locals)) { let u = shader.locals[param]; params.push(`_ext_uniform_local_${param}: ${param}`); paramsTyped.push(`_ext_uniform_local_${param}: ${JSON.stringify(u)}`); } for (let param of Object.keys(shader.globals)) { let u = shader.globals[param]; params.push( `_ext_uniform_global_${param}: globalVarGet("${cleanName(u.fileName)}", "${param}")` ); paramsTyped.push(`_ext_uniform_global_${param}: ${JSON.stringify(u.structure)}`); } finalPass = `__shadeup_gen_shader("${shader.key}", { webgl: {${paramsTyped.join(", ")}}, webgpu: ${JSON.stringify({ attributeInput: pair.wgsl.attributeInput, attributeOutput: pair.wgsl.attributeOutput, locals: pair.wgsl.locals, globals: pair.wgsl.globals })} }, {webgpu: \`${pair.wgsl.source}\`,webgl:\`${pair.glsl.source}\`, software: () => {}}, ${JSON.stringify(shader.sourceMapping)}); ` + finalPass; } if (file.path === "/main.ts") { this.print("Final pass", finalPass); } return finalPass; } mixInStructs(root, code) { let finalPass = code; let structs = []; walkNodes(root, (node2) => { if (ts.isClassDeclaration(node2)) { if (hasShadeupDocTag(node2, "struct")) { let structName = node2.name?.getText() ?? "Unknown"; let struct = { name: structName, fields: [] }; for (let member of node2.members) { if (ts.isPropertyDeclaration(member)) { let name = member.name.getText(); let type2 = member.type?.getText() ?? "any"; struct.fields.push({ name, type: type2 }); } } structs.push(struct); } } }); let sBlocks = []; for (let struct of structs) { sBlocks.push( `__shadeup_register_struct("${struct.name}", {${JSON.stringify(struct.fields)}});` ); } return finalPass; } errors(files2) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let now = performance.now(); let all2 = []; for (let f of this.files) { if (files2) { if (!files2.includes(f.path)) { continue; } } let errors2 = this.tsEnv.env.languageService.getSemanticDiagnostics(f.path); let syntacticErrors = this.tsEnv.env.languageService.getSyntacticDiagnostics(f.path); all2.push( ...[...errors2, ...syntacticErrors].filter((e) => { if (e.code == 2345) { let parsed = /Argument of type '(.*)' is not assignable to parameter of type '(.*).*'/.exec( typeof e.messageText == "string" ? e.messageText : e.messageText.messageText ); if (parsed) { let [_, from, to] = parsed; if (canTypesBeCasted(from, to)) { return false; } } } else if (e.code == 2339) { let msgText = typeof e.messageText == "string" ? e.messageText : e.messageText.messageText; if (msgText.startsWith("Property '__index' does not exist on type '")) { return false; } } else if (e.code == 2705) { let msgText = typeof e.messageText == "string" ? e.messageText : e.messageText.messageText; if (msgText.startsWith( "An async function or method in ES5/ES3 requires the 'Promise' constructor." )) { return false; } } return true; }).map((e) => this.transformTSError(f, e)) ); let validationDiagnostics = this.validationDiagnostics.get(f.path) ?? []; all2.push(...validationDiagnostics.map((e) => this.transformTSError(f, e))); let graphValidationDiagnostics = this.graphValidationDiagnostics.get(f.path) ?? []; all2.push(...graphValidationDiagnostics.map((e) => this.transformTSError(f, e))); } this.print("Got errors in", performance.now() - now, "ms"); return all2; } completions(path, pos) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let file = this.files.find((f) => f.path === path); if (!file) { throw new Error("File not found"); } let source = file.transpiled; indexToRowColumn(source, pos); let backTransform = reverseLookupIndexMappingCursor(file.mapping, pos); let fp = this.tsEnv.env.getSourceFile(path); console.log(fp.getFullText()); console.log( fp.getFullText().substring(0, backTransform) + "^" + fp.getFullText().substring(backTransform) ); let completions = this.tsEnv.env.languageService.getCompletionsAtPosition( path, backTransform, { includeExternalModuleExports: true, includeInsertTextCompletions: true, includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true, includeInlayVariableTypeHints: true, includeCompletionsWithClassMemberSnippets: true, includeCompletionsWithSnippetText: true, includeAutomaticOptionalChainCompletions: true, includeCompletionsForImportStatements: true, useLabelDetailsInCompletionEntries: true, includeInlayPropertyDeclarationTypeHints: true }, {} ); if (!completions) { return []; } let entries = []; let maxCompletions = 100; for (let c2 of completions.entries) { if (entries.length >= maxCompletions) { break; } let range2 = null; if (c2.replacementSpan) { let startOffset = c2.replacementSpan.start; let endOffset = c2.replacementSpan.start + c2.replacementSpan.length; let offsetRangeReal = lookupIndexMappingRange(file.mapping, startOffset, endOffset); let start = indexToRowColumn(file.content, offsetRangeReal.start); let end = indexToRowColumn(file.content, offsetRangeReal.end); range2 = { startLineNumber: start.row + 1, startColumn: start.column + 1, endLineNumber: end.row + 1, endColumn: end.column + 1 }; } entries.push({ range: range2, completion: c2, details: this.tsEnv.env.languageService.getCompletionEntryDetails( path, backTransform, c2.name, {}, c2.source, {}, c2.data ) }); } console.log(entries); return entries; } classifications(path) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let file = this.files.find((f) => f.path === path); if (!file) { throw new Error("File not found"); } this.tsEnv.env.getSourceFile(path); this.tsEnv.env.languageService.getProgram().getTypeChecker(); let ranges = []; for (let symbolRange of file.parsedFlatSymbolMap) { let offsetRangeReal = reverseLookupIndexMappingRange( file.mapping, symbolRange.startIndex, symbolRange.endIndex ); if (offsetRangeReal.start != 0 && offsetRangeReal.end < file.transpiled.length - 1 && isFinite(offsetRangeReal.start) && isFinite(offsetRangeReal.end)) { let info = this.tsEnv.env.languageService.getQuickInfoAtPosition( path, offsetRangeReal.start ); if (info) { let backRange = lookupIndexMappingRange( file.mapping, info.textSpan.start, info.textSpan.start + info.textSpan.length ); let kind = info.kind; const funcMatch = /^\(alias\)\s+[^(]+\(/i; if (kind == "alias") { let fullStr = ""; let isNew = false; for (let p of info.displayParts) { fullStr += p.text; if (p.kind == "keyword" && (p.text == "class" || p.text == "new")) { kind = ts.ScriptElementKind.classElement; if (p.text == "new") { isNew = true; } } if (p.kind == "keyword" && p.text == "namespace") { kind = ts.ScriptElementKind.classElement; } if (p.kind == "keyword" && p.text == "type") { kind = ts.ScriptElementKind.classElement; } } if (!isNew && funcMatch.test(fullStr)) { kind = ts.ScriptElementKind.functionElement; } } ranges.push([backRange.start, backRange.end, kind]); } } } return { ranges }; } hover(path, pos) { if (!this.tsEnv) { throw new Error("Typescript environment not initialized"); } let file = this.files.find((f) => f.path === path); if (!file) { throw new Error("File not found"); } let source = file.transpiled; indexToRowColumn(source, pos); let backTransform = reverseLookupIndexMappingCursor(file.mapping, pos); this.tsEnv.env.getSourceFile(path); let hovers = this.tsEnv.env.languageService.getQuickInfoAtPosition(path, backTransform); if (!hovers) { return null; } let startOffset = hovers.textSpan.start; let endOffset = hovers.textSpan.start + hovers.textSpan.length; let offsetRangeReal = lookupIndexMappingRange(file.mapping, startOffset, endOffset); let start = indexToRowColumn(file.content, offsetRangeReal.start); let end = indexToRowColumn(file.content, offsetRangeReal.end); hovers.range = { startLineNumber: start.row + 1, startColumn: start.column + 1, endLineNumber: end.row + 1, endColumn: end.column + 1 }; return hovers; } getFileErrorData(f, estart, eend) { let file = this.files.find((f2) => f2.path === f.path); if (!file) { return { file: f, source: f.getFullText(), start: estart, end: eend }; } let start = indexToRowColumn(file.transpiled, estart ?? 0); let realStart = file.map?.originalPositionFor({ column: start.column, line: start.row + 1 }); let end = indexToRowColumn(file.transpiled, eend); let realEnd = file.map?.originalPositionFor({ column: end.column, line: end.row + 1 }); let startIndex = realStart?.line && realStart?.column ? rowColumnToIndex(file.content, realStart?.line, realStart?.column) : 0; let endIndex = realEnd?.line && realEnd?.column ? rowColumnToIndex(file.content, realEnd?.line, realEnd?.column) : 0; startIndex = lookupIndexMapping(file.mapping, estart ?? 0); endIndex = lookupIndexMapping(file.mapping, eend); let o = lookupIndexMappingRange(file.mapping, estart ?? 0, eend); startIndex = o.start; endIndex = o.end; return { file, source: file.content, start: startIndex, end: endIndex }; } transformTSError(file, error) { if (error.file === void 0) { return { error, file: file.path, message: error.messageText.toString() }; } const printReal = true; let { source, start, end } = this.getFileErrorData( error.file, error.start ?? 0, (error.start ?? 0) + (error.length ?? 0) ); { start = error.start ?? 0; end = (error.start ?? 0) + (error.length ?? 0); } let categorymapping = { [ts.DiagnosticCategory.Error]: ReportKind.Error, [ts.DiagnosticCategory.Warning]: ReportKind.Warning, [ts.DiagnosticCategory.Message]: ReportKind.Advice, [ts.DiagnosticCategory.Suggestion]: ReportKind.Advice }; let r = Report.build(categorymapping[error.category], file.path, start).with_code(error.code); if (typeof error.messageText === "string") { r = r.with_message(error.messageText); } function addMessage(msgObj) { if (typeof msgObj === "string") { r = r.with_label( Label.from([file.path, Range.new(start, Math.max(start, end))]).with_message(msgObj) ); } else { r = r.with_label( Label.from([file.path, Range.new(start, Math.max(start, end))]).with_message( nicerError(msgObj) ) ); for (let d of msgObj.next ?? []) { addMessage(d); } } } if (typeof error.messageText === "string") { addMessage(nicerError(error)); } else { addMessage(error.messageText); } for (let d of error.relatedInformation ?? []) { let relatedRange = { start: d.start ?? 0, end: (d.start ?? 0) + (d.length ?? 0) }; if (typeof d.messageText === "string") { r.with_label( Label.from([ file.path, Range.new(relatedRange.start, Math.max(relatedRange.start, relatedRange.end)) ]).with_message(nicerError(d)) ); } else { for (let d2 of d.messageText.next ?? []) { addMessage(d2); } } } let rf = r.finish(); let writer = mkStringWriter(); try { rf.printTo( [file.path, Source.from(printReal ? error.file.text : source)], writer ); } catch (e) { this.print(e); } let ansi_up2 = new AnsiUp(); let msg = writer.unwrap(); if (typeof process === "undefined" || typeof process.stdout === "undefined") { msg = ansi_up2.ansi_to_html(msg); } return { error, file: file.path, message: msg }; } async translateSource(file, range2 = null) { if (!this.parser) { throw new Error("Parser not initialized"); } let now = performance.now(); if (range2) file.oldTree?.edit(range2); let f = this.parser.parse(file.content, range2 ? file.oldTree ?? void 0 : void 0); if (file.oldTree) { let nowTree = performance.now(); file.oldTree.getChangedRanges(f); this.print("Got edited range in", performance.now() - nowTree, "ms"); } this.print("Parsed in", performance.now() - now, "ms"); file.oldTree = f; file.parsedFlatSymbolMap = this.extractFlatSymbolMap(f.rootNode); now = performance.now(); try { let ctx = new AstContext("file:///" + file.path); prePass(ctx, f.rootNode); let compiled = compile(ctx, f.rootNode); file.parseDiagnostics = ctx.diagnostics.map((d) => ({ message: d.message, startIndex: d.node.startIndex, endIndex: d.node.endIndex })); this.print("Compiled in", performance.now() - now, "ms"); now = performance.now(); let ss = { str: "", indexMapping: [] }; compiled.toString(ss); this.print("Rendered with source map in ", performance.now() - now, "ms"); this.print("---- Translated ----"); file.transpiled = ss.str; now = performance.now(); file.mapping = ss.indexMapping; this.print("Created source map consumer in", performance.now() - now, "ms"); } catch (e) { console.error("Error while compiling", e); this.print(f.rootNode.toString()); } } extractFlatSymbolMap(rootNode) { let symbols = []; let stack = [rootNode]; while (stack.length > 0) { let node2 = stack.pop(); if (node2.type === "identifier" || node2.type === "property_identifier" || node2.type === "type_identifier") { symbols.push({ startIndex: node2.startIndex, endIndex: node2.endIndex }); } for (let c2 of node2.children) { stack.push(c2); } } return symbols; } async writeFile(path, content, ignoreValidate = false) { if (!ignoreValidate) console.log("Writing", path); let now = performance.now(); let file = this.files.find((f) => f.path === path); let oldContent = ""; if (!file) { this.files.push({ path, content, transpiled: "", shaders: [], map: null, oldTree: null, mapping: [], parseDiagnostics: [], parsedFlatSymbolMap: [] }); file = this.files[this.files.length - 1]; } else { oldContent = file.content; file.content = content; } let nowDiff = performance.now(); let r = getDiffRange(oldContent, content); this.print( "Source code diff took", performance.now() - nowDiff, "ms", "with", countLines(content), "lines" ); let getNow = performance.now(); this.print("Get source file took", performance.now() - getNow, "ms"); await this.translateSource(file, r); let sf = this.tsEnv?.env.getSourceFile(path); if (sf) { nowDiff = performance.now(); let r2 = getReplaceRange(sf.text, file.transpiled); this.print( "TypeScript code diff took", performance.now() - nowDiff, "ms", "with", countLines(sf.text), "lines" ); let updateNow = performance.now(); this.print("Replacing", r2.range, "with", r2.content.length, "chars"); this.tsEnv?.env.updateFile(path, r2.content, r2.range); this.print("Update took", performance.now() - updateNow, "ms"); let finalText = this.tsEnv.env.getSourceFile(path)?.text; if (finalText !== file.transpiled) { console.error("Final text does not match transpiled text"); } } else { this.tsEnv?.env.createFile(path, file.transpiled); } this.print("---- Took", performance.now() - now, "ms ----"); this.print(""); if (!ignoreValidate) { let sourceFile = this.tsEnv?.env.getSourceFile(path); if (sourceFile) { let program = this.tsEnv?.env.languageService.getProgram(); let checker = program?.getTypeChecker(); if (checker) { this.validationDiagnostics.set(path, validate(file, sourceFile, checker)); } } } } async writeFileTypescript(path, content) { this.print("Writing", path); let now = performance.now(); let sf = this.tsEnv?.env.getSourceFile(path); if (sf) { let nowDiff = performance.now(); let r = getReplaceRange(sf.text, content); this.print(sf.text.substring(r.range.start, r.range.start + r.range.length), r.content); this.print( "TypeScript code diff took", performance.now() - nowDiff, "ms", "with", countLines(sf.text), "lines" ); let updateNow = performance.now(); this.print("Replacing", r.range, "with", r.content.length, "chars"); this.tsEnv?.env.updateFile(path, r.content, r.range); this.print("Update took", performance.now() - updateNow, "ms"); let finalText = this.tsEnv.env.getSourceFile(path)?.text; this.print(finalText); if (finalText !== content) { console.error("Final text does not match input text"); } } else { this.tsEnv?.env.createFile(path, content); } this.print("---- Took", performance.now() - now, "ms ----"); this.print(""); } addDiagnostic(path, diagnostic) { if (!this.validationDiagnostics.has(path)) { this.validationDiagnostics.set(path, []); } this.validationDiagnostics.get(path)?.push(diagnostic); } printNodeLocation(n) { let sf = n.getSourceFile(); let file = this.files.find((f) => f.path === sf.fileName); if (!file) { return "internal"; } else { let mapping = lookupIndexMappingRange(file.mapping, n.getStart(), n.getEnd()); let loc = indexToRowColumn(file.content, mapping.start); return `${sf.fileName}:${loc.row + 1}:${loc.column + 1}`; } } renderShaders(path) { let shaders = []; this.tsEnv?.env.getSourceFile(path); let program = this.tsEnv?.env.languageService.getProgram(); if (!program) { return []; } let checker = program?.getTypeChecker(); if (!checker) { return []; } for (let sourceFile of program?.getSourceFiles() ?? []) { if (sourceFile.fileName === path) { walkNodes(sourceFile, (node2) => { if (ts.isCallExpression(node2) && node2.expression.getText() == "makeShader") { let lhsType = checker?.getTypeAtLocation(node2.getChildAt(0)); let sig = lhsType?.getCallSignatures(); if (sig && sig[0] && sig[0].getDeclaration()) { let declaration = sig[0].getDeclaration(); if (hasShadeupDocTag(declaration, "shader")) { let isComputeShader = false; let computeShaderSize = [0, 0, 0]; let parentNode = node2.parent; if (parentNode && ts.isAsExpression(parentNode) && parentNode.parent && ts.isCallExpression(parentNode.parent)) { if (parentNode.parent.arguments.length === 2) { isComputeShader = true; let lastChildArg = parentNode.parent.arguments[1]; if (ts.isArrayLiteralExpression(lastChildArg)) { let elements = lastChildArg.elements; if (elements.length === 3) { computeShaderSize = [ parseInt(elements[0].getText().replace(/[^\d]/g, "")), parseInt(elements[1].getText().replace(/[^\d]/g, "")), parseInt(elements[2].getText().replace(/[^\d]/g, "")) ]; } } } } checker?.getTypeAtLocation(declaration); if (node2.arguments.length === 2) { if (ts.isStringLiteral(node2.arguments[0])) { let key = node2.arguments[0].text; try { let glslShader = addGLSLShader( key, node2.arguments[1], checker, this, isComputeShader, computeShaderSize ); let wgslShader = addWGSLShader( key, node2.arguments[1], checker, this, isComputeShader, computeShaderSize ); if (glslShader && wgslShader) { shaders.push({ glsl: glslShader, wgsl: wgslShader }); } } catch (e) { console.error(e); if (e instanceof GLSLCompilationError) { this.addDiagnostic(path, { file: e.node.getSourceFile(), code: 0, messageText: e.message + " (this is being used in the shader defined at " + this.printNodeLocation(node2) + ")", category: ts.DiagnosticCategory.Error, start: e.node.getStart(), length: 2 }); this.addDiagnostic(path, { file: node2.getSourceFile(), code: 0, messageText: "this shader has an error in its code (" + e.message + " at " + this.printNodeLocation(e.node) + ")", category: ts.DiagnosticCategory.Error, start: node2.getStart(), length: node2.getEnd() - node2.getStart() }); } } } } } } } }); } } return shaders; } patchFile(path, content, start, length) { } } function walkNodes(node2, cb) { cb(node2); node2.forEachChild((n) => walkNodes(n, cb)); } function hasShadeupDocTag(node2, tagName) { return ts.getJSDocTags(node2).some((tag) => tag.tagName.text === "shadeup" && tag.comment === "=" + tagName); } const std = "export { ui } from '/_std/ui';\r\nexport { mesh, Mesh } from '/_std/mesh';\r\nexport { sdf } from '/_std/sdf';\r\nexport { geo } from '/_std/geo';\r\nexport * from '/_std/native';\r\n"; const ui = "import { getShadeupLocalContext } from '/_std/context';\r\n\r\nexport namespace ui {\r\n export function puck(position: float2): float2 {\r\n return getShadeupLocalContext()._SHADEUP_UI_PUCK(position);\r\n }\r\n\r\n export function draggable(position: float2, radius: float = 10): float2 {\r\n return getShadeupLocalContext()._SHADEUP_UI_PUCK(position, radius, true);\r\n }\r\n\r\n export function textbox(value: string): string {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('textbox', value);\r\n }\r\n\r\n export function slider(value: float, min: float, max: float): float {\r\n return getShadeupLocalContext()._SHADEUP_UI_SLIDER(value, { min, max });\r\n }\r\n\r\n export function label(text: string): void {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('label', text);\r\n }\r\n\r\n export function checkbox(value: bool): bool {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('checkbox', value);\r\n }\r\n\r\n export function combo(value: string, options: string[]): string {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('combo', value, { options });\r\n }\r\n\r\n export function group(text: string): void {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('group', text);\r\n }\r\n\r\n export function button(text: string): bool {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('button', false, { text });\r\n }\r\n\r\n export function pop(): void {\r\n return getShadeupLocalContext()._SHADEUP_UI_CONTROL('pop');\r\n }\r\n}\r\n"; const native = `import { float4, float3, float, float2, bool, int } from '/std_math';\r import { texture2d } from '/_std/texture';\r import { Camera, Camera2d, quat } from '/_std/common';\r import { getShadeupLocalContext } from '/_std/context';\r \r export function shadeupMakeTextureFromUrl(url: string): texture2d {\r return getShadeupLocalContext()['shadeupMakeTextureFromUrlNative'](url);\r }\r \r export class FrameContext {\r /** Delta between the previous frame's time and this frame (in seconds */\r deltaTime: float;\r /** Current time in seconds from the start of the renderer */\r time: float;\r /** Canvas size in pixels */\r screenSize: float2;\r /** Current frame index */\r frame: int;\r \r /** Mouse/touch screen input state for this frame */\r mouse: MouseInputState = new MouseInputState();\r \r /** Keyboard input state for this frame */\r keyboard: KeyboardInputState = new KeyboardInputState();\r \r /** Controllable camera (Hold right click and use WASD to move) */\r camera: Camera = new Camera();\r \r camera2d: Camera2d = new Camera2d();\r \r configureCamera(options: {\r mode?: 'free' | 'orbit' | 'orbit-free';\r \r spinning?: boolean;\r \r initialPosition?: float3;\r initialPitch?: float;\r initialYaw?: float;\r \r speed?: float;\r \r orbitTarget?: float3;\r orbitDistance?: float;\r orbitPitch?: float;\r orbitYaw?: float;\r orbitMinDistance?: float;\r orbitMaxDistance?: float;\r orbitMinPitch?: float;\r orbitMaxPitch?: float;\r }) {}\r \r /**\r * Use external values from the host JavaScript environment.\r */\r input(key: string, defaultValue: T): T {\r return defaultValue;\r }\r \r /**\r * Send values to the host JavaScript environment.\r */\r output(key: string, value: T) {}\r }\r \r export class MouseInputState {\r /** Current mouse position relative to canvas in pixels ((0, 0) is the top left */\r screen: float2;\r /** Current mouse position mapped from 0-1 in canvas space ((0, 0) is the top left while (1, 1) is the bottom right */\r uv: float2;\r /** Caches the mouse position relative to canvas in pixels when any mouse button is pressed (resets after subsequent presses */\r startScreen: float2;\r /** Caches the mouse position mapped from 0-1 in canvas space when any mouse button is pressed (resets after subsequent presses */\r startUv: float2;\r /** If dragging, this will be the delta between the start and current mouse position */\r deltaUv: float2;\r /** If dragging, this will be the delta between the mouse position last frame and the current mouse position */\r frameDeltaUv: float2;\r /** If dragging, this will be the delta between the start and current mouse position */\r deltaScreen: float2;\r /** If dragging, this will be the delta between the mouse position last frame and the current mouse position */\r frameDeltaScreen: float2;\r /** , Some("Mouse button down state for buttons 0-3 (left, middle, right */\r button: [boolean, boolean, boolean] = [false, false, false];\r /** Mouse button pressed state for buttons 0-3 (left, middle, right) */\r clicked: [boolean, boolean, boolean] = [false, false, false];\r /** If currently dragging */\r dragging: bool;\r /** Accumulated mouse wheel movement for this frame in the range of -1 to 1 */\r wheel: float;\r /** Rate of change */\r velocity: float;\r /** Is the mouse focused within the screen */\r focused: bool;\r }\r \r export class KeyboardInputState {\r /** Is key down this frame */\r backspace: bool;\r \r /** Is key down this frame */\r tab: bool;\r \r /** Is key down this frame */\r enter: bool;\r \r /** Is key down this frame */\r shiftLeft: bool;\r \r /** Is key down this frame */\r shiftRight: bool;\r \r /** Is key down this frame */\r controlLeft: bool;\r \r /** Is key down this frame */\r controlRight: bool;\r \r /** Is key down this frame */\r altLeft: bool;\r \r /** Is key down this frame */\r altRight: bool;\r \r /** Is key down this frame */\r pause: bool;\r \r /** Is key down this frame */\r capsLock: bool;\r \r /** Is key down this frame */\r escape: bool;\r \r /** Is key down this frame */\r space: bool;\r \r /** Is key down this frame */\r pageUp: bool;\r \r /** Is key down this frame */\r pageDown: bool;\r \r /** Is key down this frame */\r end: bool;\r \r /** Is key down this frame */\r home: bool;\r \r /** Is key down this frame */\r arrowLeft: bool;\r \r /** Is key down this frame */\r arrowUp: bool;\r \r /** Is key down this frame */\r arrowRight: bool;\r \r /** Is key down this frame */\r arrowDown: bool;\r \r /** Is key down this frame */\r printScreen: bool;\r \r /** Is key down this frame */\r insert: bool;\r \r /** Is key down this frame */\r delete: bool;\r \r /** Is key down this frame */\r digit0: bool;\r \r /** Is key down this frame */\r digit1: bool;\r \r /** Is key down this frame */\r digit2: bool;\r \r /** Is key down this frame */\r digit3: bool;\r \r /** Is key down this frame */\r digit4: bool;\r \r /** Is key down this frame */\r digit5: bool;\r \r /** Is key down this frame */\r digit6: bool;\r \r /** Is key down this frame */\r digit7: bool;\r \r /** Is key down this frame */\r digit8: bool;\r \r /** Is key down this frame */\r digit9: bool;\r \r /** Is key down this frame */\r keyA: bool;\r \r /** Is key down this frame */\r keyB: bool;\r \r /** Is key down this frame */\r keyC: bool;\r \r /** Is key down this frame */\r keyD: bool;\r \r /** Is key down this frame */\r keyE: bool;\r \r /** Is key down this frame */\r keyF: bool;\r \r /** Is key down this frame */\r keyG: bool;\r \r /** Is key down this frame */\r keyH: bool;\r \r /** Is key down this frame */\r keyI: bool;\r \r /** Is key down this frame */\r keyJ: bool;\r \r /** Is key down this frame */\r keyK: bool;\r \r /** Is key down this frame */\r keyL: bool;\r \r /** Is key down this frame */\r keyM: bool;\r \r /** Is key down this frame */\r keyN: bool;\r \r /** Is key down this frame */\r keyO: bool;\r \r /** Is key down this frame */\r keyP: bool;\r \r /** Is key down this frame */\r keyQ: bool;\r \r /** Is key down this frame */\r keyR: bool;\r \r /** Is key down this frame */\r keyS: bool;\r \r /** Is key down this frame */\r keyT: bool;\r \r /** Is key down this frame */\r keyU: bool;\r \r /** Is key down this frame */\r keyV: bool;\r \r /** Is key down this frame */\r keyW: bool;\r \r /** Is key down this frame */\r keyX: bool;\r \r /** Is key down this frame */\r keyY: bool;\r \r /** Is key down this frame */\r keyZ: bool;\r \r /** Is key down this frame */\r metaLeft: bool;\r \r /** Is key down this frame */\r metaRight: bool;\r \r /** Is key down this frame */\r contextMenu: bool;\r \r /** Is key down this frame */\r numpad0: bool;\r \r /** Is key down this frame */\r numpad1: bool;\r \r /** Is key down this frame */\r numpad2: bool;\r \r /** Is key down this frame */\r numpad3: bool;\r \r /** Is key down this frame */\r numpad4: bool;\r \r /** Is key down this frame */\r numpad5: bool;\r \r /** Is key down this frame */\r numpad6: bool;\r \r /** Is key down this frame */\r numpad7: bool;\r \r /** Is key down this frame */\r numpad8: bool;\r \r /** Is key down this frame */\r numpad9: bool;\r \r /** Is key down this frame */\r numpadMultiply: bool;\r \r /** Is key down this frame */\r numpadAdd: bool;\r \r /** Is key down this frame */\r numpadSubtract: bool;\r \r /** Is key down this frame */\r numpadDecimal: bool;\r \r /** Is key down this frame */\r numpadDivide: bool;\r \r /** Is key down this frame */\r f1: bool;\r \r /** Is key down this frame */\r f2: bool;\r \r /** Is key down this frame */\r f3: bool;\r \r /** Is key down this frame */\r f4: bool;\r \r /** Is key down this frame */\r f5: bool;\r \r /** Is key down this frame */\r f6: bool;\r \r /** Is key down this frame */\r f7: bool;\r \r /** Is key down this frame */\r f8: bool;\r \r /** Is key down this frame */\r f9: bool;\r \r /** Is key down this frame */\r f10: bool;\r \r /** Is key down this frame */\r f11: bool;\r \r /** Is key down this frame */\r f12: bool;\r \r /** Is key down this frame */\r numLock: bool;\r \r /** Is key down this frame */\r scrollLock: bool;\r \r /** Is key down this frame */\r semicolon: bool;\r \r /** Is key down this frame */\r equal: bool;\r \r /** Is key down this frame */\r comma: bool;\r \r /** Is key down this frame */\r minus: bool;\r \r /** Is key down this frame */\r period: bool;\r \r /** Is key down this frame */\r slash: bool;\r \r /** Is key down this frame */\r backquote: bool;\r \r /** Is key down this frame */\r bracketLeft: bool;\r \r /** Is key down this frame */\r backslash: bool;\r \r /** Is key down this frame */\r bracketRight: bool;\r \r /** Is key down this frame */\r quote: bool;\r \r /** Key pressed, triggered once until released */ pressedBackspace: bool;\r /** Key pressed, triggered once until released */ pressedTab: bool;\r /** Key pressed, triggered once until released */ pressedEnter: bool;\r /** Key pressed, triggered once until released */ pressedShiftLeft: bool;\r /** Key pressed, triggered once until released */ pressedShiftRight: bool;\r /** Key pressed, triggered once until released */ pressedControlLeft: bool;\r /** Key pressed, triggered once until released */ pressedControlRight: bool;\r /** Key pressed, triggered once until released */ pressedAltLeft: bool;\r /** Key pressed, triggered once until released */ pressedAltRight: bool;\r /** Key pressed, triggered once until released */ pressedPause: bool;\r /** Key pressed, triggered once until released */ pressedCapsLock: bool;\r /** Key pressed, triggered once until released */ pressedEscape: bool;\r /** Key pressed, triggered once until released */ pressedSpace: bool;\r /** Key pressed, triggered once until released */ pressedPageUp: bool;\r /** Key pressed, triggered once until released */ pressedPageDown: bool;\r /** Key pressed, triggered once until released */ pressedEnd: bool;\r /** Key pressed, triggered once until released */ pressedHome: bool;\r /** Key pressed, triggered once until released */ pressedArrowLeft: bool;\r /** Key pressed, triggered once until released */ pressedArrowUp: bool;\r /** Key pressed, triggered once until released */ pressedArrowRight: bool;\r /** Key pressed, triggered once until released */ pressedArrowDown: bool;\r /** Key pressed, triggered once until released */ pressedPrintScreen: bool;\r /** Key pressed, triggered once until released */ pressedInsert: bool;\r /** Key pressed, triggered once until released */ pressedDelete: bool;\r /** Key pressed, triggered once until released */ pressedDigit0: bool;\r /** Key pressed, triggered once until released */ pressedDigit1: bool;\r /** Key pressed, triggered once until released */ pressedDigit2: bool;\r /** Key pressed, triggered once until released */ pressedDigit3: bool;\r /** Key pressed, triggered once until released */ pressedDigit4: bool;\r /** Key pressed, triggered once until released */ pressedDigit5: bool;\r /** Key pressed, triggered once until released */ pressedDigit6: bool;\r /** Key pressed, triggered once until released */ pressedDigit7: bool;\r /** Key pressed, triggered once until released */ pressedDigit8: bool;\r /** Key pressed, triggered once until released */ pressedDigit9: bool;\r /** Key pressed, triggered once until released */ pressedKeyA: bool;\r /** Key pressed, triggered once until released */ pressedKeyB: bool;\r /** Key pressed, triggered once until released */ pressedKeyC: bool;\r /** Key pressed, triggered once until released */ pressedKeyD: bool;\r /** Key pressed, triggered once until released */ pressedKeyE: bool;\r /** Key pressed, triggered once until released */ pressedKeyF: bool;\r /** Key pressed, triggered once until released */ pressedKeyG: bool;\r /** Key pressed, triggered once until released */ pressedKeyH: bool;\r /** Key pressed, triggered once until released */ pressedKeyI: bool;\r /** Key pressed, triggered once until released */ pressedKeyJ: bool;\r /** Key pressed, triggered once until released */ pressedKeyK: bool;\r /** Key pressed, triggered once until released */ pressedKeyL: bool;\r /** Key pressed, triggered once until released */ pressedKeyM: bool;\r /** Key pressed, triggered once until released */ pressedKeyN: bool;\r /** Key pressed, triggered once until released */ pressedKeyO: bool;\r /** Key pressed, triggered once until released */ pressedKeyP: bool;\r /** Key pressed, triggered once until released */ pressedKeyQ: bool;\r /** Key pressed, triggered once until released */ pressedKeyR: bool;\r /** Key pressed, triggered once until released */ pressedKeyS: bool;\r /** Key pressed, triggered once until released */ pressedKeyT: bool;\r /** Key pressed, triggered once until released */ pressedKeyU: bool;\r /** Key pressed, triggered once until released */ pressedKeyV: bool;\r /** Key pressed, triggered once until released */ pressedKeyW: bool;\r /** Key pressed, triggered once until released */ pressedKeyX: bool;\r /** Key pressed, triggered once until released */ pressedKeyY: bool;\r /** Key pressed, triggered once until released */ pressedKeyZ: bool;\r /** Key pressed, triggered once until released */ pressedMetaLeft: bool;\r /** Key pressed, triggered once until released */ pressedMetaRight: bool;\r /** Key pressed, triggered once until released */ pressedContextMenu: bool;\r /** Key pressed, triggered once until released */ pressedNumpad0: bool;\r /** Key pressed, triggered once until released */ pressedNumpad1: bool;\r /** Key pressed, triggered once until released */ pressedNumpad2: bool;\r /** Key pressed, triggered once until released */ pressedNumpad3: bool;\r /** Key pressed, triggered once until released */ pressedNumpad4: bool;\r /** Key pressed, triggered once until released */ pressedNumpad5: bool;\r /** Key pressed, triggered once until released */ pressedNumpad6: bool;\r /** Key pressed, triggered once until released */ pressedNumpad7: bool;\r /** Key pressed, triggered once until released */ pressedNumpad8: bool;\r /** Key pressed, triggered once until released */ pressedNumpad9: bool;\r /** Key pressed, triggered once until released */ pressedNumpadMultiply: bool;\r /** Key pressed, triggered once until released */ pressedNumpadAdd: bool;\r /** Key pressed, triggered once until released */ pressedNumpadSubtract: bool;\r /** Key pressed, triggered once until released */ pressedNumpadDecimal: bool;\r /** Key pressed, triggered once until released */ pressedNumpadDivide: bool;\r /** Key pressed, triggered once until released */ pressedF1: bool;\r /** Key pressed, triggered once until released */ pressedF2: bool;\r /** Key pressed, triggered once until released */ pressedF3: bool;\r /** Key pressed, triggered once until released */ pressedF4: bool;\r /** Key pressed, triggered once until released */ pressedF5: bool;\r /** Key pressed, triggered once until released */ pressedF6: bool;\r /** Key pressed, triggered once until released */ pressedF7: bool;\r /** Key pressed, triggered once until released */ pressedF8: bool;\r /** Key pressed, triggered once until released */ pressedF9: bool;\r /** Key pressed, triggered once until released */ pressedF10: bool;\r /** Key pressed, triggered once until released */ pressedF11: bool;\r /** Key pressed, triggered once until released */ pressedF12: bool;\r /** Key pressed, triggered once until released */ pressedNumLock: bool;\r /** Key pressed, triggered once until released */ pressedScrollLock: bool;\r /** Key pressed, triggered once until released */ pressedSemicolon: bool;\r /** Key pressed, triggered once until released */ pressedEqual: bool;\r /** Key pressed, triggered once until released */ pressedComma: bool;\r /** Key pressed, triggered once until released */ pressedMinus: bool;\r /** Key pressed, triggered once until released */ pressedPeriod: bool;\r /** Key pressed, triggered once until released */ pressedSlash: bool;\r /** Key pressed, triggered once until released */ pressedBackquote: bool;\r /** Key pressed, triggered once until released */ pressedBracketLeft: bool;\r /** Key pressed, triggered once until released */ pressedBackslash: bool;\r /** Key pressed, triggered once until released */ pressedBracketRight: bool;\r /** Key pressed, triggered once until released */ pressedQuote: bool;\r /** 2D vector that encodes the arrow keys and WASD aligned with the screen (e.g. up arrow = (0, -1)) */\r arrowVector: float2;\r }\r \r declare global {\r const env: FrameContext;\r }\r `; const buffer = "import { getValueSize } from '../engine/adapters/webgpu';\r\nimport { getShadeupLocalContext } from '/_std/context';\r\nimport {\r\n float4,\r\n float3,\r\n float,\r\n float2,\r\n bool,\r\n int,\r\n int2,\r\n int3,\r\n int4,\r\n uint,\r\n uint2,\r\n uint3,\r\n uint4,\r\n atomic,\r\n intifyVector\r\n} from '/std_math';\r\n\r\nlet __ = { intifyVector };\r\n\r\nexport class buffer_internal {\r\n __opaque_buffer: true = true;\r\n\r\n structArray: T[] | null = null;\r\n floatArray: Float32Array | null = null;\r\n intArray: Int32Array | null = null;\r\n uintArray: Uint32Array | null = null;\r\n arrayBuffer: ArrayBuffer | null = null;\r\n vectorSize: int = 0;\r\n typeName: string;\r\n\r\n platformPayload: any = null;\r\n adapter: any = null;\r\n\r\n dirty: boolean = false;\r\n pendingWrites: number = 0;\r\n cpuReadDirty: boolean = false;\r\n cpuWriteDirty: boolean = false;\r\n\r\n elementCount: int = 0;\r\n elementBytes: int = 0;\r\n structured: boolean = false;\r\n\r\n fastIndex: (index: int) => T;\r\n fastIndexAssign: (index: int, value: T) => void;\r\n\r\n destroy() {\r\n this.adapter.destroyBuffer(this);\r\n }\r\n\r\n [index: number]: T;\r\n\r\n __index(index: int | uint): T {\r\n // this.download();\r\n // return this.fastIndex(index);\r\n return null as any;\r\n }\r\n\r\n __index_assign(index: int | uint, value: T): void {\r\n // this.download();\r\n // this.cpuWriteDirty = true;\r\n // this.fastIndexAssign(index, value);\r\n }\r\n\r\n __index_assign_op(op_fn: (a: T, b: T) => T, index: int | uint, value: T): void {\r\n // this.download();\r\n // this.cpuWriteDirty = true;\r\n // this.fastIndexAssign(index, op_fn(this.fastIndex(index), value));\r\n }\r\n\r\n len() {\r\n return this.elementCount;\r\n }\r\n\r\n /**\r\n * Returns the underlying cpu buffer as a typed array.\r\n *\r\n * > [!NOTE]\r\n * > This is considerably faster than using the raw index [] operator.\r\n *\r\n * > [!NOTE]\r\n * > If the buffer contents are structured (atomic, or a struct), this will return a normal array\r\n *\r\n * ```shadeup\r\n * let buf = buffer();\r\n * let data = buf.getData();\r\n *\r\n * for (let i = 0; i < data.length; i += 4) {\r\n * // Do something with data[i]\r\n * }\r\n * ```\r\n */\r\n getData(): Uint32Array | Float32Array | Uint8Array | Int32Array | T[] {\r\n if (this.structured) {\r\n return this.structArray!;\r\n } else {\r\n return this.floatArray ?? this.intArray ?? this.uintArray ?? new Uint8Array(0);\r\n }\r\n }\r\n\r\n write(other: buffer_internal) {\r\n if (!this.adapter) return;\r\n\r\n this.adapter.copyBufferToBuffer(other, this);\r\n }\r\n\r\n watchMutation: boolean = false;\r\n\r\n /** @shadeup=tag(async) @shadeup=noemit_gpu */\r\n async download() {\r\n if (!this.adapter) return;\r\n\r\n if (this.pendingWrites > 0) {\r\n getShadeupLocalContext().flushAdapter();\r\n }\r\n\r\n if (this.cpuReadDirty) {\r\n this.cpuReadDirty = false;\r\n await this.adapter.downloadBuffer(this);\r\n }\r\n }\r\n\r\n downloadAsync(): Promise {\r\n return this['download']();\r\n }\r\n\r\n /** @shadeup=noemit_gpu */\r\n upload(): void {\r\n if (!this.adapter) return;\r\n\r\n if (this.cpuWriteDirty) {\r\n this.cpuWriteDirty = false;\r\n this.adapter.uploadBuffer(this);\r\n }\r\n }\r\n symbol: Symbol = Symbol();\r\n\r\n constructor(size: int, typeName: string, structure: any) {\r\n this.adapter = getShadeupLocalContext().shadeupGetGraphicsAdapter();\r\n this.typeName = typeName;\r\n if (structure) {\r\n if (structure.name && !structure.name.startsWith('atomic')) {\r\n this.typeName = structure.name;\r\n }\r\n }\r\n this.elementCount = size;\r\n this.elementBytes = 4;\r\n if (\r\n typeName == 'float4' ||\r\n typeName == 'float3' ||\r\n typeName == 'float2' ||\r\n typeName == 'float'\r\n ) {\r\n this.vectorSize = 1;\r\n\r\n this.fastIndex = (index: int) => {\r\n return this.floatArray![index] as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.floatArray![index] = value as float;\r\n };\r\n\r\n if (typeName == 'float4') {\r\n this.vectorSize = 4;\r\n\r\n this.fastIndex = (index: int) => {\r\n return float4(\r\n this.floatArray![index * 4],\r\n this.floatArray![index * 4 + 1],\r\n this.floatArray![index * 4 + 2],\r\n this.floatArray![index * 4 + 3]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: float4) => {\r\n this.floatArray![index * 4] = value[0];\r\n this.floatArray![index * 4 + 1] = value[1];\r\n this.floatArray![index * 4 + 2] = value[2];\r\n this.floatArray![index * 4 + 3] = value[3];\r\n };\r\n }\r\n\r\n if (typeName == 'float3') {\r\n this.vectorSize = 3;\r\n\r\n this.fastIndex = (index: int) => {\r\n return float3(\r\n this.floatArray![index * 3],\r\n this.floatArray![index * 3 + 1],\r\n this.floatArray![index * 3 + 2]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: float3) => {\r\n this.floatArray![index * 3] = value[0];\r\n this.floatArray![index * 3 + 1] = value[1];\r\n this.floatArray![index * 3 + 2] = value[2];\r\n };\r\n }\r\n if (typeName == 'float2') {\r\n this.vectorSize = 2;\r\n\r\n this.fastIndex = (index: int) => {\r\n return float2(this.floatArray![index * 2], this.floatArray![index * 2 + 1]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: float2) => {\r\n this.floatArray![index * 2] = value[0];\r\n this.floatArray![index * 2 + 1] = value[1];\r\n };\r\n }\r\n this.floatArray = new Float32Array(size * this.vectorSize);\r\n this.arrayBuffer = this.floatArray.buffer;\r\n } else if (\r\n typeName == 'int4' ||\r\n typeName == 'int3' ||\r\n typeName == 'int2' ||\r\n typeName == 'int'\r\n ) {\r\n this.vectorSize = 1;\r\n\r\n this.fastIndex = (index: int) => {\r\n return this.intArray![index] as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.intArray![index] = value as int;\r\n };\r\n\r\n if (typeName == 'int4') {\r\n this.vectorSize = 4;\r\n\r\n this.fastIndex = (index: int) => {\r\n return int4(\r\n this.intArray![index * 4],\r\n this.intArray![index * 4 + 1],\r\n this.intArray![index * 4 + 2],\r\n this.intArray![index * 4 + 3]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: int4) => {\r\n this.intArray![index * 4] = value[0];\r\n this.intArray![index * 4 + 1] = value[1];\r\n this.intArray![index * 4 + 2] = value[2];\r\n this.intArray![index * 4 + 3] = value[3];\r\n };\r\n }\r\n\r\n if (typeName == 'int3') {\r\n this.vectorSize = 3;\r\n\r\n this.fastIndex = (index: int) => {\r\n return int3(\r\n this.intArray![index * 3],\r\n this.intArray![index * 3 + 1],\r\n this.intArray![index * 3 + 2]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: int3) => {\r\n this.intArray![index * 3] = value[0];\r\n this.intArray![index * 3 + 1] = value[1];\r\n this.intArray![index * 3 + 2] = value[2];\r\n };\r\n }\r\n\r\n if (typeName == 'int2') {\r\n this.vectorSize = 2;\r\n\r\n this.fastIndex = (index: int) => {\r\n return int2(this.intArray![index * 2], this.intArray![index * 2 + 1]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: int2) => {\r\n this.intArray![index * 2] = value[0];\r\n this.intArray![index * 2 + 1] = value[1];\r\n };\r\n }\r\n\r\n this.intArray = new Int32Array(size * this.vectorSize);\r\n this.arrayBuffer = this.intArray.buffer;\r\n } else if (\r\n typeName == 'uint4' ||\r\n typeName == 'uint3' ||\r\n typeName == 'uint2' ||\r\n typeName == 'uint'\r\n ) {\r\n this.vectorSize = 1;\r\n\r\n this.fastIndex = (index: int) => {\r\n return this.uintArray![index] as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.uintArray![index] = value as uint;\r\n };\r\n\r\n if (typeName == 'uint4') {\r\n this.vectorSize = 4;\r\n\r\n this.fastIndex = (index: int) => {\r\n return uint4(\r\n this.uintArray![index * 4],\r\n this.uintArray![index * 4 + 1],\r\n this.uintArray![index * 4 + 2],\r\n this.uintArray![index * 4 + 3]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: uint4) => {\r\n this.uintArray![index * 4] = value[0];\r\n this.uintArray![index * 4 + 1] = value[1];\r\n this.uintArray![index * 4 + 2] = value[2];\r\n this.uintArray![index * 4 + 3] = value[3];\r\n };\r\n }\r\n\r\n if (typeName == 'uint3') {\r\n this.vectorSize = 3;\r\n\r\n this.fastIndex = (index: int) => {\r\n return uint3(\r\n this.uintArray![index * 3],\r\n this.uintArray![index * 3 + 1],\r\n this.uintArray![index * 3 + 2]\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: uint3) => {\r\n this.uintArray![index * 3] = value[0];\r\n this.uintArray![index * 3 + 1] = value[1];\r\n this.uintArray![index * 3 + 2] = value[2];\r\n };\r\n }\r\n\r\n if (typeName == 'uint2') {\r\n this.vectorSize = 2;\r\n\r\n this.fastIndex = (index: int) => {\r\n return uint2(this.uintArray![index * 2], this.uintArray![index * 2 + 1]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: uint2) => {\r\n this.uintArray![index * 2] = value[0];\r\n this.uintArray![index * 2 + 1] = value[1];\r\n };\r\n }\r\n\r\n this.uintArray = new Uint32Array(size * this.vectorSize);\r\n this.arrayBuffer = this.uintArray.buffer;\r\n } else {\r\n this.structured = true;\r\n\r\n if (typeName.startsWith('atomic<')) {\r\n // this.structArray = new Array(size);\r\n this.arrayBuffer = new ArrayBuffer(size * 4);\r\n\r\n this.watchMutation = true;\r\n this.vectorSize = 1;\r\n this.elementBytes = 4;\r\n this.elementCount = size;\r\n for (let i = 0; i < size; i++) {\r\n // this.structArray[i] = atomic(0) as T;\r\n }\r\n if (typeName == 'atomic') {\r\n this.uintArray = new Uint32Array(this.arrayBuffer);\r\n this.fastIndex = (index: int) => {\r\n return atomic(this.uintArray![index]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.uintArray![index] = value.__value as any;\r\n };\r\n } else {\r\n this.intArray = new Int32Array(this.arrayBuffer);\r\n this.fastIndex = (index: int) => {\r\n return atomic(this.intArray![index]) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.intArray![index] = value.__value as any;\r\n };\r\n }\r\n } else {\r\n let elementSize = this.adapter.getValueSize(structure);\r\n let realSize = elementSize * size;\r\n this.elementCount = size;\r\n this.elementBytes = elementSize;\r\n this.arrayBuffer = new ArrayBuffer(realSize);\r\n\r\n this.fastIndex = (index: int) => {\r\n return this.adapter.readStructuredBuffer(\r\n structure,\r\n this.arrayBuffer,\r\n index * elementSize\r\n ) as T;\r\n };\r\n this.fastIndexAssign = (index: int, value: T) => {\r\n this.cpuWriteDirty = true;\r\n this.adapter.writeStructuredBuffer(\r\n structure,\r\n value,\r\n this.arrayBuffer,\r\n index * (elementSize / 4)\r\n );\r\n };\r\n }\r\n }\r\n\r\n (this.__index as any) = (index: int): T => {\r\n // await this.download();\r\n if (this.watchMutation) {\r\n let data = this.fastIndex(index);\r\n (data as any).$mutate = (to?: T) => {\r\n this.cpuWriteDirty = true;\r\n if (to !== undefined) {\r\n if (this.intArray) {\r\n this.intArray[index] = to as any;\r\n } else {\r\n this.uintArray![index] = to as any;\r\n }\r\n }\r\n };\r\n return data;\r\n } else {\r\n return this.fastIndex(index);\r\n }\r\n };\r\n\r\n this.__index_assign = (index: int, value: T): void => {\r\n // await this.download();\r\n this.cpuWriteDirty = true;\r\n this.fastIndexAssign(index, value);\r\n };\r\n\r\n this.__index_assign_op = (op_fn: (a: T, b: T) => T, index: int, value: T): void => {\r\n // await this.download();\r\n this.cpuWriteDirty = true;\r\n\r\n this.fastIndexAssign(index, op_fn(this.fastIndex(index), value));\r\n };\r\n }\r\n}\r\n\r\nexport type buffer = buffer_internal;\r\n\r\n/**\r\n * Creates a new buffer.\r\n * ```shadeup\r\n * let buf = buffer(100);\r\n *\r\n * ```\r\n */\r\nexport function buffer(data: T[], typeName: string, structure?: object): buffer;\r\nexport function buffer(size: int, typeName: string, structure?: object): buffer;\r\nexport function buffer(e1: any, typeName: string, structure?: object): buffer {\r\n if (typeof e1 === 'number') {\r\n let size = e1;\r\n let buf = new buffer_internal(size, typeName, structure!);\r\n return buf;\r\n } else {\r\n let data = e1;\r\n let buf = new buffer_internal(data.length, typeName, structure!);\r\n for (let i = 0; i < data.length; i++) {\r\n buf.fastIndexAssign(i, data[i]);\r\n }\r\n return buf;\r\n }\r\n}\r\n"; const texture = "import {\r\n float4,\r\n float3,\r\n float,\r\n float2,\r\n bool,\r\n int,\r\n int2,\r\n int3,\r\n int4,\r\n uint,\r\n uint2,\r\n uint3,\r\n uint4,\r\n uint8\r\n} from '/std_math';\r\n\r\nimport {\r\n ShaderInput,\r\n ShaderOutput,\r\n shader,\r\n draw,\r\n drawInstanced,\r\n drawAdvanced,\r\n drawIndexed\r\n} from '/_std/drawIndexed';\r\n\r\nimport { Mesh } from '/_std/mesh';\r\nimport { PaintingContext } from '/_std/paint';\r\nimport { getShadeupLocalContext } from '/_std/context';\r\n\r\nexport class texture2d_internal_empty {\r\n __opaque_texture2d: true = true;\r\n\r\n /** @shadeup=glsl(!texture($self$, $0$)) */\r\n __index(index: int2 | uint2): T {\r\n return null as any;\r\n }\r\n\r\n __index_assign(index: int2 | uint2, value: T): void {\r\n return null as any;\r\n }\r\n\r\n getFast(index: int2 | uint2): T {\r\n return null as any;\r\n }\r\n\r\n setFast(index: int2 | uint2, value: T): void {\r\n return null as any;\r\n }\r\n\r\n /** @shadeup=tag(async) */\r\n download(): void {}\r\n\r\n downloadAsync(): Promise {\r\n return null as any;\r\n }\r\n\r\n /**\r\n * Returns the underlying cpu buffer as a typed array.\r\n *\r\n * Note that this is considerably faster than using the raw index [] operator.\r\n *\r\n * ```shadeup\r\n * let tex = texture2d();\r\n * let data = tex.getData();\r\n *\r\n * for (let i = 0; i < data.length; i += 4) {\r\n * let r = data[i];\r\n * let g = data[i + 1];\r\n * let b = data[i + 2];\r\n * let a = data[i + 3];\r\n *\r\n * // Do something with the pixel\r\n * }\r\n * ```\r\n */\r\n getData(): Uint32Array | Float32Array | Uint8Array | Int32Array {\r\n return new Uint32Array(0);\r\n }\r\n\r\n upload(): void {}\r\n\r\n size: float2 = [0, 0];\r\n\r\n paint: PaintingContext = null as any;\r\n\r\n sample(position: float2): float4 {}\r\n\r\n clear(color: float | float4 | 'auto' = 'auto'): void {}\r\n flush(): void {}\r\n // draw(\r\n // geometry: Mesh,\r\n // vertexShader: shader,\r\n // pixelShader: shader\r\n // ): void;\r\n // draw(fullScreenPixelShader: shader): void;\r\n // draw() {\r\n // throw new Error('Not implemented');\r\n // }\r\n\r\n draw: typeof draw;\r\n\r\n drawIndexed: typeof drawIndexed;\r\n drawAdvanced: typeof drawAdvanced;\r\n drawInstanced: typeof drawInstanced;\r\n\r\n /** Release the texture */\r\n destroy() {}\r\n}\r\n\r\nexport type texture2d = texture2d_internal_empty;\r\nexport type TextureFormat = '32bit' | '16bit' | '8bit' | 'depth' | 'depth-32' | 'auto';\r\nexport function texture2d(\r\n size: float2,\r\n format: TextureFormat,\r\n type: string\r\n): texture2d {\r\n return getShadeupLocalContext().shadeupMakeTextureInternal(size, format, type) as texture2d;\r\n}\r\n\r\nexport class texture3d_internal_empty {\r\n __opaque_texture3d: true = true;\r\n\r\n /** @shadeup=glsl(!texture($self$, $0$)) */\r\n __index(index: int3): T {\r\n return null as any;\r\n }\r\n __index_assign(index: int3, value: T): void {}\r\n size: float3 = [0, 0, 0];\r\n\r\n sample(position: float3): float4 {}\r\n}\r\n\r\nexport type texture3d = texture3d_internal_empty;\r\n\r\nexport function texture3d(size: float3, type: string): texture3d {\r\n return getShadeupLocalContext().shadeupMakeTextureInternal(size, type) as texture3d;\r\n}\r\n"; const physics = "import type RAPIER2DNamespace from '@dimforge/rapier2d/rapier';\r\nimport type RAPIER3DNamespace from '@dimforge/rapier3d/rapier';\r\nimport type { float, float2, float3 } from './types';\r\n\r\ntype RAPIER2D = typeof RAPIER2DNamespace;\r\n\r\nexport class PhysicsCollider2d {\r\n rapier: RAPIER2D;\r\n world: RAPIER2DNamespace.World;\r\n collider: RAPIER2DNamespace.Collider;\r\n\r\n constructor(\r\n rapier: RAPIER2D,\r\n world: RAPIER2DNamespace.World,\r\n collider: RAPIER2DNamespace.Collider\r\n ) {\r\n this.rapier = rapier;\r\n this.world = world;\r\n this.collider = collider;\r\n }\r\n\r\n setTranslation(position: float2) {\r\n this.collider.setTranslation(toVec2(position));\r\n }\r\n\r\n setRotation(rotation: float) {\r\n this.collider.setRotation(rotation);\r\n }\r\n\r\n setSensor(isSensor: boolean) {\r\n this.collider.setSensor(isSensor);\r\n }\r\n\r\n setCollisionGroups(groups: int) {\r\n this.collider.setCollisionGroups(groups);\r\n }\r\n\r\n setCollidesWith(groups: int) {\r\n this.collider.setActiveCollisionTypes(groups);\r\n }\r\n\r\n setFriction(friction: float) {\r\n this.collider.setFriction(friction);\r\n }\r\n\r\n setRestitution(restitution: float) {\r\n this.collider.setRestitution(restitution);\r\n }\r\n\r\n setDensity(density: float) {\r\n this.collider.setDensity(density);\r\n }\r\n\r\n setMass(mass: float) {\r\n this.collider.setMass(mass);\r\n }\r\n\r\n setRadius(radius: float) {\r\n this.collider.setRadius(radius);\r\n }\r\n\r\n setHalfExtents(halfExtents: float2) {\r\n this.collider.setHalfExtents(toVec2(halfExtents));\r\n }\r\n}\r\nfunction toVec2(v: float2): RAPIER2DNamespace.Vector2 {\r\n return { x: v[0], y: v[1] };\r\n}\r\n\r\nfunction toVec3(v: float3): RAPIER3DNamespace.Vector {\r\n return { x: v[0], y: v[1], z: v[2] };\r\n}\r\n\r\nexport class PhysicsRayCastResult2d {\r\n rapier: RAPIER2D;\r\n result: RAPIER2DNamespace.RayIntersection;\r\n\r\n constructor(rapier: RAPIER2D, result: RAPIER2DNamespace.RayIntersection) {\r\n this.rapier = rapier;\r\n this.result = result;\r\n }\r\n}\r\n\r\nexport class PhysicsRigidBody2d {\r\n rapier: RAPIER2D;\r\n world: RAPIER2DNamespace.World;\r\n body: RAPIER2DNamespace.RigidBody;\r\n\r\n constructor(rapier: RAPIER2D, world: RAPIER2DNamespace.World, body: RAPIER2DNamespace.RigidBody) {\r\n this.rapier = rapier;\r\n this.world = world;\r\n this.body = body;\r\n }\r\n\r\n addBallCollider(radius: float): PhysicsCollider2d {\r\n let colDesc = this.rapier.ColliderDesc.ball(radius);\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addBoxCollider(halfExtents: float2): PhysicsCollider2d {\r\n let colDesc = this.rapier.ColliderDesc.cuboid(halfExtents[0], halfExtents[1]);\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addCapsuleCollider(radius: float, halfHeight: float): PhysicsCollider2d {\r\n let colDesc = this.rapier.ColliderDesc.capsule(radius, halfHeight);\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addTriangleCollider(a: float2, b: float2, c: float2): PhysicsCollider2d {\r\n let colDesc = this.rapier.ColliderDesc.triangle(toVec2(a), toVec2(b), toVec2(c));\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addConvexCollider(points: float2[]): PhysicsCollider2d {\r\n let floatarr = new Float32Array(points.length * 2);\r\n for (let i = 0; i < points.length; i++) {\r\n floatarr[i * 2 + 0] = points[i][0];\r\n floatarr[i * 2 + 1] = points[i][1];\r\n }\r\n let colDesc = this.rapier.ColliderDesc.convexHull(floatarr);\r\n if (!colDesc) throw new Error('Failed to create convex hull collider');\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n addHeightfieldCollider(heights: float[], scale: float2): PhysicsCollider2d {\r\n let arr = new Float32Array(heights.length);\r\n for (let i = 0; i < heights.length; i++) {\r\n arr[i] = heights[i];\r\n }\r\n let colDesc = this.rapier.ColliderDesc.heightfield(arr, toVec2(scale));\r\n let col = this.world.createCollider(colDesc, this.body);\r\n\r\n return new PhysicsCollider2d(this.rapier, this.world, col);\r\n }\r\n\r\n setTranslation(position: float2) {\r\n this.body.setTranslation(toVec2(position), true);\r\n }\r\n\r\n setRotation(rotation: float) {\r\n this.body.setRotation(rotation, true);\r\n }\r\n\r\n setVelocity(velocity: float2) {\r\n this.body.setLinvel(toVec2(velocity), true);\r\n }\r\n\r\n setAngularVelocity(velocity: float) {\r\n this.body.setAngvel(velocity, true);\r\n }\r\n\r\n addForce(force: float2) {\r\n this.body.addForce(toVec2(force), true);\r\n }\r\n\r\n addForceAtPoint(force: float2, point: float2) {\r\n this.body.addForceAtPoint(toVec2(force), toVec2(point), true);\r\n }\r\n\r\n addTorque(torque: float) {\r\n this.body.addTorque(torque, true);\r\n }\r\n\r\n setAdditionalMass(mass: float) {\r\n this.body.setAdditionalMass(mass, true);\r\n }\r\n\r\n setEnabled(enabled: boolean) {\r\n this.body.setEnabled(enabled);\r\n }\r\n\r\n sleep() {\r\n this.body.sleep();\r\n }\r\n\r\n wakeUp() {\r\n this.body.wakeUp();\r\n }\r\n\r\n setGravityScale(scale: float) {\r\n this.body.setGravityScale(scale, true);\r\n }\r\n\r\n setLinearDamping(damping: float) {\r\n this.body.setLinearDamping(damping);\r\n }\r\n\r\n setAngularDamping(damping: float) {\r\n this.body.setAngularDamping(damping);\r\n }\r\n\r\n isSleeping(): boolean {\r\n return this.body.isSleeping();\r\n }\r\n\r\n mass(): float {\r\n return this.body.mass() as float;\r\n }\r\n\r\n translation(): float2 {\r\n let t = this.body.translation();\r\n return [t.x as float, t.y as float];\r\n }\r\n\r\n rotation(): float {\r\n return this.body.rotation() as float;\r\n }\r\n\r\n velocity(): float2 {\r\n let t = this.body.linvel();\r\n return [t.x as float, t.y as float];\r\n }\r\n\r\n angularVelocity(): float {\r\n return this.body.angvel() as float;\r\n }\r\n\r\n isMoving(): boolean {\r\n return this.body.isMoving();\r\n }\r\n\r\n collider(index: int): PhysicsCollider2d {\r\n let collider = this.body.collider(index);\r\n if (!collider) throw new Error('Failed to get collider');\r\n return new PhysicsCollider2d(this.rapier, this.world, collider);\r\n }\r\n\r\n applyImpulse(impulse: float2) {\r\n this.body.applyImpulse(toVec2(impulse), true);\r\n }\r\n\r\n applyTorqueImpulse(impulse: float) {\r\n this.body.applyTorqueImpulse(impulse, true);\r\n }\r\n}\r\n\r\nexport class PhysicsEngine2d {\r\n rapier: RAPIER2D;\r\n world: RAPIER2DNamespace.World;\r\n constructor(rapier: RAPIER2D) {\r\n this.rapier = rapier;\r\n this.world = new rapier.World(new rapier.Vector2(0.0, -9.81));\r\n }\r\n\r\n step() {\r\n this.world.step();\r\n }\r\n\r\n createRigidBody(\r\n position: float2,\r\n rotation: float,\r\n mode: 'dynamic' | 'fixed'\r\n ): PhysicsRigidBody2d {\r\n let rbDesc =\r\n mode == 'dynamic'\r\n ? this.rapier.RigidBodyDesc.dynamic()\r\n : mode == 'fixed'\r\n ? this.rapier.RigidBodyDesc.fixed()\r\n : this.rapier.RigidBodyDesc.dynamic();\r\n rbDesc.setTranslation(position[0], position[1]);\r\n rbDesc.setRotation(rotation);\r\n let rb = this.world.createRigidBody(rbDesc);\r\n\r\n return new PhysicsRigidBody2d(this.rapier, this.world, rb);\r\n }\r\n\r\n bodies(): PhysicsRigidBody2d[] {\r\n let bodies = this.world.bodies;\r\n let result: PhysicsRigidBody2d[] = [];\r\n for (let i = 0; i < bodies.len(); i++) {\r\n result.push(new PhysicsRigidBody2d(this.rapier, this.world, bodies.get(i)!));\r\n }\r\n return result;\r\n }\r\n\r\n castRay(start: float2, end: float2, maxi: int): PhysicsRigidBody2d | null {\r\n let result = this.world.castRay(new this.rapier.Ray(toVec2(start), toVec2(end)), maxi, true);\r\n if (!result) return null;\r\n return new PhysicsRigidBody2d(this.rapier, this.world, result.collider.parent()!);\r\n }\r\n\r\n setGravity(gravity: float2) {\r\n this.world.gravity = toVec2(gravity);\r\n }\r\n}\r\n\r\nexport class PhysicsEngine3d {\r\n constructor() {}\r\n}\r\n\r\nexport namespace physics {\r\n export function engine2d(): PhysicsEngine2d {\r\n return new PhysicsEngine2d((window as any).RAPIER_2D);\r\n }\r\n}\r\n"; const context = "declare global {\r\n const localEngineContext: any;\r\n}\r\nexport const getShadeupLocalContext = (): any => {\r\n if (typeof localEngineContext !== 'undefined') {\r\n return localEngineContext;\r\n } else {\r\n return window;\r\n }\r\n};\r\n"; const drawIndexed = "import { getShadeupLocalContext } from '/_std/context';\r\nimport { buffer } from '/_std/buffer';\r\nimport { Mesh } from '/_std/mesh';\r\nimport { texture2d } from '/_std/texture';\r\nimport { float4, float3, float, float2, bool, int, uint, atomic, int3 } from '/std_math';\r\n\r\nexport function drawIndexed(\r\n indexBuffer: buffer,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_indexed(indexBuffer, vertexShader, pixelShader);\r\n}\r\n\r\nexport function drawInstanced(\r\n mesh: Mesh,\r\n instanceCount: int,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_instanced(\r\n mesh,\r\n instanceCount,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n\r\nexport function drawInstancedIndexed(\r\n indexBuffer: buffer,\r\n instanceCount: int,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_instanced_indexed(\r\n indexBuffer,\r\n instanceCount,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n\r\nexport function drawIndexedIndirect(\r\n indirectBuffer: buffer | buffer>,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_indexed_indirect(\r\n indirectBuffer,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n\r\nexport function drawIndirect(\r\n mesh: Mesh,\r\n indirectBuffer: buffer | buffer>,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_indirect(\r\n mesh,\r\n indirectBuffer,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n\r\nexport function shader_start_shd_(\r\n s: shader,\r\n groupSize?: any\r\n): shader {\r\n return s;\r\n}\r\n\r\nexport type shader = (\r\n __in: Omit\r\n) => T_OUT;\r\ndeclare global {\r\n // function __shadeup_make_shader_inst(\r\n // key: string,\r\n // params: any,\r\n // closure: any\r\n // ): shader;\r\n // function __shadeup_dispatch_draw(fullScreenPixelShader: shader): void;\r\n // function __shadeup_dispatch_draw_geometry(\r\n // geometry: Mesh,\r\n // vertexShader: shader,\r\n // pixelShader: shader\r\n // ): void;\r\n\r\n interface Array {\r\n [index: int]: T;\r\n }\r\n\r\n let window: {\r\n [index: string]: any;\r\n };\r\n}\r\n\r\n/**@shadeup=struct*/\r\nexport class ShaderInput {\r\n /** Interpolated world position (available in fragment, and vertex) */\r\n position: float3 = float3(0, 0, 0);\r\n\r\n /** Interpolated normal (fragment), Source mesh normal (vertex) */\r\n normal: float3 = float3(0, 0, 0);\r\n\r\n /** Interpolated tangent (fragment), Source mesh tangent (vertex) */\r\n tangent: float3 = float3(0, 0, 0);\r\n\r\n /** Interpolated bitangent (fragment), Source mesh bitangent (vertex) */\r\n bitangent: float3 = float3(0, 0, 0);\r\n\r\n /** Vertex shader output position */\r\n clipPosition: float4 = float4(0, 0, 0, 0);\r\n\r\n realPosition: float4 = float4(0, 0, 0, 0);\r\n\r\n /** UV channel 0 input (available in fragment, and vertex) */\r\n uv: float2 = float2(0, 0);\r\n\r\n /** Screen position in pixels (available in fragment, and vertex) */\r\n screen: float2 = float2(0, 0);\r\n\r\n /** Interpolated vertex color (available in fragment, and vertex) */\r\n color: float4 = float4(0, 0, 0, 0);\r\n\r\n /** Group ID (available in compute) */\r\n groupId: int3 = int3(0, 0, 0);\r\n\r\n /** Group size (available in compute) */\r\n groupSize: int3 = int3(0, 0, 0);\r\n\r\n /** Global id (groupId * groupSize + localId) (available in compute) */\r\n globalId: int3 = int3(0, 0, 0);\r\n\r\n /** Local id (available in compute) */\r\n localId: int3 = int3(0, 0, 0);\r\n\r\n /** Instance index (available in fragment, and vertex) */\r\n instanceIndex: int = 0;\r\n\r\n /** Vertex index (available in vertex) */\r\n vertexIndex: int = 0;\r\n\r\n /** @shadeup=noemit_gpu */\r\n attr(index: int, interpolation?: 'flat' | 'linear' | 'perspective'): T {\r\n return null as any;\r\n }\r\n}\r\n\r\n/**@shadeup=struct*/\r\nexport class ShaderOutput {\r\n /** Vertex output position */\r\n position: float4 = float4(0, 0, 0, 0);\r\n\r\n /** Vertex output normal */\r\n normal: float3 = float3(0, 0, 0);\r\n\r\n /** Vertex output tangent */\r\n tangent: float3 = float3(0, 0, 0);\r\n\r\n /** Vertex output bitangent */\r\n bitangent: float3 = float3(0, 0, 0);\r\n\r\n /** UV channel 0 output */\r\n uv: float2 = float2(0, 0);\r\n\r\n /** Pixel color output */\r\n color: float4 = float4(0, 0, 0, 0);\r\n\r\n /** @shadeup=noemit_gpu */\r\n attr(index: int, value: T, interpolation?: 'flat' | 'linear' | 'perspective') {}\r\n}\r\n\r\n/** @shadeup=shader */\r\nexport function makeShader(\r\n key: string,\r\n fn: (__in: I, __out: O) => void\r\n): shader {\r\n return fn as shader;\r\n}\r\n\r\ntype AttachmentBindings1 = {\r\n attachments: [texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings2 = {\r\n attachments: [texture2d, texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings3 = {\r\n attachments: [texture2d, texture2d, texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings4 = {\r\n attachments: [texture2d, texture2d, texture2d, texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings5 = {\r\n attachments: [texture2d, texture2d, texture2d, texture2d, texture2d];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n attachment4: A4;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings6 = {\r\n attachments: [\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d\r\n ];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n attachment4: A4;\r\n attachment5: A5;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings7 = {\r\n attachments: [\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d\r\n ];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n attachment4: A4;\r\n attachment5: A5;\r\n attachment6: A6;\r\n }\r\n >;\r\n};\r\ntype AttachmentBindings8 = {\r\n attachments: [\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d,\r\n texture2d\r\n ];\r\n vertex: shader;\r\n fragment: shader<\r\n ShaderInput,\r\n {\r\n attachment0: A0;\r\n attachment1: A1;\r\n attachment2: A2;\r\n attachment3: A3;\r\n attachment4: A4;\r\n attachment5: A5;\r\n attachment6: A6;\r\n attachment7: A7;\r\n }\r\n >;\r\n};\r\n\r\ntype DrawDescriptorBase = (\r\n | {\r\n mesh: Mesh;\r\n }\r\n | {\r\n indexBuffer: buffer;\r\n }\r\n | {}\r\n) & {\r\n indirect?: buffer | buffer>;\r\n indirectOffset?: int | uint;\r\n depth?: texture2d;\r\n depthOnly?: boolean;\r\n depthTest?: boolean;\r\n depthCompare?:\r\n | 'greater'\r\n | 'less'\r\n | 'equal'\r\n | 'greater_equal'\r\n | 'less_equal'\r\n | 'not_equal'\r\n | 'always'\r\n | 'never';\r\n backfaceCulling?: boolean;\r\n instances?: int;\r\n};\r\n\r\n/**\r\n * Normal:\r\n * ```shadeup\r\n * drawAdvanced({\r\n * mesh: mesh::box(0.xyz, 100.xyz),\r\n * vertex: shader {\r\n * // ...\r\n * },\r\n * fragment: shader {\r\n * // ...\r\n * },\r\n * });\r\n * ```\r\n *\r\n * Instancing:\r\n * ```shadeup\r\n * drawAdvanced({\r\n * mesh: mesh::box(0.xyz, 100.xyz),\r\n * vertex: shader {\r\n * in.instanceIndex;\r\n * },\r\n * fragment: shader {\r\n * // ...\r\n * },\r\n * instances: 100,\r\n * });\r\n * ```\r\n *\r\n * Indirect:\r\n * ```shadeup\r\n * let mesh = mesh::box(0.xyz, 100.xyz);\r\n *\r\n * let indirectBuffer = buffer(5);\r\n * indirectBuffer[0] = uint(m.getTriangles().len()); // indexCount\r\n * indirectBuffer[1] = 1; // instanceCount\r\n * indirectBuffer[2] = 0; // firstIndex\r\n * indirectBuffer[3] = 0; // vertexOffset\r\n * indirectBuffer[4] = 0; // firstInstance\r\n *\r\n * drawAdvanced({\r\n * mesh: mesh::box(0.xyz, 100.xyz),\r\n * vertex: shader {\r\n * // ...\r\n * },\r\n * fragment: shader {\r\n * // ...\r\n * },\r\n * indirect: indirectBuffer,\r\n * });\r\n * ```\r\n *\r\n * Attachments:\r\n * ```shadeup\r\n * let mesh = mesh::box(0.xyz, 100.xyz);\r\n * let color = texture2d(100.xy);\r\n * let normal = texture2d(100.xy);\r\n * let depth = texture2d(100.xy, \"depth\");\r\n *\r\n * drawAdvanced({\r\n * mesh: mesh,\r\n * vertex: shader {\r\n * // ...\r\n * },\r\n * fragment: shader {\r\n * out.attachment0 = float4(1, 0, 0, 1);\r\n * out.attachment1 = float3(0, 0, 1);\r\n * },\r\n * depth: depth, // Override depth buffer\r\n * attachments: [color, normal],\r\n * });\r\n */\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings8\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings7\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings6\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings5\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings4\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings3\r\n): void;\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & AttachmentBindings2\r\n): void;\r\nexport function drawAdvanced(descriptor: DrawDescriptorBase & AttachmentBindings1): void;\r\n\r\nexport function drawAdvanced(\r\n descriptor: DrawDescriptorBase & {\r\n vertex: shader;\r\n fragment: shader;\r\n }\r\n): void;\r\nexport function drawAdvanced(descriptor: any): void {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_advanced(descriptor);\r\n}\r\n\r\nexport function draw(\r\n geometry: Mesh,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n): void;\r\nexport function draw(fullScreenPixelShader: shader): void;\r\nexport function draw(\r\n first: Mesh | DrawDescriptorBase | shader,\r\n second?: shader | number,\r\n third?: shader\r\n) {\r\n if ('vertices' in first && second && third) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_geometry(first, second, third);\r\n } else if (first && !second && !third) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw(first as shader);\r\n }\r\n}\r\n\r\nexport function drawFullscreen(fullScreenPixelShader: shader): void;\r\nexport function drawFullscreen(\r\n first: Mesh | any | shader,\r\n second?: shader,\r\n third?: shader\r\n) {\r\n if ('vertices' in first && second && third) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_geometry(first, second, third);\r\n } else if (first && !second && !third) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw(first as shader);\r\n }\r\n}\r\n\r\nexport function drawAlt2(fullScreenPixelShader: shader): void {}\r\n\r\nexport function drawCount(\r\n triCount: number,\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader);\r\n}\r\n\r\nexport function drawAttributes(\r\n indexBuffer: buffer,\r\n buffers:\r\n | Map>\r\n | {\r\n [key in keyof T]: buffer;\r\n },\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_attributes(\r\n indexBuffer,\r\n buffer,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\nexport function computeIndirect(\r\n indirectBuffer: buffer | buffer>,\r\n indirectOffset: int,\r\n computeShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_compute_indirect(\r\n indirectBuffer,\r\n indirectOffset,\r\n computeShader\r\n );\r\n}\r\n"; const drawCount = "import { getShadeupLocalContext } from '/_std/context';\r\nimport { buffer } from '/_std/buffer';\r\nimport { float4, float3, float, float2, bool, int, uint } from '/std_math';\r\n\r\nexport function drawCount(triCount: number, vertexShader: shader, pixelShader: shader) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader);\r\n}\r\n"; const drawAttributes = "import { getShadeupLocalContext } from '/_std/context';\r\nimport { buffer } from '/_std/buffer';\r\nimport { float4, float3, float, float2, bool, int, uint } from '/std_math';\r\n\r\nexport function drawAttributes(\r\n indexBuffer: buffer,\r\n buffers:\r\n | Map>\r\n | {\r\n [key in keyof T]: buffer;\r\n },\r\n vertexShader: shader,\r\n pixelShader: shader\r\n) {\r\n getShadeupLocalContext().__shadeup_dispatch_draw_attributes(\r\n indexBuffer,\r\n buffer,\r\n vertexShader,\r\n pixelShader\r\n );\r\n}\r\n"; const paint = "type GraphicsAdapter = {\r\n drawImage(image: HTMLCanvasElement): void;\r\n addEventListener(name: string, fn: (...args: any) => void): void;\r\n activatePaintContext(): void;\r\n};\r\nimport type { float4, float2 } from './types';\r\n\r\nexport class PaintingContext {\r\n markDirtyCallback: () => void = () => {};\r\n constructor(canvas: HTMLCanvasElement, gl: GraphicsAdapter | null) {\r\n if (!gl) return;\r\n this.__gl = gl;\r\n this.__canvas = canvas;\r\n this.__offscreen_canvas = document.createElement('canvas');\r\n this.__offscreen_canvas.width = canvas.width;\r\n this.__offscreen_canvas.height = canvas.height;\r\n // document.body.appendChild(this.__offscreen_canvas);\r\n this.__ctx = this.__offscreen_canvas.getContext('2d', {\r\n willReadFrequently: true\r\n })!;\r\n this.__offscreen_canvas.style.position = 'absolute';\r\n this.__offscreen_canvas.style.zIndex = '10';\r\n // document.body.appendChild(this.__offscreen_canvas);\r\n this.__setColor([0, 0, 0, 1] as float4);\r\n\r\n gl.addEventListener('context', (toContext: string) => {\r\n if (toContext == 'draw') {\r\n this.flush();\r\n }\r\n });\r\n\r\n gl.addEventListener('flush', () => {\r\n this.flush();\r\n });\r\n }\r\n\r\n flush() {\r\n if (!this.__gl) return;\r\n if (!this.__canvas) return;\r\n if (!this.__offscreen_canvas) return;\r\n\r\n if (!this.stagedChanges) return;\r\n\r\n if (this.fastPoints) this.flushPoints();\r\n\r\n this.__gl.drawImage(this.__offscreen_canvas);\r\n this.stagedChanges = false;\r\n\r\n if (\r\n this.__offscreen_canvas.width != this.__canvas.width ||\r\n this.__offscreen_canvas.height != this.__canvas.height\r\n ) {\r\n this.__offscreen_canvas.width = this.__canvas.width;\r\n this.__offscreen_canvas.height = this.__canvas.height;\r\n }\r\n\r\n this.pointsCounter = 0;\r\n }\r\n\r\n private __ctx: CanvasRenderingContext2D | null = null;\r\n private __gl: GraphicsAdapter | null = null;\r\n private __offscreen_canvas: HTMLCanvasElement | null = null;\r\n\r\n private __program: WebGLProgram | null = null;\r\n\r\n private stagedChanges: boolean = false;\r\n private dirty: boolean = false;\r\n\r\n private fastPoints: boolean = false;\r\n private fastPointsBuffer: ImageData | null = null;\r\n\r\n private __beforeDraw() {\r\n if (!this.__offscreen_canvas) return;\r\n if (!this.__ctx) return;\r\n if (!this.__canvas) return;\r\n this.markDirtyCallback();\r\n this.__gl?.activatePaintContext();\r\n\r\n if (!this.stagedChanges) {\r\n this.__ctx.clearRect(0, 0, this.__canvas.width, this.__canvas.height);\r\n\r\n this.__ctx.drawImage(this.__canvas, 0, 0);\r\n\r\n let color = this.__currentColor;\r\n this.__ctx.fillStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n this.__ctx.strokeStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n }\r\n }\r\n\r\n private __afterDraw() {\r\n let gl = this.__gl;\r\n this.dirty = true;\r\n this.stagedChanges = true;\r\n }\r\n\r\n private __currentColor: number[] | null = null;\r\n private __setColor(color?: float4) {\r\n if (!this.__ctx || !color) return;\r\n\r\n if (\r\n this.__currentColor &&\r\n this.__currentColor[0] == color[0] &&\r\n this.__currentColor[1] == color[1] &&\r\n this.__currentColor[2] == color[2] &&\r\n this.__currentColor[3] == color[3]\r\n )\r\n return;\r\n\r\n this.__ctx.strokeStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n this.__ctx.fillStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n\r\n this.__currentColor = [color[0], color[1], color[2], color[3]];\r\n }\r\n\r\n fillRect(pos: float2, size: float2, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.fillRect(pos[0], pos[1], size[0], size[1]);\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n fillCircle(pos: float2, radius: number, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2);\r\n this.__ctx.fill();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n fillArc(pos: float2, radius: number, startAngle: number, endAngle: number, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle);\r\n this.__ctx.fill();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n line(pos1: float2, pos2: float2, color?: float4, width: number = 1) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.moveTo(pos1[0], pos1[1]);\r\n\r\n this.__ctx.lineTo(pos2[0], pos2[1]);\r\n this.__ctx.lineWidth = width;\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n circle(pos: float2, radius: number, color?: float4, width: number = 1) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2);\r\n this.__ctx.lineWidth = width;\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n arc(\r\n pos: float2,\r\n radius: number,\r\n startAngle: number,\r\n endAngle: number,\r\n color?: float4,\r\n width: number = 1\r\n ) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle);\r\n this.__ctx.lineWidth = width;\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n text(pos: float2, text: string, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.fillText(text, pos[0], pos[1]);\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n startPath(pos: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.flushPoints();\r\n this.__beforeDraw();\r\n\r\n this.__ctx.beginPath();\r\n this.__ctx.moveTo(pos[0], pos[1]);\r\n }\r\n\r\n lineTo(pos: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineTo(pos[0], pos[1]);\r\n }\r\n\r\n strokePath(color?: float4, width: number = 1) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineWidth = width;\r\n this.__setColor(color);\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n fillPath(color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.__setColor(color);\r\n this.__ctx.fill();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n setStrokeWidth(width: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineWidth = width;\r\n }\r\n\r\n setFont(font: string) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.font = font;\r\n }\r\n\r\n setFontSize(size: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.font = `${size}px ${this.__ctx.font.split(' ').slice(1).join(' ')}`;\r\n }\r\n\r\n setTextAlign(align: CanvasTextAlign) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.textAlign = align;\r\n }\r\n\r\n setTextBaseline(baseline: CanvasTextBaseline) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.textBaseline = baseline;\r\n }\r\n\r\n setLineCap(cap: 'butt' | 'round' | 'square') {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineCap = cap;\r\n }\r\n\r\n setLineJoin(join: CanvasLineJoin) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineJoin = join;\r\n }\r\n\r\n setMiterLimit(limit: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.miterLimit = limit;\r\n }\r\n\r\n setShadowColor(color: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.shadowColor = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${\r\n color[3]\r\n })`;\r\n }\r\n\r\n setShadowBlur(blur: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.shadowBlur = blur;\r\n }\r\n\r\n setShadowOffset(offset: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.shadowOffsetX = offset[0];\r\n this.__ctx.shadowOffsetY = offset[1];\r\n }\r\n\r\n setGlobalAlpha(alpha: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.globalAlpha = alpha;\r\n }\r\n\r\n setGlobalCompositeOperation(op: string) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.globalCompositeOperation = op as any;\r\n }\r\n\r\n setImageSmoothingEnabled(enabled: boolean) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.imageSmoothingEnabled = enabled;\r\n }\r\n\r\n setImageSmoothingQuality(quality: ImageSmoothingQuality) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.imageSmoothingQuality = quality;\r\n }\r\n\r\n setLineDash(dash: number[]) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.setLineDash(dash);\r\n }\r\n\r\n setLineDashOffset(offset: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.lineDashOffset = offset;\r\n }\r\n\r\n setTransform(a: number, b: number, c: number, d: number, e: number, f: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.setTransform(a, b, c, d, e, f);\r\n }\r\n\r\n resetTransform() {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.resetTransform();\r\n }\r\n\r\n scale(v: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.scale(v[0], v[1]);\r\n }\r\n\r\n rotate(angle: number) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.rotate(angle);\r\n }\r\n\r\n translate(v: float2) {\r\n if (!this.__ctx) return;\r\n\r\n this.__ctx.translate(v[0], v[1]);\r\n }\r\n\r\n private flushPoints() {\r\n if (!this.__ctx) return;\r\n if (!this.fastPoints) return;\r\n if (!this.fastPointsBuffer) return;\r\n\r\n this.__ctx.putImageData(this.fastPointsBuffer, 0, 0);\r\n\r\n this.fastPoints = false;\r\n this.fastPointsBuffer = null;\r\n\r\n this.pointsCounter = 0;\r\n }\r\n\r\n private pointsCounter: number = 0;\r\n private cacheSize: [number, number] = [0, 0];\r\n point(pos: float2, color?: float4) {\r\n if (!this.__ctx) return;\r\n\r\n this.pointsCounter++;\r\n\r\n this.__beforeDraw();\r\n if (this.pointsCounter > 10) {\r\n if (!this.fastPoints) {\r\n this.fastPoints = true;\r\n this.cacheSize = [this.__offscreen_canvas!.width, this.__offscreen_canvas!.height];\r\n this.fastPointsBuffer = this.__ctx.getImageData(0, 0, this.cacheSize[0], this.cacheSize[1]);\r\n }\r\n\r\n if (!this.fastPointsBuffer) return;\r\n\r\n let x = Math.floor(pos[0]);\r\n let y = Math.floor(pos[1]);\r\n\r\n let index = (y * this.cacheSize[0] + x) * 4;\r\n\r\n if (!color) {\r\n color = this.__currentColor;\r\n }\r\n let oldColorx = this.fastPointsBuffer.data[index] / 255;\r\n let oldColory = this.fastPointsBuffer.data[index + 1] / 255;\r\n let oldColorz = this.fastPointsBuffer.data[index + 2] / 255;\r\n let oldColora = this.fastPointsBuffer.data[index + 3] / 255;\r\n\r\n this.fastPointsBuffer.data[index] =\r\n color[0] * 255 * color[3] + oldColorx * 255 * (1 - color[3]);\r\n this.fastPointsBuffer.data[index + 1] =\r\n color[1] * 255 * color[3] + oldColory * 255 * (1 - color[3]);\r\n this.fastPointsBuffer.data[index + 2] =\r\n color[2] * 255 * color[3] + oldColorz * 255 * (1 - color[3]);\r\n this.fastPointsBuffer.data[index + 3] = color[3] * 255 + oldColora * 255 * (1 - color[3]);\r\n } else {\r\n this.__setColor(color);\r\n this.__ctx.fillRect(pos[0], pos[1], 1, 1);\r\n }\r\n this.__afterDraw();\r\n }\r\n\r\n vector(\r\n pos: float2,\r\n dir: float2,\r\n color: float4 = [0.9803921568627451, 0.8, 0.08235294117647059, 1] as float4,\r\n width: number = 4\r\n ) {\r\n if (!this.__ctx || (dir[0] == 0 && dir[1] == 0)) return;\r\n\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.setStrokeWidth(width);\r\n this.__ctx.moveTo(pos[0], pos[1]);\r\n this.__ctx.lineCap = 'round';\r\n\r\n this.__ctx.lineTo(pos[0] + dir[0], pos[1] + dir[1]);\r\n this.__ctx.stroke();\r\n this.__ctx.beginPath();\r\n this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]);\r\n // Arrows\r\n let arrowSize = 20;\r\n let arrowAngle = Math.PI / 5;\r\n let dirAngle = Math.atan2(dir[1], dir[0]) + Math.PI;\r\n let arrow1 = [\r\n Math.cos(dirAngle + arrowAngle) * arrowSize,\r\n Math.sin(dirAngle + arrowAngle) * arrowSize\r\n ];\r\n let arrow2 = [\r\n Math.cos(dirAngle - arrowAngle) * arrowSize,\r\n Math.sin(dirAngle - arrowAngle) * arrowSize\r\n ];\r\n this.__ctx.lineTo(pos[0] + dir[0] + arrow1[0], pos[1] + dir[1] + arrow1[1]);\r\n this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]);\r\n this.__ctx.lineTo(pos[0] + dir[0] + arrow2[0], pos[1] + dir[1] + arrow2[1]);\r\n\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n\r\n grid(\r\n center: float2,\r\n count: float2,\r\n gap: float2,\r\n color: float4 = [0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1] as float4,\r\n width: number = 2\r\n ) {\r\n if (!this.__ctx) return;\r\n\r\n this.__beforeDraw();\r\n\r\n this.__setColor(color);\r\n this.__ctx.beginPath();\r\n this.setStrokeWidth(width);\r\n\r\n let start = [\r\n center[0] - (count[0] / 2) * gap[0],\r\n center[1] - (count[1] / 2) * gap[1]\r\n ] as float2;\r\n\r\n for (let i = 0; i <= count[0]; i++) {\r\n this.__ctx.moveTo(start[0] + i * gap[0], start[1]);\r\n this.__ctx.lineTo(start[0] + i * gap[0], start[1] + count[1] * gap[1]);\r\n }\r\n\r\n for (let i = 0; i <= count[1]; i++) {\r\n this.__ctx.moveTo(start[0], start[1] + i * gap[1]);\r\n this.__ctx.lineTo(start[0] + count[0] * gap[0], start[1] + i * gap[1]);\r\n }\r\n\r\n this.__ctx.stroke();\r\n\r\n this.__afterDraw();\r\n this.pointsCounter = 0;\r\n }\r\n}\r\n\r\ndeclare global {\r\n const paint: PaintingContext;\r\n}\r\n"; const mesh = "\r\npub struct Mesh {\r\n vertices: float3[];\r\n triangles: int[];\r\n normals: float3[];\r\n tangents: float3[];\r\n bitangents: float3[];\r\n uvs: float2[];\r\n colors: float4[];\r\n pub symbol: any;\r\n}\r\n\r\nimpl Mesh {\r\n pub fn rect(self, size: float2) {\r\n let index = self.vertices.len();\r\n\r\n self.vertices.push((-size.x / 2, -size.y / 2, 0));\r\n self.vertices.push((size.x / 2, -size.y / 2, 0));\r\n self.vertices.push((size.x / 2, size.y / 2, 0));\r\n self.vertices.push((-size.x / 2, size.y / 2, 0));\r\n\r\n self.triangles.push(index + 2);\r\n self.triangles.push(index + 1);\r\n self.triangles.push(index + 0);\r\n\r\n self.triangles.push(index + 0);\r\n self.triangles.push(index + 3);\r\n self.triangles.push(index + 2);\r\n\r\n self.normals.push((0, 0, 1));\r\n self.normals.push((0, 0, 1));\r\n self.normals.push((0, 0, 1));\r\n self.normals.push((0, 0, 1));\r\n\r\n self.tangents.push((1, 0, 0));\r\n self.tangents.push((1, 0, 0));\r\n self.tangents.push((1, 0, 0));\r\n self.tangents.push((1, 0, 0));\r\n\r\n self.bitangents.push((0, 1, 0));\r\n self.bitangents.push((0, 1, 0));\r\n self.bitangents.push((0, 1, 0));\r\n self.bitangents.push((0, 1, 0));\r\n\r\n self.uvs.push((0, 0));\r\n self.uvs.push((1, 0));\r\n self.uvs.push((0, 1));\r\n self.uvs.push((1, 1));\r\n }\r\n\r\n pub fn quad(self, position: float3, direction: float3, right: float3, size: float2) {\r\n let up = normalize(cross(right, direction));\r\n\r\n let halfSize = size / 2.0;\r\n\r\n let index = self.vertices.len();\r\n \r\n self.vertices.push(position + right * -halfSize.x + up * halfSize.y);\r\n self.vertices.push(position + right * halfSize.x + up * halfSize.y);\r\n self.vertices.push(position + right * halfSize.x + up * -halfSize.y);\r\n self.vertices.push(position + right * -halfSize.x + up * -halfSize.y);\r\n\r\n self.triangles.push(index + 0);\r\n self.triangles.push(index + 1);\r\n self.triangles.push(index + 2);\r\n\r\n self.triangles.push(index + 2);\r\n self.triangles.push(index + 3);\r\n self.triangles.push(index + 0);\r\n\r\n self.normals.push(direction);\r\n self.normals.push(direction);\r\n self.normals.push(direction);\r\n self.normals.push(direction);\r\n\r\n self.tangents.push(right);\r\n self.tangents.push(right);\r\n self.tangents.push(right);\r\n self.tangents.push(right);\r\n\r\n self.bitangents.push(up);\r\n self.bitangents.push(up);\r\n self.bitangents.push(up);\r\n self.bitangents.push(up);\r\n\r\n self.uvs.push((1, 0));\r\n self.uvs.push((0, 0));\r\n self.uvs.push((0, 1));\r\n self.uvs.push((1, 1));\r\n }\r\n\r\n pub fn box(self, size: float3) {\r\n let halfSize = size / 2.0;\r\n\r\n const UP = (0, 1.0, 0);\r\n const DOWN = (0, -1.0, 0);\r\n const LEFT = (-1.0, 0, 0);\r\n const RIGHT = (1.0, 0, 0);\r\n const FORWARD = (0, 0, 1.0);\r\n const BACK = (0, 0, -1.0);\r\n\r\n // Up\r\n self.quad(UP * halfSize.y, UP, LEFT, (size.x, size.z));\r\n\r\n // Down\r\n self.quad(DOWN * halfSize.y, DOWN, RIGHT, (size.x, size.z));\r\n\r\n // Left\r\n self.quad(LEFT * halfSize.x, LEFT, BACK, (size.z, size.y));\r\n\r\n // Right\r\n self.quad(RIGHT * halfSize.x, RIGHT, FORWARD, (size.z, size.y));\r\n\r\n // Forward\r\n self.quad(FORWARD * halfSize.z, FORWARD, LEFT, (size.x, size.y));\r\n\r\n // Back\r\n self.quad(BACK * halfSize.z, BACK, RIGHT, (size.x, size.y));\r\n }\r\n\r\n pub fn rectAt(self, minPos: float2, maxPos: float2) {\r\n self.rect(maxPos - minPos);\r\n self.translate((minPos, 0));\r\n }\r\n\r\n pub fn circle(self, pos: float2, radius: float, vertices: int = 32) {\r\n\r\n }\r\n\r\n pub fn uvSphere(self, pos: float3, radius: float, vertices: int = 32, rings: int = 16) {\r\n let index = self.vertices.len();\r\n\r\n let verticesPerRing = vertices + 1;\r\n\r\n for (let i = 0; i <= rings; i++) {\r\n let y = i / float(rings);\r\n let angleY = y * PI;\r\n\r\n let posY = cos(angleY);\r\n let radiusY = sin(angleY);\r\n\r\n for (let j = 0; j <= vertices; j++) {\r\n let x = j / float(vertices);\r\n let angleX = x * PI * 2;\r\n\r\n let posX = cos(angleX);\r\n let posZ = sin(angleX);\r\n\r\n self.vertices.push((posX * radiusY * radius, posY * radius, posZ * radiusY * radius));\r\n self.normals.push(normalize((posX * radiusY, posY, posZ * radiusY)));\r\n \r\n let tangent = normalize((posZ, 0, -posX));\r\n let bitangent = normalize(cross(self.normals[self.normals.len() - 1], tangent));\r\n\r\n self.tangents.push(tangent);\r\n self.bitangents.push(bitangent);\r\n self.uvs.push((x, y));\r\n }\r\n }\r\n\r\n for (let i = 0; i < rings; i++) {\r\n for (let j = 0; j < vertices; j++) {\r\n let i0 = i * verticesPerRing + j;\r\n let i1 = i0 + 1;\r\n let i2 = i0 + verticesPerRing;\r\n let i3 = i2 + 1;\r\n\r\n self.triangles.push(index + i0);\r\n self.triangles.push(index + i1);\r\n self.triangles.push(index + i2);\r\n\r\n self.triangles.push(index + i2);\r\n self.triangles.push(index + i1);\r\n self.triangles.push(index + i3);\r\n }\r\n }\r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn icoSphere(self, pos: float3, radius: float, subdivisions: int = 1) {\r\n let index = self.vertices.len();\r\n\r\n let t = (1.0 + sqrt(5.0)) / 2.0;\r\n\r\n let vertices: float3[] = [\r\n (-1, t, 0),\r\n (1, t, 0),\r\n (-1, -t, 0),\r\n (1, -t, 0),\r\n (0, -1, t),\r\n (0, 1, t),\r\n (0, -1, -t),\r\n (0, 1, -t),\r\n (t, 0, -1),\r\n (t, 0, 1),\r\n (-t, 0, -1),\r\n (-t, 0, 1),\r\n ];\r\n\r\n let triangles: int3[] = [\r\n (0, 11, 5),\r\n (0, 5, 1),\r\n (0, 1, 7),\r\n (0, 7, 10),\r\n (0, 10, 11),\r\n (1, 5, 9),\r\n (5, 11, 4),\r\n (11, 10, 2),\r\n (10, 7, 6),\r\n (7, 1, 8),\r\n (3, 9, 4),\r\n (3, 4, 2),\r\n (3, 2, 6),\r\n (3, 6, 8),\r\n (3, 8, 9),\r\n (4, 9, 5),\r\n (2, 4, 11),\r\n (6, 2, 10),\r\n (8, 6, 7),\r\n (9, 8, 1),\r\n ];\r\n\r\n for (let i = 0; i < vertices.len(); i++) {\r\n self.vertices.push(normalize(vertices[i]) * radius);\r\n }\r\n\r\n for (let i = 0; i < triangles.len(); i++) {\r\n self.triangles.push(index + triangles[i].x);\r\n self.triangles.push(index + triangles[i].y);\r\n self.triangles.push(index + triangles[i].z);\r\n }\r\n\r\n for (let i = 0; i < subdivisions; i++) {\r\n let newTriangles: int[] = [];\r\n\r\n for (let j = 0; j < self.triangles.len(); j += 3) {\r\n let i0 = self.triangles[j + 0];\r\n let i1 = self.triangles[j + 1];\r\n let i2 = self.triangles[j + 2];\r\n\r\n let v0 = self.vertices[i0];\r\n let v1 = self.vertices[i1];\r\n let v2 = self.vertices[i2];\r\n\r\n let v3 = normalize((v0 + v1) / 2.0);\r\n let v4 = normalize((v1 + v2) / 2.0);\r\n let v5 = normalize((v2 + v0) / 2.0);\r\n\r\n let i3 = self.vertices.len();\r\n let i4 = i3 + 1;\r\n let i5 = i3 + 2;\r\n\r\n self.vertices.push(v3 * radius);\r\n self.vertices.push(v4 * radius);\r\n self.vertices.push(v5 * radius);\r\n\r\n newTriangles.push(i0, i3, i5);\r\n newTriangles.push(i3, i1, i4);\r\n newTriangles.push(i3, i4, i5);\r\n newTriangles.push(i5, i4, i2);\r\n }\r\n\r\n self.triangles = newTriangles;\r\n }\r\n\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n let normal = normalize(self.vertices[i]);\r\n let tangent = normalize((normal.z, 0, -normal.x));\r\n let bitangent = normalize(cross(normal, tangent));\r\n self.normals.push(normal);\r\n self.tangents.push(tangent);\r\n self.bitangents.push(bitangent);\r\n }\r\n\r\n for (let i = 0; i < self.triangles.len(); i += 3) {\r\n let i0 = self.triangles[i + 0];\r\n let i1 = self.triangles[i + 1];\r\n let i2 = self.triangles[i + 2];\r\n\r\n let v0 = self.vertices[i0];\r\n let v1 = self.vertices[i1];\r\n let v2 = self.vertices[i2];\r\n\r\n let uv0 = float2(atan2(v0.z, v0.x) / PI / 2.0 + 0.5, asin(v0.y) / PI + 0.5);\r\n let uv1 = float2(atan2(v1.z, v1.x) / PI / 2.0 + 0.5, asin(v1.y) / PI + 0.5);\r\n let uv2 = float2(atan2(v2.z, v2.x) / PI / 2.0 + 0.5, asin(v2.y) / PI + 0.5);\r\n\r\n self.uvs.push(uv0);\r\n self.uvs.push(uv1);\r\n self.uvs.push(uv2);\r\n }\r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn cylinder(self, pos: float3, radius: float, height: float, vertices: int = 32) {\r\n \r\n\r\n self.translate(pos);\r\n\r\n }\r\n\r\n pub fn capsule(self, pos: float3, radius: float, height: float, vertices: int = 32) {\r\n \r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn cone(self, pos: float3, radius: float, height: float, vertices: int = 32) {\r\n let index = self.vertices.len();\r\n\r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn plane(self, pos: float3, size: float2, subdivisions: int2 = (2, 2)) {\r\n let index = self.vertices.len();\r\n\r\n let halfSize = size / 2.0;\r\n\r\n for (let i = 0; i <= subdivisions.x; i++) {\r\n let x = i / float(subdivisions.x);\r\n let posX = x * size.x - halfSize.x;\r\n\r\n for (let j = 0; j <= subdivisions.y; j++) {\r\n let y = j / float(subdivisions.y);\r\n let posY = y * size.y - halfSize.y;\r\n\r\n self.vertices.push((posX, 0, posY));\r\n self.normals.push((0, 1, 0));\r\n self.tangents.push((1, 0, 0));\r\n self.bitangents.push((0, 0, 1));\r\n self.uvs.push((x, y));\r\n }\r\n }\r\n\r\n for (let i = 0; i < subdivisions.x; i++) {\r\n for (let j = 0; j < subdivisions.y; j++) {\r\n let i0 = i * (subdivisions.y + 1) + j;\r\n let i1 = i0 + 1;\r\n let i2 = i0 + subdivisions.y + 1;\r\n let i3 = i2 + 1;\r\n\r\n self.triangles.push(index + i0);\r\n self.triangles.push(index + i1);\r\n self.triangles.push(index + i2);\r\n\r\n self.triangles.push(index + i2);\r\n self.triangles.push(index + i1);\r\n self.triangles.push(index + i3);\r\n }\r\n }\r\n\r\n self.translate(pos);\r\n }\r\n\r\n pub fn translate(self, pos: float3): Mesh {\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n self.vertices[i] += pos;\r\n }\r\n\r\n return self;\r\n }\r\n\r\n pub fn rotate(self, quaternion: float4): Mesh {\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n self.vertices[i] = quat::rotate(quaternion, self.vertices[i]);\r\n }\r\n\r\n for (let i = 0; i < self.normals.len(); i++) {\r\n self.normals[i] = quat::rotate(quaternion, self.normals[i]);\r\n }\r\n\r\n return self;\r\n }\r\n\r\n pub fn transform(self, matrix: float4x4): Mesh {\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n self.vertices[i] = ((self.vertices[i], 1) * matrix).xyz;\r\n }\r\n\r\n for (let i = 0; i < self.normals.len(); i++) {\r\n self.normals[i] = ((self.normals[i], 1) * matrix).xyz;\r\n }\r\n\r\n return self;\r\n }\r\n\r\n pub fn scale(self, scale: float3): Mesh {\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n self.vertices[i] *= scale;\r\n }\r\n\r\n return self;\r\n }\r\n\r\n pub fn bounds(self): float3 {\r\n let mn = 0.0.xyz;\r\n let mx = 0.0.xyz;\r\n\r\n for (let i = 0; i < self.vertices.len(); i++) {\r\n mn = min(mn, self.vertices[i]);\r\n mx = max(mx, self.vertices[i]);\r\n }\r\n\r\n return mx - mn;\r\n }\r\n\r\n pub fn center(self): float3 {\r\n let bounds = self.bounds();\r\n return bounds / 2.0;\r\n }\r\n\r\n pub fn new() {\r\n return Mesh {\r\n vertices: [],\r\n triangles: [],\r\n tangents: [],\r\n bitangents: [],\r\n normals: [],\r\n uvs: [],\r\n colors: [],\r\n }\r\n }\r\n\r\n pub fn append(self, other: Mesh) {\r\n let oldVertices = self.vertices.len();\r\n let oldTriangles = self.triangles.len();\r\n\r\n self.vertices.append(other.vertices);\r\n self.triangles.append(other.triangles);\r\n self.normals.append(other.normals);\r\n self.tangents.append(other.tangents);\r\n self.bitangents.append(other.bitangents);\r\n self.uvs.append(other.uvs);\r\n self.colors.append(other.colors);\r\n\r\n for (let i = oldTriangles; i < self.triangles.len(); i++) {\r\n self.triangles[i] += oldVertices;\r\n }\r\n }\r\n\r\n pub fn getVertices(self) {\r\n return self.vertices;\r\n }\r\n\r\n pub fn getTriangles(self) {\r\n return self.triangles;\r\n }\r\n\r\n pub fn getNormals(self) {\r\n return self.normals;\r\n }\r\n\r\n pub fn getTangents(self) {\r\n return self.tangents;\r\n }\r\n\r\n pub fn getBitangents(self) {\r\n return self.bitangents;\r\n }\r\n\r\n pub fn getUVs(self) {\r\n return self.uvs;\r\n }\r\n\r\n pub fn getColors(self) {\r\n return self.colors;\r\n }\r\n\r\n pub fn setVertices(self, vertices: float3[]) {\r\n self.vertices = vertices;\r\n }\r\n\r\n pub fn setTriangles(self, triangles: int[]) {\r\n self.triangles = triangles;\r\n }\r\n\r\n pub fn setNormals(self, normals: float3[]) {\r\n self.normals = normals;\r\n }\r\n\r\n pub fn setTangents(self, tangents: float3[]) {\r\n self.tangents = tangents;\r\n }\r\n\r\n pub fn setBitangents(self, bitangents: float3[]) {\r\n self.bitangents = bitangents;\r\n }\r\n\r\n pub fn setUVs(self, uvs: float2[]) {\r\n self.uvs = uvs;\r\n }\r\n\r\n pub fn setColors(self, colors: float4[]) {\r\n self.colors = colors;\r\n }\r\n}\r\n\r\npub struct mesh {}\r\n\r\nimpl mesh {\r\n pub fn rect(pos: float2, size: float2) -> Mesh {\r\n let g = Mesh::new();\r\n g.rectAt(pos, pos + size);\r\n\r\n return g;\r\n }\r\n\r\n pub fn box(pos: float3, size: float3) -> Mesh {\r\n let g = Mesh::new();\r\n g.box(size);\r\n g.translate(pos);\r\n\r\n return g;\r\n }\r\n\r\n pub fn uvSphere(pos: float3, radius: float, vertices: int = 32, rings: int = 16) -> Mesh {\r\n let g = Mesh::new();\r\n g.uvSphere(pos, radius, vertices, rings);\r\n\r\n return g;\r\n }\r\n\r\n pub fn icoSphere(pos: float3, radius: float, subdivisions: int = 1) -> Mesh {\r\n let g = Mesh::new();\r\n g.icoSphere(pos, radius, subdivisions);\r\n\r\n return g;\r\n }\r\n\r\n pub fn plane(pos: float3, size: float2, subdivisions: int2 = (2, 2)) -> Mesh {\r\n let g = Mesh::new();\r\n g.plane(pos, size, subdivisions);\r\n\r\n return g;\r\n }\r\n\r\n /**\r\n * Returns a [-1, 1] position for a given index.\r\n */\r\n pub fn triangleFromIndex(index: int): float2 {\r\n if (index == 0) {\r\n return float2(-1, 1);\r\n } else if (index == 1) {\r\n return float2(1, 1);\r\n } else if (index == 2) {\r\n return float2(0, -1);\r\n } else {\r\n return float2(0, 0);\r\n }\r\n }\r\n\r\n pub fn circleFromIndex(vertexIndex: int, vertices: int): float2 {\r\n vertexIndex = vertices - vertexIndex;\r\n let numSlices = vertices / 3;\r\n let sliceIndex = floor(float(vertexIndex) / float(vertices) * float(numSlices));\r\n \r\n let incAngle = PI * 2.0 / float(numSlices);\r\n let baseAngle = incAngle * float(sliceIndex);\r\n\r\n if (vertexIndex % 3 == 0) {\r\n return float2(0, 0);\r\n } else if (vertexIndex % 3 == 1) {\r\n return float2(cos(baseAngle), sin(baseAngle));\r\n } else {\r\n return float2(cos(baseAngle + incAngle), sin(baseAngle + incAngle));\r\n }\r\n }\r\n\r\n pub fn rectFromIndex(index: int, vertices: int): float2 {\r\n let x = index % vertices;\r\n let y = index / vertices;\r\n\r\n return float2(x, y) / float(vertices) * 2.0 - 1.0;\r\n }\r\n\r\n pub fn empty(numVerts: int = 0) -> Mesh {\r\n let g = Mesh::new();\r\n if (numVerts > 0) {\r\n g.setVertices(array(numVerts, 0.xyz));\r\n g.setNormals(array(numVerts, 0.xyz));\r\n g.setTangents(array(numVerts, 0.xyz));\r\n g.setBitangents(array(numVerts, 0.xyz));\r\n g.setUVs(array(numVerts, 0.xy));\r\n g.setColors(array(numVerts, 0.xyzw));\r\n let tris = array(numVerts, 0);\r\n for (let i = 0; i < numVerts; i++) {\r\n tris[i] = i;\r\n }\r\n g.setTriangles(tris);\r\n }\r\n\r\n return g;\r\n }\r\n\r\n pub fn join(mesh1: Mesh, mesh2: Mesh) {\r\n let g = Mesh::new();\r\n g.append(mesh1);\r\n g.append(mesh2);\r\n\r\n return g;\r\n }\r\n\r\n // pub fn cylinder(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh {\r\n // let g = Mesh::new();\r\n // g.cylinder(pos, radius, height, vertices);\r\n\r\n // return g;\r\n // }\r\n\r\n // pub fn capsule(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh {\r\n // let g = Mesh::new();\r\n // g.capsule(pos, radius, height, vertices);\r\n\r\n // return g;\r\n // }\r\n\r\n // pub fn cone(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh {\r\n // let g = Mesh::new();\r\n // g.cone(pos, radius, height, vertices);\r\n\r\n // return g;\r\n // }\r\n}\r\n\r\npub struct Material {\r\n pub baseColor: float4,\r\n pub color: texture2d,\r\n \r\n pub normal: texture2d,\r\n pub normalScale: float2,\r\n pub roughness: texture2d,\r\n pub emissive: texture2d,\r\n \r\n \r\n pub metallic: texture2d,\r\n}\r\n\r\npub struct ModelPart {\r\n pub mesh: Mesh,\r\n pub material: Material,\r\n pub transform: float4x4,\r\n}\r\n\r\npub struct Model {\r\n pub parts: ModelPart[],\r\n}\r\n\r\nwindow.SHD_Mesh = Mesh;\r\nwindow.SHD_Model = Model;\r\nwindow.SHD_ModelPart = ModelPart;\r\nwindow.SHD_Material = Material;"; const geo = "struct GeoSegment {\r\n start: float2,\r\n end: float2,\r\n kind: int,\r\n arcRadius: float,\r\n arcStart: float,\r\n arcEnd: float\r\n}\r\n\r\nstruct GeoPoly {\r\n segments: GeoSegment[]\r\n}\r\n\r\ntrait Geometry {\r\n fn area(self) -> float;\r\n fn perimeter(self) -> float;\r\n fn discretize(self) -> GeoPoly;\r\n}\r\n\r\nimpl Geometry for GeoPoly {\r\n pub fn area(self) -> float {\r\n return 0.0;\r\n }\r\n\r\n pub fn perimeter(self) -> float {\r\n return 0.0;\r\n }\r\n\r\n pub fn discretize(self) -> GeoPoly {\r\n return self.clone();\r\n }\r\n}"; const textures = ""; const common = `\r import buffer from "/_std/buffer";\r import ui from "/_std/ui";\r import texture2d, texture3d from "/_std/texture";\r \r /**\r * Converts a position in screenSpace to a position in 2d clipSpace. e.g. (0, screenSize.x) -> (-1, 1)\r */\r pub fn pixelToClip(pixelPosition: float2) -> float2 {\r let zeroToOne = pixelPosition / env.screenSize;\r let zeroToTwo = zeroToOne * 2.0;\r let clipSpace = zeroToTwo - 1.0.xy;\r return (clipSpace.x, clipSpace.y * -1.0);\r }\r \r /**\r * Value of PI to 35 decimal places.\r */\r const PI = 3.14159265358979323846264338327950288;\r \r export {\r PI,\r buffer,\r texture2d,\r texture3d,\r ui\r };\r \r /**\r * Quaternion helpers\r */\r pub struct quat {}\r \r impl quat {\r /**\r * Creates a quaternion from an angle and axis.\r */\r pub fn fromAngleAxis(angle: float, axis: float3) -> float4 {\r return float4(axis * sin(angle * 0.5), cos(angle * 0.5));\r }\r \r /**\r * Multiplies two quaternions and returns the result.\r */\r pub fn mul(a: float4, b: float4) -> float4 {\r return float4(\r b.xyz * a.w + a.xyz * b.w + cross(a.xyz, b.xyz),\r a.w * b.w - dot(a.xyz, b.xyz)\r );\r }\r \r /**\r * Rotates a vector by a quaternion and returns the rotated vector.\r */\r pub fn rotate(quaternion: float4, vector: float3) -> float3 {\r let q = quat::mul(quat::mul(quaternion, float4(vector, 0)), quat::conjugate(quaternion));\r return q.xyz;\r }\r \r /**\r * Returns the conjugate of the input quaternion.\r *\r * The conjugate of a quaternion number is a quaternion with the same magnitudes but with the sign of the imaginary parts changed\r */\r pub fn conjugate(quaternion: float4) -> float4 {\r return float4(-quaternion.xyz, quaternion.w);\r }\r \r /**\r * Returns the inverse of the input quaternion.\r */\r pub fn inverse(quaternion: float4) -> float4 {\r return quat::conjugate(quaternion) / dot(quaternion, quaternion);\r }\r \r /**\r * Generates a quaternion that rotates from one direction to another via the shortest path.\r */\r pub fn fromToRotation(from: float3, to: float3) -> float4 {\r let q = 0.0.xyzw;\r let d = dot(from, to);\r if (d < -0.999999)\r {\r let right = float3(1, 0, 0);\r let up = float3(0, 1, 0);\r let tmp = cross(right, from);\r if (length(tmp) < 0.000001)\r {\r tmp = cross(up, from);\r }\r tmp = normalize(tmp);\r q = quat::fromAngleAxis(PI, tmp);\r } else if (d > 0.999999) {\r q = float4(0, 0, 0, 1);\r } else {\r q = float4(cross(from, to), 1 + d);\r q = normalize(q);\r }\r return q;\r }\r \r \r pub fn diff(a: float4, b: float4) -> float {\r return a * quat::inverse(b);\r }\r \r \r /**\r * Generates lookAt quaternion.\r */\r pub fn lookAt(forward: float3, up: float3): float4 {\r let right = normalize(cross(forward, up));\r up = normalize(cross(forward, right));\r \r let m00 = right.x;\r let m01 = right.y;\r let m02 = right.z;\r let m10 = up.x;\r let m11 = up.y;\r let m12 = up.z;\r let m20 = forward.x;\r let m21 = forward.y;\r let m22 = forward.z;\r \r let num8 = (m00 + m11) + m22;\r let q = float4(0, 0, 0, 1);\r if (num8 > 0.0)\r {\r let num = sqrt(num8 + 1.0);\r let w = num * 0.5;\r num = 0.5 / num;\r let x = (m12 - m21) * num;\r let y = (m20 - m02) * num;\r let z = (m01 - m10) * num;\r return float4(x, y, z, w);\r }\r \r if ((m00 >= m11) && (m00 >= m22))\r {\r let num7 = sqrt(((1.0 + m00) - m11) - m22);\r let num4 = 0.5 / num7;\r let x = 0.5 * num7;\r let y = (m01 + m10) * num4;\r let z = (m02 + m20) * num4;\r let w = (m12 - m21) * num4;\r return float4(x, y, z, w);\r }\r \r if (m11 > m22)\r {\r let num6 = sqrt(((1.0 + m11) - m00) - m22);\r let num3 = 0.5 / num6;\r let x = (m10 + m01) * num3;\r let y = 0.5 * num6;\r let z = (m21 + m12) * num3;\r let w = (m20 - m02) * num3;\r return float4(x, y, z, w);\r }\r \r let num5 = sqrt(((1.0 + m22) - m00) - m11);\r let num2 = 0.5 / num5;\r let x = (m20 + m02) * num2;\r let y = (m21 + m12) * num2;\r let z = 0.5 * num5;\r let w = (m01 - m10) * num2;\r return float4(x, y, z, w);\r }\r \r /**\r * Smooth interpolation between two quaternions.\r */\r pub fn slerp(a: float4, b: float4, t: float) -> float4 {\r \r if (length(a) == 0.0)\r {\r if (length(b) == 0.0)\r {\r return float4(0, 0, 0, 1);\r }\r return b;\r } else if (length(b) == 0.0) {\r return a;\r }\r \r let cosHalfAngle = a.w * b.w + dot(a.xyz, b.xyz);\r \r if (cosHalfAngle >= 1.0 || cosHalfAngle <= -1.0)\r {\r return a;\r } else if (cosHalfAngle < 0.0) {\r b *= -1.0;\r cosHalfAngle = -cosHalfAngle;\r }\r \r let blendA = 0.0;\r let blendB = 0.0;\r if (cosHalfAngle < 0.99)\r {\r let halfAngle = acos(cosHalfAngle);\r let sinHalfAngle = sin(halfAngle);\r let oneOverSinHalfAngle = 1.0 / sinHalfAngle;\r blendA = sin(halfAngle * (1.0 - t)) * oneOverSinHalfAngle;\r blendB = sin(halfAngle * t) * oneOverSinHalfAngle;\r }\r else\r {\r blendA = 1.0 - t;\r blendB = t;\r }\r \r let result = float4(blendA * a.xyz + blendB * b.xyz, blendA * a.w + blendB * b.w);\r if (length(result) > 0.0)\r {\r return normalize(result);\r }\r return float4(0, 0, 0, 1);\r }\r \r /**\r * Converts quaternion to matrix.\r */\r pub fn toMatrix(quaternion: float4) {\r let x = quaternion.x;\r let y = quaternion.y;\r let z = quaternion.z;\r let w = quaternion.w;\r let x2 = x + x;\r let y2 = y + y;\r let z2 = z + z;\r let xx = x * x2;\r let xy = x * y2;\r let xz = x * z2;\r let yy = y * y2;\r let yz = y * z2;\r let zz = z * z2;\r let wx = w * x2;\r let wy = w * y2;\r let wz = w * z2;\r \r \r let m = float4x4(\r 1.0 - (yy + zz), xy + wz, xz - wy, 0,\r xy - wz, 1.0 - (xx + zz), yz + wx, 0,\r xz + wy, yz - wx, 1.0 - (xx + yy), 0,\r 0, 0, 0, 1.0\r );\r \r return m;\r }\r \r pub fn fromEulerAngles(angles: float3) {\r let cr = cos(angles.x * 0.5);\r let sr = sin(angles.x * 0.5);\r let cp = cos(angles.y * 0.5);\r let sp = sin(angles.y * 0.5);\r let cy = cos(angles.z * 0.5);\r let sy = sin(angles.z * 0.5);\r \r return float4(\r sr * cp * cy - cr * sp * sy,\r cr * sp * cy + sr * cp * sy,\r cr * cp * sy - sr * sp * cy,\r cr * cp * cy + sr * sp * sy\r )\r }\r }\r \r window.shadeupQuat = quat;\r \r \r pub struct Camera2d {\r pub position: float2 = float2(0, 0);\r pub zoom: float = 1;\r }\r \r impl Camera2d {\r pub fn transform(self, position: float2) -> float2 {\r return (position - self.position) * self.zoom;\r }\r \r /**\r * Moves and zooms the camera to fit the given size. (centers the camera in the viewport)\r */\r pub fn fit(self, size: float2) {\r let zoom = 1/min(env.screenSize.x / size.x, env.screenSize.y / size.y);\r let position = (env.screenSize - size * (1/zoom)) / 2;\r self.position = position;\r self.zoom = zoom;\r }\r }\r \r pub struct Camera {\r pub position: float3 = float3(0, 0, 0);\r pub rotation: float4 = float4(1, 0, 0, 0);\r pub width: float = 1920;\r pub height: float = 1080;\r pub fov: float = 90;\r pub near: float = 1;\r pub far: float = 100000;\r }\r \r impl Camera {\r pub fn getRay(self, screen: float2) {\r let aspect = self.width / self.height;\r let x = screen.x;\r let y = screen.y;\r let Px = (2 * ((x + 0.5) / self.width) - 1) * tan(self.fov / 2 * PI / 180) * aspect;\r let Py = (1 - 2 * ((y + 0.5) / self.height)) * tan(self.fov / 2 * PI / 180);\r \r return quat::rotate(self.rotation, normalize((Px, Py, -1)));\r }\r \r pub fn getTransformToViewMatrix(self, position: float3, scale: float3, rotation: float4) {\r let rotationMatrix = quat::toMatrix(rotation);\r let translationMatrix = float4x4(\r scale.x, 0, 0, 0,\r 0, scale.y, 0, 0,\r 0, 0, scale.z, 0,\r position.x, position.y, position.z, 1\r );\r return self.getPerspectiveMatrix() * self.getWorldToViewMatrix() * translationMatrix * rotationMatrix;\r }\r \r pub fn getCombinedMatrix(self) -> float4x4 {\r return self.getPerspectiveMatrix() * self.getWorldToViewMatrix();\r }\r \r pub fn getCombinedMatrixReverseZ(self) -> float4x4 {\r return self.getPerspectiveMatrixReverseZ() * self.getWorldToViewMatrix();\r }\r \r pub fn getWorldToViewMatrix(self) -> float4x4 {\r let rotationMatrix = quat::toMatrix(self.rotation);\r let translationMatrix = float4x4(\r 1, 0, 0, 0,\r 0, 1, 0, 0,\r 0, 0, 1, 0,\r self.position.x, self.position.y, self.position.z, 1\r );\r return inverse(translationMatrix * rotationMatrix);\r }\r \r pub fn getPerspectiveMatrixReverseZ(self) -> float4x4 {\r return matrix::perspectiveReverseZ(self.fov, self.width / self.height, self.near);\r }\r \r pub fn getPerspectiveMatrix(self) -> float4x4 {\r return matrix::perspective(self.fov, self.width / self.height, self.near, self.far);\r // // let matrix = float4x4();\r // let far = self.far;\r // let near = self.near;\r // let aspect = self.width / self.height;\r // let fovRad = radians(self.fov);\r // let tanFov = tan( fovRad * 0.5 );\r // // matrix[0][0] = ;\r // // matrix[1][1] = 1.0 / tanFov;\r // // matrix[2][2] = -((far + near)/(far - near));\r // // matrix[3][2] = -((2*(near*far))/(far - near));\r // // matrix[2][3] = -1;\r // // matrix[3][3] = 0;\r \r // let matrix = float4x4(\r // 1.0 / (tanFov * aspect), 0, 0, 0,\r // 0, 1.0 / tanFov, 0, 0,\r // 0, 0, -((far + near)/(far - near)), -1,\r // 0, 0, -((2*(near*far))/(far - near)), 0\r // );\r \r // return matrix;\r }\r \r pub fn getOrthographicMatrix(self) -> float4x4 {\r let matrix = float4x4();\r let far = self.far;\r let near = self.near;\r \r let w = 1.0 / self.width;\r let h = 1.0 / self.height;\r \r matrix[0][0] = w;\r matrix[1][1] = h;\r matrix[2][2] = -(2.0/(far - near));\r matrix[2][3] = ((far + near)/(far-near));\r //matrix[2][2] = -((far + near)/(far - near));\r //matrix[3][2] = -((2*(near*far))/(far - near));\r matrix[3][3] = 1.0;\r \r return matrix;\r }\r }\r \r \r window._makeCamera = Camera;\r window._makeCamera2d = Camera2d;\r \r fn easeA(aA1: float, aA2: float) -> float {\r return 1.0 - 3.0 * aA2 + 3.0 * aA1;\r }\r \r fn easeB(aA1: float, aA2: float) -> float {\r return 3.0 * aA2 - 6.0 * aA1;\r }\r \r fn easeC(aA1: float) -> float {\r return 3.0 * aA1;\r }\r \r fn calcBezier(aT: float, aA1: float, aA2: float) -> float {\r return ((easeA(aA1, aA2) * aT + easeB(aA1, aA2)) * aT + easeC(aA1)) * aT;\r }\r \r fn getSlope(aT: float, aA1: float, aA2: float) -> float {\r return 3.0 * easeA(aA1, aA2) * aT * aT + 2.0 * easeB(aA1, aA2) * aT + easeC(aA1);\r }\r \r // fn getTForX(aX: float, aA1: float, aA2: float) -> float {\r // let aGuessT = aX;\r // for (let i = 0; i <= 10; i++) {\r // let currentSlope = bezSlope(aGuessT, aA1, aA2);\r // if (currentSlope == 0.0) {\r // return aGuessT;\r // }\r // let currentX = calcBezier(aGuessT, aA1, aA2) - aX;\r // aGuessT -= currentX / currentSlope;\r // }\r // return aGuessT;\r // }\r \r \r const NEWTON_ITERATIONS = 4;\r const NEWTON_MIN_SLOPE = 0.02;\r const SUBDIVISION_PRECISION = 0.0000001;\r const SUBDIVISION_MAX_ITERATIONS = 10;\r const kSplineTableSize = 11;\r \r const kSampleStepSize =\r 1.0 / float(kSplineTableSize - 1);\r \r \r fn getTForX(aX: float, mX1: float, mX2: float) {\r let mSampleValues: array = array(11, 0);\r for (let i = 0; i < kSplineTableSize; i++) {\r mSampleValues[i] = calcBezier(float(i) * kSampleStepSize, mX1, mX2);\r }\r \r // Find interval where t lies\r let intervalStart = 0.0;\r let currentSample = 1;\r let lastSample = kSplineTableSize - 1;\r \r for (let dummy = 0; currentSample != lastSample && mSampleValues[currentSample] <= aX; currentSample++) {\r intervalStart += kSampleStepSize;\r }\r currentSample--; // t now lies between *currentSample and *currentSample+1\r \r // Interpolate to provide an initial guess for t\r let csamp = mSampleValues[currentSample];\r let dst = (aX - csamp) /\r (mSampleValues[currentSample + 1] - csamp);\r let guessForT = intervalStart + dst * kSampleStepSize;\r \r // Check the slope to see what strategy to use. If the slope is too small\r // Newton-Raphson iteration won't converge on a root so we use bisection\r // instead.\r let initialSlope = getSlope(guessForT, mX1, mX2);\r if (initialSlope >= NEWTON_MIN_SLOPE) {\r return newtonRaphsonIterate(aX, guessForT, mX1, mX2);\r } else if (initialSlope == 0.0) {\r return guessForT;\r } else {\r return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);\r }\r }\r \r fn newtonRaphsonIterate(aX: float, aGuessT: float, mX1: float, mX2: float) {\r // Refine guess with Newton-Raphson iteration\r for (let i = 0; i < NEWTON_ITERATIONS; i++) {\r // We're trying to find where f(t) = aX,\r // so we're actually looking for a root for: CalcBezier(t) - aX\r let currentX = calcBezier(aGuessT, mX1, mX2) - aX;\r let currentSlope = getSlope(aGuessT, mX1, mX2);\r \r if (currentSlope == 0.0)\r return aGuessT;\r \r aGuessT -= currentX / currentSlope;\r }\r \r return aGuessT;\r }\r \r fn binarySubdivide(aX: float, aA: float, aB: float) {\r let currentX = 0.0;\r let currentT = 0.0;\r let i = 0;\r let mX1 = aA;\r let mX2 = aB;\r \r while (true) {\r i++;\r if (abs(currentX) > SUBDIVISION_PRECISION && i < SUBDIVISION_MAX_ITERATIONS) {\r currentT = aA + (aB - aA) / 2.0;\r currentX = calcBezier(currentT, mX1, mX2) - aX;\r \r if (currentX > 0.0) {\r aB = currentT;\r } else {\r aA = currentT;\r }\r }else{\r break;\r }\r }\r \r return currentT;\r }\r \r pub struct bezier {};\r \r impl bezier {\r pub fn cubic2(a: float2, b: float2, c: float2, d: float2, t: float) -> float2 {\r return (1.0 - t)**3 * a + 3.0 * (1.0 - t)**2 * t * b + 3.0 * (1.0 - t) * t**2 * c + t**3 * d;\r }\r \r pub fn cubic3(a: float3, b: float3, c: float3, d: float3, t: float) -> float3 {\r return (1.0 - t)**3 * a + 3.0 * (1.0 - t)**2 * t * b + 3.0 * (1.0 - t) * t**2 * c + t**3 * d;\r }\r \r pub fn quadratic2(a: float2, b: float2, c: float2, t: float) -> float2 {\r return (1.0 - t)**2 * a + 2.0 * (1.0 - t) * t * b + t**2 * c;\r }\r \r pub fn quadratic3(a: float3, b: float3, c: float3, t: float) -> float3 {\r return (1.0 - t)**2 * a + 2.0 * (1.0 - t) * t * b + t**2 * c;\r }\r \r /**\r * 3d triangle patch evaulation with barycentric coordinates.\r */\r pub fn patch(a: float3, ab: float3, b: float3, bc: float3, c: float3, ca: float3, barycentricT: float3) {\r const s = barycentricT.x;\r const t = barycentricT.y;\r const u = barycentricT.z;\r return 1.0 * c * (s * s) +\r 2.0 * bc * s * t +\r 2.0 * ca * s * u +\r 1.0 * b * (t * t) +\r 2.0 * ab * t * u +\r 1.0 * a * (u * u);\r }\r \r \r \r pub fn easing(controlA: float2, controlB: float2, t: float) -> float {\r return calcBezier(getTForX(t, controlA.x, controlB.x), controlA.y, controlB.y);\r }\r }\r \r /**\r * Provides space related utilities like z-order curves and quadtrees.\r */\r pub struct spatial {};\r \r impl spatial {\r pub fn cantorPair(v: int2) -> int {\r return ((v.x + v.y) * (v.x + v.y + 1)) / 2 + v.y;\r }\r \r pub fn cantorUnpair(v: int) -> int2 {\r let w = floor((sqrt(8.0 * v + 1.0) - 1.0) / 2.0);\r let t = (w * w + w) / 2.0;\r let y = v - t;\r let x = w - y;\r return int2(x, y);\r }\r \r pub fn hilbertRotate(n: int, b: int2, r: int2) -> int2 {\r let x = b.x;\r let y = b.y;\r if (r.y == 0) {\r if (r.x == 1) {\r x = n-1 - x;\r y = n-1 - y;\r }\r \r let t = x;\r x = y;\r y = t;\r }\r \r return int2(x, y);\r }\r \r pub fn hilbertUncurve(n: int, v: int2) -> int {\r let x = v.x;\r let y = v.y;\r let rx: int = 0;\r let ry: int = 0;\r let s: int = 0;\r let d: int = 0;\r for (s=n/2; s>0; s/=2) {\r rx = ((x & s) > 0) ? 1 : 0;\r ry = ((y & s) > 0) ? 1 : 0;\r d += s * s * ((3 * rx) ^ ry);\r let o = spatial::hilbertRotate(n, (x, y), (rx, ry));\r x = o.x;\r y = o.y;\r }\r return d;\r }\r \r pub fn hilbertCurve(n: int, v: int) -> int2 {\r let rx: int = 0;\r let ry: int = 0;\r let t = v;\r let x = 0;\r let y = 0;\r for (let s: int = 1; s < n; s *= 2) {\r rx = 1 & (t/2);\r ry = 1 & (t ^ rx);\r let o = spatial::hilbertRotate(s, (x, y), (rx, ry));\r x = o.x;\r y = o.y;\r x += s * rx;\r y += s * ry;\r t /= 4;\r }\r \r return int2(x, y);\r }\r \r pub fn mortonDecode(p: uint) -> uint2 {\r return uint2(reverseMortonCode2(p), reverseMortonCode2(p >> 1u));\r }\r \r pub fn mortonEncode(p: uint2) -> uint {\r return uint(mortonCode2(p.x) | (mortonCode2(p.y) << 1u));\r }\r \r }\r \r pub fn mortonCode2(x: uint) -> uint {\r x = x & 0x0000ffffu;\r let n8 = 8u;\r let n4 = 4u;\r let n2 = 2u;\r let n1 = 1u;\r x = (x ^ (x << n8)) & 0x00ff00ffu;\r x = (x ^ (x << n4)) & 0x0f0f0f0fu;\r x = (x ^ (x << n2)) & 0x33333333u;\r x = (x ^ (x << n1)) & 0x55555555u;\r return x;\r }\r \r pub fn randColor(seed: float) -> float4 {\r return float4(rand2((seed,5)), rand2((seed, 1)), rand2((seed, 4)), 1);\r }\r \r pub fn randColor2(seed: float2) -> float4 {\r return float4(rand3((seed,5)), rand3((seed, 1)), rand3((seed, 4)), 1);\r }\r \r pub fn reverseMortonCode2(x: uint) -> uint {\r x = x & 0x55555555u;\r x = (x ^ (x >> 1u)) & 0x33333333u;\r x = (x ^ (x >> 2u)) & 0x0f0f0f0fu;\r x = (x ^ (x >> 4u)) & 0x00ff00ffu;\r x = (x ^ (x >> 8u)) & 0x0000ffffu;\r return x;\r }\r \r pub struct noise {};\r \r \r const PERLIN_YWRAPB = 4;\r const PERLIN_YWRAP = 1 << PERLIN_YWRAPB;\r const PERLIN_ZWRAPB = 8;\r const PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB;\r const PERLIN_SIZE = 4095;\r \r let perlin_octaves = 4; // default to medium smooth\r let perlin_amp_falloff = 0.5; // 50% reduction/octave\r \r \r fn scaled_cosine(i: float) -> float {\r return 0.5 * (1.0 - cos(i * PI));\r }\r \r let perlin = buffer(PERLIN_SIZE + 1);\r for (let i = 0; i < PERLIN_SIZE + 1; i++) {\r perlin[i] = rand(i);\r }\r \r // \r // By Morgan McGuire @morgan3d, http://graphicscodex.com\r //\r fn hash(n: float) -> float { return frac(sin(n) * 1e4); }\r fn hash2(p: float2) -> float { return frac(1e4 * sin(17.0 * p.x + p.y * 0.1) * (0.1 + abs(sin(p.y * 13.0 + p.x)))); }\r fn hash3(p: float3) -> float { let h = dot(p, float3(127.1, 311.7, 74.7)); return frac(sin(h) * 43758.5453123); }\r \r \r \r impl noise {\r pub fn gaussian3(v: float3) -> float {\r let p = v;\r let a = floor(p);\r let d = p - a;\r d = d * d * (3.0 - 2.0 * d);\r \r let b = a.xxyy + float4(0.0, 1.0, 0.0, 1.0);\r let k1 = perm(b.xyxy);\r let k2 = perm(k1.xyxy + b.zzww);\r \r let c = k2 + a.zzzz;\r let k3 = perm(c);\r let k4 = perm(c + 1.0);\r \r let o1 = frac(k3 * (1.0 / 41.0));\r let o2 = frac(k4 * (1.0 / 41.0));\r \r let o3 = o2 * d.z + o1 * (1.0 - d.z);\r let o4 = o3.yw * d.x + o3.xz * (1.0 - d.x);\r \r return o4.y * d.y + o4.x * (1.0 - d.y);\r }\r \r pub fn gaussian2(v: float2) -> float {\r return noise::gaussian3((v, 0));\r }\r \r pub fn noise1(x: float) {\r let i = floor(x);\r let f = frac(x);\r let u = f * f * (3.0 - 2.0 * f);\r return lerp(hash(i), hash(i + 1.0), u);\r }\r \r pub fn noise2(x: float2) -> float {\r let i = floor(x);\r let f = frac(x);\r \r // Four corners in 2D of a tile\r let a = hash2(i);\r let b = hash2(i + float2(1.0, 0.0));\r let c = hash2(i + float2(0.0, 1.0));\r let d = hash2(i + float2(1.0, 1.0));\r \r // Simple 2D lerp using smoothstep envelope between the values.\r // return float3(lerp(lerp(a, b, smoothstep(0.0, 1.0, f.x)),\r // lerp(c, d, smoothstep(0.0, 1.0, f.x)),\r // smoothstep(0.0, 1.0, f.y)));\r \r // Same code, with the clamps in smoothstep and common subexpressions\r // optimized away.\r let u = f * f * (3.0 - 2.0 * f);\r return lerp(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y;\r }\r \r pub fn fmb1(x: float) -> float {\r let v = 0.0;\r let a = 0.5;\r let shift = float(100);\r for (let i = 0; i < 5; i++) {\r v += a * noise::noise1(x);\r x = x * 2.0 + shift;\r a *= 0.5;\r }\r return v;\r }\r \r pub fn fbm2(x: float2) -> float {\r let v = 0.0;\r let a = 0.5;\r let shift = float2(100.xy);\r // Rotate to reduce axial bias\r let rot = float2x2(cos(0.5), sin(0.5), -sin(0.5), cos(0.50));\r for (let i = 0; i < 5; i++) {\r v += a * noise::noise2(x);\r x = rot * x * 2.0 + shift;\r a *= 0.5;\r }\r return v;\r }\r \r pub fn fbm3(x: float3) -> float {\r let v = 0.0;\r let a = 0.5;\r let shift = float3(100.xyz);\r for (let i = 0; i < 5; i++) {\r v += a * noise::noise3(x);\r x = x * 2.0 + shift;\r a *= 0.5;\r }\r return v;\r }\r \r pub fn noise3(x: float3) -> float {\r const step = float3(110, 241, 171);\r \r let i = floor(x);\r let f = frac(x);\r \r // For performance, compute the base input to a 1D hash from the integer part of the argument and the \r // incremental change to the 1D based on the 3D -> 1D wrapping\r let n = dot(i, step);\r \r let u = f * f * (3.0 - 2.0 * f);\r return lerp(lerp(lerp( hash(n + dot(step, float3(0, 0, 0))), hash(n + dot(step, float3(1, 0, 0))), u.x),\r lerp( hash(n + dot(step, float3(0, 1, 0))), hash(n + dot(step, float3(1, 1, 0))), u.x), u.y),\r lerp(lerp( hash(n + dot(step, float3(0, 0, 1))), hash(n + dot(step, float3(1, 0, 1))), u.x),\r lerp( hash(n + dot(step, float3(0, 1, 1))), hash(n + dot(step, float3(1, 1, 1))), u.x), u.y), u.z);\r }\r \r pub fn simplex2(v: float2) -> float {\r let C = float4(0.211324865405187,\r 0.366025403784439,\r -0.577350269189626,\r 0.024390243902439);\r \r let i = floor(v + dot(v, C.yy));\r let x0 = v - i + dot(i, C.xx);\r \r let xv = step(x0.y, x0.x);\r \r let i1 = float2(xv, 1.0 - xv);\r \r let x1 = x0 + C.xx - i1;\r let x2 = x0 + C.zz;\r \r \r i = mod289_2(i);\r let p =\r permute(\r permute(float3(0.0, i1.y, 1.0) + i.y)\r + float3(0.0, i1.x, 1.0) + i.x);\r \r let m = max(0.5.xyz - float3(dot(x0, x0), dot(x1, x1), dot(x2, x2)), 0.0);\r m = m * m;\r m = m * m;\r \r let x = 2.0 * frac(p * C.www) - 1.0;\r let h = abs(x) - 0.5;\r let ox = floor(x + 0.5);\r let a0 = x - ox;\r \r // Normalise gradients implicitly by scaling m\r m *= taylorInvSqrt(a0 * a0 + h * h);\r \r // Compute final noise value at P\r let g = float3(\r a0.x * x0.x + h.x * x0.y,\r a0.y * x1.x + h.y * x1.y,\r a0.z * x2.x + h.z * x2.y\r );\r return 130.0 * dot(m, g);\r }\r \r pub fn perlin2(v: float2) -> float {\r let x = v.x;\r let y = v.y;\r let z = 0.0;\r \r if (x < 0) {\r x = -x;\r }\r if (y < 0) {\r y = -y;\r }\r if (z < 0) {\r z = -z;\r }\r \r let xi = int(floor(x)),\r yi = int(floor(y)),\r zi = int(floor(z));\r let xf = x - xi;\r let yf = y - yi;\r let zf = z - zi;\r let rxf = 0.0, ryf = 0.0;\r \r let r = 0.0;\r let ampl = 0.5;\r \r let n1= 0.0, n2 = 0.0, n3 = 0.0;\r \r for (let o = 0; o < perlin_octaves; o++) {\r let of1: int = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB);\r \r rxf = scaled_cosine(xf);\r ryf = scaled_cosine(yf);\r \r n1 = perlin[of1 & PERLIN_SIZE];\r n1 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n1);\r n2 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE];\r n2 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2);\r n1 += ryf * (n2 - n1);\r \r of1 += PERLIN_ZWRAP;\r n2 = perlin[of1 & PERLIN_SIZE];\r n2 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n2);\r n3 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE];\r n3 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3);\r n2 += ryf * (n3 - n2);\r \r n1 += scaled_cosine(zf) * (n2 - n1);\r \r r += n1 * ampl;\r ampl *= perlin_amp_falloff;\r xi = xi << 1;\r xf *= 2.0;\r yi = yi << 1;\r yf *= 2.0;\r zi = zi << 1;\r zf *= 2.0;\r \r if (xf >= 1.0) {\r xi++;\r xf-= 1.0;\r }\r if (yf >= 1.0) {\r yi++;\r yf-= 1.0;\r }\r if (zf >= 1.0) {\r zi++;\r zf-= 1.0;\r }\r }\r return r;\r \r }\r \r pub fn perlin3(v: float3) -> float {\r let x = v.x;\r let y = v.y;\r let z = v.z;\r \r if (x < 0) {\r x = -x;\r }\r if (y < 0) {\r y = -y;\r }\r if (z < 0) {\r z = -z;\r }\r \r let xi = int(floor(x)),\r yi = int(floor(y)),\r zi = int(floor(z));\r let xf = x - xi;\r let yf = y - yi;\r let zf = z - zi;\r let rxf = 0.0, ryf = 0.0;\r \r let r = 0.0;\r let ampl = 0.5;\r \r let n1= 0.0, n2 = 0.0, n3 = 0.0;\r \r for (let o = 0; o < perlin_octaves; o++) {\r let of1: int = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB);\r \r rxf = scaled_cosine(xf);\r ryf = scaled_cosine(yf);\r \r n1 = perlin[of1 & PERLIN_SIZE];\r n1 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n1);\r n2 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE];\r n2 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2);\r n1 += ryf * (n2 - n1);\r \r of1 += PERLIN_ZWRAP;\r n2 = perlin[of1 & PERLIN_SIZE];\r n2 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n2);\r n3 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE];\r n3 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3);\r n2 += ryf * (n3 - n2);\r \r n1 += scaled_cosine(zf) * (n2 - n1);\r \r r += n1 * ampl;\r ampl *= perlin_amp_falloff;\r xi = xi << 1;\r xf *= 2.0;\r yi = yi << 1;\r yf *= 2.0;\r zi = zi << 1;\r zf *= 2.0;\r \r if (xf >= 1.0) {\r xi++;\r xf-= 1.0;\r }\r if (yf >= 1.0) {\r yi++;\r yf-= 1.0;\r }\r if (zf >= 1.0) {\r zi++;\r zf-= 1.0;\r }\r }\r return r;\r }\r \r /**\r * Returns 3 values: distance to closest cell, random value of closest cell, distance to closest edge.\r */\r pub fn voronoi2(v: float2) -> float3 {\r let n = floor(v);\r let minDist = 10.0;\r let toClose = 0.0.xy;\r let closestCell = 0.0.xy;\r \r \r for (let j = -1; j <= 1; j++) {\r for (let i = -1; i <= 1; i++) {\r let cell = n + float2(i, j);\r let cellPos = cell + hash2(cell);\r let toCell = cellPos - v;\r let dst = length(toCell);\r if (dst < minDist) {\r minDist = dst;\r toClose = toCell;\r closestCell = cell;\r }\r }\r }\r \r let minEdge = 10.0;\r for (let j = -1; j <= 1; j++) {\r for (let i = -1; i <= 1; i++) {\r let cell = n + float2(i, j);\r let cellPos = cell + hash2(cell);\r let toCell = cellPos - v;\r let diff = abs(closestCell - cell);\r let isClosest = diff.x + diff.y < 0.1;\r if (!isClosest) {\r let toCenter = (toClose + toCell) * 0.5;\r let cellDiff = normalize(toCell - toClose);\r let edge = dot(toCenter, cellDiff);\r minEdge = min(minEdge, edge);\r }\r }\r }\r \r let random = hash2(closestCell);\r return float3(minDist, random, minEdge);\r }\r \r pub fn simplex3(v: float3) -> float {\r let C = float4(0.138196601125011,\r 0.276393202250021,\r 0.414589803375032,\r -0.447213595499958);\r \r let i = floor(v + dot(v, C.yyy));\r let x0 = v - i + dot(i, C.xxx);\r \r let g = step(x0.yzx, x0.xyz);\r let l = 1.0 - g;\r let i1 = min(g.xyz, l.zxy);\r let i2 = max(g.xyz, l.zxy);\r \r let x1 = x0 - i1 + 1.0 * C.xxx;\r let x2 = x0 - i2 + 2.0 * C.xxx;\r let x3 = x0 - 1. + 3.0 * C.xxx;\r \r i = mod289_3(i);\r let p =\r permute(\r permute(\r permute(i.z + float3(0.0, i1.z, i2.z))\r + i.y + float3(0.0, i1.y, i2.y))\r + i.x + float3(0.0, i1.x, i2.x));\r \r let m = max(0.5 - float3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0);\r m = m * m;\r m = m * m;\r \r let x = 2.0 * frac(p * C.www) - 1.0;\r let h = abs(x) - 0.5;\r let ox = floor(x + 0.5);\r let a0 = x - ox;\r \r // Normalise gradients implicitly by scaling m\r // Approximation of: m *= inversesqrt(a0 * a0 + h * h);\r m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\r \r // Compute final noise value at P\r let g2 = float3(\r a0.x * x0.x + h.x * x0.y,\r a0.y * x1.x + h.y * x1.y,\r a0.z * x2.x + h.z * x2.y\r );\r return 130.0 * dot(m, g2);\r }\r }\r \r fn mod289_1(x: float) -> float { return x - floor(x * (1.0 / 289.0)) * 289.0;}\r fn mod289_4(x: float4) -> float4 { return x - floor(x * (1.0 / 289.0)) * 289.0;}\r fn perm(x: float4) -> float4 { return mod289_4(((x * 34.0) + 1.0) * x);}\r \r fn mod289_3(x: float3) -> float3 {\r return x - floor(x * (1.0 / 289.0)) * 289.0;\r }\r \r fn mod289_2(x: float2) -> float2 {\r return x - floor(x * (1.0 / 289.0)) * 289.0;\r }\r \r fn permute(x: float3) -> float3 {\r return mod289_3((x * 34.0 + 1.0) * x);\r }\r \r fn taylorInvSqrt(r: float3) -> float3 {\r return 1.79284291400159 - 0.85373472095314 * r;\r }\r \r pub struct matrix {}\r \r impl matrix {\r pub fn lookAt(from: float3, to: float3, up: float3) -> float4x4 {\r let zAxis = normalize(from - to);\r let xAxis = normalize(cross(up, zAxis));\r let yAxis = normalize(cross(zAxis, xAxis));\r let dst = float4x4();\r dst[0][0] = xAxis.x; dst[0][1] = yAxis.x; dst[0][2] = zAxis.x; dst[0][3] = 0;\r dst[1][0] = xAxis.y; dst[1][1] = yAxis.y; dst[1][2] = zAxis.y; dst[1][3] = 0;\r dst[2][0] = xAxis.z; dst[2][1] = yAxis.z; dst[2][2] = zAxis.z; dst[2][3] = 0;\r \r dst[3][0] = -(xAxis.x * from.x + xAxis.y * from.y + xAxis.z * from.z);\r dst[3][1] = -(yAxis.x * from.x + yAxis.y * from.y + yAxis.z * from.z);\r dst[3][2] = -(zAxis.x * from.x + zAxis.y * from.y + zAxis.z * from.z);\r dst[3][3] = 1;\r \r return dst;\r \r let forward = normalize(from - to); \r \r let right = normalize(cross(up, forward)); \r \r let newup = cross(forward, right); \r let m = float4x4();\r m[0][0] = right.x, m[0][1] = right.y, m[0][2] = right.z; \r m[1][0] = newup.x, m[1][1] = newup.y, m[1][2] = newup.z; \r m[2][0] = forward.x, m[2][1] = forward.y, m[2][2] = forward.z; \r m[3][0] = from.x, m[3][1] = from.y, m[3][2] = from.z; \r \r return m;\r \r }\r \r \r pub fn perspective(fov: float, aspect: float, near: float, far: float) -> float4x4 {\r \r // set the basic projection matrix\r // let scale = 1.0 / tan(fov * 0.5 * PI / 180); \r // let M = float4x4();\r // M[0][0] = scale; //scale the x coordinates of the projected point \r // M[1][1] = scale * aspect; //scale the y coordinates of the projected point \r // M[2][2] = -far / (far - near); //used to remap z to [0,1] \r // M[3][2] = -far * near / (far - near); //used to remap z [0,1] \r // M[2][3] = -1; //set w = -z \r // M[3][3] = 0; \r \r //return M;\r \r let fovRad = radians(fov);\r let tanFov = tan( fovRad * 0.5 );\r \r let matrx = float4x4(\r 1.0 / (tanFov * aspect), 0, 0, 0,\r 0, 1.0 / tanFov, 0, 0,\r 0, 0, -((far + near)/(far - near)), -1,\r 0, 0, -((2*(near*far))/(far - near)), 0\r );\r \r return matrx;\r }\r \r pub fn perspectiveReverseZ(fov: float, aspect: float, near: float) -> float4 {\r // let scale = 1.0 / tan(fov * 0.5 * PI / 180);\r // let far = 10000000.0;\r // let M = float4x4();\r // M[0][0] = scale; //scale the x coordinates of the projected point \r // M[1][1] = scale * aspect; //scale the y coordinates of the projected point \r // M[2][2] = (-far / (far - near)) * -1; //used to remap z to [0,1] \r // M[3][2] = -far * near / (far - near); //used to remap z [0,1] \r // M[2][3] = 0; //set w = -z \r // M[3][3] = 0; \r // return M;\r \r let matrx = float4x4(\r 1, 0, 0, 0,\r 0, 1, 0, 0,\r 0, 0, -1, 0,\r 0, 0, 1, 1\r ) * matrix::perspective(fov, aspect, near, 10000000.0);\r \r return matrx;\r }\r }\r \r /**\r * Uses Super Sampling Anti Aliasing to smooth out the image.\r */\r pub fn screenAA(inScreenPos: float2, gridSize: int, func: (screenPos: float2) -> float4) {\r let weightSum = 0.0;\r let accumulatedColor = float4(0, 0, 0, 0);\r \r for (let y = 0; y < gridSize; y++) {\r for (let x = 0; x < gridSize; x++) {\r let offset = float2(\r (x + 0.5 - gridSize * 0.5) / gridSize,\r (y + 0.5 - gridSize * 0.5) / gridSize\r );\r \r let weight = exp(-dot(offset, offset) * 5); // Gaussian weight\r accumulatedColor += func(inScreenPos + offset) * weight;\r weightSum += weight;\r }\r }\r \r return accumulatedColor / weightSum;\r }\r \r \r // Color conversion helpers\r // A color = float4 containing rgba values in the range [0, 1]\r // All functions have an extra alpha functon and a reverse\r // i.e. hsl, hsla, hslFromColor, hslaFromColor\r // fn hsl(v: float3) -> float4\r \r pub fn hsl(v: float3) -> float4 {\r return hsla((v, 1));\r }\r \r pub fn hsla(v: float4) -> float4 {\r let h = v.x;\r let s = v.y;\r let l = v.z;\r let a = v.w;\r let c = (1 - abs(2 * l - 1)) * s;\r let x = c * (1 - abs(((h / 60) % 2) - 1));\r let m = l - c / 2;\r let r = 0.0;\r let g = 0.0;\r let b = 0.0;\r if (h < 60) {\r r = c;\r g = x;\r b = 0;\r } else if (h < 120) {\r r = x;\r g = c;\r b = 0;\r } else if (h < 180) {\r r = 0;\r g = c;\r b = x;\r } else if (h < 240) {\r r = 0;\r g = x;\r b = c;\r } else if (h < 300) {\r r = x;\r g = 0;\r b = c;\r } else {\r r = c;\r g = 0;\r b = x;\r }\r return float4(r + m, g + m, b + m, a);\r }\r \r pub fn hslFromColor(c: float4) -> float3 {\r let r = c.r;\r let g = c.g;\r let b = c.b;\r let a = c.a;\r let mx = max(r, max(g, b));\r let mn = min(r, min(g, b));\r let h = 0.0;\r let s = 0.0;\r let l = (mx + mn) / 2;\r if (mx == mn) {\r h = 0;\r s = 0;\r } else {\r let d = mx - mn;\r s = (l > 0.5) ? d / (2 - mx - mn) : d / (mx + mn);\r if (mx == r) {\r h = (g - b) / d + ((g < b) ? 6:0);\r } else if (mx == g) {\r h = (b - r) / d + 2;\r } else if (mx == b) {\r h = (r - g) / d + 4;\r }\r h /= 6;\r }\r return float3(h * 360, s, l);\r }\r \r pub fn hslaFromColor(c: float4) -> float4 {\r let hsl = hslFromColor(c);\r return float4(hsl, c.a);\r }\r \r pub fn hsv(v: float3) -> float4 {\r return hsva((v, 1));\r }\r \r pub fn hsva(val: float4) -> float4 {\r let h = val.x;\r let s = val.y;\r let v = val.z;\r let a = val.w;\r let c = v * s;\r let x = c * (1 - abs(mod(h / 60, 2) - 1));\r let m = v - c;\r let r = 0.0;\r let g = 0.0;\r let b = 0.0;\r if (h < 60) {\r r = c;\r g = x;\r b = 0;\r } else if (h < 120) {\r r = x;\r g = c;\r b = 0;\r } else if (h < 180) {\r r = 0;\r g = c;\r b = x;\r } else if (h < 240) {\r r = 0;\r g = x;\r b = c;\r } else if (h < 300) {\r r = x;\r g = 0;\r b = c;\r } else {\r r = c;\r g = 0;\r b = x;\r }\r return float4(r + m, g + m, b + m, a);\r }\r \r pub fn hsvFromColor(c: float4) -> float3 {\r let r = c.r;\r let g = c.g;\r let b = c.b;\r let mx = max(r, max(g, b));\r let mn = min(r, min(g, b));\r let h = 0.0;\r let s = 0.0;\r let v = mx;\r let d = mx - mn;\r s = (mx == 0) ? 0 : d / mx ;\r if (mx == mn) {\r h = 0;\r } else {\r if (mx == r) {\r h = (g - b) / d + ((g < b) ? 6 : 0 );\r } else if (mx == g) {\r h = (b - r) / d + 2;\r } else if (mx == b) {\r h = (r - g) / d + 4;\r }\r h /= 6;\r }\r return float3(h * 360, s, v);\r }\r \r pub fn hsvaFromColor(c: float4) -> float4 {\r let hsv = hsvFromColor(c);\r return float4(hsv, c.a);\r }\r \r pub fn rgb(v: float3) -> float4 {\r return float4(v / 255.0, 1);\r }\r \r pub fn rgba(v: float4) -> float4 {\r return float4(v / 255.0);\r }\r \r pub fn rgbFromColor(c: float4) -> float3 {\r return c.rgb * 255.0;\r }\r \r pub fn rgbaFromColor(c: float4) -> float4 {\r return c * 255.0;\r }\r \r pub fn cmyk(v: float4) -> float4 {\r let c = v.r;\r let m = v.g;\r let y = v.b;\r let k = v.a;\r let r = 1 - min(1, c * (1 - k) + k);\r let g = 1 - min(1, m * (1 - k) + k);\r let b = 1 - min(1, y * (1 - k) + k);\r return float4(r, g, b, 1);\r }\r \r pub fn cmykFromColor(c: float4) -> float4 {\r let r = c.r;\r let g = c.g;\r let b = c.b;\r let k = 1 - max(r, max(g, b));\r let c1 = (1 - r - k) / (1 - k);\r let m = (1 - g - k) / (1 - k);\r let y = (1 - b - k) / (1 - k);\r return float4(c1, m, y, k);\r }\r \r pub fn hex(v: int) -> float4 {\r let r: float = (v >> 16) & 0xFF;\r let g: float = (v >> 8) & 0xFF;\r let b: float = v & 0xFF;\r return float4(r / 255.0, g / 255.0, b / 255.0, 1.0);\r }\r \r pub fn hexFromColor(c: float4) -> int {\r let r = int(c.r * 255.0);\r let g = int(c.g * 255.0);\r let b = int(c.b * 255.0);\r return (r << 16) | (g << 8) | b;\r }\r \r /**\r * Returns sin remapped to [0, 1]\r */\r pub fn sin1(v: float) -> float {\r return (sin(v) + 1) * 0.5;\r }\r \r /**\r * Returns cos remapped to [0, 1]\r */\r pub fn cos1(v: float) -> float {\r return (cos(v) + 1) * 0.5;\r }\r \r /**\r * Returns tan remapped to [0, 1]\r */\r pub fn tan1(v: float) -> float {\r return (tan(v) + 1) * 0.5;\r }\r \r pub fn remap(v: float, low1: float, high1: float, low2: float, high2: float) -> float {\r return low2 + (v - low1) * (high2 - low2) / (high1 - low1);\r }\r \r pub fn remap1(v: float, low: float, high: float) -> float {\r return remap(v, low, high, 0, 1);\r }\r \r pub struct color {\r static slate50: float4 = float4(0.9725490196078431, 0.9803921568627451, 0.9882352941176471, 1);\r static slate100: float4 = float4(0.9450980392156862, 0.9607843137254902, 0.9764705882352941, 1);\r static slate200: float4 = float4(0.8862745098039215, 0.9098039215686274, 0.9411764705882353, 1);\r static slate300: float4 = float4(0.796078431372549, 0.8352941176470589, 0.8823529411764706, 1);\r static slate400: float4 = float4(0.5803921568627451, 0.6392156862745098, 0.7215686274509804, 1);\r static slate500: float4 = float4(0.39215686274509803, 0.4549019607843137, 0.5450980392156862, 1);\r static slate600: float4 = float4(0.2784313725490196, 0.3333333333333333, 0.4117647058823529, 1);\r static slate700: float4 = float4(0.2, 0.2549019607843137, 0.3333333333333333, 1);\r static slate800: float4 = float4(0.11764705882352941, 0.1607843137254902, 0.23137254901960785, 1);\r static slate900: float4 = float4(0.058823529411764705, 0.09019607843137255, 0.16470588235294117, 1);\r static slate950: float4 = float4(0.00784313725490196, 0.023529411764705882, 0.09019607843137255, 1);\r static gray50: float4 = float4(0.9764705882352941, 0.9803921568627451, 0.984313725490196, 1);\r static gray100: float4 = float4(0.9529411764705882, 0.9568627450980393, 0.9647058823529412, 1);\r static gray200: float4 = float4(0.8980392156862745, 0.9058823529411765, 0.9215686274509803, 1);\r static gray300: float4 = float4(0.8196078431372549, 0.8352941176470589, 0.8588235294117647, 1);\r static gray400: float4 = float4(0.611764705882353, 0.6392156862745098, 0.6862745098039216, 1);\r static gray500: float4 = float4(0.4196078431372549, 0.4470588235294118, 0.5019607843137255, 1);\r static gray600: float4 = float4(0.29411764705882354, 0.3333333333333333, 0.38823529411764707, 1);\r static gray700: float4 = float4(0.21568627450980393, 0.2549019607843137, 0.3176470588235294, 1);\r static gray800: float4 = float4(0.12156862745098039, 0.1607843137254902, 0.21568627450980393, 1);\r static gray900: float4 = float4(0.06666666666666667, 0.09411764705882353, 0.15294117647058825, 1);\r static gray950: float4 = float4(0.011764705882352941, 0.027450980392156862, 0.07058823529411765, 1);\r static zinc50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9803921568627451, 1);\r static zinc100: float4 = float4(0.9568627450980393, 0.9568627450980393, 0.9607843137254902, 1);\r static zinc200: float4 = float4(0.8941176470588236, 0.8941176470588236, 0.9058823529411765, 1);\r static zinc300: float4 = float4(0.8313725490196079, 0.8313725490196079, 0.8470588235294118, 1);\r static zinc400: float4 = float4(0.6313725490196078, 0.6313725490196078, 0.6666666666666666, 1);\r static zinc500: float4 = float4(0.44313725490196076, 0.44313725490196076, 0.47843137254901963, 1);\r static zinc600: float4 = float4(0.3215686274509804, 0.3215686274509804, 0.3568627450980392, 1);\r static zinc700: float4 = float4(0.24705882352941178, 0.24705882352941178, 0.27450980392156865, 1);\r static zinc800: float4 = float4(0.15294117647058825, 0.15294117647058825, 0.16470588235294117, 1);\r static zinc900: float4 = float4(0.09411764705882353, 0.09411764705882353, 0.10588235294117647, 1);\r static zinc950: float4 = float4(0.03529411764705882, 0.03529411764705882, 0.043137254901960784, 1);\r static neutral50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9803921568627451, 1);\r static neutral100: float4 = float4(0.9607843137254902, 0.9607843137254902, 0.9607843137254902, 1);\r static neutral200: float4 = float4(0.8980392156862745, 0.8980392156862745, 0.8980392156862745, 1);\r static neutral300: float4 = float4(0.8313725490196079, 0.8313725490196079, 0.8313725490196079, 1);\r static neutral400: float4 = float4(0.6392156862745098, 0.6392156862745098, 0.6392156862745098, 1);\r static neutral500: float4 = float4(0.45098039215686275, 0.45098039215686275, 0.45098039215686275, 1);\r static neutral600: float4 = float4(0.3215686274509804, 0.3215686274509804, 0.3215686274509804, 1);\r static neutral700: float4 = float4(0.25098039215686274, 0.25098039215686274, 0.25098039215686274, 1);\r static neutral800: float4 = float4(0.14901960784313725, 0.14901960784313725, 0.14901960784313725, 1);\r static neutral900: float4 = float4(0.09019607843137255, 0.09019607843137255, 0.09019607843137255, 1);\r static neutral950: float4 = float4(0.0392156862745098, 0.0392156862745098, 0.0392156862745098, 1);\r static stone50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9764705882352941, 1);\r static stone100: float4 = float4(0.9607843137254902, 0.9607843137254902, 0.9568627450980393, 1);\r static stone200: float4 = float4(0.9058823529411765, 0.8980392156862745, 0.8941176470588236, 1);\r static stone300: float4 = float4(0.8392156862745098, 0.8274509803921568, 0.8196078431372549, 1);\r static stone400: float4 = float4(0.6588235294117647, 0.6352941176470588, 0.6196078431372549, 1);\r static stone500: float4 = float4(0.47058823529411764, 0.44313725490196076, 0.4235294117647059, 1);\r static stone600: float4 = float4(0.3411764705882353, 0.3254901960784314, 0.3058823529411765, 1);\r static stone700: float4 = float4(0.26666666666666666, 0.25098039215686274, 0.23529411764705882, 1);\r static stone800: float4 = float4(0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1);\r static stone900: float4 = float4(0.10980392156862745, 0.09803921568627451, 0.09019607843137255, 1);\r static stone950: float4 = float4(0.047058823529411764, 0.0392156862745098, 0.03529411764705882, 1);\r static red50: float4 = float4(0.996078431372549, 0.9490196078431372, 0.9490196078431372, 1);\r static red100: float4 = float4(0.996078431372549, 0.8862745098039215, 0.8862745098039215, 1);\r static red200: float4 = float4(0.996078431372549, 0.792156862745098, 0.792156862745098, 1);\r static red300: float4 = float4(0.9882352941176471, 0.6470588235294118, 0.6470588235294118, 1);\r static red400: float4 = float4(0.9725490196078431, 0.44313725490196076, 0.44313725490196076, 1);\r static red500: float4 = float4(0.9372549019607843, 0.26666666666666666, 0.26666666666666666, 1);\r static red600: float4 = float4(0.8627450980392157, 0.14901960784313725, 0.14901960784313725, 1);\r static red700: float4 = float4(0.7254901960784313, 0.10980392156862745, 0.10980392156862745, 1);\r static red800: float4 = float4(0.6, 0.10588235294117647, 0.10588235294117647, 1);\r static red900: float4 = float4(0.4980392156862745, 0.11372549019607843, 0.11372549019607843, 1);\r static red950: float4 = float4(0.27058823529411763, 0.0392156862745098, 0.0392156862745098, 1);\r static orange50: float4 = float4(1, 0.9686274509803922, 0.9294117647058824, 1);\r static orange100: float4 = float4(1, 0.9294117647058824, 0.8352941176470589, 1);\r static orange200: float4 = float4(0.996078431372549, 0.8431372549019608, 0.6666666666666666, 1);\r static orange300: float4 = float4(0.9921568627450981, 0.7294117647058823, 0.4549019607843137, 1);\r static orange400: float4 = float4(0.984313725490196, 0.5725490196078431, 0.23529411764705882, 1);\r static orange500: float4 = float4(0.9764705882352941, 0.45098039215686275, 0.08627450980392157, 1);\r static orange600: float4 = float4(0.9176470588235294, 0.34509803921568627, 0.047058823529411764, 1);\r static orange700: float4 = float4(0.7607843137254902, 0.2549019607843137, 0.047058823529411764, 1);\r static orange800: float4 = float4(0.6039215686274509, 0.20392156862745098, 0.07058823529411765, 1);\r static orange900: float4 = float4(0.48627450980392156, 0.17647058823529413, 0.07058823529411765, 1);\r static orange950: float4 = float4(0.2627450980392157, 0.0784313725490196, 0.027450980392156862, 1);\r static amber50: float4 = float4(1, 0.984313725490196, 0.9215686274509803, 1);\r static amber100: float4 = float4(0.996078431372549, 0.9529411764705882, 0.7803921568627451, 1);\r static amber200: float4 = float4(0.9921568627450981, 0.9019607843137255, 0.5411764705882353, 1);\r static amber300: float4 = float4(0.9882352941176471, 0.8274509803921568, 0.30196078431372547, 1);\r static amber400: float4 = float4(0.984313725490196, 0.7490196078431373, 0.1411764705882353, 1);\r static amber500: float4 = float4(0.9607843137254902, 0.6196078431372549, 0.043137254901960784, 1);\r static amber600: float4 = float4(0.8509803921568627, 0.4666666666666667, 0.023529411764705882, 1);\r static amber700: float4 = float4(0.7058823529411765, 0.3254901960784314, 0.03529411764705882, 1);\r static amber800: float4 = float4(0.5725490196078431, 0.25098039215686274, 0.054901960784313725, 1);\r static amber900: float4 = float4(0.47058823529411764, 0.20784313725490197, 0.058823529411764705, 1);\r static amber950: float4 = float4(0.27058823529411763, 0.10196078431372549, 0.011764705882352941, 1);\r static yellow50: float4 = float4(0.996078431372549, 0.9882352941176471, 0.9098039215686274, 1);\r static yellow100: float4 = float4(0.996078431372549, 0.9764705882352941, 0.7647058823529411, 1);\r static yellow200: float4 = float4(0.996078431372549, 0.9411764705882353, 0.5411764705882353, 1);\r static yellow300: float4 = float4(0.9921568627450981, 0.8784313725490196, 0.2784313725490196, 1);\r static yellow400: float4 = float4(0.9803921568627451, 0.8, 0.08235294117647059, 1);\r static yellow500: float4 = float4(0.9176470588235294, 0.7019607843137254, 0.03137254901960784, 1);\r static yellow600: float4 = float4(0.792156862745098, 0.5411764705882353, 0.01568627450980392, 1);\r static yellow700: float4 = float4(0.6313725490196078, 0.3843137254901961, 0.027450980392156862, 1);\r static yellow800: float4 = float4(0.5215686274509804, 0.30196078431372547, 0.054901960784313725, 1);\r static yellow900: float4 = float4(0.44313725490196076, 0.24705882352941178, 0.07058823529411765, 1);\r static yellow950: float4 = float4(0.25882352941176473, 0.12549019607843137, 0.023529411764705882, 1);\r static lime50: float4 = float4(0.9686274509803922, 0.996078431372549, 0.9058823529411765, 1);\r static lime100: float4 = float4(0.9254901960784314, 0.9882352941176471, 0.796078431372549, 1);\r static lime200: float4 = float4(0.8509803921568627, 0.9764705882352941, 0.615686274509804, 1);\r static lime300: float4 = float4(0.7450980392156863, 0.9490196078431372, 0.39215686274509803, 1);\r static lime400: float4 = float4(0.6392156862745098, 0.9019607843137255, 0.20784313725490197, 1);\r static lime500: float4 = float4(0.5176470588235295, 0.8, 0.08627450980392157, 1);\r static lime600: float4 = float4(0.396078431372549, 0.6392156862745098, 0.050980392156862744, 1);\r static lime700: float4 = float4(0.30196078431372547, 0.48627450980392156, 0.058823529411764705, 1);\r static lime800: float4 = float4(0.24705882352941178, 0.3843137254901961, 0.07058823529411765, 1);\r static lime900: float4 = float4(0.21176470588235294, 0.3254901960784314, 0.0784313725490196, 1);\r static lime950: float4 = float4(0.10196078431372549, 0.1803921568627451, 0.0196078431372549, 1);\r static green50: float4 = float4(0.9411764705882353, 0.9921568627450981, 0.9568627450980393, 1);\r static green100: float4 = float4(0.8627450980392157, 0.9882352941176471, 0.9058823529411765, 1);\r static green200: float4 = float4(0.7333333333333333, 0.9686274509803922, 0.8156862745098039, 1);\r static green300: float4 = float4(0.5254901960784314, 0.9372549019607843, 0.6745098039215687, 1);\r static green400: float4 = float4(0.2901960784313726, 0.8705882352941177, 0.5019607843137255, 1);\r static green500: float4 = float4(0.13333333333333333, 0.7725490196078432, 0.3686274509803922, 1);\r static green600: float4 = float4(0.08627450980392157, 0.6392156862745098, 0.2901960784313726, 1);\r static green700: float4 = float4(0.08235294117647059, 0.5019607843137255, 0.23921568627450981, 1);\r static green800: float4 = float4(0.08627450980392157, 0.396078431372549, 0.20392156862745098, 1);\r static green900: float4 = float4(0.0784313725490196, 0.3254901960784314, 0.17647058823529413, 1);\r static green950: float4 = float4(0.0196078431372549, 0.1803921568627451, 0.08627450980392157, 1);\r static emerald50: float4 = float4(0.9254901960784314, 0.9921568627450981, 0.9607843137254902, 1);\r static emerald100: float4 = float4(0.8196078431372549, 0.9803921568627451, 0.8980392156862745, 1);\r static emerald200: float4 = float4(0.6549019607843137, 0.9529411764705882, 0.8156862745098039, 1);\r static emerald300: float4 = float4(0.43137254901960786, 0.9058823529411765, 0.7176470588235294, 1);\r static emerald400: float4 = float4(0.20392156862745098, 0.8274509803921568, 0.6, 1);\r static emerald500: float4 = float4(0.06274509803921569, 0.7254901960784313, 0.5058823529411764, 1);\r static emerald600: float4 = float4(0.0196078431372549, 0.5882352941176471, 0.4117647058823529, 1);\r static emerald700: float4 = float4(0.01568627450980392, 0.47058823529411764, 0.3411764705882353, 1);\r static emerald800: float4 = float4(0.023529411764705882, 0.37254901960784315, 0.27450980392156865, 1);\r static emerald900: float4 = float4(0.023529411764705882, 0.3058823529411765, 0.23137254901960785, 1);\r static emerald950: float4 = float4(0.00784313725490196, 0.17254901960784313, 0.13333333333333333, 1);\r static teal50: float4 = float4(0.9411764705882353, 0.9921568627450981, 0.9803921568627451, 1);\r static teal100: float4 = float4(0.8, 0.984313725490196, 0.9450980392156862, 1);\r static teal200: float4 = float4(0.6, 0.9647058823529412, 0.8941176470588236, 1);\r static teal300: float4 = float4(0.3686274509803922, 0.9176470588235294, 0.8313725490196079, 1);\r static teal400: float4 = float4(0.17647058823529413, 0.8313725490196079, 0.7490196078431373, 1);\r static teal500: float4 = float4(0.0784313725490196, 0.7215686274509804, 0.6509803921568628, 1);\r static teal600: float4 = float4(0.050980392156862744, 0.5803921568627451, 0.5333333333333333, 1);\r static teal700: float4 = float4(0.058823529411764705, 0.4627450980392157, 0.43137254901960786, 1);\r static teal800: float4 = float4(0.06666666666666667, 0.3686274509803922, 0.34901960784313724, 1);\r static teal900: float4 = float4(0.07450980392156863, 0.3058823529411765, 0.2901960784313726, 1);\r static teal950: float4 = float4(0.01568627450980392, 0.1843137254901961, 0.1803921568627451, 1);\r static cyan50: float4 = float4(0.9254901960784314, 0.996078431372549, 1, 1);\r static cyan100: float4 = float4(0.8117647058823529, 0.9803921568627451, 0.996078431372549, 1);\r static cyan200: float4 = float4(0.6470588235294118, 0.9529411764705882, 0.9882352941176471, 1);\r static cyan300: float4 = float4(0.403921568627451, 0.9098039215686274, 0.9764705882352941, 1);\r static cyan400: float4 = float4(0.13333333333333333, 0.8274509803921568, 0.9333333333333333, 1);\r static cyan500: float4 = float4(0.023529411764705882, 0.7137254901960784, 0.8313725490196079, 1);\r static cyan600: float4 = float4(0.03137254901960784, 0.5686274509803921, 0.6980392156862745, 1);\r static cyan700: float4 = float4(0.054901960784313725, 0.4549019607843137, 0.5647058823529412, 1);\r static cyan800: float4 = float4(0.08235294117647059, 0.3686274509803922, 0.4588235294117647, 1);\r static cyan900: float4 = float4(0.08627450980392157, 0.3058823529411765, 0.38823529411764707, 1);\r static cyan950: float4 = float4(0.03137254901960784, 0.2, 0.26666666666666666, 1);\r static sky50: float4 = float4(0.9411764705882353, 0.9764705882352941, 1, 1);\r static sky100: float4 = float4(0.8784313725490196, 0.9490196078431372, 0.996078431372549, 1);\r static sky200: float4 = float4(0.7294117647058823, 0.9019607843137255, 0.9921568627450981, 1);\r static sky300: float4 = float4(0.49019607843137253, 0.8274509803921568, 0.9882352941176471, 1);\r static sky400: float4 = float4(0.2196078431372549, 0.7411764705882353, 0.9725490196078431, 1);\r static sky500: float4 = float4(0.054901960784313725, 0.6470588235294118, 0.9137254901960784, 1);\r static sky600: float4 = float4(0.00784313725490196, 0.5176470588235295, 0.7803921568627451, 1);\r static sky700: float4 = float4(0.011764705882352941, 0.4117647058823529, 0.6313725490196078, 1);\r static sky800: float4 = float4(0.027450980392156862, 0.34901960784313724, 0.5215686274509804, 1);\r static sky900: float4 = float4(0.047058823529411764, 0.2901960784313726, 0.43137254901960786, 1);\r static sky950: float4 = float4(0.03137254901960784, 0.1843137254901961, 0.28627450980392155, 1);\r static blue50: float4 = float4(0.9372549019607843, 0.9647058823529412, 1, 1);\r static blue100: float4 = float4(0.8588235294117647, 0.9176470588235294, 0.996078431372549, 1);\r static blue200: float4 = float4(0.7490196078431373, 0.8588235294117647, 0.996078431372549, 1);\r static blue300: float4 = float4(0.5764705882352941, 0.7725490196078432, 0.9921568627450981, 1);\r static blue400: float4 = float4(0.3764705882352941, 0.6470588235294118, 0.9803921568627451, 1);\r static blue500: float4 = float4(0.23137254901960785, 0.5098039215686274, 0.9647058823529412, 1);\r static blue600: float4 = float4(0.1450980392156863, 0.38823529411764707, 0.9215686274509803, 1);\r static blue700: float4 = float4(0.11372549019607843, 0.3058823529411765, 0.8470588235294118, 1);\r static blue800: float4 = float4(0.11764705882352941, 0.25098039215686274, 0.6862745098039216, 1);\r static blue900: float4 = float4(0.11764705882352941, 0.22745098039215686, 0.5411764705882353, 1);\r static blue950: float4 = float4(0.09019607843137255, 0.1450980392156863, 0.32941176470588235, 1);\r static indigo50: float4 = float4(0.9333333333333333, 0.9490196078431372, 1, 1);\r static indigo100: float4 = float4(0.8784313725490196, 0.9058823529411765, 1, 1);\r static indigo200: float4 = float4(0.7803921568627451, 0.8235294117647058, 0.996078431372549, 1);\r static indigo300: float4 = float4(0.6470588235294118, 0.7058823529411765, 0.9882352941176471, 1);\r static indigo400: float4 = float4(0.5058823529411764, 0.5490196078431373, 0.9725490196078431, 1);\r static indigo500: float4 = float4(0.38823529411764707, 0.4, 0.9450980392156862, 1);\r static indigo600: float4 = float4(0.30980392156862746, 0.27450980392156865, 0.8980392156862745, 1);\r static indigo700: float4 = float4(0.2627450980392157, 0.2196078431372549, 0.792156862745098, 1);\r static indigo800: float4 = float4(0.21568627450980393, 0.18823529411764706, 0.6392156862745098, 1);\r static indigo900: float4 = float4(0.19215686274509805, 0.1803921568627451, 0.5058823529411764, 1);\r static indigo950: float4 = float4(0.11764705882352941, 0.10588235294117647, 0.29411764705882354, 1);\r static violet50: float4 = float4(0.9607843137254902, 0.9529411764705882, 1, 1);\r static violet100: float4 = float4(0.9294117647058824, 0.9137254901960784, 0.996078431372549, 1);\r static violet200: float4 = float4(0.8666666666666667, 0.8392156862745098, 0.996078431372549, 1);\r static violet300: float4 = float4(0.7686274509803922, 0.7098039215686275, 0.9921568627450981, 1);\r static violet400: float4 = float4(0.6549019607843137, 0.5450980392156862, 0.9803921568627451, 1);\r static violet500: float4 = float4(0.5450980392156862, 0.3607843137254902, 0.9647058823529412, 1);\r static violet600: float4 = float4(0.48627450980392156, 0.22745098039215686, 0.9294117647058824, 1);\r static violet700: float4 = float4(0.42745098039215684, 0.1568627450980392, 0.8509803921568627, 1);\r static violet800: float4 = float4(0.3568627450980392, 0.12941176470588237, 0.7137254901960784, 1);\r static violet900: float4 = float4(0.2980392156862745, 0.11372549019607843, 0.5843137254901961, 1);\r static violet950: float4 = float4(0.1803921568627451, 0.06274509803921569, 0.396078431372549, 1);\r static purple50: float4 = float4(0.9803921568627451, 0.9607843137254902, 1, 1);\r static purple100: float4 = float4(0.9529411764705882, 0.9098039215686274, 1, 1);\r static purple200: float4 = float4(0.9137254901960784, 0.8352941176470589, 1, 1);\r static purple300: float4 = float4(0.8470588235294118, 0.7058823529411765, 0.996078431372549, 1);\r static purple400: float4 = float4(0.7529411764705882, 0.5176470588235295, 0.9882352941176471, 1);\r static purple500: float4 = float4(0.6588235294117647, 0.3333333333333333, 0.9686274509803922, 1);\r static purple600: float4 = float4(0.5764705882352941, 0.2, 0.9176470588235294, 1);\r static purple700: float4 = float4(0.49411764705882355, 0.13333333333333333, 0.807843137254902, 1);\r static purple800: float4 = float4(0.4196078431372549, 0.12941176470588237, 0.6588235294117647, 1);\r static purple900: float4 = float4(0.34509803921568627, 0.10980392156862745, 0.5294117647058824, 1);\r static purple950: float4 = float4(0.23137254901960785, 0.027450980392156862, 0.39215686274509803, 1);\r static fuchsia50: float4 = float4(0.9921568627450981, 0.9568627450980393, 1, 1);\r static fuchsia100: float4 = float4(0.9803921568627451, 0.9098039215686274, 1, 1);\r static fuchsia200: float4 = float4(0.9607843137254902, 0.8156862745098039, 0.996078431372549, 1);\r static fuchsia300: float4 = float4(0.9411764705882353, 0.6705882352941176, 0.9882352941176471, 1);\r static fuchsia400: float4 = float4(0.9098039215686274, 0.4745098039215686, 0.9764705882352941, 1);\r static fuchsia500: float4 = float4(0.8509803921568627, 0.27450980392156865, 0.9372549019607843, 1);\r static fuchsia600: float4 = float4(0.7529411764705882, 0.14901960784313725, 0.8274509803921568, 1);\r static fuchsia700: float4 = float4(0.6352941176470588, 0.10980392156862745, 0.6862745098039216, 1);\r static fuchsia800: float4 = float4(0.5254901960784314, 0.09803921568627451, 0.5607843137254902, 1);\r static fuchsia900: float4 = float4(0.4392156862745098, 0.10196078431372549, 0.4588235294117647, 1);\r static fuchsia950: float4 = float4(0.2901960784313726, 0.01568627450980392, 0.3058823529411765, 1);\r static pink50: float4 = float4(0.9921568627450981, 0.9490196078431372, 0.9725490196078431, 1);\r static pink100: float4 = float4(0.9882352941176471, 0.9058823529411765, 0.9529411764705882, 1);\r static pink200: float4 = float4(0.984313725490196, 0.8117647058823529, 0.9098039215686274, 1);\r static pink300: float4 = float4(0.9764705882352941, 0.6588235294117647, 0.8313725490196079, 1);\r static pink400: float4 = float4(0.9568627450980393, 0.4470588235294118, 0.7137254901960784, 1);\r static pink500: float4 = float4(0.9254901960784314, 0.2823529411764706, 0.6, 1);\r static pink600: float4 = float4(0.8588235294117647, 0.15294117647058825, 0.4666666666666667, 1);\r static pink700: float4 = float4(0.7450980392156863, 0.09411764705882353, 0.36470588235294116, 1);\r static pink800: float4 = float4(0.615686274509804, 0.09019607843137255, 0.30196078431372547, 1);\r static pink900: float4 = float4(0.5137254901960784, 0.09411764705882353, 0.2627450980392157, 1);\r static pink950: float4 = float4(0.3137254901960784, 0.027450980392156862, 0.1411764705882353, 1);\r static rose50: float4 = float4(1, 0.9450980392156862, 0.9490196078431372, 1);\r static rose100: float4 = float4(1, 0.8941176470588236, 0.9019607843137255, 1);\r static rose200: float4 = float4(0.996078431372549, 0.803921568627451, 0.8274509803921568, 1);\r static rose300: float4 = float4(0.9921568627450981, 0.6431372549019608, 0.6862745098039216, 1);\r static rose400: float4 = float4(0.984313725490196, 0.44313725490196076, 0.5215686274509804, 1);\r static rose500: float4 = float4(0.9568627450980393, 0.24705882352941178, 0.3686274509803922, 1);\r static rose600: float4 = float4(0.8823529411764706, 0.11372549019607843, 0.2823529411764706, 1);\r static rose700: float4 = float4(0.7450980392156863, 0.07058823529411765, 0.23529411764705882, 1);\r static rose800: float4 = float4(0.6235294117647059, 0.07058823529411765, 0.2235294117647059, 1);\r static rose900: float4 = float4(0.5333333333333333, 0.07450980392156863, 0.21568627450980393, 1);\r static rose950: float4 = float4(0.2980392156862745, 0.0196078431372549, 0.09803921568627451, 1);\r \r }\r \r \r pub fn wrap2(value: float2, low: float, high: float) {\r return (wrap(value.x, low, high), wrap(value.y, low, high));\r }\r \r pub fn wrap3(value: float3, low: float, high: float) {\r return (wrap(value.x, low, high), wrap(value.y, low, high), wrap(value.z, low, high));\r }\r \r pub fn wrap4(value: float4, low: float, high: float) {\r return (wrap(value.x, low, high), wrap(value.y, low, high), wrap(value.z, low, high), wrap(value.w, low, high));\r }`; const sdf = "/**\r\n* Heplful utility for working with signed distance fields.\r\n* Most of the implementation was taken from https://iquilezles.org/articles/distfunctions/\r\n*/\r\n\r\npub struct sdf {}\r\n\r\nfn dot2( v: float2 ) -> float { return dot(v,v); }\r\nfn dot3( v: float3 ) -> float { return dot(v,v); }\r\nfn ndot( a: float2, b: float2 ) -> float { return a.x*b.x - a.y*b.y; }\r\n\r\nimpl sdf {\r\n pub fn sphere(samplePosition: float3, sphereCenter: float3, radius: float) -> float {\r\n let p = samplePosition - sphereCenter;\r\n let r = radius;\r\n return length(p) - r;\r\n }\r\n\r\n pub fn box(samplePosition: float3, boxCenter: float3, boxSize: float3) -> float {\r\n let p = samplePosition - boxCenter;\r\n let s = boxSize;\r\n let q = abs(p) - s;\r\n return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.0);\r\n }\r\n\r\n pub fn roundBox(samplePosition: float3, boxCenter: float3, boxSize: float3, cornerRadius: float) -> float {\r\n let p = samplePosition - boxCenter;\r\n let s = boxSize;\r\n let r = cornerRadius;\r\n let q = abs(p) - s;\r\n return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;\r\n }\r\n\r\n pub fn boxFrame(samplePosition: float3, boxCenter: float3, boxSize: float3, frameThickness: float) -> float {\r\n let p = samplePosition - boxCenter;\r\n let b = boxSize;\r\n let e = frameThickness;\r\n p = abs(p )-b;\r\n let q = abs(p+e)-e;\r\n return min(min(\r\n length(max(float3(p.x,q.y,q.z),0.0))+min(max(p.x,max(q.y,q.z)),0.0),\r\n length(max(float3(q.x,p.y,q.z),0.0))+min(max(q.x,max(p.y,q.z)),0.0)),\r\n length(max(float3(q.x,q.y,p.z),0.0))+min(max(q.x,max(q.y,p.z)),0.0));\r\n }\r\n\r\n pub fn torus( samplePosition: float3, torusCenter: float3, torusSize: float2 ) -> float\r\n {\r\n let p = samplePosition - torusCenter;\r\n let t = torusSize;\r\n let q = float2(length(p.xz)-t.x,p.y);\r\n return length(q)-t.y;\r\n }\r\n\r\n pub fn cappedTorus( samplePosition: float3, torusCenter: float3, torusSize: float2, ra: float, rb: float) -> float\r\n {\r\n \r\n let p1 = samplePosition - torusCenter;\r\n let p = (abs(p1.x), p1.yz);\r\n let sc = torusSize;\r\n let k = (sc.y*p.x>sc.x*p.y) ? dot(p.xy,sc) : length(p.xy);\r\n return sqrt( dot(p,p) + ra*ra - 2.0*ra*k ) - rb;\r\n }\r\n\r\n pub fn link( samplePosition: float3, linkCenter: float3, linkLength: float, r1: float, r2: float ) -> float\r\n {\r\n let p = samplePosition - linkCenter;\r\n let le = linkLength;\r\n let q = float3( p.x, max(abs(p.y)-le,0.0), p.z );\r\n return length(float2(length(q.xy)-r1,q.z)) - r2;\r\n }\r\n\r\n pub fn infinteCylinder( samplePosition: float3, cylinderCenter: float3, cylinderSize: float3) -> float\r\n {\r\n let p = samplePosition - cylinderCenter;\r\n let c = cylinderSize;\r\n return length(p.xz-c.xy)-c.z;\r\n }\r\n\r\n pub fn cone( samplePosition: float3, coneCenter: float3, c: float2, coneHeight: float ) -> float\r\n {\r\n let p = samplePosition - coneCenter;\r\n let h = coneHeight;\r\n // c is the sin/cos of the angle, h is height\r\n // Alternatively pass q instead of (c,h),\r\n // which is the point at the base in 2D\r\n let q = h*float2(c.x/c.y,-1.0);\r\n \r\n let w = float2( length(p.xz), p.y );\r\n let a = w - q*clamp( dot(w,q)/dot(q,q), 0.0, 1.0 );\r\n let b = w - q*float2( clamp( w.x/q.x, 0.0, 1.0 ), 1.0 );\r\n let k = sign( q.y );\r\n let d = min(dot( a, a ),dot(b, b));\r\n let s = max( k*(w.x*q.y-w.y*q.x),k*(w.y-q.y) );\r\n return sqrt(d)*sign(s);\r\n }\r\n\r\n pub fn plane( samplePosition: float3, planeCenter: float3, planeNormal: float3, planeHeight: float ) -> float\r\n {\r\n let p = samplePosition - planeCenter;\r\n let n = planeNormal;\r\n let h = planeHeight;\r\n \r\n // n must be normalized\r\n return dot(p,n) + h;\r\n }\r\n\r\n pub fn hexPrism( samplePosition: float3, hexCenter: float3, hexSize: float2 ) -> float\r\n {\r\n let p = samplePosition - hexCenter;\r\n let h = hexSize;\r\n\r\n let k = float3(-0.8660254, 0.5, 0.57735);\r\n p = abs(p);\r\n let dddd = min(dot(k.xy, p.xy), 0.0) * 2.0;\r\n\r\n p = p - float3(dddd * k.xy, 0.0);\r\n let d = float2(\r\n length(p.xy-float2(clamp(p.x,-k.z*h.x,k.z*h.x), h.x))*sign(p.y-h.x),\r\n p.z-h.y );\r\n return min(max(d.x,d.y),0.0) + length(max(d,0.0));\r\n }\r\n\r\n pub fn triPrism( samplePosition: float3, triCenter: float3, triSize: float2 ) -> float\r\n {\r\n let p = samplePosition - triCenter;\r\n let h = triSize;\r\n let q = abs(p);\r\n return max(q.z-h.y,max(q.x*0.866025+p.y*0.5,-p.y)-h.x*0.5);\r\n }\r\n\r\n pub fn capsuleLine( samplePosition: float3, lineStart: float3, lineEnd: float3, capsuleRadius: float ) -> float\r\n {\r\n let p = samplePosition;\r\n let a = lineStart;\r\n let b = lineEnd;\r\n let r = capsuleRadius;\r\n let pa = p - a;\r\n let ba = b - a;\r\n let h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );\r\n return length( pa - ba*h ) - r;\r\n }\r\n\r\n pub fn capsule( samplePosition: float3, capsuleCenter: float3, height: float, radius: float ) -> float\r\n {\r\n let p1 = samplePosition - capsuleCenter;\r\n let h = height;\r\n let r = radius;\r\n let p = (p1.x, p1.y - clamp( p1.y, 0.0, h ), p1.z);\r\n return length( p ) - r;\r\n }\r\n\r\n pub fn cylinder( samplePosition: float3, cylinderCenter: float3, height: float, radius: float ) -> float\r\n {\r\n let p = samplePosition - cylinderCenter;\r\n let h = height;\r\n let r = radius;\r\n let d = abs(float2(length(p.xz),p.y)) - float2(r,h);\r\n return min(max(d.x,d.y),0.0) + length(max(d,0.0));\r\n }\r\n\r\n pub fn cylinderLine( samplePosition: float3, lineStart: float3, lineEnd: float3, radius: float) -> float\r\n {\r\n let p = samplePosition;\r\n let a = lineStart;\r\n let b = lineEnd;\r\n let r = radius;\r\n\r\n let ba = b - a;\r\n let pa = p - a;\r\n let baba = dot(ba,ba);\r\n let paba = dot(pa,ba);\r\n let x = length(pa*baba-ba*paba) - r*baba;\r\n let y = abs(paba-baba*0.5) - baba*0.5;\r\n let x2 = x*x;\r\n let y2 = y*y*baba;\r\n let mxxy = max(x,y);\r\n let d = (mxxy<0.0)?-min(x2,y2):(((x>0.0)?x2:0.0)+((y>0.0)?y2:0.0));\r\n return sign(d)*sqrt(abs(d))/baba;\r\n }\r\n\r\n pub fn roundedCylinder( samplePosition: float3, cylinderCenter: float, cylinderRadius: float, cornerRadius: float, height: float ) -> float\r\n {\r\n let p = samplePosition - cylinderCenter;\r\n let h = height;\r\n let ra = cylinderRadius;\r\n let rb = cornerRadius;\r\n let d = float2( length(p.xz)-2.0*ra+rb, abs(p.y) - h );\r\n return min(max(d.x,d.y),0.0) + length(max(d,0.0)) - rb;\r\n }\r\n\r\n pub fn cappedCone( samplePosition: float3, coneCenter: float3, height: float, r1: float, r2: float ) -> float\r\n {\r\n let p = samplePosition - coneCenter;\r\n let h = height;\r\n\r\n let q = float2( length(p.xz), p.y );\r\n let k1 = float2(r2,h);\r\n let k2 = float2(r2-r1,2.0*h);\r\n let ca = float2(q.x-min(q.x,(q.y<0.0)?r1:r2), abs(q.y)-h);\r\n let cb = q - k1 + k2*clamp( dot(k1-q,k2)/dot2(k2), 0.0, 1.0 );\r\n let s = (cb.x<0.0 && ca.y<0.0) ? -1.0 : 1.0;\r\n return s*sqrt( min(dot2(ca),dot2(cb)) );\r\n }\r\n\r\n pub fn solidAngle( samplePosition: float3, solidCenter: float3, size: float2, radius: float) -> float\r\n {\r\n let p = samplePosition - solidCenter;\r\n let c = size;\r\n let ra = radius;\r\n // c is the sin/cos of the angle\r\n let q = float2( length(p.xz), p.y );\r\n let l = length(q) - ra;\r\n let m = length(q - c*clamp(dot(q,c),0.0,ra) );\r\n return max(l,m*sign(c.y*q.x-c.x*q.y));\r\n }\r\n\r\n pub fn cutSphere( samplePosition: float3, sphereCenter: float3, radius: float, height: float ) -> float\r\n {\r\n let p = samplePosition - sphereCenter;\r\n let h = height;\r\n let r = radius;\r\n\r\n // sampling independent computations (only depend on shape)\r\n let w = sqrt(r*r-h*h);\r\n\r\n // sampling dependant computations\r\n let q = float2( length(p.xz), p.y );\r\n let s = max( (h-r)*q.x*q.x+w*w*(h+r-2.0*q.y), h*q.x-w*q.y );\r\n return (s<0.0) ? length(q)-r :\r\n (q.x float\r\n {\r\n let p = samplePosition - sphereCenter;\r\n let r = radius;\r\n let h = height;\r\n let t = thickness;\r\n\r\n // sampling independent computations (only depend on shape)\r\n let w = sqrt(r*r-h*h);\r\n\r\n // sampling dependant computations\r\n let q = float2( length(p.xz), p.y );\r\n return ((h*q.x float\r\n {\r\n let p = samplePosition - coneCenter;\r\n let h = height;\r\n let r1 = coneRadius;\r\n let r2 = cornerRadius;\r\n\r\n // sampling independent computations (only depend on shape)\r\n let b = (r1-r2)/h;\r\n let a = sqrt(1.0-b*b);\r\n\r\n // sampling dependant computations\r\n let q = float2( length(p.xz), p.y );\r\n let k = dot(q,float2(-b,a));\r\n if( k<0.0 ) return length(q) - r1;\r\n if( k>a*h ) return length(q-float2(0.0,h)) - r2;\r\n return dot(q, float2(a,b) ) - r1;\r\n }\r\n\r\n pub fn ellipsoid( samplePosition: float3, center: float3, radius: float3 ) -> float\r\n { \r\n let p = samplePosition - center;\r\n let r = radius;\r\n let k0 = length(p/r);\r\n let k1 = length(p/(r*r));\r\n return k0*(k0-1.0)/k1;\r\n }\r\n\r\n pub fn rhombus( samplePosition: float3, rhombusCenter: float3, la: float, lb: float, height: float, ra: float) -> float\r\n {\r\n let p = samplePosition - rhombusCenter;\r\n let h = height;\r\n\r\n p = abs(p);\r\n let b = float2(la,lb);\r\n let f = clamp( (ndot(b,b-2.0*p.xz))/dot(b,b), -1.0, 1.0 );\r\n let q = float2(length(p.xz-0.5*b*float2(1.0-f,1.0+f))*sign(p.x*b.y+p.z*b.x-b.x*b.y)-ra, p.y-h);\r\n return min(max(q.x,q.y),0.0) + length(max(q,0.0));\r\n }\r\n\r\n pub fn octahedron( samplePosition: float3, center: float3, size: float) -> float\r\n {\r\n let p = samplePosition - center;\r\n let s = size;\r\n p = abs(p);\r\n let m = p.x+p.y+p.z-s;\r\n let q = 0.0.xyz;\r\n if( 3.0*p.x < m ) q = p.xyz;\r\n else if( 3.0*p.y < m ) q = p.yzx;\r\n else if( 3.0*p.z < m ) q = p.zxy;\r\n else return m*0.57735027;\r\n \r\n let k = clamp(0.5*(q.z-q.y+s),0.0,s); \r\n return length(float3(q.x,q.y-s+k,q.z-k)); \r\n }\r\n\r\n pub fn pyramid( samplePosition: float3, pyramidCenter: float3, height: float) -> float\r\n {\r\n let p1 = samplePosition - pyramidCenter;\r\n let h = height;\r\n\r\n let m2 = h*h + 0.25;\r\n \r\n let p2 = (abs(p1.x), p1.y, abs(p1.z));\r\n if (p1.z > p1.x) {\r\n p2 = (p2.z, p2.y, p2.x);\r\n }\r\n p2 = (p2.x - 0.5, p2.y, p2.z - 0.5);\r\n let p = p2;\r\n\r\n let q = float3( p.z, h*p.y - 0.5*p.x, h*p.x + 0.5*p.y);\r\n \r\n let s = max(-q.x,0.0);\r\n let t = clamp( (q.y-0.5*p.z)/(m2+0.25), 0.0, 1.0 );\r\n \r\n let a = m2*(q.x+s)*(q.x+s) + q.y*q.y;\r\n let b = m2*(q.x+0.5*t)*(q.x+0.5*t) + (q.y-m2*t)*(q.y-m2*t);\r\n \r\n let d2 = min(q.y,-q.x*m2-q.y*0.5) > 0.0 ? 0.0 : min(a,b);\r\n \r\n return sqrt( (d2+q.z*q.z)/m2 ) * sign(max(q.z,-p.y));\r\n }\r\n\r\n pub fn udTriangle( samplePosition: float3, a: float3, b: float3, c: float3 ) -> float\r\n {\r\n let p = samplePosition;\r\n let ba = b - a;\r\n let pa = p - a;\r\n let cb = c - b;\r\n let pb = p - b;\r\n let ac = a - c;\r\n let pc = p - c;\r\n let nor = cross( ba, ac );\r\n\r\n return sqrt(\r\n (sign(dot(cross(ba,nor),pa)) +\r\n sign(dot(cross(cb,nor),pb)) +\r\n sign(dot(cross(ac,nor),pc))<2.0)\r\n ?\r\n min( min(\r\n dot3(ba*clamp(dot(ba,pa)/dot3(ba),0.0,1.0) - pa),\r\n dot3(cb*clamp(dot(cb,pb)/dot3(cb),0.0,1.0) - pb) ),\r\n dot3(ac*clamp(dot(ac,pc)/dot3(ac),0.0,1.0) - pc) )\r\n :\r\n dot(nor,pa)*dot(nor,pa)/dot3(nor) );\r\n }\r\n\r\n pub fn udQuad( samplePosition: float3, a: float3, b: float3, c: float3, d: float3 ) -> float\r\n {\r\n let p = samplePosition;\r\n let ba = b - a; let pa = p - a;\r\n let cb = c - b; let pb = p - b;\r\n let dc = d - c; let pc = p - c;\r\n let ad = a - d; let pd = p - d;\r\n let nor = cross( ba, ad );\r\n\r\n return sqrt(\r\n (sign(dot(cross(ba,nor),pa)) +\r\n sign(dot(cross(cb,nor),pb)) +\r\n sign(dot(cross(dc,nor),pc)) +\r\n sign(dot(cross(ad,nor),pd))<3.0)\r\n ?\r\n min( min( min(\r\n dot3(ba*clamp(dot(ba,pa)/dot3(ba),0.0,1.0)-pa),\r\n dot3(cb*clamp(dot(cb,pb)/dot3(cb),0.0,1.0)-pb) ),\r\n dot3(dc*clamp(dot(dc,pc)/dot3(dc),0.0,1.0)-pc) ),\r\n dot3(ad*clamp(dot(ad,pd)/dot3(ad),0.0,1.0)-pd) )\r\n :\r\n dot(nor,pa)*dot(nor,pa)/dot3(nor) );\r\n }\r\n\r\n\r\n /**\r\n * Returns the intersection of two SDFs\r\n * = max(a, b)\r\n */\r\n pub fn intersect(a: float, b: float) -> float {\r\n return max(a, b);\r\n }\r\n\r\n /**\r\n * Returns the union of two SDFs\r\n * = min(a, b)\r\n */\r\n pub fn union(a: float, b: float) -> float {\r\n return min(a, b);\r\n }\r\n\r\n pub fn subtract(a: float, b: float) -> float {\r\n return max(-a, b);\r\n }\r\n\r\n pub fn smoothIntersect(a: float, b: float, k: float) -> float {\r\n let h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);\r\n return lerp(b, a, h) - k * h * (1.0 - h);\r\n }\r\n\r\n /**\r\n * Smoothly joins two SDFs using blending distance k\r\n */\r\n pub fn smoothUnion(a: float, b: float, k: float) -> float {\r\n let d1 = a;\r\n let d2 = b;\r\n let h = clamp( 0.5 + 0.5*(d2-d1)/k, 0.0, 1.0 );\r\n return lerp( d2, d1, h ) - k*h*(1.0-h);\r\n }\r\n\r\n pub fn smoothSubtract(a: float, b: float, k: float) -> float {\r\n let d1 = a;\r\n let d2 = b;\r\n let h = clamp( 0.5 - 0.5*(d2+d1)/k, 0.0, 1.0 );\r\n return lerp( d2, -d1, h ) + k*h*(1.0-h); \r\n }\r\n\r\n /**\r\n * Blends between two SDFs using interpolation\r\n */\r\n pub fn blend(a: float, b: float, t: float) -> float {\r\n return t * a + (1 - t) * b;\r\n }\r\n\r\n pub fn round(a: float, r: float) -> float {\r\n return a - r;\r\n }\r\n\r\n /**\r\n * Carve out the interior of an SDF\r\n */\r\n pub fn onion(a: float, thickness: float) -> float {\r\n return abs(a) - thickness;\r\n }\r\n\r\n\r\n pub fn grad(p:float3, sampler: (pos: float3) -> float) {\r\n const DELTA = 0.0001;\r\n return float3(sampler(p + float3(DELTA, 0.0, 0.0)) - sampler(p - float3(DELTA, 0.0, 0.0)),\r\n sampler(p + float3(0.0, DELTA, 0.0)) - sampler(p - float3(0.0, DELTA, 0.0)),\r\n sampler(p + float3(0.0, 0.0, DELTA)) - sampler(p - float3(0.0, 0.0, DELTA))) / (2.0 * DELTA);\r\n }\r\n\r\n /**\r\n * Poorly returns the closest point on the surface of an SDF\r\n * This is an inaccurate method\r\n */\r\n pub fn closest(position: float3, sampler: (pos: float3) -> float) -> float3 {\r\n let sep = 0.0001;\r\n let zero = min(env.frame, 0);\r\n let closest = position;\r\n let initialDist = sampler(position);\r\n let seed = 0;\r\n for (let j: int = 0; j < 200; j++) {\r\n let n = 0.0.xyz;\r\n let distSum = 0.0;\r\n for (let i: int = zero; i < 4; i++) {\r\n let e = 0.5773*(2.0*float3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0);\r\n let d = sampler(closest+e*sep);\r\n distSum += d;\r\n n += e*d;\r\n }\r\n closest = normalize(n) * distSum * -1 / 4.0 + closest;\r\n if (distSum < 0.0001) {\r\n break;\r\n }\r\n }\r\n\r\n return closest;\r\n }\r\n\r\n pub fn normal(position: float3, sampler: (pos: float3) -> float) -> float3 {\r\n const h = 0.1;\r\n let zero = min(env.frame, 0);\r\n let n = 0.0.xyz;\r\n let distSum = 0.0;\r\n \r\n for (let i: int = zero; i < 4; i++) {\r\n let e = 0.5773*(2.0*float3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0);\r\n let d = sampler(position+e*h);\r\n distSum += d;\r\n n += e*d;\r\n }\r\n return normalize(n);\r\n }\r\n\r\n pub fn vizRings(d: float) -> float4 {\r\n if (false) {\r\n let color = 1.0 - sign(d) * float3(0.1, 0.4, 0.7);\r\n color *= 1.0 - exp(-4.0 * abs(d));\r\n color *= 0.8 + 0.2 * cos(140.0 * d);\r\n color = lerp(color, 1.0.xyz, 1.0 - smoothstep(0.0, 0.015, abs(d)));\r\n return (color, 1.0);\r\n }else{\r\n\r\n let size = 2;\r\n let fadeDist = 100;\r\n let v = 1-clamp(d/ fadeDist, 0, 1);\r\n let color = (0.4 * v, 0.6* v, 1, 1);\r\n let s = sin(d / size);\r\n if (abs(d) < 1) {\r\n return float4(1.xyzw);\r\n }else{\r\n return d > 0 ? color * ceil(1-s) : color * ceil(s);\r\n }\r\n }\r\n }\r\n\r\n pub fn march(position: float3, direction: float3, sampler: (pos: float3) -> float) -> float {\r\n let maxDist = 100000.0;\r\n let minDist = 1.0;\r\n let dist = minDist;\r\n\r\n for (let i = 0; i < 256 && dist < maxDist; i++) {\r\n let samp = sampler(position + direction * dist);\r\n dist += samp;\r\n if (abs(samp) < (0.00005 * dist)) {\r\n break;\r\n }\r\n }\r\n if (dist > maxDist) {\r\n dist = -1.0;\r\n }\r\n return dist;\r\n }\r\n\r\n /**\r\n * See: https://iquilezles.org/articles/distfunctions/\r\n * Infinitely repeats an SDF with space in between. This returns an updated position\r\n *\r\n * Example:\r\n * ```shadeup\r\n * sdf::sphere(sdf::repeat(p, 100.xyz), 0.xyz, 50.0);\r\n * ```\r\n */\r\n pub fn repeat(position: float3, space: float3) -> float3 {\r\n let p = position;\r\n let s = space;\r\n return p - s*round(p/s);\r\n }\r\n\r\n /**\r\n * See: https://iquilezles.org/articles/distfunctions/\r\n * Repeats an SDF with space in between upto the limit. This returns an updated position\r\n *\r\n * Example:\r\n * ```shadeup\r\n * sdf::sphere(sdf::repeatLimited(p, 100, 10.xyz), 0.xyz, 50.0);\r\n * ```\r\n */\r\n pub fn repeatLimited(position: float3, space: float, limit: float3) -> float3 {\r\n let p = position;\r\n let s = space;\r\n return p - s*clamp(round(p/s),-limit,limit);\r\n }\r\n \r\n}"; const files = { shadeup: { mesh, textures, common, sdf, geo }, ts: { std, ui, native, paint, buffer, texture, drawIndexed, drawAttributes, drawCount, physics, context } }; async function makeSimpleShadeupEnvironment(esnext = false, declaration = false) { let env2 = new ShadeupEnvironment({ esnext, declaration }); env2.emitLogs = false; await env2.init(); await env2.writeFile( "/file.ts", ` ` ); let writes = []; performance.now(); for (let [path, contents] of Object.entries(files.ts)) { let p = "/_std/" + path + ".ts"; if (path == "std") p = "/std.ts"; writes.push(env2.writeFileTypescript(p, contents)); } for (let [path, contents] of Object.entries(files.shadeup)) { let p = "/_std/" + path + ".ts"; writes.push(env2.writeFile(p, contents, true)); } return env2; } exports2.makeSimpleShadeupEnvironment = makeSimpleShadeupEnvironment; Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" }); }); ================================================ FILE: extension/vscode/shadeup/server/package.json ================================================ { "name": "lsp-sample-server", "description": "Example implementation of a language server in node.", "version": "1.0.0", "author": "Microsoft Corporation", "license": "MIT", "engines": { "node": "*" }, "repository": { "type": "git", "url": "https://github.com/Microsoft/vscode-extension-samples" }, "dependencies": { "@typescript/vfs": "^1.5.0", "typescript": "^5.3.3", "uglify-js": "^3.17.4", "vscode-languageserver": "^9.0.1", "vscode-languageserver-textdocument": "^1.0.11", "web-tree-sitter": "^0.20.8" }, "scripts": {} } ================================================ FILE: extension/vscode/shadeup/server/src/server.ts ================================================ /* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ import { createConnection, TextDocuments, Diagnostic, DiagnosticSeverity, ProposedFeatures, InitializeParams, DidChangeConfigurationNotification, CompletionItem, CompletionItemKind, TextDocumentPositionParams, TextDocumentSyncKind, InitializeResult, SemanticTokensBuilder, } from "vscode-languageserver/node"; import { makeLSPCompiler } from "../compiler-dist/compiler.js"; import * as ts from "typescript"; import { TextDocument } from "vscode-languageserver-textdocument"; // Create a connection for the server, using Node's IPC as a transport. // Also include all preview / proposed LSP features. const connection = createConnection(ProposedFeatures.all); // Create a simple text document manager. const documents: TextDocuments = new TextDocuments(TextDocument); let env: any = undefined; let hasConfigurationCapability = false; let hasWorkspaceFolderCapability = false; let hasDiagnosticRelatedInformationCapability = false; export type ShadeupFileOutput = { path: string; contents: string; mapping: IndexMapping; }; export type ShadeupRenderedFile = { path: string; contents: string; }; export type ShadeupDiagnostic = { path: string; level: "info" | "warning" | "error"; fullMessage: string; startLine: number; startColumn: number; endLine: number; endColumn: number; message: string; }; export function indexToRowColumn(str: string, index: number) { let row = 0; let column = 0; for (let i = 0; i < index; i++) { if (str[i] === "\n") { row++; column = 0; } else { column++; } } return { row, column }; } export function rowColumnToIndex(str: string, row: number, column: number) { let index = 0; let currentRow = 0; let currentColumn = 0; while (currentRow < row || currentColumn < column) { if (str[index] === "\n") { currentRow++; currentColumn = 0; } else { currentColumn++; } index++; } return index; } export type IndexMapping = [number, number, number, number][]; export type SourceString = { str: string; indexMapping: IndexMapping; }; export type ShadeupGenericDiagnostic = { message: string; startIndex: number; endIndex: number; }; // Finds the smallest range in the index mapping that contains the given range export function lookupIndexMappingRange( indexMapping: IndexMapping, start: number, end: number ) { let minStart = Infinity; let maxEnd = -Infinity; let size = 0; for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) { if (start >= newStart && end <= newEnd) { if (oldEnd - oldStart < size || size === 0) { minStart = oldStart; maxEnd = oldEnd; size = oldEnd - oldStart; } } } return { start: minStart, end: maxEnd }; } function findFile(path: string) { return env.files.find((f: any) => f.path === path); } function tsDiagnosticToShadeupDiagnostic(diag: { error: ts.Diagnostic; file: string; message: string; }): Diagnostic | null { let path = diag.error.file?.fileName ?? ""; let file = findFile(path); if (!file) return null; let mapping = file.mapping; if (!mapping) return null; let to = lookupIndexMappingRange( mapping, diag.error.start ?? 0, (diag.error.start ?? 0) + (diag.error.length ?? 0) ); let fileSource = file.content; if (fileSource) { let start = indexToRowColumn(fileSource, to.start); let end = indexToRowColumn(fileSource, to.end); return { severity: DiagnosticSeverity.Error, /** * A human-readable string describing the source of this * diagnostic, e.g. 'typescript' or 'super lint'. It usually * appears in the user interface. */ source: "shadeup", /** * The diagnostic's message. It usually appears in the user interface */ message: ts.flattenDiagnosticMessageText(diag.error.messageText, "\n"), range: { start: { character: start.column, line: start.row, }, end: { character: end.column, line: end.row, }, }, }; } return null; } function genericDiagnosticToShadeupDiagnostic( path: string, diag: ShadeupGenericDiagnostic ): Diagnostic | null { let file = findFile(path); if (!file) return null; let mapping = file.mapping; if (!mapping) return null; let fileSource = file.content; if (fileSource) { let start = indexToRowColumn(fileSource, diag.startIndex); let end = indexToRowColumn(fileSource, diag.endIndex); return { source: "shadeup", message: diag.message ?? "", range: { start: { character: start.column, line: start.row, }, end: { character: end.column, line: end.row, }, }, }; } return null; } function delay(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } let dirtyFiles = new Set(); const TOKEN_TYPES = [ "class", "comment", "constant", "function", "keyword", "number", "operator", "parameter", "property", "string", "type", "variable", ]; const TOKEN_MAP = { class: "class", comment: "comment", constant: "constant", function: "function", functionElement: "function", keyword: "keyword", let: "variable", alias: "keyword", const: "variable", constElement: "variable", letElement: "variable", number: "number", operator: "operator", parameter: "parameter", property: "property", string: "string", type: "type", typeElement: "type", variable: "variable", var: "variable", "local var": "variable", variableElement: "variable", localVariableElement: "variable", }; connection.onInitialize(async (params: InitializeParams) => { const capabilities = params.capabilities; env = await makeLSPCompiler(); connection.console.log("Initialized"); // Does the client support the `workspace/configuration` request? // If not, we fall back using global settings. hasConfigurationCapability = !!( capabilities.workspace && !!capabilities.workspace.configuration ); hasWorkspaceFolderCapability = !!( capabilities.workspace && !!capabilities.workspace.workspaceFolders ); hasDiagnosticRelatedInformationCapability = !!( capabilities.textDocument && capabilities.textDocument.publishDiagnostics && capabilities.textDocument.publishDiagnostics.relatedInformation ); const result: InitializeResult = { capabilities: { textDocumentSync: TextDocumentSyncKind.Incremental, // Tell the client that this server supports code completion. completionProvider: { resolveProvider: true, }, hoverProvider: true, semanticTokensProvider: { legend: { tokenTypes: TOKEN_TYPES, tokenModifiers: ["declaration", "definition", "readonly"], }, range: false, full: true, }, }, }; if (hasWorkspaceFolderCapability) { result.capabilities.workspace = { workspaceFolders: { supported: true, }, }; } return result; }); connection.onInitialized(() => { if (hasConfigurationCapability) { // Register for all configuration changes. connection.client.register( DidChangeConfigurationNotification.type, undefined ); } if (hasWorkspaceFolderCapability) { connection.workspace.onDidChangeWorkspaceFolders((_event) => { connection.console.log("Workspace folder change event received."); }); } }); connection.onDidChangeConfiguration((change) => {}); // Only keep settings for open documents documents.onDidClose((e) => {}); function cleanPath(path: string) { path = path.replace("file://", ""); path = path.replace("%3A", ":").replace(/\\/g, "/"); // path = path.split("/").slice(-1)[0]; path = path.replace(".shadeup", ".ts"); return path; } const tokenBuilders: Map = new Map(); documents.onDidClose((event) => { tokenBuilders.delete(event.document.uri); }); function getTokenBuilder(document: TextDocument): SemanticTokensBuilder { let result = tokenBuilders.get(document.uri); if (result !== undefined) { return result; } result = new SemanticTokensBuilder(); tokenBuilders.set(document.uri, result); return result; } let docChangePromise: Map> = new Map(); connection.languages.semanticTokens.on(async (params) => { let path = cleanPath(params.textDocument.uri); let docChange = docChangePromise.get(params.textDocument.uri) ?? Promise.resolve(); await Promise.race([docChange, delay(400)]); const document = documents.get(params.textDocument.uri); let file = findFile(path); if (!file) return { data: [] }; if (document === undefined) { return { data: [] }; } // const builder = getTokenBuilder(document); let builder = new SemanticTokensBuilder(); let toks = env.classifications(path); toks.ranges.sort((a: any, b: any) => a[0] - b[0]); for (let tok of toks.ranges) { let s = tok[0]; let e = tok[1]; let type = (TOKEN_MAP as any)[tok[2]]; let fileSource = file.content; // let start = indexToRowColumn(fileSource, s); // let end = indexToRowColumn(fileSource, e); let start = document.positionAt(s); let length = e - s; builder.push( start.line, start.character, length, TOKEN_TYPES.indexOf(type), 0 ); } return builder.build(); }); // The content of a text document has changed. This event is emitted // when the text document first opened or when its content has changed. let currentContentChange: NodeJS.Timeout | null = null; documents.onDidChangeContent((change) => { let outResolve = () => {}; let resolveable = new Promise((resolve) => { outResolve = resolve; }); docChangePromise.set(change.document.uri, resolveable); if (currentContentChange) clearTimeout(currentContentChange); currentContentChange = setTimeout(async () => { const contents = change.document.getText(); let path = cleanPath(change.document.uri); const ignoreErrors = false; await env.writeFile(path, contents, ignoreErrors); // let filesToGenerate = [e.data.message.path]; // for (let dirty of dirtyFiles) { // if (dirty !== e.data.message.path) filesToGenerate.push(dirty); // } let output: { path: string; contents: string; }[] = []; // if (e.data.message.emit) output = await env.regenerate(filesToGenerate); //await env.regenerate(); let errors: { error: ts.Diagnostic; file: string; message: string; }[] = []; if (!ignoreErrors) { errors = await env.errors([path]); } outResolve(); let file = findFile(path); let diags: Diagnostic[] = []; for (let parseError of file?.parseDiagnostics ?? []) { if (parseError.path !== path) continue; let diag = genericDiagnosticToShadeupDiagnostic(path, parseError); if (diag) diags.push(diag); } for (let error of errors) { if (error.file !== path) continue; let diag = tsDiagnosticToShadeupDiagnostic(error); if (diag) diags.push(diag); } // let output: ShadeupRenderedFile[] = []; if (errors.length == 0) { dirtyFiles.clear(); // console.log('Output', e.data.message.path, output); } else { dirtyFiles.add(path); // console.log('Errors', e.data.message.path, errors); } // connection.console.log(JSON.stringify(env.classifications(path))); const diagnostics: Diagnostic[] = diags.map((d) => d); // Send the computed diagnostics to VSCode. connection.sendDiagnostics({ uri: change.document.uri, diagnostics }); // console.log('Sending writefile nonce', e.data.nonce); // postMessage({ // nonce: e.data.nonce, // classifications: { // path: e.data.message.path, // encoded: env.classifications(e.data.message.path) // }, // files: env.files.map((f) => ({ // path: f.path, // contents: f.content, // mapping: f.mapping // })), // diagnostics: diags, // output // }); }, 400); }); connection.onDidChangeWatchedFiles(async (_change) => {}); function displayPartsToString(parts?: ts.SymbolDisplayPart[]): string { if (parts) { let content = ""; for (let p of parts) { content += p.text; } return content .replace(/__\./g, "") .replace(/\(property\)/g, "") .replace(/\(method\)/g, ""); } else { return ""; } } connection.onCompletion( async ( _textDocumentPosition: TextDocumentPositionParams ): Promise => { const doc = documents.get(_textDocumentPosition.textDocument.uri); if (!doc) return []; let offset = doc.offsetAt(_textDocumentPosition.position); const path = cleanPath(_textDocumentPosition.textDocument.uri); let start = Date.now(); let completions = await env.completions(path, offset); let items: CompletionItem[] = []; for (let completion of completions) { let c = completion.completion; let kind = ( { [ts.ScriptElementKind.functionElement]: CompletionItemKind.Function, [ts.ScriptElementKind.memberVariableElement]: CompletionItemKind.Field, [ts.ScriptElementKind.memberGetAccessorElement]: CompletionItemKind.Field, [ts.ScriptElementKind.memberSetAccessorElement]: CompletionItemKind.Field, [ts.ScriptElementKind.variableElement]: CompletionItemKind.Variable, [ts.ScriptElementKind.constElement]: CompletionItemKind.Variable, [ts.ScriptElementKind.localVariableElement]: CompletionItemKind.Variable, [ts.ScriptElementKind.classElement]: CompletionItemKind.Class, [ts.ScriptElementKind.interfaceElement]: CompletionItemKind.Interface, [ts.ScriptElementKind.typeElement]: CompletionItemKind.Class, [ts.ScriptElementKind.enumElement]: CompletionItemKind.Enum, [ts.ScriptElementKind.moduleElement]: CompletionItemKind.Module, [ts.ScriptElementKind.keyword]: CompletionItemKind.Keyword, [ts.ScriptElementKind.scriptElement]: CompletionItemKind.File, [ts.ScriptElementKind.alias]: CompletionItemKind.File, [ts.ScriptElementKind.letElement]: CompletionItemKind.Variable, [ts.ScriptElementKind.directory]: CompletionItemKind.Folder, [ts.ScriptElementKind.string]: CompletionItemKind.Text, } as any )[c.kind.toString()] ?? CompletionItemKind.Property; let parts = displayPartsToString(completion.details?.displayParts); if (c.kind.toString() == ts.ScriptElementKind.alias) { if (parts.startsWith("(alias) class")) { kind = CompletionItemKind.Class; } else if (parts.startsWith("(alias) enum")) { kind = CompletionItemKind.Enum; } else if (parts.startsWith("(alias) interface")) { kind = CompletionItemKind.Interface; } else if (parts.startsWith("(alias) type")) { kind = CompletionItemKind.Class; } else if (parts.startsWith("(alias) namespace")) { kind = CompletionItemKind.Module; } else if (parts.startsWith("(alias) function")) { kind = CompletionItemKind.Function; } else if ( parts.startsWith("(alias) var") || parts.startsWith("(alias) let") ) { kind = CompletionItemKind.Variable; } else if (parts.startsWith("(alias) const")) { kind = CompletionItemKind.Variable; } } if (c.kind.toString() == ts.ScriptElementKind.string) { c.name = `"${c.name.replace(/"/g, "")}"`; } let documentation = completion.details?.documentation?.map((p: any) => ({ value: p.text, })) ?? []; if (!c.name.startsWith("__")) items.push({ label: c.name, sortText: c.sortText, kind, insertText: c.name, detail: parts, documentation: documentation[0] ?? undefined, // range: (completion as any).range, }); } return items; } ); connection.onHover(async (params) => { const doc = documents.get(params.textDocument.uri); if (!doc) return null; let offset = doc.offsetAt(params.position); const path = cleanPath(params.textDocument.uri); let hover = await env.hover(path, offset); if (hover) { return { contents: "```ts\n" + hover.displayParts.map((p: any) => p.text).join("") + "\n```", range: { start: { line: hover.range.startLineNumber, character: hover.range.startColumn, }, end: { line: hover.range.endLineNumber, character: hover.range.endColumn, }, }, }; } return null; }); // This handler resolves additional information for the item selected in // the completion list. connection.onCompletionResolve((item: CompletionItem): CompletionItem => { if (item.data === 1) { item.detail = "TypeScript details"; item.documentation = "TypeScript documentation"; } else if (item.data === 2) { item.detail = "JavaScript details"; item.documentation = "JavaScript documentation"; } return item; }); // Make the text document manager listen on the connection // for open, change and close text document events documents.listen(connection); // Listen on the connection connection.listen(); ================================================ FILE: extension/vscode/shadeup/server/tsconfig.json ================================================ { "compilerOptions": { "target": "es2020", "lib": ["es2020"], "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "strict": true, "outDir": "out", "rootDir": "src" }, "include": ["src"], "exclude": ["node_modules", ".vscode-test"] } ================================================ FILE: extension/vscode/shadeup/shadeup.tmlanguage.json ================================================ { "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", "name": "Shadeup", "scopeName": "source.shadeup", "fileTypes": [ ".shadeup" ], "patterns": [ { "include": "#expression" }, { "include": "#comments" } ], "repository": { "array-literal": { "name": "meta.array-literal.shadeup", "begin": "\\[(?!(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*\\bfor\\b)", "end": "]", "patterns": [ { "include": "#expression" }, { "include": "#comments" } ] }, "block-comment": { "name": "comment.block.shadeup", "begin": "/\\*", "end": "\\*/" }, "comments": { "patterns": [ { "include": "#line-comment" }, { "include": "#block-comment" } ] }, "decorator": { "name": "meta.decorator.shadeup", "begin": "@(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*(?=\\b[_$[:alpha:]][_$[:alnum:]]*\\b)", "end": "", "patterns": [ { "include": "#expression" }, { "include": "#comments" } ] }, "directive": { "name": "meta.directive.shadeup", "begin": "#\\b[_a-zA-Z-0-9]+\\b", "end": "$", "patterns": [ { "include": "#directive-variable" }, { "include": "#comments" } ] }, "directive-variable": { "name": "keyword.control.declaration.shadeup", "match": "\\b[_a-zA-Z-0-9]+\\b" }, "escape-character": { "name": "constant.character.escape.shadeup", "match": "\\\\(u{[0-9A-Fa-f]+}|n|r|t|\\\\|'|\\${)" }, "expression": { "patterns": [ { "include": "#string-literal-double" }, { "include": "#string-literal" }, { "include": "#string-verbatim" }, { "include": "#numeric-literal" }, { "include": "#named-literal" }, { "include": "#object-literal" }, { "include": "#array-literal" }, { "include": "#keyword" }, { "include": "#storage-func" }, { "include": "#variable" }, { "include": "#storage-modifier" }, { "include": "#identifier" }, { "include": "#function-call" }, { "include": "#decorator" }, { "include": "#lambda-start" }, { "include": "#directive" } ] }, "function-call": { "name": "meta.function-call.shadeup", "begin": "(\\b[_$[:alpha:]][_$[:alnum:]]*\\b)(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*\\(", "beginCaptures": { "1": { "name": "entity.name.function.shadeup" } }, "end": "\\)", "patterns": [ { "include": "#expression" }, { "include": "#comments" } ] }, "identifier": { "name": "variable.other.readwrite.shadeup", "match": "\\b[_$[:alpha:]][_$[:alnum:]]*\\b(?!(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*\\()" }, "keyword": { "name": "keyword.control.declaration.shadeup", "match": "\\b(metadata|targetScope|resource|module|param|shader|workgroup|output|for|in|if|while|break|continue|else|return|existing|import|as|type|with|using|assert|provider)\\b" }, "lambda-start": { "name": "meta.lambda-start.shadeup", "begin": "(\\((?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*\\b[_$[:alpha:]][_$[:alnum:]]*\\b(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*(,(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*\\b[_$[:alpha:]][_$[:alnum:]]*\\b(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*)*\\)|\\((?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*\\)|(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*\\b[_$[:alpha:]][_$[:alnum:]]*\\b(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*)(?=(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*=>)", "beginCaptures": { "1": { "name": "meta.undefined.shadeup", "patterns": [ { "include": "#identifier" }, { "include": "#comments" } ] } }, "end": "(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*=>" }, "line-comment": { "name": "comment.line.double-slash.shadeup", "match": "//.*(?=$)" }, "named-literal": { "name": "constant.language.shadeup", "match": "\\b(true|false|null)\\b" }, "numeric-literal": { "name": "constant.numeric.shadeup", "match": "[0-9]+" }, "object-literal": { "name": "meta.object-literal.shadeup", "begin": "{", "end": "}", "patterns": [ { "include": "#object-property-key" }, { "include": "#expression" }, { "include": "#comments" } ] }, "object-property-key": { "name": "variable.other.property.shadeup", "match": "\\b[_$[:alpha:]][_$[:alnum:]]*\\b(?=(?:[ \\t\\r\\n]|\\/\\*(?:\\*(?!\\/)|[^*])*\\*\\/)*:)" }, "storage-func": { "name": "storage.type.function.shadeup", "match": "\\b(fn|struct|trait|impl)\\b" }, "storage-modifier": { "name": "storage.modifier.shadeup", "match": "\\b(pub)\\b" }, "string-literal": { "name": "string.quoted.single.shadeup", "begin": "'(?!'')", "end": "'", "patterns": [ { "include": "#escape-character" }, { "include": "#string-literal-subst" } ] }, "string-literal-double": { "name": "string.quoted.double.shadeup", "begin": "\"(?!\"\")", "end": "\"", "patterns": [ { "include": "#escape-character" }, { "include": "#string-literal-subst" } ] }, "string-literal-subst": { "name": "meta.string-literal-subst.shadeup", "begin": "(?Shadeup logo

Shadeup Lang

Here lies a partial mirror of the shadeup language tools. > [!NOTE] > Running/building this standalone is not possible at the moment, but this is in the works. ================================================ FILE: lang/shadeup/alert.ts ================================================ export type ShadeupAlert = { level: 'info' | 'warning' | 'error'; message: string; location: Number; line?: Number; column?: Number; }; ================================================ FILE: lang/shadeup/compiler/assets.json ================================================ [ ["heightmaps/crater-lake-color", "image"], ["heightmaps/crater-lake", "image"], ["heightmaps/grand-canyon", "image"], ["heightmaps/rugged", "image"], ["models/bunny", "model"], ["models/cornell-box", "model"], ["models/dragon", "model"], ["models/erato", "model"], ["models/head", "model"], ["models/sponza", "model"], ["models/suzanne", "model"], ["models/teapot", "model"], ["textures/bark/arm", "image"], ["textures/bark/color", "image"], ["textures/bark/displacement", "image"], ["textures/bark/normal", "image"], ["textures/beach/arm", "image"], ["textures/beach/color", "image"], ["textures/beach/displacement", "image"], ["textures/beach/normal", "image"], ["textures/brick/arm", "image"], ["textures/brick/color", "image"], ["textures/brick/displacement", "image"], ["textures/brick/normal", "image"], ["textures/pebbles/arm", "image"], ["textures/pebbles/color", "image"], ["textures/pebbles/displacement", "image"], ["textures/pebbles/normal", "image"], ["textures/stone-path/arm", "image"], ["textures/stone-path/color", "image"], ["textures/stone-path/displacement", "image"], ["textures/stone-path/normal", "image"], ["textures/wood/arm", "image"], ["textures/wood/color", "image"], ["textures/wood/normal", "image"] ] ================================================ FILE: lang/shadeup/compiler/assets.ts ================================================ import type { AssetFileType } from '../../components/common/Asset'; import builtInAssets from './assets.json'; export function buildAssetsFile(content: string) { let out = ` import { float4, float3, float, float2, bool, int, int2, int3, int4, uint, uint2, uint3, uint4, uint8 } from '/std_math'; import { Mesh, Model } from '/_std/mesh'; import { texture2d } from '/_std/texture'; declare global {\n`; let typeMapping: { [key in AssetFileType]: string } = { image: 'texture2d', audio: 'unknown', video: 'unknown', binary: 'buffer', text: 'string', model: 'Model' }; try { let parsed = JSON.parse(content); parsed.forEach((asset: { name: string; type: AssetFileType; previewId: string }) => { let docCom = `![thumb](https://assets.shadeup.dev/`; out += ` /** * ${docCom}${asset.previewId}) */ function load(asset: '${asset.name}'): ${typeMapping[asset.type]}; `; }); } catch (e) { console.error(e); } for (let asset of builtInAssets) { out += ` /** * Built-in asset: ${asset[0]} */ function load(asset: '${asset[0]}'): ${typeMapping[asset[1] as AssetFileType]}; `; } return out + `}`; } export const defaultAssets = builtInAssets; ================================================ FILE: lang/shadeup/compiler/common.ts ================================================ import type ts from 'typescript'; import type { ClassificationRanges } from '../../../../shadeup-frontend/lib/environment/ShadeupEnvironment'; import type { IndexMapping } from '../../../../shadeup-frontend/lib/generator/root'; export type ShadeupFileOutput = { path: string; contents: string; mapping: IndexMapping; }; export type ShadeupRenderedFile = { path: string; contents: string; }; export type ShadeupDiagnostic = { path: string; level: 'info' | 'warning' | 'error'; fullMessage: string; startLine: number; startColumn: number; endLine: number; endColumn: number; message: string; }; export type MessageWorkerToMain = { nonce: number; files: ShadeupFileOutput[]; diagnostics: ShadeupDiagnostic[]; classifications?: { path: string; encoded: ClassificationRanges; }; completions: { completion: ts.CompletionEntry; details: ts.CompletionEntryDetails | undefined; }[]; hover: | (ts.QuickInfo & { range: { startLineNumber: number; endLineNumber: number; startColumn: number; endColumn: number; }; }) | null; output: ShadeupRenderedFile[]; ready: boolean; }; type WriteFileMessage = { path: string; contents: string; emit: boolean; ignoreErrors?: boolean; }; type GetCompletionsMessage = { path: string; position: number; }; type GetHoverMessage = { path: string; position: number; }; export type MessageMainToWorker = { nonce?: number; } & ( | { key: 'writeFile'; message: WriteFileMessage; } | { key: 'writeFileTypescript'; message: WriteFileMessage; } | { key: 'getCompletions'; message: GetCompletionsMessage; } | { key: 'getHover'; message: GetHoverMessage; } | { key: 'init'; } | { key: 'build'; } | { key: 'reset' } | { key: 'assets'; message: [string, [string, string]][] } ); ================================================ FILE: lang/shadeup/compiler/generateDocs.ts ================================================ import { ShadeupEnvironment, type ShadeupGenericDiagnostic } from '../../../../shadeup-frontend/lib/environment/ShadeupEnvironment'; import type { MessageMainToWorker, MessageWorkerToMain, ShadeupDiagnostic, ShadeupRenderedFile } from './common'; import { lookupIndexMappingRange, reverseLookupIndexMapping } from '../../../../shadeup-frontend/lib/generator/root'; import { indexToRowColumn } from '../../../../shadeup-frontend/lib/environment/ShadeupEnvironment'; import ts from 'typescript'; import files from '../library/files'; export type DocFunction = { name: string; overloads: { description: string; parameters: { name: string; description: string; type: string; }[]; typeParameters: string[]; returnType: string; }[]; }; export type DocProp = { name: string; description: string; type: string; default?: string; }; export type DocModule = { name: string; description: string; functions: DocFunction[]; }; export type DocClass = { name: string; description: string; functions: DocFunction[]; props: DocProp[]; }; export type Doc = { modules: DocModule[]; classes: DocClass[]; functions: DocFunction[]; constants: DocProp[]; }; export async function generateDocs() { let env = new ShadeupEnvironment(); env.emitLogs = false; await env.init(); await env.writeFile( '/file.ts', ` ` ); let writes: Promise[] = []; let initFiles = ['/file.ts']; let start = performance.now(); for (let [path, contents] of Object.entries(files.ts)) { let p = '/_std/' + path + '.ts'; if (path == 'std') p = '/std.ts'; // So we can import it via import ui from "std"; writes.push(env.writeFileTypescript(p, contents)); initFiles.push(p); } for (let [path, contents] of Object.entries(files.shadeup)) { let p = '/_std/' + path + '.ts'; writes.push(env.writeFile(p, contents, true)); initFiles.push(p); } await Promise.all(writes); let docs: Doc = { modules: [], functions: [], classes: [], constants: [ { name: 'env', description: 'Global env context struct. This updates every frame and includes input data, time data, and more.', type: 'FrameContext' } ] }; const IGNORE_LIST = [ 'swizzle', 'add', 'sub', 'div', 'shader_start_shd_', 'shadeupMakeTextureFromUrl', 'rshift', 'lshift', 'refract2', 'refract3', 'refract4', 'RegExp', 'RangeError', 'ReferenceError', 'Number', 'neq', 'Object', 'or', 'and', 'gte', 'lte', 'negate', 'mul', 'mod289_1', 'mod289_2', 'mod289_3', 'mod289_4', 'matrixMul2x2float2', 'matrixMul3x3float3', 'matrixMul4x4float4', 'matrixMulfloat22x2', 'matrixMulfloat33x3', 'matrixMulfloat44x4', 'matrixTransposefloat2x2', 'matrixTransposefloat3x3', 'matrixTransposefloat4x4', 'matrixMul', 'matrixInversefloat4x4', 'matrixInversefloat3x3', 'matrixInversefloat2x2', 'makeVector', 'String', 'SyntaxError', 'TypeError', 'testDocComment', 'bitand', 'bitnot', 'bitor', 'bitxor', 'Boolean', 'cCall', 'componentOpSingularFloat', 'componentOpSingular', 'componentOpMatch', 'componentOp', 'componentMathSingular', 'componentMath', 'componentReduce', 'drawAlt2', 'drawFullscreen', 'cross2', 'cross3', 'dot2', 'dot3', 'dot4', 'Array', 'lt', 'gt', 'applyMatrix3x3Methods', 'applyMatrix2x2Methods', 'applyMatrix4x4Methods', 'makeShader', 'lerp1', 'lerp2', 'lerp3' ]; let checker: ts.TypeChecker = env.tsEnv?.env.languageService .getProgram() ?.getTypeChecker() as any; let allFiles = env.tsEnv?.fsMap.keys(); if (allFiles && checker) { for (let f of allFiles) { let ff = env.tsEnv?.env.getSourceFile(f); if (!ff) continue; function addFunc(node: ts.Node, list: DocFunction[]): DocFunction | undefined { if ( ts.isFunctionDeclaration(node) || ts.isVariableStatement(node) || ts.isMethodDeclaration(node) ) { if (ts.isVariableStatement(node)) { node = node.declarationList.declarations[0]; } let signatures = checker.getSignaturesOfType( checker.getTypeAtLocation(node), ts.SignatureKind.Call ); if (IGNORE_LIST.includes(node.name?.getText())) return; let funcExists = list.find((f) => f.name === node.name?.getText()); if (!funcExists) { if (!node.name?.getText()) return; let funcDoc = { name: node.name?.getText() ?? '', overloads: signatures.map((sig) => { let sigSymbol = checker.getSymbolAtLocation(sig.declaration!); let params = sig.getParameters().map((p) => { let decl = p.getDeclarations()![0]; let symbol = checker.getSymbolAtLocation(decl); if (!symbol) { return { name: p.name, description: '', type: checker.typeToString(checker.getTypeOfSymbolAtLocation(p, decl)) }; } let type = checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol!, decl)); return { name: p.name, description: ts.displayPartsToString(p.getDocumentationComment(checker)), type }; }); let returnType = checker.typeToString(sig.getReturnType()); return { typeParameters: sig.typeParameters?.map((t) => checker.typeToString(t)) ?? [], description: ts.displayPartsToString(sig.getDocumentationComment(checker)), parameters: params, returnType }; }) } as DocFunction; if (funcDoc.overloads.length == 12) { let isMatch = true; for (let ov of funcDoc.overloads) { if (ov.parameters.length != 1) { isMatch = false; break; } if (ov.parameters[0].type != ov.returnType) { isMatch = false; break; } if ( ![ 'float', 'float2', 'float3', 'float4', 'int', 'int2', 'int3', 'int4', 'uint', 'uint2', 'uint3', 'uint4' ].includes(ov.parameters[0].type) ) { isMatch = false; break; } } if (isMatch) { funcDoc.overloads = [ { description: funcDoc.overloads[0].description, parameters: [ { name: 'a', type: 'vec | scalar', description: '' } ], typeParameters: funcDoc.overloads[0].typeParameters, returnType: 'vec | scalar' } ]; } } return funcDoc; } } } function recursive(node: ts.Node) { if (!isNodeExported(node)) return; if ( ts.isFunctionDeclaration(node) || ts.isVariableStatement(node) || ts.isMethodDeclaration(node) ) { if (ts.isVariableStatement(node)) { let decl = node.declarationList.declarations[0]; if (['PI', 'env'].includes(decl.name?.getText() ?? '')) { docs.constants.push({ name: decl.name?.getText() ?? '', description: ts.displayPartsToString( checker.getSymbolAtLocation(decl.name!)?.getDocumentationComment(checker) ), type: checker.typeToString( checker.getTypeOfSymbolAtLocation(checker.getSymbolAtLocation(decl.name!)!, decl) ) }); } } let f = addFunc(node, docs.functions); if (f && f.overloads.length > 0) docs.functions.push(f); } else if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { let name = node.name?.getText(); if (!name) return; if (['global', 'Intl'].includes(name)) return; let symbol = checker.getSymbolAtLocation(node.name!); if (!symbol) return; let isModule = true; if (symbol.members) { symbol.members.forEach((m) => { let decl = m.valueDeclaration; if (decl && ts.isPropertyDeclaration(decl)) { isModule = false; } }); } if (isModule) { let mod = docs.modules.find((m) => m.name === name); if (!mod) { let funcs: DocFunction[] = []; function visitModuleSub(n: ts.Node) { if ( ts.isFunctionDeclaration(n) || ts.isVariableStatement(n) || ts.isMethodDeclaration(n) ) { let f = addFunc(n, funcs); if (f) funcs.push(f); } else { n.forEachChild((n) => { visitModuleSub(n); }); } } node.forEachChild((n) => { visitModuleSub(n); }); mod = { name: name, description: ts.displayPartsToString(symbol.getDocumentationComment(checker)), functions: funcs }; docs.modules.push(mod); } node.forEachChild((node) => { recursive(node); }); } else { if (name == 'buffer_internal') name = 'buffer'; if (name == 'texture2d_internal_empty') name = 'texture2d'; if (name == 'texture3d_internal_empty') name = 'texture3d'; if (name == 'atomic_internal') name = 'atomic'; let mod = docs.classes.find((m) => m.name === name); if (!mod) { let funcs: DocFunction[] = []; let props: DocProp[] = []; function visitModuleSub(n: ts.Node) { if ( ts.isFunctionDeclaration(n) || ts.isVariableStatement(n) || ts.isMethodDeclaration(n) ) { let f = addFunc(n, funcs); if (f) funcs.push(f); } else if (ts.isPropertyDeclaration(n)) { let name = n.name.getText(); let symbol = checker.getSymbolAtLocation(n.name); if (!symbol) return; let type = checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol!, n)); props.push({ name, description: ts.displayPartsToString(symbol.getDocumentationComment(checker)), type, default: n.initializer ? n.initializer.getText() : undefined }); } else { n.forEachChild((n) => { visitModuleSub(n); }); } } node.forEachChild((n) => { visitModuleSub(n); }); mod = { name: name, description: ts.displayPartsToString(symbol.getDocumentationComment(checker)), functions: funcs, props: props }; docs.classes.push(mod); } node.forEachChild((node) => { recursive(node); }); } } else { node.forEachChild((node) => { recursive(node); }); } } ff.forEachChild((node) => { recursive(node); }); } } // env.emitLogs = true; console.log('Generated docs in ', performance.now() - start, 'ms'); console.log(docs); return docs; } function isNodeExported(node: ts.Node): boolean { return ( (ts.getCombinedModifierFlags(node as ts.Declaration) & ts.ModifierFlags.Export) !== 0 || (!!node.parent && node.parent.kind === ts.SyntaxKind.SourceFile) ); } ================================================ FILE: lang/shadeup/compiler/generateTsCache.ts ================================================ import { ShadeupEnvironment, type ShadeupGenericDiagnostic } from '../../../../shadeup-frontend/lib/environment/ShadeupEnvironment'; import type { MessageMainToWorker, MessageWorkerToMain, ShadeupDiagnostic, ShadeupRenderedFile } from './common'; import { lookupIndexMappingRange, reverseLookupIndexMapping } from '../../../../shadeup-frontend/lib/generator/root'; import { indexToRowColumn } from '../../../../shadeup-frontend/lib/environment/ShadeupEnvironment'; import ts from 'typescript'; import files from '../library/files'; export async function generateTsCache() { let env = new ShadeupEnvironment(); env.emitLogs = false; await env.init(); env.stdEmitCache.clear(); await env.writeFile( '/file.ts', ` ` ); let writes: Promise[] = []; let initFiles = ['/file.ts']; let start = performance.now(); for (let [path, contents] of Object.entries(files.ts)) { let p = '/_std/' + path + '.ts'; if (path == 'std') p = '/std.ts'; // So we can import it via import ui from "std"; writes.push(env.writeFileTypescript(p, contents)); initFiles.push(p); } for (let [path, contents] of Object.entries(files.shadeup)) { let p = '/_std/' + path + '.ts'; writes.push(env.writeFile(p, contents, true)); initFiles.push(p); } await Promise.all(writes); await env.regenerate(); let outs = await env.errors(); for (let out of outs) { if (out.error) { console.log(out.error); } } return env.stdEmitCache; } ================================================ FILE: lang/shadeup/compiler/interface.ts ================================================ import type { IndexMapping } from '../../../../shadeup-frontend/lib/generator/root'; import type { MonacoEditorInstance } from 'src/monaco/editor'; import type ts from 'typescript'; import type { MessageMainToWorker, MessageWorkerToMain, ShadeupDiagnostic, ShadeupRenderedFile } from './common'; export type ShadeupWorkspaceDiagnosticEvent = { diagnostics: ShadeupDiagnostic[]; }; export type ShadeupWorkspaceOutputEvent = { files: ShadeupRenderedFile[]; }; export class ShadeupWorkspaceInterface extends EventTarget { id: number = 0; worker: Worker; autoCompile = true; messageTimings: Map = new Map(); pendingWrites: Map = new Map(); dirtyFilesForWrite: Set = new Set(); files: Map = new Map(); fileTypes: Map = new Map(); fileMapping: Map = new Map(); diagnostics: ShadeupDiagnostic[] = []; cachedFiles: ShadeupRenderedFile[] = []; queue: MessageMainToWorker[] = []; workerReady = false; nonceCounter = 0; waitingForNonce: Map void> = new Map(); constructor(worker: Worker) { super(); this.setupWorker(worker); } setupWorker(worker: Worker) { this.worker = worker; this.worker.onerror = (e) => { console.log('Worker crashed'); console.error(e); let newWorker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); this.setupWorker(newWorker); }; this.worker.onmessage = async (e: MessageEvent) => { console.log('Got message', e.data); if (e.data.ready) { this.workerReady = true; let resp = await this.sendMessageWithResponse({ key: 'init' }); if (resp.output) { this.updateCachedFiles(resp.output); this.dispatchOutputEvent(resp.output); } this.processQueue(); } console.log( 'Processing message with', e.data.nonce, 'in', this.nonceCounter - 1, 'and', this.pendingWrites.size, 'pending writes' ); for (let entry of this.pendingWrites.entries()) { if (entry[1].nonce === e.data.nonce) { this.pendingWrites.delete(entry[0]); if (this.dirtyFilesForWrite.has(entry[0])) { this.dirtyFilesForWrite.delete(entry[0]); this.trySendWrite(entry[0]); } } } if (this.pendingWriteWatcher) this.pendingWriteWatcher(); // if (e.data.nonce < this.nonceCounter - 1) return; if (typeof e.data.nonce === 'number') { let cb = this.waitingForNonce.get(e.data.nonce); if (cb) { cb(e.data); return; } } let timing = this.messageTimings.get(e.data.nonce); if (timing) { console.log(`Message ${timing.name} took ${performance.now() - timing.timestamp}ms`); this.messageTimings.delete(e.data.nonce); } if (e.data.files) { for (let f of e.data.files) { this.fileMapping.set(f.path, f.mapping); } } if (e.data.diagnostics) this.diagnostics = e.data.diagnostics; if (e.data.output) { this.updateCachedFiles(e.data.output); this.dispatchOutputEvent(e.data.output); } if (e.data.classifications) { this.applyClassifications(e.data.classifications.path, e.data.classifications.encoded); } this.dispatchEvent( new CustomEvent('diagnostic', { detail: { diagnostics: e.data.diagnostics } }) ); }; } catchUpWorker() { for (let file of this.files.entries()) { let type = this.fileTypes.get(file[0]); if (type == 'shadeup') { this.writeFile(file[0], file[1]); } else { this.writeFileTypescript(file[0], file[1]); } } } pendingWriteWatcher: (() => void) | null = null; flushWrites(): Promise { return new Promise((resolve, reject) => { this.pendingWriteWatcher = () => { if (this.pendingWrites.size == 0 && this.dirtyFilesForWrite.size == 0) { this.pendingWriteWatcher = null; resolve(); } }; }); } replayOutput() { console.log('Replaying output', this.cachedFiles); this.dispatchOutputEvent(this.cachedFiles); } updateCachedFiles(files: ShadeupRenderedFile[]) { for (let i = this.cachedFiles.length - 1; i >= 0; i--) { let f = this.cachedFiles[i]; if (files.find((f2) => f2.path === f.path)) { this.cachedFiles.splice(i, 1); } } this.cachedFiles.push(...files); } applyClassifications(path: string, encoded: ts.Classifications) { this.dispatchEvent( new CustomEvent<{ path: string; encoded: ts.Classifications }>('classifications', { detail: { path, encoded } }) ); } dispatchOutputEvent(files: ShadeupRenderedFile[]) { this.dispatchEvent( new CustomEvent('output', { detail: { files } }) ); } on( event: 'diagnostic', listener: (evt: CustomEvent) => void ): void; on(event: 'output', listener: (evt: CustomEvent) => void): void; on( event: 'writeFile', listener: (evt: CustomEvent<{ file: string; content: string }>) => void ): void; on( event: 'classifications', listener: (evt: CustomEvent<{ path: string; encoded: ts.Classifications }>) => void ): void; on(event: string, listener: (evt: CustomEvent) => void) { this.addEventListener(event, listener as any); } off( event: 'diagnostic', listener: (evt: CustomEvent) => void ): void; off(event: 'output', listener: (evt: CustomEvent) => void): void; off( event: 'writeFile', listener: (evt: CustomEvent<{ file: string; content: string }>) => void ): void; off( event: 'classifications', listener: (evt: CustomEvent<{ path: string; encoded: ts.Classifications }>) => void ): void; off(event: string, listener: (evt: CustomEvent) => void) { this.removeEventListener(event, listener as any); } processQueue() { if (!this.workerReady) return; for (let msg of this.queue) { this.sendMessage(msg); } } enqueueMessage(msg: MessageMainToWorker) { if (this.workerReady) { this.sendMessage(msg); return; } this.queue.push(msg); } async enqueueMessageWithResponse(msg: MessageMainToWorker): Promise { while (!this.workerReady) { await new Promise((resolve) => setTimeout(resolve, 10)); } return await this.sendMessageWithResponse(msg); } trySendWrite(path: string, ignoreErrors = false) { let pending = this.pendingWrites.get(path); if (pending) { this.dirtyFilesForWrite.add(path); } else { let contents = this.files.get(path); if (contents) { this.enqueueMessage({ key: 'writeFile', message: { path, emit: this.autoCompile, contents, ignoreErrors } }); } } } writeFile(path: string, contents: string, ignoreErrors = false) { this.files.set(path, contents); this.fileTypes.set(path, 'shadeup'); this.trySendWrite(path, ignoreErrors); this.dispatchEvent( new CustomEvent<{ file: string; content: string; ignoreErrors: boolean }>('writeFile', { detail: { file: path, emit: this.autoCompile, content: contents, ignoreErrors } }) ); } writeFileWithResponse(path: string, contents: string, ignoreErrors = false) { this.files.set(path, contents); this.fileTypes.set(path, 'shadeup'); let ppromise = new Promise(() => {}); let pending = this.pendingWrites.get(path); if (pending) { console.log('pending write', path); this.dirtyFilesForWrite.add(path); } else { let contents = this.files.get(path); if (contents) { ppromise = this.enqueueMessageWithResponse({ key: 'writeFile', message: { path, emit: this.autoCompile, contents, ignoreErrors } }); } } this.dispatchEvent( new CustomEvent<{ file: string; content: string }>('writeFile', { detail: { file: path, content: contents } }) ); return ppromise; } writeFileTypescript(path: string, contents: string) { this.files.set(path, contents); this.fileTypes.set(path, 'typescript'); this.enqueueMessage({ key: 'writeFileTypescript', message: { path, contents, emit: this.autoCompile } }); } sendMessage(msg: MessageMainToWorker) { msg.nonce = this.nonceCounter++; this.messageTimings.set(msg.nonce, { name: msg.key, timestamp: performance.now() }); if (msg.key == 'writeFile') { console.log('Set Pending write for', msg.message.path, msg.nonce); this.pendingWrites.set(msg.message.path, { nonce: msg.nonce, content: msg.message.contents }); } this.worker.postMessage(msg); } sendMessageWithResponse(msg: MessageMainToWorker): Promise { return new Promise((resolve, reject) => { msg.nonce = this.nonceCounter++; this.waitingForNonce.set(msg.nonce, (msg) => { // console.log('got response', msg); this.waitingForNonce.delete(msg.nonce); resolve(msg); }); this.worker.postMessage(msg); }); } async connectEditor(path: string, monacoFilename: string, editor: MonacoEditorInstance) { const connectMonacoEditorToShadeupWorkspace = (await import('../monaco/connector')) .connectMonacoEditorToShadeupWorkspace; connectMonacoEditorToShadeupWorkspace(this, path, monacoFilename, editor); } async getCompletions(path: string, position: number) { let resp = await this.sendMessageWithResponse({ key: 'getCompletions', message: { path, position } }); return resp.completions; } async getHover(path: string, position: number) { let resp = await this.sendMessageWithResponse({ key: 'getHover', message: { path, position } }); return resp.hover; } reset() { this.enqueueMessage({ key: 'reset' }); this.files.clear(); this.fileMapping.clear(); this.diagnostics = []; this.cachedFiles = []; this.dirtyFilesForWrite.clear(); this.pendingWrites.clear(); } assets(assets: [string, [string, string]][]) { this.enqueueMessage({ key: 'assets', message: assets }); } } export async function makeShadeupWorkspace(): Promise { let worker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); let p = new ShadeupWorkspaceInterface(worker); if (!(window as any)['workspaceCounter']) (window as any)['workspaceCounter'] = 0; p.id = (window as any)['workspaceCounter']++; return p; } ================================================ FILE: lang/shadeup/compiler/simple.ts ================================================ import { ShadeupEnvironment } from '../../../../shadeup-frontend/lib/environment/ShadeupEnvironment'; import files from '../library/files'; export async function makeSimpleShadeupEnvironment() { let env = new ShadeupEnvironment(); env.emitLogs = false; await env.init(); await env.writeFile( '/file.ts', ` ` ); let writes: Promise[] = []; let initFiles = ['/file.ts']; let start = performance.now(); for (let [path, contents] of Object.entries(files.ts)) { let p = '/_std/' + path + '.ts'; if (path == 'std') p = '/std.ts'; // So we can import it via import ui from "std"; writes.push(env.writeFileTypescript(p, contents)); initFiles.push(p); } for (let [path, contents] of Object.entries(files.shadeup)) { let p = '/_std/' + path + '.ts'; writes.push(env.writeFile(p, contents, true)); initFiles.push(p); } return env; } ================================================ FILE: lang/shadeup/compiler/worker.ts ================================================ import { ShadeupEnvironment, type ShadeupGenericDiagnostic } from '../../../../shadeup-frontend/lib/environment/ShadeupEnvironment'; import type { MessageMainToWorker, MessageWorkerToMain, ShadeupDiagnostic, ShadeupRenderedFile } from './common'; import { lookupIndexMappingRange, reverseLookupIndexMapping } from '../../../../shadeup-frontend/lib/generator/root'; import { indexToRowColumn } from '../../../../shadeup-frontend/lib/environment/ShadeupEnvironment'; import ts from 'typescript'; let env = new ShadeupEnvironment(); env.emitLogs = false; await env.init(); await env.writeFile( '/file.ts', ` ` ); import files from '../library/files'; let writes: Promise[] = []; let initFiles = ['/file.ts']; let start = performance.now(); for (let [path, contents] of Object.entries(files.ts)) { let p = '/_std/' + path + '.ts'; if (path == 'std') p = '/std.ts'; // So we can import it via import ui from "std"; writes.push(env.writeFileTypescript(p, contents)); initFiles.push(p); } for (let [path, contents] of Object.entries(files.shadeup)) { let p = '/_std/' + path + '.ts'; writes.push(env.writeFile(p, contents, true)); initFiles.push(p); } await Promise.all(writes); // env.emitLogs = true; console.log('Initialized worker in', performance.now() - start, 'ms'); postMessage({ nonce: 0, diagnostics: [], files: [], ready: true, completions: [], hover: null, output: [] } as MessageWorkerToMain); function findFile(path: string) { return env.files.find((f) => f.path === path); } function tsDiagnosticToShadeupDiagnostic(diag: { error: ts.Diagnostic; file: string; message: string; }): ShadeupDiagnostic | null { let path = diag.error.file?.fileName ?? ''; let file = findFile(path); if (!file) return null; let mapping = file.mapping; if (!mapping) return null; let to = lookupIndexMappingRange( mapping, diag.error.start ?? 0, (diag.error.start ?? 0) + (diag.error.length ?? 0) ); let fileSource = file.content; if (fileSource) { let start = indexToRowColumn(fileSource, to.start); let end = indexToRowColumn(fileSource, to.end); return { path: diag.file, level: 'error', fullMessage: diag.message ?? '', startLine: start.row + 1, startColumn: start.column + 1, endLine: end.row + 1, endColumn: end.column + 1, message: ts.flattenDiagnosticMessageText(diag.error.messageText, '\n') }; } return null; } function genericDiagnosticToShadeupDiagnostic( path: string, diag: ShadeupGenericDiagnostic ): ShadeupDiagnostic | null { let file = findFile(path); if (!file) return null; let mapping = file.mapping; if (!mapping) return null; let fileSource = file.content; if (fileSource) { let start = indexToRowColumn(fileSource, diag.startIndex); let end = indexToRowColumn(fileSource, diag.endIndex); return { path, level: 'error', fullMessage: diag.message ?? '', startLine: start.row + 1, startColumn: start.column + 1, endLine: end.row + 1, endColumn: end.column + 1, message: diag.message }; } return null; } function delay(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } let dirtyFiles = new Set(); onerror = function (e) { console.error(e); }; onmessage = async function (e: MessageEvent) { if (e.data.key === 'writeFile') { console.log('Received writefile nonce', e.data.nonce); await env.writeFile(e.data.message.path, e.data.message.contents, e.data.message.ignoreErrors); let filesToGenerate = [e.data.message.path]; for (let dirty of dirtyFiles) { if (dirty !== e.data.message.path) filesToGenerate.push(dirty); } let output: { path: string; contents: string; }[] = []; if (e.data.message.emit) output = await env.regenerate(filesToGenerate); // await env.regenerate(); let errors: { error: ts.Diagnostic; file: string; message: string; }[] = []; if (!e.data.message.ignoreErrors) { errors = await env.errors([e.data.message.path]); } let file = findFile(e.data.message.path); let diags: ShadeupDiagnostic[] = []; for (let parseError of file?.parseDiagnostics ?? []) { let diag = genericDiagnosticToShadeupDiagnostic(e.data.message.path, parseError); if (diag) diags.push(diag); } for (let error of errors) { let diag = tsDiagnosticToShadeupDiagnostic(error); if (diag) diags.push(diag); } // let output: ShadeupRenderedFile[] = []; if (errors.length == 0) { dirtyFiles.clear(); // console.log('Output', e.data.message.path, output); } else { dirtyFiles.add(e.data.message.path); // console.log('Errors', e.data.message.path, errors); } console.log('Sending writefile nonce', e.data.nonce); postMessage({ nonce: e.data.nonce, classifications: { path: e.data.message.path, encoded: env.classifications(e.data.message.path) }, files: env.files.map((f) => ({ path: f.path, contents: f.content, mapping: f.mapping })), diagnostics: diags, output }); } else if (e.data.key === 'build') { let all = await env.regenerate(); postMessage({ nonce: e.data.nonce, output: all }); } else if (e.data.key === 'writeFileTypescript') { await env.writeFileTypescript(e.data.message.path, e.data.message.contents); let errors = await env.errors(); let file = findFile(e.data.message.path); let diags: ShadeupDiagnostic[] = []; for (let parseError of file?.parseDiagnostics ?? []) { let diag = genericDiagnosticToShadeupDiagnostic(e.data.message.path, parseError); if (diag) diags.push(diag); } for (let error of errors) { let diag = tsDiagnosticToShadeupDiagnostic(error); if (diag) diags.push(diag); } let output: ShadeupRenderedFile[] = []; if (errors.length == 0) { let filesToGenerate = [e.data.message.path]; for (let dirty of dirtyFiles) { if (dirty !== e.data.message.path) filesToGenerate.push(dirty); } console.log('Ready to regenerate', filesToGenerate, dirtyFiles); if (e.data.message.emit) output = await env.regenerate(filesToGenerate); dirtyFiles.clear(); // console.log('Output', e.data.message.path, output); } else { dirtyFiles.add(e.data.message.path); // console.log('Errors', e.data.message.path, errors); } postMessage({ nonce: e.data.nonce, files: env.files.map((f) => ({ path: f.path, contents: f.content, mapping: f.mapping })), diagnostics: diags, output }); } else if (e.data.key == 'getCompletions') { let completions = await env.completions(e.data.message.path, e.data.message.position); postMessage({ nonce: e.data.nonce, completions }); } else if (e.data.key == 'getHover') { let hover = await env.hover(e.data.message.path, e.data.message.position); postMessage({ nonce: e.data.nonce, hover }); } else if (e.data.key == 'init') { let output = await env.regenerate([ '/static-math.ts', '/std_math.ts', '/std___std_all.ts', ...initFiles ]); let errors = await env.errors(); if (errors.length == 0) { dirtyFiles.clear(); } else { dirtyFiles.add([...env.files][0].path); } postMessage({ nonce: e.data.nonce, output: output //.filter((f) => f.path == '/std___std_all.js' || f.path == '/std_math.js') }); } else if (e.data.key == 'reset') { dirtyFiles.clear(); env.reset(); } else if (e.data.key == 'assets') { env.setAssetMapping(e.data.message); } }; ================================================ FILE: lang/shadeup/engine/adapters/adapter.ts ================================================ import type { buffer } from 'src/shadeup/library/buffer'; import type { Mesh } from '../../../../../shadeup-frontend/lib/std/all'; import type { ShadeupTexture2d } from '../engine'; import type { ShadeupShaderInstance, ShadeupShaderSource } from '../shader'; import type { int } from 'src/shadeup/library/types'; import type { texture2d } from '../../library/texture'; export type ShaderType = 'vertex' | 'fragment' | 'compute' | 'vertex-indexed'; export type ShaderCodeMapping = { webgl: string; webgpu: string; software: () => void; }; export type ShaderParamsMapping = { webgl: { [key: string]: UniformValueType }; webgpu: { attributeInput: string; attributeOutput: string; globals: [string, { fileName: string; structure: UniformValueType }][]; locals: UniformKeyValuePair[]; }; }; export class GenericShader { uniqueSourceKey: string = ''; code: string; type: ShaderType; payload: any; parent: ShadeupShaderSource | null = null; constructor(code: string, type: ShaderType) { this.code = code; this.type = type; } } export type UniformKeyValuePair = [string, UniformValueType]; export type PrimitiveVectorSizes = '' | '2' | '3' | '4'; export type PrimitiveUniformType = | `float${PrimitiveVectorSizes}` | `float2x2` | `float3x3` | `float4x4` | `int${PrimitiveVectorSizes}` | `uint${PrimitiveVectorSizes}` | 'bool'; export class UniformValue { valueType: UniformValueType; value: any; constructor(valueType: UniformValueType, value: any) { this.valueType = valueType; this.value = value; } } export type UniformValueType = | { type: 'array'; element: UniformValueType; staticSize?: number; } | { type: 'struct'; fields: UniformKeyValuePair[]; name: string; } | { type: 'primitive'; name: PrimitiveUniformType; } | { type: 'primitive'; name: 'texture2d' | 'rwtexture2d'; element: UniformValueType; access: 'read' | 'write' | 'sample' | 'sample_write'; } | { type: 'primitive'; name: 'atomic'; element: UniformValueType; } | { type: 'buffer'; element: UniformValueType; access: 'read' | 'write'; }; export function makePrimitiveUniform(type: UniformValueType, value: any): UniformValue { return new UniformValue(type, value); } export class UniformPayload { uniforms: Map = new Map(); } export type ShaderTextureType = | `float${'' | '2' | '3' | '4'}` | `int${'' | '2' | '3' | '4'}` | `uint${'' | '2' | '3' | '4'}` | `uint8`; export type ShaderBindingOptions = { attachments?: ShaderTextureType[]; initialDispatch?: ShadeupShaderInstance; }; export type ShaderDepthCompareMode = | 'greater' | 'less' | 'equal' | 'greater-equal' | 'less-equal' | 'not-equal' | 'always' | 'never'; export class ShaderDispatch { type: 'draw' | 'compute'; drawType: 'indexed' | 'screen' | 'count' | 'geometry' = 'screen'; vertexUniforms: UniformPayload; fragmentUniforms: UniformPayload; depthOnly: boolean = false; backfaceCulling: boolean = true; reverseZ: boolean = false; depthCompare: ShaderDepthCompareMode | 'auto' = 'auto'; attachments: ShadeupTexture2d[] | null = null; vertexShader: GenericShader | null = null; fragmentShader: GenericShader | null = null; computeShader: GenericShader | null = null; geometry: Mesh | null = null; indexBuffer: buffer | null = null; drawCount: number = 0; instanceCount: number = 1; indirectBuffer: buffer | null = null; indirectOffset: number = 0; overrideDepth: ShadeupTexture2d | null = null; computeCount: [number, number, number] = [0, 0, 0]; constructor(type: 'draw' | 'compute') { this.type = type; this.vertexUniforms = new UniformPayload(); this.fragmentUniforms = new UniformPayload(); } setVertexUniform(name: string, value: UniformValue) { this.vertexUniforms.uniforms.set(name, value); } setFragmentUniform(name: string, value: UniformValue) { this.fragmentUniforms.uniforms.set(name, value); } setVertexShader(shader: GenericShader) { this.vertexShader = shader; } setFragmentShader(shader: GenericShader) { this.fragmentShader = shader; } setComputeShader(shader: GenericShader) { this.computeShader = shader; } setGeometry(geometry: Mesh) { this.geometry = geometry; } setIndexBuffer(indexBuffer: buffer) { this.indexBuffer = indexBuffer; } } export class GraphicsAdapter { canvas: HTMLCanvasElement | null; contextMode: 'paint' | 'draw' = 'draw'; listeners: Map = new Map(); constructor(cnvs: HTMLCanvasElement | null) { this.canvas = cnvs; } clear( immediate: boolean = false, color: float | [number, number, number, number] | 'auto' = 'auto' ) {} draw() {} init() {} addEventListener(name: string, callback: any) { let listeners = this.listeners.get(name); if (!listeners) { listeners = []; this.listeners.set(name, listeners); } listeners.push(callback); } removeEventListener(name: string, callback: any) { const listeners = this.listeners.get(name); if (!listeners) return; const index = listeners.indexOf(callback); if (index === -1) return; listeners.splice(index, 1); } triggerEvent(name: string, ...args: any[]) { const listeners = this.listeners.get(name); if (!listeners) return; for (const listener of listeners) { listener(...args); } } dispatch( dispatch: ShaderDispatch, options: { depthTest: boolean } = { depthTest: true } ) { this.activateDrawContext(); } activateDrawContext() { if (this.contextMode === 'paint') { this.switchContext('draw'); } } activatePaintContext() { if (this.contextMode === 'draw') { this.switchContext('paint'); this.flush(); } } switchContext(mode: 'paint' | 'draw') { this.contextMode = mode; this.triggerEvent('context', mode); } drawImage(image: HTMLCanvasElement, x: number, y: number, width: number, height: number) {} async downloadImage(): Promise { return new Float32Array(0); } uploadImage( data: Uint32Array | Uint16Array | Int16Array | Int32Array | Float32Array | Uint8Array ) {} setViewport(width: number, height: number) {} getOrCreateShader( instance: ShadeupShaderInstance, type: ShaderType, config?: ShaderBindingOptions ): GenericShader { return new GenericShader('', 'vertex'); } createShader(code: ShaderCodeMapping, type: ShaderType): GenericShader { return new GenericShader('', 'vertex'); } unbindTexture(texture: ShadeupTexture2d) {} dispose() {} flush() { this.triggerEvent('flush'); } waitForDraw(): Promise { return Promise.resolve(); } } ================================================ FILE: lang/shadeup/engine/adapters/webgl.ts ================================================ import type { buffer } from 'src/shadeup/library/buffer'; import { ShadeupTexture2d } from '../engine'; import type { ShadeupShaderInstance } from '../shader'; import { translateNumericToGLSL } from '../util'; import { GenericShader, GraphicsAdapter, ShaderDispatch, type ShaderCodeMapping, type ShaderType, type UniformValueType, type ShaderBindingOptions } from './adapter'; import { LRUCache } from 'lru-cache'; export function indexToRowColumn(str: string, index: number) { let row = 0; let column = 0; for (let i = 0; i < index; i++) { if (str[i] === '\n') { row++; column = 0; } else { column++; } } return { row, column }; } type WithCachedUniformLocation = { getUniformLocationCached: (path: string) => WebGLUniformLocation; }; const TRANSPOSE_MATRICES_UNIFORM = false; const boundTextures = new Map(); let boundTexturesCache = new LRUCache({ max: 16 }); for (let ti = 0; ti < 16; ti++) { boundTextures.set(ti, null); } export function rowColumnToIndex(str: string, row: number, column: number) { let index = 0; let currentRow = 0; let currentColumn = 0; while (currentRow < row || currentColumn < column) { if (str[index] === '\n') { currentRow++; currentColumn = 0; } else { currentColumn++; } index++; } return index; } let webglCounter = 0; export class WebGLAdapter extends GraphicsAdapter { gl: WebGL2RenderingContext | null = null; index: number = 0; blankImage: HTMLCanvasElement | null = null; GL_SHADER_TYPES: { [K in ShaderType]: number } = { vertex: 0, 'vertex-indexed': 0, fragment: 0, compute: -1 }; programCache = new Map(); init() { this.index = webglCounter++; console.log('Creating gl with index', this.index); this.gl = this.canvas.getContext('webgl2', { preserveDrawingBuffer: true }); if (!this.gl) { throw new Error('WebGL is not supported'); } this.GL_SHADER_TYPES = { vertex: this.gl.VERTEX_SHADER, fragment: this.gl.FRAGMENT_SHADER, 'vertex-indexed': this.gl.VERTEX_SHADER, compute: -1 }; this.blankImage = document.createElement('canvas'); this.blankImage.width = 1; this.blankImage.height = 1; this.blankImage.getContext('2d')!.fillRect(0, 0, 1, 1); this.setupImageDrawing(); } __program: WebGLProgram | null = null; setupImageDrawing() { const gl = this.getGL(); this.__program = gl.createProgram(); let program = this.__program; if (!program) throw new Error('Could not create program'); let vertexShader = this.genNativeShader( `#version 300 es precision highp float; in vec4 a_position; in vec2 a_texcoord; uniform vec2 size; out vec2 v_texcoord; void main() { gl_Position = a_position; v_texcoord = a_texcoord; float x = float((gl_VertexID & 1) << 2); float y = float((gl_VertexID & 2) << 1); v_texcoord.x = x * 0.5; v_texcoord.y = 1.f - (y * 0.5); gl_Position = vec4(x - 1.0, y - 1.0, 0, 1); } `, gl.VERTEX_SHADER ); let fragmentShader = this.genNativeShader( `#version 300 es precision mediump float; precision mediump int; in vec2 v_texcoord; out vec4 _i_gl_out_pixel; uniform sampler2D u_texture; void main() { vec2 t = vec2(v_texcoord.x, v_texcoord.y); vec4 c = texture(u_texture, t); // c.rgb *= c.a; _i_gl_out_pixel = c; // _i_gl_out_pixel = vec4(t, 0.0, 1.0); } `, gl.FRAGMENT_SHADER ); if (!vertexShader || !fragmentShader) { return; } gl.attachShader(program, vertexShader!); gl.attachShader(program, fragmentShader!); gl.linkProgram(program); } drawImage( image: HTMLCanvasElement, dstX: number, dstY: number, texWidth: number, texHeight: number ): void { const gl = this.getGL(); const program = this.__program; if (!program) throw new Error('Could not create program'); let positionLocation = gl.getAttribLocation(program, 'a_position'); let texcoordLocation = gl.getAttribLocation(program, 'a_texcoord'); let matrixLocation = gl.getUniformLocation(program, 'u_matrix'); let textureLocation = gl.getUniformLocation(program, 'u_texture'); let positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); let positions = [-1, -1, -1, 1, 1, -1, 1, -1]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); let texcoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer); let texcoords = [0, 0, 0, 1, 1, 0, 1, 0]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texcoords), gl.STATIC_DRAW); let unit = this.getTextureUnit(image); // let tex = gl.createTexture(); // gl.bindTexture(gl.TEXTURE_2D, tex); // gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.useProgram(program); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.enableVertexAttribArray(positionLocation); gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer); gl.enableVertexAttribArray(texcoordLocation); gl.vertexAttribPointer(texcoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(textureLocation, unit); // gl.activeTexture(gl.TEXTURE0 + unit); // gl.bindTexture(gl.TEXTURE_2D, unit); gl.enable(gl.BLEND); // gl.blendFunc(gl.ONE, gl.ZERO); let indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); let tris = [0, 1, 2]; let indexArr = new Uint16Array(tris.length); for (let i = 0; i < tris.length; i += 3) { indexArr[i] = tris[i]; indexArr[i + 1] = tris[i + 1]; indexArr[i + 2] = tris[i + 2]; } gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indexArr, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.drawElements(gl.TRIANGLES, 3, gl.UNSIGNED_SHORT, 0); // gl.deleteTexture(tex); gl.deleteBuffer(positionBuffer); gl.deleteBuffer(texcoordBuffer); } getGL(): WebGL2RenderingContext { if (!this.gl) { throw new Error('WebGL is not supported'); } return this.gl; } setViewport(width: number, height: number) { const gl = this.getGL(); gl.viewport(0, 0, width, height); } getOrCreateShader( instance: ShadeupShaderInstance, type: ShaderType, config?: ShaderBindingOptions ): GenericShader { const gl = this.getGL(); let arrSizeChanged = false; for (let param of Object.keys(instance.parent.params.webgl)) { let type = instance.parent.params.webgl[param]; if (type.type == 'array') { if (!instance.parent.arraySizes[param]) instance.parent.arraySizes[param] = 0; if (Array.isArray(instance.bindings[param])) { if (instance.bindings[param].length > instance.parent.arraySizes[param]) { instance.parent.arraySizes[param] = instance.bindings[param].length; arrSizeChanged = true; } } } } if (instance.parent.types[type] && !arrSizeChanged) { return instance.parent.types[type]; } else { if (type == 'compute') { throw new Error('Compute shaders are not supported in WebGL'); } let shader = gl.createShader(this.GL_SHADER_TYPES[type]); if (!shader) { console.log('Shader on canvas failed', this.canvas); throw new Error('Failed to create shader of type ' + type); } let base = instance.parent.code.webgl; for (let param of Object.keys(instance.parent.arraySizes)) { base = base.replace(`%${param}_size%`, instance.parent.arraySizes[param]); // console.log(base, `%${param}_size%`); } if (type == 'vertex') { base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/', `in vec3 a_position; in vec3 a_normal; in vec3 a_tangent; in vec3 a_bitangent; in vec2 a_uv; in vec4 a_color; out vec3 _v_position; out vec3 _v_normal; out vec3 _v_tangent; out vec3 _v_bitangent; out vec2 _v_uv; out vec4 _v_color; uniform vec2 _vtex_canvas;`.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/', `ShaderOutput _i_out; _i_out.position = vec4(a_position, 1.0); _i_out.normal = a_normal; _i_out.tangent = a_tangent; _i_out.bitangent = a_bitangent; _i_out.uv = a_uv; _i_out.color = a_color; ShaderInput _i_in; _i_in.position = a_position; _i_in.uv = a_uv; _i_in.normal = a_normal; _i_in.tangent = a_tangent; _i_in.bitangent = a_bitangent; _i_in.color = a_color; _i_in.screen = vec2(0, 0);`.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/', `gl_Position = _i_out.position; _v_position = _i_out.position.xyz; _v_normal = _i_out.normal; _v_tangent = _i_out.tangent; _v_bitangent = _i_out.bitangent; _v_uv = _i_out.uv; _v_color = _i_out.color;`.replace(/\t\n/g, '') ); base = base.replaceAll('_ext_uniform_global_', '_vertex_ext_uniform_global_'); base = base.replaceAll('_ext_uniform_local_', '_vertex_ext_uniform_local_'); } else if (type == 'vertex-indexed') { base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/', ` out vec3 _v_position; out vec3 _v_normal; out vec3 _v_tangent; out vec3 _v_bitangent; out vec2 _v_uv; out vec4 _v_color; uniform vec2 _vtex_canvas;`.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/', `ShaderOutput _i_out; _i_out.position = vec4(0.0, 0.0, 0.0, 1.0); _i_out.normal = vec3(0.0); _i_out.tangent = vec3(0.0); _i_out.bitangent = vec3(0.0); _i_out.uv = vec2(0.0); _i_out.color = vec4(0.0); ShaderInput _i_in; _i_in.vertexIndex = uint(gl_VertexID); _i_in.position = vec3(0.0); _i_in.uv = vec2(0.0); _i_in.normal = vec3(0.0); _i_in.tangent = vec3(0.0); _i_in.bitangent = vec3(0.0); _i_in.color = vec4(0.0); _i_in.screen = vec2(0, 0);`.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/', `gl_Position = _i_out.position; _v_position = _i_out.position.xyz; _v_normal = _i_out.normal; _v_tangent = _i_out.tangent; _v_bitangent = _i_out.bitangent; _v_uv = _i_out.uv; _v_color = _i_out.color;`.replace(/\t\n/g, '') ); base = base.replaceAll('_ext_uniform_global_', '_vertex_ext_uniform_global_'); base = base.replaceAll('_ext_uniform_local_', '_vertex_ext_uniform_local_'); } else { base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/', `out vec4 _i_gl_out_pixel; in vec3 _v_position; in vec3 _v_normal; in vec3 _v_tangent; in vec3 _v_bitangent; in vec2 _v_uv; in vec4 _v_color; uniform vec2 _vtex_canvas;`.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/', `ShaderOutput _i_out; ShaderInput _i_in; _i_in.uv = _v_uv; _i_in.normal = _v_normal; _i_in.tangent = _v_tangent; _i_in.bitangent = _v_bitangent; _i_in.color = _v_color; _i_in.position = _v_position; _i_in.screen = vec2(gl_FragCoord.x, _vtex_canvas.y - gl_FragCoord.y);`.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/', '_i_gl_out_pixel = _i_out.color;' ); base = base.replaceAll('_ext_uniform_global_', '_pixel_ext_uniform_global_'); base = base.replaceAll('_ext_uniform_local_', '_pixel_ext_uniform_local_'); } let finalSource = `#version 300 es\nprecision mediump float;\nprecision mediump int;\n\n${base}`; gl.shaderSource(shader, finalSource); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { let err = gl.getShaderInfoLog(shader); if (err) { let location = err.match(/ERROR: \d+:(\d+):/); if (location) { let line = parseInt(location[1]); let col = parseInt(location[0]); let lines = finalSource.split('\n'); console.error(lines[line - 1]); console.error(' '.repeat(col - 1) + '^'); } } console.error('Shader compile error', gl.getShaderInfoLog(shader)); // gl.shader; console.log(finalSource); (window as any).bubbleError('Shader compile error ' + gl.getShaderInfoLog(shader)); } instance.version++; let gShader = new GenericShader(instance.parent.code.webgl, type); if (!gShader.payload) { gShader.payload = {}; } gShader.payload[this.index] = shader; gShader.code = finalSource; gShader.parent = instance.parent; instance.parent.types[type] = gShader; return gShader; } } createShader(code: ShaderCodeMapping, type: ShaderType) { const gl = this.getGL(); if (type == 'compute') { let gComputeShader = new GenericShader(code.webgl, type); gComputeShader.payload = code.software; gComputeShader.parent = null; return gComputeShader; } let shader = gl.createShader(this.GL_SHADER_TYPES[type]); if (!shader) { throw new Error('Failed to create shader'); } gl.shaderSource(shader, code.webgl); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.log('Code', code); console.error('Shader compile error', gl.getShaderInfoLog(shader)); throw new Error('Shader compile error'); } let gShader = new GenericShader(code.webgl, type); gShader.payload = { [this.index]: shader }; gShader.parent = null; return gShader; } clear() { const gl = this.getGL(); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); } getProgramVertexPixel( vertexShaderKey: string, vertexShader: WebGLShader, pixelShaderKey: string, pixelShader: WebGLShader ): (WebGLProgram & WithCachedUniformLocation) | null { const gl = this.getGL(); let key = `${vertexShaderKey}_${pixelShaderKey}`; let uniformCache = new Map(); if (this.programCache.has(key)) { return this.programCache.get(key) ?? null; } let program: WebGLProgram & WithCachedUniformLocation = gl.createProgram() as any; if (!program) { return null; } (program as any).getUniformLocationCached = (path: string) => { if (!program) throw new Error('Program is null'); if (uniformCache.has(path)) { return uniformCache.get(path) ?? null; } // let errBefore = gl.getError(); let loc = gl.getUniformLocation(program, path); if (!loc) { // let err = gl.getError(); // throw new Error('Uniform not found ' + path + ' ' + err + ' ' + errBefore + ' ' + loc); } else { uniformCache.set(path, loc); return loc; } }; if (!vertexShader || !pixelShader) { return null; } gl.attachShader(program, vertexShader); gl.attachShader(program, pixelShader); gl.linkProgram(program); gl.useProgram(program); this.programCache.set(key, program); return program ?? null; } unbindTexture(texture: ShadeupTexture2d) { const gl = this.getGL(); if (texture.isBound && texture.payload) { boundTextures.set(texture.payload.unit, null); texture.isBound = false; gl.deleteTexture(texture.payload.texture); texture.payload = null; } } flush(): void { const gl = this.getGL(); gl.flush(); } getTextureUnit(texture: ShadeupTexture2d | TexImageSource) { const gl = this.getGL(); let isBound = false; if (texture instanceof ShadeupTexture2d) { texture.flush(); isBound = texture.isBound; } if (!isBound) { let unit = -1; for (let [ti, tex] of boundTextures) { if (tex == null) { unit = ti; break; } } if (unit == -1) { let oldest = boundTexturesCache.pop(); unit = oldest![0]; // throw new Error('Too many textures bound'); } if (texture instanceof ShadeupTexture2d) { texture.payload = { texture: gl.createTexture(), unit: -1, version: texture.version }; gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, texture.payload.texture); } else { gl.activeTexture(gl.TEXTURE0 + unit); if (!texture.$gl) { texture.$gl = {}; } if (!texture.$gl[this.index]) { texture.$gl[this.index] = gl.createTexture(); } gl.bindTexture(gl.TEXTURE_2D, texture.$gl[this.index]!); } gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); if (texture instanceof ShadeupTexture2d) { let webglAdapter = texture.adapter as WebGLAdapter; let useImage: TexImageSource = webglAdapter.canvas as TexImageSource; gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, useImage); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture); } boundTextures.set(unit, texture); if (texture instanceof ShadeupTexture2d) { texture.isBound = true; texture.payload.unit = unit; boundTexturesCache.set(texture.payload.unit, [texture.payload.unit, texture]); } else { boundTexturesCache.set(unit, [unit, texture]); } return unit; } else { if (texture instanceof ShadeupTexture2d) { if (texture.payload.version != texture.version) { gl.activeTexture(gl.TEXTURE0 + texture.payload.unit); gl.bindTexture(gl.TEXTURE_2D, texture.payload.texture); let webglAdapter = texture.adapter as WebGLAdapter; let useImage: TexImageSource = webglAdapter.canvas as TexImageSource; gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, useImage); texture.payload.version = texture.version; } boundTexturesCache.set(texture.payload.unit, [ texture.payload.unit, texture.payload.texture ]); return texture.payload.unit; } } } setUniform( program: WebGLProgram & WithCachedUniformLocation, path: string, val: any, type: UniformValueType, shaderKind: 'pixel' | 'vertex' ) { const gl = this.getGL(); const setUniform = this.setUniform.bind(this); let expandedType = type; if (expandedType.type == 'array') { let innerType = expandedType.element; for (let i = 0; i < val.length; i++) { setUniform(program, `${path}[${i}]`, val[i], innerType, shaderKind); } if (path.split('.').length < 2) { setUniform( program, `${path}_size`, val.length, { type: 'primitive', name: 'int' }, shaderKind ); } } else if (expandedType.type == 'primitive') { if (expandedType.name == 'texture2d' || expandedType.name == 'rwtexture2d') { let innerType = expandedType.element; let u = this.getTextureUnit(val); let loc = program.getUniformLocationCached(path); gl.uniform1i(loc, u); if (path.split('.').length < 2) { setUniform( program, `${path}_size`, val.size, { type: 'primitive', name: 'float2' }, shaderKind ); } } else { let methodName = translateNumericToGLSL(expandedType.name); let loc = program.getUniformLocationCached(path); if (!Array.isArray(val)) { val = [val]; } methodName = `uniform${methodName}v`; if (methodName.startsWith('uniformMatrix')) { // Transpose the matrix if TRANSPOSE_MATRICES_UNIFORM if (val.length == 4) { if (TRANSPOSE_MATRICES_UNIFORM) val = [val[0], val[2], val[1], val[3]]; } else if (val.length == 9) { if (TRANSPOSE_MATRICES_UNIFORM) val = [val[0], val[3], val[6], val[1], val[4], val[7], val[2], val[5], val[8]]; } else if (val.length == 16) { if (TRANSPOSE_MATRICES_UNIFORM) val = [ val[0], val[4], val[8], val[12], val[1], val[5], val[9], val[13], val[2], val[6], val[10], val[14], val[3], val[7], val[11], val[15] ]; } (gl as any)[methodName](loc, false, val); } else { (gl as any)[methodName](loc, val); } } } else if (expandedType.type == 'buffer') { } else if (expandedType.type == 'struct') { for (let field of Object.keys(expandedType.fields)) { if (!val) { throw new Error( `Found null value for ${path}.${field} while passing to shader (nulls are not allowed)` ); } setUniform(program, `${path}.${field}`, val[field], expandedType.fields[field], shaderKind); } } } dispatchDraw( dispatch: ShaderDispatch, options: { depthTest: boolean } = { depthTest: true } ) { const gl = this.getGL(); let pixelShader = dispatch.fragmentShader; let vertexShader = dispatch.vertexShader; if (!pixelShader || !vertexShader) { return; } let program = this.getProgramVertexPixel( vertexShader.uniqueSourceKey, vertexShader.payload[this.index], pixelShader.uniqueSourceKey, pixelShader.payload[this.index] ); if (!program) { return; } // let err = gl.getError(); // if (err != gl.NO_ERROR) { // throw new Error(`WebGL error: ${err}`); // } // let log = gl.getProgramInfoLog(program); // if (log) { // throw new Error(log + '\n\n' + vertexShader.code + '\n\n' + pixelShader.code); // } gl.useProgram(program); for (let k of dispatch.vertexUniforms.uniforms.keys()) { let val = dispatch.vertexUniforms.uniforms.get(k); if (!val) continue; k = k.replaceAll('_ext_uniform_global_', '_vertex_ext_uniform_global_'); k = k.replaceAll('_ext_uniform_local_', '_vertex_ext_uniform_local_'); this.setUniform(program, k, val.value, val.valueType, 'vertex'); } for (let k of dispatch.fragmentUniforms.uniforms.keys()) { let val = dispatch.fragmentUniforms.uniforms.get(k); if (!val) continue; k = k.replaceAll('_ext_uniform_global_', '_pixel_ext_uniform_global_'); k = k.replaceAll('_ext_uniform_local_', '_pixel_ext_uniform_local_'); this.setUniform(program, k, val.value, val.valueType, 'pixel'); } const geometry = dispatch.geometry; if (!geometry) { return; } let vao = gl.createVertexArray(); gl.bindVertexArray(vao); function generateEmptyData(arr: number[], size: number, numItems: number) { if (arr.length == 0) { for (let i = 0; i < numItems * size; i++) { for (let j = 0; j < size; j++) arr.push(0); } } return arr; } let geoGl = geometry as typeof geometry & { _cacheGL?: { positionBuffer: WebGLBuffer | null; normalBuffer: WebGLBuffer | null; tangentBuffer: WebGLBuffer | null; bitangentBuffer: WebGLBuffer | null; uvBuffer: WebGLBuffer | null; colorBuffer: WebGLBuffer | null; indexBuffer: WebGLBuffer | null; }; }; let positionBuffer: WebGLBuffer | null; let normalBuffer: WebGLBuffer | null; let tangentBuffer: WebGLBuffer | null; let bitangentBuffer: WebGLBuffer | null; let uvBuffer: WebGLBuffer | null; let colorBuffer: WebGLBuffer | null; let indexBuffer: WebGLBuffer | null; if (geoGl._cacheGL) { positionBuffer = geoGl._cacheGL.positionBuffer; normalBuffer = geoGl._cacheGL.normalBuffer; tangentBuffer = geoGl._cacheGL.tangentBuffer; bitangentBuffer = geoGl._cacheGL.bitangentBuffer; uvBuffer = geoGl._cacheGL.uvBuffer; colorBuffer = geoGl._cacheGL.colorBuffer; indexBuffer = geoGl._cacheGL.indexBuffer; } else { let tris = geometry.getTriangles(); positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(geometry.getVertices().flat()), gl.STATIC_DRAW ); normalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(generateEmptyData(geometry.getNormals().flat(), 3, tris.length)), gl.STATIC_DRAW ); tangentBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, tangentBuffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(generateEmptyData(geometry.getTangents().flat(), 3, tris.length)), gl.STATIC_DRAW ); bitangentBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, bitangentBuffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(generateEmptyData(geometry.getBitangents().flat(), 3, tris.length)), gl.STATIC_DRAW ); uvBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, uvBuffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(generateEmptyData(geometry.getUVs().flat(), 2, tris.length)), gl.STATIC_DRAW ); colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(generateEmptyData(geometry.getColors().flat(), 4, tris.length)), gl.STATIC_DRAW ); indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); let indexArr = new Uint16Array(tris.length); for (let i = 0; i < tris.length; i += 3) { if (false) { indexArr[i] = tris[i + 2]; indexArr[i + 1] = tris[i + 1]; indexArr[i + 2] = tris[i]; } else { indexArr[i] = tris[i]; indexArr[i + 1] = tris[i + 1]; indexArr[i + 2] = tris[i + 2]; } } gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indexArr, gl.STATIC_DRAW); geoGl._cacheGL = { positionBuffer, normalBuffer, tangentBuffer, bitangentBuffer, uvBuffer, colorBuffer, indexBuffer }; } let positionAttr = gl.getAttribLocation(program, 'a_position'); let normalAttr = gl.getAttribLocation(program, 'a_normal'); let tangentAttr = gl.getAttribLocation(program, 'a_tangent'); let bitangentAttr = gl.getAttribLocation(program, 'a_bitangent'); let uvAttr = gl.getAttribLocation(program, 'a_uv'); let colorAttr = gl.getAttribLocation(program, 'a_color'); gl.enable(gl.BLEND); if (options.depthTest) gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); if (positionAttr != -1) { gl.enableVertexAttribArray(positionAttr); gl.vertexAttribPointer( positionAttr, // location 3, // size (components per iteration) gl.FLOAT, // type of to get from buffer false, // normalize 0, // stride (bytes to advance each iteration) 0 // offset (bytes from start of buffer) ); } gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer); if (normalAttr != -1) { gl.enableVertexAttribArray(normalAttr); gl.vertexAttribPointer( normalAttr, // location 3, // size (components per iteration) gl.FLOAT, // type of to get from buffer false, // normalize 0, // stride (bytes to advance each iteration) 0 // offset (bytes from start of buffer) ); } gl.bindBuffer(gl.ARRAY_BUFFER, tangentBuffer); if (tangentAttr != -1) { gl.enableVertexAttribArray(tangentAttr); gl.vertexAttribPointer( tangentAttr, // location 3, // size (components per iteration) gl.FLOAT, // type of to get from buffer false, // normalize 0, // stride (bytes to advance each iteration) 0 // offset (bytes from start of buffer) ); } gl.bindBuffer(gl.ARRAY_BUFFER, bitangentBuffer); if (bitangentAttr != -1) { gl.enableVertexAttribArray(bitangentAttr); gl.vertexAttribPointer( bitangentAttr, // location 3, // size (components per iteration) gl.FLOAT, // type of to get from buffer false, // normalize 0, // stride (bytes to advance each iteration) 0 // offset (bytes from start of buffer) ); } gl.bindBuffer(gl.ARRAY_BUFFER, uvBuffer); if (uvAttr != -1) { gl.enableVertexAttribArray(uvAttr); gl.vertexAttribPointer( uvAttr, // location 2, // size (components per iteration) gl.FLOAT, // type of to get from buffer false, // normalize 0, // stride (bytes to advance each iteration) 0 // offset (bytes from start of buffer) ); } gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); if (colorAttr != -1) { gl.enableVertexAttribArray(colorAttr); gl.vertexAttribPointer( colorAttr, // location 4, // size (components per iteration) gl.FLOAT, // type of to get from buffer false, // normalize 0, // stride (bytes to advance each iteration) 0 // offset (bytes from start of buffer) ); } gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); gl.drawElements(gl.TRIANGLES, geometry.getTriangles().length, gl.UNSIGNED_SHORT, 0); // gl.deleteBuffer(positionBuffer); // gl.deleteBuffer(normalBuffer); // gl.deleteBuffer(uvBuffer); // gl.deleteBuffer(colorBuffer); // gl.deleteBuffer(indexBuffer); gl.deleteVertexArray(vao); // let errors = gl.getError(); // if (errors) { // console.error(errors); // } // let log2 = gl.getProgramInfoLog(program); // if (log2) { // throw new Error(log2 + '\n\n' + vertexShader.code + '\n\n' + pixelShader.code); // } } dispatchDrawIndexed( dispatch: ShaderDispatch, options: { depthTest: boolean } = { depthTest: true } ) { const gl = this.getGL(); let pixelShader = dispatch.fragmentShader; let vertexShader = dispatch.vertexShader; if (!pixelShader || !vertexShader) { return; } let program = this.getProgramVertexPixel( vertexShader.uniqueSourceKey, vertexShader.payload[this.index], pixelShader.uniqueSourceKey, pixelShader.payload[this.index] ); if (!program) { return; } gl.useProgram(program); for (let k of dispatch.vertexUniforms.uniforms.keys()) { let val = dispatch.vertexUniforms.uniforms.get(k); if (!val) continue; k = k.replaceAll('_ext_uniform_global_', '_vertex_ext_uniform_global_'); k = k.replaceAll('_ext_uniform_local_', '_vertex_ext_uniform_local_'); this.setUniform(program, k, val.value, val.valueType, 'vertex'); } for (let k of dispatch.fragmentUniforms.uniforms.keys()) { let val = dispatch.fragmentUniforms.uniforms.get(k); if (!val) continue; k = k.replaceAll('_ext_uniform_global_', '_pixel_ext_uniform_global_'); k = k.replaceAll('_ext_uniform_local_', '_pixel_ext_uniform_local_'); this.setUniform(program, k, val.value, val.valueType, 'pixel'); } const indexBuffer = dispatch.indexBuffer; if (!indexBuffer) { return; } // let vertexIdLoc = gl.getAttribLocation(program, '_a_vertex_id'); // gl.enableVertexAttribArray(vertexIdLoc); // gl.bindBuffer(gl.ARRAY_BUFFER, this.getOrCreateBuffer(indexBuffer, gl.ARRAY_BUFFER)); // const size = 1; // 1 components per iteration // const type = gl.UNSIGNED_INT; // the data is 32bit uint // const normalize = false; // don't normalize the data // const stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position // const offset = 0; // start at the beginning of the buffer // gl.vertexAttribPointer(vertexIdLoc, size, type, normalize, stride, offset); // let vao = gl.createVertexArray(); // gl.bindVertexArray(vao); function generateEmptyData(arr: number[], size: number, numItems: number) { if (arr.length == 0) { for (let i = 0; i < numItems * size; i++) { for (let j = 0; j < size; j++) arr.push(0); } } return arr; } gl.enable(gl.BLEND); if (options.depthTest) gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.drawArrays(gl.TRIANGLES, 0, indexBuffer.len()); // gl.deleteVertexArray(vao); } dispatchDrawCount( dispatch: ShaderDispatch, options: { depthTest: boolean } = { depthTest: true } ) { const gl = this.getGL(); let pixelShader = dispatch.fragmentShader; let vertexShader = dispatch.vertexShader; if (!pixelShader || !vertexShader) { return; } let program = this.getProgramVertexPixel( vertexShader.uniqueSourceKey, vertexShader.payload[this.index], pixelShader.uniqueSourceKey, pixelShader.payload[this.index] ); if (!program) { return; } gl.useProgram(program); for (let k of dispatch.vertexUniforms.uniforms.keys()) { let val = dispatch.vertexUniforms.uniforms.get(k); if (!val) continue; k = k.replaceAll('_ext_uniform_global_', '_vertex_ext_uniform_global_'); k = k.replaceAll('_ext_uniform_local_', '_vertex_ext_uniform_local_'); this.setUniform(program, k, val.value, val.valueType, 'vertex'); } for (let k of dispatch.fragmentUniforms.uniforms.keys()) { let val = dispatch.fragmentUniforms.uniforms.get(k); if (!val) continue; k = k.replaceAll('_ext_uniform_global_', '_pixel_ext_uniform_global_'); k = k.replaceAll('_ext_uniform_local_', '_pixel_ext_uniform_local_'); this.setUniform(program, k, val.value, val.valueType, 'pixel'); } gl.enable(gl.BLEND); if (options.depthTest) gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.drawArrays(gl.TRIANGLES, 0, dispatch.drawCount * 3); } getOrCreateBuffer(buf: buffer, binding: number): WebGLBuffer { const gl = this.getGL(); if (buf.platformPayload) { return buf.platformPayload as WebGLBuffer; } let buffer = gl.createBuffer(); if (!buffer) { throw new Error('Could not create buffer'); } gl.bindBuffer(binding, buffer); if (buf.structured) { // todo } else { gl.bufferData( binding, buf.uintArray ?? buf.floatArray ?? buf.intArray ?? new Uint8Array(0), gl.STATIC_DRAW ); } buf.platformPayload = buffer; return buffer; } dispatch( dispatch: ShaderDispatch, options: { depthTest: boolean } = { depthTest: true } ): void { super.dispatch(dispatch, options); if (dispatch.type == 'draw') { this.activateDrawContext(); this.triggerEvent('draw', dispatch); if (dispatch.drawType == 'indexed') { this.dispatchDrawIndexed(dispatch, options); } else if (dispatch.drawType == 'count') { this.dispatchDrawCount(dispatch, options); } else { this.dispatchDraw(dispatch, options); } } } genNativeShader(code: string, type: number) { const gl = this.getGL(); let shader = gl.createShader(type); if (!shader) { throw new Error('Could not create shader'); } gl.shaderSource(shader, code); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.log('Code', code); console.error('Shader compile error', gl.getShaderInfoLog(shader)); } return shader; } } ================================================ FILE: lang/shadeup/engine/adapters/webgpu.ts ================================================ import type { buffer, buffer_internal } from '../../library/buffer'; import type { Mesh } from '../../../../../shadeup-frontend/lib/std/all'; import { ShadeupTexture2d, type TextureComponentType } from '../engine'; import type { ShadeupShaderInstance } from '../shader'; import { Float16Array, isFloat16Array, isTypedArray, getFloat16, setFloat16, f16round } from '@petamoriken/float16'; import { GenericShader, GraphicsAdapter, ShaderDispatch, type ShaderCodeMapping, type ShaderType, UniformPayload, type UniformValueType, type UniformKeyValuePair, UniformValue, type ShaderBindingOptions } from './adapter'; import { LRUCache } from 'lru-cache'; const CACHE_PIPELINES = false; const FormatCapabilities: { [key in GPUTextureFormat]: { blendable: boolean; sampleTypes: string[]; }; } = { r8unorm: { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, r8snorm: { blendable: false, sampleTypes: ['float', 'unfilterable-float'] }, r8uint: { blendable: false, sampleTypes: ['uint'] }, r8sint: { blendable: false, sampleTypes: ['sint'] }, rg8unorm: { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, rg8snorm: { blendable: false, sampleTypes: ['float', 'unfilterable-float'] }, rg8uint: { blendable: false, sampleTypes: ['uint'] }, rg8sint: { blendable: false, sampleTypes: ['sint'] }, rgba8unorm: { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, 'rgba8unorm-srgb': { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, rgba8snorm: { blendable: false, sampleTypes: ['float', 'unfilterable-float'] }, rgba8uint: { blendable: false, sampleTypes: ['uint'] }, rgba8sint: { blendable: false, sampleTypes: ['sint'] }, bgra8unorm: { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, 'bgra8unorm-srgb': { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, r16uint: { blendable: false, sampleTypes: ['uint'] }, r16sint: { blendable: false, sampleTypes: ['sint'] }, r16float: { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, rg16uint: { blendable: false, sampleTypes: ['uint'] }, rg16sint: { blendable: false, sampleTypes: ['sint'] }, rg16float: { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, rgba16uint: { blendable: false, sampleTypes: ['uint'] }, rgba16sint: { blendable: false, sampleTypes: ['sint'] }, rgba16float: { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, r32uint: { blendable: false, sampleTypes: ['uint'] }, r32sint: { blendable: false, sampleTypes: ['sint'] }, r32float: { blendable: false, sampleTypes: [ 'unfilterable-float', 'float', 'float32-filterable', 'float', 'float32-filterable' ] }, rg32uint: { blendable: false, sampleTypes: ['uint'] }, rg32sint: { blendable: false, sampleTypes: ['sint'] }, rg32float: { blendable: false, sampleTypes: [ 'unfilterable-float', 'float', 'float32-filterable', 'float', 'float32-filterable' ] }, rgba32uint: { blendable: false, sampleTypes: ['uint'] }, rgba32sint: { blendable: false, sampleTypes: ['sint'] }, rgba32float: { blendable: false, sampleTypes: [ 'unfilterable-float', 'float', 'float32-filterable', 'float', 'float32-filterable' ] }, rgb10a2uint: { blendable: false, sampleTypes: ['uint'] }, rgb10a2unorm: { blendable: true, sampleTypes: ['float', 'unfilterable-float'] }, rg11b10ufloat: { blendable: false, sampleTypes: ['float', 'unfilterable-float'] } }; class WebGPUMeshData { sourceMesh: Mesh; vertexBuffer: GPUBuffer; indexBuffer: GPUBuffer; vertexCount: number; indexCount: number; constructor( sourceMesh: Mesh, vertexBuffer: GPUBuffer, indexBuffer: GPUBuffer, vertexCount: number, indexCount: number ) { this.sourceMesh = sourceMesh; this.vertexBuffer = vertexBuffer; this.indexBuffer = indexBuffer; this.vertexCount = vertexCount; this.indexCount = indexCount; } } const lruCacheOptions = { max: 500 }; let lruUniformOptions = { max: 128 }; type ShaderUniformCachePayload = { key: (number | string)[]; bindGroupLayout: GPUBindGroupLayout; bindGroup: GPUBindGroup; uniformBuffer: GPUBuffer; specialBuffers: GPUBuffer[]; cachedUniforms: ArrayBuffer; specialsKey: (number | string | Symbol)[]; specialEntries: GPUBindGroupEntry[]; }; type PipelinePreDispatchCommands = ((encoder: GPUCommandEncoder) => void)[]; type DrawPipelinePayload = { pipeline: GPURenderPipeline; bindGroupFragment: GPUBindGroup; bindGroupVertex: GPUBindGroup; baseUniformBuffer: GPUBuffer; fragmentUniformBuffer: GPUBuffer; vertexUniformBuffer: GPUBuffer; specialBuffersFragment: GPUBuffer[]; specialBuffersVertex: GPUBuffer[]; commands: PipelinePreDispatchCommands; }; type ComputePipelinePayload = { pipeline: GPUComputePipeline; bindGroup: GPUBindGroup; baseUniformBuffer: GPUBuffer; uniformBuffer: GPUBuffer; specialBuffers: GPUBuffer[]; commands: PipelinePreDispatchCommands; }; const vertexLayout: GPUVertexBufferLayout[] = [ { // Position arrayStride: (3 + // Position 3 + // Normal 3 + // Tangent 3 + // Bitangent 2 + // UV 4) * // Color 4, stepMode: 'vertex', attributes: [ { shaderLocation: 0, offset: 0, format: 'float32x3' }, { shaderLocation: 1, offset: 3 * 4, format: 'float32x3' }, { shaderLocation: 2, offset: (3 + 3) * 4, format: 'float32x3' }, { shaderLocation: 3, offset: (3 + 3 + 3) * 4, format: 'float32x3' }, { shaderLocation: 4, offset: (3 + 3 + 3 + 3) * 4, format: 'float32x2' }, { shaderLocation: 5, offset: (3 + 3 + 3 + 3 + 2) * 4, format: 'float32x4' } ] } ]; const FORMATS: { [key in TextureComponentType]: GPUTextureFormat } & { uint8: GPUTextureFormat } = { float: 'r32float', int: 'r32sint', uint: 'r32uint', float2: 'rg32float', int2: 'rg32sint', uint2: 'rg32uint', float3: 'rgba32float', int3: 'rgba32sint', uint3: 'rgba32uint', float4: 'rgba32float', int4: 'rgba32sint', uint4: 'rgba32uint', uint8: 'rgba8unorm' }; const CAN_BLEND: { [key in TextureComponentType]: boolean } & { uint8: boolean } = { float: false, int: false, uint: false, float2: false, int2: false, uint2: false, float3: false, int3: false, uint3: false, float4: false, int4: false, uint4: false, uint8: true }; export class WebGPUAdapter extends GraphicsAdapter { ctx: GPUCanvasContext | null = null; texture: GPUTexture | null = null; storageTexture: GPUTexture | null = null; storageDirty = false; pendingWrites: number = 0; adapter: GPUAdapter | null = null; device: GPUDevice | null = null; headless = false; headlessDimensions: 2 | 3 = 2; headlessWidth = 1024; headlessHeight = 1024; headlessDepth = 1024; baseUniformBufferSize = 2 * 4; // _vtex_canvas baseUniformValues = new Float32Array(this.baseUniformBufferSize / 4); baseUniformBuffer: GPUBuffer | null = null; pipelineCache: LRUCache = new LRUCache( lruCacheOptions ); ready = false; catchGPUErrors = true; gpuMeshData: Map = new Map(); depthTexture: GPUTexture | null = null; textureFormat: TextureComponentType | 'uint8' = 'float4'; gpuTextureFormat: GPUTextureFormat = 'rgba8unorm'; clearEnqueued = false; getValueSize(vt: UniformValueType) { return getValueSize(vt); } init() { this.ready = false; this.adapter = (window as any).shadeupWebGPUAdapter; this.device = (window as any).shadeupWebGPUDevice; if (!this.adapter || !this.device) { throw new Error('WebGPU is not supported'); } this.addEventListener('context', (to: string) => { if (to == 'paint') { if (!this.clearEnqueued) { this.beforeScreenDraw(); } } }); this.baseUniformBuffer = this.device.createBuffer({ size: this.baseUniformBufferSize, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); // this.adapter = await navigator.gpu.requestAdapter(); // if (!this.adapter) { // throw new Error('WebGPU is not supported'); // } // this.device = await this.adapter.requestDevice(); // if (!this.device) { // throw new Error('WebGPU is not supported'); // } if (this.headless) { if (this.headlessDimensions == 2) { this.startDispatch(); this.texture = this.device.createTexture({ size: { width: this.headlessWidth, height: this.headlessHeight }, format: this.gpuTextureFormat, dimension: '2d', viewFormats: [this.gpuTextureFormat], usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST }); this.endDispatch(); } else { this.startDispatch(); this.texture = this.device.createTexture({ size: { width: this.headlessWidth, height: this.headlessHeight, depthOrArrayLayers: this.headlessDepth }, format: this.gpuTextureFormat, dimension: '3d', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST }); this.endDispatch(); } } else { this.textureFormat = 'uint8'; this.ctx = this.canvas!.getContext('webgpu'); if (!this.ctx) { throw new Error('WebGPU is not supported'); } this.ctx.configure({ device: this.device, format: 'rgba8unorm', alphaMode: 'premultiplied', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST }); } if (this.canvas) { this.startDispatch(); this.depthTexture = this.device.createTexture({ size: { width: this.canvas.width, height: this.canvas.height }, format: 'depth24plus', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING }); this.endDispatch(); } this.ready = true; } startDispatch() { if (!this.device) return; if (this.catchGPUErrors) { this.device.pushErrorScope('validation'); this.device.pushErrorScope('internal'); this.device.pushErrorScope('out-of-memory'); } } endDispatch() { if (!this.device) return; let handler = (e: GPUError | null) => { if (!e) return; let ignore = e.message.includes('[Invalid ShaderModule] is invalid.') || e.message.includes('[Invalid BindGroup] is invalid.') || e.message.includes('[Invalid ComputePipeline') || e.message.includes('[Invalid RenderPipeline'); if (ignore) return; (window as any).bubbleError(e.message); let stack = new Error(); console.error(e, stack.stack); }; if (this.catchGPUErrors) { this.device.popErrorScope().then(handler); this.device.popErrorScope().then(handler); this.device.popErrorScope().then(handler); } } drawImageCache: any | null; trace(id: string, data: any) { // console.log(id, data); } drawImage(image: HTMLCanvasElement, x: number, y: number, width: number, height: number): void { const { device } = this.getGPU(); this.trace('drawImage', { image, x, y, width, height }); if (!this.ready) { return; } this.startDispatch(); // this.clear(true); let selfTexture = this.getTexture(); // this.fill([1, 0, 0, 1], true); // this.fill([0, 0, 0, 0], true); device.queue.copyExternalImageToTexture( { source: image }, { texture: selfTexture, premultipliedAlpha: true }, { width: image.width, height: image.height } ); this.copyToCanvas(); //printImage(image.toDataURL(), 10, () => console.log('Image read 0')); // printImage(this.canvas.toDataURL(), 10, () => console.log('canvas raed 0')); // let doCop = (msg: string) => { // let mapTex = this.device?.createBuffer({ // size: image.width * image.height * 4 * 2, // usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST // }); // let encoder = this.device?.createCommandEncoder(); // encoder.copyTextureToBuffer( // { texture: selfTexture }, // { buffer: mapTex, bytesPerRow: image.width * 4 * 2 }, // { width: image.width, height: image.height } // ); // let commandBuffer = encoder.finish(); // device.queue.submit([commandBuffer]); // mapTex?.mapAsync(GPUMapMode.READ).then(() => { // let data = new Uint16Array(mapTex?.getMappedRange()!); // let buf = new Uint8Array(image.width * image.height * 4); // for (let i = 0; i < image.width * image.height * 4; i++) { // buf[i] = data[i] / 100; // } // let cnvs = document.createElement('canvas'); // cnvs.width = image.width; // cnvs.height = image.height; // let ctx = cnvs.getContext('2d'); // if (!ctx) return; // let imageData = ctx.createImageData(image.width, image.height); // imageData.data.set(buf); // ctx.putImageData(imageData, 0, 0); // printImage(cnvs.toDataURL(), 10, () => console.log('MAp read', msg)); // }); // }; // setTimeout(() => doCop('5000'), 5000); // setTimeout(() => doCop('1000'), 1000); // setTimeout(() => doCop('100'), 100); // setTimeout(() => doCop('10'), 10); // setTimeout(() => doCop('1'), 1); // doCop('0'); // setTimeout(() => { // printImage(image.toDataURL(), 10, () => console.log('Image read 5000')); // printImage(this.canvas.toDataURL(), 10, () => console.log('canvas raed 5000')); // }, 5000); // setTimeout(() => { // printImage(image.toDataURL(), 10, () => console.log('Image read 2500')); // printImage(this.canvas.toDataURL(), 10, () => console.log('canvas raed 2500')); // }, 2500); // setTimeout(() => { // printImage(image.toDataURL(), 10, () => console.log('Image read 10')); // printImage(this.canvas.toDataURL(), 10, () => console.log('canvas raed 10')); // }, 10); // device.queue.copyExternalImageToTexture( // { source: image }, // { texture: this.ctx?.getCurrentTexture(), premultipliedAlpha: false }, // { width: image.width, height: image.height } // ); // const data = new Uint8Array([1 * 255, 1 * 255, 0 * 255, 0 * 255]); // device.queue.copyExternalImageToTexture( // { source: image }, // { texture: selfTexture, premultipliedAlpha: true }, // { width: image.width, height: image.height } // ); // this.fill([1, 0, 0, 1], true); // device.queue.writeTexture( // { texture: selfTexture }, // data, // {}, // { width: selfTexture.width, height: selfTexture.height } // ); // this.copyToCanvas(); // device.queue.copyExternalImageToTexture( // { source: image }, // { texture: selfTexture, premultipliedAlpha: true }, // { width: image.width, height: image.height } // ); this.endDispatch(); } genericBufferFlags() { return GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC; } copyBufferToBuffer(from: buffer, to: buffer) { const { device } = this.getGPU(); this.enqueueCommand((encoder) => { encoder.copyBufferToBuffer( this.getOrCreateBuffer(from, this.genericBufferFlags()), 0, this.getOrCreateBuffer(to, this.genericBufferFlags()), 0, from.elementCount * from.elementBytes ); }); } async downloadBuffer(buf: buffer) { this.trace('downloadBuffer', { buffer: buf }); const { device } = this.getGPU(); let nativeBuffer = this.getOrCreateBuffer(buf, this.genericBufferFlags()); this.startDispatch(); let encoder = device.createCommandEncoder(); let buffer = device.createBuffer({ size: nativeBuffer.size, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); encoder.copyBufferToBuffer(nativeBuffer, 0, buffer, 0, nativeBuffer.size); let commandBuffer = encoder.finish(); device.queue.submit([commandBuffer]); await buffer.mapAsync(GPUMapMode.READ); let arr = buffer.getMappedRange(); if (!buf.structured) { // Simple 1-to-1 mapping if (buf.arrayBuffer) { let u8down = new Uint8Array(arr); let u8in = new Uint8Array(buf.arrayBuffer); u8in.set(u8down); } else { throw new Error('Buffer not found while downloading'); } } else { if (buf.typeName == 'atomic') { // if (!buf.structArray) throw new Error('Buffer not found while downloading'); let u32down = new Uint32Array(arr); buf.uintArray?.set(u32down); } else if (buf.typeName == 'atomic') { // if (!buf.structArray) throw new Error('Buffer not found while downloading'); let i32down = new Int32Array(arr); buf.intArray?.set(i32down); } else { // let structure = (window as any).__shadeup_structs[buf.typeName]; // let elSize = getValueSize(structure.fields); // for (let i = 0; i < buf.elementCount; i++) { // buf.structArray[i] = this.readStructuredBuffer(structure.fields, arr, i * elSize); // } new Uint8Array(buf.arrayBuffer!).set(new Uint8Array(arr)); } } buffer.destroy(); this.endDispatch(); } uploadBuffer(buf: buffer) { const { device } = this.getGPU(); this.trace('uploadBuffer', { buffer: buf }); this.startDispatch(); let nativeBuffer = this.getOrCreateBuffer(buf, this.genericBufferFlags()); if (!buf.structured) { // Simple 1-to-1 mapping if (buf.arrayBuffer) { let u8in = new Uint8Array(buf.arrayBuffer); device.queue.writeBuffer(nativeBuffer, 0, u8in); } else { throw new Error('Buffer not found while downloading'); } } else { if (buf.typeName == 'atomic') { device.queue.writeBuffer(nativeBuffer, 0, buf.arrayBuffer!); } else if (buf.typeName == 'atomic') { let i32down = new Int32Array(buf.elementCount); device.queue.writeBuffer(nativeBuffer, 0, buf.arrayBuffer!); } else { // let structure = (window as any).__shadeup_structs[buf.typeName]; // let size = getValueSize(structure.fields); // let arrayBuffer = new ArrayBuffer(buf.elementCount * size); // for (let i = 0; i < buf.elementCount; i++) { // this.writeStructuredBuffer(structure.fields, buf.structArray[i], arrayBuffer, i * size); // } device.queue.writeBuffer(nativeBuffer, 0, new Uint8Array(buf.arrayBuffer!)); } } this.endDispatch(); } async downloadImage() { const { device } = this.getGPU(); this.flushStorage(); this.startDispatch(); let encoder = device.createCommandEncoder(); let texture = this.getTexture(); let stride = parseInt(this.textureFormat[this.textureFormat.length - 1]) || 1; if (this.textureFormat == 'uint8') { stride = 4; } let bytesPerComponent = 2; if (this.textureFormat == 'uint8') { bytesPerComponent = 1; } else if (this.textureFormat.startsWith('float')) { bytesPerComponent = 4; } else if (this.textureFormat.startsWith('int')) { bytesPerComponent = 4; } else { bytesPerComponent = 4; } let alignment = 256; let bytesPerRow = texture.width * stride * bytesPerComponent; let neededAlignment = false; let alignmentPad = 0; if (bytesPerRow % alignment != 0) { let oldBytes = bytesPerRow; bytesPerRow += alignment - (bytesPerRow % alignment); alignmentPad = bytesPerRow - oldBytes; neededAlignment = true; } let buffer = device.createBuffer({ size: bytesPerRow * texture.height, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); encoder.copyTextureToBuffer({ texture: texture }, { buffer: buffer, bytesPerRow }, texture); let commandBuffer = encoder.finish(); device.queue.submit([commandBuffer]); await buffer.mapAsync(GPUMapMode.READ); let arr: Uint32Array | Uint16Array | Int16Array | Int32Array | Float32Array | Uint8Array; let buf = new Uint8Array(buffer.getMappedRange()); if (neededAlignment) { let oldBytes = bytesPerRow - alignmentPad; let newData = new Uint8Array(oldBytes * texture.height); for (let i = 0; i < texture.height; i++) { newData.set(new Uint8Array(buf.buffer, i * bytesPerRow, oldBytes), i * oldBytes); } buf = newData; } if (this.textureFormat == 'uint8') { arr = new Uint8Array(buf.buffer); } else if (this.textureFormat.startsWith('float')) { arr = new Float32Array(buf.buffer); } else if (this.textureFormat.startsWith('int')) { arr = new Uint32Array(buf.buffer); } else { arr = new Uint32Array(buf.buffer); } this.endDispatch(); return arr; } uploadImage( data: Uint32Array | Uint16Array | Int16Array | Int32Array | Float32Array | Uint8Array ): void { this.startDispatch(); const { device } = this.getGPU(); let encoder = device.createCommandEncoder(); let texture = this.getTexture(); let stride = parseInt(this.textureFormat[this.textureFormat.length - 1]) || 1; if (this.textureFormat == 'uint8') { stride = 4; } let bytesPerComponent = 2; if (this.textureFormat == 'uint8') { bytesPerComponent = 1; } else if (this.textureFormat.startsWith('float')) { bytesPerComponent = 4; } else if (this.textureFormat.startsWith('int')) { bytesPerComponent = 4; } else { bytesPerComponent = 4; } let alignment = 256; let bytesPerRow = texture.width * stride * bytesPerComponent; if (bytesPerRow % alignment != 0) { let oldBytes = bytesPerRow; bytesPerRow += alignment - (bytesPerRow % alignment); let pad = bytesPerRow - oldBytes; // Add padding let newData = new Uint8Array(bytesPerRow * texture.height); for (let i = 0; i < texture.height; i++) { newData.set(new Uint8Array(data.buffer, i * oldBytes, oldBytes), i * bytesPerRow); } data = newData; } let buffer = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST }); device.queue.writeBuffer(buffer, 0, data); encoder.copyBufferToTexture( { buffer: buffer, bytesPerRow }, { texture: texture }, { width: texture.width, height: texture.height } ); let commandBuffer = encoder.finish(); device.queue.submit([commandBuffer]); buffer.destroy(); this.copyToCanvas(); this.endDispatch(); } getGPU(): { device: GPUDevice; } { if (!this.device) { throw new Error('WebGPU is not supported'); } if (!this.ready) { throw new Error('WebGPU is not ready'); } return { device: this.device }; } setViewport(width: number, height: number) { if (!this.device) { return; } // Refresh depth tex this.startDispatch(); this.depthTexture?.destroy(); this.depthTexture = this.device.createTexture({ size: { width: width, height: height }, format: 'depth24plus', usage: GPUTextureUsage.RENDER_ATTACHMENT }); this.endDispatch(); } translateFormatToGPUType(type: TextureComponentType): string { if (type == 'float4') { return 'vec4'; } if (type == 'float3') { return 'vec3'; } if (type == 'float2') { return 'vec2'; } if (type == 'float') { return 'f32'; } if (type == 'int4') { return 'vec4'; } if (type == 'int3') { return 'vec3'; } if (type == 'int2') { return 'vec2'; } if (type == 'int') { return 'i32'; } if (type == 'uint4') { return 'vec4'; } if (type == 'uint3') { return 'vec3'; } if (type == 'uint2') { return 'vec2'; } if (type == 'uint') { return 'u32'; } throw new Error('Invalid type'); } getOrCreateShader( instance: ShadeupShaderInstance, type: ShaderType, config?: ShaderBindingOptions ): GenericShader { const { device } = this.getGPU(); let key: string = type; if (config) { if (config.attachments) { key += '|' + config.attachments.join(','); } } if (instance.parent.types[key]) { return instance.parent.types[key]; } else { let base = instance.parent.code.webgpu; for (let param of Object.keys(instance.parent.arraySizes)) { base = base.replace(`%${param}_size%`, instance.parent.arraySizes[param]); // console.log(base, `%${param}_size%`); } if ( instance.parent.params.webgpu.globals.length == 0 && instance.parent.params.webgpu.locals.length == 0 ) { base = base.replace(`/*SHADEUP_UNIFORM_STRUCT_START*/`, ''); } if (instance) { for (let key of Object.keys(instance.bindings)) { let value = instance.bindings[key]; let isArrayTex = false; if ( value instanceof ShadeupTexture2d || (Array.isArray(value) && value.length > 0 && value[0] instanceof ShadeupTexture2d) ) { if (Array.isArray(value)) { if (value.length == 0) { throw new Error('Invalid array length'); } else { if (value[0] instanceof ShadeupTexture2d) { value = value[0]; isArrayTex = true; } } } // Replace %WRITE_TYPE_X% with the correct type let name = `%WRITE_TYPE_${key}%`; let texFormat = (value.adapter as WebGPUAdapter).gpuTextureFormat; base = base.replace(name, texFormat); if (texFormat == 'depth24plus' || texFormat == 'depth32float') { base = base.replace( `var ${key}_texture: texture_2d${isArrayTex ? '_array' : ''}<${ value.innerType.startsWith('float') ? 'f32' : value.innerType.startsWith('int') ? 'i32' : 'u32' }>`, `var ${key}_texture: texture_depth_2d${isArrayTex ? '_array' : ''}` ); // .replace( // new RegExp( // `@group\\(%GROUP_INDEX%\\) @binding\\(\\d\\) var ${key}: sampler;`, // 'g' // ), // '' // ); // Replace texture loads let startIndexes = base.matchAll(new RegExp(`textureLoad\\(${key}_texture, `, 'g')); for (let match of startIndexes) { let balance = 0; let hitFirst = false; for (let i = match.index ?? 0; i < base.length; i++) { let count; if (base[i] == '(') { balance++; hitFirst = true; } if (base[i] == ')') { balance--; } if (balance == 0 && hitFirst) { base = base.substring(0, i + 1) + base.substring(i + 3, base.length); break; } } } // Replace samples startIndexes = base.matchAll(new RegExp(`textureSample\\(${key}_texture, `, 'g')); let replaces = []; for (let match of startIndexes) { let balance = 0; let hitFirst = false; for (let i = match.index ?? 0; i < base.length; i++) { let count; if (base[i] == '(') { balance++; hitFirst = true; } if (base[i] == ')') { balance--; } if (balance == 0 && hitFirst) { replaces.push(base.substring(match.index!, i)); break; } } } for (let replace of replaces) { base = base.replace(replace, 'vec4(' + replace + ')'); } } } } } if (type == 'compute') { base = base.replaceAll('%GROUP_INDEX%', '0'); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/', ` struct _ComputeUniformInput { _vtex_canvas: vec2, }; @group(0) @binding(0) var _compute_uniform_input: _ComputeUniformInput; `.replace(/\t\n/g, '') ); base = base.replace(`/*__SHADEUP_TEMPLATE_OUTPUT*/`, `void`); base = base.replace( `/*__SHADEUP_TEMPLATE_INPUT*/`, ` @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_id) local_invocation_id : vec3, @builtin(global_invocation_id) global_invocation_id : vec3, @builtin(local_invocation_index) local_invocation_index: u32, @builtin(num_workgroups) num_workgroups: vec3 `.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/', `var _i_in: ShaderInput; _i_in.groupId = vec3(workgroup_id); _i_in.groupSize = vec3(num_workgroups); _i_in.localId = vec3(local_invocation_id); _i_in.globalId = vec3(global_invocation_id); `.replace(/\t\n/g, '') ); base = base.replace('/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/', ``.replace(/\t\n/g, '')); } else if (type == 'vertex') { base = base.replaceAll('%GROUP_INDEX%', '1'); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/', ` struct _VertexShaderOutput { @builtin(position) position: vec4, @location(0) normal: vec3, @location(1) tangent: vec3, @location(2) bitangent: vec3, @location(3) uv: vec2, @location(4) color: vec4, @location(5) @interpolate(flat) instanceIndex: u32, @location(6) worldPosition: vec3, ${instance.parent.params.webgpu.attributeOutput} }; struct _VertexUniformInput { _vtex_canvas: vec2, }; @group(0) @binding(0) var _vertex_uniform_input: _VertexUniformInput; @vertex `.replace(/\t\n/g, '') ); base = base.replace(`/*__SHADEUP_TEMPLATE_OUTPUT*/`, `_VertexShaderOutput`); base = base.replace( `/*__SHADEUP_TEMPLATE_INPUT*/`, ` @builtin(vertex_index) vertexIndex: u32, @builtin(instance_index) instanceIndex: u32, @location(0) position: vec3, @location(1) normal: vec3, @location(2) tangent: vec3, @location(3) bitangent: vec3, @location(4) uv: vec2, @location(5) color: vec4 `.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/', `var _i_out: _VertexShaderOutput; _i_out.position = vec4(position, 1.0); _i_out.normal = normal; _i_out.tangent = tangent; _i_out.bitangent = bitangent; _i_out.uv = uv; _i_out.color = color; _i_out.instanceIndex = instanceIndex; var _i_in: ShaderInput; _i_in.position = position; _i_in.normal = normal; _i_in.tangent = tangent; _i_in.bitangent = bitangent; _i_in.vertexIndex = i32(vertexIndex); _i_in.instanceIndex = i32(instanceIndex); _i_in.uv = uv; _i_in.color = color; _i_in.screen = vec2(0, 0); `.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/', ` // _i_out.position = vec4(_i_out.position.x, _i_out.position.y, (1.0 + _i_out.position.z) / 2.0, _i_out.position.w); _i_out.worldPosition = position; return _i_out;`.replace(/\t\n/g, '') ); } else if (type == 'vertex-indexed') { base = base.replaceAll('%GROUP_INDEX%', '1'); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/', ` struct _VertexShaderOutput { @builtin(position) position: vec4, @location(0) normal: vec3, @location(1) tangent: vec3, @location(2) bitangent: vec3, @location(3) uv: vec2, @location(4) color: vec4, @location(5) @interpolate(flat) instanceIndex: u32, @location(6) worldPosition: vec3, ${instance.parent.params.webgpu.attributeOutput} }; struct _VertexUniformInput { _vtex_canvas: vec2, }; @group(0) @binding(0) var _vertex_uniform_input: _VertexUniformInput; @vertex `.replace(/\t\n/g, '') ); base = base.replace(`/*__SHADEUP_TEMPLATE_OUTPUT*/`, `_VertexShaderOutput`); base = base.replace( `/*__SHADEUP_TEMPLATE_INPUT*/`, ` @builtin(vertex_index) vertexIndex: u32, @builtin(instance_index) instanceIndex: u32, `.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/', `var _i_out: _VertexShaderOutput; _i_out.position = vec4(0.0, 0.0, 0.0, 1.0); _i_out.normal = vec3(0.0, 0.0, 0.0); _i_out.tangent = vec3(0.0, 0.0, 0.0); _i_out.bitangent = vec3(0.0, 0.0, 0.0); _i_out.uv = vec2(0.0, 0.0); _i_out.color = vec4(0.0, 0.0, 0.0, 0.0); _i_out.instanceIndex = instanceIndex; var _i_in: ShaderInput; _i_in.position = vec3(0.0, 0.0, 0.0); _i_in.normal = vec3(0.0, 0.0, 0.0); _i_in.tangent = vec3(0.0, 0.0, 0.0); _i_in.bitangent = vec3(0.0, 0.0, 0.0); _i_in.vertexIndex = i32(vertexIndex); _i_in.instanceIndex = i32(instanceIndex); _i_in.uv = vec2(0.0, 0.0); _i_in.color = vec4(0.0, 0.0, 0.0, 0.0); _i_in.screen = vec2(0, 0); `.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/', ` // _i_out.position = vec4(_i_out.position.x, _i_out.position.y, (1.0 + _i_out.position.z) / 2.0, _i_out.position.w); // _i_out.worldPosition = position; return _i_out;`.replace(/\t\n/g, '') ); } else { let headerStr = ''; if (config?.attachments) { let i = 0; headerStr += 'struct _ShaderFragmentOutput {\n'; for (let attachment of config.attachments) { headerStr += `@location(${i}) attachment${i}: ${this.translateFormatToGPUType( attachment )},\n`; i++; } headerStr += '\n};'; } base = base.replaceAll('%GROUP_INDEX%', '0'); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/', ` struct _VertexShaderOutput { @builtin(position) position: vec4, @location(0) normal: vec3, @location(1) tangent: vec3, @location(2) bitangent: vec3, @location(3) uv: vec2, @location(4) color: vec4, @location(5) @interpolate(flat) instanceIndex: u32, @location(6) worldPosition: vec3, ${instance.parent.params.webgpu.attributeInput} }; ${headerStr} struct _FragmentUniformInput { _vtex_canvas: vec2, }; @group(0) @binding(0) var _fragment_uniform_input: _FragmentUniformInput; @fragment `.replace(/\t\n/g, '') ); base = base.replace( `/*__SHADEUP_TEMPLATE_OUTPUT*/`, config?.attachments ? `_ShaderFragmentOutput` : `@location(0) vec4` ); base = base.replace( `/*__SHADEUP_TEMPLATE_INPUT*/`, ` _frag_in: _VertexShaderOutput `.replace(/\t\n/g, '') ); let writeCustoms = instance.parent.params.webgpu.attributeInput.split('@location').length; let extra = ''; if (writeCustoms >= 2) { for (let i = 0; i < writeCustoms - 1; i++) { extra += `_i_in.custom${i} = _frag_in.custom${i};\n`; } } base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/', `var _i_out: ${config?.attachments ? '_ShaderFragmentOutput' : 'ShaderOutput'}; var _i_in: ShaderInput; _i_in.position = _frag_in.worldPosition; _i_in.clipPosition = _frag_in.position; _i_in.normal = _frag_in.normal; _i_in.tangent = _frag_in.tangent; _i_in.bitangent = _frag_in.bitangent; _i_in.uv = _frag_in.uv; _i_in.color = _frag_in.color; _i_in.screen = vec2(_frag_in.position.x, _frag_in.position.y); _i_in.instanceIndex = i32(_frag_in.instanceIndex); ${extra} `.replace(/\t\n/g, '') ); base = base.replace( '/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/', `return ${config?.attachments ? '_i_out' : '_i_out.color'};`.replace(/\t\n/g, '') ); } this.startDispatch(); let shader = device.createShaderModule({ code: base }); this.endDispatch(); if (!shader) throw new Error('Failed to create shader'); instance.version++; let gShader = new GenericShader(base, type); gShader.payload = shader; gShader.parent = instance.parent; instance.parent.types[key] = gShader; return gShader; } } createShader(code: ShaderCodeMapping, type: ShaderType) { const { device } = this.getGPU(); if (type == 'compute') { let gComputeShader = new GenericShader(code.webgl, type); gComputeShader.payload = code.software; gComputeShader.parent = null; return gComputeShader; } this.startDispatch(); let shader = device.createShaderModule({ code: code.webgpu }); // shader.getCompilationInfo().then((info) => { // console.log(info); // }); this.endDispatch(); if (!shader) { console.error('Failed to create shader'); throw new Error('Failed to create shader'); } let gShader = new GenericShader(code.webgpu, type); gShader.payload = shader; gShader.parent = null; return gShader; } clear(immediate = false, color: number | [number, number, number, number] | 'auto' = 'auto') { this.enqueueCommand((encoder) => { const { device } = this.getGPU(); if (!this.depthTexture) return; const textureView = this.getTexture().createView(); if (this.gpuTextureFormat == 'depth24plus' || this.gpuTextureFormat == 'depth32float') { const clearPassDesc: GPURenderPassDescriptor = { colorAttachments: [], depthStencilAttachment: { view: this.getTexture().createView(), depthClearValue: typeof color === 'number' ? color : 1.0, depthLoadOp: 'clear', depthStoreOp: 'store' } }; const passEncoder = encoder.beginRenderPass(clearPassDesc); passEncoder.end(); } else { const clearPassDesc: GPURenderPassDescriptor = { colorAttachments: [ { view: textureView, clearValue: Array.isArray(color) ? { r: color[0], g: color[1], b: color[2], a: color[3] } : { r: 0, g: 0, b: 0, a: 0 }, storeOp: 'store', loadOp: 'clear' } ], depthStencilAttachment: { view: this.depthTexture.createView(), depthClearValue: 1.0, depthLoadOp: 'clear', depthStoreOp: 'store' } }; const passEncoder = encoder.beginRenderPass(clearPassDesc); passEncoder.end(); } }, immediate); } fill(color: [number, number, number, number], immediate = false) { this.enqueueCommand((encoder) => { const { device } = this.getGPU(); if (!this.depthTexture) return; const textureView = this.getTexture().createView({ format: this.gpuTextureFormat }); const clearPassDesc: GPURenderPassDescriptor = { colorAttachments: [ { view: textureView, clearValue: { r: color[0], g: color[1], b: color[2], a: color[3] }, storeOp: 'store', loadOp: 'clear' } ], depthStencilAttachment: { view: this.depthTexture.createView(), depthClearValue: 1.0, depthLoadOp: 'clear', depthStoreOp: 'store' } }; const passEncoder = encoder.beginRenderPass(clearPassDesc); passEncoder.end(); }, immediate); } unbindTexture(texture: ShadeupTexture2d) {} getOrCreateMeshData(mesh: Mesh) { const { device } = this.getGPU(); if (mesh.symbol == null) mesh.symbol = Symbol(); if ((mesh as any).$__gpuMeshData) { return (mesh as any).$__gpuMeshData as WebGPUMeshData; } else { let meshVertices = mesh.getVertices(); let meshIndices = mesh.getTriangles(); let meshNormals = mesh.getNormals(); let meshTangents = mesh.getTangents(); let meshBitangents = mesh.getBitangents(); let meshUVs = mesh.getUVs(); let meshColors = mesh.getColors(); let vertexCount = meshVertices.length; let vertexData = new Float32Array(vertexCount * (3 + 3 + 3 + 3 + 2 + 4)); let indexData = new Uint32Array(meshIndices.length); let offset = 0; for (let i = 0; i < vertexCount; i++) { vertexData[offset++] = meshVertices[i][0]; vertexData[offset++] = meshVertices[i][1]; vertexData[offset++] = meshVertices[i][2]; if (meshNormals[i]) { vertexData[offset++] = meshNormals[i][0]; vertexData[offset++] = meshNormals[i][1]; vertexData[offset++] = meshNormals[i][2]; } else { vertexData[offset++] = 0; vertexData[offset++] = 0; vertexData[offset++] = 0; } if (meshTangents[i]) { vertexData[offset++] = meshTangents[i][0]; vertexData[offset++] = meshTangents[i][1]; vertexData[offset++] = meshTangents[i][2]; } else { vertexData[offset++] = 0; vertexData[offset++] = 0; vertexData[offset++] = 0; } if (meshBitangents[i]) { vertexData[offset++] = meshBitangents[i][0]; vertexData[offset++] = meshBitangents[i][1]; vertexData[offset++] = meshBitangents[i][2]; } else { vertexData[offset++] = 0; vertexData[offset++] = 0; vertexData[offset++] = 0; } if (meshUVs[i]) { vertexData[offset++] = meshUVs[i][0]; vertexData[offset++] = meshUVs[i][1]; } else { vertexData[offset++] = 0; vertexData[offset++] = 0; } if (meshColors[i]) { vertexData[offset++] = meshColors[i][0]; vertexData[offset++] = meshColors[i][1]; vertexData[offset++] = meshColors[i][2]; vertexData[offset++] = meshColors[i][3]; } else { vertexData[offset++] = 0; vertexData[offset++] = 0; vertexData[offset++] = 0; vertexData[offset++] = 0; } } for (let i = 0; i < meshIndices.length; i++) { indexData[i] = meshIndices[i]; } let vertexBuffer = device.createBuffer({ size: vertexData.byteLength, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }); let indexBuffer = device.createBuffer({ size: indexData.byteLength, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST }); device.queue.writeBuffer(vertexBuffer, 0, vertexData); device.queue.writeBuffer(indexBuffer, 0, indexData); let meshData = new WebGPUMeshData( mesh, vertexBuffer, indexBuffer, vertexCount, meshIndices.length ); (mesh as any).$__gpuMeshData = meshData; return meshData; } } flushStorage() { const { device } = this.getGPU(); this.startDispatch(); if (this.storageDirty && this.texture) { let encoder = device.createCommandEncoder(); encoder.copyTextureToTexture( { texture: this.getStorageTexture() }, { texture: this.getTexture() }, { width: this.texture.width, height: this.texture.height } ); device.queue.submit([encoder.finish()]); this.storageDirty = false; } this.endDispatch(); } buildUniformKey(generatedUniforms: GeneratedUniforms): (number | string)[] { let key = []; const KEY_TYPES = { BINDING: 1241253932, MARK: 153925923059, SAMPLER: 1241253932, TEXTURE: 153925923059, BUFFER: 1241253932 }; key.push(KEY_TYPES.BINDING, 0, KEY_TYPES.MARK); if (generatedUniforms.size > 0) { key.push(KEY_TYPES.BINDING, 1, KEY_TYPES.MARK); } if (generatedUniforms.special) for (let s of generatedUniforms.special) { if (s.type == 'sampler2D') { let gpuFormat = (s.value?.texture.adapter as WebGPUAdapter).gpuTextureFormat; let texInner = s.value?.texture?.innerType ?? 'float4'; let filterMode = texInner == 'uint8' ? 'filtering' : 'non-filtering'; if (s.access == 'sample_write') { key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index, gpuFormat, KEY_TYPES.MARK); key.push(KEY_TYPES.BINDING, KEY_TYPES.SAMPLER, s.index + 1, filterMode, KEY_TYPES.MARK); key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index + 2, KEY_TYPES.MARK); } else if (s.access == 'write') { key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index, gpuFormat, KEY_TYPES.MARK); key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index + 1, gpuFormat, KEY_TYPES.MARK); } else if (s.access == 'sample' || s.access == 'read') { key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index, gpuFormat, KEY_TYPES.MARK); key.push(KEY_TYPES.BINDING, KEY_TYPES.SAMPLER, s.index + 1, filterMode, KEY_TYPES.MARK); } } else if (s.type == 'sampler2DArray') { if (!s.value?.textures[0]) continue; let firstTexture = s.value?.textures[0]; let gpuFormat = (firstTexture.adapter as WebGPUAdapter).gpuTextureFormat; let texInner = firstTexture.innerType ?? 'float4'; let filterMode = texInner == 'uint8' ? 'filtering' : 'non-filtering'; if (s.access == 'sample_write') { key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index, gpuFormat, KEY_TYPES.MARK); key.push(KEY_TYPES.BINDING, KEY_TYPES.SAMPLER, s.index + 1, filterMode, KEY_TYPES.MARK); key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index + 2, KEY_TYPES.MARK); } else if (s.access == 'write') { key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index, gpuFormat, KEY_TYPES.MARK); key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index + 1, gpuFormat, KEY_TYPES.MARK); } else if (s.access == 'sample' || s.access == 'read') { key.push(KEY_TYPES.BINDING, KEY_TYPES.TEXTURE, s.index, gpuFormat, KEY_TYPES.MARK); key.push(KEY_TYPES.BINDING, KEY_TYPES.SAMPLER, s.index + 1, filterMode, KEY_TYPES.MARK); } key.push('len', s.value.textures.length); } else if (s.type == 'array') { key.push(KEY_TYPES.BINDING, KEY_TYPES.BUFFER, s.index, 3623, KEY_TYPES.MARK); } else if (s.type == 'atomic') { key.push(KEY_TYPES.BINDING, KEY_TYPES.BUFFER, s.index, 124, KEY_TYPES.MARK); } else if (s.type == 'buffer') { key.push(KEY_TYPES.BINDING, KEY_TYPES.BUFFER, s.index, 111, s.access, KEY_TYPES.MARK); } } return key; } bindGroupLayoutCounter = 0; buildUniformsForPipeline( shader: GenericShader & { webgpuUniformCache?: LRUCache; }, generatedUniforms: GeneratedUniforms, baseUniformBuffer: GPUBuffer, stage: number ) { // We need to cache bind group layouts based on the uniforms passed in // Prepass will build a lightweight key for the uniforms passed in // If the key is the same, we can reuse the bind group layout // Otherwise, we need to rebuild the bind group layout and pipeline // We also need to cache the uniform buffer if possible // We can build a create a buffer locally on the cpu and compare it to the previous buffer // If the buffer is the same, we can reuse the buffer // Otherwise, we need to rebuild the buffer and bind group layout and pipeline let key = this.buildUniformKey(generatedUniforms).join('|'); const { device } = this.getGPU(); let commands: PipelinePreDispatchCommands = []; if (generatedUniforms.special) { for (let s of generatedUniforms.special) { if (s.type == 'sampler2D') { commands.push((encoder) => { if (s.value && 'texture' in s.value) { if (s.value?.texture.adapter && s.value.texture.adapter instanceof WebGPUAdapter) { if (s.value.texture.adapter.storageDirty) { this.trace('copyWritableTextureToReadable', { texture: s.value.texture }); encoder.copyTextureToTexture( { texture: s.value.texture.adapter.getStorageTexture() }, { texture: s.value.texture.adapter.getTexture() }, { width: s.value.texture.size[0], height: s.value.texture.size[1] } ); s.value.texture.adapter.storageDirty = false; s.value.texture.cpuReadDirty = true; } } s.value?.texture.flush(false); } }); let texInner = s.value?.texture?.innerType ?? 'float4'; if (s.access == 'sample_write') { // No op } else if (s.access == 'write') { if (s.value?.texture.adapter && s.value.texture.adapter instanceof WebGPUAdapter) { s.value.texture.adapter.pendingWrites++; } commands.push((encoder) => { if (s.value && 'texture' in s.value) { if (s.value?.texture.adapter && s.value.texture.adapter instanceof WebGPUAdapter) { this.trace('markWritableTextureDirty', { texture: s.value.texture }); s.value.texture.adapter.storageDirty = true; s.value.texture.adapter.pendingWrites--; } } }); } else if (s.access == 'sample' || s.access == 'read') { // No op } } else if (s.type == 'sampler2DArray') { let needsNewTexture = false; if (s.value && 'textures' in s.value) { if (!s.value?.textures.$arrTexture) { needsNewTexture = true; } else { if ( s.value.textures[0].adapter.getTexture().usage != s.value.textures.$arrTexture.usage ) { needsNewTexture = true; } if ( s.value.textures[0].adapter.getTexture().format != s.value.textures.$arrTexture.format ) { needsNewTexture = true; } if ( s.value.textures[0].adapter.getTexture().width != s.value.textures.$arrTexture.width ) { needsNewTexture = true; } if ( s.value.textures[0].adapter.getTexture().height != s.value.textures.$arrTexture.height ) { needsNewTexture = true; } if (s.value.textures.length != s.value.textures.$arrTexture.depthOrArrayLayers) { needsNewTexture = true; } } if (needsNewTexture) { if (s.value.textures.$arrTexture) { let oldTex = s.value.textures.$arrTexture; this.enqueueCleanupCommand(() => { this.trace('destroyMissizedArrayTexture', { texture: oldTex }); oldTex.destroy(); }); } s.value.textures.$arrTexture = device.createTexture({ size: [ s.value.textures[0].size[0], s.value.textures[0].size[1], s.value.textures.length ], format: (s.value.textures[0].adapter as WebGPUAdapter).gpuTextureFormat, usage: (s.value.textures[0].adapter as WebGPUAdapter).getTexture().usage }); } } commands.push((encoder) => { let arrDirty = false; let texVersions: number[] = []; if (s.value && 'textures' in s.value) { if (s.value.textures.$arrTexture) { if (s.value.textures.$arrTexture.$versions) { texVersions = s.value.textures.$arrTexture.$versions; } } if (texVersions.length != s.value.textures.length) { texVersions = []; for (let i = 0; i < s.value.textures.length; i++) { texVersions.push(-1); } } for (let [i, texture] of s.value.textures.entries()) { if (texture.adapter && texture.adapter instanceof WebGPUAdapter) { if (texture.adapter.storageDirty) { arrDirty = true; encoder.copyTextureToTexture( { texture: texture.adapter.getStorageTexture() }, { texture: texture.adapter.getTexture() }, { width: texture.size[0], height: texture.size[1] } ); texture.adapter.storageDirty = false; texture.cpuReadDirty = true; } if (texture.version != texVersions[i]) { texVersions[i] = texture.version; arrDirty = true; } } texture.flush(false); } if (arrDirty) { s.value.textures.$arrTexture.$versions = texVersions; this.trace('copyToArrayTexture', { texture: s.value.textures.$arrTexture }); for (let [i, texture] of s.value.textures.entries()) { encoder.copyTextureToTexture( { texture: (texture.adapter as WebGPUAdapter).getTexture() }, { texture: s.value.textures.$arrTexture, origin: [0, 0, i] }, { width: texture.size[0], height: texture.size[1], depthOrArrayLayers: 1 } ); } } } }); if (s.value && 'textures' in s.value) { for (let texture of s.value.textures) { let texInner = texture.innerType ?? 'float4'; if (s.access == 'sample_write') { // No op } else if (s.access == 'write') { if (texture.adapter && texture.adapter instanceof WebGPUAdapter) { texture.adapter.pendingWrites++; } commands.push((encoder) => { if (texture.adapter && texture.adapter instanceof WebGPUAdapter) { this.trace('markWritableTextureDirty', { texture: texture }); texture.adapter.storageDirty = true; texture.adapter.pendingWrites--; } }); } else if (s.access == 'sample' || s.access == 'read') { // No op } } } } else if (s.type == 'array') { // No op } else if (s.type == 'atomic') { // No op } else if (s.type == 'buffer') { if (s.value && s.access == 'write') { s.value.pendingWrites++; } commands.push((encoder) => { if (s.value) { let sv = s.value as any; if (sv.cpuWriteDirty) { this.trace('uploadCPUDirtyBuffer', { buffer: s.value }); sv.upload(); } if ((s as any).access == 'write') { this.trace('markBufferDirty', { buffer: s.value }); sv.cpuReadDirty = true; sv.pendingWrites--; } } }); // No op } } } let bindGroupLayout: GPUBindGroupLayout | null = null; let bindGroup: GPUBindGroup | null = null; if (!shader.webgpuUniformCache) { shader.webgpuUniformCache = new LRUCache({ ...lruUniformOptions, dispose(value, key) { value.uniformBuffer.destroy(); } }); } let cache: ShaderUniformCachePayload | undefined = undefined; if (shader.webgpuUniformCache) { cache = shader.webgpuUniformCache.get(key); let matches = true; if (!cache) { matches = false; } else { // for (let i = 0; i < key.length; i++) { // if (shader.webgpuUniformCache.key[i] != key[i]) { // matches = false; // break; // } // } } if (matches && cache) { bindGroupLayout = cache.bindGroupLayout; bindGroup = cache.bindGroup; } } if (!bindGroupLayout) { this.startDispatch(); bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: stage, buffer: { minBindingSize: 0 } }, ...(generatedUniforms.size > 0 ? [ { binding: 1, visibility: stage, buffer: { minBindingSize: 0 } } ] : []), ...(generatedUniforms.special .map((s) => { if (s.type == 'sampler2D') { let sampleType = (t: string): GPUTextureSampleType => { let gpuFormat = (s.value?.texture.adapter as WebGPUAdapter).gpuTextureFormat; if (gpuFormat == 'depth24plus' || gpuFormat == 'depth32float') { return 'depth'; } if (t == 'uint8') { return 'float'; } if (t.startsWith('int')) { return 'sint'; } else if (t.startsWith('uint')) { return 'uint'; } else if (t.startsWith('float')) { return 'unfilterable-float'; } return 'unfilterable-float'; }; let texInner = s.value?.texture?.innerType ?? 'float4'; let filterMode = texInner == 'uint8' ? 'filtering' : 'non-filtering'; let sampleTypeGPU = sampleType(s.value?.texture?.innerType ?? 'float4'); if (s.access == 'sample_write') { return [ { binding: s.index, visibility: stage, texture: { sampleType: sampleType(texInner), viewDimension: '2d', multisampled: false } } as GPUBindGroupLayoutEntry, { binding: s.index + 1, visibility: stage, sampler: { type: filterMode } } as GPUBindGroupLayoutEntry, { binding: s.index + 2, visibility: stage, storageTexture: { format: (s.value?.texture.adapter as WebGPUAdapter).gpuTextureFormat, access: 'write-only', viewDimension: '2d' } } as GPUBindGroupLayoutEntry ]; } else if (s.access == 'write') { return [ { binding: s.index, visibility: stage, texture: { sampleType: sampleTypeGPU, viewDimension: '2d', multisampled: false } } as GPUBindGroupLayoutEntry, { binding: s.index + 1, visibility: stage, storageTexture: { format: (s.value?.texture.adapter as WebGPUAdapter).gpuTextureFormat, access: 'write-only', viewDimension: '2d' } } as GPUBindGroupLayoutEntry ]; } else if (s.access == 'sample' || s.access == 'read') { return [ { binding: s.index, visibility: stage, texture: { sampleType: sampleTypeGPU, viewDimension: '2d', multisampled: false } } as GPUBindGroupLayoutEntry, { binding: s.index + 1, visibility: stage, sampler: { type: filterMode } } as GPUBindGroupLayoutEntry ]; } } else if (s.type == 'sampler2DArray') { if (!s.value?.textures[0]) return []; let firstTexture: ShadeupTexture2d = s.value?.textures[0]!; let sampleType = (t: string): GPUTextureSampleType => { let gpuFormat = (firstTexture.adapter as WebGPUAdapter).gpuTextureFormat; if (gpuFormat == 'depth24plus' || gpuFormat == 'depth32float') { return 'depth'; } if (t == 'uint8') { return 'float'; } if (t.startsWith('int')) { return 'sint'; } else if (t.startsWith('uint')) { return 'uint'; } else if (t.startsWith('float')) { return 'unfilterable-float'; } return 'unfilterable-float'; }; let texInner = firstTexture.innerType ?? 'float4'; let filterMode = texInner == 'uint8' ? 'filtering' : 'non-filtering'; let sampleTypeGPU = sampleType(firstTexture.innerType ?? 'float4'); if (s.access == 'sample_write') { return [ { binding: s.index, visibility: stage, texture: { sampleType: sampleType(texInner), viewDimension: '2d-array', multisampled: false } } as GPUBindGroupLayoutEntry, { binding: s.index + 1, visibility: stage, sampler: { type: filterMode } } as GPUBindGroupLayoutEntry, { binding: s.index + 2, visibility: stage, storageTexture: { format: (firstTexture.adapter as WebGPUAdapter).gpuTextureFormat, access: 'write-only', viewDimension: '2d-array' } } as GPUBindGroupLayoutEntry ]; } else if (s.access == 'write') { return [ { binding: s.index, visibility: stage, texture: { sampleType: sampleTypeGPU, viewDimension: '2d-array', multisampled: false } } as GPUBindGroupLayoutEntry, { binding: s.index + 1, visibility: stage, storageTexture: { format: (firstTexture.adapter as WebGPUAdapter).gpuTextureFormat, access: 'write-only', viewDimension: '2d-array' } } as GPUBindGroupLayoutEntry ]; } else if (s.access == 'sample' || s.access == 'read') { return [ { binding: s.index, visibility: stage, texture: { sampleType: sampleTypeGPU, viewDimension: '2d-array', multisampled: false } } as GPUBindGroupLayoutEntry, { binding: s.index + 1, visibility: stage, sampler: { type: filterMode } } as GPUBindGroupLayoutEntry ]; } } else if (s.type == 'array') { return [ { binding: s.index, visibility: stage, buffer: { type: 'read-only-storage' } } ]; } else if (s.type == 'atomic') { return [ { binding: s.index, visibility: stage, buffer: { type: 'storage' } } ]; } else if (s.type == 'buffer') { return [ { binding: s.index, visibility: stage, buffer: { type: s.access == 'read' ? 'read-only-storage' : 'storage' } } ]; } }) .flat() as any) ] }); (bindGroupLayout as any).$__gpuKey = this.bindGroupLayoutCounter++; this.endDispatch(); } let outUniformBuffer = cache?.uniformBuffer; let outSpecialBuffers = cache?.specialBuffers; if (cache) { if (cache.cachedUniforms) { let matches = generatedUniforms.data.byteLength == cache.cachedUniforms.byteLength; let uintView = new Uint8Array(generatedUniforms.data); let uintView2 = new Uint8Array(cache.cachedUniforms); if (matches) { for (let i = 0; i < uintView.length; i++) { if (uintView[i] != uintView2[i]) { matches = false; break; } } } if (!matches) { if (outUniformBuffer) { // Clean it up after the frame let oldBuffer = outUniformBuffer; this.enqueueCleanupCommand(() => { oldBuffer.destroy(); }); } bindGroup = null; outUniformBuffer = undefined; } } } let specialsKey: (number | string | Symbol)[] = []; let alwaysDirty = false; for (let special of generatedUniforms.special) { if (special.type == 'sampler2D') { if (!special.value || !('texture' in special.value)) continue; let tex = special.value.texture; if (tex.image) { let texture; if (tex.adapter instanceof WebGPUAdapter && tex.adapter.texture) { let texCtx = tex.adapter.getTexture(); texture = texCtx; if (!texture) continue; specialsKey.push(5623462, special.index, tex.symbol, tex.innerType, special.access); } } else { return; } } else if (special.type == 'sampler2DArray') { if (!special.value || !('textures' in special.value)) continue; let tex = special.value.textures[0]; if (tex) { if (tex.image) { let texture; if (tex.adapter instanceof WebGPUAdapter && tex.adapter.texture) { let texCtx = tex.adapter.getTexture(); texture = texCtx; if (!texture) continue; specialsKey.push( 5653223462, special.index, tex.symbol, tex.innerType, special.access ); } } } else { return; } } else if (special.type == 'array' && special.value) { specialsKey.push(5523462, special.index); alwaysDirty = true; } else if (special.type == 'buffer' && special.value) { specialsKey.push(1253462, special.index, special.access, special.value.symbol); } else if (special.type == 'atomic' && special.value) { specialsKey.push(125342, special.index); alwaysDirty = true; } else { throw new Error(`Unknown special type ${special.type}`); } } let specialsDirty = false; if (cache) { if (cache.specialsKey.length != specialsKey.length) { specialsDirty = true; } else { for (let i = 0; i < specialsKey.length; i++) { if (cache.specialsKey[i] != specialsKey[i]) { specialsDirty = true; break; } } } } else { specialsDirty = true; } let specialEntries: GPUBindGroupEntry[] | undefined = undefined; if (cache) { specialEntries = cache.specialEntries; } if (alwaysDirty || specialsDirty) { outSpecialBuffers = undefined; specialEntries = undefined; } if (!bindGroup || !outUniformBuffer || !outSpecialBuffers || !specialEntries) { let outEntries: GPUBindGroupEntry[] = [ { binding: 0, resource: { buffer: baseUniformBuffer } } ]; if (!outSpecialBuffers || !specialEntries) { outSpecialBuffers = []; specialEntries = []; for (let special of generatedUniforms.special) { if (special.type == 'sampler2D') { // TODO: Support samplers // fragmentEntries.push({ // binding: special.index, // resource: special.value // }); if (!special.value || !('texture' in special.value)) continue; let tex = special.value.texture; if (tex.image) { let texture; if (tex.adapter instanceof WebGPUAdapter && tex.adapter.texture) { let texCtx = tex.adapter.getTexture(); texture = texCtx; if (!texture) continue; let filterable = tex.innerType == 'uint8'; if (special.access == 'sample_write') { const sampler = device.createSampler( filterable ? { magFilter: 'linear', minFilter: 'linear' } : {} ); specialEntries.push({ binding: special.index, resource: texture.createView({ format: tex.adapter.gpuTextureFormat }) }); specialEntries.push({ binding: special.index + 1, resource: sampler }); specialEntries.push({ binding: special.index + 2, resource: tex.adapter.getStorageTexture().createView() }); } else if (special.access == 'write') { specialEntries.push({ binding: special.index, resource: texture.createView({ format: tex.adapter.gpuTextureFormat }) }); specialEntries.push({ binding: special.index + 1, resource: tex.adapter.getStorageTexture().createView() }); } else if (special.access == 'read' || special.access == 'sample') { const sampler = device.createSampler( filterable ? { magFilter: 'linear', minFilter: 'linear' } : {} ); specialEntries.push({ binding: special.index, resource: texture.createView({ format: tex.adapter.gpuTextureFormat }) }); specialEntries.push({ binding: special.index + 1, resource: sampler }); } } } else { return; } } else if (special.type == 'sampler2DArray') { // TODO: Support samplers // fragmentEntries.push({ // binding: special.index, // resource: special.value // }); if (!special.value || !('textures' in special.value)) continue; if (special.value.textures.$arrTexture) { if (special.value.textures.$arrTexture instanceof GPUTexture) { let tex = special.value.textures[0]; if (!tex) return; let texture: GPUTexture = special.value.textures.$arrTexture as any; let filterable = tex.innerType == 'uint8'; if (special.access == 'sample_write') { const sampler = device.createSampler( filterable ? { magFilter: 'linear', minFilter: 'linear' } : {} ); specialEntries.push({ binding: special.index, resource: texture.createView({ format: tex.adapter.gpuTextureFormat }) }); specialEntries.push({ binding: special.index + 1, resource: sampler }); specialEntries.push({ binding: special.index + 2, resource: tex.adapter.getStorageTexture().createView() }); throw new Error('Writing to texture arrays is not supported yet'); } else if (special.access == 'write') { specialEntries.push({ binding: special.index, resource: texture.createView({ format: tex.adapter.gpuTextureFormat }) }); specialEntries.push({ binding: special.index + 1, resource: tex.adapter.getStorageTexture().createView() }); throw new Error('Writing to texture arrays is not supported yet'); } else if (special.access == 'read' || special.access == 'sample') { const sampler = device.createSampler( filterable ? { magFilter: 'linear', minFilter: 'linear' } : {} ); specialEntries.push({ binding: special.index, resource: texture.createView({ format: tex.adapter.gpuTextureFormat, arrayLayerCount: special.value.textures.length, baseArrayLayer: 0, dimension: '2d-array' }) }); specialEntries.push({ binding: special.index + 1, resource: sampler }); } } } } else if (special.type == 'array' && special.value) { let buffer = device.createBuffer({ size: special.value.size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); outSpecialBuffers.push(buffer); specialEntries.push({ binding: special.index, resource: { buffer } }); } else if (special.type == 'buffer' && special.value) { let buf = this.getOrCreateBuffer(special.value, this.genericBufferFlags()); outSpecialBuffers.push(buf); specialEntries.push({ binding: special.index, resource: { buffer: buf } }); } else if (special.type == 'atomic' && special.value) { let buf = device.createBuffer({ size: 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); outSpecialBuffers.push(buf); specialEntries.push({ binding: special.index, resource: { buffer: buf } }); } else { throw new Error(`Unknown special type ${special.type}`); } } } let needsUniformWrite = false; if (!outUniformBuffer) { outUniformBuffer = device.createBuffer({ size: generatedUniforms.size, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); needsUniformWrite = true; } if (generatedUniforms.size > 0) { outEntries.push({ binding: 1, resource: { buffer: outUniformBuffer } }); if (needsUniformWrite) device.queue.writeBuffer(outUniformBuffer, 0, generatedUniforms.data); } for (let i = 0; i < specialEntries.length; i++) { outEntries.push(specialEntries[i]); } let bufCounter = 0; for (let i = 0; i < generatedUniforms.special.length; i++) { let special = generatedUniforms.special[i]; if (special.type == 'array' && special.value) { device.queue.writeBuffer(outSpecialBuffers[bufCounter++], 0, special.value.buffer); } } bindGroup = device.createBindGroup({ layout: bindGroupLayout, entries: outEntries }); } if (cache) { cache.key = key; cache.bindGroupLayout = bindGroupLayout; cache.bindGroup = bindGroup; cache.uniformBuffer = outUniformBuffer; cache.specialBuffers = outSpecialBuffers; cache.cachedUniforms = generatedUniforms.data; cache.specialsKey = specialsKey; cache.specialEntries = specialEntries; } else { shader.webgpuUniformCache.set(key, { key, bindGroupLayout, bindGroup, uniformBuffer: outUniformBuffer, specialBuffers: outSpecialBuffers, cachedUniforms: generatedUniforms.data, specialsKey, specialEntries }); } return { bindGroupLayout, bindGroup, uniformBuffer: outUniformBuffer, specialBuffers: outSpecialBuffers, commands }; } writeStructuredBuffer( structure: UniformValueType, raw: any, buffer: ArrayBuffer, offset: number = 0 ) { let rootObj: { [key: string]: any } = { val: raw }; let queue: [UniformKeyValuePair, any, number | null][] = [[['val', structure], rootObj, null]]; writeBufferStructure(queue, rootObj, buffer, offset); } readStructuredBuffer(structure: UniformValueType, buffer: ArrayBuffer, offset: number = 0): any { if (structure.type == 'array') { let arr = []; if ('staticSize' in structure && structure.staticSize != null) { let elSize = getValueSize(structure.element); for (let i = 0; i < structure.staticSize; i++) { arr.push(this.readStructuredBuffer(structure.element, buffer, offset)); offset += elSize / 4; } return arr; } else { throw new Error(`Unable to read dynamic array`); } } else if (structure.type == 'primitive') { let uview = new Uint32Array(buffer); let iview = new Int32Array(buffer); let fview = new Float32Array(buffer); if (structure.name == 'uint4') { return [uview[offset], uview[offset + 1], uview[offset + 2], uview[offset + 3]]; } else if (structure.name == 'int4') { return [iview[offset], iview[offset + 1], iview[offset + 2], iview[offset + 3]]; } else if (structure.name == 'float4') { return [fview[offset], fview[offset + 1], fview[offset + 2], fview[offset + 3]]; } else if (structure.name == 'uint3') { return [uview[offset], uview[offset + 1], uview[offset + 2]]; } else if (structure.name == 'int3') { return [iview[offset], iview[offset + 1], iview[offset + 2]]; } else if (structure.name == 'float3') { return [fview[offset], fview[offset + 1], fview[offset + 2]]; } else if (structure.name == 'uint2') { return [uview[offset], uview[offset + 1]]; } else if (structure.name == 'int2') { return [iview[offset], iview[offset + 1]]; } else if (structure.name == 'float2') { return [fview[offset], fview[offset + 1]]; } else if (structure.name == 'uint') { return uview[offset]; } else if (structure.name == 'int') { return iview[offset]; } else if (structure.name == 'float') { return fview[offset]; } else if (structure.name == 'bool') { return uview[offset] == 1; } else if (structure.name == 'float2x2') { return (window as any).applyMatrix2x2Methods([ [fview[offset], fview[offset + 1]], [fview[offset + 2], fview[offset + 3]] ]); } else if (structure.name == 'float3x3') { return (window as any).applyMatrix3x3Methods([ [fview[offset], fview[offset + 1], fview[offset + 2]], [fview[offset + 3], fview[offset + 4], fview[offset + 5]], [fview[offset + 6], fview[offset + 7], fview[offset + 8]] ]); } else if (structure.name == 'float4x4') { return (window as any).applyMatrix4x4Methods([ [fview[offset], fview[offset + 1], fview[offset + 2], fview[offset + 3]], [fview[offset + 4], fview[offset + 5], fview[offset + 6], fview[offset + 7]], [fview[offset + 8], fview[offset + 9], fview[offset + 10], fview[offset + 11]], [fview[offset + 12], fview[offset + 13], fview[offset + 14], fview[offset + 15]] ]); } else if (structure.name == 'atomic') { if (structure.element.type == 'primitive') { if (structure.element.name == 'uint') { return (window as any).makeAtomic(uview[offset]); } else if (structure.element.name == 'int') { return (window as any).makeAtomic(iview[offset]); } } } else { throw new Error(`Unable to convert primitive type ${structure.name}`); } } else if (structure.type == 'struct') { let out: any = {}; for (let field of structure.fields) { let size = getValueSize(field[1]); out[field[0]] = this.readStructuredBuffer(field[1], buffer, offset / 4); offset += size; } let clazz = (window as any).__shadeup_structs[structure.name].struct; if (clazz) { return new clazz(out); } } else { throw new Error(`Unable to convert type ${structure.type}`); } } buildComputePipeline( shader: GenericShader, computeUniform: GeneratedUniforms ): ComputePipelinePayload | undefined { const { device } = this.getGPU(); let commands: PipelinePreDispatchCommands = []; const baseUniformValues = this.baseUniformValues; const baseUniformBufferSize = this.baseUniformBufferSize; const baseUniformBuffer = device.createBuffer({ size: baseUniformBufferSize, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); const compute = this.buildUniformsForPipeline( shader, computeUniform, baseUniformBuffer, GPUShaderStage.COMPUTE ); if (!compute) { return; } commands = compute.commands; const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [compute.bindGroupLayout] }); this.startDispatch(); let pipeline = device.createComputePipeline({ label: 'compute pipeline', layout: pipelineLayout, compute: { module: shader.payload, entryPoint: 'main' } }); this.endDispatch(); return { pipeline, bindGroup: compute.bindGroup, baseUniformBuffer, uniformBuffer: compute.uniformBuffer, specialBuffers: compute.specialBuffers, commands }; } cachedPipelines: Map = new Map(); cachedPipelineLayouts: Map = new Map(); setupDrawPipeline( shaders: { fragment: GenericShader; vertex: GenericShader }, fragmentUniform: GeneratedUniforms, vertexUniform: GeneratedUniforms, options: DrawOptions, ignoreVertexLayout: boolean = false ): DrawPipelinePayload | undefined { const { device } = this.getGPU(); if (!this.baseUniformBuffer) { throw new Error('Base uniform buffer not initialized'); } let commands: PipelinePreDispatchCommands = []; const fragment = this.buildUniformsForPipeline( shaders.fragment, fragmentUniform, this.baseUniformBuffer, GPUShaderStage.FRAGMENT ); const vertex = this.buildUniformsForPipeline( shaders.vertex, vertexUniform, this.baseUniformBuffer, GPUShaderStage.VERTEX ); if (!fragment || !vertex) { return; } commands.push(...fragment.commands); commands.push(...vertex.commands); let pipelineLayoutKey = `${shaders.fragment.uniqueSourceKey}_${fragment.bindGroupLayout.$__gpuKey}_${shaders.vertex.uniqueSourceKey}_${vertex.bindGroupLayout.$__gpuKey}`; let pipelineLayout: GPUPipelineLayout; if (this.cachedPipelineLayouts.has(pipelineLayoutKey)) { pipelineLayout = this.cachedPipelineLayouts.get(pipelineLayoutKey)!; } else { pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [fragment.bindGroupLayout, vertex.bindGroupLayout] }); this.cachedPipelineLayouts.set(pipelineLayoutKey, pipelineLayout); } if (!this.depthTexture) { throw new Error('Depth texture not initialized'); } let pipelineKey = pipelineLayoutKey + this.depthTexture.format + options.depthTest + options.depthFormat + options.depthOnly + options.backfaceCulling + options.depthCompare + options.attachments?.length; let pipeline: GPURenderPipeline; if (this.cachedPipelines.has(pipelineKey)) { pipeline = this.cachedPipelines.get(pipelineKey)!; } else { const generateTarget = (adap: WebGPUAdapter) => { return { format: adap.headless ? adap.gpuTextureFormat : 'rgba8unorm', blend: FormatCapabilities[adap.gpuTextureFormat].blendable ? { alpha: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' }, color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' } } : undefined } as GPUColorTargetState; }; const pipelineDescriptor = { vertex: { module: shaders.vertex.payload, entryPoint: 'main', buffers: ignoreVertexLayout ? [] : vertexLayout }, ...(options.depthOnly ? {} : { fragment: { module: shaders.fragment.payload, entryPoint: 'main', targets: options.attachments && options.attachments.length > 0 ? options.attachments.map((att) => generateTarget(att.adapter as WebGPUAdapter)) : [generateTarget(this)] } }), primitive: { topology: 'triangle-list', cullMode: options.backfaceCulling ? 'back' : 'none' }, ...(options.depthTest ? { depthStencil: { depthWriteEnabled: true, depthCompare: options.depthCompare ?? 'less', format: options.depthFormat ?? 'depth24plus' } } : {}), layout: pipelineLayout } as GPURenderPipelineDescriptor; this.startDispatch(); pipeline = device.createRenderPipeline(pipelineDescriptor); this.endDispatch(); this.cachedPipelines.set(pipelineKey, pipeline); } let drawData = { pipeline, bindGroupFragment: fragment.bindGroup, bindGroupVertex: vertex.bindGroup, baseUniformBuffer: this.baseUniformBuffer, vertexUniformBuffer: vertex.uniformBuffer, fragmentUniformBuffer: fragment.uniformBuffer, specialBuffersFragment: fragment.specialBuffers, specialBuffersVertex: vertex.specialBuffers, commands }; return drawData; } buildDrawPipeline( shaders: { fragment: GenericShader; vertex: GenericShader }, fragmentUniform: GeneratedUniforms, vertexUniform: GeneratedUniforms, options: DrawOptions, ignoreVertexLayout: boolean = false ): DrawPipelinePayload | undefined { const { device } = this.getGPU(); let commands: PipelinePreDispatchCommands = []; const baseUniformValues = this.baseUniformValues; const baseUniformBufferSize = this.baseUniformBufferSize; const baseUniformBuffer = device.createBuffer({ size: baseUniformBufferSize, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); const fragment = this.buildUniformsForPipeline( shaders.fragment, fragmentUniform, baseUniformBuffer, GPUShaderStage.FRAGMENT ); const vertex = this.buildUniformsForPipeline( shaders.vertex, vertexUniform, baseUniformBuffer, GPUShaderStage.VERTEX ); if (!fragment || !vertex) { return; } commands.push(...fragment.commands); commands.push(...vertex.commands); const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [fragment.bindGroupLayout, vertex.bindGroupLayout] }); if (!this.depthTexture) { throw new Error('Depth texture not initialized'); } const generateTarget = (adap: WebGPUAdapter) => { return { format: adap.headless ? adap.gpuTextureFormat : 'rgba8unorm', blend: FormatCapabilities[adap.gpuTextureFormat].blendable ? { alpha: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' }, color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha', operation: 'add' } } : undefined } as GPUColorTargetState; }; const pipelineDescriptor = { vertex: { module: shaders.vertex.payload, entryPoint: 'main', buffers: ignoreVertexLayout ? [] : vertexLayout }, ...(options.depthOnly ? {} : { fragment: { module: shaders.fragment.payload, entryPoint: 'main', targets: options.attachments && options.attachments.length > 0 ? options.attachments.map((att) => generateTarget(att.adapter as WebGPUAdapter)) : [generateTarget(this)] } }), primitive: { topology: 'triangle-list', cullMode: 'back' }, ...(options.depthTest ? { depthStencil: { depthWriteEnabled: true, depthCompare: 'less', format: options.depthFormat ?? 'depth24plus' } } : {}), layout: pipelineLayout } as GPURenderPipelineDescriptor; this.startDispatch(); let pipeline = device.createRenderPipeline(pipelineDescriptor); this.endDispatch(); let drawData = { pipeline, bindGroupFragment: fragment.bindGroup, bindGroupVertex: vertex.bindGroup, baseUniformBuffer, vertexUniformBuffer: vertex.uniformBuffer, fragmentUniformBuffer: fragment.uniformBuffer, specialBuffersFragment: fragment.specialBuffers, specialBuffersVertex: vertex.specialBuffers, commands }; return drawData; } getTexture(): GPUTexture { if (!this.headless) { if (this.ctx) { return this.ctx.getCurrentTexture(); } else { throw new Error('No context'); } } else { return this.texture as GPUTexture; } } getStorageTexture(): GPUTexture { const { device } = this.getGPU(); if (!this.storageTexture) { this.startDispatch(); this.storageTexture = device.createTexture({ size: { width: this.headlessWidth, height: this.headlessHeight }, format: this.gpuTextureFormat, dimension: '2d', viewFormats: [this.gpuTextureFormat], usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST }); this.endDispatch(); } return this.storageTexture; } commandQueue: ((encoder: GPUCommandEncoder) => void | undefined | (() => void | undefined))[] = []; cleanupCommands: ((() => void | undefined | (() => void | undefined)) & { $counter: number })[] = []; immediate = false; enqueueCommand( command: (encoder: GPUCommandEncoder) => void | undefined | (() => void | undefined), immediate = false ) { if (this.immediate || immediate) { const { device } = this.getGPU(); this.startDispatch(); let encoder = device.createCommandEncoder(); let result = command(encoder); device.queue.submit([encoder.finish()]); if (result) { result(); } this.endDispatch(); } else { this.commandQueue.push(command); } } enqueueCleanupCommand(command: () => void | undefined | (() => void | undefined)) { let cmd = command as any; cmd.$counter = 10; this.cleanupCommands.push(cmd); } dispatchCompute(dispatch: ShaderDispatch) { this.trace('enqueueCompute', { dispatch }); const { device } = this.getGPU(); if (!dispatch.computeShader) { throw new Error('Dispatch is missing compute shader'); } // this.startDispatch(); let cacheKey = `${dispatch.computeShader.uniqueSourceKey}`; const computeUniform = generateUniforms(dispatch.fragmentUniforms, dispatch.computeShader); let output = this.buildComputePipeline(dispatch.computeShader, computeUniform); this.enqueueCommand((encoder) => { // const encoder = device.createCommandEncoder({ label: 'compute builtin encoder' }); if (output) for (let command of output.commands) { command(encoder); } const pass = encoder.beginComputePass({ label: 'compute builtin pass' }); let baseUniformValues = this.baseUniformValues; let baseUniformBufferSize = this.baseUniformBufferSize; baseUniformValues.set([0, 0], 0); let computeData: ComputePipelinePayload; if (CACHE_PIPELINES) { let cacheValue = this.pipelineCache.get(cacheKey); if (!cacheValue) { let output = this.buildComputePipeline(dispatch.computeShader, computeUniform); if (!output) return; computeData = output; this.pipelineCache.set(cacheKey, computeData); } else { computeData = cacheValue as ComputePipelinePayload; } } else { if (!output) return; computeData = output; } let { pipeline, bindGroup, baseUniformBuffer, uniformBuffer, specialBuffers } = computeData; device.queue.writeBuffer(baseUniformBuffer, 0, baseUniformValues); device.queue.writeBuffer(uniformBuffer, 0, computeUniform.data); let bufCounter = 0; for (let i = 0; i < computeUniform.special.length; i++) { let special = computeUniform.special[i]; if (special.type == 'array' && special.value) { this.trace('writeArray', { special }); device.queue.writeBuffer(specialBuffers[bufCounter++], 0, special.value.buffer); } } pass.setPipeline(pipeline); pass.setBindGroup(0, bindGroup); if (dispatch.indirectBuffer) { pass.dispatchWorkgroupsIndirect( this.getOrCreateBuffer(dispatch.indirectBuffer, GPUBufferUsage.INDIRECT), dispatch.indirectOffset ); } else { pass.dispatchWorkgroups(...dispatch.computeCount); } this.trace('dispatchCompute', { dispatch }); pass.end(); }); // device.queue.submit([encoder.finish()]); // this.endDispatch(); } writeSpecialBuffer(buffer: GPUBuffer, data: Float32Array) { const { device } = this.getGPU(); this.startDispatch(); device.queue.writeBuffer(buffer, 0, data); this.endDispatch(); } beforeScreenDraw() { if (!this.clearEnqueued) { this.enqueueCommand((encoder) => { const { device } = this.getGPU(); if (!this.depthTexture) return; const textureView = this.getTexture().createView(); if (this.gpuTextureFormat == 'depth24plus' || this.gpuTextureFormat == 'depth32float') { const clearPassDesc: GPURenderPassDescriptor = { colorAttachments: [], depthStencilAttachment: { view: textureView, depthClearValue: 1.0, depthLoadOp: 'clear', depthStoreOp: 'store' } }; const passEncoder = encoder.beginRenderPass(clearPassDesc); passEncoder.end(); } else { const clearPassDesc: GPURenderPassDescriptor = { colorAttachments: [ { view: textureView, clearValue: { r: 0, g: 0, b: 0, a: 0 }, storeOp: 'store', loadOp: 'clear' } ], depthStencilAttachment: { view: this.depthTexture.createView(), depthClearValue: 1.0, depthLoadOp: 'clear', depthStoreOp: 'store' } }; const passEncoder = encoder.beginRenderPass(clearPassDesc); passEncoder.end(); } this.clearEnqueued = false; }); this.clearEnqueued = true; } } dispatchDraw( dispatch: ShaderDispatch, options: { depthTest: boolean } = { depthTest: true } ) { this.trace('enqueueDraw', { dispatch, options }); const { device } = this.getGPU(); if (!dispatch.vertexShader || !dispatch.fragmentShader) { throw new Error('Dispatch is missing vertex or fragment shader'); } if (!dispatch.geometry && !dispatch.indirectBuffer) { throw new Error('Dispatch is missing geometry'); } if (!this.depthTexture) { throw new Error('Depth texture not created'); } this.startDispatch(); if (dispatch.overrideDepth) { if (dispatch.overrideDepth.adapter instanceof WebGPUAdapter) { dispatch.overrideDepth.adapter.flush(); } } let fragment = dispatch.fragmentShader; let vertex = dispatch.vertexShader; const fragmentUniform = generateUniforms(dispatch.fragmentUniforms, dispatch.fragmentShader); const vertexUniform = generateUniforms(dispatch.vertexUniforms, dispatch.vertexShader); let cacheKey = `${dispatch.fragmentShader.uniqueSourceKey}|${dispatch.vertexShader.uniqueSourceKey}|${options.depthTest}`; let depthTex = dispatch.overrideDepth ? (dispatch.overrideDepth.adapter as WebGPUAdapter).getTexture() : this.depthTexture; let output = this.setupDrawPipeline( { fragment, vertex }, fragmentUniform, vertexUniform, { ...options, depthFormat: depthTex.format, depthOnly: dispatch.depthOnly, attachments: dispatch.attachments ?? [], depthCompare: dispatch.depthCompare == 'auto' ? 'less' : dispatch.depthCompare, backfaceCulling: dispatch.backfaceCulling } ); this.beforeScreenDraw(); this.enqueueCommand((encoder) => { if (output) for (let command of output.commands) { command(encoder); } let attachments = [] as GPURenderPassColorAttachment[]; if (!dispatch.depthOnly) { if (!dispatch.attachments) { attachments.push({ view: this.getTexture().createView(), storeOp: 'store', loadOp: 'load' }); } else { for (let attachment of dispatch.attachments) { if (attachment.adapter instanceof WebGPUAdapter) { let view = attachment.adapter.getTexture().createView(); attachments.push({ view, storeOp: 'store', loadOp: 'load' }); } } } } let passDescriptor: GPURenderPassDescriptor = { colorAttachments: attachments, ...(options.depthTest ? { depthStencilAttachment: { view: depthTex.createView(), depthClearValue: 1.0, depthLoadOp: 'load', depthStoreOp: 'store' } } : {}) }; const pass = encoder.beginRenderPass(passDescriptor); let myTex = this.getTexture(); // pass.setViewport(0, 0, myTex.width, myTex.height, 0, 1); let baseUniformValues = this.baseUniformValues; let baseUniformBufferSize = this.baseUniformBufferSize; baseUniformValues.set([myTex.width, myTex.height], 0); let drawData: DrawPipelinePayload; if (!output) return; drawData = output; let { pipeline, bindGroupFragment, bindGroupVertex, baseUniformBuffer, vertexUniformBuffer, fragmentUniformBuffer, specialBuffersFragment, specialBuffersVertex } = drawData; pass.setPipeline(pipeline); device.queue.writeBuffer(baseUniformBuffer, 0, baseUniformValues); // device.queue.writeBuffer(fragmentUniformBuffer, 0, fragmentUniform.data); // let bufCounterFrag = 0; // for (let i = 0; i < fragmentUniform.special.length; i++) { // let special = fragmentUniform.special[i]; // if (special.type == 'array' && special.value) { // device.queue.writeBuffer( // specialBuffersFragment[bufCounterFrag++], // 0, // special.value.buffer // ); // } // } // device.queue.writeBuffer(vertexUniformBuffer, 0, vertexUniform.data); // let bufCounterVert = 0; // for (let i = 0; i < vertexUniform.special.length; i++) { // let special = vertexUniform.special[i]; // if (special.type == 'array' && special.value) { // device.queue.writeBuffer(specialBuffersVertex[bufCounterVert++], 0, special.value.buffer); // } // } pass.setBindGroup(0, bindGroupFragment); pass.setBindGroup(1, bindGroupVertex); if (dispatch.indirectBuffer) { if (dispatch.geometry) { let meshData = this.getOrCreateMeshData(dispatch.geometry); pass.setVertexBuffer(0, meshData.vertexBuffer); pass.setIndexBuffer(meshData.indexBuffer, 'uint32'); } if (dispatch.indexBuffer) { if (dispatch.indexBuffer) { pass.setIndexBuffer( this.getOrCreateBuffer(dispatch.indexBuffer, GPUBufferUsage.INDEX), 'uint32' ); } if (dispatch.indirectBuffer.elementCount % 5 != 0) { throw new Error( 'Indirect buffer needs to be a multiple of 5 (must be at least 5 elements for indexedIndirect)' ); } pass.drawIndexedIndirect( this.getOrCreateBuffer(dispatch.indirectBuffer, GPUBufferUsage.INDIRECT), dispatch.indirectOffset ); } else { if (dispatch.indirectBuffer.elementCount % 4 != 0) { throw new Error( 'Indirect buffer needs to be a multiple of 4 (must be at least 4 elements for indirect)' ); } pass.drawIndirect( this.getOrCreateBuffer(dispatch.indirectBuffer, GPUBufferUsage.INDIRECT), dispatch.indirectOffset ); } } else if (dispatch.geometry) { let meshData = this.getOrCreateMeshData(dispatch.geometry); pass.setVertexBuffer(0, meshData.vertexBuffer); if (meshData.indexCount > 0) { pass.setIndexBuffer(meshData.indexBuffer, 'uint32'); pass.drawIndexed(meshData.indexCount, dispatch.instanceCount); } else { pass.draw(meshData.vertexCount, dispatch.instanceCount); } } this.trace('dispatchDraw', { dispatch, options }); pass.end(); return () => { // baseUniformBuffer.destroy(); // vertexUniformBuffer.destroy(); // fragmentUniformBuffer.destroy(); }; }); // device.queue.submit([encoder.finish()]); // this.endDispatch(); } dispatchDrawIndexed( dispatch: ShaderDispatch, options: { depthTest: boolean } = { depthTest: true } ) { const { device } = this.getGPU(); if (!dispatch.vertexShader || !dispatch.fragmentShader) { throw new Error('Dispatch is missing vertex or fragment shader'); } if (!dispatch.indexBuffer) { throw new Error('Dispatch is missing indexBuffer'); } this.startDispatch(); let fragment = dispatch.fragmentShader; let vertex = dispatch.vertexShader; const fragmentUniform = generateUniforms(dispatch.fragmentUniforms, dispatch.fragmentShader); const vertexUniform = generateUniforms(dispatch.vertexUniforms, dispatch.vertexShader); let cacheKey = `${dispatch.fragmentShader.uniqueSourceKey}|${dispatch.vertexShader.uniqueSourceKey}|${options.depthTest}`; let output = this.buildDrawPipeline( { fragment, vertex }, fragmentUniform, vertexUniform, options, true ); this.beforeScreenDraw(); this.enqueueCommand((encoder) => { if (output) for (let command of output.commands) { command(encoder); } if (!this.depthTexture) { throw new Error('Depth texture not created'); } let passDescriptor: GPURenderPassDescriptor = { colorAttachments: [ { view: this.getTexture().createView(), storeOp: 'store', loadOp: 'load' } ], depthStencilAttachment: { view: this.depthTexture.createView(), depthClearValue: 1.0, depthLoadOp: 'load', depthStoreOp: 'store' } }; const pass = encoder.beginRenderPass(passDescriptor); let baseUniformValues = this.baseUniformValues; let baseUniformBufferSize = this.baseUniformBufferSize; let myTex = this.getTexture(); baseUniformValues.set([myTex.width, myTex.height], 0); let drawData: DrawPipelinePayload; if (CACHE_PIPELINES) { let cacheValue = this.pipelineCache.get(cacheKey); if (!cacheValue) { let output = this.buildDrawPipeline( { fragment, vertex }, fragmentUniform, vertexUniform, options ); if (!output) return; drawData = output; this.pipelineCache.set(cacheKey, drawData); } else { drawData = cacheValue as DrawPipelinePayload; } } else { if (!output) return; drawData = output; } let { pipeline, bindGroupFragment, bindGroupVertex, baseUniformBuffer, vertexUniformBuffer, fragmentUniformBuffer, specialBuffersFragment, specialBuffersVertex } = drawData; pass.setPipeline(pipeline); device.queue.writeBuffer(baseUniformBuffer, 0, baseUniformValues); device.queue.writeBuffer(fragmentUniformBuffer, 0, fragmentUniform.data); let bufCounterFrag = 0; for (let i = 0; i < fragmentUniform.special.length; i++) { let special = fragmentUniform.special[i]; if (special.type == 'array' && special.value) { device.queue.writeBuffer( specialBuffersFragment[bufCounterFrag++], 0, special.value.buffer ); } } device.queue.writeBuffer(vertexUniformBuffer, 0, vertexUniform.data); let bufCounterVert = 0; for (let i = 0; i < vertexUniform.special.length; i++) { let special = vertexUniform.special[i]; if (special.type == 'array' && special.value) { device.queue.writeBuffer(specialBuffersVertex[bufCounterVert++], 0, special.value.buffer); } } pass.setBindGroup(0, bindGroupFragment); pass.setBindGroup(1, bindGroupVertex); pass.setIndexBuffer( this.getOrCreateBuffer(dispatch.indexBuffer, GPUBufferUsage.INDEX), 'uint32' ); pass.drawIndexed(dispatch.indexBuffer.len(), dispatch.instanceCount); pass.end(); }); // device.queue.submit([encoder.finish()]); // this.endDispatch(); } dispatchDrawCount( dispatch: ShaderDispatch, options: { depthTest: boolean } = { depthTest: true } ) { const { device } = this.getGPU(); if (!dispatch.vertexShader || !dispatch.fragmentShader) { throw new Error('Dispatch is missing vertex or fragment shader'); } this.startDispatch(); let fragment = dispatch.fragmentShader; let vertex = dispatch.vertexShader; let cacheKey = `${dispatch.fragmentShader.uniqueSourceKey}|${dispatch.vertexShader.uniqueSourceKey}|${options.depthTest}`; const fragmentUniform = generateUniforms(dispatch.fragmentUniforms, dispatch.fragmentShader); const vertexUniform = generateUniforms(dispatch.vertexUniforms, dispatch.vertexShader); let output = this.buildDrawPipeline( { fragment, vertex }, fragmentUniform, vertexUniform, options, true ); this.beforeScreenDraw(); this.enqueueCommand((encoder) => { if (output) for (let command of output.commands) { command(encoder); } if (!this.depthTexture) { throw new Error('Depth texture not created'); } let passDescriptor: GPURenderPassDescriptor = { colorAttachments: [ { view: this.getTexture().createView(), storeOp: 'store', loadOp: 'load' } ], depthStencilAttachment: { view: this.depthTexture.createView(), depthClearValue: 1.0, depthLoadOp: 'load', depthStoreOp: 'store' } }; const pass = encoder.beginRenderPass(passDescriptor); let baseUniformValues = this.baseUniformValues; let baseUniformBufferSize = this.baseUniformBufferSize; let myTex = this.getTexture(); baseUniformValues.set([myTex.width, myTex.height], 0); let drawData: DrawPipelinePayload; if (CACHE_PIPELINES) { let cacheValue = this.pipelineCache.get(cacheKey); if (!cacheValue) { let output = this.buildDrawPipeline( { fragment, vertex }, fragmentUniform, vertexUniform, options, true ); if (!output) return; drawData = output; this.pipelineCache.set(cacheKey, drawData); } else { drawData = cacheValue as DrawPipelinePayload; } } else { if (!output) return; drawData = output; } let { pipeline, bindGroupFragment, bindGroupVertex, baseUniformBuffer, vertexUniformBuffer, fragmentUniformBuffer, specialBuffersFragment, specialBuffersVertex } = drawData; pass.setPipeline(pipeline); device.queue.writeBuffer(baseUniformBuffer, 0, baseUniformValues); device.queue.writeBuffer(fragmentUniformBuffer, 0, fragmentUniform.data); let bufCounterFrag = 0; for (let i = 0; i < fragmentUniform.special.length; i++) { let special = fragmentUniform.special[i]; if (special.type == 'array' && special.value) { device.queue.writeBuffer( specialBuffersFragment[bufCounterFrag++], 0, special.value.buffer ); } } device.queue.writeBuffer(vertexUniformBuffer, 0, vertexUniform.data); let bufCounterVert = 0; for (let i = 0; i < vertexUniform.special.length; i++) { let special = vertexUniform.special[i]; if (special.type == 'array' && special.value) { device.queue.writeBuffer(specialBuffersVertex[bufCounterVert++], 0, special.value.buffer); } } pass.setBindGroup(0, bindGroupFragment); pass.setBindGroup(1, bindGroupVertex); pass.draw(dispatch.drawCount * 3, 1, 0, 0); pass.end(); }); } drawCalls: GPUCommandBuffer[] = []; flush(): Promise { this.trace('flush', {}); super.flush(); const { device } = this.getGPU(); let needsDraw = true; if (this.drawCalls.length == 0 && this.commandQueue.length == 0) needsDraw = false; if (needsDraw) { if (this.drawCalls.length > 0) { device.queue.submit(this.drawCalls); this.drawCalls = []; } if (this.commandQueue.length > 0) { let cleanups = []; this.startDispatch(); let encoder = device.createCommandEncoder(); for (let i = 0; i < this.commandQueue.length; i++) { let o = this.commandQueue[i](encoder); if (o) { cleanups.push(o); } } device.queue.submit([encoder.finish()]); for (let i = this.cleanupCommands.length - 1; i >= 0; i--) { if (this.cleanupCommands[i].$counter > 0) { this.cleanupCommands[i].$counter--; } else { this.cleanupCommands[i](); this.cleanupCommands.splice(i, 1); } } for (let i = 0; i < cleanups.length; i++) { cleanups[i](); } this.endDispatch(); this.commandQueue = []; } this.copyToCanvas(); } return device.queue.onSubmittedWorkDone(); } drawImageRender(texture: GPUTexture, toTexture: GPUTexture): void { const { device } = this.getGPU(); if (!this.ready) { return; } if (this.drawImageCache) { this.drawImageCache(texture, toTexture); return; } const bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'unfilterable-float' } }, { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'non-filtering' } } ] }); let vertexShader = this.createShader( { webgl: ``, webgpu: ` struct VertexOutput { @builtin(position) Position : vec4, @location(0) Normal : vec3, @location(1) TexCoord : vec2, @location(2) Color : vec4, }; @vertex fn main( @builtin(vertex_index) VertexIndex : u32 ) -> VertexOutput { var x : f32 = f32((VertexIndex & 1) << 2); var y : f32 = f32((VertexIndex & 2) << 1); var output : VertexOutput; output.Position = vec4(x - 1.0, y - 1.0, 0, 1); output.Normal = vec3(1.0, 0.0, 0.0); output.TexCoord = vec2(x * 0.5, 1.0 - (y * 0.5)); output.Color = vec4(0.0, 0.0, 0.0, 0.0); return output; } `, software: () => {} }, 'vertex' ); let fragmentShader = this.createShader( { webgl: ``, webgpu: ` struct VertexOutput { @builtin(position) Position : vec4, @location(0) Normal : vec3, @location(1) TexCoord : vec2, @location(2) Color : vec4, }; @group(0) @binding(1) var _sampler: sampler; @group(0) @binding(0) var _texture: texture_2d; @fragment fn main( _in: VertexOutput ) -> @location(0) vec4 { return textureSample(_texture, _sampler, _in.TexCoord); } `, software: () => {} }, 'fragment' ); const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout] }); const pipelineDescriptor = { vertex: { module: vertexShader.payload, entryPoint: 'main', buffers: vertexLayout }, fragment: { module: fragmentShader.payload, entryPoint: 'main', targets: [ { format: 'rgba8unorm', blend: { alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' }, color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' } } } ] }, primitive: { topology: 'triangle-list', cullMode: 'back' }, layout: pipelineLayout } as GPURenderPipelineDescriptor; const pipeline = device.createRenderPipeline(pipelineDescriptor); let geo = { vertices: [ [0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0] ], uvs: [ [0, 0], [0, 1], [1, 1], [1, 0] ], triangles: [0, 1, 2], colors: [], normals: [], tangents: [], bitangents: [], getTriangles: () => { return geo.triangles; }, getVertices: () => { return geo.vertices; }, getUVs: () => { return geo.uvs; }, getNormals: (): number[][] => { return []; }, getTangents: (): number[][] => { return []; }, getBitangents: (): number[][] => { return []; }, getColors: (): number[][] => { return []; }, symbol: Symbol() }; let meshData = this.getOrCreateMeshData(geo as any); this.drawImageCache = (texture: GPUTexture, toTexture: GPUTexture) => { device.pushErrorScope('internal'); device.pushErrorScope('validation'); const commandEncoder = device.createCommandEncoder(); const passEncoder = commandEncoder.beginRenderPass({ colorAttachments: [ { view: toTexture.createView(), storeOp: 'store', loadOp: 'load' } ] } as GPURenderPassDescriptor); const sampler = device.createSampler({}); passEncoder.setPipeline(pipeline); const bindGroup = device.createBindGroup({ layout: bindGroupLayout, entries: [ { binding: 0, resource: texture.createView() }, { binding: 1, resource: sampler } ] }); passEncoder.setBindGroup(0, bindGroup); passEncoder.setVertexBuffer(0, meshData.vertexBuffer); passEncoder.setIndexBuffer(meshData.indexBuffer, 'uint32'); passEncoder.drawIndexed(meshData.indexCount); passEncoder.end(); device.queue.submit([commandEncoder.finish()]); device.popErrorScope().then((error) => { if (error) { console.log('Error', error); (window as any).bubbleError(error.message); throw new Error('Failed to create shader'); } }); device.popErrorScope().then((error) => { if (error) { console.log('Error', error); (window as any).bubbleError(error.message); throw new Error('Failed to create shader'); } }); }; this.drawImageCache(texture, toTexture); } async copyToOtherCanvas(canvas: HTMLCanvasElement): Promise { const { device } = this.getGPU(); let encoder = device.createCommandEncoder(); let ctx = canvas.getContext('webgpu'); if (!ctx) throw new Error('Could not get webgpu context'); ctx.configure({ device: device, format: 'rgba8unorm', alphaMode: 'premultiplied', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST }); encoder.copyTextureToTexture( { texture: this.getTexture() }, { texture: ctx.getCurrentTexture() }, { width: this.getTexture().width, height: this.getTexture().height } ); device.queue.submit([encoder.finish()]); await device.queue.onSubmittedWorkDone(); } copyToCanvas() { const { device } = this.getGPU(); if ( this.headless && this.texture && (this.textureFormat.endsWith('4') || this.textureFormat == 'uint8') ) { // Draw to canvas if (!this.ctx) { this.ctx = this.canvas!.getContext('webgpu'); if (!this.ctx) throw new Error('Could not get webgpu context'); this.ctx.configure({ device, format: 'rgba8unorm', alphaMode: 'premultiplied', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST }); // document.body.appendChild(this.canvas!); } this.startDispatch(); let encoder = device.createCommandEncoder(); if (this.texture.format == 'rgba8unorm') { encoder.copyTextureToTexture( { texture: this.texture }, { texture: this.ctx.getCurrentTexture() }, { width: this.texture.width, height: this.texture.height } ); } else { // Render via draw call this.drawImageRender(this.texture, this.ctx.getCurrentTexture()); } device.queue.submit([encoder.finish()]); this.endDispatch(); } } dispatch( dispatch: ShaderDispatch, options: { depthTest: boolean; } = { depthTest: true } ): void { super.dispatch(dispatch, options); if (dispatch.type == 'draw') { this.activateDrawContext(); this.triggerEvent('draw', dispatch); if (dispatch.drawType == 'indexed') { this.dispatchDrawIndexed(dispatch, options); } else if (dispatch.drawType == 'count') { this.dispatchDrawCount(dispatch, options); } else { this.dispatchDraw(dispatch, options); } } } dispose(): void { this.canvas?.remove(); this.texture?.destroy(); this.storageTexture?.destroy(); } destroyBuffer(buf: buffer): void { this.enqueueCommand((encoder) => { if (buf.platformPayload) { buf.platformPayload.destroy(); } }); } waitForDraw(): Promise { const { device } = this.getGPU(); return device.queue.onSubmittedWorkDone(); } bufferCounter: number = 0; getOrCreateBuffer(buf: buffer, extraFlags: GPUBufferUsageFlags | null): GPUBuffer { let useOldBuffer: GPUBuffer | null = null; if (buf.platformPayload) { let gpuBuf = buf.platformPayload as GPUBuffer; if (extraFlags !== null) { if (gpuBuf.usage & extraFlags) { return gpuBuf; } extraFlags |= gpuBuf.usage; useOldBuffer = gpuBuf; } else { return gpuBuf; } } const { device } = this.getGPU(); let flags = this.genericBufferFlags(); if (extraFlags) { flags |= extraFlags; } let bufferSize = buf.len() * buf.elementBytes; if (!buf.structured) { bufferSize *= buf.vectorSize; } this.startDispatch(); let buffer = device.createBuffer({ size: bufferSize, usage: flags }); (buf as any).$_bufferIndex = this.bufferCounter; this.bufferCounter++; buf.symbol = Symbol(); if (useOldBuffer) { let encoder = device.createCommandEncoder(); encoder.copyBufferToBuffer(useOldBuffer, 0, buffer, 0, bufferSize); device.queue.submit([encoder.finish()]); } else if (buf.cpuWriteDirty) { if (buf.structured) { if (buf.typeName == 'atomic' || buf.typeName == 'atomic') { let zero: Uint32Array | Int32Array; if (buf.typeName == 'atomic') { zero = new Uint32Array(buf.elementCount); } else { zero = new Int32Array(buf.elementCount); } if (buf.structArray) for (let i = 0; i < buf.structArray.length; i++) { let struct = buf.structArray[i]; if (struct) { zero[i] = struct; } } device.queue.writeBuffer(buffer, 0, zero); } else { // let structure = (window as any).__shadeup_structs[buf.typeName]; // let size = getValueSize(structure.fields); // let arrayBuffer = new ArrayBuffer(buf.elementCount * size); // if (buf.structArray) // for (let i = 0; i < buf.elementCount; i++) { // this.writeStructuredBuffer(structure.fields, buf.structArray[i], arrayBuffer, i * size); // } device.queue.writeBuffer(buffer, 0, buf.arrayBuffer!); } } else { device.queue.writeBuffer( buffer, 0, buf.uintArray ?? buf.floatArray ?? buf.intArray ?? new Uint8Array(0) ); } buf.cpuWriteDirty = false; } buf.platformPayload = buffer; buf.adapter = this; this.endDispatch(); return buffer; } } const TYPE_SIZES_NATIVE = { f32: 4, 'vec2': 8, 'vec3': 12, 'vec4': 16, 'mat2x2': 16, 'mat3x3': 36, 'mat4x4': 64, u32: 4, 'vec2': 8, 'vec3': 12, 'vec4': 16, i32: 4, 'vec2': 8, 'vec3': 12, 'vec4': 16 }; const TRANSPOSE_MATRICES_UNIFORM = false; const TYPE_SIZES = { atomic: [8, 8], texture2d: [8, 8], rwtexture2d: [8, 8], bool: [1, 15], float: [4, 12], float2: [8, 8], float3: [12, 4], float4: [16, 0], float2x2: [16, 0], float3x3: [12 + 12 + 12, 4 + 4 + 4], float4x4: [16 + 16 + 16 + 16, 4 + 4 + 4 + 4], uint: [4, 12], uint2: [8, 8], uint3: [12, 4], uint4: [16, 0], int: [4, 12], int2: [8, 8], int3: [12, 4], int4: [16, 0] }; function getValueSize(val: UniformValueType): number { let totalSize = 0; if (val.type == 'struct') { let lastSlotPadding = 0; for (let member of val.fields) { let fieldSize = getValueSize(member[1]); totalSize += fieldSize; if (lastSlotPadding == 0) { lastSlotPadding = 16 - fieldSize; } else if (lastSlotPadding == 4 && fieldSize == 4) { } else if (lastSlotPadding == 8 && fieldSize == 4) { lastSlotPadding = 4; } else if (lastSlotPadding == 12 && fieldSize == 4) { lastSlotPadding = 0; } // if (member[1].type == 'primitive') { // lastSlotPadding = 16 - fieldSize; // }else{ // lastSlotPadding = 0; // } } } else if (val.type == 'primitive') { let n = val.name; if (n == 'atomic') { totalSize += 4; } else if (n == 'texture2d' || n == 'rwtexture2d') { totalSize += 8; } else { let s = TYPE_SIZES[n]; if (s[0] == 0) { throw new Error(`Cannot calculate size of struct with unknown size type ${n}`); } totalSize += s[0] + s[1]; } } else if (val.type == 'array') { let elementSize = getValueSize(val.element); if (typeof val.staticSize !== 'undefined') { totalSize += val.staticSize * elementSize; } else { throw new Error(`Cannot calculate size of struct with unknown size type ${val.element}`); } } return totalSize; } function generateArrayBuffer( rootVt: UniformValueType, rawData: any, data?: ArrayBuffer, offset?: number ): { buffer: ArrayBuffer; size: number; } { if (rootVt.type != 'array') { throw new Error(`Cannot generate array buffer for non-array type ${rootVt.type}`); } let specialCounter = 2; let totalSize = 0; let lastFieldPadding = 0; let vsize = getValueSize(rootVt.element); totalSize += vsize * rawData.value.len(); if (totalSize == 0) { // Dummy data totalSize = 4 * 4; } if (!data) data = new ArrayBuffer(totalSize); let floatView = new Float32Array(data); let uintView = new Uint32Array(data); let intView = new Int32Array(data); if (!offset) offset = 0; let queue: [UniformKeyValuePair, any, number | null][] = []; let rootObj = rawData.value; for (let i = 0; i < rawData.value.len(); i++) { queue.unshift([[`[${i}]`, rootVt.element], rootObj, i]); } while (queue.length > 0) { let [uniform, obj, arrayIndex] = queue.pop() as [UniformKeyValuePair, any, number | null]; let vt = uniform[1]; let name = uniform[0]; if (vt.type == 'primitive') { let n = vt.name; let s = TYPE_SIZES[n]; if (s[0] == 0) { throw new Error(`Cannot calculate size of struct with unknown size type ${n}`); } let val; if (arrayIndex !== null) { val = obj[arrayIndex]; } else { val = obj[name]; } if (typeof val === 'undefined') { throw new Error(`Uniform ${name} is not defined`); } if (val instanceof UniformValue) { val = val.value; } let view: Float32Array | Uint32Array | Int32Array = floatView; if (n.startsWith('u')) { view = uintView; } else if (n.startsWith('i')) { view = intView; } if (n == 'float' || n == 'uint' || n == 'int') { if (typeof val == 'boolean') { val = val ? 1 : 0; } view[offset++] = val; offset += 3; } else if (n == 'float2' || n == 'uint2' || n == 'int2') { view[offset++] = val[0]; view[offset++] = val[1]; offset += 2; } else if (n == 'float3' || n == 'uint3' || n == 'int3') { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; offset += 1; } else if (n == 'float4' || n == 'uint4' || n == 'int4') { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; view[offset++] = val[3]; } else if (n == 'float2x2') { // Column major order if (TRANSPOSE_MATRICES_UNIFORM) { view[offset++] = val[0]; view[offset++] = val[2]; view[offset++] = val[1]; view[offset++] = val[3]; } else { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; view[offset++] = val[3]; } } else if (n == 'float3x3') { // Column major order if (TRANSPOSE_MATRICES_UNIFORM) { view[offset++] = val[0]; view[offset++] = val[3]; view[offset++] = val[6]; offset++; view[offset++] = val[1]; view[offset++] = val[4]; view[offset++] = val[7]; offset++; view[offset++] = val[2]; view[offset++] = val[5]; view[offset++] = val[8]; offset++; } else { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; offset++; view[offset++] = val[3]; view[offset++] = val[4]; view[offset++] = val[5]; offset++; view[offset++] = val[6]; view[offset++] = val[7]; view[offset++] = val[8]; offset++; } } else if (n == 'float4x4') { // Column major order if (TRANSPOSE_MATRICES_UNIFORM) { view[offset++] = val[0]; view[offset++] = val[4]; view[offset++] = val[8]; view[offset++] = val[12]; view[offset++] = val[1]; view[offset++] = val[5]; view[offset++] = val[9]; view[offset++] = val[13]; view[offset++] = val[2]; view[offset++] = val[6]; view[offset++] = val[10]; view[offset++] = val[14]; view[offset++] = val[3]; view[offset++] = val[7]; view[offset++] = val[11]; view[offset++] = val[15]; } else { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; view[offset++] = val[3]; view[offset++] = val[4]; view[offset++] = val[5]; view[offset++] = val[6]; view[offset++] = val[7]; view[offset++] = val[8]; view[offset++] = val[9]; view[offset++] = val[10]; view[offset++] = val[11]; view[offset++] = val[12]; view[offset++] = val[13]; view[offset++] = val[14]; view[offset++] = val[15]; } } else if (n == 'bool') { intView[offset++] = val ? 1 : 0; offset += 3; } else if (n == 'rwtexture2d' || n == 'texture2d') { floatView[offset++] = val.size[0]; floatView[offset++] = val.size[1]; offset += 2; } else if (n == 'atomic') { view[offset++] = val; offset += 3; } else { throw new Error('Invalid param type ' + n); } } else if (vt.type == 'array') { let val = obj[name]; if (val instanceof UniformValue) { val = val.value; } if (obj == rootObj) { if (typeof val === 'object' && Array.isArray(val)) { intView[offset++] = val.length; offset += 3; } } else { for (let i = val.length - 1; i >= 0; i--) { queue.push([['', vt.element], val, i]); } } } else if (vt.type == 'buffer') { let val = obj[name]; if (val instanceof UniformValue) { val = val.value; } if (obj == rootObj) { if (typeof val === 'object') { intView[offset++] = val.elementCount; offset += 3; } } } else if (vt.type == 'struct') { let val; if (arrayIndex !== null) { val = obj[arrayIndex]; } else { val = obj[name]; } if (typeof val === 'object') { for (let i = vt.fields.length - 1; i >= 0; i--) { let member = vt.fields[i]; if (val instanceof UniformValue) { queue.push([member, val.value, null]); } else { queue.push([member, val, null]); } } } } } return { size: totalSize, buffer: data }; } type WebGPUSpecialUniform = | { index: number; type: 'sampler2D'; valueType: UniformValueType; access: 'read' | 'write' | 'sample_write' | 'sample'; value?: { texture: ShadeupTexture2d; }; } | { index: number; type: 'sampler2DArray'; valueType: UniformValueType; access: 'read' | 'write' | 'sample_write' | 'sample'; value?: { textures: ShadeupTexture2d[]; }; } | { index: number; type: 'array'; valueType: UniformValueType; value?: { size: number; buffer: ArrayBuffer; }; } | { index: number; type: 'buffer'; access: 'read' | 'write'; valueType: UniformValueType; value?: buffer; } | { index: number; type: 'atomic'; valueType: UniformValueType; value: { __value: number }; }; type GeneratedUniforms = { size: number; special: WebGPUSpecialUniform[]; data: ArrayBuffer; }; function generateUniforms( fragmentUniforms: UniformPayload, fragmentShader: GenericShader ): GeneratedUniforms { if (fragmentShader.parent == null) { return { size: 0, special: [], data: new ArrayBuffer(0) }; } let orderedUniforms: UniformKeyValuePair[] = [ ...fragmentShader.parent.params.webgpu.locals.map((l) => { return ['_ext_uniform_local_' + l[0], l[1]] as UniformKeyValuePair; }), ...fragmentShader.parent.params.webgpu.globals.map((g) => { return ['_ext_uniform_global_' + g[0], g[1].structure] as UniformKeyValuePair; }) ]; let special: WebGPUSpecialUniform[] = []; let specialCounter = 2; let totalSize = 0; let lastFieldPadding = 0; for (let uniform of orderedUniforms) { let vt = uniform[1]; if (vt.type == 'primitive' && (vt.name == 'texture2d' || vt.name == 'rwtexture2d')) { let texPayload = fragmentUniforms.uniforms.get(uniform[0]) as any; special.push({ index: specialCounter, type: 'sampler2D', valueType: vt, value: { texture: texPayload.value }, access: vt.access }); specialCounter += 2; lastFieldPadding = 8; totalSize += 8 + lastFieldPadding; // Size } else if (vt.type == 'array') { if (vt.element.type == 'primitive' && vt.element.name == 'texture2d') { let texPayload = fragmentUniforms.uniforms.get(uniform[0]) as any; special.push({ index: specialCounter, type: 'sampler2DArray', valueType: vt, value: { textures: texPayload.value }, access: vt.element.access }); specialCounter += 2; lastFieldPadding = 8; totalSize += 8 + lastFieldPadding; // Size } else { special.push({ index: specialCounter, type: 'array', valueType: vt, value: generateArrayBuffer(vt, fragmentUniforms.uniforms.get(uniform[0]) as any) }); specialCounter++; lastFieldPadding = 12; totalSize += 4 + lastFieldPadding; // Len } } else if (vt.type == 'buffer') { special.push({ type: 'buffer', valueType: vt, access: vt.access, index: specialCounter, value: fragmentUniforms.uniforms.get(uniform[0])?.value as buffer_internal as any }); specialCounter++; lastFieldPadding = 12; totalSize += 4 + lastFieldPadding; // Len } else if (vt.type == 'primitive' && vt.name == 'atomic') { special.push({ type: 'atomic', valueType: vt, index: specialCounter, value: fragmentUniforms.uniforms.get(uniform[0])?.value as any }); specialCounter++; lastFieldPadding = 12; totalSize += 4 + lastFieldPadding; // Len } else { let vsize = getValueSize(vt); let extra = vsize % 16; if (vt.type == 'primitive') { lastFieldPadding = 16 - extra; } else { lastFieldPadding = 0; } totalSize += vsize + lastFieldPadding; } } if (totalSize == 0) { // Dummy data totalSize = 4 * 4; } let queue: [UniformKeyValuePair, any, number | null][] = []; let rootObj: { [key: string]: any } = {}; for (let k of fragmentUniforms.uniforms.keys()) { rootObj[k] = fragmentUniforms.uniforms.get(k); } for (let uniform of orderedUniforms) { queue.unshift([uniform, rootObj, null]); } let data = new ArrayBuffer(totalSize); let offset = 0; writeBufferStructure(queue, rootObj, data, offset); return { size: totalSize, special, data }; } function writeBufferStructure( initialQueue: [UniformKeyValuePair, any, number | null][], rootObj: { [key: string]: any }, data: ArrayBuffer, offset: number ) { let floatView = new Float32Array(data); let uintView = new Uint32Array(data); let intView = new Int32Array(data); let queue: [UniformKeyValuePair, any, number | null][] = [...initialQueue]; while (queue.length > 0) { let [uniform, obj, arrayIndex] = queue.pop() as [UniformKeyValuePair, any, number | null]; let vt = uniform[1]; let name = uniform[0]; if (vt.type == 'primitive') { let n = vt.name; let s = TYPE_SIZES[n]; if (s[0] == 0) { throw new Error(`Cannot calculate size of struct with unknown size type ${n}`); } let val; if (arrayIndex !== null) { val = obj[arrayIndex]; } else { val = obj[name]; } if (typeof val === 'undefined') { throw new Error(`Uniform ${name} is not defined`); } if (val instanceof UniformValue) { val = val.value; } let view: Float32Array | Uint32Array | Int32Array = floatView; if (n.startsWith('u')) { view = uintView; } else if (n.startsWith('i')) { view = intView; } if (n == 'float' || n == 'uint' || n == 'int') { if (typeof val == 'boolean') { val = val ? 1 : 0; } view[offset++] = val; offset += 3; } else if (n == 'float2' || n == 'uint2' || n == 'int2') { view[offset++] = val[0]; view[offset++] = val[1]; offset += 2; } else if (n == 'float3' || n == 'uint3' || n == 'int3') { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; offset += 1; } else if (n == 'float4' || n == 'uint4' || n == 'int4') { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; view[offset++] = val[3]; } else if (n == 'float2x2') { // Column major order if (TRANSPOSE_MATRICES_UNIFORM) { view[offset++] = val[0]; view[offset++] = val[2]; view[offset++] = val[1]; view[offset++] = val[3]; } else { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; view[offset++] = val[3]; } } else if (n == 'float3x3') { // Column major order if (TRANSPOSE_MATRICES_UNIFORM) { view[offset++] = val[0]; view[offset++] = val[3]; view[offset++] = val[6]; offset++; view[offset++] = val[1]; view[offset++] = val[4]; view[offset++] = val[7]; offset++; view[offset++] = val[2]; view[offset++] = val[5]; view[offset++] = val[8]; offset++; } else { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; offset++; view[offset++] = val[3]; view[offset++] = val[4]; view[offset++] = val[5]; offset++; view[offset++] = val[6]; view[offset++] = val[7]; view[offset++] = val[8]; offset++; } } else if (n == 'float4x4') { // Column major order if (TRANSPOSE_MATRICES_UNIFORM) { view[offset++] = val[0]; view[offset++] = val[4]; view[offset++] = val[8]; view[offset++] = val[12]; view[offset++] = val[1]; view[offset++] = val[5]; view[offset++] = val[9]; view[offset++] = val[13]; view[offset++] = val[2]; view[offset++] = val[6]; view[offset++] = val[10]; view[offset++] = val[14]; view[offset++] = val[3]; view[offset++] = val[7]; view[offset++] = val[11]; view[offset++] = val[15]; } else { view[offset++] = val[0]; view[offset++] = val[1]; view[offset++] = val[2]; view[offset++] = val[3]; view[offset++] = val[4]; view[offset++] = val[5]; view[offset++] = val[6]; view[offset++] = val[7]; view[offset++] = val[8]; view[offset++] = val[9]; view[offset++] = val[10]; view[offset++] = val[11]; view[offset++] = val[12]; view[offset++] = val[13]; view[offset++] = val[14]; view[offset++] = val[15]; } } else if (n == 'bool') { intView[offset++] = val ? 1 : 0; offset += 3; } else if (n == 'rwtexture2d' || n == 'texture2d') { floatView[offset++] = val.size[0]; floatView[offset++] = val.size[1]; offset += 2; } else if (n == 'atomic') { if ((vt as any).element == 'uint') { uintView[offset++] = val; } else { intView[offset++] = val; } offset += 3; } else { throw new Error('Invalid param type ' + n); } } else if (vt.type == 'array') { let val = obj[name]; if (val instanceof UniformValue) { val = val.value; } if (obj == rootObj) { if (typeof val === 'object' && Array.isArray(val)) { intView[offset++] = val.length; offset += 3; } } else { for (let i = val.length - 1; i >= 0; i--) { queue.push([['', vt.element], val, i]); } } } else if (vt.type == 'buffer') { let val = obj[name]; if (val instanceof UniformValue) { val = val.value; } if (obj == rootObj) { if (typeof val === 'object') { intView[offset++] = val.elementCount; offset += 3; } } } else if (vt.type == 'struct') { let val; if (arrayIndex !== null) { val = obj[arrayIndex]; } else { val = obj[name]; } if (typeof val === 'object') { for (let i = vt.fields.length - 1; i >= 0; i--) { let member = vt.fields[i]; if (val instanceof UniformValue) { queue.push([member, val.value, null]); } else { queue.push([member, val, null]); } } } } } } type DrawOptions = { depthFormat: GPUTextureFormat; depthOnly?: boolean; depthTest: boolean; attachments?: ShadeupTexture2d[]; backfaceCulling: boolean; depthCompare: GPUCompareFunction; }; function printImage(url: string, size = 10, afterRead?: () => void) { var image = new Image(); image.onload = function () { var style = [ 'font-size: 1px;', 'padding: ' + (this.height / 100) * size + 'px ' + (this.width / 100) * size + 'px;', 'background: url(' + url + ') no-repeat;', 'background-size: contain;' ].join(' '); if (afterRead) { afterRead(); } console.log('%c ', style); }; image.src = url; } ================================================ FILE: lang/shadeup/engine/amd.ts ================================================ import resolvePathname from 'resolve-pathname'; // AMD loader // This is a very simple AMD loader that is only intended to be used in the // context of the editor. It is not intended to be used in production. export function globalDefine(name: string, deps: string[], callback: Function): void { if (typeof name !== 'string') { callback = deps; deps = name; name = null; } if (!Array.isArray(deps)) { callback = deps; deps = []; } if (!deps.length && callback.length) { if (callback.length === 1) { deps = ['require']; } else if (callback.length === 2) { deps = ['require', 'exports']; } else { deps = ['require', 'exports', 'module']; } } globalDefine.amd[name] = { deps: deps, callback: callback }; } globalDefine.amd = { require: { deps: [], callback: function () { return globalRequire; } }, exports: { deps: [], callback: function () { return {}; } } }; export function globalRequire(deps: string[]): any { let result = []; for (let i = 0; i < deps.length; i++) { let dep = deps[i]; if (dep !== 'require' && dep !== 'exports' && dep !== 'module') { dep = resolvePathname(dep, '/'); if (!(dep in globalDefine.amd)) { if (!dep.endsWith('.js')) { dep += '.js'; } } } if (dep in globalDefine.amd) { let deps = globalDefine.amd[dep].deps; let depsResults = []; for (let d of deps) { depsResults.push(globalRequire([d])[0]); } let callback = globalDefine.amd[dep].callback; let exports = callback.apply(null, depsResults); if (deps.indexOf('exports') !== -1) { exports = depsResults[deps.indexOf('exports')]; } result.push(exports); } else { throw new Error(`Cannot find module '${dep}'`); } } return result; } ================================================ FILE: lang/shadeup/engine/engine-headless.ts ================================================ import type { ShadeupRenderedFile } from '../compiler/common'; import { globalDefine, globalRequire } from './amd'; import { initInput, type MouseState } from './input/input'; import { keyboardKeys } from './input/keyboardKeys'; import { ShadeupShaderInstance, ShadeupShaderSource } from './shader'; import { initUI } from './ui/ui'; import { parse_type, stringify_type, translateIdentifier, translateNumericToGLSL } from './util'; window.addEventListener('message', async function (e: MessageEvent) { var mainWindow = e.source; if (mainWindow == null) return; var result = ''; if (e.data.type == 'frame') { try { let files: ShadeupRenderedFile[] = e.data.files; console.log(e.data); for (let file of files) { console.log(file); (() => { let define = (deps: string[], func: Function) => { globalDefine(file.path, deps, func); }; define; try { const postMessage = (v: any) => mainWindow.postMessage(v, e.origin); eval(file.contents); } catch (e) { console.log(e); result = e.message; } })(); } try { let outs = globalRequire(['/main.js'])[0]; if (typeof outs.main === 'function') { let result = await outs.main(); mainWindow.postMessage({ gid: (window as any)['LONG_GID'], data: result }, e.origin); } else { result = 'main is not a function'; } } catch (e) { console.log(e); result = e.message; } } catch (e) { console.error(e); result = 'eval() threw an exception.'; } mainWindow.postMessage(result, e.origin); } }); ================================================ FILE: lang/shadeup/engine/engine.ts ================================================ import type { IndexMapping } from '../../../../shadeup-frontend/lib/generator/root'; import type { ShadeupRenderedFile } from '../compiler/common'; import { globalDefine, globalRequire } from './amd'; import { initInput, normalizeWheel, type MouseState } from './input/input'; import { keyboardKeys } from './input/keyboardKeys'; import { ShadeupShaderInstance, ShadeupShaderSource } from './shader'; import { initUI } from './ui/ui'; import { parse_type, stringify_type, translateIdentifier, translateNumericToGLSL } from './util'; import { PaintingContext } from '../library/paint'; import type { Mesh } from '../../../../shadeup-frontend/lib/std/all'; import type { atomic } from '../../../../shadeup-frontend/lib/std/math'; import { WebGLAdapter } from './adapters/webgl'; import { WebGPUAdapter } from './adapters/webgpu'; import { ShaderDispatch, type ShaderCodeMapping, type ShaderType, makePrimitiveUniform, GraphicsAdapter, GenericShader, type UniformKeyValuePair, type UniformValueType, type ShaderParamsMapping } from './adapters/adapter'; import type { buffer } from '../library/buffer'; import type { uint } from '../library/types'; import type { RenderOptions } from 'src/routes/(app)/farm/render/farm'; import type { AssetFileType } from '../../components/common/Asset'; import type { GLTF } from 'three/examples/jsm/loaders/GLTFLoader'; import './setZero'; import type { TextureFormat, texture2d } from '../library/texture'; console.log('Engine loaded'); let registeredLibs = new Set(); function __shadeup_register_libs(libs: string[]) { console.log('Registering libs', libs); for (let lib of libs) { registeredLibs.add(lib); } } (window as any).__shadeup_register_libs = __shadeup_register_libs; let fpsCanvas = document.getElementById('fps') as HTMLCanvasElement; let fpsCtx = fpsCanvas.getContext('2d'); fpsCtx.font = 12 * window.devicePixelRatio + 'px monospace'; if (fpsCanvas) fpsCanvas.style.display = 'none'; let canvas: HTMLCanvasElement = document.getElementById('canvas') as HTMLCanvasElement; let container = document.querySelector('.render-container'); if (!container) throw new Error('container not found'); let preferredAdapter = document.body.dataset.renderingMode ?? 'webgl'; if (navigator.gpu) { (window as any).shadeupWebGPUAdapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }); if (!(window as any).shadeupWebGPUAdapter) { throw new Error('WebGPU not supported'); } console.log( 'Using WebGPU adapter', await (window as any).shadeupWebGPUAdapter.requestAdapterInfo() ); let supported = await (window as any).shadeupWebGPUAdapter.limits; let requiredLimits = { maxStorageBufferBindingSize: Math.min( 1024 * 1024 * 1024, supported.maxStorageBufferBindingSize ), // 1GB maxBufferSize: Math.min(1024 * 1024 * 1024, supported.maxBufferSize), // 1GB maxColorAttachmentBytesPerSample: Math.min(64, supported.maxColorAttachmentBytesPerSample), // 64 bytes maxComputeWorkgroupSizeX: Math.min(1024, supported.maxComputeWorkgroupSizeX), maxComputeWorkgroupSizeY: Math.min(1024, supported.maxComputeWorkgroupSizeY), maxComputeWorkgroupSizeZ: Math.min(64, supported.maxComputeWorkgroupSizeZ), maxComputeInvocationsPerWorkgroup: Math.min(1024, supported.maxComputeInvocationsPerWorkgroup) }; console.log('WebGPU limits', requiredLimits); (window as any).shadeupWebGPUDevice = await (window as any).shadeupWebGPUAdapter.requestDevice({ // requiredLimits: (window as any).shadeupWebGPUAdapter.limits requiredLimits }); (window as any).shadeupWebGPUDevice.addEventListener('uncapturederror', (e) => { console.error('Uncaught WebGPU', e); (window as any).bubbleError((e as GPUUncapturedErrorEvent).error.message); }); } let graphicsAdapter: GraphicsAdapter; window.onerror = (e) => { console.error(e); (window as any).bubbleError(e.toString()); }; if (preferredAdapter == 'webgl') { graphicsAdapter = new WebGLAdapter(canvas); } else if (preferredAdapter == 'webgpu') { graphicsAdapter = new WebGPUAdapter(canvas); } else { throw new Error('No adapter found'); } const blank = document.createElement('canvas'); blank.width = canvas.width; blank.height = canvas.height; function sizeCanvas() { let targetWidth = Math.floor(container.clientWidth * window.devicePixelRatio); let targetHeight = Math.floor(container.clientHeight * window.devicePixelRatio); if (canvas.width != targetWidth || canvas.height != targetHeight) { canvas.width = targetWidth; canvas.height = targetHeight; blank.width = canvas.width; blank.height = canvas.height; if (graphicsAdapter) graphicsAdapter.setViewport(canvas.width, canvas.height); } if ((window as any).env && (window as any).env.camera) { (window as any).env.camera.width = canvas.width; (window as any).env.camera.height = canvas.height; } let targetFpsWidth = Math.floor(96 * window.devicePixelRatio); let targetFpsHeight = Math.floor(20 * window.devicePixelRatio); if (fpsCanvas.width != targetFpsWidth || fpsCanvas.height != targetFpsHeight) { fpsCanvas.width = targetFpsWidth; fpsCanvas.height = targetFpsHeight; fpsCanvas.style.width = '96px'; fpsCanvas.style.height = '20px'; } if ((window as any)['paint']) { let offscreen = (window as any)['paint'].__offscreen_canvas; if (offscreen.width != canvas.width || offscreen.height != canvas.height) { offscreen.width = canvas.width; offscreen.height = canvas.height; } } } try { graphicsAdapter.init(); sizeCanvas(); (window as any)['paint'] = new PaintingContext(canvas, graphicsAdapter as any); } catch (e) { console.error(e); if (preferredAdapter == 'webgpu') { console.log('Failed to initialize WebGPU, falling back to WebGL'); preferredAdapter = 'webgl'; rebuildAdapter(); graphicsAdapter.init(); (window as any)['paint'] = new PaintingContext(canvas, graphicsAdapter as any); } } function rebuildAdapter() { console.log('Rebuilding adapter'); let newCanvas = document.createElement('canvas'); newCanvas.width = canvas.width; newCanvas.height = canvas.height; newCanvas.style.maxWidth = canvas.style.maxWidth; newCanvas.style.borderRadius = canvas.style.borderRadius; container?.appendChild(newCanvas); canvas.remove(); canvas = newCanvas; graphicsAdapter.dispose(); if (preferredAdapter == 'webgl') { graphicsAdapter = new WebGLAdapter(canvas); } else if (preferredAdapter == 'webgpu') { graphicsAdapter = new WebGPUAdapter(canvas); } } (window as any).shadeupGetGraphicsAdapter = () => graphicsAdapter; let inputValues = new Map(); let lastFrame = performance.now(); let frameCount = 0; let timeCounter = 0; let errCount = 0; let screenshotQueue: RenderOptions[] = []; let screenshotQueueResults: { options: RenderOptions; image: string }[] = []; let keyboardSink = new Map(); let lastFrameMousePosition = [0, 0]; let mouseState: MouseState = { button: [false, false, false], clicked: [false, false, false], screen: [0, 0], uv: [0, 0], startScreen: [0, 0], startUv: [0, 0], deltaUv: [0, 0], frameDeltaUv: [0, 0], deltaScreen: [0, 0], frameDeltaScreen: [0, 0], dragging: false, velocity: 0, wheel: 0, focused: false }; let { getKeyboardState } = initInput(canvas, mouseState, keyboardSink); let { frame: uiFrame, puck, slider, preFrame: uiPreFrame, controls } = initUI(canvas); function resetFrameContext() { lastFrame = performance.now(); timeCounter = 0; frameCount = 0; errCount = 0; cameraRotX = 0; cameraRotY = 0; if ((window as any).env.camera) { let cam = (window as any).env.camera; cam.position = [0, 0, 0]; cam.rotation = [1, 0, 0, 0]; cam.width = canvas.width; cam.height = canvas.height; cam.fov = 90; cam.near = 1; cam.far = 100000; let cam2d = (window as any).env.camera2d; cam2d.position = [0, 0]; cam2d.zoom = 1; cameraConfig = { ...defaultCameraConfig }; targetOrbitDistance = cameraConfig.orbitDistance; } } let cameraConfig = { mode: 'orbit-free', spinning: false, initialPosition: [0, 0, 0], initialPitch: 0, initialYaw: 0, speed: 10, orbitTarget: [0, 0, 0], orbitDistance: 650, orbitPitch: Math.PI / 6, orbitYaw: Math.PI / 4, orbitMinDistance: 0, orbitMaxDistance: 100000, orbitMinPitch: -Math.PI / 2, orbitMaxPitch: Math.PI / 2 - 0.001 }; let defaultCameraConfig = { ...cameraConfig }; function updateFrameContext() { let delta = performance.now() - lastFrame; lastFrame = performance.now(); timeCounter += (delta / 1000) * timeMultiplier; frameCount += 1 * timeMultiplier; let lastFramePos = lastFrameMousePosition; mouseState.frameDeltaScreen = [ mouseState.screen[0] - lastFramePos[0], mouseState.screen[1] - lastFramePos[1] ]; let lastFramePosUv = [lastFramePos[0] / canvas.width, lastFramePos[1] / canvas.height]; mouseState.frameDeltaUv = [ mouseState.uv[0] - lastFramePosUv[0], mouseState.uv[1] - lastFramePosUv[1] ]; mouseState.velocity = Math.sqrt( mouseState.frameDeltaScreen[0] ** 2 + mouseState.frameDeltaScreen[1] ** 2 ); lastFrameMousePosition = [...mouseState.screen]; window.env = { camera: (window as any)?.env?.camera ?? ((window as any)._makeCamera ? new (window as any)._makeCamera({}) : null), camera2d: (window as any)?.env?.camera2d ?? ((window as any)._makeCamera2d ? new (window as any)._makeCamera2d({}) : null), deltaTime: (delta / 1000) * timeMultiplier, time: timeCounter, frame: frameCount, screenSize: [canvas.width, canvas.height], keyboard: getKeyboardState(), mouse: { ...mouseState }, configureCamera(options: { mode?: 'free' | 'orbit' | 'orbit-free'; spinning?: boolean; initialPosition?: [number, number, number]; initialPitch?: float; initialYaw?: float; speed?: float; orbitTarget?: [number, number, number]; orbitDistance?: float; orbitPitch?: float; orbitYaw?: float; orbitMinDistance?: float; orbitMaxDistance?: float; orbitMinPitch?: float; orbitMaxPitch?: float; }) { cameraConfig = { ...cameraConfig, ...options }; targetOrbitDistance = cameraConfig.orbitDistance; }, input(key: string, defaultValue: T): T { return inputValues.get(key) ?? defaultValue; }, output(key: string, value: T) { window.parent.postMessage({ type: 'output', key, value }, '*'); } }; sizeCanvas(); } function clear() { try { graphicsAdapter.clear(); } catch (e) { console.error(e); } } (window as any).flushAdapter = async () => { await graphicsAdapter.flush(); }; window.addEventListener('resize', sizeCanvas); setTimeout(() => { sizeCanvas(); }, 1000); let playing = true; let timeMultiplier = 1; let useAnimationFrame = true; let now = performance.now(); let gatherSpeed = 1; let fpsHistogram = new Array(fpsCanvas.width).fill(0); let fpsHistogramIndex = 0; let lastFps = 0; let fps = 0; let minFps = Infinity; let maxFps = -Infinity; let counter = 0; let isFirstFrame = true; let hasLoadedCode = false; let frameFunc = () => {}; let initFunc = () => {}; let localLerp = (a: number, b: number, t: number) => a * (1 - t) + b * t; async function frameLoop() { try { if (movementFrame) movementFrame(); } catch (e) { console.error(e); } if (playing) { for (let i = screenshotQueue.length - 1; i >= 0; i--) { let item = screenshotQueue[i]; let doCapture = false; if ('frame' in item) { if (item.frame <= frameCount - 1 || (timeMultiplier != 1 && frameCount - 1 > item.frame!)) { doCapture = true; } } if ('time' in item) { if (timeCounter >= item.time!) { doCapture = true; } } console.log('Checking screenshot', item, doCapture); if (doCapture) { // Wait for all commands to finish // Wait an extra event tick for the paint to finish performance.mark('start capture'); performance.mark('wait cap'); if (canvas) { let cacheScreenshotItem = screenshotQueue[i]; screenshotQueue.splice(i, 1); performance.mark('start to url'); // debugger; let data = canvas.toDataURL('image/png'); let ctx = blank.getContext('2d'); ctx?.drawImage(canvas, 0, 0); let blankData = ctx?.getImageData(0, 0, blank.width, blank.height); if (cacheScreenshotItem.$tries && cacheScreenshotItem.$tries > 100 && blankData) { blankData.data[0] = 1; } if (!blankData?.data.some((v) => v != 0)) { console.log('Blank screenshot, retrying', screenshotQueue); if (!cacheScreenshotItem.$tries) cacheScreenshotItem.$tries = 0; cacheScreenshotItem.$tries++; screenshotQueue.push(cacheScreenshotItem); } else { performance.mark('end to url'); console.log('Screenshot captured, sending to parent'); screenshotQueueResults.push({ options: item, image: data }); } } } } updateFrameContext(); uiPreFrame(); fps++; let then = now; now = performance.now(); let dt = now - then; counter += dt; let smoothness = 0.2; if (counter >= 1000) { counter -= 1000; if (lastFps <= 1) { lastFps = 1 / env.deltaTime; } lastFps = Math.round(lastFps * smoothness + fps * (1 - smoothness)); fps = 0; } if (fps >= Infinity) { fps = lastFps; } maxFps = localLerp(maxFps, lastFps, 0.1); minFps = localLerp(minFps, lastFps, 0.1); if (fps < minFps) minFps = lastFps; if (fps > maxFps) maxFps = lastFps; if (counter > 50) { fpsHistogram[fpsHistogramIndex] = 1000 / dt; fpsHistogramIndex = (fpsHistogramIndex + 1) % fpsHistogram.length; } // Draw fps histogram and value // fpsCtx.clearColor = 'transparent'; let width = 96 * window.devicePixelRatio; let histwidth = 64 * window.devicePixelRatio; let textwidth = 32 * window.devicePixelRatio; let height = 20 * window.devicePixelRatio; fpsCtx.clearRect(0, 0, width, height); fpsCtx.fillStyle = 'white'; fpsCtx?.beginPath(); if (true) { for (let j = 0; j < fpsHistogram.length; j++) { let rev = fpsHistogramIndex - j; let i = rev < 0 ? fpsHistogram.length + rev : rev; let x = (1 - j / fpsHistogram.length) * histwidth; let drawHeight = 12 * window.devicePixelRatio; let fpsPercent = Math.min(1, fpsHistogram[i] / maxFps); let top = height - drawHeight * fpsPercent; if (isNaN(top)) { top = height; } if (isNaN(x)) { x = 0; } if (j == 0) { fpsCtx?.moveTo(textwidth + x, top); } // fpsCtx.fillRect(textwidth + x, top, (histwidth / fpsHistogram.length) * 2, bottom - top); fpsCtx.lineTo(textwidth + x, top); } fpsCtx.lineTo(textwidth, height); fpsCtx.lineTo(width, height); fpsCtx.fill(); } fpsCtx.fillStyle = 'white'; let fontStyle = 12 * window.devicePixelRatio + 'px monospace'; if (fpsCtx.font != fontStyle) { fpsCtx.font = fontStyle; } // fpsCtx.font = 12 * window.devicePixelRatio + 'px monospace'; fpsCtx.fillText(lastFps, 0, 18 * window.devicePixelRatio); fpsCtx.lineWidth = 1; // fpsCtx.strokeStyle = 'black'; // fpsCtx.strokeText(lastFps, 0, 24); try { let now = performance.now(); if (graphicsAdapter instanceof WebGPUAdapter) { // We let the adapter clear just before the first draw call to the screen } else { clear(); } // performance.mark('frameStart'); await frameFunc(); paint.flush(); graphicsAdapter.flush(); if (graphicsAdapter instanceof WebGPUAdapter) { graphicsAdapter.trace('endFrame\n\n', {}); } graphicsAdapter.switchContext('draw'); // performance.mark('frameEnd'); for (let tex of textureDestroyQueue) { if (tex.adapter) { tex.adapter.dispose(); } } textureDestroyQueue = []; } catch (e) { if (errCount < 10) { console.error(e); if ((window as any).bubbleError) (window as any).bubbleError(e.toString() + e.stack); errCount++; if (errCount === 10) { console.warn('Too many errors, slowing logs'); } } else { errCount++; if (errCount % 100 === 0) { if ((window as any).bubbleError) (window as any).bubbleError(e.toString() + e.stack); console.error(e); } } } uiFrame(); mouseState.clicked[0] = false; mouseState.clicked[1] = false; mouseState.clicked[2] = false; for (let statKey of stats.keys()) { if ((statsMark.get(statKey) ?? 0) <= 0) { stats.get(statKey)?.remove(); stats.delete(statKey); statsMark.delete(statKey); } else { statsMark.set(statKey, statsMark.get(statKey)! - 1); } } for (let statKey of statsGraph.keys()) { if ((statsGraphMark.get(statKey) ?? 0) <= 0) { statsGraph.get(statKey)?.graph.parentElement?.remove(); statsGraph.delete(statKey); statsGraphMark.delete(statKey); } else { statsGraphMark.set(statKey, statsGraphMark.get(statKey)! - 1); } } if (screenshotQueue.length == 0 && screenshotQueueResults.length > 0) { console.log('Posting screenshot results'); window.parent.postMessage({ type: 'screenshot-results', data: screenshotQueueResults }, '*'); screenshotQueueResults = []; } if (isFirstFrame && hasLoadedCode) { isFirstFrame = false; (async () => { await graphicsAdapter.waitForDraw(); window.parent.postMessage({ type: 'firstFrame' }, '*'); })(); } } } // frameLoop(); function __shadeup_gen_native_shader(code: ShaderCodeMapping, type: ShaderType) { return graphicsAdapter.createShader(code, type); } (window as any).__shadeup_gen_native_shader = __shadeup_gen_native_shader; let registeredShaders = new Map(); function __shadeup_gen_shader( key: string, params: ShaderParamsMapping, code: ShaderCodeMapping, indexMapping: IndexMapping ) { registeredShaders.set(key, new ShadeupShaderSource(params, code, indexMapping)); } (window as any).__shadeup_gen_shader = __shadeup_gen_shader; function __shadeup_make_shader_inst( key: string, params: { [key: string]: string }, closure: Function ) { let shader = registeredShaders.get(key); if (!shader) { throw new Error('Shader not found'); } return shader.instance(params); } (window as any).__shadeup_make_shader_inst = __shadeup_make_shader_inst; let fullscreenVertexShader: GenericShader | null = null; export type TextureComponentType = `${'float' | 'int' | 'uint'}${'' | '2' | '3' | '4'}` | 'uint8'; export class ShadeupTexture3d { size: [number, number, number] = [0, 0, 0]; width: number = 0; height: number = 0; depth: number = 0; adapter: GraphicsAdapter | null = null; innerType: TextureComponentType = 'float4'; isBound = false; boundUnit = -1; dirty = true; payload: any; constructor() {} /** @shadeup=glsl(!texture($self$, $0$)) */ __index(index: [number, number, number]): number[] { return [0, 0, 0, 0]; // return (window as any).__shadeup_texture2d_index(this, index); } __index_assign(index: [number, number, number], value: number[]) { // (window as any).__shadeup_texture2d_index_assign(this, index, value); } } let textureDestroyQueue: ShadeupTexture2d[] = []; let shadeupTextureCounter = 0; export class ShadeupTexture2d { symbol: string; image: HTMLCanvasElement | null = null; loading: boolean = true; size: [number, number] = [0, 0]; width: number = 0; height: number = 0; paint: PaintingContext | null = null; adapter: GraphicsAdapter | null = null; innerType: TextureComponentType = 'float4'; isBound = false; boundUnit = -1; dirty = true; cpuReadDirty = true; cpuWriteDirty = false; cpuData: Uint8Array | Uint32Array | Int32Array | Float32Array | null = null; dataIndexStride = 4; version = 0; payload: any; data: ArrayBuffer | null = null; constructor() { this.symbol = `stx${shadeupTextureCounter++}`; } destroy() { textureDestroyQueue.push(this); } async download() { if (!this.adapter) return; if (this.adapter instanceof WebGPUAdapter) { if (this.adapter.pendingWrites > 0) { graphicsAdapter.flush(); } if (this.adapter.storageDirty) { this.cpuReadDirty = true; } } if (this.cpuReadDirty) { if (this.dirty) { this.flush(); } this.cpuReadDirty = false; this.cpuData = await this.adapter.downloadImage(); } } getData(): Uint32Array | Float32Array | Uint8Array | Int32Array { return this.cpuData!; } downloadAsync(): Promise { return this.download(); } /** @shadeup=glsl(!texture($self$, $0$)) */ __index(index: [number, number]): number[] | number { // if (this.cpuReadDirty) { // await this.download(); // } if (!this.cpuData) return [0, 0, 0, 0]; return this.getFast(index); } getFast: any; setFast: any; init() { this.dataIndexStride = parseInt(this.innerType[this.innerType.length - 1] as any) || 1; if (this.innerType == 'uint8') { this.dataIndexStride = 4; } let width = this.size[0]; if (this.innerType == 'uint8') { this.getFast = (index: [number, number]) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; return [ this.cpuData![i] / 255, this.cpuData![i + 1] / 255, this.cpuData![i + 2] / 255, this.cpuData![i + 3] / 255 ]; }; } else { if (this.dataIndexStride == 4) { this.getFast = (index: [number, number]) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; return [ this.cpuData![i], this.cpuData![i + 1], this.cpuData![i + 2], this.cpuData![i + 3] ]; }; } else if (this.dataIndexStride == 3) { this.getFast = (index: [number, number]) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; return [this.cpuData![i], this.cpuData![i + 1], this.cpuData![i + 2]]; }; } else if (this.dataIndexStride == 2) { this.getFast = (index: [number, number]) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; return [this.cpuData![i], this.cpuData![i + 1]]; }; } else if (this.dataIndexStride == 1) { this.getFast = (index: [number, number]) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; return this.cpuData![i]; }; } } if (this.dataIndexStride == 1) { this.setFast = (index: [number, number], val: any) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; this.cpuWriteDirty = true; this.cpuData![i] = val; }; } else { if (this.innerType == 'uint8') { this.setFast = (index: [number, number], value: any) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; this.cpuWriteDirty = true; this.cpuData![i] = value[2] * 255; this.cpuData![i + 1] = value[1] * 255; this.cpuData![i + 2] = value[0] * 255; this.cpuData![i + 3] = value[3] * 255; }; } else { if (this.dataIndexStride == 4) { this.setFast = (index: [number, number], value: any) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; this.cpuWriteDirty = true; this.cpuData![i] = value[0]; this.cpuData![i + 1] = value[1]; this.cpuData![i + 2] = value[2]; this.cpuData![i + 3] = value[3]; }; } else if (this.dataIndexStride == 3) { this.setFast = (index: [number, number], value: any) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; this.cpuWriteDirty = true; this.cpuData![i] = value[0]; this.cpuData![i + 1] = value[1]; this.cpuData![i + 2] = value[2]; }; } else if (this.dataIndexStride == 2) { this.setFast = (index: [number, number], value: any) => { let i = ((index[1] | 0) * width + (index[0] | 0)) * this.dataIndexStride; this.cpuWriteDirty = true; this.cpuData![i] = value[0]; this.cpuData![i + 1] = value[1]; }; } } } } __index_assign(index: [number, number], value: number[] | number) { // if (this.cpuReadDirty) { // await this.download(); // } if (!this.cpuData) this.fillCpuData(); this.setFast(index, value); } fillCpuData() { let arr; let components = this.dataIndexStride; if (this.innerType.startsWith('float')) { arr = new Float32Array(this.width * this.height * this.dataIndexStride); } else if (this.innerType.startsWith('int')) { arr = new Int32Array(this.width * this.height * this.dataIndexStride); } else if (this.innerType.startsWith('uint')) { arr = new Uint32Array(this.width * this.height * this.dataIndexStride); } else if (this.innerType == 'uint8') { arr = new Uint8Array(this.width * this.height * this.dataIndexStride); } else { throw new Error('Unknown texture type ' + this.innerType); } this.cpuData = arr; } sample(pos: [number, number]): number[] { return [0, 0, 0, 0]; } cpuFlush() { if (this.cpuData && this.cpuWriteDirty && this.adapter) { this.adapter.uploadImage(this.cpuData); } } upload() { this.cpuFlush(); } flush(flushStorage = true) { this.cpuFlush(); if (flushStorage) { if (this.adapter instanceof WebGPUAdapter) { if (this.adapter.storageDirty) { this.adapter.flushStorage(); this.cpuReadDirty = true; } } } if (this.dirty) { this.dirty = false; if (this.adapter?.contextMode == 'draw') { this.adapter?.flush(); } else { this.paint?.flush(); } } } drawAdvanced(config: { fragment: ShadeupShaderInstance; vertex: ShadeupShaderInstance; mesh?: Mesh; instances?: number; indirect?: buffer | buffer>; indirectOffset?: int | uint; indexBuffer?: buffer; attachments: ShadeupTexture2d[]; depthTest?: boolean; depthOnly?: boolean; depth?: ShadeupTexture2d; depthCompare?: | 'greater' | 'less' | 'equal' | 'greater-equal' | 'less-equal' | 'not-equal' | 'always' | 'never'; backfaceCulling?: boolean; }) { if (!this.adapter) return; let drawCall = new ShaderDispatch('draw'); if (config.mesh) { drawCall.drawType = 'geometry'; } else if (config.indexBuffer) { drawCall.drawType = 'indexed'; } if (config.depth) { drawCall.overrideDepth = config.depth; } if (config.indirect) { drawCall.indirectBuffer = config.indirect; } if (config.depthCompare) { drawCall.depthCompare = config.depthCompare; } if ('backfaceCulling' in config) { drawCall.backfaceCulling = config.backfaceCulling!; } if ('indirectOffset' in config) { drawCall.indirectOffset = config.indirectOffset!; } drawCall.instanceCount = config.instances ?? 1; drawCall.attachments = config.attachments ?? null; drawCall.depthOnly = config.depthOnly ?? false; let fragShader = config.fragment.get(this.adapter, 'fragment', { attachments: config.attachments ? config.attachments.map((a) => a.innerType) : undefined }); if (!fragShader) { throw new Error('Fragment shader not found'); } drawCall.setFragmentShader(fragShader); let vertShader = config.vertex.get(this.adapter, 'vertex'); if (!vertShader) { throw new Error('Vertex shader not found'); } drawCall.setVertexShader(vertShader); config.fragment.bindUniforms(drawCall.fragmentUniforms); config.vertex.bindUniforms(drawCall.vertexUniforms); if (config.mesh) { drawCall.setGeometry(config.mesh as any); } else if (config.indexBuffer) { drawCall.setIndexBuffer(config.indexBuffer); } this.adapter.dispatch(drawCall, { depthTest: config.depthTest ?? true }); } draw(geometry: Mesh | any, vertexShader: shader, pixelShader: shader): void; draw(fullScreenPixelShader: shader): void; draw(first: Mesh | any | shader, second?: shader, third?: shader) { this.cpuFlush(); this.dirty = true; this.cpuReadDirty = true; this.version++; if ('vertices' in first && second && third) { this._draw_geometry(first, second as any, third as any); } else if (first && !second && !third) { this._draw_fullscreen(first as any); } } fullscreenVertexShaderInternal: GenericShader | null = null; _draw_fullscreen(pixelShaderInst: ShadeupShaderInstance) { if (!this.adapter) return; if (!this.fullscreenVertexShaderInternal) { this.fullscreenVertexShaderInternal = this.adapter.createShader( { webgl: `#version 300 es precision highp float; in vec3 a_position; in vec3 a_normal; in vec3 a_tangent; in vec3 a_bitangent; in vec2 a_uv; in vec4 a_color; out vec3 _v_position; out vec3 _v_normal; out vec3 _v_tangent; out vec3 _v_bitangent; out vec2 _v_uv; out vec4 _v_color; void main(void) { float x = float((gl_VertexID & 1) << 2); float y = float((gl_VertexID & 2) << 1); _v_uv.x = x * 0.5; _v_uv.y = 1.f - (y * 0.5); gl_Position = vec4(x - 1.0, y - 1.0, 0, 1); }`, webgpu: ` struct VertexOutput { @builtin(position) Position : vec4, @location(0) Normal : vec3, @location(1) Tangent : vec3, @location(2) Bitangent : vec3, @location(3) TexCoord : vec2, @location(4) Color : vec4, @location(5) @interpolate(flat) instanceIndex : u32, @location(6) worldPosition: vec3, }; @vertex fn main( @builtin(vertex_index) VertexIndex : u32 ) -> VertexOutput { var x : f32 = f32((VertexIndex & 1) << 2); var y : f32 = f32((VertexIndex & 2) << 1); var output : VertexOutput; output.Position = vec4(x - 1.0, y - 1.0, 0, 1); output.Normal = vec3(1.0, 0.0, 0.0); output.Tangent = vec3(0.0, 1.0, 0.0); output.Bitangent = vec3(0.0, 0.0, 1.0); output.TexCoord = vec2(x * 0.5, 1.0 - (y * 0.5)); output.Color = vec4(0.0, 0.0, 0.0, 0.0); output.instanceIndex = 0; return output; } `, software: () => {} }, 'vertex' ); } if (!this.fullscreenVertexShaderInternal) { throw new Error('Fullscreen vertex shader not found'); } let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'screen'; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [this.size[0], this.size[1]] ) ); drawCall.setVertexShader(this.fullscreenVertexShaderInternal); let fragShader = pixelShaderInst.get(this.adapter, 'fragment'); if (!fragShader) { throw new Error('Fragment shader not found'); } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); if (!this.$geo) { this.$geo = makeFullscreenQuadGeometry(); } drawCall.setGeometry(this.$geo); this.adapter.dispatch(drawCall, { depthTest: false }); } _draw_geometry( geometry: Geometry, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { this.dirty = true; this.cpuReadDirty = true; this.cpuFlush(); this.version++; if (!this.adapter) return; let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'geometry'; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [this.size[0], this.size[1]] ) ); let fragShader = pixelShaderInst.get(this.adapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(this.adapter, 'vertex'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); drawCall.setGeometry(geometry); this.adapter.dispatch(drawCall); } drawIndexed( indexBuffer: buffer, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { this.dirty = true; this.cpuReadDirty = true; this.cpuFlush(); this.version++; if (!this.adapter) return; let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'indexed'; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); let fragShader = pixelShaderInst.get(this.adapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(this.adapter, 'vertex-indexed'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); drawCall.setIndexBuffer(indexBuffer); this.adapter.dispatch(drawCall); } clear(color: float | [number, number, number, number] | 'auto' = 'auto') { this.dirty = true; this.cpuReadDirty = true; this.cpuFlush(); this.version++; if (!this.adapter) return; this.adapter.clear(false, color); } drawCount( count: number, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { this.dirty = true; this.cpuReadDirty = true; this.cpuFlush(); this.version++; if (!this.adapter) return; let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'count'; drawCall.drawCount = count; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); let fragShader = pixelShaderInst.get(this.adapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(this.adapter, 'vertex-indexed'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); this.adapter.dispatch(drawCall); } drawInstanced( mesh: Mesh, instanceCount: number, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { if (!this.adapter) { return; } let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'geometry'; drawCall.instanceCount = instanceCount; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); let fragShader = pixelShaderInst.get(this.adapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(this.adapter, 'vertex'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); drawCall.setGeometry(mesh); this.adapter.dispatch(drawCall); } } let registeredLoads: [string, string][] = []; (window as any).__shadeup_register_loads = (ids: [string, string][]) => { registeredLoads.push(...ids); }; (window as any).load = (id: string) => { let asset = loadedAssets.get(id); if (!asset) { throw new Error('Asset not found'); } if (asset instanceof HTMLCanvasElement) { if (primedTextureAssets.has(id)) { let a = primedTextureAssets.get(id)!; primedTextureAssets.delete(id); return a; } let tex = (window as any).shadeupMakeTextureInternal( [asset.width, asset.height], '8bit', 'uint8' ) as ShadeupTexture2d; tex.adapter?.drawImage(asset, 0, 0, asset.width, asset.height); tex.adapter?.flush(); return tex; } else if (asset && asset.clone) { return asset.clone(); } return asset; }; const FormatInnerTypeMapping: { [key in `${Exclude}-${TextureComponentType}`]: GPUTextureFormat; } = { '8bit-float': 'r16float', '8bit-float2': 'rg16float', '8bit-float3': 'rgba16float', '8bit-float4': 'rgba16float', '16bit-float': 'r16float', '16bit-float2': 'rg16float', '16bit-float3': 'rgba16float', '16bit-float4': 'rgba16float', '32bit-float': 'r32float', '32bit-float2': 'rg32float', '32bit-float3': 'rgba32float', '32bit-float4': 'rgba32float', '16bit-int': 'r16sint', '16bit-int2': 'rg16sint', '16bit-int3': 'rgba16sint', '16bit-int4': 'rgba16sint', '8bit-int': 'r8sint', '8bit-int2': 'rg8sint', '8bit-int3': 'rgba8sint', '8bit-int4': 'rgba8sint', '32bit-int': 'r32sint', '32bit-int2': 'rg32sint', '32bit-int3': 'rgba32sint', '32bit-int4': 'rgba32sint', '8bit-uint': 'r8uint', '8bit-uint2': 'rg8uint', '8bit-uint3': 'rgba8uint', '8bit-uint4': 'rgba8uint', '16bit-uint': 'r16uint', '16bit-uint2': 'rg16uint', '16bit-uint3': 'rgba16uint', '16bit-uint4': 'rgba16uint', '32bit-uint': 'r32uint', '32bit-uint2': 'rg32uint', '32bit-uint3': 'rgba32uint', '32bit-uint4': 'rgba32uint', '8bit-uint8': 'rgba8unorm', '16bit-uint8': 'rgba16uint', '32bit-uint8': 'rgba32float', 'depth-uint8': 'depth24plus', 'depth-float': 'depth24plus', 'depth-float2': 'depth24plus', 'depth-float3': 'depth24plus', 'depth-float4': 'depth24plus', 'depth-int': 'depth24plus', 'depth-int2': 'depth24plus', 'depth-int3': 'depth24plus', 'depth-int4': 'depth24plus', 'depth-uint': 'depth24plus', 'depth-uint2': 'depth24plus', 'depth-uint3': 'depth24plus', 'depth-uint4': 'depth24plus', 'depth-32-uint8': 'depth32float', 'depth-32-float': 'depth32float', 'depth-32-float2': 'depth32float', 'depth-32-float3': 'depth32float', 'depth-32-float4': 'depth32float', 'depth-32-int': 'depth32float', 'depth-32-int2': 'depth32float', 'depth-32-int3': 'depth32float', 'depth-32-int4': 'depth32float', 'depth-32-uint': 'depth32float', 'depth-32-uint2': 'depth32float', 'depth-32-uint3': 'depth32float', 'depth-32-uint4': 'depth32float' }; function shadeupMakeTextureInternal( size: [number, number] | [number, number, number], format: TextureFormat, innerType: TextureComponentType = 'float4' ) { if (size.length == 3) { size = [Math.floor(size[0]), Math.floor(size[1]), Math.floor(size[2])]; let tex = new ShadeupTexture3d(); tex.innerType = innerType; tex.size = size; tex.width = size[0]; tex.height = size[1]; tex.depth = size[2]; if (preferredAdapter == 'webgl') { tex.adapter = new WebGLAdapter(null); } else if (preferredAdapter == 'webgpu') { tex.adapter = new WebGPUAdapter(null); let webgpu = tex.adapter as WebGPUAdapter; webgpu.textureFormat = tex.innerType; webgpu.headless = true; webgpu.headlessHeight = tex.height; webgpu.headlessWidth = tex.width; webgpu.headlessDepth = tex.depth; webgpu.headlessDimensions = 3; } else { throw new Error('No adapter found'); } tex.adapter.init(); tex.adapter.setViewport(0, 0); return tex; } size = [Math.floor(size[0]), Math.floor(size[1])]; let tex = new ShadeupTexture2d(); tex.innerType = innerType; tex.size = size; tex.width = size[0]; tex.height = size[1]; tex.image = document.createElement('canvas'); // document.body.appendChild(tex.image); tex.image.width = tex.width; tex.image.height = tex.height; if (preferredAdapter == 'webgl') { tex.adapter = new WebGLAdapter(tex.image); } else if (preferredAdapter == 'webgpu') { let gpuTextureFormat: GPUTextureFormat = 'rgba8unorm'; if (format == 'auto') { format = innerType == 'uint8' ? '8bit' : '32bit'; } gpuTextureFormat = FormatInnerTypeMapping[`${format as Exclude<'auto', TextureFormat>}-${innerType}`]; tex.adapter = new WebGPUAdapter(tex.image); let webgpu = tex.adapter as WebGPUAdapter; webgpu.textureFormat = tex.innerType; webgpu.gpuTextureFormat = gpuTextureFormat; webgpu.headless = true; webgpu.headlessHeight = tex.height; webgpu.headlessWidth = tex.width; } else { throw new Error('No adapter found'); } tex.init(); tex.adapter.init(); tex.adapter.setViewport(tex.width, tex.height); tex.paint = new PaintingContext(tex.image, tex.adapter as any); tex.paint.markDirtyCallback = () => { tex.cpuFlush(); tex.dirty = true; tex.cpuReadDirty = true; tex.version++; }; tex.adapter.clear(true); return tex; } (window as any)['shadeupMakeTextureInternal'] = shadeupMakeTextureInternal; function shadeupMakeTextureFromImageLike( img: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas | HTMLVideoElement ) { let tex = shadeupMakeTextureInternal([img.width, img.height], '8bit', 'uint8'); let canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; let ctx = canvas.getContext('2d'); ctx?.drawImage(img, 0, 0); tex.adapter?.drawImage(canvas, 0, 0, img.width, img.height); tex.adapter?.flush(); return tex; } (window as any)['shadeupMakeTextureFromUrlNative'] = (url: string) => { var image = new Image(); image.crossOrigin = 'anonymous'; image.src = `/images/${url}`; let tex = new ShadeupTexture2d(); image.onload = function () { tex.image = document.createElement('canvas'); tex.loading = false; tex.size = [image.width, image.height]; if (!tex.image) return; tex.image.width = image.width; tex.image.height = image.height; let ctx = tex.image.getContext('2d'); ctx?.drawImage(image, 0, 0); graphicsAdapter.unbindTexture(tex); }; return tex; }; let logger = document.createElement('div'); logger.style.position = 'absolute'; logger.style.pointerEvents = 'none'; logger.style.top = '0'; logger.style.left = '0'; logger.style.bottom = '0'; logger.style.width = '100%'; logger.style.overflow = 'auto'; logger.style.display = 'flex'; logger.style.flexDirection = 'column'; logger.style.justifyContent = 'flex-end'; logger.style.fontFamily = 'monospace'; logger.style.color = 'white'; logger.style.backgroundColor = 'rgba(0,0,0,0.5)'; logger.style.borderRadius = 'inherit'; logger.style.zIndex = '1000'; logger.style.display = 'none'; logger.style.paddingBottom = '0.5rem'; let realUiContainer = document.querySelector('.ui-container'); let uiContainer = document.querySelector('.render-container'); if (uiContainer) { uiContainer.appendChild(logger); } let stater = document.createElement('div'); stater.classList.add('stater'); stater.style.position = 'absolute'; stater.style.pointerEvents = 'none'; stater.style.top = '0'; stater.style.right = '0'; stater.style.width = '100%'; stater.style.display = 'flex'; stater.style.flexDirection = 'column'; stater.style.alignItems = 'flex-end'; stater.style.paddingRight = '10px'; stater.style.paddingTop = '10px'; stater.style.fontFamily = 'monospace'; stater.style.color = 'white'; stater.style.zIndex = '1001'; if (uiContainer) { uiContainer.appendChild(stater); } (window as any).__shadeup_print = (...args: any[]) => { logger.style.display = 'flex'; let el = document.createElement('div'); el.style.display = 'flex'; el.style.alignItems = 'center'; el.style.height = 'auto'; el.style.lineHeight = '1em'; el.style.flexShrink = '0'; el.style.borderTop = '1px solid rgba(255,255,255,0.2)'; el.style.backgroundColor = 'rgba(255,255,255,0.05)'; let texts = []; for (let arg of args) { if (typeof arg === 'string') { texts.push(arg); } else { let stringified = JSON.stringify(arg); texts.push(stringified); } } el.innerText = texts.join(' '); if (logger.childElementCount > 50) { logger.removeChild(logger.children[0]); } logger.appendChild(el); }; let stats = new Map(); let statsGraph = new Map< string, { num: HTMLElement; graph: HTMLCanvasElement; ctx: CanvasRenderingContext2D; min: number; max: number; index: number; counter: number; history: number[]; } >(); let statsMark = new Map(); let statsGraphMark = new Map(); function serializeValueToHtml(value: any) { let placesColoring = ['#9abcff', '#aadfaa', '#f0ff76', '#aeaeae']; let displayValue = value.toString(); if (typeof value == 'number') { displayValue = `${splitNumberPlaces(value)}`; } else if (typeof value == 'object') { if (Array.isArray(value)) { if (value.length == 0) { displayValue = `[]`; } else { let numeric = true; for (let v of value) { if (typeof v != 'number') { numeric = false; } } if (numeric) { displayValue = value .map((v, i) => { let index = i % 4; return `${splitNumberPlaces(v)}`; }) .join(' '); } else { displayValue = `[ ${value.map(serializeValueToHtml).join(',')} ]`; } } } else if (typeof value == 'boolean') { if (value) { displayValue = `true`; } else { displayValue = `false`; } } else if (typeof value == 'string') { displayValue = `${value}`; } else { displayValue = JSON.stringify(value); } } return displayValue; } const statTimeout = 144; (window as any).__shadeup_stat = (name: string, value: any) => { if (!stats.has(name)) { let el = document.createElement('div'); el.style.display = 'inline-flex'; el.style.alignItems = 'center'; el.style.backdropFilter = 'blur(1px)'; el.style.borderRadius = '20px'; el.style.padding = '2px 4px'; el.style.background = 'rgba(0,0,0,0.5)'; el.style.fontSize = '12px'; el.style.lineHeight = '12px'; el.style.flexShrink = '0'; el.style.marginBottom = '2px'; stats.set(name, el); stater.appendChild(el); } statsMark.set(name, statTimeout); let el = stats.get(name); if (!el) return; let htm = `${name} ${serializeValueToHtml(value)}`; if (el.innerHTML != htm) { el.innerHTML = htm; } }; (window as any).__shadeup_statGraph = (name: string, value: any, sampleRate: number = 1) => { if (!statsGraph.has(name)) { let el = document.createElement('div'); el.style.display = 'inline-flex'; el.style.alignItems = 'center'; el.style.backdropFilter = 'blur(1px)'; el.style.borderRadius = '20px'; el.style.padding = '2px 4px'; let text = document.createElement('span'); text.style.marginLeft = '8px'; text.innerText = name; el.appendChild(text); el.style.background = 'rgba(0,0,0,0.5)'; el.style.fontSize = '12px'; el.style.lineHeight = '12px'; el.style.flexShrink = '0'; el.style.marginBottom = '2px'; let canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 20; canvas.style.marginLeft = '8px'; canvas.style.borderRadius = '4px'; canvas.style.background = 'rgba(0,0,0,0.3)'; el.appendChild(canvas); let ctx = canvas.getContext('2d'); let num = document.createElement('span'); num.style.marginLeft = '8px'; el.appendChild(num); statsGraph.set(name, { ctx: ctx!, graph: canvas, num, min: value, max: value, index: 0, counter: 0, history: new Array(canvas.width).fill(0) }); stater.appendChild(el); } let statData = statsGraph.get(name)!; statData.counter++; let histMax = localLerp(statData.max, value, 0.1); let histMin = localLerp(statData.min, value, 0.1); for (let subVal of statData.history) { if (subVal < histMin) histMin = subVal; if (subVal > histMax) histMax = subVal; } statData.max = histMax; statData.min = histMin; if (statData.counter % sampleRate == 0) { statData.history[statData.index] = value; statData.index = (statData.index + 1) % statData.history.length; } // Draw fps histogram and value let width = statData.graph.width; let histwidth = width; let height = statData.graph.height; let ctx = statData.ctx; ctx.fillStyle = 'white'; ctx.clearRect(0, 0, width, height); ctx?.beginPath(); for (let j = 0; j < statData.history.length; j++) { let rev = statData.index - j; let i = rev < 0 ? statData.history.length + rev : rev; let x = (1 - j / statData.history.length) * histwidth; let drawHeight = height; let valPercent = Math.min(1, (statData.history[i] - histMin) / (histMax - histMin)); let top = height - drawHeight * valPercent; if (isNaN(top)) { top = height; } if (isNaN(x)) { x = 0; } if (j == 0) { ctx?.moveTo(x, top); } ctx.lineTo(x, top); } ctx.lineTo(0, height); ctx.lineTo(width, height); ctx.fill(); statsGraphMark.set(name, statTimeout); let lastValue = statData.history[statData.index]; let htm = `${serializeValueToHtml(value)}`; if (statData.num.innerHTML != htm) { statData.num.innerHTML = htm; } }; function splitNumberPlaces(num: number) { let parts = ''; let decimalCount = 5; if (num > 100) { decimalCount = 2; } let str = num.toFixed(decimalCount); if (num > 100) { str = str.replace(/\.?0+$/, ''); } let hitDecimal = !str.includes('.'); let counter = 0; for (let i = str.length - 1; i >= 0; i--) { if (hitDecimal) { if (counter == 3) { parts = str[i] + ',' + parts; counter = 0; } else { parts = str[i] + parts; } counter++; } else { parts = str[i] + parts; } if (str[i] == '.') { hitDecimal = true; } } return parts; } const fullscreenGeo = makeFullscreenQuadGeometry(); let flying = false; let orbiting = false; let cameraUnlocked = false; function activateFreeFly() { if (cameraConfig.mode == 'orbit-free') { cameraUnlocked = true; } cameraConfig.mode = 'free'; cameraRotY = cameraConfig.orbitPitch; cameraRotX = cameraConfig.orbitYaw - Math.PI / 2; } function activateOrbit() { if (cameraConfig.mode == 'free') { cameraUnlocked = false; } cameraConfig.mode = 'orbit-free'; // Recalc orbit target, and then pitch and yaw // Reproject orbit target based on our current position and free look let camera = (window as any).env.camera; let currentDist = cameraConfig.orbitDistance; let currentCameraPos = camera.position; let rotation = camera.rotation; let quatMulled = quaternionMul(rotation, [0, 0, 1]); let targetForward: [number, number, number] = [quatMulled[0], quatMulled[1], quatMulled[2]]; cameraConfig.orbitTarget = [ currentCameraPos[0] - targetForward[0] * currentDist, currentCameraPos[1] - targetForward[1] * currentDist, currentCameraPos[2] - targetForward[2] * currentDist ]; // Recalc pitch and yaw let target = cameraConfig.orbitTarget; let position = currentCameraPos; let dx = target[0] - position[0]; let dy = target[1] - position[1]; let dz = target[2] - position[2]; let yaw = Math.atan2(dz, dx); let pitch = Math.atan2(dy, Math.sqrt(dx * dx + dz * dz)); cameraConfig.orbitPitch = -pitch; cameraConfig.orbitYaw = yaw - Math.PI; } window.addEventListener('contextmenu', async (e) => { if (e.target == realUiContainer) { e.preventDefault(); if (cameraConfig.mode == 'orbit-free' || cameraConfig.mode == 'free') { await canvas.requestPointerLock(); flying = true; if (cameraConfig.mode == 'orbit-free') { activateFreeFly(); } canvas.focus(); } } }); window.addEventListener('mousedown', async (e) => { if (e.target == realUiContainer) { if (e.button == 2) { e.preventDefault(); if (cameraConfig.mode == 'orbit-free' || cameraConfig.mode == 'free') { await canvas.requestPointerLock(); canvas.focus(); flying = true; if (cameraConfig.mode == 'orbit-free') { activateFreeFly(); } } } else if (e.buttons == 4) { e.preventDefault(); orbiting = true; } else if (e.button == 0 || e.button == 1) { orbiting = true; } } }); window.addEventListener('mouseup', async (e) => { if (e.target == realUiContainer || e.target == document.body || e.target == canvas) { if (e.button == 2) { e.preventDefault(); if (cameraConfig.mode == 'orbit-free' || cameraConfig.mode == 'free') { document.exitPointerLock(); if (cameraUnlocked) { activateOrbit(); } flying = false; cameraSpeed = defaultCameraSpeed; } } else if (e.buttons == 4) { e.preventDefault(); orbiting = false; } else if (e.button == 0 || e.button == 1) { orbiting = false; } } }); function quaternionFromAxisAngle( axis: [number, number, number], angle: number ): [number, number, number, number] { let halfAngle = angle * 0.5; let sin = Math.sin(halfAngle); let cos = Math.cos(halfAngle); return [axis[0] * sin, axis[1] * sin, axis[2] * sin, cos]; } function normalizeVector3(v: [number, number, number]): [number, number, number] { let len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); return [v[0] / len, v[1] / len, v[2] / len]; } let cameraRotX = 0; let cameraRotY = 0; let cameraPitchVelocity = 0; let cameraYawVelocity = 0; window.addEventListener('mousemove', (e) => { if (e.target == document.body || e.target == realUiContainer || e.target == canvas) { if (e.buttons == 4 || e.buttons == 2) { let camera2d = (window as any).env.camera2d; if (camera2d) { camera2d.position[0] += e.movementX * window.devicePixelRatio; camera2d.position[1] += e.movementY * window.devicePixelRatio; } } if (flying) { let dx = e.movementX; let dy = e.movementY; let camera = (window as any).env.camera; let up: [number, number, number] = [0, 1, 0]; let forward: [number, number, number] = [0, 0, -1]; let right: [number, number, number] = [1, 0, 0]; let cameraRight = quaternionRotate(camera.rotation, right); // Lock the cameraRight vector to the horizontal plane cameraRight[1] = 0; cameraRight = normalizeVector3(cameraRight); // Lock rotation to horizontal plane cameraRotX += dx * 0.001; cameraRotY += dy * 0.001; // let rightRot = quaternionFromAxisAngle(cameraRight, dy * 0.001); // camera.rotation = quaternionMulQuaternion(camera.rotation, rightRot); // let upRot = quaternionFromAxisAngle(up, dx * -0.001); // camera.rotation = quaternionMulQuaternion(camera.rotation, upRot); } else { if (cameraConfig.mode.startsWith('orbit') && orbiting) { if (e.buttons == 1) { cameraYawVelocity += e.movementX * 0.01; cameraPitchVelocity += e.movementY * 0.01; cameraConfig.spinning = false; } else if (e.buttons == 4) { cameraConfig.spinning = false; let camera = (window as any).env.camera; if (camera) { // Move camera cameraConfig.orbitTarget along the camera's right vector and up vector let up: [number, number, number] = [0, 1, 0]; let forward: [number, number, number] = [0, 0, -1]; let right: [number, number, number] = [1, 0, 0]; let cameraRight = quaternionRotate(camera.rotation, right); // Lock the cameraRight vector to the horizontal plane cameraRight = normalizeVector3(cameraRight); let cameraUp = quaternionRotate(camera.rotation, up); cameraUp = normalizeVector3(cameraUp); let cameraForward = quaternionRotate(camera.rotation, forward); cameraForward[1] = 0; cameraForward = normalizeVector3(cameraForward); let cameraSpeed = 0.6 * (Math.sqrt(cameraConfig.orbitDistance) / 20); let cameraTarget = cameraConfig.orbitTarget; if (e.shiftKey) { cameraSpeed = 0.01; } if (e.ctrlKey) { cameraSpeed = 1; } cameraTarget[0] += cameraRight[0] * e.movementX * cameraSpeed * -1; cameraTarget[1] += cameraRight[1] * e.movementX * cameraSpeed * -1; cameraTarget[2] += cameraRight[2] * e.movementX * cameraSpeed * -1; cameraTarget[0] += cameraUp[0] * e.movementY * cameraSpeed; cameraTarget[1] += cameraUp[1] * e.movementY * cameraSpeed; cameraTarget[2] += cameraUp[2] * e.movementY * cameraSpeed; cameraConfig.orbitTarget = cameraTarget; } } } } } }); function quaternionRotate( quaternion: [number, number, number, number], vector: [number, number, number] ): [number, number, number] { let [x, y, z] = vector; let [qx, qy, qz, qw] = quaternion; let ix = qw * x + qy * z - qz * y; let iy = qw * y + qz * x - qx * z; let iz = qw * z + qx * y - qy * x; let iw = -qx * x - qy * y - qz * z; return [ ix * qw + iw * -qx + iy * -qz - iz * -qy, iy * qw + iw * -qy + iz * -qx - ix * -qz, iz * qw + iw * -qz + ix * -qy - iy * -qx ]; } function quaternionMul( quat: [number, number, number, number], vec: [number, number, number] ): [number, number, number, number] { let [qx, qy, qz, qw] = quat; let [vx, vy, vz] = vec; let ix = qw * vx + qy * vz - qz * vy; let iy = qw * vy + qz * vx - qx * vz; let iz = qw * vz + qx * vy - qy * vx; let iw = -qx * vx - qy * vy - qz * vz; return [ ix * qw + iw * -qx + iy * -qz - iz * -qy, iy * qw + iw * -qy + iz * -qx - ix * -qz, iz * qw + iw * -qz + ix * -qy - iy * -qx, iw * qw - ix * -qx - iy * -qy - iz * -qz ]; } function quaternionMulQuaternion( a: [number, number, number, number], b: [number, number, number, number] ): [number, number, number, number] { let [ax, ay, az, aw] = a; let [bx, by, bz, bw] = b; let ix = aw * bx + ax * bw + ay * bz - az * by; let iy = aw * by + ay * bw + az * bx - ax * bz; let iz = aw * bz + az * bw + ax * by - ay * bx; let iw = aw * bw - ax * bx - ay * by - az * bz; return [ix, iy, iz, iw]; } let movementForward = 0; let movementRight = 0; let movementUp = 0; let movement = { w: 0, a: 0, s: 0, d: 0, q: 0, e: 0 }; let movementReal = { w: 0, a: 0, s: 0, d: 0, q: 0, e: 0 }; let fovDirection = 0; window.addEventListener('keydown', (e) => { if (e.target && (e.target.closest('input') || e.target.closest('textarea'))) return; if (e.key == 'w') { movement.w = 1; } else if (e.key == 's') { movement.s = 1; } else if (e.key == 'a') { movement.a = 1; } else if (e.key == 'd') { movement.d = 1; } else if (e.key == 'e') { movement.e = 1; } else if (e.key == 'q') { movement.q = 1; } else if (e.key == 'c') { fovDirection = -1; } else if (e.key == 'z') { fovDirection = 1; } }); let targetOrbitDistance = cameraConfig.orbitDistance; window.addEventListener('wheel', (e) => { if (e.target == document.body || e.target == realUiContainer || e.target == canvas) { if (e.deltaY > 0) { cameraSpeed = cameraSpeed / 1.2; } else if (e.deltaY < 0) { cameraSpeed = cameraSpeed * 1.2; } let wheel = normalizeWheel(e); if (cameraConfig.mode.startsWith('orbit')) { targetOrbitDistance = Math.max(0.1, targetOrbitDistance - wheel.spinY * -100); } let camera2d = (window as any).env.camera2d; if (camera2d) { // Zoom to the center of the mouse let mousePos = [mouseState.screen[0], mouseState.screen[1]]; let cameraPos = camera2d.position; let cameraZoom = camera2d.zoom; let zoomDelta = wheel.spinY * 0.1; // Exponential zoom let newZoom = Math.max(0.01, cameraZoom + zoomDelta * cameraZoom); let mouseWorldPos = [ (mousePos[0] - cameraPos[0]) / cameraZoom, (mousePos[1] - cameraPos[1]) / cameraZoom ]; let mouseWorldPos2 = [ (mousePos[0] - cameraPos[0]) / newZoom, (mousePos[1] - cameraPos[1]) / newZoom ]; let mouseWorldDelta = [ mouseWorldPos2[0] - mouseWorldPos[0], mouseWorldPos2[1] - mouseWorldPos[1] ]; camera2d.position = [ cameraPos[0] - mouseWorldDelta[0] * cameraZoom, cameraPos[1] - mouseWorldDelta[1] * cameraZoom ]; camera2d.zoom = newZoom; } } }); window.addEventListener('keyup', (e) => { if (e.key == 'w') { movement.w = 0; } else if (e.key == 's') { movement.s = 0; } else if (e.key == 'a') { movement.a = 0; } else if (e.key == 'd') { movement.d = 0; } else if (e.key == 'e') { movement.e = 0; } else if (e.key == 'q') { movement.q = 0; } else if (e.key == 'c' || e.key == 'z') { fovDirection = 0; } }); let lastFrameMovement = Date.now(); let defaultCameraSpeed = 1; let cameraSpeed = defaultCameraSpeed; function lerp(a: number, b: number, t: number) { return a + (b - a) * t; } function quaternionFromEuler(euler: [number, number, number]): [number, number, number, number] { let [x, y, z] = euler; let c1 = Math.cos(x / 2); let c2 = Math.cos(y / 2); let c3 = Math.cos(z / 2); let s1 = Math.sin(x / 2); let s2 = Math.sin(y / 2); let s3 = Math.sin(z / 2); return [ s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3 ]; } function cross(a: [number, number, number], b: [number, number, number]): [number, number, number] { let [ax, ay, az] = a; let [bx, by, bz] = b; return [ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx]; } function movementFrame() { let now = Date.now(); let dt = now - lastFrameMovement; lastFrameMovement = now; if (cameraConfig.mode == 'orbit-free' || cameraConfig.mode == 'free') { if (!flying) { if ((window as any).env.camera) { (window as any).env.camera.fov = lerp((window as any).env.camera.fov, 90, dt * 0.01); } } } if (cameraConfig.mode == 'orbit' || cameraConfig.mode == 'orbit-free') { { cameraConfig.orbitYaw += cameraYawVelocity * dt * 0.025; cameraConfig.orbitPitch += cameraPitchVelocity * dt * 0.025; cameraYawVelocity = lerp(cameraYawVelocity, 0, dt * 0.03); cameraPitchVelocity = lerp(cameraPitchVelocity, 0, dt * 0.03); cameraConfig.orbitPitch = Math.max( cameraConfig.orbitMinPitch, Math.min(cameraConfig.orbitMaxPitch, cameraConfig.orbitPitch) ); } cameraConfig.orbitDistance = lerp(cameraConfig.orbitDistance, targetOrbitDistance, dt * 0.025); if (cameraConfig.spinning) { cameraConfig.orbitYaw -= dt * 0.0002; } let theta = cameraConfig.orbitYaw; let phi = Math.PI / 2 - cameraConfig.orbitPitch; let orbitTarget = cameraConfig.orbitTarget; let cameraPosition = [ Math.sin(phi) * Math.cos(theta) * cameraConfig.orbitDistance + orbitTarget[0], Math.cos(phi) * cameraConfig.orbitDistance + orbitTarget[1], Math.sin(phi) * Math.sin(theta) * cameraConfig.orbitDistance + orbitTarget[2] ]; let camera = (window as any).env.camera; if (camera) { camera.position = cameraPosition; let quat = (window as any).shadeupQuat; if (quat) { camera.rotation = quat.lookAt( normalizeVector3([ cameraPosition[0] - orbitTarget[0], cameraPosition[1] - orbitTarget[1], cameraPosition[2] - orbitTarget[2] ]), [0, -1, 0] ); } } } else if (cameraConfig.mode == 'free') { const damping = 60; movementReal = { w: lerp(movementReal.w, movement.w, dt / damping), a: lerp(movementReal.a, movement.a, dt / damping), s: lerp(movementReal.s, movement.s, dt / damping), d: lerp(movementReal.d, movement.d, dt / damping), q: lerp(movementReal.q, movement.q, dt / damping), e: lerp(movementReal.e, movement.e, dt / damping) }; let camera = (window as any).env.camera; let up: [number, number, number] = [0, 1, 0]; let forward: [number, number, number] = [0, 0, -1]; let right: [number, number, number] = [1, 0, 0]; if (camera) { cameraRotY = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, cameraRotY)); camera.rotation = quaternionMulQuaternion( quaternionFromEuler([0, -cameraRotX, 0]), quaternionFromEuler([-cameraRotY, 0, 0]) ); } if (!flying) { return; } let rotation = camera.rotation; let quatMulled = quaternionMul(rotation, [0, 0, 1]); let targetForward: [number, number, number] = [quatMulled[0], quatMulled[1], quatMulled[2]]; // targetForward[0] = 2 * (rotation[0] * rotation[2] - rotation[3] * rotation[1]); // targetForward[1] = 2 * (rotation[1] * rotation[2] + rotation[3] * rotation[0]); // targetForward[2] = 1 - 2 * (rotation[0] * rotation[0] + rotation[1] * rotation[1]); let targetUp = up; let targetRight = cross(targetForward, targetUp); targetRight = normalizeVector3(targetRight); movementForward = 0; movementRight = 0; movementUp = 0; movementForward += movementReal.w; movementForward -= movementReal.s; movementRight += movementReal.d; movementRight -= movementReal.a; movementUp += movementReal.e; movementUp -= movementReal.q; movementRight *= -1; movementForward *= -1; let movementVector = [0, 0, 0]; movementVector[0] += targetForward[0] * movementForward; movementVector[1] += targetForward[1] * movementForward; movementVector[2] += targetForward[2] * movementForward; movementVector[0] += targetRight[0] * movementRight; movementVector[1] += targetRight[1] * movementRight; movementVector[2] += targetRight[2] * movementRight; movementVector[0] += targetUp[0] * movementUp; movementVector[1] += targetUp[1] * movementUp; movementVector[2] += targetUp[2] * movementUp; // let dist = Math.sqrt( // movementVector[0] * movementVector[0] + // movementVector[1] * movementVector[1] + // movementVector[2] * movementVector[2] // ); // if (dist > 0) { // movementVector[0] /= dist; // movementVector[1] /= dist; // movementVector[2] /= dist; // } camera.position = [ camera.position[0] + movementVector[0] * dt * cameraSpeed, camera.position[1] + movementVector[1] * dt * cameraSpeed, camera.position[2] + movementVector[2] * dt * cameraSpeed ]; camera.fov += fovDirection * dt * 0.1; camera.fov = Math.max(Math.min(camera.fov, 150), 4); } } // movementFrame(); function __shadeup_dispatch_compute( workgroups: [number, number, number], shaderInst: ShadeupShaderInstance ) { let computeCall = new ShaderDispatch('compute'); computeCall.computeCount = workgroups; let compShader = shaderInst.get(graphicsAdapter, 'compute', { initialDispatch: shaderInst }); if (!compShader) { throw new Error('Fragment shader not found'); } computeCall.setComputeShader(compShader); shaderInst.bindUniforms(computeCall.fragmentUniforms); if (graphicsAdapter instanceof WebGPUAdapter) { graphicsAdapter.dispatchCompute(computeCall); } else { throw new Error('WebGL compute not supported'); } } (window as any).__shadeup_dispatch_compute = __shadeup_dispatch_compute; function __shadeup_dispatch_compute_indirect( indirectBuffer: buffer | buffer>, indirectOffset: number, shaderInst: ShadeupShaderInstance ) { let computeCall = new ShaderDispatch('compute'); computeCall.indirectBuffer = indirectBuffer; computeCall.indirectOffset = indirectOffset; let compShader = shaderInst.get(graphicsAdapter, 'compute', { initialDispatch: shaderInst }); if (!compShader) { throw new Error('Fragment shader not found'); } computeCall.setComputeShader(compShader); shaderInst.bindUniforms(computeCall.fragmentUniforms); if (graphicsAdapter instanceof WebGPUAdapter) { graphicsAdapter.dispatchCompute(computeCall); } else { throw new Error('WebGL compute not supported'); } } (window as any).__shadeup_dispatch_compute_indirect = __shadeup_dispatch_compute_indirect; function __shadeup_dispatch_draw_advanced(config: { fragment: ShadeupShaderInstance; vertex: ShadeupShaderInstance; mesh?: Mesh; instances?: number; indirect?: buffer | buffer>; indexBuffer?: buffer; attachments: ShadeupTexture2d[]; depthTest?: boolean; depthOnly?: boolean; depth?: ShadeupTexture2d; depthCompare?: | 'greater' | 'less' | 'equal' | 'greater-equal' | 'less-equal' | 'not-equal' | 'always' | 'never'; backfaceCulling?: boolean; }) { let drawCall = new ShaderDispatch('draw'); if (config.mesh) { drawCall.drawType = 'geometry'; } else if (config.indexBuffer) { drawCall.drawType = 'indexed'; } if (config.depth) { drawCall.overrideDepth = config.depth; } if (config.depthCompare) { drawCall.depthCompare = config.depthCompare; } if ('backfaceCulling' in config) { drawCall.backfaceCulling = config.backfaceCulling!; } if (config.indirect) { drawCall.indirectBuffer = config.indirect; } drawCall.instanceCount = config.instances ?? 1; drawCall.attachments = config.attachments ?? null; drawCall.depthOnly = config.depthOnly ?? false; let fragShader = config.fragment.get(graphicsAdapter, 'fragment', { attachments: config.attachments ? config.attachments.map((a) => a.innerType) : undefined }); if (!fragShader) { throw new Error('Fragment shader not found'); } drawCall.setFragmentShader(fragShader); let vertShader = config.vertex.get(graphicsAdapter, 'vertex'); if (!vertShader) { throw new Error('Vertex shader not found'); } drawCall.setVertexShader(vertShader); config.fragment.bindUniforms(drawCall.fragmentUniforms); config.vertex.bindUniforms(drawCall.vertexUniforms); if (config.mesh) { drawCall.setGeometry(config.mesh as any); } else if (config.indexBuffer) { drawCall.setIndexBuffer(config.indexBuffer); } graphicsAdapter.dispatch(drawCall, { depthTest: config.depthTest ?? true }); } (window as any).__shadeup_dispatch_draw_advanced = __shadeup_dispatch_draw_advanced; function __shadeup_dispatch_draw(pixelShaderInst: ShadeupShaderInstance) { if (!fullscreenVertexShader) { fullscreenVertexShader = __shadeup_gen_native_shader( { webgl: `#version 300 es precision highp float; in vec3 a_position; in vec3 a_normal; in vec3 a_tangent; in vec3 a_bitangent; in vec2 a_uv; in vec4 a_color; out vec3 _v_position; out vec3 _v_normal; out vec3 _v_tangent; out vec3 _v_bitangent; out vec2 _v_uv; out vec4 _v_color; void main(void) { float x = float((gl_VertexID & 1) << 2); float y = float((gl_VertexID & 2) << 1); _v_uv.x = x * 0.5; _v_uv.y = 1.f - (y * 0.5); gl_Position = vec4(x - 1.0, y - 1.0, 0, 1); }`, webgpu: ` struct VertexOutput { @builtin(position) Position : vec4, @location(0) Normal : vec3, @location(1) Tangent : vec3, @location(2) Bitangent : vec3, @location(3) TexCoord : vec2, @location(4) Color : vec4, @location(5) @interpolate(flat) instanceIndex : u32, @location(6) WorldPosition : vec3, }; @vertex fn main( @builtin(vertex_index) VertexIndex : u32 ) -> VertexOutput { var x : f32 = f32((VertexIndex & 1) << 2); var y : f32 = f32((VertexIndex & 2) << 1); var output : VertexOutput; output.Position = vec4(x - 1.0, y - 1.0, 0, 1); output.Normal = vec3(1.0, 0.0, 0.0); output.Tangent = vec3(0.0, 1.0, 0.0); output.Bitangent = vec3(0.0, 0.0, 1.0); output.TexCoord = vec2(x * 0.5, 1.0 - (y * 0.5)); output.Color = vec4(0.0, 0.0, 0.0, 0.0); output.instanceIndex = 0; return output; } `, software: () => {} }, 'vertex' ); } if (!fullscreenVertexShader) { throw new Error('Fullscreen vertex shader not found'); } let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'screen'; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); drawCall.setVertexShader(fullscreenVertexShader); let fragShader = pixelShaderInst.get(graphicsAdapter, 'fragment', { initialDispatch: pixelShaderInst }); if (!fragShader) { throw new Error('Fragment shader not found'); } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); drawCall.setGeometry(fullscreenGeo as any); graphicsAdapter.dispatch(drawCall, { depthTest: false }); } function makeFullscreenQuadGeometry() { let geo = { vertices: [ [0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0] ], uvs: [ [0, 0], [0, 1], [1, 1], [1, 0] ], triangles: [0, 1, 2], colors: [], normals: [], tangents: [], bitangents: [], getTriangles: () => { return geo.triangles; }, getVertices: () => { return geo.vertices; }, getUVs: () => { return geo.uvs; }, getNormals: (): number[][] => { return []; }, getTangents: (): number[][] => { return []; }, getBitangents: (): number[][] => { return []; }, getColors: (): number[][] => { return []; }, symbol: Symbol() }; return geo; } (window as any).PLATFORM_WEBGL = preferredAdapter == 'webgl'; (window as any).PLATFORM_WEBGPU = preferredAdapter == 'webgpu'; (window as any).__shadeup_dispatch_draw = __shadeup_dispatch_draw; function __shadeup_dispatch_draw_geometry( geometry: Mesh, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'geometry'; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); let fragShader = pixelShaderInst.get(graphicsAdapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(graphicsAdapter, 'vertex'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); drawCall.setGeometry(geometry); graphicsAdapter.dispatch(drawCall); } (window as any).__shadeup_dispatch_draw_geometry = __shadeup_dispatch_draw_geometry; function __shadeup_dispatch_draw_indexed( indexBuffer: buffer, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'indexed'; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); let fragShader = pixelShaderInst.get(graphicsAdapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(graphicsAdapter, 'vertex-indexed'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); drawCall.setIndexBuffer(indexBuffer); graphicsAdapter.dispatch(drawCall); } (window as any).__shadeup_dispatch_draw_indexed = __shadeup_dispatch_draw_indexed; function __shadeup_dispatch_draw_instanced_indexed( indexBuffer: buffer, instanceCount: int, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'indexed'; drawCall.instanceCount = instanceCount; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); let fragShader = pixelShaderInst.get(graphicsAdapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(graphicsAdapter, 'vertex-indexed'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); drawCall.setIndexBuffer(indexBuffer); graphicsAdapter.dispatch(drawCall); } (window as any).__shadeup_dispatch_draw_instanced_indexed = __shadeup_dispatch_draw_instanced_indexed; function __shadeup_dispatch_draw_instanced( mesh: Mesh, instanceCount: int, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'geometry'; drawCall.instanceCount = instanceCount; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); let fragShader = pixelShaderInst.get(graphicsAdapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(graphicsAdapter, 'vertex'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); drawCall.setGeometry(mesh); graphicsAdapter.dispatch(drawCall); } (window as any).__shadeup_dispatch_draw_instanced = __shadeup_dispatch_draw_instanced; function __shadeup_dispatch_draw_count( count: number, vertexShaderInst: ShadeupShaderInstance, pixelShaderInst: ShadeupShaderInstance ) { let drawCall = new ShaderDispatch('draw'); drawCall.drawType = 'count'; drawCall.drawCount = count; drawCall.setVertexUniform( '_vtex_canvas', makePrimitiveUniform( { type: 'primitive', name: 'float2' }, [canvas.width, canvas.height] ) ); let fragShader = pixelShaderInst.get(graphicsAdapter, 'fragment'); if (!fragShader) { return; } drawCall.setFragmentShader(fragShader); pixelShaderInst.bindUniforms(drawCall.fragmentUniforms); let vertShader = vertexShaderInst.get(graphicsAdapter, 'vertex-indexed'); if (!vertShader) { return; } drawCall.setVertexShader(vertShader); vertexShaderInst.bindUniforms(drawCall.vertexUniforms); graphicsAdapter.dispatch(drawCall); } (window as any).__shadeup_dispatch_draw_count = __shadeup_dispatch_draw_count; function __shadeup_get_struct(name) { if (!window.__shadeup_structs) window.__shadeup_structs = {}; return window.__shadeup_structs[name]; } function __shadeup_register_struct(fields, cls) { if (!window.__shadeup_structs) window.__shadeup_structs = {}; window.__shadeup_structs[fields.name] = { fields, struct: cls }; } (window as any).__shadeup_register_struct = __shadeup_register_struct; function __shadeup_error(err, context) { return err || context; if (!err.__shadeup_stack) { return { stack: [context], error: err, message: err.message }; } else { err.stack.push(context); return err; } } let initFuncs = new Map(); let sourceWindow: MessageEventSource | null = null; let sourceOrigin: MessageEventSource | null = null; (window as any).bubbleError = function (err: string) { if (!sourceWindow || !sourceOrigin) { return; } sourceWindow.postMessage(err, sourceOrigin); }; let mainRestart = () => {}; let loadedAssets = new Map(); let primedTextureAssets = new Map(); async function loadLib(name: string) { if (name == 'rapier2d') { console.log('Loading rapier2d'); (window as any).RAPIER_2D = await import('https://cdn.skypack.dev/@dimforge/rapier2d-compat'); console.log('Loaded rapier2d'); await (window as any).RAPIER_2D.init(); console.log('Initialized rapier2d'); } else if (name == 'rapier3d') { (window as any).RAPIER_3D = await import('https://cdn.skypack.dev/@dimforge/rapier3d-compat'); await (window as any).RAPIER_3D.init(); } } async function loadLibs() { console.log('Loading libs', [...registeredLibs.keys()]); await Promise.all( [...registeredLibs.keys()].map(async (lib) => { await loadLib(lib); }) ); } async function loadAssets() { let promises = []; console.log('Loading assets', [...registeredLoads.keys()]); registeredLoads = registeredLoads.filter((load) => { return !loadedAssets.has(load[0]); }); for (let load of registeredLoads) { promises.push( (async () => { let [key, type] = load as [string, AssetFileType]; let baseUrl = 'https://assets.shadeup.dev/'; // if (key.startsWith('models/') || key.startsWith('textures/')) { // baseUrl = 'localhost:5173/assets/'; // } if (type == 'image') { await new Promise((resolve) => { let img = new Image(); img.crossOrigin = 'anonymous'; img.onerror = () => { console.error('Failed to load image ' + key); resolve(); }; img.onload = async () => { let canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; // document.body.appendChild(canvas); let ctx = canvas.getContext('2d'); if (ctx) ctx.drawImage(img, 0, 0); loadedAssets.set(key, canvas); let tex = (window as any).shadeupMakeTextureInternal( [canvas.width, canvas.height], '8bit', 'uint8' ) as ShadeupTexture2d; tex.adapter?.drawImage(canvas, 0, 0, canvas.width, canvas.height); tex.adapter?.flush(); if (tex.adapter instanceof WebGPUAdapter) { await tex.adapter.waitForDraw(); } primedTextureAssets.set(key, tex); resolve(); }; img.src = baseUrl + key; }); } else if (type == 'audio') { await new Promise((resolve) => { let audio = new Audio(); audio.oncanplaythrough = () => { loadedAssets.set(key, audio); resolve(); }; audio.src = baseUrl + key; }); } else if (type == 'video') { await new Promise((resolve) => { let video = document.createElement('video'); video.oncanplaythrough = () => { loadedAssets.set(key, video); resolve(); }; video.src = baseUrl + key; }); } else { let raw = fetch(baseUrl + key); if (type == 'binary') { await raw .then((res) => res.arrayBuffer()) .then((res) => { loadedAssets.set(key, res); }); } else if (type == 'text') { await raw .then((res) => res.text()) .then((res) => { loadedAssets.set(key, res); }); } else if (type == 'model') { await raw .then((res) => res.arrayBuffer()) .then(async (res) => { const { GLTFLoader } = await import('three/examples/jsm/loaders/GLTFLoader'); const { Vector3, Mesh: THREEMesh, MeshStandardMaterial } = await import('three'); const { DRACOLoader } = await import('three/examples/jsm/loaders/DRACOLoader'); const dracoLoader = new DRACOLoader(); dracoLoader.setDecoderPath('/lib/draco/'); const loader = new GLTFLoader(); loader.setDRACOLoader(dracoLoader); let out = await new Promise((reso, rej) => { loader.parse( res, '', (d) => { reso(d); }, (e) => { rej(e); } ); }); let parts: any[] = []; let scene = out.scene; class SHD_Mesh {} function convertMesh(mesh: THREE.Mesh): SHD_Mesh { let positions: [number, number, number][] = []; let normals: [number, number, number][] = []; let tangents: [number, number, number][] = []; let bitangents: [number, number, number][] = []; let uvs: [number, number][] = []; let colors: [number, number, number, number][] = []; let indices: number[] = []; if (mesh.geometry.index) { for (let i = 0; i < mesh.geometry.index.count; i++) { indices.push(mesh.geometry.index?.array[i]); } } if (mesh.geometry.attributes.position) { for (let i = 0; i < mesh.geometry.attributes.position.array.length; i += 3) { positions.push([ mesh.geometry.attributes.position.array[i], mesh.geometry.attributes.position.array[i + 1], mesh.geometry.attributes.position.array[i + 2] ]); } } if (mesh.geometry.attributes.normal) { for (let i = 0; i < mesh.geometry.attributes.normal.array.length; i += 3) { normals.push([ mesh.geometry.attributes.normal.array[i], mesh.geometry.attributes.normal.array[i + 1], mesh.geometry.attributes.normal.array[i + 2] ]); } } if (mesh.geometry.attributes.tangent) { for (let i = 0; i < mesh.geometry.attributes.tangent.array.length; i += 4) { tangents.push([ mesh.geometry.attributes.tangent.array[i], mesh.geometry.attributes.tangent.array[i + 1], mesh.geometry.attributes.tangent.array[i + 2] ]); } } if (mesh.geometry.attributes.bitangent) { for (let i = 0; i < mesh.geometry.attributes.bitangent.array.length; i += 3) { bitangents.push([ mesh.geometry.attributes.bitangent.array[i], mesh.geometry.attributes.bitangent.array[i + 1], mesh.geometry.attributes.bitangent.array[i + 2] ]); } } if (mesh.geometry.attributes.uv) { for (let i = 0; i < mesh.geometry.attributes.uv.array.length; i += 2) { uvs.push([ mesh.geometry.attributes.uv.array[i], mesh.geometry.attributes.uv.array[i + 1] ]); } } if (mesh.geometry.attributes.color) { for (let i = 0; i < mesh.geometry.attributes.color.array.length; i += 4) { colors.push([ mesh.geometry.attributes.color.array[i], mesh.geometry.attributes.color.array[i + 1], mesh.geometry.attributes.color.array[i + 2], mesh.geometry.attributes.color.array[i + 3] ]); } } let m = new (window as any).SHD_Mesh({}) as any; m.vertices = positions; m.normals = normals; m.uvs = uvs; m.colors = colors; m.triangles = indices; return m; } function convertTexMap(map: THREE.Texture): ShadeupTexture2d { let t = shadeupMakeTextureFromImageLike(map.source.data); return t; } scene.traverse((obj) => { if (obj instanceof THREEMesh && obj.isMesh) { let mobj = obj as THREE.Mesh; let m = convertMesh(mobj); let mat = mobj.material; let part = new (window as any).SHD_ModelPart({}) as any; if (!Array.isArray(mat)) { let shdMat = new (window as any).SHD_Material({}) as any; if (mat instanceof MeshStandardMaterial) { shdMat.baseColor = [mat.color.r, mat.color.g, mat.color.b, 1]; if (mat.normalMap) { shdMat.normal = convertTexMap(mat.normalMap); shdMat.normalScale = [mat.normalScale.x, mat.normalScale.y]; } if (mat.map) { shdMat.color = convertTexMap(mat.map); } if (mat.metalnessMap) { shdMat.metallic = convertTexMap(mat.metalnessMap); } if (mat.roughnessMap) { shdMat.roughness = convertTexMap(mat.roughnessMap); } if (mat.emissiveMap) { shdMat.emissive = convertTexMap(mat.emissiveMap); } part.material = shdMat; } } part.mesh = m; let world = obj.getWorldPosition(new Vector3()); part.position = [world.x, world.y, world.z]; parts.push(part); } }); let model = new (window as any).SHD_Model({}) as any; model.parts = parts; loadedAssets.set(key, model); }); } } })() ); } await Promise.all(promises); console.log('Loaded assets', [...loadedAssets.keys()]); } window.addEventListener('message', async function (e: MessageEvent) { var mainWindow = e.source; sourceWindow = mainWindow; sourceOrigin = e.origin; var result = ''; if (e.data.type == 'frame') { logger.innerHTML = ''; logger.style.display = 'none'; fpsCanvas.style.display = 'block'; try { let files: ShadeupRenderedFile[] = e.data.files; let hasMain = files.some((f) => f.path == '/main.js'); registeredLoads.splice(0, registeredLoads.length); registeredLibs.clear(); // loadedAssets.clear(); // console.log(e.data); for (let file of files) { // console.log(file); (() => { let define = (deps: string[], func: Function) => { globalDefine(file.path, deps, func); }; (window as any).define = define; try { let f = new Function(`${file.contents}`); f(); } catch (e: any) { console.error(e); result = e.message; console.log(file.contents); } })(); } globalRequire(['/_std/mesh.js'])[0]; // Load any assets before calling main await loadAssets(); await loadLibs(); if (hasMain) { try { let outs = globalRequire(['/main.js'])[0]; if (typeof outs.main === 'function') { frameFunc = outs.main; hasLoadedCode = true; } else { result = 'main is not a function'; } } catch (e) { console.error(e); result = e.message; } mainRestart = () => { try { let outs = globalRequire(['/main.js'])[0]; if (typeof outs.main === 'function') { frameFunc = outs.main; hasLoadedCode = true; } else { result = 'main is not a function'; } } catch (e) { console.error(e); } }; } } catch (e) { console.error(e); result = 'eval() threw an exception.'; } mainWindow.postMessage(result, e.origin); } else if (e.data.type == 'preview') { console.log('preview received', e.data); registeredLoads.splice(0, registeredLoads.length); registeredLibs.clear(); // loadedAssets.clear(); isFirstFrame = true; hasLoadedCode = false; frameFunc = () => {}; clear(); (() => { let define = (path: string, deps: string[], func: Function) => { globalDefine(path, deps, func); }; (window as any).define = define; try { let f = new Function(`${e.data.code}`); f(); } catch (e: any) { console.error(e); result = e.message; } })(); globalRequire(['/_std/mesh.js'])[0]; await loadAssets(); await loadLibs(); try { let outs = globalRequire(['/main.js'])[0]; if (typeof outs.main === 'function') { frameFunc = outs.main; hasLoadedCode = true; } else { result = 'main is not a function'; } } catch (e) { console.log(e); (window as any).bubbleError(e.message); } sizeCanvas(); } else if (e.data.type == 'focus') { mouseState.focused = e.data.focused; mouseState.button[0] = false; mouseState.button[1] = false; mouseState.button[2] = false; mouseState.dragging = false; } else if (e.data.type == 'restart') { registeredLoads.splice(0, registeredLoads.length); registeredLibs.clear(); // loadedAssets.clear(); resetFrameContext(); logger.innerHTML = ''; logger.style.display = 'none'; sizeCanvas(); mainRestart(); } else if (e.data.type == 'kill') { registeredLoads.splice(0, registeredLoads.length); registeredLibs.clear(); loadedAssets.clear(); clear(); frameFunc = () => {}; isFirstFrame = true; hasLoadedCode = false; resetFrameContext(); } else if (e.data.type == 'frameless') { fpsCanvas.style.display = 'none'; } else if (e.data.type == 'meta') { console.log('got meta', e.data); lastFrame = performance.now(); playing = e.data.playing; if (e.data.timeMultiplier) { timeMultiplier = e.data.timeMultiplier; } if ('useAnimationFrame' in e.data) { useAnimationFrame = e.data.useAnimationFrame; } if (e.data.roundedCorners) { if (!container) return; let containerEl = container as HTMLElement; if (e.data.roundedCorners.topLeft) { canvas.style.borderTopLeftRadius = '0.75rem'; containerEl.style.borderTopLeftRadius = '0.75rem'; } else { canvas.style.borderTopLeftRadius = '0'; containerEl.style.borderTopLeftRadius = '0'; } if (e.data.roundedCorners.topRight) { canvas.style.borderTopRightRadius = '0.75rem'; containerEl.style.borderTopRightRadius = '0.75rem'; } else { canvas.style.borderTopRightRadius = '0'; containerEl.style.borderTopRightRadius = '0'; } if (e.data.roundedCorners.bottomLeft) { canvas.style.borderBottomLeftRadius = '0.75rem'; containerEl.style.borderBottomLeftRadius = '0.75rem'; } else { canvas.style.borderBottomLeftRadius = '0'; containerEl.style.borderBottomLeftRadius = '0'; } if (e.data.roundedCorners.bottomRight) { canvas.style.borderBottomRightRadius = '0.75rem'; containerEl.style.borderBottomRightRadius = '0.75rem'; } else { canvas.style.borderBottomRightRadius = '0'; containerEl.style.borderBottomRightRadius = '0'; } } if ('transparent' in e.data) { if (container && container instanceof HTMLElement) { if (e.data.transparent) { container.style.backgroundColor = 'transparent'; } else { container.style.backgroundColor = '#111111'; } } } if (e.data.fullscreen) { this.document.body.classList.add('fullscreen'); } else { this.document.body.classList.remove('fullscreen'); } } else if (e.data.type == 'screenshot') { if (canvas) { let data = canvas.toDataURL('image/png'); mainWindow.postMessage( { type: 'screenshot', data: data, width: canvas.width, height: canvas.height }, e.origin ); } else { mainWindow.postMessage({ type: 'screenshot', data: null }, e.origin); } } else if (e.data.type == 'video') { if (canvas) { let framerate = e.data.framerate ?? 30; let duration = e.data.duration ?? 10; let width = e.data.width ?? canvas.width; let height = e.data.height ?? canvas.height; let format = e.data.format ?? 'webm'; let videoStream = canvas.captureStream(framerate); let mediaRecorder = new MediaRecorder(videoStream, { videoBitsPerSecond: width * height * framerate * 4 * 8 }); let chunks: Blob[] = []; mediaRecorder.ondataavailable = function (e) { chunks.push(e.data); }; let ogOrigin = e.origin; mediaRecorder.onstop = async function (e) { let blob = new Blob(chunks, { type: 'video/mp4' }); chunks = []; let video = document.createElement('video'); let videoURL = URL.createObjectURL(blob); // video.src = videoURL; // video.style.position = 'absolute'; // video.style.top = '0'; // video.style.left = '0'; // document.body.appendChild(video); if (format == 'mp4') { let funcs = await getFfmpeg(); let out = await funcs.transcode(videoURL); videoURL = out; } let elem = window.document.createElement('a'); elem.href = videoURL; //window.URL.createObjectURL(blob); elem.download = 'shadeup_video_capture.' + format.toLowerCase(); document.body.appendChild(elem); elem.click(); document.body.removeChild(elem); if (mainWindow) mainWindow.postMessage( { type: 'video', data: videoURL, width: canvas.width, height: canvas.height, framerate: framerate, duration: duration }, ogOrigin ); }; mediaRecorder.ondataavailable = function (e) { chunks.push(e.data); }; mediaRecorder.start(); setTimeout(function () { mediaRecorder.stop(); }, duration * 1000); } } else if (e.data.type == 'enqueue-screenshots') { screenshotQueue.push(...e.data.items); } else if (e.data.type == 'get-canvas-size') { mainWindow.postMessage( { type: 'get-canvas-size', width: canvas.width, height: canvas.height }, e.origin ); } else if (e.data.type == 'setInput') { if (!e.data.key) { console.error('No key provided for input'); return; } inputValues.set(e.data.key, e.data.value); } }); function printImage(url: string, size = 10) { var image = new Image(); image.onload = function () { var style = [ 'font-size: 1px;', 'padding: ' + (this.height / 100) * size + 'px ' + (this.width / 100) * size + 'px;', 'background: url(' + url + ') no-repeat;', 'background-size: contain;' ].join(' '); console.log('%c ', style); }; image.src = url; } (window as any)._SHADEUP_UI_PUCK = puck; (window as any)._SHADEUP_UI_SLIDER = slider; (window as any)._SHADEUP_UI_CONTROL = (name: string, ...args: any[]) => { return controls[name](...args); }; window.parent.postMessage({ type: 'ready' }, '*'); function bubbleToParent(e: Event) { if (!sourceWindow || !sourceOrigin) { return; } sourceWindow.postMessage( { type: 'keydown', event: { key: (e as KeyboardEvent).key, ctrlKey: (e as KeyboardEvent).ctrlKey, altKey: (e as KeyboardEvent).altKey, metaKey: (e as KeyboardEvent).metaKey, shiftKey: (e as KeyboardEvent).shiftKey, code: (e as KeyboardEvent).code } }, sourceOrigin ); } function handleKeyDown(e: KeyboardEvent) { if (e.key === 's' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); bubbleToParent(e); } if (e.key === 'r' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); bubbleToParent(e); } } window.addEventListener('keydown', handleKeyDown); (async () => { do { await frameLoop(); if (graphicsAdapter instanceof WebGPUAdapter) { // await graphicsAdapter.waitForDraw(); } if (useAnimationFrame) { await new Promise(requestAnimationFrame); } else { await new Promise(setZeroTimeout); } } while (true); })(); let ffmpegFuncs = {}; let ffmpeg = null; let ffmpegLoaded = false; async function getFfmpeg(): Promise { if (!ffmpegLoaded) { const { FFmpeg } = await import('@ffmpeg/ffmpeg'); const { fetchFile, toBlobURL } = await import('@ffmpeg/util'); const ffmpeg = new FFmpeg(); const baseURL = 'https://unpkg.com/@ffmpeg/core@0.12.2/dist/esm'; ffmpeg.on('log', ({ message }) => { console.log(message); }); // toBlobURL is used to bypass CORS issue, urls with the same // domain can be used directly. await ffmpeg.load({ coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, 'text/javascript'), wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, 'application/wasm') }); ffmpegFuncs = { async transcode(input: string) { await ffmpeg.writeFile('input.webm', await fetchFile(input)); await ffmpeg.exec(['-i', 'input.webm', 'output.mp4']); const data = await ffmpeg.readFile('output.mp4'); let video = document.createElement('video'); let outSrc = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' })); video.src = outSrc; video.autoplay = true; video.loop = true; video.controls = true; document.body.appendChild(video); video.style.position = 'absolute'; video.style.top = '0'; return outSrc; } }; ffmpegLoaded = true; } return ffmpegFuncs; } ================================================ FILE: lang/shadeup/engine/frame-embed.html ================================================ Shadeup engine
================================================ FILE: lang/shadeup/engine/frame-headless.html ================================================ Shadeup engine (headless) ================================================ FILE: lang/shadeup/engine/frame-preview.html ================================================ Shadeup engine
================================================ FILE: lang/shadeup/engine/frame.html ================================================ Shadeup engine
================================================ FILE: lang/shadeup/engine/gltf.js ================================================ var Uo="155";var Hl=0,ba=1,Vl=2;var sl=1,Gl=2,hn=3,jt=0,bt=1,Gt=2;var Tn=0,xi=1,Aa=2,Ta=3,Ea=4,Wl=5,mi=100,Xl=101,ql=102,wa=103,Ra=104,Yl=200,Zl=201,Kl=202,Jl=203,rl=204,ol=205,$l=206,jl=207,Ql=208,eh=209,th=210,nh=0,ih=1,sh=2,Kr=3,rh=4,oh=5,ah=6,ch=7,al=0,lh=1,hh=2,En=0,uh=1,dh=2,fh=3,ph=4,mh=5,cl=300,Mi=301,Si=302,Jr=303,$r=304,lr=306,Zn=1e3,Rt=1001,Ki=1002,st=1003,Fs=1004;var Wi=1005;var vt=1006,Do=1007;var Rn=1008;var wn=1009,gh=1010,_h=1011,No=1012,ll=1013,An=1014,dn=1015,Ji=1016,hl=1017,ul=1018,Wn=1020,xh=1021,Ut=1023,yh=1024,vh=1025,Xn=1026,bi=1027,Mh=1028,dl=1029,Sh=1030,fl=1031,pl=1033,_r=33776,xr=33777,yr=33778,vr=33779,Ca=35840,Pa=35841,La=35842,Ia=35843,bh=36196,Ua=37492,Da=37496,Na=37808,Oa=37809,Fa=37810,Ba=37811,za=37812,ka=37813,Ha=37814,Va=37815,Ga=37816,Wa=37817,Xa=37818,qa=37819,Ya=37820,Za=37821,Mr=36492,Ah=36283,Ka=36284,Ja=36285,$a=36286;var Ai=2300,Kn=2301,Sr=2302,ja=2400,Qa=2401,ec=2402,Th=2500;var ml=0,hr=1,cs=2,gl=3e3,qn=3001,Eh=3200,wh=3201,_l=0,Rh=1,Yn="",xe="srgb",Nt="srgb-linear",xl="display-p3";var br=7680;var Ch=519,Ph=512,Lh=513,Ih=514,Uh=515,Dh=516,Nh=517,Oh=518,Fh=519,jr=35044;var tc="300 es",Qr=1035,fn=2e3,Bs=2001,Cn=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;let n=this._listeners;return n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;let i=this._listeners[e];if(i!==void 0){let r=i.indexOf(t);r!==-1&&i.splice(r,1)}}dispatchEvent(e){if(this._listeners===void 0)return;let n=this._listeners[e.type];if(n!==void 0){e.target=this;let i=n.slice(0);for(let r=0,o=i.length;r>8&255]+dt[s>>16&255]+dt[s>>24&255]+"-"+dt[e&255]+dt[e>>8&255]+"-"+dt[e>>16&15|64]+dt[e>>24&255]+"-"+dt[t&63|128]+dt[t>>8&255]+"-"+dt[t>>16&255]+dt[t>>24&255]+dt[n&255]+dt[n>>8&255]+dt[n>>16&255]+dt[n>>24&255]).toLowerCase()}function pt(s,e,t){return Math.max(e,Math.min(t,s))}function Oo(s,e){return(s%e+e)%e}function Bh(s,e,t,n,i){return n+(s-e)*(i-n)/(t-e)}function zh(s,e,t){return s!==e?(t-s)/(e-s):0}function qi(s,e,t){return(1-t)*s+t*e}function kh(s,e,t,n){return qi(s,e,1-Math.exp(-t*n))}function Hh(s,e=1){return e-Math.abs(Oo(s,e*2)-e)}function Vh(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*(3-2*s))}function Gh(s,e,t){return s<=e?0:s>=t?1:(s=(s-e)/(t-e),s*s*s*(s*(s*6-15)+10))}function Wh(s,e){return s+Math.floor(Math.random()*(e-s+1))}function Xh(s,e){return s+Math.random()*(e-s)}function qh(s){return s*(.5-Math.random())}function Yh(s){s!==void 0&&(nc=s);let e=nc+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function Zh(s){return s*Xi}function Kh(s){return s*Ti}function eo(s){return(s&s-1)===0&&s!==0}function yl(s){return Math.pow(2,Math.ceil(Math.log(s)/Math.LN2))}function zs(s){return Math.pow(2,Math.floor(Math.log(s)/Math.LN2))}function Jh(s,e,t,n,i){let r=Math.cos,o=Math.sin,a=r(t/2),c=o(t/2),l=r((e+n)/2),h=o((e+n)/2),u=r((e-n)/2),d=o((e-n)/2),p=r((n-e)/2),g=o((n-e)/2);switch(i){case"XYX":s.set(a*h,c*u,c*d,a*l);break;case"YZY":s.set(c*d,a*h,c*u,a*l);break;case"ZXZ":s.set(c*u,c*d,a*h,a*l);break;case"XZX":s.set(a*h,c*g,c*p,a*l);break;case"YXY":s.set(c*p,a*h,c*g,a*l);break;case"ZYZ":s.set(c*g,c*p,a*h,a*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Jt(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return s/4294967295;case Uint16Array:return s/65535;case Uint8Array:return s/255;case Int32Array:return Math.max(s/2147483647,-1);case Int16Array:return Math.max(s/32767,-1);case Int8Array:return Math.max(s/127,-1);default:throw new Error("Invalid component type.")}}function Ve(s,e){switch(e.constructor){case Float32Array:return s;case Uint32Array:return Math.round(s*4294967295);case Uint16Array:return Math.round(s*65535);case Uint8Array:return Math.round(s*255);case Int32Array:return Math.round(s*2147483647);case Int16Array:return Math.round(s*32767);case Int8Array:return Math.round(s*127);default:throw new Error("Invalid component type.")}}var vl={DEG2RAD:Xi,RAD2DEG:Ti,generateUUID:Wt,clamp:pt,euclideanModulo:Oo,mapLinear:Bh,inverseLerp:zh,lerp:qi,damp:kh,pingpong:Hh,smoothstep:Vh,smootherstep:Gh,randInt:Wh,randFloat:Xh,randFloatSpread:qh,seededRandom:Yh,degToRad:Zh,radToDeg:Kh,isPowerOfTwo:eo,ceilPowerOfTwo:yl,floorPowerOfTwo:zs,setQuaternionFromProperEuler:Jh,normalize:Ve,denormalize:Jt},Be=class s{constructor(e=0,t=0){s.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(pt(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,o=this.y-e.y;return this.x=r*n-o*i+e.x,this.y=r*i+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Ie=class s{constructor(e,t,n,i,r,o,a,c,l){s.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,i,r,o,a,c,l)}set(e,t,n,i,r,o,a,c,l){let h=this.elements;return h[0]=e,h[1]=i,h[2]=a,h[3]=t,h[4]=r,h[5]=c,h[6]=n,h[7]=o,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,r=this.elements,o=n[0],a=n[3],c=n[6],l=n[1],h=n[4],u=n[7],d=n[2],p=n[5],g=n[8],_=i[0],m=i[3],f=i[6],S=i[1],x=i[4],A=i[7],E=i[2],C=i[5],w=i[8];return r[0]=o*_+a*S+c*E,r[3]=o*m+a*x+c*C,r[6]=o*f+a*A+c*w,r[1]=l*_+h*S+u*E,r[4]=l*m+h*x+u*C,r[7]=l*f+h*A+u*w,r[2]=d*_+p*S+g*E,r[5]=d*m+p*x+g*C,r[8]=d*f+p*A+g*w,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8];return t*o*h-t*a*l-n*r*h+n*a*c+i*r*l-i*o*c}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8],u=h*o-a*l,d=a*c-h*r,p=l*r-o*c,g=t*u+n*d+i*p;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);let _=1/g;return e[0]=u*_,e[1]=(i*l-h*n)*_,e[2]=(a*n-i*o)*_,e[3]=d*_,e[4]=(h*t-i*c)*_,e[5]=(i*r-a*t)*_,e[6]=p*_,e[7]=(n*c-l*t)*_,e[8]=(o*t-n*r)*_,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,r,o,a){let c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*o+l*a)+o+e,-i*l,i*c,-i*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Ar.makeScale(e,t)),this}rotate(e){return this.premultiply(Ar.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ar.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Ar=new Ie;function Ml(s){for(let e=s.length-1;e>=0;--e)if(s[e]>=65535)return!0;return!1}function $i(s){return document.createElementNS("http://www.w3.org/1999/xhtml",s)}var ic={};function Yi(s){s in ic||(ic[s]=!0,console.warn(s))}function yi(s){return s<.04045?s*.0773993808:Math.pow(s*.9478672986+.0521327014,2.4)}function Tr(s){return s<.0031308?s*12.92:1.055*Math.pow(s,.41666)-.055}var $h=new Ie().fromArray([.8224621,.0331941,.0170827,.177538,.9668058,.0723974,-1e-7,1e-7,.9105199]),jh=new Ie().fromArray([1.2249401,-.0420569,-.0196376,-.2249404,1.0420571,-.0786361,1e-7,0,1.0982735]);function Qh(s){return s.convertSRGBToLinear().applyMatrix3(jh)}function eu(s){return s.applyMatrix3($h).convertLinearToSRGB()}var tu={[Nt]:s=>s,[xe]:s=>s.convertSRGBToLinear(),[xl]:Qh},nu={[Nt]:s=>s,[xe]:s=>s.convertLinearToSRGB(),[xl]:eu},zt={enabled:!0,get legacyMode(){return console.warn("THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150."),!this.enabled},set legacyMode(s){console.warn("THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150."),this.enabled=!s},get workingColorSpace(){return Nt},set workingColorSpace(s){console.warn("THREE.ColorManagement: .workingColorSpace is readonly.")},convert:function(s,e,t){if(this.enabled===!1||e===t||!e||!t)return s;let n=tu[e],i=nu[t];if(n===void 0||i===void 0)throw new Error(`Unsupported color space conversion, "${e}" to "${t}".`);return i(n(s))},fromWorkingColorSpace:function(s,e){return this.convert(s,this.workingColorSpace,e)},toWorkingColorSpace:function(s,e){return this.convert(s,e,this.workingColorSpace)}},$n,ks=class{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{$n===void 0&&($n=$i("canvas")),$n.width=e.width,$n.height=e.height;let n=$n.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=$n}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=$i("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let o=0;o0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==cl)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Zn:e.x=e.x-Math.floor(e.x);break;case Rt:e.x=e.x<0?0:1;break;case Ki:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Zn:e.y=e.y-Math.floor(e.y);break;case Rt:e.y=e.y<0?0:1;break;case Ki:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return Yi("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===xe?qn:gl}set encoding(e){Yi("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===qn?xe:Yn}};mt.DEFAULT_IMAGE=null;mt.DEFAULT_MAPPING=cl;mt.DEFAULT_ANISOTROPY=1;var We=class s{constructor(e=0,t=0,n=0,i=1){s.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,r=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*i+o[12]*r,this.y=o[1]*t+o[5]*n+o[9]*i+o[13]*r,this.z=o[2]*t+o[6]*n+o[10]*i+o[14]*r,this.w=o[3]*t+o[7]*n+o[11]*i+o[15]*r,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r,c=e.elements,l=c[0],h=c[4],u=c[8],d=c[1],p=c[5],g=c[9],_=c[2],m=c[6],f=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-_)<.01&&Math.abs(g-m)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+_)<.1&&Math.abs(g+m)<.1&&Math.abs(l+p+f-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let x=(l+1)/2,A=(p+1)/2,E=(f+1)/2,C=(h+d)/4,w=(u+_)/4,k=(g+m)/4;return x>A&&x>E?x<.01?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(x),i=C/n,r=w/n):A>E?A<.01?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(A),n=C/i,r=k/i):E<.01?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(E),n=w/r,i=k/r),this.set(n,i,r,t),this}let S=Math.sqrt((m-g)*(m-g)+(u-_)*(u-_)+(d-h)*(d-h));return Math.abs(S)<.001&&(S=1),this.x=(m-g)/S,this.y=(u-_)/S,this.z=(d-h)/S,this.w=Math.acos((l+p+f-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this.w=this.w<0?Math.ceil(this.w):Math.floor(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},to=class extends Cn{constructor(e=1,t=1,n={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new We(0,0,e,t),this.scissorTest=!1,this.viewport=new We(0,0,e,t);let i={width:e,height:t,depth:1};n.encoding!==void 0&&(Yi("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),n.colorSpace=n.encoding===qn?xe:Yn),this.texture=new mt(i,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=n.generateMipmaps!==void 0?n.generateMipmaps:!1,this.texture.internalFormat=n.internalFormat!==void 0?n.internalFormat:null,this.texture.minFilter=n.minFilter!==void 0?n.minFilter:vt,this.depthBuffer=n.depthBuffer!==void 0?n.depthBuffer:!0,this.stencilBuffer=n.stencilBuffer!==void 0?n.stencilBuffer:!1,this.depthTexture=n.depthTexture!==void 0?n.depthTexture:null,this.samples=n.samples!==void 0?n.samples:0}setSize(e,t,n=1){(this.width!==e||this.height!==t||this.depth!==n)&&(this.width=e,this.height=t,this.depth=n,this.texture.image.width=e,this.texture.image.height=t,this.texture.image.depth=n,this.dispose()),this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.texture.isRenderTargetTexture=!0;let t=Object.assign({},e.texture.image);return this.texture.source=new Hs(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}},pn=class extends to{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Vs=class extends mt{constructor(e=null,t=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=st,this.minFilter=st,this.wrapR=Rt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};var no=class extends mt{constructor(e=null,t=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=st,this.minFilter=st,this.wrapR=Rt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};var Xt=class{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,r,o,a){let c=n[i+0],l=n[i+1],h=n[i+2],u=n[i+3],d=r[o+0],p=r[o+1],g=r[o+2],_=r[o+3];if(a===0){e[t+0]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u;return}if(a===1){e[t+0]=d,e[t+1]=p,e[t+2]=g,e[t+3]=_;return}if(u!==_||c!==d||l!==p||h!==g){let m=1-a,f=c*d+l*p+h*g+u*_,S=f>=0?1:-1,x=1-f*f;if(x>Number.EPSILON){let E=Math.sqrt(x),C=Math.atan2(E,f*S);m=Math.sin(m*C)/E,a=Math.sin(a*C)/E}let A=a*S;if(c=c*m+d*A,l=l*m+p*A,h=h*m+g*A,u=u*m+_*A,m===1-a){let E=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=E,l*=E,h*=E,u*=E}}e[t]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,r,o){let a=n[i],c=n[i+1],l=n[i+2],h=n[i+3],u=r[o],d=r[o+1],p=r[o+2],g=r[o+3];return e[t]=a*g+h*u+c*p-l*d,e[t+1]=c*g+h*d+l*u-a*p,e[t+2]=l*g+h*p+a*d-c*u,e[t+3]=h*g-a*u-c*d-l*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t){let n=e._x,i=e._y,r=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(n/2),h=a(i/2),u=a(r/2),d=c(n/2),p=c(i/2),g=c(r/2);switch(o){case"XYZ":this._x=d*h*u+l*p*g,this._y=l*p*u-d*h*g,this._z=l*h*g+d*p*u,this._w=l*h*u-d*p*g;break;case"YXZ":this._x=d*h*u+l*p*g,this._y=l*p*u-d*h*g,this._z=l*h*g-d*p*u,this._w=l*h*u+d*p*g;break;case"ZXY":this._x=d*h*u-l*p*g,this._y=l*p*u+d*h*g,this._z=l*h*g+d*p*u,this._w=l*h*u-d*p*g;break;case"ZYX":this._x=d*h*u-l*p*g,this._y=l*p*u+d*h*g,this._z=l*h*g-d*p*u,this._w=l*h*u+d*p*g;break;case"YZX":this._x=d*h*u+l*p*g,this._y=l*p*u+d*h*g,this._z=l*h*g-d*p*u,this._w=l*h*u-d*p*g;break;case"XZY":this._x=d*h*u-l*p*g,this._y=l*p*u-d*h*g,this._z=l*h*g+d*p*u,this._w=l*h*u+d*p*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t!==!1&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],i=t[4],r=t[8],o=t[1],a=t[5],c=t[9],l=t[2],h=t[6],u=t[10],d=n+a+u;if(d>0){let p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-c)*p,this._y=(r-l)*p,this._z=(o-i)*p}else if(n>a&&n>u){let p=2*Math.sqrt(1+n-a-u);this._w=(h-c)/p,this._x=.25*p,this._y=(i+o)/p,this._z=(r+l)/p}else if(a>u){let p=2*Math.sqrt(1+a-n-u);this._w=(r-l)/p,this._x=(i+o)/p,this._y=.25*p,this._z=(c+h)/p}else{let p=2*Math.sqrt(1+u-n-a);this._w=(o-i)/p,this._x=(r+l)/p,this._y=(c+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return nMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(pt(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,i=e._y,r=e._z,o=e._w,a=t._x,c=t._y,l=t._z,h=t._w;return this._x=n*h+o*a+i*l-r*c,this._y=i*h+o*c+r*a-n*l,this._z=r*h+o*l+n*c-i*a,this._w=o*h-n*a-i*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let n=this._x,i=this._y,r=this._z,o=this._w,a=o*e._w+n*e._x+i*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=o,this._x=n,this._y=i,this._z=r,this;let c=1-a*a;if(c<=Number.EPSILON){let p=1-t;return this._w=p*o+t*this._w,this._x=p*n+t*this._x,this._y=p*i+t*this._y,this._z=p*r+t*this._z,this.normalize(),this._onChangeCallback(),this}let l=Math.sqrt(c),h=Math.atan2(l,a),u=Math.sin((1-t)*h)/l,d=Math.sin(t*h)/l;return this._w=o*u+this._w*d,this._x=n*u+this._x*d,this._y=i*u+this._y*d,this._z=r*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=Math.random(),t=Math.sqrt(1-e),n=Math.sqrt(e),i=2*Math.PI*Math.random(),r=2*Math.PI*Math.random();return this.set(t*Math.cos(i),n*Math.sin(r),n*Math.cos(r),t*Math.sin(i))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},P=class s{constructor(e=0,t=0,n=0){s.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(sc.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(sc.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,r=e.elements,o=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*o,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*o,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*o,this}applyQuaternion(e){let t=this.x,n=this.y,i=this.z,r=e.x,o=e.y,a=e.z,c=e.w,l=c*t+o*i-a*n,h=c*n+a*t-r*i,u=c*i+r*n-o*t,d=-r*t-o*n-a*i;return this.x=l*c+d*-r+h*-a-u*-o,this.y=h*c+d*-o+u*-r-l*-a,this.z=u*c+d*-a+l*-o-h*-r,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(e,Math.min(t,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,i=e.y,r=e.z,o=t.x,a=t.y,c=t.z;return this.x=i*c-r*a,this.y=r*o-n*c,this.z=n*a-i*o,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return wr.copy(this).projectOnVector(e),this.sub(wr)}reflect(e){return this.sub(wr.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(pt(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=(Math.random()-.5)*2,t=Math.random()*Math.PI*2,n=Math.sqrt(1-e**2);return this.x=n*Math.cos(t),this.y=n*Math.sin(t),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},wr=new P,sc=new Xt,Ot=class{constructor(e=new P(1/0,1/0,1/0),t=new P(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;tthis.max.x||e.ythis.max.y||e.zthis.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.xthis.max.x||e.max.ythis.max.y||e.max.zthis.max.z)}intersectsSphere(e){return this.clampPoint(e.center,sn),sn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Oi),ds.subVectors(this.max,Oi),Qn.subVectors(e.a,Oi),ei.subVectors(e.b,Oi),ti.subVectors(e.c,Oi),yn.subVectors(ei,Qn),vn.subVectors(ti,ei),Bn.subVectors(Qn,ti);let t=[0,-yn.z,yn.y,0,-vn.z,vn.y,0,-Bn.z,Bn.y,yn.z,0,-yn.x,vn.z,0,-vn.x,Bn.z,0,-Bn.x,-yn.y,yn.x,0,-vn.y,vn.x,0,-Bn.y,Bn.x,0];return!Rr(t,Qn,ei,ti,ds)||(t=[1,0,0,0,1,0,0,0,1],!Rr(t,Qn,ei,ti,ds))?!1:(fs.crossVectors(yn,vn),t=[fs.x,fs.y,fs.z],Rr(t,Qn,ei,ti,ds))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,sn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(sn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(nn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),nn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),nn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),nn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),nn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),nn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),nn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),nn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(nn),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},nn=[new P,new P,new P,new P,new P,new P,new P,new P],sn=new P,jn=new Ot,Qn=new P,ei=new P,ti=new P,yn=new P,vn=new P,Bn=new P,Oi=new P,ds=new P,fs=new P,zn=new P;function Rr(s,e,t,n,i){for(let r=0,o=s.length-3;r<=o;r+=3){zn.fromArray(s,r);let a=i.x*Math.abs(zn.x)+i.y*Math.abs(zn.y)+i.z*Math.abs(zn.z),c=e.dot(zn),l=t.dot(zn),h=n.dot(zn);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>a)return!1}return!0}var ru=new Ot,Fi=new P,Cr=new P,Ct=class{constructor(e=new P,t=-1){this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t!==void 0?n.copy(t):ru.setFromPoints(e).getCenter(n);let i=0;for(let r=0,o=e.length;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Fi.subVectors(e,this.center);let t=Fi.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=(n-this.radius)*.5;this.center.addScaledVector(Fi,i/n),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Cr.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Fi.copy(e.center).add(Cr)),this.expandByPoint(Fi.copy(e.center).sub(Cr))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}},rn=new P,Pr=new P,ps=new P,Mn=new P,Lr=new P,ms=new P,Ir=new P,Ei=class{constructor(e=new P,t=new P(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,rn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=rn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(rn.copy(this.origin).addScaledVector(this.direction,t),rn.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Pr.copy(e).add(t).multiplyScalar(.5),ps.copy(t).sub(e).normalize(),Mn.copy(this.origin).sub(Pr);let r=e.distanceTo(t)*.5,o=-this.direction.dot(ps),a=Mn.dot(this.direction),c=-Mn.dot(ps),l=Mn.lengthSq(),h=Math.abs(1-o*o),u,d,p,g;if(h>0)if(u=o*c-a,d=o*a-c,g=r*h,u>=0)if(d>=-g)if(d<=g){let _=1/h;u*=_,d*=_,p=u*(u+o*d+2*a)+d*(o*u+d+2*c)+l}else d=r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*c)+l;else d=-r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*c)+l;else d<=-g?(u=Math.max(0,-(-o*r+a)),d=u>0?-r:Math.min(Math.max(-r,-c),r),p=-u*u+d*(d+2*c)+l):d<=g?(u=0,d=Math.min(Math.max(-r,-c),r),p=d*(d+2*c)+l):(u=Math.max(0,-(o*r+a)),d=u>0?r:Math.min(Math.max(-r,-c),r),p=-u*u+d*(d+2*c)+l);else d=o>0?-r:r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(Pr).addScaledVector(ps,d),p}intersectSphere(e,t){rn.subVectors(e.center,this.origin);let n=rn.dot(this.direction),i=rn.dot(rn)-n*n,r=e.radius*e.radius;if(i>r)return null;let o=Math.sqrt(r-i),a=n-o,c=n+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,o,a,c,l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(n=(e.min.x-d.x)*l,i=(e.max.x-d.x)*l):(n=(e.max.x-d.x)*l,i=(e.min.x-d.x)*l),h>=0?(r=(e.min.y-d.y)*h,o=(e.max.y-d.y)*h):(r=(e.max.y-d.y)*h,o=(e.min.y-d.y)*h),n>o||r>i||((r>n||isNaN(n))&&(n=r),(o=0?(a=(e.min.z-d.z)*u,c=(e.max.z-d.z)*u):(a=(e.max.z-d.z)*u,c=(e.min.z-d.z)*u),n>c||a>i)||((a>n||n!==n)&&(n=a),(c=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,rn)!==null}intersectTriangle(e,t,n,i,r){Lr.subVectors(t,e),ms.subVectors(n,e),Ir.crossVectors(Lr,ms);let o=this.direction.dot(Ir),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;Mn.subVectors(this.origin,e);let c=a*this.direction.dot(ms.crossVectors(Mn,ms));if(c<0)return null;let l=a*this.direction.dot(Lr.cross(Mn));if(l<0||c+l>o)return null;let h=-a*Mn.dot(Ir);return h<0?null:this.at(h/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Ue=class s{constructor(e,t,n,i,r,o,a,c,l,h,u,d,p,g,_,m){s.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,i,r,o,a,c,l,h,u,d,p,g,_,m)}set(e,t,n,i,r,o,a,c,l,h,u,d,p,g,_,m){let f=this.elements;return f[0]=e,f[4]=t,f[8]=n,f[12]=i,f[1]=r,f[5]=o,f[9]=a,f[13]=c,f[2]=l,f[6]=h,f[10]=u,f[14]=d,f[3]=p,f[7]=g,f[11]=_,f[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new s().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){let t=this.elements,n=e.elements,i=1/ni.setFromMatrixColumn(e,0).length(),r=1/ni.setFromMatrixColumn(e,1).length(),o=1/ni.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,i=e.y,r=e.z,o=Math.cos(n),a=Math.sin(n),c=Math.cos(i),l=Math.sin(i),h=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){let d=o*h,p=o*u,g=a*h,_=a*u;t[0]=c*h,t[4]=-c*u,t[8]=l,t[1]=p+g*l,t[5]=d-_*l,t[9]=-a*c,t[2]=_-d*l,t[6]=g+p*l,t[10]=o*c}else if(e.order==="YXZ"){let d=c*h,p=c*u,g=l*h,_=l*u;t[0]=d+_*a,t[4]=g*a-p,t[8]=o*l,t[1]=o*u,t[5]=o*h,t[9]=-a,t[2]=p*a-g,t[6]=_+d*a,t[10]=o*c}else if(e.order==="ZXY"){let d=c*h,p=c*u,g=l*h,_=l*u;t[0]=d-_*a,t[4]=-o*u,t[8]=g+p*a,t[1]=p+g*a,t[5]=o*h,t[9]=_-d*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){let d=o*h,p=o*u,g=a*h,_=a*u;t[0]=c*h,t[4]=g*l-p,t[8]=d*l+_,t[1]=c*u,t[5]=_*l+d,t[9]=p*l-g,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){let d=o*c,p=o*l,g=a*c,_=a*l;t[0]=c*h,t[4]=_-d*u,t[8]=g*u+p,t[1]=u,t[5]=o*h,t[9]=-a*h,t[2]=-l*h,t[6]=p*u+g,t[10]=d-_*u}else if(e.order==="XZY"){let d=o*c,p=o*l,g=a*c,_=a*l;t[0]=c*h,t[4]=-u,t[8]=l*h,t[1]=d*u+_,t[5]=o*h,t[9]=p*u-g,t[2]=g*u-p,t[6]=a*h,t[10]=_*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(ou,e,au)}lookAt(e,t,n){let i=this.elements;return Et.subVectors(e,t),Et.lengthSq()===0&&(Et.z=1),Et.normalize(),Sn.crossVectors(n,Et),Sn.lengthSq()===0&&(Math.abs(n.z)===1?Et.x+=1e-4:Et.z+=1e-4,Et.normalize(),Sn.crossVectors(n,Et)),Sn.normalize(),gs.crossVectors(Et,Sn),i[0]=Sn.x,i[4]=gs.x,i[8]=Et.x,i[1]=Sn.y,i[5]=gs.y,i[9]=Et.y,i[2]=Sn.z,i[6]=gs.z,i[10]=Et.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,r=this.elements,o=n[0],a=n[4],c=n[8],l=n[12],h=n[1],u=n[5],d=n[9],p=n[13],g=n[2],_=n[6],m=n[10],f=n[14],S=n[3],x=n[7],A=n[11],E=n[15],C=i[0],w=i[4],k=i[8],v=i[12],T=i[1],Y=i[5],ne=i[9],B=i[13],V=i[2],G=i[6],$=i[10],W=i[14],q=i[3],Z=i[7],K=i[11],D=i[15];return r[0]=o*C+a*T+c*V+l*q,r[4]=o*w+a*Y+c*G+l*Z,r[8]=o*k+a*ne+c*$+l*K,r[12]=o*v+a*B+c*W+l*D,r[1]=h*C+u*T+d*V+p*q,r[5]=h*w+u*Y+d*G+p*Z,r[9]=h*k+u*ne+d*$+p*K,r[13]=h*v+u*B+d*W+p*D,r[2]=g*C+_*T+m*V+f*q,r[6]=g*w+_*Y+m*G+f*Z,r[10]=g*k+_*ne+m*$+f*K,r[14]=g*v+_*B+m*W+f*D,r[3]=S*C+x*T+A*V+E*q,r[7]=S*w+x*Y+A*G+E*Z,r[11]=S*k+x*ne+A*$+E*K,r[15]=S*v+x*B+A*W+E*D,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],o=e[1],a=e[5],c=e[9],l=e[13],h=e[2],u=e[6],d=e[10],p=e[14],g=e[3],_=e[7],m=e[11],f=e[15];return g*(+r*c*u-i*l*u-r*a*d+n*l*d+i*a*p-n*c*p)+_*(+t*c*p-t*l*d+r*o*d-i*o*p+i*l*h-r*c*h)+m*(+t*l*u-t*a*p-r*o*u+n*o*p+r*a*h-n*l*h)+f*(-i*a*h-t*c*u+t*a*d+i*o*u-n*o*d+n*c*h)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8],u=e[9],d=e[10],p=e[11],g=e[12],_=e[13],m=e[14],f=e[15],S=u*m*l-_*d*l+_*c*p-a*m*p-u*c*f+a*d*f,x=g*d*l-h*m*l-g*c*p+o*m*p+h*c*f-o*d*f,A=h*_*l-g*u*l+g*a*p-o*_*p-h*a*f+o*u*f,E=g*u*c-h*_*c-g*a*d+o*_*d+h*a*m-o*u*m,C=t*S+n*x+i*A+r*E;if(C===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let w=1/C;return e[0]=S*w,e[1]=(_*d*r-u*m*r-_*i*p+n*m*p+u*i*f-n*d*f)*w,e[2]=(a*m*r-_*c*r+_*i*l-n*m*l-a*i*f+n*c*f)*w,e[3]=(u*c*r-a*d*r-u*i*l+n*d*l+a*i*p-n*c*p)*w,e[4]=x*w,e[5]=(h*m*r-g*d*r+g*i*p-t*m*p-h*i*f+t*d*f)*w,e[6]=(g*c*r-o*m*r-g*i*l+t*m*l+o*i*f-t*c*f)*w,e[7]=(o*d*r-h*c*r+h*i*l-t*d*l-o*i*p+t*c*p)*w,e[8]=A*w,e[9]=(g*u*r-h*_*r-g*n*p+t*_*p+h*n*f-t*u*f)*w,e[10]=(o*_*r-g*a*r+g*n*l-t*_*l-o*n*f+t*a*f)*w,e[11]=(h*a*r-o*u*r-h*n*l+t*u*l+o*n*p-t*a*p)*w,e[12]=E*w,e[13]=(h*_*i-g*u*i+g*n*d-t*_*d-h*n*m+t*u*m)*w,e[14]=(g*a*i-o*_*i-g*n*c+t*_*c+o*n*m-t*a*m)*w,e[15]=(o*u*i-h*a*i+h*n*c-t*u*c-o*n*d+t*a*d)*w,this}scale(e){let t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),i=Math.sin(t),r=1-n,o=e.x,a=e.y,c=e.z,l=r*o,h=r*a;return this.set(l*o+n,l*a-i*c,l*c+i*a,0,l*a+i*c,h*a+n,h*c-i*o,0,l*c-i*a,h*c+i*o,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,o){return this.set(1,n,r,0,e,1,o,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){let i=this.elements,r=t._x,o=t._y,a=t._z,c=t._w,l=r+r,h=o+o,u=a+a,d=r*l,p=r*h,g=r*u,_=o*h,m=o*u,f=a*u,S=c*l,x=c*h,A=c*u,E=n.x,C=n.y,w=n.z;return i[0]=(1-(_+f))*E,i[1]=(p+A)*E,i[2]=(g-x)*E,i[3]=0,i[4]=(p-A)*C,i[5]=(1-(d+f))*C,i[6]=(m+S)*C,i[7]=0,i[8]=(g+x)*w,i[9]=(m-S)*w,i[10]=(1-(d+_))*w,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){let i=this.elements,r=ni.set(i[0],i[1],i[2]).length(),o=ni.set(i[4],i[5],i[6]).length(),a=ni.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],kt.copy(this);let l=1/r,h=1/o,u=1/a;return kt.elements[0]*=l,kt.elements[1]*=l,kt.elements[2]*=l,kt.elements[4]*=h,kt.elements[5]*=h,kt.elements[6]*=h,kt.elements[8]*=u,kt.elements[9]*=u,kt.elements[10]*=u,t.setFromRotationMatrix(kt),n.x=r,n.y=o,n.z=a,this}makePerspective(e,t,n,i,r,o,a=fn){let c=this.elements,l=2*r/(t-e),h=2*r/(n-i),u=(t+e)/(t-e),d=(n+i)/(n-i),p,g;if(a===fn)p=-(o+r)/(o-r),g=-2*o*r/(o-r);else if(a===Bs)p=-o/(o-r),g=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=l,c[4]=0,c[8]=u,c[12]=0,c[1]=0,c[5]=h,c[9]=d,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,r,o,a=fn){let c=this.elements,l=1/(t-e),h=1/(n-i),u=1/(o-r),d=(t+e)*l,p=(n+i)*h,g,_;if(a===fn)g=(o+r)*u,_=-2*u;else if(a===Bs)g=r*u,_=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=2*l,c[4]=0,c[8]=0,c[12]=-d,c[1]=0,c[5]=2*h,c[9]=0,c[13]=-p,c[2]=0,c[6]=0,c[10]=_,c[14]=-g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},ni=new P,kt=new Ue,ou=new P(0,0,0),au=new P(1,1,1),Sn=new P,gs=new P,Et=new P,rc=new Ue,oc=new Xt,Gs=class s{constructor(e=0,t=0,n=0,i=s.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let i=e.elements,r=i[0],o=i[4],a=i[8],c=i[1],l=i[5],h=i[9],u=i[2],d=i[6],p=i[10];switch(t){case"XYZ":this._y=Math.asin(pt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-pt(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(pt(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-pt(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(pt(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,p));break;case"XZY":this._z=Math.asin(-pt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return rc.makeRotationFromQuaternion(e),this.setFromRotationMatrix(rc,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return oc.setFromEuler(this),this.setFromQuaternion(oc,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};Gs.DEFAULT_ORDER="XYZ";var Ws=class{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let n=0;n0&&(n=n.concat(o))}return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Bi,e,lu),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Bi,hu,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,i=t.length;n0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON()));function r(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);let a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let c=a.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(n.geometries=a),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),d.length>0&&(n.skeletons=d),p.length>0&&(n.animations=p),g.length>0&&(n.nodes=g)}return n.object=i,n;function o(a){let c=[];for(let l in a){let h=a[l];delete h.metadata,c.push(h)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){Ht.subVectors(i,t),an.subVectors(n,t),Ur.subVectors(e,t);let o=Ht.dot(Ht),a=Ht.dot(an),c=Ht.dot(Ur),l=an.dot(an),h=an.dot(Ur),u=o*l-a*a;if(u===0)return r.set(-2,-1,-1);let d=1/u,p=(l*c-a*h)*d,g=(o*h-a*c)*d;return r.set(1-p-g,g,p)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,cn),cn.x>=0&&cn.y>=0&&cn.x+cn.y<=1}static getUV(e,t,n,i,r,o,a,c){return xs===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),xs=!0),this.getInterpolation(e,t,n,i,r,o,a,c)}static getInterpolation(e,t,n,i,r,o,a,c){return this.getBarycoord(e,t,n,i,cn),c.setScalar(0),c.addScaledVector(r,cn.x),c.addScaledVector(o,cn.y),c.addScaledVector(a,cn.z),c}static isFrontFacing(e,t,n,i){return Ht.subVectors(n,t),an.subVectors(e,t),Ht.cross(an).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ht.subVectors(this.c,this.b),an.subVectors(this.a,this.b),Ht.cross(an).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return s.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return s.getBarycoord(e,this.a,this.b,this.c,t)}getUV(e,t,n,i,r){return xs===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),xs=!0),s.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}getInterpolation(e,t,n,i,r){return s.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return s.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return s.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,r=this.c,o,a;si.subVectors(i,n),ri.subVectors(r,n),Dr.subVectors(e,n);let c=si.dot(Dr),l=ri.dot(Dr);if(c<=0&&l<=0)return t.copy(n);Nr.subVectors(e,i);let h=si.dot(Nr),u=ri.dot(Nr);if(h>=0&&u<=h)return t.copy(i);let d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return o=c/(c-h),t.copy(n).addScaledVector(si,o);Or.subVectors(e,r);let p=si.dot(Or),g=ri.dot(Or);if(g>=0&&p<=g)return t.copy(r);let _=p*l-c*g;if(_<=0&&l>=0&&g<=0)return a=l/(l-g),t.copy(n).addScaledVector(ri,a);let m=h*g-p*u;if(m<=0&&u-h>=0&&p-g>=0)return dc.subVectors(r,i),a=(u-h)/(u-h+(p-g)),t.copy(i).addScaledVector(dc,a);let f=1/(m+_+d);return o=_*f,a=d*f,t.copy(n).addScaledVector(si,o).addScaledVector(ri,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},du=0,Pt=class extends Cn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:du++}),this.uuid=Wt(),this.name="",this.type="Material",this.blending=xi,this.side=jt,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=rl,this.blendDst=ol,this.blendEquation=mi,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=Kr,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Ch,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=br,this.stencilZFail=br,this.stencilZPass=br,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==xi&&(n.blending=this.blending),this.side!==jt&&(n.side=this.side),this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=this.transparent),n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.stencilWrite=this.stencilWrite,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=this.alphaHash),this.alphaToCoverage===!0&&(n.alphaToCoverage=this.alphaToCoverage),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=this.premultipliedAlpha),this.forceSinglePass===!0&&(n.forceSinglePass=this.forceSinglePass),this.wireframe===!0&&(n.wireframe=this.wireframe),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=this.flatShading),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function i(r){let o=[];for(let a in r){let c=r[a];delete c.metadata,o.push(c)}return o}if(t){let r=i(e.textures),o=i(e.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let i=t.length;n=new Array(i);for(let r=0;r!==i;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},Sl={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Vt={h:0,s:0,l:0},ys={h:0,s:0,l:0};function Fr(s,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?s+(e-s)*6*t:t<1/2?e:t<2/3?s+(e-s)*6*(2/3-t):s}var Ae=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=xe){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,zt.toWorkingColorSpace(this,t),this}setRGB(e,t,n,i=zt.workingColorSpace){return this.r=e,this.g=t,this.b=n,zt.toWorkingColorSpace(this,i),this}setHSL(e,t,n,i=zt.workingColorSpace){if(e=Oo(e,1),t=pt(t,0,1),n=pt(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,o=2*n-r;this.r=Fr(o,r,e+1/3),this.g=Fr(o,r,e),this.b=Fr(o,r,e-1/3)}return zt.toWorkingColorSpace(this,i),this}setStyle(e,t=xe){function n(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r,o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){let r=i[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(r,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=xe){let n=Sl[e.toLowerCase()];return n!==void 0?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=yi(e.r),this.g=yi(e.g),this.b=yi(e.b),this}copyLinearToSRGB(e){return this.r=Tr(e.r),this.g=Tr(e.g),this.b=Tr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=xe){return zt.fromWorkingColorSpace(ft.copy(this),e),Math.round(pt(ft.r*255,0,255))*65536+Math.round(pt(ft.g*255,0,255))*256+Math.round(pt(ft.b*255,0,255))}getHexString(e=xe){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=zt.workingColorSpace){zt.fromWorkingColorSpace(ft.copy(this),t);let n=ft.r,i=ft.g,r=ft.b,o=Math.max(n,i,r),a=Math.min(n,i,r),c,l,h=(a+o)/2;if(a===o)c=0,l=0;else{let u=o-a;switch(l=h<=.5?u/(o+a):u/(2-o-a),o){case n:c=(i-r)/u+(i0&&(e.userData=this.userData),this.parameters!==void 0){let c=this.parameters;for(let l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let c in n){let l=n[c];e.data.attributes[c]=l.toJSON(e.data)}let i={},r=!1;for(let c in this.morphAttributes){let l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u0&&(i[c]=h,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);let o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));let a=this.boundingSphere;return a!==null&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone(t));let i=e.attributes;for(let l in i){let h=i[l];this.setAttribute(l,h.clone(t))}let r=e.morphAttributes;for(let l in r){let h=[],u=r[l];for(let d=0,p=u.length;d0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;r(e.far-e.near)**2))&&(fc.copy(r).invert(),kn.copy(e.ray).applyMatrix4(fc),!(n.boundingBox!==null&&kn.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,kn)))}_computeIntersections(e,t,n){let i,r=this.geometry,o=this.material,a=r.index,c=r.attributes.position,l=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,d=r.groups,p=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,_=d.length;g<_;g++){let m=d[g],f=o[m.materialIndex],S=Math.max(m.start,p.start),x=Math.min(a.count,Math.min(m.start+m.count,p.start+p.count));for(let A=S,E=x;At.far?null:{distance:l,point:ws.clone(),object:s}}function Rs(s,e,t,n,i,r,o,a,c,l){s.getVertexPosition(a,ai),s.getVertexPosition(c,ci),s.getVertexPosition(l,li);let h=pu(s,e,t,n,ai,ci,li,Es);if(h){i&&(bs.fromBufferAttribute(i,a),As.fromBufferAttribute(i,c),Ts.fromBufferAttribute(i,l),h.uv=gi.getInterpolation(Es,ai,ci,li,bs,As,Ts,new Be)),r&&(bs.fromBufferAttribute(r,a),As.fromBufferAttribute(r,c),Ts.fromBufferAttribute(r,l),h.uv1=gi.getInterpolation(Es,ai,ci,li,bs,As,Ts,new Be),h.uv2=h.uv1),o&&(mc.fromBufferAttribute(o,a),gc.fromBufferAttribute(o,c),_c.fromBufferAttribute(o,l),h.normal=gi.getInterpolation(Es,ai,ci,li,mc,gc,_c,new P),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let u={a,b:c,c:l,normal:new P,materialIndex:0};gi.getNormal(ai,ci,li,u.normal),h.face=u}return h}var ji=class s extends At{constructor(e=1,t=1,n=1,i=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:o};let a=this;i=Math.floor(i),r=Math.floor(r),o=Math.floor(o);let c=[],l=[],h=[],u=[],d=0,p=0;g("z","y","x",-1,-1,n,t,e,o,r,0),g("z","y","x",1,-1,n,t,-e,o,r,1),g("x","z","y",1,1,e,n,t,i,o,2),g("x","z","y",1,-1,e,n,-t,i,o,3),g("x","y","z",1,-1,e,t,n,i,r,4),g("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(c),this.setAttribute("position",new Dt(l,3)),this.setAttribute("normal",new Dt(h,3)),this.setAttribute("uv",new Dt(u,2));function g(_,m,f,S,x,A,E,C,w,k,v){let T=A/w,Y=E/k,ne=A/2,B=E/2,V=C/2,G=w+1,$=k+1,W=0,q=0,Z=new P;for(let K=0;K<$;K++){let D=K*Y-B;for(let X=0;X0?1:-1,h.push(Z.x,Z.y,Z.z),u.push(X/w),u.push(1-K/k),W+=1}}for(let K=0;K0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},Ys=class extends Qe{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ue,this.projectionMatrix=new Ue,this.projectionMatrixInverse=new Ue,this.coordinateSystem=fn}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(-t[8],-t[9],-t[10]).normalize()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},lt=class extends Ys{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=Ti*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Xi*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Ti*2*Math.atan(Math.tan(Xi*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(e,t,n,i,r,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Xi*.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i,o=this.view;if(this.view!==null&&this.view.enabled){let c=o.fullWidth,l=o.fullHeight;r+=o.offsetX*i/c,t-=o.offsetY*n/l,i*=o.width/c,n*=o.height/l}let a=this.filmOffset;a!==0&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},hi=-90,ui=1,io=class extends Qe{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null;let i=new lt(hi,ui,e,t);i.layers=this.layers,this.add(i);let r=new lt(hi,ui,e,t);r.layers=this.layers,this.add(r);let o=new lt(hi,ui,e,t);o.layers=this.layers,this.add(o);let a=new lt(hi,ui,e,t);a.layers=this.layers,this.add(a);let c=new lt(hi,ui,e,t);c.layers=this.layers,this.add(c);let l=new lt(hi,ui,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,r,o,a,c]=t;for(let l of t)this.remove(l);if(e===fn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===Bs)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let n=this.renderTarget;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,r,o,a,c,l]=this.children,h=e.getRenderTarget(),u=e.xr.enabled;e.xr.enabled=!1;let d=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0),e.render(t,i),e.setRenderTarget(n,1),e.render(t,r),e.setRenderTarget(n,2),e.render(t,o),e.setRenderTarget(n,3),e.render(t,a),e.setRenderTarget(n,4),e.render(t,c),n.texture.generateMipmaps=d,e.setRenderTarget(n,5),e.render(t,l),e.setRenderTarget(h),e.xr.enabled=u,n.texture.needsPMREMUpdate=!0}},Zs=class extends mt{constructor(e,t,n,i,r,o,a,c,l,h){e=e!==void 0?e:[],t=t!==void 0?t:Mi,super(e,t,n,i,r,o,a,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},so=class extends pn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];t.encoding!==void 0&&(Yi("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),t.colorSpace=t.encoding===qn?xe:Yn),this.texture=new Zs(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:vt}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } `,fragmentShader:` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } `},i=new ji(5,5,5),r=new mn({name:"CubemapFromEquirect",uniforms:wi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:bt,blending:Tn});r.uniforms.tEquirect.value=t;let o=new Mt(i,r),a=t.minFilter;return t.minFilter===Rn&&(t.minFilter=vt),new io(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t,n,i){let r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,i);e.setRenderTarget(r)}},kr=new P,yu=new P,vu=new Ie,un=class{constructor(e=new P(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let i=kr.subVectors(n,t).cross(yu.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){let n=e.delta(kr),i=this.normal.dot(n);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||vu.getNormalMatrix(e),i=this.coplanarPoint(kr).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Hn=new Ct,Cs=new P,Qi=class{constructor(e=new un,t=new un,n=new un,i=new un,r=new un,o=new un){this.planes=[e,t,n,i,r,o]}set(e,t,n,i,r,o){let a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(o),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=fn){let n=this.planes,i=e.elements,r=i[0],o=i[1],a=i[2],c=i[3],l=i[4],h=i[5],u=i[6],d=i[7],p=i[8],g=i[9],_=i[10],m=i[11],f=i[12],S=i[13],x=i[14],A=i[15];if(n[0].setComponents(c-r,d-l,m-p,A-f).normalize(),n[1].setComponents(c+r,d+l,m+p,A+f).normalize(),n[2].setComponents(c+o,d+h,m+g,A+S).normalize(),n[3].setComponents(c-o,d-h,m-g,A-S).normalize(),n[4].setComponents(c-a,d-u,m-_,A-x).normalize(),t===fn)n[5].setComponents(c+a,d+u,m+_,A+x).normalize();else if(t===Bs)n[5].setComponents(a,u,_,x).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Hn.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Hn.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Hn)}intersectsSprite(e){return Hn.center.set(0,0,0),Hn.radius=.7071067811865476,Hn.applyMatrix4(e.matrixWorld),this.intersectsSphere(Hn)}intersectsSphere(e){let t=this.planes,n=e.center,i=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)0?e.max.x:e.min.x,Cs.y=i.normal.y>0?e.max.y:e.min.y,Cs.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Cs)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}};function Al(){let s=null,e=!1,t=null,n=null;function i(r,o){t(r,o),n=s.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(n=s.requestAnimationFrame(i),e=!0)},stop:function(){s.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(r){t=r},setContext:function(r){s=r}}}function Mu(s,e){let t=e.isWebGL2,n=new WeakMap;function i(l,h){let u=l.array,d=l.usage,p=s.createBuffer();s.bindBuffer(h,p),s.bufferData(h,u,d),l.onUploadCallback();let g;if(u instanceof Float32Array)g=s.FLOAT;else if(u instanceof Uint16Array)if(l.isFloat16BufferAttribute)if(t)g=s.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else g=s.UNSIGNED_SHORT;else if(u instanceof Int16Array)g=s.SHORT;else if(u instanceof Uint32Array)g=s.UNSIGNED_INT;else if(u instanceof Int32Array)g=s.INT;else if(u instanceof Int8Array)g=s.BYTE;else if(u instanceof Uint8Array)g=s.UNSIGNED_BYTE;else if(u instanceof Uint8ClampedArray)g=s.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+u);return{buffer:p,type:g,bytesPerElement:u.BYTES_PER_ELEMENT,version:l.version}}function r(l,h,u){let d=h.array,p=h.updateRange;s.bindBuffer(u,l),p.count===-1?s.bufferSubData(u,0,d):(t?s.bufferSubData(u,p.offset*d.BYTES_PER_ELEMENT,d,p.offset,p.count):s.bufferSubData(u,p.offset*d.BYTES_PER_ELEMENT,d.subarray(p.offset,p.offset+p.count)),p.count=-1),h.onUploadCallback()}function o(l){return l.isInterleavedBufferAttribute&&(l=l.data),n.get(l)}function a(l){l.isInterleavedBufferAttribute&&(l=l.data);let h=n.get(l);h&&(s.deleteBuffer(h.buffer),n.delete(l))}function c(l,h){if(l.isGLBufferAttribute){let d=n.get(l);(!d||d.version 0 vec4 plane; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif`,Ou=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,Fu=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,Bu=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,zu=`#if defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #elif defined( USE_COLOR ) diffuseColor.rgb *= vColor; #endif`,ku=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; #endif`,Hu=`#if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) varying vec3 vColor; #endif`,Vu=`#if defined( USE_COLOR_ALPHA ) vColor = vec4( 1.0 ); #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) vColor = vec3( 1.0 ); #endif #ifdef USE_COLOR vColor *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.xyz *= instanceColor.xyz; #endif`,Gu=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; struct GeometricContext { vec3 position; vec3 normal; vec3 viewDir; #ifdef USE_CLEARCOAT vec3 clearcoatNormal; #endif }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } mat3 transposeMat3( const in mat3 m ) { mat3 tmp; tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); return tmp; } float luminance( const in vec3 rgb ) { const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 ); return dot( weights, rgb ); } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`,Wu=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_v0 0.339 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_v1 0.276 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_v4 0.046 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_v5 0.016 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_v6 0.0038 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`,Xu=`vec3 transformedNormal = objectNormal; #ifdef USE_INSTANCING mat3 m = mat3( instanceMatrix ); transformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) ); transformedNormal = m * transformedNormal; #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT vec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif #endif`,qu=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,Yu=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,Zu=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); totalEmissiveRadiance *= emissiveColor.rgb; #endif`,Ku=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,Ju="gl_FragColor = linearToOutputTexel( gl_FragColor );",$u=`vec4 LinearToLinear( in vec4 value ) { return value; } vec4 LinearTosRGB( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); }`,ju=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); #else vec4 envColor = vec4( 0.0 ); #endif #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif`,Qu=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`,ed=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`,td=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`,nd=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`,id=`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,sd=`#ifdef USE_FOG varying float vFogDepth; #endif`,rd=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`,od=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,ad=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`,cd=`#ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; reflectedLight.indirectDiffuse += lightMapIrradiance; #endif`,ld=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,hd=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,ud=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,dd=`uniform bool receiveShadow; uniform vec3 ambientLightColor; uniform vec3 lightProbe[ 9 ]; vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { #if defined ( LEGACY_LIGHTS ) if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) { return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent ); } return 1.0; #else float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; #endif } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) { vec3 lVector = pointLight.position - geometry.position; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) { vec3 lVector = spotLight.position - geometry.position; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif`,fd=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`,pd=`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,md=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { vec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,gd=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,_d=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength; } void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,xd=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x - tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x + tbn[ 0 ] * anisotropyV.y; #endif`,yd=`struct PhysicalMaterial { vec3 diffuseColor; float roughness; vec3 specularColor; float specularF90; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecular = vec3( 0.0 ); vec3 sheenSpecular = vec3( 0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); float v = 0.5 / ( gv + gl ); return saturate(v); } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColor; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); return saturate( DG * RECIPROCAL_PI ); } vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); vec4 r = roughness * c0 + c1; float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; return fab; } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { vec2 fab = DFGApprox( normal, viewDir, roughness ); return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #else void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { #endif vec2 fab = DFGApprox( normal, viewDir, roughness ); #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } #if NUM_RECT_AREA_LIGHTS > 0 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { vec3 normal = geometry.normal; vec3 viewDir = geometry.viewDir; vec3 position = geometry.position; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); } #endif void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { float dotNL = saturate( dot( geometry.normal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness ); #endif reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { #ifdef USE_CLEARCOAT clearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness ); #endif vec3 singleScattering = vec3( 0.0 ); vec3 multiScattering = vec3( 0.0 ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); #else computeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); #endif vec3 totalScattering = singleScattering + multiScattering; vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); reflectedLight.indirectSpecular += radiance * singleScattering; reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`,vd=` GeometricContext geometry; geometry.position = - vViewPosition; geometry.normal = normal; geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); #ifdef USE_CLEARCOAT geometry.clearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometry.viewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometry, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometry, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, geometry, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); } #pragma unroll_loop_end #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`,Md=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) iblIrradiance += getIBLIrradiance( geometry.normal ); #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometry.viewDir, geometry.normal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness ); #endif #endif`,Sd=`#if defined( RE_IndirectDiffuse ) RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight ); #endif`,bd=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,Ad=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,Td=`#ifdef USE_LOGDEPTHBUF #ifdef USE_LOGDEPTHBUF_EXT varying float vFragDepth; varying float vIsPerspective; #else uniform float logDepthBufFC; #endif #endif`,Ed=`#ifdef USE_LOGDEPTHBUF #ifdef USE_LOGDEPTHBUF_EXT vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #else if ( isPerspectiveMatrix( projectionMatrix ) ) { gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0; gl_Position.z *= gl_Position.w; } #endif #endif`,wd=`#ifdef USE_MAP diffuseColor *= texture2D( map, vMapUv ); #endif`,Rd=`#ifdef USE_MAP uniform sampler2D map; #endif`,Cd=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`,Pd=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`,Ld=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,Id=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,Ud=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`,Dd=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; #ifdef MORPHTARGETS_TEXTURE for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #else objectNormal += morphNormal0 * morphTargetInfluences[ 0 ]; objectNormal += morphNormal1 * morphTargetInfluences[ 1 ]; objectNormal += morphNormal2 * morphTargetInfluences[ 2 ]; objectNormal += morphNormal3 * morphTargetInfluences[ 3 ]; #endif #endif`,Nd=`#ifdef USE_MORPHTARGETS uniform float morphTargetBaseInfluence; #ifdef MORPHTARGETS_TEXTURE uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #else #ifndef USE_MORPHNORMALS uniform float morphTargetInfluences[ 8 ]; #else uniform float morphTargetInfluences[ 4 ]; #endif #endif #endif`,Od=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; #ifdef MORPHTARGETS_TEXTURE for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #else transformed += morphTarget0 * morphTargetInfluences[ 0 ]; transformed += morphTarget1 * morphTargetInfluences[ 1 ]; transformed += morphTarget2 * morphTargetInfluences[ 2 ]; transformed += morphTarget3 * morphTargetInfluences[ 3 ]; #ifndef USE_MORPHNORMALS transformed += morphTarget4 * morphTargetInfluences[ 4 ]; transformed += morphTarget5 * morphTargetInfluences[ 5 ]; transformed += morphTarget6 * morphTargetInfluences[ 6 ]; transformed += morphTarget7 * morphTargetInfluences[ 7 ]; #endif #endif #endif`,Fd=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 geometryNormal = normal;`,Bd=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`,zd=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,kd=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,Hd=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`,Vd=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`,Gd=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = geometryNormal; #endif`,Wd=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,Xd=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`,qd=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,Yd=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Zd=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.; const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. ); const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. ); const float ShiftRight8 = 1. / 256.; vec4 packDepthToRGBA( const in float v ) { vec4 r = vec4( fract( v * PackFactors ), v ); r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale; } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors ); } vec2 packDepthToRG( in highp float v ) { return packDepthToRGBA( v ).yx; } float unpackRGToDepth( const in highp vec2 v ) { return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) ); } vec4 pack2HalfToRGBA( vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { return depth * ( near - far ) - near; } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { return ( near * far ) / ( ( far - near ) * depth - far ); }`,Kd=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,Jd=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`,$d=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,jd=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`,Qd=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,ef=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,tf=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; struct SpotLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); } vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { return unpackRGBATo2Half( texture2D( shadow, uv ) ); } float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ float occlusion = 1.0; vec2 distribution = texture2DDistribution( shadow, uv ); float hard_shadow = step( compare , distribution.x ); if (hard_shadow != 1.0 ) { float distance = compare - distribution.x ; float variance = max( 0.00000, distribution.y * distribution.y ); float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); } return occlusion; } float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { #if defined( SHADOWMAP_TYPE_PCF ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx0 = - texelSize.x * shadowRadius; float dy0 = - texelSize.y * shadowRadius; float dx1 = + texelSize.x * shadowRadius; float dy1 = + texelSize.y * shadowRadius; float dx2 = dx0 / 2.0; float dy2 = dy0 / 2.0; float dx3 = dx1 / 2.0; float dy3 = dy1 / 2.0; shadow = ( texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) ) * ( 1.0 / 17.0 ); #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float dx = texelSize.x; float dy = texelSize.y; vec2 uv = shadowCoord.xy; vec2 f = fract( uv * shadowMapSize + 0.5 ); uv -= f * texelSize; shadow = ( texture2DCompare( shadowMap, uv, shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), f.x ) + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), f.y ) + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), f.x ), mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), f.x ), f.y ) ) * ( 1.0 / 9.0 ); #elif defined( SHADOWMAP_TYPE_VSM ) shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); #else shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); #endif } return shadow; } vec2 cubeToUV( vec3 v, float texelSizeY ) { vec3 absV = abs( v ); float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); absV *= scaleToCube; v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); vec2 planar = v.xy; float almostATexel = 1.5 * texelSizeY; float almostOne = 1.0 - almostATexel; if ( absV.z >= almostOne ) { if ( v.z > 0.0 ) planar.x = 4.0 - v.x; } else if ( absV.x >= almostOne ) { float signX = sign( v.x ); planar.x = v.z * signX + 2.0 * signX; } else if ( absV.y >= almostOne ) { float signY = sign( v.y ); planar.x = v.x + 2.0 * signY + 2.0; planar.y = v.z * signY - 2.0; } return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); } float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); vec3 lightToPosition = shadowCoord.xyz; float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; return ( texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) ) * ( 1.0 / 9.0 ); #else return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); #endif } #endif`,nf=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`,sf=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`,rf=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`,of=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,af=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; uniform int boneTextureSize; mat4 getBoneMatrix( const in float i ) { float j = i * 4.0; float x = mod( j, float( boneTextureSize ) ); float y = floor( j / float( boneTextureSize ) ); float dx = 1.0 / float( boneTextureSize ); float dy = 1.0 / float( boneTextureSize ); y = dy * ( y + 0.5 ); vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) ); vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) ); vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) ); vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) ); mat4 bone = mat4( v1, v2, v3, v4 ); return bone; } #endif`,cf=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`,lf=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`,hf=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,uf=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,df=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,ff=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 OptimizedCineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } vec3 CustomToneMapping( vec3 color ) { return color; }`,pf=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`,mf=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`,gf=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,_f=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,xf=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`,yf=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`,vf=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`,Mf=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,Sf=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,bf=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float flipEnvMap; uniform float backgroundBlurriness; uniform float backgroundIntensity; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,Af=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,Tf=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`,Ef=`#include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`,wf=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include vec4 diffuseColor = vec4( 1.0 ); #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #endif }`,Rf=`#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include void main() { #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`,Cf=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include #include void main () { #include vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = packDepthToRGBA( dist ); }`,Pf=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`,Lf=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`,If=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include }`,Uf=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,Df=`#include #include #include #include #include #include #include #include #include void main() { #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`,Nf=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`,Of=`#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,Ff=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,Bf=`#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`,zf=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`,kf=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`,Hf=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include void main() { #include #include #include #include gl_FragColor = vec4( packNormalToRGB( normal ), opacity ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`,Vf=`#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,Gf=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,Wf=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`,Xf=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat; #endif #include #include #include #include #include #include }`,qf=`#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`,Yf=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include vec4 diffuseColor = vec4( diffuse, opacity ); ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`,Zf=`uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`,Kf=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { #include vec3 outgoingLight = vec3( 0.0 ); vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,Jf=`#include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include }`,$f=`uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include }`,jf=`uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 ); vec2 scale; scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) ); scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`,Qf=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { #include vec3 outgoingLight = vec3( 0.0 ); vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`,Ce={alphahash_fragment:Su,alphahash_pars_fragment:bu,alphamap_fragment:Au,alphamap_pars_fragment:Tu,alphatest_fragment:Eu,alphatest_pars_fragment:wu,aomap_fragment:Ru,aomap_pars_fragment:Cu,begin_vertex:Pu,beginnormal_vertex:Lu,bsdfs:Iu,iridescence_fragment:Uu,bumpmap_pars_fragment:Du,clipping_planes_fragment:Nu,clipping_planes_pars_fragment:Ou,clipping_planes_pars_vertex:Fu,clipping_planes_vertex:Bu,color_fragment:zu,color_pars_fragment:ku,color_pars_vertex:Hu,color_vertex:Vu,common:Gu,cube_uv_reflection_fragment:Wu,defaultnormal_vertex:Xu,displacementmap_pars_vertex:qu,displacementmap_vertex:Yu,emissivemap_fragment:Zu,emissivemap_pars_fragment:Ku,colorspace_fragment:Ju,colorspace_pars_fragment:$u,envmap_fragment:ju,envmap_common_pars_fragment:Qu,envmap_pars_fragment:ed,envmap_pars_vertex:td,envmap_physical_pars_fragment:fd,envmap_vertex:nd,fog_vertex:id,fog_pars_vertex:sd,fog_fragment:rd,fog_pars_fragment:od,gradientmap_pars_fragment:ad,lightmap_fragment:cd,lightmap_pars_fragment:ld,lights_lambert_fragment:hd,lights_lambert_pars_fragment:ud,lights_pars_begin:dd,lights_toon_fragment:pd,lights_toon_pars_fragment:md,lights_phong_fragment:gd,lights_phong_pars_fragment:_d,lights_physical_fragment:xd,lights_physical_pars_fragment:yd,lights_fragment_begin:vd,lights_fragment_maps:Md,lights_fragment_end:Sd,logdepthbuf_fragment:bd,logdepthbuf_pars_fragment:Ad,logdepthbuf_pars_vertex:Td,logdepthbuf_vertex:Ed,map_fragment:wd,map_pars_fragment:Rd,map_particle_fragment:Cd,map_particle_pars_fragment:Pd,metalnessmap_fragment:Ld,metalnessmap_pars_fragment:Id,morphcolor_vertex:Ud,morphnormal_vertex:Dd,morphtarget_pars_vertex:Nd,morphtarget_vertex:Od,normal_fragment_begin:Fd,normal_fragment_maps:Bd,normal_pars_fragment:zd,normal_pars_vertex:kd,normal_vertex:Hd,normalmap_pars_fragment:Vd,clearcoat_normal_fragment_begin:Gd,clearcoat_normal_fragment_maps:Wd,clearcoat_pars_fragment:Xd,iridescence_pars_fragment:qd,opaque_fragment:Yd,packing:Zd,premultiplied_alpha_fragment:Kd,project_vertex:Jd,dithering_fragment:$d,dithering_pars_fragment:jd,roughnessmap_fragment:Qd,roughnessmap_pars_fragment:ef,shadowmap_pars_fragment:tf,shadowmap_pars_vertex:nf,shadowmap_vertex:sf,shadowmask_pars_fragment:rf,skinbase_vertex:of,skinning_pars_vertex:af,skinning_vertex:cf,skinnormal_vertex:lf,specularmap_fragment:hf,specularmap_pars_fragment:uf,tonemapping_fragment:df,tonemapping_pars_fragment:ff,transmission_fragment:pf,transmission_pars_fragment:mf,uv_pars_fragment:gf,uv_pars_vertex:_f,uv_vertex:xf,worldpos_vertex:yf,background_vert:vf,background_frag:Mf,backgroundCube_vert:Sf,backgroundCube_frag:bf,cube_vert:Af,cube_frag:Tf,depth_vert:Ef,depth_frag:wf,distanceRGBA_vert:Rf,distanceRGBA_frag:Cf,equirect_vert:Pf,equirect_frag:Lf,linedashed_vert:If,linedashed_frag:Uf,meshbasic_vert:Df,meshbasic_frag:Nf,meshlambert_vert:Of,meshlambert_frag:Ff,meshmatcap_vert:Bf,meshmatcap_frag:zf,meshnormal_vert:kf,meshnormal_frag:Hf,meshphong_vert:Vf,meshphong_frag:Gf,meshphysical_vert:Wf,meshphysical_frag:Xf,meshtoon_vert:qf,meshtoon_frag:Yf,points_vert:Zf,points_frag:Kf,shadow_vert:Jf,shadow_frag:$f,sprite_vert:jf,sprite_frag:Qf},ie={common:{diffuse:{value:new Ae(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ie},alphaMap:{value:null},alphaMapTransform:{value:new Ie},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ie}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ie}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ie}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ie},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ie},normalScale:{value:new Be(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ie},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ie}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ie}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ie}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ae(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Ae(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ie},alphaTest:{value:0},uvTransform:{value:new Ie}},sprite:{diffuse:{value:new Ae(16777215)},opacity:{value:1},center:{value:new Be(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ie},alphaMap:{value:null},alphaMapTransform:{value:new Ie},alphaTest:{value:0}}},Kt={basic:{uniforms:yt([ie.common,ie.specularmap,ie.envmap,ie.aomap,ie.lightmap,ie.fog]),vertexShader:Ce.meshbasic_vert,fragmentShader:Ce.meshbasic_frag},lambert:{uniforms:yt([ie.common,ie.specularmap,ie.envmap,ie.aomap,ie.lightmap,ie.emissivemap,ie.bumpmap,ie.normalmap,ie.displacementmap,ie.fog,ie.lights,{emissive:{value:new Ae(0)}}]),vertexShader:Ce.meshlambert_vert,fragmentShader:Ce.meshlambert_frag},phong:{uniforms:yt([ie.common,ie.specularmap,ie.envmap,ie.aomap,ie.lightmap,ie.emissivemap,ie.bumpmap,ie.normalmap,ie.displacementmap,ie.fog,ie.lights,{emissive:{value:new Ae(0)},specular:{value:new Ae(1118481)},shininess:{value:30}}]),vertexShader:Ce.meshphong_vert,fragmentShader:Ce.meshphong_frag},standard:{uniforms:yt([ie.common,ie.envmap,ie.aomap,ie.lightmap,ie.emissivemap,ie.bumpmap,ie.normalmap,ie.displacementmap,ie.roughnessmap,ie.metalnessmap,ie.fog,ie.lights,{emissive:{value:new Ae(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ce.meshphysical_vert,fragmentShader:Ce.meshphysical_frag},toon:{uniforms:yt([ie.common,ie.aomap,ie.lightmap,ie.emissivemap,ie.bumpmap,ie.normalmap,ie.displacementmap,ie.gradientmap,ie.fog,ie.lights,{emissive:{value:new Ae(0)}}]),vertexShader:Ce.meshtoon_vert,fragmentShader:Ce.meshtoon_frag},matcap:{uniforms:yt([ie.common,ie.bumpmap,ie.normalmap,ie.displacementmap,ie.fog,{matcap:{value:null}}]),vertexShader:Ce.meshmatcap_vert,fragmentShader:Ce.meshmatcap_frag},points:{uniforms:yt([ie.points,ie.fog]),vertexShader:Ce.points_vert,fragmentShader:Ce.points_frag},dashed:{uniforms:yt([ie.common,ie.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ce.linedashed_vert,fragmentShader:Ce.linedashed_frag},depth:{uniforms:yt([ie.common,ie.displacementmap]),vertexShader:Ce.depth_vert,fragmentShader:Ce.depth_frag},normal:{uniforms:yt([ie.common,ie.bumpmap,ie.normalmap,ie.displacementmap,{opacity:{value:1}}]),vertexShader:Ce.meshnormal_vert,fragmentShader:Ce.meshnormal_frag},sprite:{uniforms:yt([ie.sprite,ie.fog]),vertexShader:Ce.sprite_vert,fragmentShader:Ce.sprite_frag},background:{uniforms:{uvTransform:{value:new Ie},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ce.background_vert,fragmentShader:Ce.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:Ce.backgroundCube_vert,fragmentShader:Ce.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ce.cube_vert,fragmentShader:Ce.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ce.equirect_vert,fragmentShader:Ce.equirect_frag},distanceRGBA:{uniforms:yt([ie.common,ie.displacementmap,{referencePosition:{value:new P},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ce.distanceRGBA_vert,fragmentShader:Ce.distanceRGBA_frag},shadow:{uniforms:yt([ie.lights,ie.fog,{color:{value:new Ae(0)},opacity:{value:1}}]),vertexShader:Ce.shadow_vert,fragmentShader:Ce.shadow_frag}};Kt.physical={uniforms:yt([Kt.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ie},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ie},clearcoatNormalScale:{value:new Be(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ie},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ie},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ie},sheen:{value:0},sheenColor:{value:new Ae(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ie},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ie},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ie},transmissionSamplerSize:{value:new Be},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ie},attenuationDistance:{value:0},attenuationColor:{value:new Ae(0)},specularColor:{value:new Ae(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ie},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ie},anisotropyVector:{value:new Be},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ie}}]),vertexShader:Ce.meshphysical_vert,fragmentShader:Ce.meshphysical_frag};var Ps={r:0,b:0,g:0};function ep(s,e,t,n,i,r,o){let a=new Ae(0),c=r===!0?0:1,l,h,u=null,d=0,p=null;function g(m,f){let S=!1,x=f.isScene===!0?f.background:null;switch(x&&x.isTexture&&(x=(f.backgroundBlurriness>0?t:e).get(x)),x===null?_(a,c):x&&x.isColor&&(_(x,1),S=!0),s.xr.getEnvironmentBlendMode()){case"opaque":S=!0;break;case"additive":n.buffers.color.setClear(0,0,0,1,o),S=!0;break;case"alpha-blend":n.buffers.color.setClear(0,0,0,0,o),S=!0;break}(s.autoClear||S)&&s.clear(s.autoClearColor,s.autoClearDepth,s.autoClearStencil),x&&(x.isCubeTexture||x.mapping===lr)?(h===void 0&&(h=new Mt(new ji(1,1,1),new mn({name:"BackgroundCubeMaterial",uniforms:wi(Kt.backgroundCube.uniforms),vertexShader:Kt.backgroundCube.vertexShader,fragmentShader:Kt.backgroundCube.fragmentShader,side:bt,depthTest:!1,depthWrite:!1,fog:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(C,w,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(h)),h.material.uniforms.envMap.value=x,h.material.uniforms.flipEnvMap.value=x.isCubeTexture&&x.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=f.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=f.backgroundIntensity,h.material.toneMapped=x.colorSpace!==xe,(u!==x||d!==x.version||p!==s.toneMapping)&&(h.material.needsUpdate=!0,u=x,d=x.version,p=s.toneMapping),h.layers.enableAll(),m.unshift(h,h.geometry,h.material,0,0,null)):x&&x.isTexture&&(l===void 0&&(l=new Mt(new ro(2,2),new mn({name:"BackgroundMaterial",uniforms:wi(Kt.background.uniforms),vertexShader:Kt.background.vertexShader,fragmentShader:Kt.background.fragmentShader,side:jt,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=x,l.material.uniforms.backgroundIntensity.value=f.backgroundIntensity,l.material.toneMapped=x.colorSpace!==xe,x.matrixAutoUpdate===!0&&x.updateMatrix(),l.material.uniforms.uvTransform.value.copy(x.matrix),(u!==x||d!==x.version||p!==s.toneMapping)&&(l.material.needsUpdate=!0,u=x,d=x.version,p=s.toneMapping),l.layers.enableAll(),m.unshift(l,l.geometry,l.material,0,0,null))}function _(m,f){m.getRGB(Ps,bl(s)),n.buffers.color.setClear(Ps.r,Ps.g,Ps.b,f,o)}return{getClearColor:function(){return a},setClearColor:function(m,f=1){a.set(m),c=f,_(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(m){c=m,_(a,c)},render:g}}function tp(s,e,t,n){let i=s.getParameter(s.MAX_VERTEX_ATTRIBS),r=n.isWebGL2?null:e.get("OES_vertex_array_object"),o=n.isWebGL2||r!==null,a={},c=m(null),l=c,h=!1;function u(V,G,$,W,q){let Z=!1;if(o){let K=_(W,$,G);l!==K&&(l=K,p(l.object)),Z=f(V,W,$,q),Z&&S(V,W,$,q)}else{let K=G.wireframe===!0;(l.geometry!==W.id||l.program!==$.id||l.wireframe!==K)&&(l.geometry=W.id,l.program=$.id,l.wireframe=K,Z=!0)}q!==null&&t.update(q,s.ELEMENT_ARRAY_BUFFER),(Z||h)&&(h=!1,k(V,G,$,W),q!==null&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t.get(q).buffer))}function d(){return n.isWebGL2?s.createVertexArray():r.createVertexArrayOES()}function p(V){return n.isWebGL2?s.bindVertexArray(V):r.bindVertexArrayOES(V)}function g(V){return n.isWebGL2?s.deleteVertexArray(V):r.deleteVertexArrayOES(V)}function _(V,G,$){let W=$.wireframe===!0,q=a[V.id];q===void 0&&(q={},a[V.id]=q);let Z=q[G.id];Z===void 0&&(Z={},q[G.id]=Z);let K=Z[W];return K===void 0&&(K=m(d()),Z[W]=K),K}function m(V){let G=[],$=[],W=[];for(let q=0;q=0){let ae=q[X],ce=Z[X];if(ce===void 0&&(X==="instanceMatrix"&&V.instanceMatrix&&(ce=V.instanceMatrix),X==="instanceColor"&&V.instanceColor&&(ce=V.instanceColor)),ae===void 0||ae.attribute!==ce||ce&&ae.data!==ce.data)return!0;K++}return l.attributesNum!==K||l.index!==W}function S(V,G,$,W){let q={},Z=G.attributes,K=0,D=$.getAttributes();for(let X in D)if(D[X].location>=0){let ae=Z[X];ae===void 0&&(X==="instanceMatrix"&&V.instanceMatrix&&(ae=V.instanceMatrix),X==="instanceColor"&&V.instanceColor&&(ae=V.instanceColor));let ce={};ce.attribute=ae,ae&&ae.data&&(ce.data=ae.data),q[X]=ce,K++}l.attributes=q,l.attributesNum=K,l.index=W}function x(){let V=l.newAttributes;for(let G=0,$=V.length;G<$;G++)V[G]=0}function A(V){E(V,0)}function E(V,G){let $=l.newAttributes,W=l.enabledAttributes,q=l.attributeDivisors;$[V]=1,W[V]===0&&(s.enableVertexAttribArray(V),W[V]=1),q[V]!==G&&((n.isWebGL2?s:e.get("ANGLE_instanced_arrays"))[n.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](V,G),q[V]=G)}function C(){let V=l.newAttributes,G=l.enabledAttributes;for(let $=0,W=G.length;$=0){let oe=q[D];if(oe===void 0&&(D==="instanceMatrix"&&V.instanceMatrix&&(oe=V.instanceMatrix),D==="instanceColor"&&V.instanceColor&&(oe=V.instanceColor)),oe!==void 0){let ae=oe.normalized,ce=oe.itemSize,_e=t.get(oe);if(_e===void 0)continue;let Ee=_e.buffer,ye=_e.type,He=_e.bytesPerElement,St=n.isWebGL2===!0&&(ye===s.INT||ye===s.UNSIGNED_INT||oe.gpuType===ll);if(oe.isInterleavedBufferAttribute){let Pe=oe.data,U=Pe.stride,ht=oe.offset;if(Pe.isInstancedInterleavedBuffer){for(let ve=0;ve0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision>0)return"highp";w="mediump"}return w==="mediump"&&s.getShaderPrecisionFormat(s.VERTEX_SHADER,s.MEDIUM_FLOAT).precision>0&&s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let o=typeof WebGL2RenderingContext<"u"&&s.constructor.name==="WebGL2RenderingContext",a=t.precision!==void 0?t.precision:"highp",c=r(a);c!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",c,"instead."),a=c);let l=o||e.has("WEBGL_draw_buffers"),h=t.logarithmicDepthBuffer===!0,u=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),d=s.getParameter(s.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=s.getParameter(s.MAX_TEXTURE_SIZE),g=s.getParameter(s.MAX_CUBE_MAP_TEXTURE_SIZE),_=s.getParameter(s.MAX_VERTEX_ATTRIBS),m=s.getParameter(s.MAX_VERTEX_UNIFORM_VECTORS),f=s.getParameter(s.MAX_VARYING_VECTORS),S=s.getParameter(s.MAX_FRAGMENT_UNIFORM_VECTORS),x=d>0,A=o||e.has("OES_texture_float"),E=x&&A,C=o?s.getParameter(s.MAX_SAMPLES):0;return{isWebGL2:o,drawBuffers:l,getMaxAnisotropy:i,getMaxPrecision:r,precision:a,logarithmicDepthBuffer:h,maxTextures:u,maxVertexTextures:d,maxTextureSize:p,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:m,maxVaryings:f,maxFragmentUniforms:S,vertexTextures:x,floatFragmentTextures:A,floatVertexTextures:E,maxSamples:C}}function sp(s){let e=this,t=null,n=0,i=!1,r=!1,o=new un,a=new Ie,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){let p=u.length!==0||d||n!==0||i;return i=d,n=u.length,p},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,d){t=h(u,d,0)},this.setState=function(u,d,p){let g=u.clippingPlanes,_=u.clipIntersection,m=u.clipShadows,f=s.get(u);if(!i||g===null||g.length===0||r&&!m)r?h(null):l();else{let S=r?0:n,x=S*4,A=f.clippingState||null;c.value=A,A=h(g,d,x,p);for(let E=0;E!==x;++E)A[E]=t[E];f.clippingState=A,this.numIntersection=_?this.numPlanes:0,this.numPlanes+=S}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(u,d,p,g){let _=u!==null?u.length:0,m=null;if(_!==0){if(m=c.value,g!==!0||m===null){let f=p+_*4,S=d.matrixWorldInverse;a.getNormalMatrix(S),(m===null||m.length0){let l=new so(c.height/2);return l.fromEquirectangularTexture(s,o),e.set(o,l),o.addEventListener("dispose",i),t(l.texture,o.mapping)}else return null}}return o}function i(o){let a=o.target;a.removeEventListener("dispose",i);let c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}var Ri=class extends Ys{constructor(e=-1,t=1,n=1,i=-1,r=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=r,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,r,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2,r=n-e,o=n+e,a=i+t,c=i-t;if(this.view!==null&&this.view.enabled){let l=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,o=r+l*this.view.width,a-=h*this.view.offsetY,c=a-h*this.view.height}this.projectionMatrix.makeOrthographic(r,o,a,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},_i=4,xc=[.125,.215,.35,.446,.526,.582],Gn=20,Hr=new Ri,yc=new Ae,Vr=null,Vn=(1+Math.sqrt(5))/2,di=1/Vn,vc=[new P(1,1,1),new P(-1,1,1),new P(1,1,-1),new P(-1,1,-1),new P(0,Vn,di),new P(0,Vn,-di),new P(di,0,Vn),new P(-di,0,Vn),new P(Vn,di,0),new P(-Vn,di,0)],Ks=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,i=100){Vr=this._renderer.getRenderTarget(),this._setSize(256);let r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,n,i,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=bc(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Sc(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?x:0,x,x),h.setRenderTarget(i),_&&h.render(g,a),h.render(e,a)}g.geometry.dispose(),g.material.dispose(),h.toneMapping=d,h.autoClear=u,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===Mi||e.mapping===Si;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=bc()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Sc());let r=i?this._cubemapMaterial:this._equirectMaterial,o=new Mt(this._lodPlanes[0],r),a=r.uniforms;a.envMap.value=e;let c=this._cubeSize;Ls(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(o,Hr)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;for(let i=1;iGn&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Gn}`);let f=[],S=0;for(let w=0;wx-_i?i-x+_i:0),C=4*(this._cubeSize-A);Ls(t,E,C,3*A,2*A),c.setRenderTarget(t),c.render(u,Hr)}};function op(s){let e=[],t=[],n=[],i=s,r=s-_i+1+xc.length;for(let o=0;os-_i?c=xc[o-s+_i-1]:o===0&&(c=0),n.push(c);let l=1/(a-2),h=-l,u=1+l,d=[h,h,u,h,u,u,h,h,u,u,h,u],p=6,g=6,_=3,m=2,f=1,S=new Float32Array(_*g*p),x=new Float32Array(m*g*p),A=new Float32Array(f*g*p);for(let C=0;C2?0:-1,v=[w,k,0,w+2/3,k,0,w+2/3,k+1,0,w,k,0,w+2/3,k+1,0,w,k+1,0];S.set(v,_*g*C),x.set(d,m*g*C);let T=[C,C,C,C,C,C];A.set(T,f*g*C)}let E=new At;E.setAttribute("position",new $e(S,_)),E.setAttribute("uv",new $e(x,m)),E.setAttribute("faceIndex",new $e(A,f)),e.push(E),i>_i&&i--}return{lodPlanes:e,sizeLods:t,sigmas:n}}function Mc(s,e,t){let n=new pn(s,e,t);return n.texture.mapping=lr,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Ls(s,e,t,n,i){s.viewport.set(e,t,n,i),s.scissor.set(e,t,n,i)}function ap(s,e,t){let n=new Float32Array(Gn),i=new P(0,1,0);return new mn({name:"SphericalGaussianBlur",defines:{n:Gn,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${s}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Fo(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } `,blending:Tn,depthTest:!1,depthWrite:!1})}function Sc(){return new mn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Fo(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } `,blending:Tn,depthTest:!1,depthWrite:!1})}function bc(){return new mn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Fo(),fragmentShader:` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } `,blending:Tn,depthTest:!1,depthWrite:!1})}function Fo(){return` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } `}function cp(s){let e=new WeakMap,t=null;function n(a){if(a&&a.isTexture){let c=a.mapping,l=c===Jr||c===$r,h=c===Mi||c===Si;if(l||h)if(a.isRenderTargetTexture&&a.needsPMREMUpdate===!0){a.needsPMREMUpdate=!1;let u=e.get(a);return t===null&&(t=new Ks(s)),u=l?t.fromEquirectangular(a,u):t.fromCubemap(a,u),e.set(a,u),u.texture}else{if(e.has(a))return e.get(a).texture;{let u=a.image;if(l&&u&&u.height>0||h&&u&&i(u)){t===null&&(t=new Ks(s));let d=l?t.fromEquirectangular(a):t.fromCubemap(a);return e.set(a,d),a.addEventListener("dispose",r),d.texture}else return null}}}return a}function i(a){let c=0,l=6;for(let h=0;he.maxTextureSize&&(T=Math.ceil(v/e.maxTextureSize),v=e.maxTextureSize);let Y=new Float32Array(v*T*4*g),ne=new Vs(Y,v,T,g);ne.type=dn,ne.needsUpdate=!0;let B=k*4;for(let G=0;G0)return s;let i=e*t,r=Ac[i];if(r===void 0&&(r=new Float32Array(i),Ac[i]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,s[o].toArray(r,a)}return r}function rt(s,e){if(s.length!==e.length)return!1;for(let t=0,n=s.length;t":" "} ${a}: ${t[o]}`)}return n.join(` `)}function om(s){switch(s){case Nt:return["Linear","( value )"];case xe:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",s),["Linear","( value )"]}}function Lc(s,e,t){let n=s.getShaderParameter(e,s.COMPILE_STATUS),i=s.getShaderInfoLog(e).trim();if(n&&i==="")return"";let r=/ERROR: 0:(\d+)/.exec(i);if(r){let o=parseInt(r[1]);return t.toUpperCase()+` `+i+` `+rm(s.getShaderSource(e),o)}else return i}function am(s,e){let t=om(e);return"vec4 "+s+"( vec4 value ) { return LinearTo"+t[0]+t[1]+"; }"}function cm(s,e){let t;switch(e){case uh:t="Linear";break;case dh:t="Reinhard";break;case fh:t="OptimizedCineon";break;case ph:t="ACESFilmic";break;case mh:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+s+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}function lm(s){return[s.extensionDerivatives||s.envMapCubeUVHeight||s.bumpMap||s.normalMapTangentSpace||s.clearcoatNormalMap||s.flatShading||s.shaderID==="physical"?"#extension GL_OES_standard_derivatives : enable":"",(s.extensionFragDepth||s.logarithmicDepthBuffer)&&s.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",s.extensionDrawBuffers&&s.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(s.extensionShaderTextureLOD||s.envMap||s.transmission)&&s.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(Gi).join(` `)}function hm(s){let e=[];for(let t in s){let n=s[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(` `)}function um(s,e){let t={},n=s.getProgramParameter(e,s.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function lo(s){return s.replace(dm,pm)}var fm=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function pm(s,e){let t=Ce[e];if(t===void 0){let n=fm.get(e);if(n!==void 0)t=Ce[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return lo(t)}var mm=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Dc(s){return s.replace(mm,gm)}function gm(s,e,t,n){let i="";for(let r=parseInt(e);r0&&(m+=` `),f=[p,"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g].filter(Gi).join(` `),f.length>0&&(f+=` `)):(m=[Nc(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors&&t.isWebGL2?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0&&t.isWebGL2?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.useLegacyLights?"#define LEGACY_LIGHTS":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.logarithmicDepthBuffer&&t.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` `].filter(Gi).join(` `),f=[p,Nc(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+h:"",t.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.useLegacyLights?"#define LEGACY_LIGHTS":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.logarithmicDepthBuffer&&t.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==En?"#define TONE_MAPPING":"",t.toneMapping!==En?Ce.tonemapping_pars_fragment:"",t.toneMapping!==En?cm("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Ce.colorspace_pars_fragment,am("linearToOutputTexel",t.outputColorSpace),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` `].filter(Gi).join(` `)),o=lo(o),o=Ic(o,t),o=Uc(o,t),a=lo(a),a=Ic(a,t),a=Uc(a,t),o=Dc(o),a=Dc(a),t.isWebGL2&&t.isRawShaderMaterial!==!0&&(S=`#version 300 es `,m=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+m,f=["#define varying in",t.glslVersion===tc?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===tc?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` `+f);let x=S+m+o,A=S+f+a,E=Pc(i,i.VERTEX_SHADER,x),C=Pc(i,i.FRAGMENT_SHADER,A);if(i.attachShader(_,E),i.attachShader(_,C),t.index0AttributeName!==void 0?i.bindAttribLocation(_,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(_,0,"position"),i.linkProgram(_),s.debug.checkShaderErrors){let v=i.getProgramInfoLog(_).trim(),T=i.getShaderInfoLog(E).trim(),Y=i.getShaderInfoLog(C).trim(),ne=!0,B=!0;if(i.getProgramParameter(_,i.LINK_STATUS)===!1)if(ne=!1,typeof s.debug.onShaderError=="function")s.debug.onShaderError(i,_,E,C);else{let V=Lc(i,E,"vertex"),G=Lc(i,C,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(_,i.VALIDATE_STATUS)+` Program Info Log: `+v+` `+V+` `+G)}else v!==""?console.warn("THREE.WebGLProgram: Program Info Log:",v):(T===""||Y==="")&&(B=!1);B&&(this.diagnostics={runnable:ne,programLog:v,vertexShader:{log:T,prefix:m},fragmentShader:{log:Y,prefix:f}})}i.deleteShader(E),i.deleteShader(C);let w;this.getUniforms=function(){return w===void 0&&(w=new vi(i,_)),w};let k;return this.getAttributes=function(){return k===void 0&&(k=um(i,_)),k},this.destroy=function(){n.releaseStatesOfProgram(this),i.deleteProgram(_),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=sm++,this.cacheKey=e,this.usedTimes=1,this.program=_,this.vertexShader=E,this.fragmentShader=C,this}var bm=0,ho=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,i=this._getShaderStage(t),r=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(r)===!1&&(o.add(r),r.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new uo(e),t.set(e,n)),n}},uo=class{constructor(e){this.id=bm++,this.code=e,this.usedTimes=0}};function Am(s,e,t,n,i,r,o){let a=new Ws,c=new ho,l=[],h=i.isWebGL2,u=i.logarithmicDepthBuffer,d=i.vertexTextures,p=i.precision,g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function _(v){return v===0?"uv":`uv${v}`}function m(v,T,Y,ne,B){let V=ne.fog,G=B.geometry,$=v.isMeshStandardMaterial?ne.environment:null,W=(v.isMeshStandardMaterial?t:e).get(v.envMap||$),q=W&&W.mapping===lr?W.image.height:null,Z=g[v.type];v.precision!==null&&(p=i.getMaxPrecision(v.precision),p!==v.precision&&console.warn("THREE.WebGLProgram.getParameters:",v.precision,"not supported, using",p,"instead."));let K=G.morphAttributes.position||G.morphAttributes.normal||G.morphAttributes.color,D=K!==void 0?K.length:0,X=0;G.morphAttributes.position!==void 0&&(X=1),G.morphAttributes.normal!==void 0&&(X=2),G.morphAttributes.color!==void 0&&(X=3);let oe,ae,ce,_e;if(Z){let Ye=Kt[Z];oe=Ye.vertexShader,ae=Ye.fragmentShader}else oe=v.vertexShader,ae=v.fragmentShader,c.update(v),ce=c.getVertexShaderID(v),_e=c.getFragmentShaderID(v);let Ee=s.getRenderTarget(),ye=B.isInstancedMesh===!0,He=!!v.map,St=!!v.matcap,Pe=!!W,U=!!v.aoMap,ht=!!v.lightMap,ve=!!v.bumpMap,we=!!v.normalMap,Te=!!v.displacementMap,Ze=!!v.emissiveMap,Fe=!!v.metalnessMap,Le=!!v.roughnessMap,Ge=v.anisotropy>0,ct=v.clearcoat>0,ut=v.iridescence>0,b=v.sheen>0,y=v.transmission>0,N=Ge&&!!v.anisotropyMap,j=ct&&!!v.clearcoatMap,J=ct&&!!v.clearcoatNormalMap,Q=ct&&!!v.clearcoatRoughnessMap,de=ut&&!!v.iridescenceMap,ee=ut&&!!v.iridescenceThicknessMap,F=b&&!!v.sheenColorMap,me=b&&!!v.sheenRoughnessMap,fe=!!v.specularMap,pe=!!v.specularColorMap,he=!!v.specularIntensityMap,ue=y&&!!v.transmissionMap,De=y&&!!v.thicknessMap,Xe=!!v.gradientMap,R=!!v.alphaMap,se=v.alphaTest>0,O=!!v.alphaHash,te=!!v.extensions,re=!!G.attributes.uv1,ke=!!G.attributes.uv2,Ke=!!G.attributes.uv3,et=En;return v.toneMapped&&(Ee===null||Ee.isXRRenderTarget===!0)&&(et=s.toneMapping),{isWebGL2:h,shaderID:Z,shaderType:v.type,shaderName:v.name,vertexShader:oe,fragmentShader:ae,defines:v.defines,customVertexShaderID:ce,customFragmentShaderID:_e,isRawShaderMaterial:v.isRawShaderMaterial===!0,glslVersion:v.glslVersion,precision:p,instancing:ye,instancingColor:ye&&B.instanceColor!==null,supportsVertexTextures:d,outputColorSpace:Ee===null?s.outputColorSpace:Ee.isXRRenderTarget===!0?Ee.texture.colorSpace:Nt,map:He,matcap:St,envMap:Pe,envMapMode:Pe&&W.mapping,envMapCubeUVHeight:q,aoMap:U,lightMap:ht,bumpMap:ve,normalMap:we,displacementMap:d&&Te,emissiveMap:Ze,normalMapObjectSpace:we&&v.normalMapType===Rh,normalMapTangentSpace:we&&v.normalMapType===_l,metalnessMap:Fe,roughnessMap:Le,anisotropy:Ge,anisotropyMap:N,clearcoat:ct,clearcoatMap:j,clearcoatNormalMap:J,clearcoatRoughnessMap:Q,iridescence:ut,iridescenceMap:de,iridescenceThicknessMap:ee,sheen:b,sheenColorMap:F,sheenRoughnessMap:me,specularMap:fe,specularColorMap:pe,specularIntensityMap:he,transmission:y,transmissionMap:ue,thicknessMap:De,gradientMap:Xe,opaque:v.transparent===!1&&v.blending===xi,alphaMap:R,alphaTest:se,alphaHash:O,combine:v.combine,mapUv:He&&_(v.map.channel),aoMapUv:U&&_(v.aoMap.channel),lightMapUv:ht&&_(v.lightMap.channel),bumpMapUv:ve&&_(v.bumpMap.channel),normalMapUv:we&&_(v.normalMap.channel),displacementMapUv:Te&&_(v.displacementMap.channel),emissiveMapUv:Ze&&_(v.emissiveMap.channel),metalnessMapUv:Fe&&_(v.metalnessMap.channel),roughnessMapUv:Le&&_(v.roughnessMap.channel),anisotropyMapUv:N&&_(v.anisotropyMap.channel),clearcoatMapUv:j&&_(v.clearcoatMap.channel),clearcoatNormalMapUv:J&&_(v.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Q&&_(v.clearcoatRoughnessMap.channel),iridescenceMapUv:de&&_(v.iridescenceMap.channel),iridescenceThicknessMapUv:ee&&_(v.iridescenceThicknessMap.channel),sheenColorMapUv:F&&_(v.sheenColorMap.channel),sheenRoughnessMapUv:me&&_(v.sheenRoughnessMap.channel),specularMapUv:fe&&_(v.specularMap.channel),specularColorMapUv:pe&&_(v.specularColorMap.channel),specularIntensityMapUv:he&&_(v.specularIntensityMap.channel),transmissionMapUv:ue&&_(v.transmissionMap.channel),thicknessMapUv:De&&_(v.thicknessMap.channel),alphaMapUv:R&&_(v.alphaMap.channel),vertexTangents:!!G.attributes.tangent&&(we||Ge),vertexColors:v.vertexColors,vertexAlphas:v.vertexColors===!0&&!!G.attributes.color&&G.attributes.color.itemSize===4,vertexUv1s:re,vertexUv2s:ke,vertexUv3s:Ke,pointsUvs:B.isPoints===!0&&!!G.attributes.uv&&(He||R),fog:!!V,useFog:v.fog===!0,fogExp2:V&&V.isFogExp2,flatShading:v.flatShading===!0,sizeAttenuation:v.sizeAttenuation===!0,logarithmicDepthBuffer:u,skinning:B.isSkinnedMesh===!0,morphTargets:G.morphAttributes.position!==void 0,morphNormals:G.morphAttributes.normal!==void 0,morphColors:G.morphAttributes.color!==void 0,morphTargetsCount:D,morphTextureStride:X,numDirLights:T.directional.length,numPointLights:T.point.length,numSpotLights:T.spot.length,numSpotLightMaps:T.spotLightMap.length,numRectAreaLights:T.rectArea.length,numHemiLights:T.hemi.length,numDirLightShadows:T.directionalShadowMap.length,numPointLightShadows:T.pointShadowMap.length,numSpotLightShadows:T.spotShadowMap.length,numSpotLightShadowsWithMaps:T.numSpotLightShadowsWithMaps,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:v.dithering,shadowMapEnabled:s.shadowMap.enabled&&Y.length>0,shadowMapType:s.shadowMap.type,toneMapping:et,useLegacyLights:s._useLegacyLights,premultipliedAlpha:v.premultipliedAlpha,doubleSided:v.side===Gt,flipSided:v.side===bt,useDepthPacking:v.depthPacking>=0,depthPacking:v.depthPacking||0,index0AttributeName:v.index0AttributeName,extensionDerivatives:te&&v.extensions.derivatives===!0,extensionFragDepth:te&&v.extensions.fragDepth===!0,extensionDrawBuffers:te&&v.extensions.drawBuffers===!0,extensionShaderTextureLOD:te&&v.extensions.shaderTextureLOD===!0,rendererExtensionFragDepth:h||n.has("EXT_frag_depth"),rendererExtensionDrawBuffers:h||n.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:h||n.has("EXT_shader_texture_lod"),customProgramCacheKey:v.customProgramCacheKey()}}function f(v){let T=[];if(v.shaderID?T.push(v.shaderID):(T.push(v.customVertexShaderID),T.push(v.customFragmentShaderID)),v.defines!==void 0)for(let Y in v.defines)T.push(Y),T.push(v.defines[Y]);return v.isRawShaderMaterial===!1&&(S(T,v),x(T,v),T.push(s.outputColorSpace)),T.push(v.customProgramCacheKey),T.join()}function S(v,T){v.push(T.precision),v.push(T.outputColorSpace),v.push(T.envMapMode),v.push(T.envMapCubeUVHeight),v.push(T.mapUv),v.push(T.alphaMapUv),v.push(T.lightMapUv),v.push(T.aoMapUv),v.push(T.bumpMapUv),v.push(T.normalMapUv),v.push(T.displacementMapUv),v.push(T.emissiveMapUv),v.push(T.metalnessMapUv),v.push(T.roughnessMapUv),v.push(T.anisotropyMapUv),v.push(T.clearcoatMapUv),v.push(T.clearcoatNormalMapUv),v.push(T.clearcoatRoughnessMapUv),v.push(T.iridescenceMapUv),v.push(T.iridescenceThicknessMapUv),v.push(T.sheenColorMapUv),v.push(T.sheenRoughnessMapUv),v.push(T.specularMapUv),v.push(T.specularColorMapUv),v.push(T.specularIntensityMapUv),v.push(T.transmissionMapUv),v.push(T.thicknessMapUv),v.push(T.combine),v.push(T.fogExp2),v.push(T.sizeAttenuation),v.push(T.morphTargetsCount),v.push(T.morphAttributeCount),v.push(T.numDirLights),v.push(T.numPointLights),v.push(T.numSpotLights),v.push(T.numSpotLightMaps),v.push(T.numHemiLights),v.push(T.numRectAreaLights),v.push(T.numDirLightShadows),v.push(T.numPointLightShadows),v.push(T.numSpotLightShadows),v.push(T.numSpotLightShadowsWithMaps),v.push(T.shadowMapType),v.push(T.toneMapping),v.push(T.numClippingPlanes),v.push(T.numClipIntersection),v.push(T.depthPacking)}function x(v,T){a.disableAll(),T.isWebGL2&&a.enable(0),T.supportsVertexTextures&&a.enable(1),T.instancing&&a.enable(2),T.instancingColor&&a.enable(3),T.matcap&&a.enable(4),T.envMap&&a.enable(5),T.normalMapObjectSpace&&a.enable(6),T.normalMapTangentSpace&&a.enable(7),T.clearcoat&&a.enable(8),T.iridescence&&a.enable(9),T.alphaTest&&a.enable(10),T.vertexColors&&a.enable(11),T.vertexAlphas&&a.enable(12),T.vertexUv1s&&a.enable(13),T.vertexUv2s&&a.enable(14),T.vertexUv3s&&a.enable(15),T.vertexTangents&&a.enable(16),T.anisotropy&&a.enable(17),v.push(a.mask),a.disableAll(),T.fog&&a.enable(0),T.useFog&&a.enable(1),T.flatShading&&a.enable(2),T.logarithmicDepthBuffer&&a.enable(3),T.skinning&&a.enable(4),T.morphTargets&&a.enable(5),T.morphNormals&&a.enable(6),T.morphColors&&a.enable(7),T.premultipliedAlpha&&a.enable(8),T.shadowMapEnabled&&a.enable(9),T.useLegacyLights&&a.enable(10),T.doubleSided&&a.enable(11),T.flipSided&&a.enable(12),T.useDepthPacking&&a.enable(13),T.dithering&&a.enable(14),T.transmission&&a.enable(15),T.sheen&&a.enable(16),T.opaque&&a.enable(17),T.pointsUvs&&a.enable(18),v.push(a.mask)}function A(v){let T=g[v.type],Y;if(T){let ne=Kt[T];Y=gu.clone(ne.uniforms)}else Y=v.uniforms;return Y}function E(v,T){let Y;for(let ne=0,B=l.length;ne0?n.push(f):p.transparent===!0?i.push(f):t.push(f)}function c(u,d,p,g,_,m){let f=o(u,d,p,g,_,m);p.transmission>0?n.unshift(f):p.transparent===!0?i.unshift(f):t.unshift(f)}function l(u,d){t.length>1&&t.sort(u||Em),n.length>1&&n.sort(d||Oc),i.length>1&&i.sort(d||Oc)}function h(){for(let u=e,d=s.length;u=r.length?(o=new Fc,r.push(o)):o=r[i],o}function t(){s=new WeakMap}return{get:e,dispose:t}}function Rm(){let s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new P,color:new Ae};break;case"SpotLight":t={position:new P,direction:new P,color:new Ae,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new P,color:new Ae,distance:0,decay:0};break;case"HemisphereLight":t={direction:new P,skyColor:new Ae,groundColor:new Ae};break;case"RectAreaLight":t={color:new Ae,position:new P,halfWidth:new P,halfHeight:new P};break}return s[e.id]=t,t}}}function Cm(){let s={};return{get:function(e){if(s[e.id]!==void 0)return s[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Be};break;case"SpotLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Be};break;case"PointLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Be,shadowCameraNear:1,shadowCameraFar:1e3};break}return s[e.id]=t,t}}}var Pm=0;function Lm(s,e){return(e.castShadow?2:0)-(s.castShadow?2:0)+(e.map?1:0)-(s.map?1:0)}function Im(s,e){let t=new Rm,n=Cm(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0};for(let h=0;h<9;h++)i.probe.push(new P);let r=new P,o=new Ue,a=new Ue;function c(h,u){let d=0,p=0,g=0;for(let Y=0;Y<9;Y++)i.probe[Y].set(0,0,0);let _=0,m=0,f=0,S=0,x=0,A=0,E=0,C=0,w=0,k=0;h.sort(Lm);let v=u===!0?Math.PI:1;for(let Y=0,ne=h.length;Y0&&(e.isWebGL2||s.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=ie.LTC_FLOAT_1,i.rectAreaLTC2=ie.LTC_FLOAT_2):s.has("OES_texture_half_float_linear")===!0?(i.rectAreaLTC1=ie.LTC_HALF_1,i.rectAreaLTC2=ie.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),i.ambient[0]=d,i.ambient[1]=p,i.ambient[2]=g;let T=i.hash;(T.directionalLength!==_||T.pointLength!==m||T.spotLength!==f||T.rectAreaLength!==S||T.hemiLength!==x||T.numDirectionalShadows!==A||T.numPointShadows!==E||T.numSpotShadows!==C||T.numSpotMaps!==w)&&(i.directional.length=_,i.spot.length=f,i.rectArea.length=S,i.point.length=m,i.hemi.length=x,i.directionalShadow.length=A,i.directionalShadowMap.length=A,i.pointShadow.length=E,i.pointShadowMap.length=E,i.spotShadow.length=C,i.spotShadowMap.length=C,i.directionalShadowMatrix.length=A,i.pointShadowMatrix.length=E,i.spotLightMatrix.length=C+w-k,i.spotLightMap.length=w,i.numSpotLightShadowsWithMaps=k,T.directionalLength=_,T.pointLength=m,T.spotLength=f,T.rectAreaLength=S,T.hemiLength=x,T.numDirectionalShadows=A,T.numPointShadows=E,T.numSpotShadows=C,T.numSpotMaps=w,i.version=Pm++)}function l(h,u){let d=0,p=0,g=0,_=0,m=0,f=u.matrixWorldInverse;for(let S=0,x=h.length;S=a.length?(c=new Bc(s,e),a.push(c)):c=a[o],c}function i(){t=new WeakMap}return{get:n,dispose:i}}var fo=class extends Pt{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Eh,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},po=class extends Pt{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}},Dm=`void main() { gl_Position = vec4( position, 1.0 ); }`,Nm=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; #include void main() { const float samples = float( VSM_SAMPLES ); float mean = 0.0; float squared_mean = 0.0; float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); float uvStart = samples <= 1.0 ? 0.0 : - 1.0; for ( float i = 0.0; i < samples; i ++ ) { float uvOffset = uvStart + i * uvStride; #ifdef HORIZONTAL_PASS vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); mean += distribution.x; squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; #else float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); mean += depth; squared_mean += depth * depth; #endif } mean = mean / samples; squared_mean = squared_mean / samples; float std_dev = sqrt( squared_mean - mean * mean ); gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); }`;function Om(s,e,t){let n=new Qi,i=new Be,r=new Be,o=new We,a=new fo({depthPacking:wh}),c=new po,l={},h=t.maxTextureSize,u={[jt]:bt,[bt]:jt,[Gt]:Gt},d=new mn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Be},radius:{value:4}},vertexShader:Dm,fragmentShader:Nm}),p=d.clone();p.defines.HORIZONTAL_PASS=1;let g=new At;g.setAttribute("position",new $e(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let _=new Mt(g,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=sl;let f=this.type;this.render=function(E,C,w){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||E.length===0)return;let k=s.getRenderTarget(),v=s.getActiveCubeFace(),T=s.getActiveMipmapLevel(),Y=s.state;Y.setBlending(Tn),Y.buffers.color.setClear(1,1,1,1),Y.buffers.depth.setTest(!0),Y.setScissorTest(!1);let ne=f!==hn&&this.type===hn,B=f===hn&&this.type!==hn;for(let V=0,G=E.length;Vh||i.y>h)&&(i.x>h&&(r.x=Math.floor(h/q.x),i.x=r.x*q.x,W.mapSize.x=r.x),i.y>h&&(r.y=Math.floor(h/q.y),i.y=r.y*q.y,W.mapSize.y=r.y)),W.map===null||ne===!0||B===!0){let K=this.type!==hn?{minFilter:st,magFilter:st}:{};W.map!==null&&W.map.dispose(),W.map=new pn(i.x,i.y,K),W.map.texture.name=$.name+".shadowMap",W.camera.updateProjectionMatrix()}s.setRenderTarget(W.map),s.clear();let Z=W.getViewportCount();for(let K=0;K0||C.map&&C.alphaTest>0){let Y=v.uuid,ne=C.uuid,B=l[Y];B===void 0&&(B={},l[Y]=B);let V=B[ne];V===void 0&&(V=v.clone(),B[ne]=V),v=V}if(v.visible=C.visible,v.wireframe=C.wireframe,k===hn?v.side=C.shadowSide!==null?C.shadowSide:C.side:v.side=C.shadowSide!==null?C.shadowSide:u[C.side],v.alphaMap=C.alphaMap,v.alphaTest=C.alphaTest,v.map=C.map,v.clipShadows=C.clipShadows,v.clippingPlanes=C.clippingPlanes,v.clipIntersection=C.clipIntersection,v.displacementMap=C.displacementMap,v.displacementScale=C.displacementScale,v.displacementBias=C.displacementBias,v.wireframeLinewidth=C.wireframeLinewidth,v.linewidth=C.linewidth,w.isPointLight===!0&&v.isMeshDistanceMaterial===!0){let Y=s.properties.get(v);Y.light=w}return v}function A(E,C,w,k,v){if(E.visible===!1)return;if(E.layers.test(C.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&v===hn)&&(!E.frustumCulled||n.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(w.matrixWorldInverse,E.matrixWorld);let ne=e.update(E),B=E.material;if(Array.isArray(B)){let V=ne.groups;for(let G=0,$=V.length;G<$;G++){let W=V[G],q=B[W.materialIndex];if(q&&q.visible){let Z=x(E,q,k,v);s.renderBufferDirect(w,null,ne,Z,E,W)}}}else if(B.visible){let V=x(E,B,k,v);s.renderBufferDirect(w,null,ne,V,E,null)}}let Y=E.children;for(let ne=0,B=Y.length;ne=1):q.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(q)[1]),$=W>=2);let Z=null,K={},D=s.getParameter(s.SCISSOR_BOX),X=s.getParameter(s.VIEWPORT),oe=new We().fromArray(D),ae=new We().fromArray(X);function ce(R,se,O,te){let re=new Uint8Array(4),ke=s.createTexture();s.bindTexture(R,ke),s.texParameteri(R,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(R,s.TEXTURE_MAG_FILTER,s.NEAREST);for(let Ke=0;Ke"u"?!1:/OculusBrowser/g.test(navigator.userAgent),g=new WeakMap,_,m=new WeakMap,f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function S(b,y){return f?new OffscreenCanvas(b,y):$i("canvas")}function x(b,y,N,j){let J=1;if((b.width>j||b.height>j)&&(J=j/Math.max(b.width,b.height)),J<1||y===!0)if(typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&b instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&b instanceof ImageBitmap){let Q=y?zs:Math.floor,de=Q(J*b.width),ee=Q(J*b.height);_===void 0&&(_=S(de,ee));let F=N?S(de,ee):_;return F.width=de,F.height=ee,F.getContext("2d").drawImage(b,0,0,de,ee),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+b.width+"x"+b.height+") to ("+de+"x"+ee+")."),F}else return"data"in b&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+b.width+"x"+b.height+")."),b;return b}function A(b){return eo(b.width)&&eo(b.height)}function E(b){return a?!1:b.wrapS!==Rt||b.wrapT!==Rt||b.minFilter!==st&&b.minFilter!==vt}function C(b,y){return b.generateMipmaps&&y&&b.minFilter!==st&&b.minFilter!==vt}function w(b){s.generateMipmap(b)}function k(b,y,N,j,J=!1){if(a===!1)return y;if(b!==null){if(s[b]!==void 0)return s[b];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+b+"'")}let Q=y;return y===s.RED&&(N===s.FLOAT&&(Q=s.R32F),N===s.HALF_FLOAT&&(Q=s.R16F),N===s.UNSIGNED_BYTE&&(Q=s.R8)),y===s.RED_INTEGER&&(N===s.UNSIGNED_BYTE&&(Q=s.R8UI),N===s.UNSIGNED_SHORT&&(Q=s.R16UI),N===s.UNSIGNED_INT&&(Q=s.R32UI),N===s.BYTE&&(Q=s.R8I),N===s.SHORT&&(Q=s.R16I),N===s.INT&&(Q=s.R32I)),y===s.RG&&(N===s.FLOAT&&(Q=s.RG32F),N===s.HALF_FLOAT&&(Q=s.RG16F),N===s.UNSIGNED_BYTE&&(Q=s.RG8)),y===s.RGBA&&(N===s.FLOAT&&(Q=s.RGBA32F),N===s.HALF_FLOAT&&(Q=s.RGBA16F),N===s.UNSIGNED_BYTE&&(Q=j===xe&&J===!1?s.SRGB8_ALPHA8:s.RGBA8),N===s.UNSIGNED_SHORT_4_4_4_4&&(Q=s.RGBA4),N===s.UNSIGNED_SHORT_5_5_5_1&&(Q=s.RGB5_A1)),(Q===s.R16F||Q===s.R32F||Q===s.RG16F||Q===s.RG32F||Q===s.RGBA16F||Q===s.RGBA32F)&&e.get("EXT_color_buffer_float"),Q}function v(b,y,N){return C(b,N)===!0||b.isFramebufferTexture&&b.minFilter!==st&&b.minFilter!==vt?Math.log2(Math.max(y.width,y.height))+1:b.mipmaps!==void 0&&b.mipmaps.length>0?b.mipmaps.length:b.isCompressedTexture&&Array.isArray(b.image)?y.mipmaps.length:1}function T(b){return b===st||b===Fs||b===Wi?s.NEAREST:s.LINEAR}function Y(b){let y=b.target;y.removeEventListener("dispose",Y),B(y),y.isVideoTexture&&g.delete(y)}function ne(b){let y=b.target;y.removeEventListener("dispose",ne),G(y)}function B(b){let y=n.get(b);if(y.__webglInit===void 0)return;let N=b.source,j=m.get(N);if(j){let J=j[y.__cacheKey];J.usedTimes--,J.usedTimes===0&&V(b),Object.keys(j).length===0&&m.delete(N)}n.remove(b)}function V(b){let y=n.get(b);s.deleteTexture(y.__webglTexture);let N=b.source,j=m.get(N);delete j[y.__cacheKey],o.memory.textures--}function G(b){let y=b.texture,N=n.get(b),j=n.get(y);if(j.__webglTexture!==void 0&&(s.deleteTexture(j.__webglTexture),o.memory.textures--),b.depthTexture&&b.depthTexture.dispose(),b.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(N.__webglFramebuffer[J]))for(let Q=0;Q=c&&console.warn("THREE.WebGLTextures: Trying to use "+b+" texture units while this GPU supports only "+c),$+=1,b}function Z(b){let y=[];return y.push(b.wrapS),y.push(b.wrapT),y.push(b.wrapR||0),y.push(b.magFilter),y.push(b.minFilter),y.push(b.anisotropy),y.push(b.internalFormat),y.push(b.format),y.push(b.type),y.push(b.generateMipmaps),y.push(b.premultiplyAlpha),y.push(b.flipY),y.push(b.unpackAlignment),y.push(b.colorSpace),y.join()}function K(b,y){let N=n.get(b);if(b.isVideoTexture&&ct(b),b.isRenderTargetTexture===!1&&b.version>0&&N.__version!==b.version){let j=b.image;if(j===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(j.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{He(N,b,y);return}}t.bindTexture(s.TEXTURE_2D,N.__webglTexture,s.TEXTURE0+y)}function D(b,y){let N=n.get(b);if(b.version>0&&N.__version!==b.version){He(N,b,y);return}t.bindTexture(s.TEXTURE_2D_ARRAY,N.__webglTexture,s.TEXTURE0+y)}function X(b,y){let N=n.get(b);if(b.version>0&&N.__version!==b.version){He(N,b,y);return}t.bindTexture(s.TEXTURE_3D,N.__webglTexture,s.TEXTURE0+y)}function oe(b,y){let N=n.get(b);if(b.version>0&&N.__version!==b.version){St(N,b,y);return}t.bindTexture(s.TEXTURE_CUBE_MAP,N.__webglTexture,s.TEXTURE0+y)}let ae={[Zn]:s.REPEAT,[Rt]:s.CLAMP_TO_EDGE,[Ki]:s.MIRRORED_REPEAT},ce={[st]:s.NEAREST,[Fs]:s.NEAREST_MIPMAP_NEAREST,[Wi]:s.NEAREST_MIPMAP_LINEAR,[vt]:s.LINEAR,[Do]:s.LINEAR_MIPMAP_NEAREST,[Rn]:s.LINEAR_MIPMAP_LINEAR},_e={[Ph]:s.NEVER,[Fh]:s.ALWAYS,[Lh]:s.LESS,[Uh]:s.LEQUAL,[Ih]:s.EQUAL,[Oh]:s.GEQUAL,[Dh]:s.GREATER,[Nh]:s.NOTEQUAL};function Ee(b,y,N){if(N?(s.texParameteri(b,s.TEXTURE_WRAP_S,ae[y.wrapS]),s.texParameteri(b,s.TEXTURE_WRAP_T,ae[y.wrapT]),(b===s.TEXTURE_3D||b===s.TEXTURE_2D_ARRAY)&&s.texParameteri(b,s.TEXTURE_WRAP_R,ae[y.wrapR]),s.texParameteri(b,s.TEXTURE_MAG_FILTER,ce[y.magFilter]),s.texParameteri(b,s.TEXTURE_MIN_FILTER,ce[y.minFilter])):(s.texParameteri(b,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(b,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),(b===s.TEXTURE_3D||b===s.TEXTURE_2D_ARRAY)&&s.texParameteri(b,s.TEXTURE_WRAP_R,s.CLAMP_TO_EDGE),(y.wrapS!==Rt||y.wrapT!==Rt)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),s.texParameteri(b,s.TEXTURE_MAG_FILTER,T(y.magFilter)),s.texParameteri(b,s.TEXTURE_MIN_FILTER,T(y.minFilter)),y.minFilter!==st&&y.minFilter!==vt&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),y.compareFunction&&(s.texParameteri(b,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(b,s.TEXTURE_COMPARE_FUNC,_e[y.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){let j=e.get("EXT_texture_filter_anisotropic");if(y.magFilter===st||y.minFilter!==Wi&&y.minFilter!==Rn||y.type===dn&&e.has("OES_texture_float_linear")===!1||a===!1&&y.type===Ji&&e.has("OES_texture_half_float_linear")===!1)return;(y.anisotropy>1||n.get(y).__currentAnisotropy)&&(s.texParameterf(b,j.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(y.anisotropy,i.getMaxAnisotropy())),n.get(y).__currentAnisotropy=y.anisotropy)}}function ye(b,y){let N=!1;b.__webglInit===void 0&&(b.__webglInit=!0,y.addEventListener("dispose",Y));let j=y.source,J=m.get(j);J===void 0&&(J={},m.set(j,J));let Q=Z(y);if(Q!==b.__cacheKey){J[Q]===void 0&&(J[Q]={texture:s.createTexture(),usedTimes:0},o.memory.textures++,N=!0),J[Q].usedTimes++;let de=J[b.__cacheKey];de!==void 0&&(J[b.__cacheKey].usedTimes--,de.usedTimes===0&&V(y)),b.__cacheKey=Q,b.__webglTexture=J[Q].texture}return N}function He(b,y,N){let j=s.TEXTURE_2D;(y.isDataArrayTexture||y.isCompressedArrayTexture)&&(j=s.TEXTURE_2D_ARRAY),y.isData3DTexture&&(j=s.TEXTURE_3D);let J=ye(b,y),Q=y.source;t.bindTexture(j,b.__webglTexture,s.TEXTURE0+N);let de=n.get(Q);if(Q.version!==de.__version||J===!0){t.activeTexture(s.TEXTURE0+N),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,y.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,y.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,y.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);let ee=E(y)&&A(y.image)===!1,F=x(y.image,ee,!1,h);F=ut(y,F);let me=A(F)||a,fe=r.convert(y.format,y.colorSpace),pe=r.convert(y.type),he=k(y.internalFormat,fe,pe,y.colorSpace);Ee(j,y,me);let ue,De=y.mipmaps,Xe=a&&y.isVideoTexture!==!0,R=de.__version===void 0||J===!0,se=v(y,F,me);if(y.isDepthTexture)he=s.DEPTH_COMPONENT,a?y.type===dn?he=s.DEPTH_COMPONENT32F:y.type===An?he=s.DEPTH_COMPONENT24:y.type===Wn?he=s.DEPTH24_STENCIL8:he=s.DEPTH_COMPONENT16:y.type===dn&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),y.format===Xn&&he===s.DEPTH_COMPONENT&&y.type!==No&&y.type!==An&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),y.type=An,pe=r.convert(y.type)),y.format===bi&&he===s.DEPTH_COMPONENT&&(he=s.DEPTH_STENCIL,y.type!==Wn&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),y.type=Wn,pe=r.convert(y.type))),R&&(Xe?t.texStorage2D(s.TEXTURE_2D,1,he,F.width,F.height):t.texImage2D(s.TEXTURE_2D,0,he,F.width,F.height,0,fe,pe,null));else if(y.isDataTexture)if(De.length>0&&me){Xe&&R&&t.texStorage2D(s.TEXTURE_2D,se,he,De[0].width,De[0].height);for(let O=0,te=De.length;O>=1,te>>=1}}else if(De.length>0&&me){Xe&&R&&t.texStorage2D(s.TEXTURE_2D,se,he,De[0].width,De[0].height);for(let O=0,te=De.length;O0&&R++,t.texStorage2D(s.TEXTURE_CUBE_MAP,R,ue,F[0].width,F[0].height));for(let O=0;O<6;O++)if(ee){De?t.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+O,0,0,0,F[O].width,F[O].height,pe,he,F[O].data):t.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+O,0,ue,F[O].width,F[O].height,0,pe,he,F[O].data);for(let te=0;te>Q),pe=Math.max(1,y.height>>Q);J===s.TEXTURE_3D||J===s.TEXTURE_2D_ARRAY?t.texImage3D(J,Q,F,fe,pe,y.depth,0,de,ee,null):t.texImage2D(J,Q,F,fe,pe,0,de,ee,null)}t.bindFramebuffer(s.FRAMEBUFFER,b),Ge(y)?d.framebufferTexture2DMultisampleEXT(s.FRAMEBUFFER,j,J,n.get(N).__webglTexture,0,Le(y)):(J===s.TEXTURE_2D||J>=s.TEXTURE_CUBE_MAP_POSITIVE_X&&J<=s.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&s.framebufferTexture2D(s.FRAMEBUFFER,j,J,n.get(N).__webglTexture,Q),t.bindFramebuffer(s.FRAMEBUFFER,null)}function U(b,y,N){if(s.bindRenderbuffer(s.RENDERBUFFER,b),y.depthBuffer&&!y.stencilBuffer){let j=s.DEPTH_COMPONENT16;if(N||Ge(y)){let J=y.depthTexture;J&&J.isDepthTexture&&(J.type===dn?j=s.DEPTH_COMPONENT32F:J.type===An&&(j=s.DEPTH_COMPONENT24));let Q=Le(y);Ge(y)?d.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,Q,j,y.width,y.height):s.renderbufferStorageMultisample(s.RENDERBUFFER,Q,j,y.width,y.height)}else s.renderbufferStorage(s.RENDERBUFFER,j,y.width,y.height);s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,b)}else if(y.depthBuffer&&y.stencilBuffer){let j=Le(y);N&&Ge(y)===!1?s.renderbufferStorageMultisample(s.RENDERBUFFER,j,s.DEPTH24_STENCIL8,y.width,y.height):Ge(y)?d.renderbufferStorageMultisampleEXT(s.RENDERBUFFER,j,s.DEPTH24_STENCIL8,y.width,y.height):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,y.width,y.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,b)}else{let j=y.isWebGLMultipleRenderTargets===!0?y.texture:[y.texture];for(let J=0;J0){N.__webglFramebuffer[ee]=[];for(let F=0;F0){N.__webglFramebuffer=[];for(let ee=0;ee0&&Ge(b)===!1){let ee=Q?y:[y];N.__webglMultisampledFramebuffer=s.createFramebuffer(),N.__webglColorRenderbuffer=[],t.bindFramebuffer(s.FRAMEBUFFER,N.__webglMultisampledFramebuffer);for(let F=0;F0)for(let F=0;F0)for(let F=0;F0&&Ge(b)===!1){let y=b.isWebGLMultipleRenderTargets?b.texture:[b.texture],N=b.width,j=b.height,J=s.COLOR_BUFFER_BIT,Q=[],de=b.stencilBuffer?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,ee=n.get(b),F=b.isWebGLMultipleRenderTargets===!0;if(F)for(let me=0;me0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&y.__useRenderToTexture!==!1}function ct(b){let y=o.render.frame;g.get(b)!==y&&(g.set(b,y),b.update())}function ut(b,y){let N=b.colorSpace,j=b.format,J=b.type;return b.isCompressedTexture===!0||b.format===Qr||N!==Nt&&N!==Yn&&(N===xe?a===!1?e.has("EXT_sRGB")===!0&&j===Ut?(b.format=Qr,b.minFilter=vt,b.generateMipmaps=!1):y=ks.sRGBToLinear(y):(j!==Ut||J!==wn)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",N)),y}this.allocateTextureUnit=q,this.resetTextureUnits=W,this.setTexture2D=K,this.setTexture2DArray=D,this.setTexture3D=X,this.setTextureCube=oe,this.rebindTextures=we,this.setupRenderTarget=Te,this.updateRenderTargetMipmap=Ze,this.updateMultisampleRenderTarget=Fe,this.setupDepthRenderbuffer=ve,this.setupFrameBufferTexture=Pe,this.useMultisampledRTT=Ge}function zm(s,e,t){let n=t.isWebGL2;function i(r,o=Yn){let a;if(r===wn)return s.UNSIGNED_BYTE;if(r===hl)return s.UNSIGNED_SHORT_4_4_4_4;if(r===ul)return s.UNSIGNED_SHORT_5_5_5_1;if(r===gh)return s.BYTE;if(r===_h)return s.SHORT;if(r===No)return s.UNSIGNED_SHORT;if(r===ll)return s.INT;if(r===An)return s.UNSIGNED_INT;if(r===dn)return s.FLOAT;if(r===Ji)return n?s.HALF_FLOAT:(a=e.get("OES_texture_half_float"),a!==null?a.HALF_FLOAT_OES:null);if(r===xh)return s.ALPHA;if(r===Ut)return s.RGBA;if(r===yh)return s.LUMINANCE;if(r===vh)return s.LUMINANCE_ALPHA;if(r===Xn)return s.DEPTH_COMPONENT;if(r===bi)return s.DEPTH_STENCIL;if(r===Qr)return a=e.get("EXT_sRGB"),a!==null?a.SRGB_ALPHA_EXT:null;if(r===Mh)return s.RED;if(r===dl)return s.RED_INTEGER;if(r===Sh)return s.RG;if(r===fl)return s.RG_INTEGER;if(r===pl)return s.RGBA_INTEGER;if(r===_r||r===xr||r===yr||r===vr)if(o===xe)if(a=e.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(r===_r)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===xr)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===yr)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===vr)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=e.get("WEBGL_compressed_texture_s3tc"),a!==null){if(r===_r)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===xr)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===yr)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===vr)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===Ca||r===Pa||r===La||r===Ia)if(a=e.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(r===Ca)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===Pa)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===La)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===Ia)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===bh)return a=e.get("WEBGL_compressed_texture_etc1"),a!==null?a.COMPRESSED_RGB_ETC1_WEBGL:null;if(r===Ua||r===Da)if(a=e.get("WEBGL_compressed_texture_etc"),a!==null){if(r===Ua)return o===xe?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(r===Da)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===Na||r===Oa||r===Fa||r===Ba||r===za||r===ka||r===Ha||r===Va||r===Ga||r===Wa||r===Xa||r===qa||r===Ya||r===Za)if(a=e.get("WEBGL_compressed_texture_astc"),a!==null){if(r===Na)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===Oa)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===Fa)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===Ba)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===za)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===ka)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===Ha)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===Va)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===Ga)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===Wa)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===Xa)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===qa)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===Ya)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===Za)return o===xe?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===Mr)if(a=e.get("EXT_texture_compression_bptc"),a!==null){if(r===Mr)return o===xe?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT}else return null;if(r===Ah||r===Ka||r===Ja||r===$a)if(a=e.get("EXT_texture_compression_rgtc"),a!==null){if(r===Mr)return a.COMPRESSED_RED_RGTC1_EXT;if(r===Ka)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===Ja)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===$a)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===Wn?n?s.UNSIGNED_INT_24_8:(a=e.get("WEBGL_depth_texture"),a!==null?a.UNSIGNED_INT_24_8_WEBGL:null):s[r]!==void 0?s[r]:null}return{convert:i}}var mo=class extends lt{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}},$t=class extends Qe{constructor(){super(),this.isGroup=!0,this.type="Group"}},km={type:"move"},Zi=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new $t,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new $t,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new P,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new P),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new $t,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new P,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new P),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let i=null,r=null,o=null,a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(let _ of e.hand.values()){let m=t.getJointPose(_,n),f=this._getHandJoint(l,_);m!==null&&(f.matrix.fromArray(m.transform.matrix),f.matrix.decompose(f.position,f.rotation,f.scale),f.matrixWorldNeedsUpdate=!0,f.jointRadius=m.radius),f.visible=m!==null}let h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),p=.02,g=.005;l.inputState.pinching&&d>p+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&d<=p-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(i=t.getPose(e.targetRaySpace,n),i===null&&r!==null&&(i=r),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(km)))}return a!==null&&(a.visible=i!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new $t;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},go=class extends mt{constructor(e,t,n,i,r,o,a,c,l,h){if(h=h!==void 0?h:Xn,h!==Xn&&h!==bi)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");n===void 0&&h===Xn&&(n=An),n===void 0&&h===bi&&(n=Wn),super(null,i,r,o,a,c,h,n,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=a!==void 0?a:st,this.minFilter=c!==void 0?c:st,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},_o=class extends Cn{constructor(e,t){super();let n=this,i=null,r=1,o=null,a="local-floor",c=1,l=null,h=null,u=null,d=null,p=null,g=null,_=t.getContextAttributes(),m=null,f=null,S=[],x=[],A=new lt;A.layers.enable(1),A.viewport=new We;let E=new lt;E.layers.enable(2),E.viewport=new We;let C=[A,E],w=new mo;w.layers.enable(1),w.layers.enable(2);let k=null,v=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(D){let X=S[D];return X===void 0&&(X=new Zi,S[D]=X),X.getTargetRaySpace()},this.getControllerGrip=function(D){let X=S[D];return X===void 0&&(X=new Zi,S[D]=X),X.getGripSpace()},this.getHand=function(D){let X=S[D];return X===void 0&&(X=new Zi,S[D]=X),X.getHandSpace()};function T(D){let X=x.indexOf(D.inputSource);if(X===-1)return;let oe=S[X];oe!==void 0&&(oe.update(D.inputSource,D.frame,l||o),oe.dispatchEvent({type:D.type,data:D.inputSource}))}function Y(){i.removeEventListener("select",T),i.removeEventListener("selectstart",T),i.removeEventListener("selectend",T),i.removeEventListener("squeeze",T),i.removeEventListener("squeezestart",T),i.removeEventListener("squeezeend",T),i.removeEventListener("end",Y),i.removeEventListener("inputsourceschange",ne);for(let D=0;D=0&&(x[ae]=null,S[ae].disconnect(oe))}for(let X=0;X=x.length){x.push(oe),ae=_e;break}else if(x[_e]===null){x[_e]=oe,ae=_e;break}if(ae===-1)break}let ce=S[ae];ce&&ce.connect(oe)}}let B=new P,V=new P;function G(D,X,oe){B.setFromMatrixPosition(X.matrixWorld),V.setFromMatrixPosition(oe.matrixWorld);let ae=B.distanceTo(V),ce=X.projectionMatrix.elements,_e=oe.projectionMatrix.elements,Ee=ce[14]/(ce[10]-1),ye=ce[14]/(ce[10]+1),He=(ce[9]+1)/ce[5],St=(ce[9]-1)/ce[5],Pe=(ce[8]-1)/ce[0],U=(_e[8]+1)/_e[0],ht=Ee*Pe,ve=Ee*U,we=ae/(-Pe+U),Te=we*-Pe;X.matrixWorld.decompose(D.position,D.quaternion,D.scale),D.translateX(Te),D.translateZ(we),D.matrixWorld.compose(D.position,D.quaternion,D.scale),D.matrixWorldInverse.copy(D.matrixWorld).invert();let Ze=Ee+we,Fe=ye+we,Le=ht-Te,Ge=ve+(ae-Te),ct=He*ye/Fe*Ze,ut=St*ye/Fe*Ze;D.projectionMatrix.makePerspective(Le,Ge,ct,ut,Ze,Fe),D.projectionMatrixInverse.copy(D.projectionMatrix).invert()}function $(D,X){X===null?D.matrixWorld.copy(D.matrix):D.matrixWorld.multiplyMatrices(X.matrixWorld,D.matrix),D.matrixWorldInverse.copy(D.matrixWorld).invert()}this.updateCamera=function(D){if(i===null)return;w.near=E.near=A.near=D.near,w.far=E.far=A.far=D.far,(k!==w.near||v!==w.far)&&(i.updateRenderState({depthNear:w.near,depthFar:w.far}),k=w.near,v=w.far);let X=D.parent,oe=w.cameras;$(w,X);for(let ae=0;ae0&&(m.alphaTest.value=f.alphaTest);let S=e.get(f).envMap;if(S&&(m.envMap.value=S,m.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap){m.lightMap.value=f.lightMap;let x=s._useLegacyLights===!0?Math.PI:1;m.lightMapIntensity.value=f.lightMapIntensity*x,t(f.lightMap,m.lightMapTransform)}f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,t(f.aoMap,m.aoMapTransform))}function o(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform))}function a(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function c(m,f,S,x){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*S,m.scale.value=x*.5,f.map&&(m.map.value=f.map,t(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function l(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,t(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,t(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function h(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function u(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function d(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,t(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,t(f.roughnessMap,m.roughnessMapTransform)),e.get(f).envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function p(m,f,S){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,t(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,t(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,t(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,t(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,t(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===bt&&m.clearcoatNormalScale.value.negate())),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,t(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,t(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=S.texture,m.transmissionSamplerSize.value.set(S.width,S.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,t(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,t(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,t(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,t(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,t(f.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,f){f.matcap&&(m.matcap.value=f.matcap)}function _(m,f){let S=e.get(f).light;m.referencePosition.value.setFromMatrixPosition(S.matrixWorld),m.nearDistance.value=S.shadow.camera.near,m.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:i}}function Vm(s,e,t,n){let i={},r={},o=[],a=t.isWebGL2?s.getParameter(s.MAX_UNIFORM_BUFFER_BINDINGS):0;function c(S,x){let A=x.program;n.uniformBlockBinding(S,A)}function l(S,x){let A=i[S.id];A===void 0&&(g(S),A=h(S),i[S.id]=A,S.addEventListener("dispose",m));let E=x.program;n.updateUBOMapping(S,E);let C=e.render.frame;r[S.id]!==C&&(d(S),r[S.id]=C)}function h(S){let x=u();S.__bindingPointIndex=x;let A=s.createBuffer(),E=S.__size,C=S.usage;return s.bindBuffer(s.UNIFORM_BUFFER,A),s.bufferData(s.UNIFORM_BUFFER,E,C),s.bindBuffer(s.UNIFORM_BUFFER,null),s.bindBufferBase(s.UNIFORM_BUFFER,x,A),A}function u(){for(let S=0;S0){C=A%E;let ne=E-C;C!==0&&ne-T.boundary<0&&(A+=E-C,v.__offset=A)}A+=T.storage}return C=A%E,C>0&&(A+=E-C),S.__size=A,S.__cache={},this}function _(S){let x={boundary:0,storage:0};return typeof S=="number"?(x.boundary=4,x.storage=4):S.isVector2?(x.boundary=8,x.storage=8):S.isVector3||S.isColor?(x.boundary=16,x.storage=12):S.isVector4?(x.boundary=16,x.storage=16):S.isMatrix3?(x.boundary=48,x.storage=48):S.isMatrix4?(x.boundary=64,x.storage=64):S.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",S),x}function m(S){let x=S.target;x.removeEventListener("dispose",m);let A=o.indexOf(x.__bindingPointIndex);o.splice(A,1),s.deleteBuffer(i[x.id]),delete i[x.id],delete r[x.id]}function f(){for(let S in i)s.deleteBuffer(i[S]);o=[],i={},r={}}return{bind:c,update:l,dispose:f}}function Gm(){let s=$i("canvas");return s.style.display="block",s}var xo=class{constructor(e={}){let{canvas:t=Gm(),context:n=null,depth:i=!0,stencil:r=!0,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1}=e;this.isWebGLRenderer=!0;let d;n!==null?d=n.getContextAttributes().alpha:d=o;let p=new Uint32Array(4),g=new Int32Array(4),_=null,m=null,f=[],S=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.outputColorSpace=xe,this._useLegacyLights=!1,this.toneMapping=En,this.toneMappingExposure=1;let x=this,A=!1,E=0,C=0,w=null,k=-1,v=null,T=new We,Y=new We,ne=null,B=new Ae(0),V=0,G=t.width,$=t.height,W=1,q=null,Z=null,K=new We(0,0,G,$),D=new We(0,0,G,$),X=!1,oe=new Qi,ae=!1,ce=!1,_e=null,Ee=new Ue,ye=new Be,He=new P,St={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Pe(){return w===null?W:1}let U=n;function ht(M,I){for(let H=0;H0?m=S[S.length-1]:m=null,f.pop(),f.length>0?_=f[f.length-1]:_=null};function _a(M,I,H,L){if(M.visible===!1)return;if(M.layers.test(I.layers)){if(M.isGroup)H=M.renderOrder;else if(M.isLOD)M.autoUpdate===!0&&M.update(I);else if(M.isLight)m.pushLight(M),M.castShadow&&m.pushShadow(M);else if(M.isSprite){if(!M.frustumCulled||oe.intersectsSprite(M)){L&&He.setFromMatrixPosition(M.matrixWorld).applyMatrix4(Ee);let ge=y.update(M),Se=M.material;Se.visible&&_.push(M,ge,Se,H,He.z,null)}}else if((M.isMesh||M.isLine||M.isPoints)&&(!M.frustumCulled||oe.intersectsObject(M))){let ge=y.update(M),Se=M.material;if(L&&(M.boundingSphere!==void 0?(M.boundingSphere===null&&M.computeBoundingSphere(),He.copy(M.boundingSphere.center)):(ge.boundingSphere===null&&ge.computeBoundingSphere(),He.copy(ge.boundingSphere.center)),He.applyMatrix4(M.matrixWorld).applyMatrix4(Ee)),Array.isArray(Se)){let be=ge.groups;for(let Ne=0,Me=be.length;Ne0&&Ol(z,le,I,H),L&&Te.viewport(T.copy(L)),z.length>0&&hs(z,I,H),le.length>0&&hs(le,I,H),ge.length>0&&hs(ge,I,H),Te.buffers.depth.setTest(!0),Te.buffers.depth.setMask(!0),Te.buffers.color.setMask(!0),Te.setPolygonOffset(!1)}function Ol(M,I,H,L){let z=we.isWebGL2;_e===null&&(_e=new pn(1,1,{generateMipmaps:!0,type:ve.has("EXT_color_buffer_half_float")?Ji:wn,minFilter:Rn,samples:z?4:0})),x.getDrawingBufferSize(ye),z?_e.setSize(ye.x,ye.y):_e.setSize(zs(ye.x),zs(ye.y));let le=x.getRenderTarget();x.setRenderTarget(_e),x.getClearColor(B),V=x.getClearAlpha(),V<1&&x.setClearColor(16777215,.5),x.clear();let ge=x.toneMapping;x.toneMapping=En,hs(M,H,L),Le.updateMultisampleRenderTarget(_e),Le.updateRenderTargetMipmap(_e);let Se=!1;for(let be=0,Ne=I.length;be0),Re=!!H.morphAttributes.position,Je=!!H.morphAttributes.normal,je=!!H.morphAttributes.color,Lt=En;L.toneMapped&&(w===null||w.isXRRenderTarget===!0)&&(Lt=x.toneMapping);let tn=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,tt=tn!==void 0?tn.length:0,Oe=Fe.get(L),fr=m.state.lights;if(ae===!0&&(ce===!0||M!==v)){let Tt=M===v&&L.id===k;de.setState(L,M,Tt)}let nt=!1;L.version===Oe.__version?(Oe.needsLights&&Oe.lightsStateVersion!==fr.state.version||Oe.outputColorSpace!==Se||z.isInstancedMesh&&Oe.instancing===!1||!z.isInstancedMesh&&Oe.instancing===!0||z.isSkinnedMesh&&Oe.skinning===!1||!z.isSkinnedMesh&&Oe.skinning===!0||z.isInstancedMesh&&Oe.instancingColor===!0&&z.instanceColor===null||z.isInstancedMesh&&Oe.instancingColor===!1&&z.instanceColor!==null||Oe.envMap!==be||L.fog===!0&&Oe.fog!==le||Oe.numClippingPlanes!==void 0&&(Oe.numClippingPlanes!==de.numPlanes||Oe.numIntersection!==de.numIntersection)||Oe.vertexAlphas!==Ne||Oe.vertexTangents!==Me||Oe.morphTargets!==Re||Oe.morphNormals!==Je||Oe.morphColors!==je||Oe.toneMapping!==Lt||we.isWebGL2===!0&&Oe.morphTargetsCount!==tt)&&(nt=!0):(nt=!0,Oe.__version=L.version);let On=Oe.currentProgram;nt===!0&&(On=us(L,I,z));let Ma=!1,Ni=!1,pr=!1,_t=On.getUniforms(),Fn=Oe.uniforms;if(Te.useProgram(On.program)&&(Ma=!0,Ni=!0,pr=!0),L.id!==k&&(k=L.id,Ni=!0),Ma||v!==M){if(_t.setValue(U,"projectionMatrix",M.projectionMatrix),we.logarithmicDepthBuffer&&_t.setValue(U,"logDepthBufFC",2/(Math.log(M.far+1)/Math.LN2)),v!==M&&(v=M,Ni=!0,pr=!0),L.isShaderMaterial||L.isMeshPhongMaterial||L.isMeshToonMaterial||L.isMeshStandardMaterial||L.envMap){let Tt=_t.map.cameraPosition;Tt!==void 0&&Tt.setValue(U,He.setFromMatrixPosition(M.matrixWorld))}(L.isMeshPhongMaterial||L.isMeshToonMaterial||L.isMeshLambertMaterial||L.isMeshBasicMaterial||L.isMeshStandardMaterial||L.isShaderMaterial)&&_t.setValue(U,"isOrthographic",M.isOrthographicCamera===!0),(L.isMeshPhongMaterial||L.isMeshToonMaterial||L.isMeshLambertMaterial||L.isMeshBasicMaterial||L.isMeshStandardMaterial||L.isShaderMaterial||L.isShadowMaterial||z.isSkinnedMesh)&&_t.setValue(U,"viewMatrix",M.matrixWorldInverse)}if(z.isSkinnedMesh){_t.setOptional(U,z,"bindMatrix"),_t.setOptional(U,z,"bindMatrixInverse");let Tt=z.skeleton;Tt&&(we.floatVertexTextures?(Tt.boneTexture===null&&Tt.computeBoneTexture(),_t.setValue(U,"boneTexture",Tt.boneTexture,Le),_t.setValue(U,"boneTextureSize",Tt.boneTextureSize)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}let mr=H.morphAttributes;if((mr.position!==void 0||mr.normal!==void 0||mr.color!==void 0&&we.isWebGL2===!0)&&me.update(z,H,On),(Ni||Oe.receiveShadow!==z.receiveShadow)&&(Oe.receiveShadow=z.receiveShadow,_t.setValue(U,"receiveShadow",z.receiveShadow)),L.isMeshGouraudMaterial&&L.envMap!==null&&(Fn.envMap.value=be,Fn.flipEnvMap.value=be.isCubeTexture&&be.isRenderTargetTexture===!1?-1:1),Ni&&(_t.setValue(U,"toneMappingExposure",x.toneMappingExposure),Oe.needsLights&&Bl(Fn,pr),le&&L.fog===!0&&j.refreshFogUniforms(Fn,le),j.refreshMaterialUniforms(Fn,L,W,$,_e),vi.upload(U,Oe.uniformsList,Fn,Le)),L.isShaderMaterial&&L.uniformsNeedUpdate===!0&&(vi.upload(U,Oe.uniformsList,Fn,Le),L.uniformsNeedUpdate=!1),L.isSpriteMaterial&&_t.setValue(U,"center",z.center),_t.setValue(U,"modelViewMatrix",z.modelViewMatrix),_t.setValue(U,"normalMatrix",z.normalMatrix),_t.setValue(U,"modelMatrix",z.matrixWorld),L.isShaderMaterial||L.isRawShaderMaterial){let Tt=L.uniformsGroups;for(let gr=0,kl=Tt.length;gr0&&Le.useMultisampledRTT(M)===!1?z=Fe.get(M).__webglMultisampledFramebuffer:Array.isArray(Me)?z=Me[H]:z=Me,T.copy(M.viewport),Y.copy(M.scissor),ne=M.scissorTest}else T.copy(K).multiplyScalar(W).floor(),Y.copy(D).multiplyScalar(W).floor(),ne=X;if(Te.bindFramebuffer(U.FRAMEBUFFER,z)&&we.drawBuffers&&L&&Te.drawBuffers(M,z),Te.viewport(T),Te.scissor(Y),Te.setScissorTest(ne),le){let be=Fe.get(M.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_CUBE_MAP_POSITIVE_X+I,be.__webglTexture,H)}else if(ge){let be=Fe.get(M.texture),Ne=I||0;U.framebufferTextureLayer(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,be.__webglTexture,H||0,Ne)}k=-1},this.readRenderTargetPixels=function(M,I,H,L,z,le,ge){if(!(M&&M.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Se=Fe.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&ge!==void 0&&(Se=Se[ge]),Se){Te.bindFramebuffer(U.FRAMEBUFFER,Se);try{let be=M.texture,Ne=be.format,Me=be.type;if(Ne!==Ut&&he.convert(Ne)!==U.getParameter(U.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}let Re=Me===Ji&&(ve.has("EXT_color_buffer_half_float")||we.isWebGL2&&ve.has("EXT_color_buffer_float"));if(Me!==wn&&he.convert(Me)!==U.getParameter(U.IMPLEMENTATION_COLOR_READ_TYPE)&&!(Me===dn&&(we.isWebGL2||ve.has("OES_texture_float")||ve.has("WEBGL_color_buffer_float")))&&!Re){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}I>=0&&I<=M.width-L&&H>=0&&H<=M.height-z&&U.readPixels(I,H,L,z,he.convert(Ne),he.convert(Me),le)}finally{let be=w!==null?Fe.get(w).__webglFramebuffer:null;Te.bindFramebuffer(U.FRAMEBUFFER,be)}}},this.copyFramebufferToTexture=function(M,I,H=0){let L=Math.pow(2,-H),z=Math.floor(I.image.width*L),le=Math.floor(I.image.height*L);Le.setTexture2D(I,0),U.copyTexSubImage2D(U.TEXTURE_2D,H,0,0,M.x,M.y,z,le),Te.unbindTexture()},this.copyTextureToTexture=function(M,I,H,L=0){let z=I.image.width,le=I.image.height,ge=he.convert(H.format),Se=he.convert(H.type);Le.setTexture2D(H,0),U.pixelStorei(U.UNPACK_FLIP_Y_WEBGL,H.flipY),U.pixelStorei(U.UNPACK_PREMULTIPLY_ALPHA_WEBGL,H.premultiplyAlpha),U.pixelStorei(U.UNPACK_ALIGNMENT,H.unpackAlignment),I.isDataTexture?U.texSubImage2D(U.TEXTURE_2D,L,M.x,M.y,z,le,ge,Se,I.image.data):I.isCompressedTexture?U.compressedTexSubImage2D(U.TEXTURE_2D,L,M.x,M.y,I.mipmaps[0].width,I.mipmaps[0].height,ge,I.mipmaps[0].data):U.texSubImage2D(U.TEXTURE_2D,L,M.x,M.y,ge,Se,I.image),L===0&&H.generateMipmaps&&U.generateMipmap(U.TEXTURE_2D),Te.unbindTexture()},this.copyTextureToTexture3D=function(M,I,H,L,z=0){if(x.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}let le=M.max.x-M.min.x+1,ge=M.max.y-M.min.y+1,Se=M.max.z-M.min.z+1,be=he.convert(L.format),Ne=he.convert(L.type),Me;if(L.isData3DTexture)Le.setTexture3D(L,0),Me=U.TEXTURE_3D;else if(L.isDataArrayTexture)Le.setTexture2DArray(L,0),Me=U.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}U.pixelStorei(U.UNPACK_FLIP_Y_WEBGL,L.flipY),U.pixelStorei(U.UNPACK_PREMULTIPLY_ALPHA_WEBGL,L.premultiplyAlpha),U.pixelStorei(U.UNPACK_ALIGNMENT,L.unpackAlignment);let Re=U.getParameter(U.UNPACK_ROW_LENGTH),Je=U.getParameter(U.UNPACK_IMAGE_HEIGHT),je=U.getParameter(U.UNPACK_SKIP_PIXELS),Lt=U.getParameter(U.UNPACK_SKIP_ROWS),tn=U.getParameter(U.UNPACK_SKIP_IMAGES),tt=H.isCompressedTexture?H.mipmaps[0]:H.image;U.pixelStorei(U.UNPACK_ROW_LENGTH,tt.width),U.pixelStorei(U.UNPACK_IMAGE_HEIGHT,tt.height),U.pixelStorei(U.UNPACK_SKIP_PIXELS,M.min.x),U.pixelStorei(U.UNPACK_SKIP_ROWS,M.min.y),U.pixelStorei(U.UNPACK_SKIP_IMAGES,M.min.z),H.isDataTexture||H.isData3DTexture?U.texSubImage3D(Me,z,I.x,I.y,I.z,le,ge,Se,be,Ne,tt.data):H.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),U.compressedTexSubImage3D(Me,z,I.x,I.y,I.z,le,ge,Se,be,tt.data)):U.texSubImage3D(Me,z,I.x,I.y,I.z,le,ge,Se,be,Ne,tt),U.pixelStorei(U.UNPACK_ROW_LENGTH,Re),U.pixelStorei(U.UNPACK_IMAGE_HEIGHT,Je),U.pixelStorei(U.UNPACK_SKIP_PIXELS,je),U.pixelStorei(U.UNPACK_SKIP_ROWS,Lt),U.pixelStorei(U.UNPACK_SKIP_IMAGES,tn),z===0&&L.generateMipmaps&&U.generateMipmap(Me),Te.unbindTexture()},this.initTexture=function(M){M.isCubeTexture?Le.setTextureCube(M,0):M.isData3DTexture?Le.setTexture3D(M,0):M.isDataArrayTexture||M.isCompressedArrayTexture?Le.setTexture2DArray(M,0):Le.setTexture2D(M,0),Te.unbindTexture()},this.resetState=function(){E=0,C=0,w=null,Te.reset(),ue.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return fn}get physicallyCorrectLights(){return console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),!this.useLegacyLights}set physicallyCorrectLights(e){console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),this.useLegacyLights=!e}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===xe?qn:gl}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===qn?xe:Nt}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}},yo=class extends xo{};yo.prototype.isWebGL1Renderer=!0;var es=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=jr,this.updateRange={offset:0,count:-1},this.version=0,this.uuid=Wt()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;ic)continue;d.applyMatrix4(this.matrixWorld);let k=e.ray.origin.distanceTo(d);ke.far||t.push({distance:k,point:u.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}else{let f=Math.max(0,o.start),S=Math.min(m.count,o.start+o.count);for(let x=f,A=S-1;xc)continue;d.applyMatrix4(this.matrixWorld);let C=e.ray.origin.distanceTo(d);Ce.far||t.push({distance:C,point:u.clone().applyMatrix4(this.matrixWorld),index:x,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;r0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=i.length;ri.far)return;r.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:e,face:null,object:o})}}var Pi=class extends Pt{constructor(e){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new Ae(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ae(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=_l,this.normalScale=new Be(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},qt=class extends Pi{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Be(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return pt(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Ae(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Ae(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Ae(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}};function bn(s,e,t){return Cl(s)?new s.constructor(s.subarray(e,t!==void 0?t:s.length)):s.slice(e,t)}function Os(s,e,t){return!s||!t&&s.constructor===e?s:typeof e.BYTES_PER_ELEMENT=="number"?new e(s):Array.prototype.slice.call(s)}function Cl(s){return ArrayBuffer.isView(s)&&!(s instanceof DataView)}function Ym(s){function e(i,r){return s[i]-s[r]}let t=s.length,n=new Array(t);for(let i=0;i!==t;++i)n[i]=i;return n.sort(e),n}function el(s,e,t){let n=s.length,i=new s.constructor(n);for(let r=0,o=0;o!==n;++r){let a=t[r]*e;for(let c=0;c!==e;++c)i[o++]=s[a+c]}return i}function Pl(s,e,t,n){let i=1,r=s[0];for(;r!==void 0&&r[n]===void 0;)r=s[i++];if(r===void 0)return;let o=r[n];if(o!==void 0)if(Array.isArray(o))do o=r[n],o!==void 0&&(e.push(r.time),t.push.apply(t,o)),r=s[i++];while(r!==void 0);else if(o.toArray!==void 0)do o=r[n],o!==void 0&&(e.push(r.time),o.toArray(t,t.length)),r=s[i++];while(r!==void 0);else do o=r[n],o!==void 0&&(e.push(r.time),t.push(o)),r=s[i++];while(r!==void 0)}var Pn=class{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,i=t[n],r=t[n-1];n:{e:{let o;t:{i:if(!(e=r)){let a=t[1];e=r)break e}o=n,n=0;break t}break n}for(;n>>1;et;)--o;if(++o,r!==0||o!==i){r>=o&&(o=Math.max(o,1),r=o-1);let a=this.getValueSize();this.times=bn(n,r,o),this.values=bn(this.values,r*a,o*a)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,i=this.values,r=n.length;r===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let o=null;for(let a=0;a!==r;a++){let c=n[a];if(typeof c=="number"&&isNaN(c)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,a,c),e=!1;break}if(o!==null&&o>c){console.error("THREE.KeyframeTrack: Out of order keys.",this,a,c,o),e=!1;break}o=c}if(i!==void 0&&Cl(i))for(let a=0,c=i.length;a!==c;++a){let l=i[a];if(isNaN(l)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,a,l),e=!1;break}}return e}optimize(){let e=bn(this.times),t=bn(this.values),n=this.getValueSize(),i=this.getInterpolation()===Sr,r=e.length-1,o=1;for(let a=1;a0){e[o]=e[r];for(let a=r*n,c=o*n,l=0;l!==n;++l)t[c+l]=t[a+l];++o}return o!==e.length?(this.times=bn(e,0,o),this.values=bn(t,0,o*n)):(this.times=e,this.values=t),this}clone(){let e=bn(this.times,0),t=bn(this.values,0),n=this.constructor,i=new n(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}};Ft.prototype.TimeBufferType=Float32Array;Ft.prototype.ValueBufferType=Float32Array;Ft.prototype.DefaultInterpolation=Kn;var Ln=class extends Ft{};Ln.prototype.ValueTypeName="bool";Ln.prototype.ValueBufferType=Array;Ln.prototype.DefaultInterpolation=Ai;Ln.prototype.InterpolantFactoryMethodLinear=void 0;Ln.prototype.InterpolantFactoryMethodSmooth=void 0;var nr=class extends Ft{};nr.prototype.ValueTypeName="color";var gn=class extends Ft{};gn.prototype.ValueTypeName="number";var To=class extends Pn{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=(n-t)/(i-t),l=e*a;for(let h=l+a;l!==h;l+=4)Xt.slerpFlat(r,0,o,l-a,o,l,c);return r}},en=class extends Ft{InterpolantFactoryMethodLinear(e){return new To(this.times,this.values,this.getValueSize(),e)}};en.prototype.ValueTypeName="quaternion";en.prototype.DefaultInterpolation=Kn;en.prototype.InterpolantFactoryMethodSmooth=void 0;var In=class extends Ft{};In.prototype.ValueTypeName="string";In.prototype.ValueBufferType=Array;In.prototype.DefaultInterpolation=Ai;In.prototype.InterpolantFactoryMethodLinear=void 0;In.prototype.InterpolantFactoryMethodSmooth=void 0;var _n=class extends Ft{};_n.prototype.ValueTypeName="vector";var ir=class{constructor(e,t=-1,n,i=Th){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=Wt(),this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let o=0,a=n.length;o!==a;++o)t.push(Km(n[o]).scale(i));let r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r}static toJSON(e){let t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let r=0,o=n.length;r!==o;++r)t.push(Ft.toJSON(n[r]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let r=t.length,o=[];for(let a=0;a1){let u=h[1],d=i[u];d||(i[u]=d=[]),d.push(l)}}let o=[];for(let a in i)o.push(this.CreateFromMorphTargetSequence(a,i[a],t,n));return o}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;let n=function(u,d,p,g,_){if(p.length!==0){let m=[],f=[];Pl(p,m,f,g),m.length!==0&&_.push(new u(d,m,f))}},i=[],r=e.name||"default",o=e.fps||30,a=e.blendMode,c=e.length||-1,l=e.hierarchy||[];for(let u=0;u{t&&t(r),this.manager.itemEnd(e)},0),r;if(ln[e]!==void 0){ln[e].push({onLoad:t,onProgress:n,onError:i});return}ln[e]=[],ln[e].push({onLoad:t,onProgress:n,onError:i});let o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,c=this.responseType;fetch(o).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;let h=ln[e],u=l.body.getReader(),d=l.headers.get("Content-Length")||l.headers.get("X-File-Size"),p=d?parseInt(d):0,g=p!==0,_=0,m=new ReadableStream({start(f){S();function S(){u.read().then(({done:x,value:A})=>{if(x)f.close();else{_+=A.byteLength;let E=new ProgressEvent("progress",{lengthComputable:g,loaded:_,total:p});for(let C=0,w=h.length;C{switch(c){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(h=>new DOMParser().parseFromString(h,a));case"json":return l.json();default:if(a===void 0)return l.text();{let u=/charset="?([^;"\s]*)"?/i.exec(a),d=u&&u[1]?u[1].toLowerCase():void 0,p=new TextDecoder(d);return l.arrayBuffer().then(g=>p.decode(g))}}}).then(l=>{Li.add(e,l);let h=ln[e];delete ln[e];for(let u=0,d=h.length;u{let h=ln[e];if(h===void 0)throw this.manager.itemError(e),l;delete ln[e];for(let u=0,d=h.length;u{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}};var Ro=class extends Yt{constructor(e){super(e)}load(e,t,n,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let r=this,o=Li.get(e);if(o!==void 0)return r.manager.itemStart(e),setTimeout(function(){t&&t(o),r.manager.itemEnd(e)},0),o;let a=$i("img");function c(){h(),Li.add(e,this),t&&t(this),r.manager.itemEnd(e)}function l(u){h(),i&&i(u),r.manager.itemError(e),r.manager.itemEnd(e)}function h(){a.removeEventListener("load",c,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",c,!1),a.addEventListener("error",l,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(e),a.src=e,a}};var sr=class extends Yt{constructor(e){super(e)}load(e,t,n,i){let r=new mt,o=new Ro(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(e,function(a){r.image=a,r.needsUpdate=!0,t!==void 0&&t(r)},n,i),r}},os=class extends Qe{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Ae(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),t}};var Yr=new Ue,tl=new P,nl=new P,as=class{constructor(e){this.camera=e,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Be(512,512),this.map=null,this.mapPass=null,this.matrix=new Ue,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Qi,this._frameExtents=new Be(1,1),this._viewportCount=1,this._viewports=[new We(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;tl.setFromMatrixPosition(e.matrixWorld),t.position.copy(tl),nl.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(nl),t.updateMatrixWorld(),Yr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Yr),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Yr)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.bias=e.bias,this.radius=e.radius,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},Co=class extends as{constructor(){super(new lt(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){let t=this.camera,n=Ti*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height,r=e.distance||t.far;(n!==t.fov||i!==t.aspect||r!==t.far)&&(t.fov=n,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},rr=class extends os{constructor(e,t,n=0,i=Math.PI/3,r=0,o=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Qe.DEFAULT_UP),this.updateMatrix(),this.target=new Qe,this.distance=n,this.angle=i,this.penumbra=r,this.decay=o,this.map=null,this.shadow=new Co}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},il=new Ue,Vi=new P,Zr=new P,Po=class extends as{constructor(){super(new lt(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Be(4,2),this._viewportCount=6,this._viewports=[new We(2,1,1,1),new We(0,1,1,1),new We(3,1,1,1),new We(1,1,1,1),new We(3,0,1,1),new We(1,0,1,1)],this._cubeDirections=[new P(1,0,0),new P(-1,0,0),new P(0,0,1),new P(0,0,-1),new P(0,1,0),new P(0,-1,0)],this._cubeUps=[new P(0,1,0),new P(0,1,0),new P(0,1,0),new P(0,1,0),new P(0,0,1),new P(0,0,-1)]}updateMatrices(e,t=0){let n=this.camera,i=this.matrix,r=e.distance||n.far;r!==n.far&&(n.far=r,n.updateProjectionMatrix()),Vi.setFromMatrixPosition(e.matrixWorld),n.position.copy(Vi),Zr.copy(n.position),Zr.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(Zr),n.updateMatrixWorld(),i.makeTranslation(-Vi.x,-Vi.y,-Vi.z),il.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(il)}},or=class extends os{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Po}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}},Lo=class extends as{constructor(){super(new Ri(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},ar=class extends os{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Qe.DEFAULT_UP),this.updateMatrix(),this.target=new Qe,this.shadow=new Lo}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}};var Ii=class{static decodeText(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let n=0,i=e.length;n"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(e){return this.options=e,this}load(e,t,n,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let r=this,o=Li.get(e);if(o!==void 0)return r.manager.itemStart(e),setTimeout(function(){t&&t(o),r.manager.itemEnd(e)},0),o;let a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader,fetch(e,a).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(c){Li.add(e,c),t&&t(c),r.manager.itemEnd(e)}).catch(function(c){i&&i(c),r.manager.itemError(e),r.manager.itemEnd(e)}),r.manager.itemStart(e)}};var Bo="\\[\\]\\.:\\/",$m=new RegExp("["+Bo+"]","g"),zo="[^"+Bo+"]",jm="[^"+Bo.replace("\\.","")+"]",Qm=/((?:WC+[\/:])*)/.source.replace("WC",zo),eg=/(WCOD+)?/.source.replace("WCOD",jm),tg=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",zo),ng=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",zo),ig=new RegExp("^"+Qm+eg+tg+ng+"$"),sg=["material","materials","bones","map"],Io=class{constructor(e,t,n){let i=n||qe.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,i=this._bindings[n];i!==void 0&&i.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,r=n.length;i!==r;++i)n[i].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},qe=class s{constructor(e,t,n){this.path=t,this.parsedPath=n||s.parseTrackName(t),this.node=s.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new s.Composite(e,t,n):new s(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace($m,"")}static parseTrackName(e){let t=ig.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let r=n.nodeName.substring(i+1);sg.indexOf(r)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=r)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(r){for(let o=0;o=2.0 are supported."));return}let l=new pa(r,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(o),l.setPlugins(a),l.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,r){n.parse(e,t,i,r)})}};function rg(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}var ze={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},Xo=class{constructor(e){this.parser=e,this.name=ze.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,r.source,o)}},ia=class{constructor(e){this.parser=e,this.name=ze.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){let t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],a=i.images[o.source],c=n.textureLoader;if(a.uri){let l=n.options.manager.getHandler(a.uri);l!==null&&(c=l)}return this.detectSupport().then(function(l){if(l)return n.loadTextureImage(e,o.source,c);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){let t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}},sa=class{constructor(e){this.parser=e,this.name=ze.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){let t=this.name,n=this.parser,i=n.json,r=i.textures[e];if(!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],a=i.images[o.source],c=n.textureLoader;if(a.uri){let l=n.options.manager.getHandler(a.uri);l!==null&&(c=l)}return this.detectSupport().then(function(l){if(l)return n.loadTextureImage(e,o.source,c);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){let t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}},ra=class{constructor(e){this.name=ze.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let i=n.extensions[this.name],r=this.parser.getDependency("buffer",i.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return r.then(function(a){let c=i.byteOffset||0,l=i.byteLength||0,h=i.count,u=i.byteStride,d=new Uint8Array(a,c,l);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(h,u,d,i.mode,i.filter).then(function(p){return p.buffer}):o.ready.then(function(){let p=new ArrayBuffer(h*u);return o.decodeGltfBuffer(new Uint8Array(p),h,u,d,i.mode,i.filter),p})})}else return null}},oa=class{constructor(e){this.name=ze.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let i=t.meshes[n.mesh];for(let l of i.primitives)if(l.mode!==Bt.TRIANGLES&&l.mode!==Bt.TRIANGLE_STRIP&&l.mode!==Bt.TRIANGLE_FAN&&l.mode!==void 0)return null;let o=n.extensions[this.name].attributes,a=[],c={};for(let l in o)a.push(this.parser.getDependency("accessor",o[l]).then(h=>(c[l]=h,c[l])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(l=>{let h=l.pop(),u=h.isGroup?h.children:[h],d=l[0].count,p=[];for(let g of u){let _=new Ue,m=new P,f=new Xt,S=new P(1,1,1),x=new js(g.geometry,g.material,d);for(let A=0;A0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}var fg=new Ue,pa=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new rg,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=!1,r=-1;typeof navigator<"u"&&(n=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)===!0,i=navigator.userAgent.indexOf("Firefox")>-1,r=i?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1),typeof createImageBitmap>"u"||n||i&&r<98?this.textureLoader=new sr(this.options.manager):this.textureLoader=new cr(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Un(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,i=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){let a={scene:o[0][i.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:i.asset,parser:n,userData:{}};Jn(r,a,i),Nn(a,i),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,r=t.length;i{let c=this.associations.get(o);c!=null&&this.associations.set(a,c);for(let[l,h]of o.children.entries())r(h,a.children[l])};return r(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n=2&&m.setY(v,C[w*c+1]),c>=3&&m.setZ(v,C[w*c+2]),c>=4&&m.setW(v,C[w*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return m})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,o=t.images[r],a=this.textureLoader;if(o.uri){let c=n.manager.getHandler(o.uri);c!==null&&(a=c)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let i=this,r=this.json,o=r.textures[e],a=r.images[t],c=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];let l=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=o.name||a.name||"",h.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(h.name=a.uri);let d=(r.samplers||{})[o.sampler]||{};return h.magFilter=Il[d.magFilter]||vt,h.minFilter=Il[d.minFilter]||Rn,h.wrapS=Ul[d.wrapS]||Zn,h.wrapT=Ul[d.wrapT]||Zn,i.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[c]=l,l}loadImageSource(e,t){let n=this,i=this.json,r=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());let o=i.images[e],a=self.URL||self.webkitURL,c=o.uri||"",l=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(u){l=!0;let d=new Blob([u],{type:o.mimeType});return c=a.createObjectURL(d),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let h=Promise.resolve(c).then(function(u){return new Promise(function(d,p){let g=d;t.isImageBitmapLoader===!0&&(g=function(_){let m=new mt(_);m.needsUpdate=!0,d(m)}),t.load(Ii.resolveURL(u,r.path),g,void 0,p)})}).then(function(u){return l===!0&&a.revokeObjectURL(c),u.userData.mimeType=o.mimeType||dg(o.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=h,h}assignTexture(e,t,n,i){let r=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),r.extensions[ze.KHR_TEXTURE_TRANSFORM]){let a=n.extensions!==void 0?n.extensions[ze.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let c=r.associations.get(o);o=r.extensions[ze.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),r.associations.set(o,c)}}return i!==void 0&&(o.colorSpace=i),e[t]=o,o})}assignFinalMaterial(e){let t=e.geometry,n=e.material,i=t.attributes.tangent===void 0,r=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){let a="PointsMaterial:"+n.uuid,c=this.cache.get(a);c||(c=new rs,Pt.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){let a="LineBasicMaterial:"+n.uuid,c=this.cache.get(a);c||(c=new ss,Pt.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(i||r||o){let a="ClonedMaterial:"+n.uuid+":";i&&(a+="derivative-tangents:"),r&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),r&&(c.vertexColors=!0),o&&(c.flatShading=!0),i&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return Pi}loadMaterial(e){let t=this,n=this.json,i=this.extensions,r=n.materials[e],o,a={},c=r.extensions||{},l=[];if(c[ze.KHR_MATERIALS_UNLIT]){let u=i[ze.KHR_MATERIALS_UNLIT];o=u.getMaterialType(),l.push(u.extendParams(a,r,t))}else{let u=r.pbrMetallicRoughness||{};if(a.color=new Ae(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){let d=u.baseColorFactor;a.color.fromArray(d),a.opacity=d[3]}u.baseColorTexture!==void 0&&l.push(t.assignTexture(a,"map",u.baseColorTexture,xe)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),l.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),o=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,a)})))}r.doubleSided===!0&&(a.side=Gt);let h=r.alphaMode||Vo.OPAQUE;if(h===Vo.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,h===Vo.MASK&&(a.alphaTest=r.alphaCutoff!==void 0?r.alphaCutoff:.5)),r.normalTexture!==void 0&&o!==Qt&&(l.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new Be(1,1),r.normalTexture.scale!==void 0)){let u=r.normalTexture.scale;a.normalScale.set(u,u)}return r.occlusionTexture!==void 0&&o!==Qt&&(l.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),r.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=r.occlusionTexture.strength)),r.emissiveFactor!==void 0&&o!==Qt&&(a.emissive=new Ae().fromArray(r.emissiveFactor)),r.emissiveTexture!==void 0&&o!==Qt&&l.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,xe)),Promise.all(l).then(function(){let u=new o(a);return r.name&&(u.name=r.name),Nn(u,r),t.associations.set(u,{materials:e}),r.extensions&&Jn(i,u,r),u})}createUniqueName(e){let t=qe.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,i=this.primitiveCache;function r(a){return n[ze.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return Dl(c,a,t)})}let o=[];for(let a=0,c=e.length;a0&&hg(f,r),f.name=t.createUniqueName(r.name||"mesh_"+e),Nn(f,r),m.extensions&&Jn(i,f,m),t.assignFinalMaterial(f),u.push(f)}for(let p=0,g=u.length;p1?h=new $t:l.length===1?h=l[0]:h=new Qe,h!==l[0])for(let u=0,d=l.length;u{let u=new Map;for(let[d,p]of i.associations)(d instanceof Pt||d instanceof mt)&&u.set(d,p);return h.traverse(d=>{let p=i.associations.get(d);p!=null&&u.set(d,p)}),u};return i.associations=l(r),r})}_createAnimationTracks(e,t,n,i,r){let o=[],a=e.name?e.name:e.uuid,c=[];Dn[r.path]===Dn.weights?e.traverse(function(d){d.morphTargetInfluences&&c.push(d.name?d.name:d.uuid)}):c.push(a);let l;switch(Dn[r.path]){case Dn.weights:l=gn;break;case Dn.rotation:l=en;break;case Dn.position:case Dn.scale:l=_n;break;default:switch(n.itemSize){case 1:l=gn;break;case 2:case 3:default:l=_n;break}break}let h=i.interpolation!==void 0?ag[i.interpolation]:Kn,u=this._getArrayFromAccessor(n);for(let d=0,p=c.length;d{this.parse(o,t,i)},n,i)}parse(e,t,n){this.decodeDracoFile(e,t,null,null,xe).catch(n)}decodeDracoFile(e,t,n,i,r=Nt){let o={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:i||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:r};return this.decodeGeometry(e,o).then(t)}decodeGeometry(e,t){let n=JSON.stringify(t);if(ma.has(e)){let c=ma.get(e);if(c.key===n)return c.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let i,r=this.workerNextTaskID++,o=e.byteLength,a=this._getWorker(r,o).then(c=>(i=c,new Promise((l,h)=>{i._callbacks[r]={resolve:l,reject:h},i.postMessage({type:"decode",id:r,taskConfig:t,buffer:e},[e])}))).then(c=>this._createGeometry(c.geometry));return a.catch(()=>!0).then(()=>{i&&r&&this._releaseTask(i,r)}),ma.set(e,{key:n,promise:a}),a}_createGeometry(e){let t=new At;e.index&&t.setIndex(new $e(e.index.array,1));for(let n=0;n{n.load(e,i,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;let e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{let i=n[0];e||(this.decoderConfig.wasmBinary=n[1]);let r=mg.toString(),o=["/* draco decoder */",i,"","/* worker */",r.substring(r.indexOf("{")+1,r.lastIndexOf("}"))].join(` `);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.lengthr._taskLoad?-1:1});let n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e{let u=h.draco,d=new u.Decoder;try{let p=t(u,d,new Int8Array(c),l),g=p.attributes.map(_=>_.array.buffer);p.index&&g.push(p.index.array.buffer),self.postMessage({type:"decode",id:a.id,geometry:p},g)}catch(p){console.error(p),self.postMessage({type:"error",id:a.id,error:p.message})}finally{u.destroy(d)}});break}};function t(o,a,c,l){let h=l.attributeIDs,u=l.attributeTypes,d,p,g=a.GetEncodedGeometryType(c);if(g===o.TRIANGULAR_MESH)d=new o.Mesh,p=a.DecodeArrayToMesh(c,c.byteLength,d);else if(g===o.POINT_CLOUD)d=new o.PointCloud,p=a.DecodeArrayToPointCloud(c,c.byteLength,d);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!p.ok()||d.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+p.error_msg());let _={index:null,attributes:[]};for(let m in h){let f=self[u[m]],S,x;if(l.useUniqueIDs)x=h[m],S=a.GetAttributeByUniqueId(d,x);else{if(x=a.GetAttributeId(d,o[h[m]]),x===-1)continue;S=a.GetAttribute(d,x)}let A=i(o,a,d,m,f,S);m==="color"&&(A.vertexColorSpace=l.vertexColorSpace),_.attributes.push(A)}return g===o.TRIANGULAR_MESH&&(_.index=n(o,a,d)),o.destroy(d),_}function n(o,a,c){let h=c.num_faces()*3,u=h*4,d=o._malloc(u);a.GetTrianglesUInt32Array(c,u,d);let p=new Uint32Array(o.HEAPF32.buffer,d,h).slice();return o._free(d),{array:p,itemSize:1}}function i(o,a,c,l,h,u){let d=u.num_components(),g=c.num_points()*d,_=g*h.BYTES_PER_ELEMENT,m=r(o,h),f=o._malloc(_);a.GetAttributeDataArrayForAllPoints(c,u,m,_,f);let S=new h(o.HEAPF32.buffer,f,g).slice();return o._free(f),{name:l,array:S,itemSize:d}}function r(o,a){switch(a){case Float32Array:return o.DT_FLOAT32;case Int8Array:return o.DT_INT8;case Int16Array:return o.DT_INT16;case Int32Array:return o.DT_INT32;case Uint8Array:return o.DT_UINT8;case Uint16Array:return o.DT_UINT16;case Uint32Array:return o.DT_UINT32}}}export{ga as DRACOLoader,Wo as GLTFLoader}; /** * @license * Copyright 2010-2023 Three.js Authors * SPDX-License-Identifier: MIT */ ================================================ FILE: lang/shadeup/engine/input/input.ts ================================================ import { keyboardKeys } from './keyboardKeys'; export type MouseState = { button: [boolean, boolean, boolean]; clicked: [boolean, boolean, boolean]; screen: [number, number]; uv: [number, number]; startScreen: [number, number]; startUv: [number, number]; deltaUv: [number, number]; frameDeltaUv: [number, number]; deltaScreen: [number, number]; frameDeltaScreen: [number, number]; dragging: boolean; velocity: number; wheel: number; focused: boolean; }; export function initInput( canvas: HTMLCanvasElement, mouseState: MouseState, keyboardSink: Map ) { let frameKeySink = new Map(); window.addEventListener('keydown', (e) => { keyboardSink.set(e.code, true); frameKeySink.set(e.code, true); if (e.code.startsWith('Arrow')) { e.preventDefault(); } }); window.addEventListener('keyup', (e) => { if (keyboardSink.has(e.code)) { keyboardSink.delete(e.code); } }); let puckDown = false; let puckId = ''; let offsetLeft = document.querySelector('.ui-container')?.offsetLeft ?? 0; let offsetTop = document.querySelector('.ui-container')?.offsetTop ?? 0; window.addEventListener('mousedown', (e: MouseEvent) => { if (e.target && (e.target as HTMLElement).closest('.ui-container')) { mouseState.button[e.button] = true; console.log('down', mouseState.button); mouseState.startScreen = [...mouseState.screen]; mouseState.startUv = [...mouseState.uv]; mouseState.deltaScreen = [0, 0]; mouseState.deltaUv = [0, 0]; mouseState.dragging = true; } }); window.addEventListener('mouseup', (e) => { mouseState.clicked[0] = false; mouseState.clicked[1] = false; mouseState.clicked[2] = false; mouseState.button[e.button] = false; mouseState.dragging = false; }); window.addEventListener('click', (e) => { if (e.target && (e.target as HTMLElement).closest('.ui-container')) { mouseState.clicked[e.button] = true; } }); window.addEventListener('mousemove', (e) => { mouseState.screen = [ (e.clientX - offsetLeft) * window.devicePixelRatio, (e.clientY - offsetTop) * window.devicePixelRatio ]; mouseState.uv = [ ((e.clientX - offsetLeft) * window.devicePixelRatio) / canvas.width, ((e.clientY - offsetTop) * window.devicePixelRatio) / canvas.height ]; if (mouseState.dragging) { mouseState.deltaScreen = [ mouseState.screen[0] - mouseState.startScreen[0], mouseState.screen[1] - mouseState.startScreen[1] ]; mouseState.deltaUv = [ mouseState.uv[0] - mouseState.startUv[0], mouseState.uv[1] - mouseState.startUv[1] ]; } }); window.addEventListener('touchstart', (e) => { if (e.target && (e.target as HTMLElement).closest('.ui-container')) { mouseState.button[0] = true; mouseState.startScreen = [...mouseState.screen]; mouseState.startUv = [...mouseState.uv]; mouseState.deltaScreen = [0, 0]; mouseState.deltaUv = [0, 0]; mouseState.dragging = true; } }); window.addEventListener('touchend', (e) => { mouseState.button[0] = false; mouseState.dragging = false; }); window.addEventListener('touchmove', (e) => { mouseState.screen = [ (e.touches[0].clientX - offsetLeft) * window.devicePixelRatio, (e.touches[0].clientY - offsetTop) * window.devicePixelRatio ]; mouseState.uv = [ ((e.touches[0].clientX - offsetLeft) * window.devicePixelRatio) / canvas.width, ((e.touches[0].clientY - offsetTop) * window.devicePixelRatio) / canvas.height ]; if (mouseState.dragging) { mouseState.deltaScreen = [ mouseState.screen[0] - mouseState.startScreen[0], mouseState.screen[1] - mouseState.startScreen[1] ]; mouseState.deltaUv = [ mouseState.uv[0] - mouseState.startUv[0], mouseState.uv[1] - mouseState.startUv[1] ]; } }); window.addEventListener( 'wheel', (e) => { if ( e.target.matches('canvas') || e.target.matches('.ui-container') || e.target == document.body ) { e.preventDefault(); mouseState.wheel += normalizeWheel(e).pixelY * -0.01; } }, { passive: false } ); window.addEventListener('scroll', (e) => { if ( e.target.matches('canvas') || e.target.matches('.ui-container') || e.target == document.body ) { e.preventDefault(); } }); document.addEventListener('scroll', (e) => { // e.preventDefault(); }); let getKeyboardState = () => { let keys: { [key: string]: boolean | [number, number] } = {}; for (let key of keyboardKeys) { if (!key.code) continue; let realKey = key.code[0].toLowerCase() + key.code.slice(1); keys[realKey] = keyboardSink.has(key.code); keys['pressed' + key.code] = frameKeySink.has(key.code); } let vec = [0, 0]; if (keys.keyW) vec[1] -= 1; if (keys.keyS) vec[1] += 1; if (keys.keyA) vec[0] -= 1; if (keys.keyD) vec[0] += 1; if (keys.arrowUp) vec[1] -= 1; if (keys.arrowDown) vec[1] += 1; if (keys.arrowLeft) vec[0] -= 1; if (keys.arrowRight) vec[0] += 1; keys.arrowVector = [vec[0], vec[1]]; frameKeySink.clear(); return keys; }; return { getKeyboardState }; } // Reasonable defaults var PIXEL_STEP = 10; var LINE_HEIGHT = 40; var PAGE_HEIGHT = 800; // Taken from SO answer/facebook code https://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers export function normalizeWheel(/*object*/ event: any) /*object*/ { var sX = 0, sY = 0, // spinX, spinY pX = 0, pY = 0; // pixelX, pixelY // Legacy if ('detail' in event) { sY = event.detail; } if ('wheelDelta' in event) { sY = -event.wheelDelta / 120; } if ('wheelDeltaY' in event) { sY = -event.wheelDeltaY / 120; } if ('wheelDeltaX' in event) { sX = -event.wheelDeltaX / 120; } // side scrolling on FF with DOMMouseScroll if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) { sX = sY; sY = 0; } pX = sX * PIXEL_STEP; pY = sY * PIXEL_STEP; if ('deltaY' in event) { pY = event.deltaY; } if ('deltaX' in event) { pX = event.deltaX; } if ((pX || pY) && event.deltaMode) { if (event.deltaMode == 1) { // delta in LINE units pX *= LINE_HEIGHT; pY *= LINE_HEIGHT; } else { // delta in PAGE units pX *= PAGE_HEIGHT; pY *= PAGE_HEIGHT; } } // Fall-back if spin cannot be determined if (pX && !sX) { sX = pX < 1 ? -1 : 1; } if (pY && !sY) { sY = pY < 1 ? -1 : 1; } return { spinX: sX, spinY: sY, pixelX: pX, pixelY: pY }; } ================================================ FILE: lang/shadeup/engine/input/keyboardKeys.ts ================================================ export const keyboardKeys = [ { name: 'backspace', which: '8', key: 'Backspace', code: 'Backspace' }, { name: 'tab', which: '9', key: 'Tab', code: 'Tab' }, { name: 'enter', which: '13', key: 'Enter', code: 'Enter' }, { name: 'shift(left)', which: '16', key: 'Shift', code: 'ShiftLeft' }, { name: 'shift(right)', which: '16', key: 'Shift', code: 'ShiftRight' }, { name: 'ctrl(left)', which: '17', key: 'Control', code: 'ControlLeft' }, { name: 'ctrl(right)', which: '17', key: 'Control', code: 'ControlRight' }, { name: 'alt(left)', which: '18', key: 'Alt', code: 'AltLeft' }, { name: 'alt(right)', which: '18', key: 'Alt', code: 'AltRight' }, { name: 'pause/break', which: '19', key: 'Pause', code: 'Pause' }, { name: 'caps lock', which: '20', key: 'CapsLock', code: 'CapsLock' }, { name: 'escape', which: '27', key: 'Escape', code: 'Escape' }, { name: 'space', which: '32', key: '', code: 'Space' }, { name: 'page up', which: '33', key: 'PageUp', code: 'PageUp' }, { name: 'page down', which: '34', key: 'PageDown', code: 'PageDown' }, { name: 'end', which: '35', key: 'End', code: 'End' }, { name: 'home', which: '36', key: 'Home', code: 'Home' }, { name: 'left arrow', which: '37', key: 'ArrowLeft', code: 'ArrowLeft' }, { name: 'up arrow', which: '38', key: 'ArrowUp', code: 'ArrowUp' }, { name: 'right arrow', which: '39', key: 'ArrowRight', code: 'ArrowRight' }, { name: 'down arrow', which: '40', key: 'ArrowDown', code: 'ArrowDown' }, { name: 'print screen', which: '44', key: 'PrintScreen', code: 'PrintScreen' }, { name: 'insert', which: '45', key: 'Insert', code: 'Insert' }, { name: 'delete', which: '46', key: 'Delete', code: 'Delete' }, { name: '0', which: '48', key: '0', code: 'Digit0' }, { name: '1', which: '49', key: '1', code: 'Digit1' }, { name: '2', which: '50', key: '2', code: 'Digit2' }, { name: '3', which: '51', key: '3', code: 'Digit3' }, { name: '#', which: '51', key: '#', code: 'Digit3' }, { name: '4', which: '52', key: '4', code: 'Digit4' }, { name: '5', which: '53', key: '5', code: 'Digit5' }, { name: '6', which: '54', key: '6', code: 'Digit6' }, { name: '7', which: '55', key: '7', code: 'Digit7' }, { name: '8', which: '56', key: '8', code: 'Digit8' }, { name: '9', which: '57', key: '9', code: 'Digit9' }, { name: 'a', which: '65', key: 'a', code: 'KeyA' }, { name: 'b', which: '66', key: 'b', code: 'KeyB' }, { name: 'c', which: '67', key: 'c', code: 'KeyC' }, { name: 'd', which: '68', key: 'd', code: 'KeyD' }, { name: 'e', which: '69', key: 'e', code: 'KeyE' }, { name: 'f', which: '70', key: 'f', code: 'KeyF' }, { name: 'g', which: '71', key: 'g', code: 'KeyG' }, { name: 'h', which: '72', key: 'h', code: 'KeyH' }, { name: 'i', which: '73', key: 'i', code: 'KeyI' }, { name: 'j', which: '74', key: 'j', code: 'KeyJ' }, { name: 'k', which: '75', key: 'k', code: 'KeyK' }, { name: 'l', which: '76', key: 'l', code: 'KeyL' }, { name: 'm', which: '77', key: 'm', code: 'KeyM' }, { name: 'n', which: '78', key: 'n', code: 'KeyN' }, { name: 'o', which: '79', key: 'o', code: 'KeyO' }, { name: 'p', which: '80', key: 'p', code: 'KeyP' }, { name: 'q', which: '81', key: 'q', code: 'KeyQ' }, { name: 'r', which: '82', key: 'r', code: 'KeyR' }, { name: 's', which: '83', key: 's', code: 'KeyS' }, { name: 't', which: '84', key: 't', code: 'KeyT' }, { name: 'u', which: '85', key: 'u', code: 'KeyU' }, { name: 'v', which: '86', key: 'v', code: 'KeyV' }, { name: 'w', which: '87', key: 'w', code: 'KeyW' }, { name: 'x', which: '88', key: 'x', code: 'KeyX' }, { name: 'y', which: '89', key: 'y', code: 'KeyY' }, { name: 'z', which: '90', key: 'z', code: 'KeyZ' }, { name: 'left window key', which: '91', key: 'Meta', code: 'MetaLeft' }, { name: 'right window key', which: '92', key: 'Meta', code: 'MetaRight' }, { name: 'select key (Context Menu)', which: '93', key: 'ContextMenu', code: 'ContextMenu' }, { name: 'numpad 0', which: '96', key: '0', code: 'Numpad0' }, { name: 'numpad 1', which: '97', key: '1', code: 'Numpad1' }, { name: 'numpad 2', which: '98', key: '2', code: 'Numpad2' }, { name: 'numpad 3', which: '99', key: '3', code: 'Numpad3' }, { name: 'numpad 4', which: '100', key: '4', code: 'Numpad4' }, { name: 'numpad 5', which: '101', key: '5', code: 'Numpad5' }, { name: 'numpad 6', which: '102', key: '6', code: 'Numpad6' }, { name: 'numpad 7', which: '103', key: '7', code: 'Numpad7' }, { name: 'numpad 8', which: '104', key: '8', code: 'Numpad8' }, { name: 'numpad 9', which: '105', key: '9', code: 'Numpad9' }, { name: 'multiply', which: '106', key: '*', code: 'NumpadMultiply' }, { name: 'add', which: '107', key: '+', code: 'NumpadAdd' }, { name: 'subtract', which: '109', key: '-', code: 'NumpadSubtract' }, { name: 'decimal point', which: '110', key: '.', code: 'NumpadDecimal' }, { name: 'divide', which: '111', key: '/', code: 'NumpadDivide' }, { name: 'f1', which: '112', key: 'F1', code: 'F1' }, { name: 'f2', which: '113', key: 'F2', code: 'F2' }, { name: 'f3', which: '114', key: 'F3', code: 'F3' }, { name: 'f4', which: '115', key: 'F4', code: 'F4' }, { name: 'f5', which: '116', key: 'F5', code: 'F5' }, { name: 'f6', which: '117', key: 'F6', code: 'F6' }, { name: 'f7', which: '118', key: 'F7', code: 'F7' }, { name: 'f8', which: '119', key: 'F8', code: 'F8' }, { name: 'f9', which: '120', key: 'F9', code: 'F9' }, { name: 'f10', which: '121', key: 'F10', code: 'F10' }, { name: 'f11', which: '122', key: 'F11', code: 'F11' }, { name: 'f12', which: '123', key: 'F12', code: 'F12' }, { name: 'num lock', which: '144', key: 'NumLock', code: 'NumLock' }, { name: 'scroll lock', which: '145', key: 'ScrollLock', code: 'ScrollLock' }, { name: 'audio volume mute', which: '173', key: 'AudioVolumeMute', code: '' }, { name: 'audio volume down', which: '174', key: 'AudioVolumeDown', code: '' }, { name: 'audio volume up', which: '175', key: 'AudioVolumeUp', code: '' }, { name: 'media player', which: '181', key: 'LaunchMediaPlayer', code: '' }, { name: 'launch application 1', which: '182', key: 'LaunchApplication1', code: '' }, { name: 'launch application 2', which: '183', key: 'LaunchApplication2', code: '' }, { name: 'semi-colon', which: '186', key: ';', code: 'Semicolon' }, { name: 'equal sign', which: '187', key: '=', code: 'Equal' }, { name: 'comma', which: '188', key: ',', code: 'Comma' }, { name: 'dash', which: '189', key: '-', code: 'Minus' }, { name: 'period', which: '190', key: '.', code: 'Period' }, { name: 'forward slash', which: '191', key: '/', code: 'Slash' }, { name: 'Backquote/Grave accent', which: '192', key: '`', code: 'Backquote' }, { name: 'open bracket', which: '219', key: '[', code: 'BracketLeft' }, { name: 'back slash', which: '220', key: '\\', code: 'Backslash' }, { name: 'close bracket', which: '221', key: ']', code: 'BracketRight' }, { name: 'single quote', which: '222', key: "'", code: 'Quote' } ]; ================================================ FILE: lang/shadeup/engine/requirejs.js ================================================ /** vim: et:ts=4:sw=4:sts=4 * @license RequireJS 2.3.6 Copyright jQuery Foundation and other contributors. * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE */ //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, setTimeout) { var req, s, head, baseElement, dataMain, src, interactiveScript, currentlyAddingScript, mainScript, subPath, version = '2.3.6', commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/gm, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, currDirRegExp = /^\.\//, op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty, 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; //Could match something like ')//comment', do not lose the prefix to comment. function commentReplace(match, singlePrefix) { return singlePrefix || ''; } function isFunction(it) { return ostring.call(it) === '[object Function]'; } function isArray(it) { return ostring.call(it) === '[object Array]'; } /** * 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; } } } } /** * 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]; } /** * 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; } } } } /** * 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} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttps://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; /** * 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; } } } } /** * 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. * * @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 (isNormalized) { normalizedName = name; } else 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); } } } /** * 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. */ 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) { var resLoadMaps = []; each(this.depMaps, function (depMap) { resLoadMaps.push(depMap.normalizedMap || depMap); }); req.onResourceLoad(context, this.map, resLoadMaps); } } //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, true); on( normalizedMap, 'defined', bind(this, function (value) { this.map.normalizedMap = normalizedMap; 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 * @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, /** * 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 += '/'; } } // Convert old style urlArgs string to a function. if (typeof cfg.urlArgs === 'string') { var urlArgs = cfg.urlArgs; cfg.urlArgs = function (id, url) { return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; }; } //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; }, /** * 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. */ 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(); }, /** * 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\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js'); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs && !/^blob\:/.test(url) ? url + config.urlArgs(moduleName, url) : 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. * * @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); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { var parents = []; eachProp(registry, function (value, key) { if (key.indexOf('_@r') !== 0) { each(value.depMaps, function (depMap) { if (depMap.id === data.id) { parents.push(key); return true; } }); } }); return onError( makeError( 'scripterror', 'Script error for "' + data.id + (parents.length ? '", needed by: ' + parents.join(', ') : '"'), 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. */ 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); 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/requirejs/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/requirejs/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; //Calling onNodeCreated after all properties on the node have been //set, but before it is placed in the DOM. if (config.onNodeCreated) { config.onNodeCreated(node, config, moduleName, 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 is 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. // Post a task to the event loop to work around a bug in WebKit // where the worker gets garbage-collected after calling // importScripts(): https://webkit.org/b/153317 setTimeout(function () {}, 0); 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, //but only do so if the data-main value is not a loader plugin //module ID. if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { //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, commentReplace) .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); })({}, typeof setTimeout === 'undefined' ? undefined : setTimeout); export { define, require, requirejs }; ================================================ FILE: lang/shadeup/engine/setZero.ts ================================================ // Only add setZeroTimeout to the window object, and hide everything // else in a closure. (function () { var timeouts = []; var messageName = 'zero-timeout-message'; // Like setTimeout, but only takes a function argument. There's // no time argument (always zero) and no arguments (you have to // use a closure). function setZeroTimeout(fn) { timeouts.push(fn); window.postMessage(messageName, '*'); } function handleMessage(event) { if (event.source == window && event.data == messageName) { event.stopPropagation(); if (timeouts.length > 0) { var fn = timeouts.shift(); fn(); } } } window.addEventListener('message', handleMessage, true); // Add the one thing we want added to the window object. window.setZeroTimeout = setZeroTimeout; })(); export {}; declare global { interface Window { setZeroTimeout(fn: () => void): void; } } ================================================ FILE: lang/shadeup/engine/shader.ts ================================================ import type { IndexMapping } from '../../../../shadeup-frontend/lib/generator/root'; import { UniformValue, type GenericShader, type GraphicsAdapter, type ShaderCodeMapping, type ShaderType, type UniformPayload, type ShaderParamsMapping, type ShaderBindingOptions } from './adapters/adapter'; import { translateIdentifier } from './util'; import { parse_type, getGl } from './util'; const simpleHash = (str: string) => { let hash = 0; for (let i = 0; i < str.length; i++) { const char = str.charCodeAt(i); hash = (hash << 5) - hash + char; hash &= hash; // Convert to 32bit integer } return new Uint32Array([hash])[0].toString(36); }; export class ShadeupShaderInstance { parent: ShadeupShaderSource; bindings: any; key: string; version: number; constructor(parentSource: ShadeupShaderSource, bindings: any, key: string) { this.parent = parentSource; this.bindings = bindings; this.key = key; this.version = 0; } getKey() { return `${this.key}_${this.version}`; } get( adapter: GraphicsAdapter, type: ShaderType, config?: ShaderBindingOptions ): GenericShader | null { let shade = adapter.getOrCreateShader(this, type, config); shade.uniqueSourceKey = this.getKey(); return shade; } bindUniforms(to: UniformPayload) { for (let k of Object.keys(this.parent.params.webgl)) { let paramType = this.parent.params.webgl[k]; let val = this.bindings[k]; let uniVal = new UniformValue(paramType, val); let uniformName = translateIdentifier(k); to.uniforms.set(uniformName, uniVal); } } } export class ShadeupShaderSource { code: ShaderCodeMapping; params: ShaderParamsMapping; types: { [key: string]: any }; arraySizes: { [key: string]: any }; indexMapping: IndexMapping; key: string; constructor(params: ShaderParamsMapping, code: ShaderCodeMapping, indexMapping: IndexMapping) { this.code = code; this.params = params; this.indexMapping = indexMapping; this.types = {}; this.arraySizes = {}; this.key = simpleHash(JSON.stringify(code)); } instance(bindings: any) { return new ShadeupShaderInstance(this, bindings, this.key); } } ================================================ FILE: lang/shadeup/engine/ui/components/Button.svelte ================================================
================================================ FILE: lang/shadeup/engine/ui/components/Checkbox.svelte ================================================
{ setValue(e.target.checked); value = e.target.checked; }} />
================================================ FILE: lang/shadeup/engine/ui/components/Combo.svelte ================================================
================================================ FILE: lang/shadeup/engine/ui/components/FloatingPanel.svelte ================================================ { isFullscreen = window.innerHeight >= screen.height; }} /> {@html styleStr} {#if children.length > 0}
{#each children as child}
{/each}
{#if isFullscreen} {:else} {/if}
{/if} ================================================ FILE: lang/shadeup/engine/ui/components/Group.svelte ================================================
{#each children as child, i}
{/each}
================================================ FILE: lang/shadeup/engine/ui/components/Host.svelte ================================================
{#each children as child} {/each}
================================================ FILE: lang/shadeup/engine/ui/components/Label.svelte ================================================
{value}
================================================ FILE: lang/shadeup/engine/ui/components/Slider.svelte ================================================ (dragging = false)} on:mousemove={handleMove} />
{ dragging = true; handleMove(event); }} class="track w-full h-4 relative flex items-center" >
{ setValue(parseFloat(e.target.value)); value = parseFloat(e.target.value); }} /> { setValue(parseFloat(e.target.value)); value = parseFloat(e.target.value); }} />
================================================ FILE: lang/shadeup/engine/ui/components/Text.svelte ================================================
{ setValue(e.target.value); value = e.target.value; }} />
================================================ FILE: lang/shadeup/engine/ui/components/host.scss ================================================ @tailwind base; @tailwind components; @tailwind utilities; @layer base { html { @apply text-white; } } .floating-panel { > .control-button:first-child, > .control-combo:first-child, > .control-input:first-child, > .control-label:first-child, > .control-select:first-child, > .control-text:first-child { @apply mt-2; } > .control-button:last-child, > .control-combo:last-child, > .control-input:last-child, > .control-label:last-child, > .control-select:last-child, > .control-text:last-child { @apply mb-1; } } ================================================ FILE: lang/shadeup/engine/ui/puck.ts ================================================ import type { SvelteComponent } from 'svelte'; import Slider from './components/Slider.svelte'; import Combo from './components/Combo.svelte'; import Label from './components/Label.svelte'; import Host from './components/Host.svelte'; import Group from './components/Group.svelte'; import Checkbox from './components/Checkbox.svelte'; import Button from './components/Button.svelte'; import Text from './components/Text.svelte'; import FloatingPanel from './components/FloatingPanel.svelte'; export type UIChild = { name: string; type: typeof SvelteComponent; value: any; options: object; children?: UIChild[]; setValue: (v: any) => void; }; const ENABLE_INERTIA = true; export function initPuck(canvas: HTMLCanvasElement) { let uiContainer = document.querySelector('.ui-container'); let puckDown = false; let puckId = ''; let pucks = {}; function blankUISink() { return { knob: new Map(), knobCounter: 0, button: new Map(), buttonCounter: 0, switch: new Map(), switchCounter: 0, slider: new Map(), sliderCounter: 0, puck: new Map(), puckCounter: 0 }; } let uiSink = blankUISink(); function copyUISink(s) { return { ...s, knob: new Map(s.knob), button: new Map(s.button), switch: new Map(s.switch), slider: new Map(s.slider), puck: new Map(s.puck) }; } let uiSinkLastFrame = blankUISink(); window.addEventListener('mousedown', (e: MouseEvent) => { if (e.target.closest('.puck')) { let p = e.target.closest('.puck'); p.dataset.down = true; let mp = getPosRelativeToCanvas([e.clientX, e.clientY]); let rect = p.getBoundingClientRect(); let pmp = getPosRelativeToCanvas([rect.left + rect.width / 2, rect.top + rect.height / 2]); p.dataset.offsetX = pmp[0] - mp[0]; p.dataset.offsetY = pmp[1] - mp[1]; puckId = p.dataset.id; puckDown = true; lastPuckPos = [...pmp]; updateDocumentCursor(); } }); function updateDocumentCursor() { if (puckDown) { document.body.style.cursor = 'grabbing'; } else { document.body.style.cursor = 'default'; } } window.addEventListener('mouseup', (e) => { puckDown = false; updateDocumentCursor(); for (let el of [...document.querySelectorAll('.puck')]) { let p = el as HTMLElement; if (p.dataset.down == 'true') { // let velocityX = parseInt(p.dataset.velocityX ?? '0'); // let velocityY = parseInt(p.dataset.velocityY ?? '0'); // let vectorLength = Math.sqrt(velocityX * velocityX + velocityY * velocityY); // let angle = Math.atan2(velocityY, velocityX); // p.dataset.velocity = vectorLength.toString(); // p.dataset.angle = angle.toString(); // console.log(p.dataset.velocity, angle * (180 / Math.PI)); p.dataset.down = 'false'; } } }); function getPuckPos(puck: HTMLElement) { let rect = canvas.getBoundingClientRect(); let x = puck.offsetLeft - rect.left; let y = puck.offsetTop - rect.top; return [ [x, y], [puck.offsetLeft, puck.offsetTop] ]; } function getPosRelativeToCanvas(pos: [number, number]) { let rect = canvas.getBoundingClientRect(); return [ ((pos[0] - rect.left) / rect.width) * canvas.width, ((pos[1] - rect.top) / rect.height) * canvas.height ]; } const host = new Host({ target: document.body, props: { children: [] } }); let queuedCommands = []; let realSetControls: any = null; host.$on('init', (e) => {}); let lastPuckPos = [0, 0]; window.addEventListener('mousemove', (e) => { if (!puckDown) return; let puck = document.querySelector(`.puck[data-id="${puckId}"]`) as HTMLElement; if (!puck) return; let [x, y] = getPosRelativeToCanvas([e.clientX, e.clientY]); // puck.dataset.velocityX = ( // (parseInt(puck.dataset.velocityX ?? '0') || 0) + // (x - lastPuckPos[0]) * 2 // ).toString(); // puck.dataset.velocityY = ( // (parseInt(puck.dataset.velocityY ?? '0') || 0) + // (y - lastPuckPos[1]) * 2 // ).toString(); let velocityX = x - lastPuckPos[0]; let velocityY = y - lastPuckPos[1]; let vectorLength = Math.sqrt(velocityX * velocityX + velocityY * velocityY); let angle = Math.atan2(velocityY, velocityX); let oldVel = parseFloat(puck.dataset.velocity ?? '0'); puck.dataset.velocity = (oldVel + vectorLength).toString(); let oldAngle = parseFloat(puck.dataset.angle ?? '0'); let oldDirVelX = oldVel * Math.cos(oldAngle); let oldDirVelY = oldVel * Math.sin(oldAngle); let newDirVelX = vectorLength * Math.cos(angle); let newDirVelY = vectorLength * Math.sin(angle); puck.dataset.angle = Math.atan2(oldDirVelY + newDirVelY, oldDirVelX + newDirVelX).toString(); lastPuckPos = [x, y]; puck.dataset.oldX = puck.offsetLeft.toString(); puck.dataset.oldY = puck.offsetTop.toString(); x += parseInt(puck.dataset.offsetX ?? '0'); y += parseInt(puck.dataset.offsetY ?? '0'); uiSinkLastFrame.puck.set(puckId, { vec: [x, y] }); }); setInterval(() => { for (let el of [...document.querySelectorAll('.puck')]) { let p: HTMLElement = el as HTMLElement; let maxSpeed = 105; let restitution = 0.75; // p.dataset.velocityX = Math.max( // Math.min(parseInt(p.dataset.velocityX ?? '0') * restitution, maxSpeed), // -maxSpeed // ).toString(); // p.dataset.velocityY = Math.max( // Math.min(parseInt(p.dataset.velocityY ?? '0') * restitution, maxSpeed), // -maxSpeed // ).toString(); p.dataset.velocity = Math.max( Math.min(parseFloat(p.dataset.velocity ?? '0') * restitution, maxSpeed), -maxSpeed ).toString(); let angle = parseFloat(p.dataset.angle ?? '0'); let velocity = parseFloat(p.dataset.velocity ?? '0') / 5; if (p.dataset.down == 'true') continue; if (ENABLE_INERTIA) { if (uiSink.puck.has(p.dataset.id) && velocity > 1) { let { vec } = uiSink.puck.get(p.dataset.id); uiSinkLastFrame.puck.set(p.dataset.id, { vec: [vec[0] + Math.cos(angle) * velocity, vec[1] + Math.sin(angle) * velocity] }); } } } }, 1000 / 60); const SIMPLE_MATH = { clamp(a, min, max) { return Math.min(Math.max(a, min), max); }, clamp2(a, min, max) { return [this.clamp(a[0], min[0], max[0]), this.clamp(a[1], min[1], max[1])]; } }; function _SHADEUP_UI_PUCK(vec, radius = 10, invisible = false) { let id = uiSink.puckCounter++; uiSink.puck.set(id.toString(), { vec: [...vec] }); addPuck(id.toString(), vec, radius, invisible); if (uiSinkLastFrame.puck.has(id.toString())) { return SIMPLE_MATH.clamp2( uiSinkLastFrame.puck.get(id.toString()).vec, [0, 0], [canvas.width, canvas.height] ); } else { return [...vec]; } } function addPuck(name, puck, radius = 10, invisible = false) { puck = [puck[0] / canvas.width, puck[1] / canvas.height]; if (pucks[name]) { pucks[name].div.style.left = `calc(${puck[0] * 100}% - ${radius}px)`; pucks[name].div.style.top = `calc(${puck[1] * 100}% - ${radius}px)`; pucks[name].div.style.opacity = invisible ? '0' : '1'; pucks[name].div.style.width = `${radius * 2}px`; pucks[name].div.style.height = `${radius * 2}px`; return; } let div = document.createElement('div'); div.className = 'puck'; div.dataset.id = name; div.innerHTML = ``; div.style.width = `${radius * 2}px`; div.style.height = `${radius * 2}px`; div.style.opacity = invisible ? '0' : '1'; uiContainer.appendChild(div); pucks[name] = { div, puck }; } let hostChildren: UIChild[] = []; let childrenCrumbs: UIChild[] = []; let rootChild: UIChild; let preFrameHandlers: (() => void)[] = []; let postFrameHandlers: (() => void)[] = []; function createImmediateModeUIElement( type: string, component: typeof SvelteComponent, canHaveChildren = false ) { let els: Map = new Map(); function blankUISink() { return { map: new Map(), counter: 0 }; } let uiSink = blankUISink(); let uiSinkLastFrame = blankUISink(); preFrameHandlers.push(() => { uiSink = blankUISink(); }); postFrameHandlers.push(() => { // Clean up unused controls for (let name of els.keys()) { if (!uiSink.map.has(name)) { // els.get(name)!.$destroy(); // els.delete(name); } } uiSinkLastFrame = blankUISink(); }); function invoke(value: any, options: any = {}) { let id = uiSink.counter++; uiSink.map.set(id.toString(), { value: value, options: options }); addControl( id.toString(), { value: value, options: options }, canHaveChildren ); if (uiSinkLastFrame.map.has(id.toString())) { return uiSinkLastFrame.map.get(id.toString()).value; } else { return value; } } function addControl(name: string, v: { value: any; options: object }, canHaveChildren = false) { if (els.has(name)) { els.get(name)!.$set({ value: v.value, ...v.options }); return; } function setValue(v: any) { uiSinkLastFrame.map.set(name, { value: v }); } // let comp = new component({ // target: uiContainer!, // props: { // value: v.value, // ...v.options, // setValue // } // }); rootChild.children?.push({ type: component, value: v.value, options: v.options, children: canHaveChildren ? [] : undefined, setValue, name: type }); if (canHaveChildren) { childrenCrumbs.push(rootChild); rootChild = rootChild.children![rootChild.children!.length - 1]; } // els.set(name, comp); } return invoke; } let slider = createImmediateModeUIElement('slider', Slider); let label = createImmediateModeUIElement('label', Label); let group = createImmediateModeUIElement('group', Group, true); let checkbox = createImmediateModeUIElement('checkbox', Checkbox); let textbox = createImmediateModeUIElement('textbox', Text); let combo = createImmediateModeUIElement('combo', Combo); let button = createImmediateModeUIElement('button', Button); function preFrame() { hostChildren = []; rootChild = { type: FloatingPanel, value: null, children: [], options: {}, setValue: () => {}, name: 'root' }; hostChildren.push(rootChild); childrenCrumbs = [rootChild]; for (let handler of preFrameHandlers) { handler(); } uiSink = blankUISink(); } return { frame() { // Clean up unused pucks for (let name in pucks) { if (!uiSink.puck.has(name)) { pucks[name].div.remove(); delete pucks[name]; } } for (let post of postFrameHandlers) { post(); } uiSinkLastFrame = blankUISink(); host.$set({ children: hostChildren }); }, preFrame, puck: _SHADEUP_UI_PUCK, slider, controls: { label, group, checkbox, textbox, combo, button, pop() { childrenCrumbs.pop(); rootChild = childrenCrumbs[childrenCrumbs.length - 1]; } } }; } ================================================ FILE: lang/shadeup/engine/ui/ui.ts ================================================ import { initPuck } from './puck'; import Host from './components/Host.svelte'; export function initUI(canvas: HTMLCanvasElement) { let { frame, puck, preFrame, slider, controls } = initPuck(canvas); return { frame() { frame(); }, preFrame() { preFrame(); }, puck, slider, controls: controls // controls: host }; } ================================================ FILE: lang/shadeup/engine/util.ts ================================================ type ExpandedType = { name: string; generics: ExpandedType[] }; export function parse_type(type: string): ExpandedType { let name = ''; let generics = []; let generic = ''; let depth = 0; for (let i = 0; i < type.length; i++) { let c = type[i]; if (c == '<') { depth += 1; if (depth == 1) { continue; } } else if (c == '>') { depth -= 1; if (depth == 0) { generics.push(parse_type(generic)); generic = ''; continue; } } else if (c == ',' && depth == 1) { generics.push(parse_type(generic)); generic = ''; continue; } if (depth == 0) { name += c; } else { generic += c; } } return { name: name, generics: generics }; } export function stringify_type(type: ExpandedType): string { return `${type.name}${ type.generics.length > 0 ? '<' + type.generics.map(stringify_type).join(',') + '>' : '' }`; } export function translateNumericToGLSL(type: string): string | null { if (type == 'float2x2') { return 'Matrix2f'; } else if (type == 'float3x3') { return 'Matrix3f'; } else if (type == 'float4x4') { return 'Matrix4f'; } let matches = type.match(/^([A-Za-z]+)(\d)?$/); if (!matches) { return null; } let base = matches[1]; let size = matches[2] ? parseInt(matches[2]) : 1; let type_name = ''; switch (base) { case 'float': type_name = 'f'; break; case 'int': type_name = 'i'; break; case 'uint': type_name = 'i'; break; case 'bool': type_name = 'i'; break; default: return null; } return `${size}${type_name}`; } export function translate_type_for_uniform(type: ExpandedType): string | null { if (type.name == 'array') { let inner = translate_type_for_uniform(type.generics[0]); return `${inner}[]`; } else { return translateNumericToGLSL(type.name); } } export function translateIdentifier(str: string) { return str.replace(/\_\_\_/g, '_ii_').replace(/\_\_/g, '_i_'); } export function getGl(): WebGL2RenderingContext { return (window as any).gl; } ================================================ FILE: lang/shadeup/engine/virtual-webgl2.js ================================================ /* * Copyright 2018, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * Neither the name of Gregg Tavares. nor the names of his * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* eslint-env browser */ (function () { const settings = { disableWebGL1: true, compositorCreator() {} }; const canvasToVirtualContextMap = new Map(); const extensionInfo = {}; const extensionSaveRestoreHelpersArray = []; const extensionSaveRestoreHelpers = {}; let currentVirtualContext = null; let someContextsNeedRendering; const sharedWebGLContext = document.createElement('canvas').getContext('webgl2'); const numAttribs = sharedWebGLContext.getParameter(sharedWebGLContext.MAX_VERTEX_ATTRIBS); const numTextureUnits = sharedWebGLContext.getParameter( sharedWebGLContext.MAX_COMBINED_TEXTURE_IMAGE_UNITS ); const numUniformBufferBindings = sharedWebGLContext.getParameter( sharedWebGLContext.MAX_UNIFORM_BUFFER_BINDINGS ); const baseState = makeDefaultState(sharedWebGLContext, 300, 150); const INT = 0x1404; const UNSIGNED_INT = 0x1405; const FLOAT = 0x1406; const vs = ` attribute vec4 position; varying vec2 v_texcoord; void main() { gl_Position = position; v_texcoord = position.xy * .5 + .5; } `; const fs = ` precision mediump float; varying vec2 v_texcoord; uniform sampler2D u_tex; void main() { gl_FragColor = texture2D(u_tex, v_texcoord); } `; const fs2 = ` precision mediump float; varying vec2 v_texcoord; uniform sampler2D u_tex; void main() { gl_FragColor = texture2D(u_tex, v_texcoord); gl_FragColor.rgb *= gl_FragColor.a; } `; const premultiplyAlphaTrueProgram = createProgram(sharedWebGLContext, [vs, fs]); const premultiplyAlphaFalseProgram = createProgram(sharedWebGLContext, [vs, fs2]); { const gl = sharedWebGLContext; const positionLoc = 0; // hard coded in createProgram const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]), gl.STATIC_DRAW ); gl.enableVertexAttribArray(positionLoc); gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0); } saveAllState(baseState); HTMLCanvasElement.prototype.getContext = (function (origFn) { return function (type, contextAttributes) { if (type === 'webgl' || type === 'experimental-webgl') { return createOrGetVirtualWebGLContext(this, type, contextAttributes); } else if (type === 'webgl2') { return createOrGetVirtualWebGLContext(this, type, contextAttributes); } return origFn.call(this, type, contextAttributes); }; })(HTMLCanvasElement.prototype.getContext); function valueOrDefault(value, defaultValue) { return value === undefined ? defaultValue : value; } function errorDisposedContext(fnName) { return function () { throw new Error(`tried to call ${fnName} on disposed context`); }; } class DefaultCompositor { constructor(canvas) { this._ctx = canvas.getContext('2d'); } composite(gl, texture, canvas, contextAttributes) { // note: not entirely sure what to do here. We need this canvas to be at least as large // as the canvas we're drawing to. Resizing a canvas is slow so I think just making // sure we never get smaller than the largest canvas. At the moment though I'm too lazy // to make it smaller. const ctx = this._ctx; const width = canvas.width; const height = canvas.height; const maxWidth = Math.max(gl.canvas.width, width); const maxHeight = Math.max(gl.canvas.height, height); if (gl.canvas.width !== maxWidth || gl.canvas.height !== maxHeight) { gl.canvas.width = maxWidth; gl.canvas.height = maxHeight; } gl.viewport(0, 0, width, height); gl.useProgram( contextAttributes.premultipliedAlpha ? premultiplyAlphaTrueProgram : premultiplyAlphaFalseProgram ); // draw the drawingbuffer's texture to the offscreen canvas gl.bindTexture(gl.TEXTURE_2D, texture); gl.drawArrays(gl.TRIANGLES, 0, 6); // copy it to target canvas ctx.globalCompositeOperation = 'copy'; ctx.drawImage( gl.canvas, 0, maxHeight - height, width, height, // src rect 0, 0, width, height ); // dest rect } dispose() {} } function virtualGLConstruct(canvas, contextAttributes = {}, compositor, disposeHelper) { const gl = sharedWebGLContext; this._canvas = canvas; // Should use Symbols or something to hide these variables from the outside. this._compositor = compositor; this._disposeHelper = disposeHelper; this._extensions = {}; // based on context attributes and canvas.width, canvas.height // create a texture and framebuffer this._drawingbufferTexture = gl.createTexture(); this._drawingbufferFramebuffer = gl.createFramebuffer(); this._contextAttributes = { alpha: valueOrDefault(contextAttributes.alpha, true), antialias: false, depth: valueOrDefault(contextAttributes.depth, true), failIfMajorPerformanceCaveat: false, premultipliedAlpha: valueOrDefault(contextAttributes.premultipliedAlpha, true), stencil: valueOrDefault(contextAttributes.stencil, false) }; this._preserveDrawingbuffer = valueOrDefault(contextAttributes.preserveDrawingBuffer, false); const oldTexture = gl.getParameter(gl.TEXTURE_BINDING_2D); const oldFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); gl.bindTexture(gl.TEXTURE_2D, this._drawingbufferTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // this._drawingbufferTexture.id = canvas.id; // this._drawingbufferFramebuffer.id = canvas.id; gl.bindFramebuffer(gl.FRAMEBUFFER, this._drawingbufferFramebuffer); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._drawingbufferTexture, 0 ); if (this._contextAttributes.depth) { const oldRenderbuffer = gl.getParameter(gl.RENDERBUFFER_BINDING); this._depthRenderbuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderbuffer); const attachmentPoint = this._contextAttributes.stencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; gl.framebufferRenderbuffer( gl.FRAMEBUFFER, attachmentPoint, gl.RENDERBUFFER, this._depthRenderbuffer ); gl.bindRenderbuffer(gl.RENDERBUFFER, oldRenderbuffer); } gl.bindTexture(gl.TEXTURE_2D, oldTexture); gl.bindFramebuffer(gl.FRAMEBUFFER, oldFramebuffer); // remember all WebGL state (default bindings, default texture units, // default attributes and/or vertex shade object, default program, // default blend, stencil, zBuffer, culling, viewport etc... state this._state = makeDefaultState(gl, canvas.width, canvas.height); this._state.readFramebuffer = this._drawingbufferFramebuffer; this._state.drawFramebuffer = this._drawingbufferFramebuffer; this._state.readBuffer = gl.COLOR_ATTACHMENT0; this._state.vertexArray = gl.createVertexArray(); this._defaultVertexArray = this._state.vertexArray; } function virtualGLDispose() { this._disposeHelper(); const gl = sharedWebGLContext; gl.deleteFramebuffer(this._drawingbufferFramebuffer); gl.deleteTexture(this._drawingbufferTexture); if (this._depthRenderbuffer) { gl.deleteRenderbuffer(this._depthRenderbuffer); } if (this._compositor.dispose) { this._compositor.dispose(); } for (const [key, value] of Object.entries(this)) { if (typeof value === 'function') { this[key] = errorDisposedContext(key); } } for (const [key, value] of Object.entries(this.prototype)) { if (typeof value === 'function') { this[key] = errorDisposedContext(key); } } } function virtualGLComposite(gl) { this._compositor.composite( gl, this._drawingbufferTexture, this.canvas, this._contextAttributes ); if (!this._preserveDrawingbuffer) { this._needClear = true; } } // Base exists so VirtualWebGLContext has a base class we can replace // because otherwise it's base is Object which we can't replace. class Base {} class VirtualWebGLContext extends Base { constructor(canvas, contextAttributes = {}, compositor, disposeHelper) { super(); this.dispose = virtualGLDispose; this.composite = virtualGLComposite; virtualGLConstruct.call(this, canvas, contextAttributes, compositor, disposeHelper); } get canvas() { return this._canvas; } get drawingBufferWidth() { return this.canvas.width; } get drawingBufferHeight() { return this.canvas.height; } } class Base2 {} class VirtualWebGL2Context extends Base2 { constructor(canvas, contextAttributes = {}, compositor, disposeHelper) { super(); this.dispose = virtualGLDispose; this.composite = virtualGLComposite; virtualGLConstruct.call(this, canvas, contextAttributes, compositor, disposeHelper); } get canvas() { return this._canvas; } get drawingBufferWidth() { return this.canvas.width; } get drawingBufferHeight() { return this.canvas.height; } } // Replace the prototype with WebGL2RenderingContext so that someCtx instanceof WebGL2RenderingContext returns true Object.setPrototypeOf( Object.getPrototypeOf(VirtualWebGLContext.prototype), WebGLRenderingContext.prototype ); Object.setPrototypeOf( Object.getPrototypeOf(VirtualWebGL2Context.prototype), WebGL2RenderingContext.prototype ); function makeDefaultState(gl, width, height) { const vao = gl.createVertexArray(); gl.bindVertexArray(vao); const state = { arrayBuffer: null, renderbuffer: null, drawFramebuffer: null, readFramebuffer: null, copyReadBuffer: null, copyWriteBuffer: null, pixelPackBuffer: null, pixelUnpackBuffer: null, transformFeedbackBuffer: null, uniformBuffer: null, readBuffer: gl.BACK, enable: new Map([ [gl.BLEND, false], [gl.CULL_FACE, false], [gl.DEPTH_TEST, false], [gl.DITHER, false], [gl.POLYGON_OFFSET_FILL, false], [gl.RASTERIZER_DISCARD, false], [gl.SAMPLE_ALPHA_TO_COVERAGE, false], [gl.SAMPLE_COVERAGE, false], [gl.SCISSOR_TEST, false], [gl.STENCIL_TEST, false] ]), // This is a place the spec gets wrong! This data should have been part of a VertexArray attribValues: new Array(numAttribs).fill(0).map(() => { return { type: gl.FLOAT, value: [0, 0, 0, 1] }; }), vertexArray: vao, activeTexture: gl.TEXTURE0, transformFeedback: null, pack: new Map([ [gl.PACK_ALIGNMENT, 4], [gl.UNPACK_ALIGNMENT, 4], [gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.BROWSER_DEFAULT_WEBGL], [gl.UNPACK_FLIP_Y_WEBGL, 0], [gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0], [gl.UNPACK_ROW_LENGTH, 0], [gl.UNPACK_SKIP_ROWS, 0], [gl.UNPACK_SKIP_PIXELS, 0], [gl.UNPACK_SKIP_IMAGES, 0], [gl.UNPACK_IMAGE_HEIGHT, 0], [gl.PACK_ROW_LENGTH, 0], [gl.PACK_SKIP_ROWS, 0], [gl.PACK_SKIP_PIXELS, 0] ]), currentProgram: null, viewport: [0, 0, width, height], scissor: [0, 0, width, height], blendSrcRgb: gl.ONE, blendDstRgb: gl.ZERO, blendSrcAlpha: gl.ONE, blendDstAlpha: gl.ZERO, blendEquationRgb: gl.FUNC_ADD, blendEquationAlpha: gl.FUNC_ADD, blendColor: [0, 0, 0, 0], clearColor: [0, 0, 0, 0], colorMask: [true, true, true, true], cullFaceMode: gl.BACK, clearDepth: 1, depthFunc: gl.LESS, depthRange: [0, 1], depthMask: true, frontFace: gl.CCW, generateMipmapHint: gl.DONT_CARE, lineWidth: 1, polygonOffsetFactor: 0, polygonOffsetUnits: 0, sampleCoverageValue: 1, sampleCoverageUnits: false, stencilFront: { fail: gl.KEEP, func: gl.ALWAYS, depthFail: gl.KEEP, depthPass: gl.KEEP, ref: 0, valueMask: 0xffffffff, writeMask: 0xffffffff }, stencilBack: { fail: gl.KEEP, func: gl.ALWAYS, depthFail: gl.KEEP, depthPass: gl.KEEP, ref: 0, valueMask: 0xffffffff, writeMask: 0xffffffff }, stencilClearValue: 0, textureUnits: new Array(numTextureUnits).fill(0).map(() => { return { texture2D: null, textureCubemap: null, texture2DArray: null, texture3D: null, sampler: null }; }), uniformBufferBindings: new Array(numUniformBufferBindings).fill(0).map(() => { return { buffer: null, size: 0, start: 0 }; }) }; return state; } function isFramebufferBindingNull(vCtx) { return vCtx._state.drawFramebuffer === vCtx._drawingbufferFramebuffer; } function createWrapper(origFn /*, name*/) { // lots of optimization could happen here depending on specific functions return function (...args) { makeCurrentContext(this); resizeCanvasIfChanged(this); return origFn.call(sharedWebGLContext, ...args); }; } function clearIfNeeded(vCtx) { if (vCtx._needClear) { vCtx._needClear = false; const gl = sharedWebGLContext; gl.bindFramebuffer(gl.FRAMEBUFFER, vCtx._drawingbufferFramebuffer); gl.disable(gl.SCISSOR_TEST); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); enableDisable(gl, gl.SCISSOR_TEST, vCtx._state.scissorTest); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, vCtx._state.drawFramebuffer); } } function beforeDraw(vCtx) { makeCurrentContext(vCtx); resizeCanvasIfChanged(vCtx); clearIfNeeded(vCtx); } function afterDraw(vCtx) { if (isFramebufferBindingNull(vCtx)) { vCtx._needComposite = true; if (!someContextsNeedRendering) { someContextsNeedRendering = true; setTimeout(renderAllDirtyVirtualCanvases, 0); } } } function createDrawWrapper(origFn) { return function (...args) { // a rendering function was called so we need to copy are drawingBuffer // to the canvas for this context after the current event. beforeDraw(this); const result = origFn.call(sharedWebGLContext, ...args); afterDraw(this); return result; }; } function createStateArgsSaverFn(fnName) { return function (...args) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl[fnName](...args); const v = this._state[fnName]; for (let i = 0; i < args.length; ++i) { v[i] = args[i]; } }; } function createSaveStateNamedArgs(fnName, argsToStateProps) { return function (...args) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl[fnName](...args); for (let i = 0; i < argsToStateProps.length; ++i) { this._state[argsToStateProps[i]] = args[i]; } }; } function createVertexAttribWrapper(origFn, fn) { return function (loc, ...args) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; origFn.call(gl, loc, ...args); const [type, value] = fn(args); this._state.attribValues[loc] = { type, value }; }; } function saveStencilMaskImpl(st, mask) { st.writeMask = mask; } function saveStencilMask(state, face, mask) { if (face === sharedWebGLContext.FRONT || face === sharedWebGLContext.FRONT_AND_BACK) { saveStencilMaskImpl(state.stencilFront, mask); } if (face === sharedWebGLContext.BACK || face === sharedWebGLContext.FRONT_AND_BACK) { saveStencilMaskImpl(state.stencilBack, mask); } } function saveStencilFuncImpl(st, func, ref, mask) { st.func = func; st.ref = ref; st.valueMask = mask; } function saveStencilFunc(state, face, func, ref, mask) { if (face === sharedWebGLContext.FRONT || face === sharedWebGLContext.FRONT_AND_BACK) { saveStencilFuncImpl(state.stencilFront, func, ref, mask); } if (face === sharedWebGLContext.BACK || face === sharedWebGLContext.FRONT_AND_BACK) { saveStencilFuncImpl(state.stencilBack, func, ref, mask); } } function saveStencilOpImpl(st, fail, zfail, zpass) { st.fail = fail; st.depthFail = zfail; st.depthPass = zpass; } function saveStencilOp(state, face, fail, zfail, zpass) { if (face === sharedWebGLContext.FRONT || face === sharedWebGLContext.FRONT_AND_BACK) { saveStencilOpImpl(state.stencilFront, fail, zfail, zpass); } if (face === sharedWebGLContext.BACK || face === sharedWebGLContext.FRONT_AND_BACK) { saveStencilOpImpl(state.stencilBack, fail, zfail, zpass); } } const virtualFns = { getExtension(name) { // just like the real context each extension needs a virtual class because each use // of the extension might be modified (as in people adding properties to it) const existingExt = this._extensions[name]; if (existingExt) { return existingExt; } const ext = sharedWebGLContext.getExtension(name); if (!ext) { return null; } const wrapperInfo = extensionInfo[name] || {}; const wrapperFnMakerFn = wrapperInfo.wrapperFnMakerFn || (() => { console.log('trying to get extension:', name); }); const saveRestoreHelper = extensionSaveRestoreHelpers[name]; if (!saveRestoreHelper) { const saveRestoreMakerFn = wrapperInfo.saveRestoreMakerFn; if (saveRestoreMakerFn) { const saveRestore = saveRestoreMakerFn(ext); extensionSaveRestoreHelpers[name] = saveRestore; extensionSaveRestoreHelpersArray.push(saveRestore); } } const wrapper = { _context: this }; for (const key in ext) { let value = ext[key]; if (typeof value === 'function') { value = wrapperFnMakerFn(ext, value, name); } wrapper[key] = value; } return wrapper; }, activeTexture(unit) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.activeTexture(unit); this._state.activeTexture = unit; }, enable(pname) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.enable(pname); this._state.enable.set(pname, true); }, disable(pname) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.disable(pname); this._state.enable.set(pname, false); }, viewport: createStateArgsSaverFn('viewport'), scissor: createStateArgsSaverFn('scissor'), blendColor: createStateArgsSaverFn('blendColor'), clearColor: createStateArgsSaverFn('clearColor'), colorMask: createStateArgsSaverFn('colorMask'), depthRange: createStateArgsSaverFn('depthRange'), bindBuffer(target, buffer) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.bindBuffer(target, buffer); switch (gl.target) { case gl.ARRAY_BUFFER: this._state.arrayBuffer = buffer; break; case gl.COPY_READ_BUFFER: this._state.copyReadBuffer = buffer; break; case gl.COPY_WRITE_BUFFER: this._state.copyWriteBuffer = buffer; break; case gl.PIXEL_PACK_BUFFER: this._state.pixelPackBuffer = buffer; break; case gl.PIXEL_UNPACK_BUFFER: this._state.pixelUnpackBuffer = buffer; break; case gl.TRANSFORM_FEEDBACK_BUFFER: this._state.transformFeedbackBuffer = buffer; break; case gl.UNIFORM_BUFFER: this._state.uniformBuffer = buffer; } }, bindBufferBase(target, index, buffer) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.bindBufferBase(target, index, buffer); switch (target) { case gl.UNIFORM_BUFFER: { const ub = this._state.uniformBufferBindings[index]; ub.buffer = buffer; ub.size = 0; ub.start = 0; break; } default: break; } }, bindBufferRange(target, index, buffer, offset, size) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.bindBufferRange(target, index, buffer, offset, size); switch (target) { case gl.UNIFORM_BUFFER: { const ub = this._state.uniformBufferBindings[index]; ub.buffer = buffer; ub.size = size; ub.start = offset; break; } default: break; } }, bindTexture(target, texture) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.bindTexture(target, texture); const unit = this._state.textureUnits[this._state.activeTexture - gl.TEXTURE0]; switch (target) { case gl.TEXTURE_2D: unit.texture2D = texture; break; case gl.TEXTURE_CUBE_MAP: unit.textureCubemap = texture; break; case gl.TEXTURE_2D_ARRAY: unit.texture2DArray = texture; break; case gl.TEXTURE_3D: unit.texture3D = texture; break; } }, bindRenderbuffer(target, renderbuffer) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.bindRenderbuffer(target, renderbuffer); this._state.renderbuffer = renderbuffer; }, bindSampler(unit, sampler) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.bindSampler(unit, sampler); this._state.textureUnits[unit].sampler = sampler; }, bindVertexArray(va) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; if (va === null) { va = this._defaultVertexArray; } gl.bindVertexArray(va); this._state.vertexArray = va; }, getContextAttributes() { return this._contextAttributes; }, readPixels(...args) { makeCurrentContext(this); resizeCanvasIfChanged(this); clearIfNeeded(this); const gl = sharedWebGLContext; return gl.readPixels(...args); }, getParameter(pname) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; const value = gl.getParameter(pname); switch (pname) { case gl.FRAMEBUFFER_BINDING: if (value === this._drawingbufferFramebuffer) { return null; } break; case gl.DRAW_BUFFER0: if (isFramebufferBindingNull(this)) { if (value === gl.COLOR_ATTACHMENT0) { return gl.BACK; } } break; case gl.READ_BUFFER: if (isFramebufferBindingNull(this)) { if (value === gl.COLOR_ATTACHMENT0) { return gl.BACK; } } break; case gl.VERTEX_ARRAY_BINDING: if (value === this._defaultVertexArray) { return null; } break; } return value; }, blendFunc(sfactor, dfactor) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.blendFunc(sfactor, dfactor); this._state.blendSrcRgb = sfactor; this._state.blendSrcAlpha = sfactor; this._state.blendDstRgb = dfactor; this._state.blendDstAlpha = dfactor; }, blendEquation(mode) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.blendEquation(mode); this._state.blendEquationRgb = mode; this._state.blendEquationAlpha = mode; }, blendFuncSeparate: createSaveStateNamedArgs('blendFuncSeparate', [ 'blendSrcRgb', 'blendDstRgb', 'blendSrcAlpha', 'blendDstAlpha' ]), blendEquationSeparate: createSaveStateNamedArgs('blendEquationSeparate', [ 'blendEquationRgb', 'blendEquationAlpha' ]), cullFace: createSaveStateNamedArgs('cullFace', ['cullFaceMode']), clearDepth: createSaveStateNamedArgs('clearDepth', ['clearDepth']), depthFunc: createSaveStateNamedArgs('depthFunc', ['depthFunc']), depthMask: createSaveStateNamedArgs('depthMask', ['depthMask']), frontFace: createSaveStateNamedArgs('frontFace', ['frontFace']), lineWidth: createSaveStateNamedArgs('lineWidth', ['lineWidth']), polygonOffset: createSaveStateNamedArgs('polygonOffset', [ 'polygonOffsetFactor', 'polygonOffsetUnits' ]), sampleCoverage: createSaveStateNamedArgs('sampleCoverage', [ 'sampleCoverageValue', 'sampleCoverageUnits' ]), clearStencil: createSaveStateNamedArgs('clearStencil', ['clearStencilValue']), hint(pname, value) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.hint(pname, value); this._state.generateMipmapHint = value; }, bindFramebuffer(bindPoint, framebuffer) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; if (framebuffer === null) { // bind our drawingBuffer framebuffer = this._drawingbufferFramebuffer; } gl.bindFramebuffer(bindPoint, framebuffer); switch (bindPoint) { case gl.FRAMEBUFFER: this._state.readFramebuffer = framebuffer; this._state.drawFramebuffer = framebuffer; break; case gl.DRAW_FRAMEBUFFER: this._state.drawFramebuffer = framebuffer; break; case gl.READ_FRAMEBUFFER: this._state.readFramebuffer = framebuffer; break; } }, drawBuffers: (function () { const gl = sharedWebGLContext; const backBuffer = [gl.COLOR_ATTACHMENT0]; return function (drawingBuffers) { makeCurrentContext(this); resizeCanvasIfChanged(this); // if the virtual context is bound to canvas then fake it if (isFramebufferBindingNull(this)) { // this really isn't checking everything // for example if the user passed in array.length != 1 // then we are supposed to generate an error if (drawingBuffers[0] === gl.BACK) { drawingBuffers = backBuffer; } } gl.drawBuffers(drawingBuffers); }; })(), clear: createDrawWrapper(WebGL2RenderingContext.prototype.clear), drawArrays: createDrawWrapper(WebGL2RenderingContext.prototype.drawArrays), drawElements: createDrawWrapper(WebGL2RenderingContext.prototype.drawElements), drawArraysInstanced: createDrawWrapper(WebGL2RenderingContext.prototype.drawArraysInstanced), drawElementsInstanced: createDrawWrapper( WebGL2RenderingContext.prototype.drawElementsInstanced ), drawRangeElements: createDrawWrapper(WebGL2RenderingContext.prototype.drawRangeElements), useProgram(program) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.useProgram(program); this._state.currentProgram = program; }, bindTransformFeedback(target, tb) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.bindTransformFeedback(target, tb); this._state.transformFeedback = tb; }, readBuffer(src) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; if (src === gl.BACK) { src = gl.COLOR_ATTACHMENT0; } gl.readBuffer(src); this._state.readBuffer = src; }, stencilFunc(func, ref, mask) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.stencilFunc(func, ref, mask); saveStencilFunc(this._state, gl.FRONT_AND_BACK, func, ref, mask); }, stencilFuncSeparate(face, func, ref, mask) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.stencilFuncSeparate(face, func, ref, mask); saveStencilFunc(this._state, face, func, ref, mask); }, stencilMask(mask) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.stencilMask(mask); saveStencilMask(this._state, gl.FRONT_AND_BACK, mask); }, stencilMaskSeparate(face, mask) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.stencilMaskSeparate(face, mask); saveStencilMask(this._state, face, mask); }, stencilOp(fail, zfail, zpass) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.stencilOp(fail, zfail, zpass); saveStencilOp(this._state, gl.FRONT_AND_BACK, fail, zfail, zpass); }, stencilOpSeparate(face, fail, zfail, zpass) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; gl.stencilOpSeparate(face, fail, zfail, zpass); saveStencilOp(this._state, face, fail, zfail, zpass); }, vertexAttrib1f: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1f, ([x]) => [FLOAT, [x, 0, 0, 1]] ), vertexAttrib2f: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1f, ([x, y]) => [FLOAT, [x, y, 0, 1]] ), vertexAttrib3f: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1f, ([x, y, z]) => [FLOAT, [x, y, z, 1]] ), vertexAttrib4f: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1f, ([x, y, z, w]) => [FLOAT, [x, y, z, w]] ), vertexAttrib1fv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1fv, ([[x]]) => [FLOAT, [x, 0, 0, 1]] ), vertexAttrib2fv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1fv, ([[x, y]]) => [FLOAT, [x, y, 0, 1]] ), vertexAttrib3fv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1fv, ([[x, y, z]]) => [FLOAT, [x, y, z, 1]] ), vertexAttrib4fv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1fv, ([[x, y, z, w]]) => [FLOAT, [x, y, z, w]] ), vertexAttrib1i: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1i, ([x]) => [FLOAT, [x, 0, 0, 1]] ), vertexAttrib2i: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1i, ([x, y]) => [FLOAT, [x, y, 0, 1]] ), vertexAttrib3i: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1i, ([x, y, z]) => [FLOAT, [x, y, z, 1]] ), vertexAttrib4i: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1i, ([x, y, z, w]) => [FLOAT, [x, y, z, w]] ), vertexAttrib1iv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1iv, ([[x]]) => [FLOAT, [x, 0, 0, 1]] ), vertexAttrib2iv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1iv, ([[x, y]]) => [FLOAT, [x, y, 0, 1]] ), vertexAttrib3iv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1iv, ([[x, y, z]]) => [FLOAT, [x, y, z, 1]] ), vertexAttrib4iv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1iv, ([[x, y, z, w]]) => [FLOAT, [x, y, z, w]] ), vertexAttrib1ui: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1ui, ([x]) => [FLOAT, [x, 0, 0, 1]] ), vertexAttrib2ui: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1ui, ([x, y]) => [FLOAT, [x, y, 0, 1]] ), vertexAttrib3ui: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1ui, ([x, y, z]) => [FLOAT, [x, y, z, 1]] ), vertexAttrib4ui: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1ui, ([x, y, z, w]) => [FLOAT, [x, y, z, w]] ), vertexAttrib1uiv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1uiv, ([[x]]) => [FLOAT, [x, 0, 0, 1]] ), vertexAttrib2uiv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1uiv, ([[x, y]]) => [FLOAT, [x, y, 0, 1]] ), vertexAttrib3uiv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1uiv, ([[x, y, z]]) => [FLOAT, [x, y, z, 1]] ), vertexAttrib4uiv: createVertexAttribWrapper( WebGL2RenderingContext.prototype.vertexAttrib1uiv, ([[x, y, z, w]]) => [FLOAT, [x, y, z, w]] ) }; const webgl1Extensions = { OES_texture_float: { fn() { return {}; } }, OES_vertex_array_object: { fn(vCtx) { return { VERTEX_ARRAY_BINDING_OES: sharedWebGLContext.VERTEX_ARRAY_BINDING, createVertexArrayOES() { return sharedWebGLContext.createVertexArray(); }, deleteVertexArrayOES(va) { sharedWebGLContext.deleteVertexArray(va); }, bindVertexArrayOES(va) { virtualFns.bindVertexArray.call(vCtx, va); }, isVertexArrayOES(va) { return sharedWebGLContext.isVertexArray(va); } }; } }, ANGLE_instanced_arrays: { fn(vCtx) { return { VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: 0x88fe, drawArraysInstancedANGLE(...args) { virtualFns.drawArraysInstanced.call(vCtx, ...args); }, drawElementsInstancedANGLE(...args) { virtualFns.drawElementsInstanced.call(vCtx, ...args); }, vertexAttribDivisorANGLE(...args) { sharedWebGLContext.vertexAttribDivisor(...args); } }; } } // We can't easily support WebGL_draw_buffers because WebGL2 does not // support gl_FragData. Instead, it requires you to write your shaders // in GLSL ES 3.0 if you want to use multiple color attachments. To support // that correctly would require writing a GLSL parser. We need to change // 'attribute' -> 'in', 'varying' -> 'out' in vertex shaders, 'varying' to 'in' // in fragment shader, 'texture2D' to 'texture' and declare outputs. That sounds // simple but it quickly becomes complicated. // // * 'texture' is a valid identifier in GLSL ES 1.0 but a reserved word in // GLSL ES 3.0 so we'd have to rename identifiers // // * Changing the fragment shader means it's on longer compatible with // GLSL ES 1.0 vertex shaders. But, back in WebGL1, we could easily use // the same vertex shader with and without WEBGL_draw_buffers. That means // we now need 2 versions of every vertex shader (ES 1.0 and ES 3.0), OR // we need to translate ALL shaders to GLSL ES 3.0 // // * GLSL 1.0 shaders support dynamically indexing an array of samplers. // GLSL 3.0 does not. So we'd have to emit an emulation function. // // The point is it's not a trivial amount of work. /* WEBGL_draw_buffers: { fn(vCtx) { return { COLOR_ATTACHMENT0_WEBGL : 0x8CE0, COLOR_ATTACHMENT1_WEBGL : 0x8CE1, COLOR_ATTACHMENT2_WEBGL : 0x8CE2, COLOR_ATTACHMENT3_WEBGL : 0x8CE3, COLOR_ATTACHMENT4_WEBGL : 0x8CE4, COLOR_ATTACHMENT5_WEBGL : 0x8CE5, COLOR_ATTACHMENT6_WEBGL : 0x8CE6, COLOR_ATTACHMENT7_WEBGL : 0x8CE7, COLOR_ATTACHMENT8_WEBGL : 0x8CE8, COLOR_ATTACHMENT9_WEBGL : 0x8CE9, COLOR_ATTACHMENT10_WEBGL : 0x8CEA, COLOR_ATTACHMENT11_WEBGL : 0x8CEB, COLOR_ATTACHMENT12_WEBGL : 0x8CEC, COLOR_ATTACHMENT13_WEBGL : 0x8CED, COLOR_ATTACHMENT14_WEBGL : 0x8CEE, COLOR_ATTACHMENT15_WEBGL : 0x8CEF, DRAW_BUFFER0_WEBGL : 0x8825, DRAW_BUFFER1_WEBGL : 0x8826, DRAW_BUFFER2_WEBGL : 0x8827, DRAW_BUFFER3_WEBGL : 0x8828, DRAW_BUFFER4_WEBGL : 0x8829, DRAW_BUFFER5_WEBGL : 0x882A, DRAW_BUFFER6_WEBGL : 0x882B, DRAW_BUFFER7_WEBGL : 0x882C, DRAW_BUFFER8_WEBGL : 0x882D, DRAW_BUFFER9_WEBGL : 0x882E, DRAW_BUFFER10_WEBGL : 0x882F, DRAW_BUFFER11_WEBGL : 0x8830, DRAW_BUFFER12_WEBGL : 0x8831, DRAW_BUFFER13_WEBGL : 0x8832, DRAW_BUFFER14_WEBGL : 0x8833, DRAW_BUFFER15_WEBGL : 0x8834, MAX_COLOR_ATTACHMENTS_WEBGL : 0x8CDF, MAX_DRAW_BUFFERS_WEBGL : 0x8824, drawBuffersWEBGL(buffers) { virtualFns.drawBuffers.call(vCtx, buffers); }, }; }, }, */ }; const texImage2DArgParersMap = new Map([ [ 9, function ([target, level, internalFormat, width, height, , format, type]) { return { target, level, internalFormat, width, height, format, type }; } ], [ 6, function ([target, level, internalFormat, format, type, texImageSource]) { return { target, level, internalFormat, width: texImageSource.width, height: texImageSource.height, format, type }; } ], [ 10, function ([target, level, internalFormat, width, height, , format, type]) { return { target, level, internalFormat, width, height, format, type }; } ] ]); const webgl1Fns = { getExtension(name) { const existingExt = this._extensions[name]; if (existingExt) { return existingExt; } const info = webgl1Extensions[name]; if (!info) { return virtualFns.getExtension.call(this, name); } return info.fn(this); }, texImage2D(...args) { makeCurrentContext(this); resizeCanvasIfChanged(this); const gl = sharedWebGLContext; const fn = texImage2DArgParersMap.get(args.length); const { internalFormat, type } = fn(args); if (type === sharedWebGLContext.FLOAT) { switch (internalFormat) { case gl.RGBA: args[2] = gl.RGBA32F; break; case gl.RGB: args[2] = gl.RGB32F; break; } } gl.texImage2D(...args); }, getSupportedExtensions: function () { return [ ...sharedWebGLContext.getSupportedExtensions(), 'OES_texture_float', 'WEBGL_depth_texture', 'OES_vertex_array_object' // "WEBGL_draw_buffers", // See other comment ]; } }; // copy all WebGL constants and functions to the prototype of // VirtualWebGLContext function copyProperties(keys, VirtualClass, overrideFns) { for (const key of keys) { const propDesc = Object.getOwnPropertyDescriptor(WebGL2RenderingContext.prototype, key); if (propDesc.get) { // it's a getter/setter ? const virtualPropDesc = Object.getOwnPropertyDescriptor(VirtualClass.prototype, key); if (!virtualPropDesc) { console.warn(`WebGL2RenderingContext.${key} is not supported`); } continue; } switch (key) { default: { const value = WebGL2RenderingContext.prototype[key]; let newValue = value; const fn = overrideFns[key] || virtualFns[key]; if (fn) { newValue = fn; } else { if (typeof value === 'function') { newValue = createWrapper(value, key); } } try { VirtualClass.prototype[key] = newValue; } catch (e) { // console.log(e); } break; } } } } copyProperties(Object.keys(WebGLRenderingContext.prototype), VirtualWebGLContext, webgl1Fns); copyProperties(Object.keys(WebGL2RenderingContext.prototype), VirtualWebGL2Context, {}); function makeCurrentContext(vCtx) { if (currentVirtualContext === vCtx) { return; } // save all current WebGL state on the previous current virtual context if (currentVirtualContext) { saveAllState(currentVirtualContext._state, currentVirtualContext); } // restore all state for the new context restoreAllState(vCtx._state, vCtx); // check if the current state is supposed to be rendering to the canvas. // if so bind vCtx._drawingbuffer currentVirtualContext = vCtx; } function resizeCanvasIfChanged(vCtx) { const width = vCtx.canvas.width; const height = vCtx.canvas.height; if (width !== vCtx._width || height !== vCtx._height) { vCtx._width = width; vCtx._height = height; const gl = sharedWebGLContext; const oldTexture = gl.getParameter(gl.TEXTURE_BINDING_2D); const format = vCtx._contextAttributes.alpha ? gl.RGBA : gl.RGB; gl.bindTexture(gl.TEXTURE_2D, vCtx._drawingbufferTexture); gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, gl.UNSIGNED_BYTE, null); gl.bindTexture(gl.TEXTURE_2D, oldTexture); if (vCtx._depthRenderbuffer) { const oldRenderbuffer = gl.getParameter(gl.RENDERBUFFER_BINDING); const internalFormat = vCtx._contextAttributes.stencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT16; gl.bindRenderbuffer(gl.RENDERBUFFER, vCtx._depthRenderbuffer); gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height); gl.bindRenderbuffer(gl.RENDERBUFFER, oldRenderbuffer); } } } function createOrGetVirtualWebGLContext(canvas, type, contextAttributes) { // check if this canvas already has a context const existingVirtualCtx = canvasToVirtualContextMap.get(canvas); if (existingVirtualCtx) { return existingVirtualCtx; } const compositor = settings.compositorCreator(canvas, type, contextAttributes) || new DefaultCompositor(canvas, type, contextAttributes); const newVirtualCtx = type === 'webgl2' ? new VirtualWebGL2Context(canvas, contextAttributes, compositor, () => { canvasToVirtualContextMap.delete(canvas); }) : new VirtualWebGLContext(canvas, contextAttributes, compositor, () => { canvasToVirtualContextMap.delete(canvas); }); canvasToVirtualContextMap.set(canvas, newVirtualCtx); return newVirtualCtx; } function createProgram(gl, shaderSources) { const program = gl.createProgram(); [gl.VERTEX_SHADER, gl.FRAGMENT_SHADER].forEach((type, ndx) => { const shader = gl.createShader(type); gl.shaderSource(shader, shaderSources[ndx]); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.error(gl.getShaderInfoLog(shader)); // eslint-disable-line } gl.attachShader(program, shader); }); gl.bindAttribLocation(program, 0, 'position'); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { console.error(gl.getProgramInfoLog(program)); // eslint-disable-line } return program; } function saveAllState(state, vCtx) { // save all WebGL state (current bindings, current texture units, // current attributes and/or vertex shade object, current program, // current blend, stencil, zBuffer, culling, viewport etc... state for (const fns of extensionSaveRestoreHelpersArray) { fns.save(state, vCtx); } } function setStencil(gl, face, st) { gl.stencilFuncSeparate(face, st.func, st.ref, st.valueMask); gl.stencilOpSeparate(face, st.fail, st.depthFail, st.depthPass); gl.stencilMaskSeparate(face, st.writeMask); } function restoreAllState(state, vCtx) { // restore all WebGL state (current bindings, current texture units, // current attributes and/or vertex shade object, current program, // current blend, stencil, zBuffer, culling, viewport etc... state // save all WebGL state (current bindings, current texture units, // current attributes and/or vertex shade object, current program, // current blend, stencil, zBuffer, culling, viewport etc... state const gl = sharedWebGLContext; gl.bindRenderbuffer(gl.RENDERBUFFER, state.renderbuffer); gl.bindFramebuffer(gl.READ_FRAMEBUFFER, state.readFramebuffer); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, state.drawFramebuffer); // restore attributes gl.bindVertexArray(state.vertexArray); for (let i = 0; i < numAttribs; ++i) { const attr = state.attribValues[i]; switch (attr.type) { case gl.FLOAT: gl.vertexAttrib4fv(i, attr.value); break; case gl.INT: gl.vertexAttribI4iv(i, attr.value); break; case gl.UNSIGNED_INT: gl.vertexAttribI4uiv(i, attr.value); break; } } gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, state.transformFeedback); // restore texture units for (let i = 0; i < numTextureUnits; ++i) { gl.activeTexture(gl.TEXTURE0 + i); const unit = state.textureUnits[i]; gl.bindTexture(gl.TEXTURE_2D, unit.texture2D); gl.bindTexture(gl.TEXTURE_CUBE_MAP, unit.textureCubemap); gl.bindTexture(gl.TEXTURE_2D_ARRAY, unit.texture2DArray); gl.bindTexture(gl.TEXTURE_3D, unit.texture3D); gl.bindSampler(i, unit.sampler); } gl.activeTexture(state.activeTexture); // uniform buffer bindings (must be restored before UNIFORM_BUFFER restore) for (let i = 0; i < numUniformBufferBindings; ++i) { const ub = state.uniformBufferBindings[i]; if (ub.size || ub.start) { gl.bindBufferRange(gl.UNIFORM_BUFFER, i, ub.buffer, ub.start, ub.size); } else { gl.bindBufferBase(gl.UNIFORM_BUFFER, i, ub.buffer); } } // bindings gl.bindBuffer(gl.ARRAY_BUFFER, state.arrayBuffer); gl.bindBuffer(gl.COPY_READ_BUFFER, state.copyReadBuffer); gl.bindBuffer(gl.COPY_WRITE_BUFFER, state.copyWriteBuffer); gl.bindBuffer(gl.PIXEL_PACK_BUFFER, state.pixelPackBuffer); gl.bindBuffer(gl.PIXEL_UNPACK_BUFFER, state.pixelUnpackBuffer); gl.bindBuffer(gl.TRANSFORM_FEEDBACK_BUFFER, state.transformFeedbackBuffer); gl.bindBuffer(gl.UNIFORM_BUFFER, state.uniformBuffer); gl.readBuffer(state.readBuffer); state.enable.forEach((value, key) => { enableDisable(gl, key, value); }); state.pack.forEach((value, key) => { gl.pixelStorei(key, value); }); gl.useProgram(state.currentProgram); gl.viewport(...state.viewport); gl.scissor(...state.scissor); gl.blendFuncSeparate( state.blendSrcRgb, state.blendDstRgb, state.blendSrcAlpha, state.blendDstAlpha ); gl.blendEquationSeparate(state.blendEquationRgb, state.blendEquationAlpha); gl.blendColor(...state.blendColor); gl.clearColor(...state.clearColor); gl.colorMask(...state.colorMask); gl.cullFace(state.cullFaceMode); gl.clearDepth(state.clearDepth); gl.depthFunc(state.depthFunc); gl.depthRange(...state.depthRange); gl.depthMask(state.depthMask); gl.frontFace(state.frontFace); gl.hint(gl.GENERATE_MIPMAP_HINT, state.generateMipmapHint); gl.lineWidth(state.lineWidth); gl.polygonOffset(state.polygonOffsetFactor, state.polygonOffsetUnits); gl.sampleCoverage(state.sampleCoverageValue, state.sampleCoverageUnits); setStencil(gl, gl.BACK, state.stencilBack); setStencil(gl, gl.FRONT, state.stencilFront); gl.clearStencil(state.stencilClearValue); for (const fns of extensionSaveRestoreHelpersArray) { fns.restore(state, vCtx); } } function enableDisable(gl, feature, enable) { if (enable) { gl.enable(feature); } else { gl.disable(feature); } } function renderAllDirtyVirtualCanvases() { if (!someContextsNeedRendering) { return; } someContextsNeedRendering = false; // save all current WebGL state on the previous current virtual context if (currentVirtualContext) { saveAllState(currentVirtualContext._state, currentVirtualContext); currentVirtualContext = null; } // set the state back to the one for drawing the canvas restoreAllState(baseState); for (const vCtx of canvasToVirtualContextMap.values()) { if (!vCtx._needComposite) { continue; } vCtx._needComposite = false; vCtx.composite(sharedWebGLContext); } } window.requestAnimationFrame = (function (origFn) { return function (callback) { return origFn.call(window, (time) => { const result = callback(time); renderAllDirtyVirtualCanvases(); return result; }); }; })(window.requestAnimationFrame); function setup(options) { Object.assign(settings, options); } window.virtualWebGL = { setup }; })(); ================================================ FILE: lang/shadeup/environment.ts ================================================ // parse("hello world"); import type { ShadeupExternalSymbol } from './symbol.js'; import type * as TYPES from '../../../parser-wasm/pkg/parser_wasm'; import type { ShadeupAlert } from './alert.js'; import files from './library/files'; let wasm_cache: any = null; export function loadWasm() { if (wasm_cache) { return wasm_cache; } let exp = import('../../../parser-wasm/pkg/parser_wasm.js'); wasm_cache = exp; return exp; } export default class ShadeupEnvironment extends EventTarget { files: Map; private alerts: Map; private env: TYPES.Environment; private mod: any; constructor() { super(); this.files = new Map(); this.alerts = new Map(); } async load() { let exp = await loadWasm(); this.mod = exp; this.env = exp.make_environment(); for (let k of Object.keys(files)) { this.updateFile(k, files[k]); this.evaluate(k); } console.log('loaded', this.files); } loaded() { if (this.env) { return Promise.resolve(); } return new Promise((resolve) => { if (this.env) { resolve(); } else { const interval = setInterval(() => { if (this.env) { clearInterval(interval); resolve(); } }, 100); } }); } addSymbol(sym: ShadeupExternalSymbol) { if (sym.kind == 'function') { let send = { name: sym.name, parameters: sym.parameters, return_type: sym.outType, js: sym.js }; this.mod.add_native_function(this.env, send); } } getAlerts(filename: string) { return this.alerts.get(filename) || []; } getIntellisense(filename: string) { return this.mod.get_intellisense(this.env, filename) || []; } evaluate(filename: string): boolean { let now = performance.now(); const content = this.files.get(filename); // const ast = this.parse(content); // console.log( // ast.alerts.length + " alerts in " + (performance.now() - now) + "ms" // ); // this.alerts.set(filename, ast.alerts); this.mod.set_file(this.env, filename, content); let successfulParse = this.mod.parse_file(this.env, filename); let alerts = this.mod.get_file_alerts(this.env, filename); this.alerts.set(filename, alerts); return successfulParse; } getAst(filename: string) { return this.mod.get_ast(this.env, filename); } updateFile(filename: string, content: string) { this.files.set(filename, content); this.mod.set_file(this.env, filename, content); setTimeout(() => { this.dispatchEvent(new CustomEvent('change', { detail: filename })); }, 0); } generateFile(filename: string): string { return this.mod.generate_file(this.env, filename); } getImports(filename: string) { return this.mod.get_imports(this.env, filename); } getSymbols() { return this.mod.get_symbols(this.env); } reset() { this.files.clear(); this.alerts.clear(); } } ================================================ FILE: lang/shadeup/environmentWorker.ts ================================================ import type ShadeupEnvironment from './environment'; import type { ShadeupExternalSymbol } from './symbol'; import type { ShadeupAlert } from './alert.js'; export class ShadeupEnvironmentProxy extends EventTarget { worker: Worker; renderedFiles: Map; files: Map; alerts: Map; intellisense: Map; symbols: any; imports: Map; constructor(worker: Worker) { super(); this.worker = worker; this.renderedFiles = new Map(); this.files = new Map(); this.alerts = new Map(); this.intellisense = new Map(); this.symbols = new Map(); this.imports = new Map(); let handleMessage = (msg: any) => { if (msg.type == 'intellisense') { this.intellisense.set(msg.filename, msg.data); this.dispatchEvent(new CustomEvent('intellisensed', { detail: msg.filename })); } else if (msg.type == 'alerts') { this.alerts.set(msg.filename, msg.data); this.dispatchEvent(new CustomEvent('alerted', { detail: msg.filename })); } else if (msg.type == 'symbols') { this.symbols = msg.data; } else if (msg.type == 'imports') { this.imports.set(msg.filename, msg.data); } else if (msg.type == 'rendered') { this.renderedFiles.set(msg.filename, msg.data); } }; this.worker.onmessage = (e) => { if (e.data.type == 'messages') { let hadRender = false; let renderFile = null; for (let msg of e.data.messages) { handleMessage(msg); if (msg.type == 'rendered') { hadRender = true; renderFile = msg.filename; } } if (hadRender) { this.dispatchEvent(new CustomEvent('rendered', { detail: renderFile })); } this.dispatchEvent(new CustomEvent('refresh', {})); } else { handleMessage(e.data); } }; } sendMessage(message: any) { this.worker.postMessage(message); } addSymbol(sym: ShadeupExternalSymbol) { this.sendMessage({ type: 'addSymbol', symbol: sym }); } getAlerts(filename: string) { return this.alerts.get(filename) ?? []; } getIntellisense(filename: string) { return this.intellisense.get(filename); } writeFile(filename: string, content: string) { this.files.set(filename, content); this.sendMessage({ type: 'writeFile', filename, data: content }); this.dispatchEvent(new CustomEvent('fileChanged', { detail: filename })); } evaluate(filename: string, skipGenerate = false) { this.sendMessage({ type: 'evaluate', filename, data: { skipGenerate } }); } getImports(filename: string) { return this.imports.get(filename); } getSymbols() { return this.symbols; } reset() { this.sendMessage({ type: 'reset' }); this.files.clear(); this.alerts.clear(); this.intellisense.clear(); this.symbols.clear(); this.imports.clear(); } } export function newEnvironmentWorker(): ShadeupEnvironmentProxy { let worker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); let p = new ShadeupEnvironmentProxy(worker); return p; } ================================================ FILE: lang/shadeup/frame.html ================================================ Shadeup sandbox ================================================ FILE: lang/shadeup/library/buffer.ts ================================================ import { getValueSize } from '../engine/adapters/webgpu'; import { float4, float3, float, float2, bool, int, int2, int3, int4, uint, uint2, uint3, uint4, atomic } from '/std_math'; export class buffer_internal { __opaque_buffer: true = true; structArray: T[] | null = null; floatArray: Float32Array | null = null; intArray: Int32Array | null = null; uintArray: Uint32Array | null = null; arrayBuffer: ArrayBuffer | null = null; vectorSize: int = 0; typeName: string; platformPayload: any = null; adapter: any = null; dirty: boolean = false; pendingWrites: number = 0; cpuReadDirty: boolean = false; cpuWriteDirty: boolean = false; elementCount: int = 0; elementBytes: int = 0; structured: boolean = false; fastIndex: (index: int) => T; fastIndexAssign: (index: int, value: T) => void; destroy() { this.adapter.destroyBuffer(this); } [index: number]: T; __index(index: int | uint): T { // this.download(); // return this.fastIndex(index); return null as any; } __index_assign(index: int | uint, value: T): void { // this.download(); // this.cpuWriteDirty = true; // this.fastIndexAssign(index, value); } __index_assign_op(op_fn: (a: T, b: T) => T, index: int | uint, value: T): void { // this.download(); // this.cpuWriteDirty = true; // this.fastIndexAssign(index, op_fn(this.fastIndex(index), value)); } len() { return this.elementCount; } /** * Returns the underlying cpu buffer as a typed array. * * > [!NOTE] * > This is considerably faster than using the raw index [] operator. * * > [!NOTE] * > If the buffer contents are structured (atomic, or a struct), this will return a normal array * * ```shadeup * let buf = buffer(); * let data = buf.getData(); * * for (let i = 0; i < data.length; i += 4) { * // Do something with data[i] * } * ``` */ getData(): Uint32Array | Float32Array | Uint8Array | Int32Array | T[] { if (this.structured) { return this.structArray!; } else { return this.floatArray ?? this.intArray ?? this.uintArray ?? new Uint8Array(0); } } write(other: buffer_internal) { if (!this.adapter) return; this.adapter.copyBufferToBuffer(other, this); } watchMutation: boolean = false; /** @shadeup=tag(async) @shadeup=noemit_gpu */ async download() { if (!this.adapter) return; if (this.pendingWrites > 0) { (window as any).flushAdapter(); } if (this.cpuReadDirty) { this.cpuReadDirty = false; await this.adapter.downloadBuffer(this); } } downloadAsync(): Promise { return this['download'](); } /** @shadeup=noemit_gpu */ upload(): void { if (!this.adapter) return; if (this.cpuWriteDirty) { this.cpuWriteDirty = false; this.adapter.uploadBuffer(this); } } symbol: Symbol = Symbol(); constructor(size: int, typeName: string, structure: any) { this.adapter = (window as any).shadeupGetGraphicsAdapter(); this.typeName = typeName; if (structure) { if (structure.name && !structure.name.startsWith('atomic')) { this.typeName = structure.name; } } this.elementCount = size; this.elementBytes = 4; if ( typeName == 'float4' || typeName == 'float3' || typeName == 'float2' || typeName == 'float' ) { this.vectorSize = 1; this.fastIndex = (index: int) => { return this.floatArray![index] as T; }; this.fastIndexAssign = (index: int, value: T) => { this.floatArray![index] = value as float; }; if (typeName == 'float4') { this.vectorSize = 4; this.fastIndex = (index: int) => { return float4( this.floatArray![index * 4], this.floatArray![index * 4 + 1], this.floatArray![index * 4 + 2], this.floatArray![index * 4 + 3] ) as T; }; this.fastIndexAssign = (index: int, value: float4) => { this.floatArray![index * 4] = value[0]; this.floatArray![index * 4 + 1] = value[1]; this.floatArray![index * 4 + 2] = value[2]; this.floatArray![index * 4 + 3] = value[3]; }; } if (typeName == 'float3') { this.vectorSize = 3; this.fastIndex = (index: int) => { return float3( this.floatArray![index * 3], this.floatArray![index * 3 + 1], this.floatArray![index * 3 + 2] ) as T; }; this.fastIndexAssign = (index: int, value: float3) => { this.floatArray![index * 3] = value[0]; this.floatArray![index * 3 + 1] = value[1]; this.floatArray![index * 3 + 2] = value[2]; }; } if (typeName == 'float2') { this.vectorSize = 2; this.fastIndex = (index: int) => { return float2(this.floatArray![index * 2], this.floatArray![index * 2 + 1]) as T; }; this.fastIndexAssign = (index: int, value: float2) => { this.floatArray![index * 2] = value[0]; this.floatArray![index * 2 + 1] = value[1]; }; } this.floatArray = new Float32Array(size * this.vectorSize); this.arrayBuffer = this.floatArray.buffer; } else if ( typeName == 'int4' || typeName == 'int3' || typeName == 'int2' || typeName == 'int' ) { this.vectorSize = 1; this.fastIndex = (index: int) => { return this.intArray![index] as T; }; this.fastIndexAssign = (index: int, value: T) => { this.intArray![index] = value as int; }; if (typeName == 'int4') { this.vectorSize = 4; this.fastIndex = (index: int) => { return int4( this.intArray![index * 4], this.intArray![index * 4 + 1], this.intArray![index * 4 + 2], this.intArray![index * 4 + 3] ) as T; }; this.fastIndexAssign = (index: int, value: int4) => { this.intArray![index * 4] = value[0]; this.intArray![index * 4 + 1] = value[1]; this.intArray![index * 4 + 2] = value[2]; this.intArray![index * 4 + 3] = value[3]; }; } if (typeName == 'int3') { this.vectorSize = 3; this.fastIndex = (index: int) => { return int3( this.intArray![index * 3], this.intArray![index * 3 + 1], this.intArray![index * 3 + 2] ) as T; }; this.fastIndexAssign = (index: int, value: int3) => { this.intArray![index * 3] = value[0]; this.intArray![index * 3 + 1] = value[1]; this.intArray![index * 3 + 2] = value[2]; }; } if (typeName == 'int2') { this.vectorSize = 2; this.fastIndex = (index: int) => { return int2(this.intArray![index * 2], this.intArray![index * 2 + 1]) as T; }; this.fastIndexAssign = (index: int, value: int2) => { this.intArray![index * 2] = value[0]; this.intArray![index * 2 + 1] = value[1]; }; } this.intArray = new Int32Array(size * this.vectorSize); this.arrayBuffer = this.intArray.buffer; } else if ( typeName == 'uint4' || typeName == 'uint3' || typeName == 'uint2' || typeName == 'uint' ) { this.vectorSize = 1; this.fastIndex = (index: int) => { return this.uintArray![index] as T; }; this.fastIndexAssign = (index: int, value: T) => { this.uintArray![index] = value as uint; }; if (typeName == 'uint4') { this.vectorSize = 4; this.fastIndex = (index: int) => { return uint4( this.uintArray![index * 4], this.uintArray![index * 4 + 1], this.uintArray![index * 4 + 2], this.uintArray![index * 4 + 3] ) as T; }; this.fastIndexAssign = (index: int, value: uint4) => { this.uintArray![index * 4] = value[0]; this.uintArray![index * 4 + 1] = value[1]; this.uintArray![index * 4 + 2] = value[2]; this.uintArray![index * 4 + 3] = value[3]; }; } if (typeName == 'uint3') { this.vectorSize = 3; this.fastIndex = (index: int) => { return uint3( this.uintArray![index * 3], this.uintArray![index * 3 + 1], this.uintArray![index * 3 + 2] ) as T; }; this.fastIndexAssign = (index: int, value: uint3) => { this.uintArray![index * 3] = value[0]; this.uintArray![index * 3 + 1] = value[1]; this.uintArray![index * 3 + 2] = value[2]; }; } if (typeName == 'uint2') { this.vectorSize = 2; this.fastIndex = (index: int) => { return uint2(this.uintArray![index * 2], this.uintArray![index * 2 + 1]) as T; }; this.fastIndexAssign = (index: int, value: uint2) => { this.uintArray![index * 2] = value[0]; this.uintArray![index * 2 + 1] = value[1]; }; } this.uintArray = new Uint32Array(size * this.vectorSize); this.arrayBuffer = this.uintArray.buffer; } else { this.structured = true; if (typeName.startsWith('atomic<')) { // this.structArray = new Array(size); this.arrayBuffer = new ArrayBuffer(size * 4); this.watchMutation = true; this.vectorSize = 1; this.elementBytes = 4; this.elementCount = size; for (let i = 0; i < size; i++) { // this.structArray[i] = atomic(0) as T; } if (typeName == 'atomic') { this.uintArray = new Uint32Array(this.arrayBuffer); this.fastIndex = (index: int) => { return atomic(this.uintArray![index]) as T; }; this.fastIndexAssign = (index: int, value: T) => { this.uintArray![index] = value.__value as any; }; } else { this.intArray = new Int32Array(this.arrayBuffer); this.fastIndex = (index: int) => { return atomic(this.intArray![index]) as T; }; this.fastIndexAssign = (index: int, value: T) => { this.intArray![index] = value.__value as any; }; } } else { let elementSize = this.adapter.getValueSize(structure); let realSize = elementSize * size; this.elementCount = size; this.elementBytes = elementSize; this.arrayBuffer = new ArrayBuffer(realSize); this.fastIndex = (index: int) => { return this.adapter.readStructuredBuffer( structure, this.arrayBuffer, index * elementSize ) as T; }; this.fastIndexAssign = (index: int, value: T) => { this.cpuWriteDirty = true; this.adapter.writeStructuredBuffer( structure, value, this.arrayBuffer, index * (elementSize / 4) ); }; } } (this.__index as any) = (index: int): T => { // await this.download(); if (this.watchMutation) { let data = this.fastIndex(index); (data as any).$mutate = (to?: T) => { this.cpuWriteDirty = true; if (to !== undefined) { if (this.intArray) { this.intArray[index] = to as any; } else { this.uintArray![index] = to as any; } } }; return data; } else { return this.fastIndex(index); } }; this.__index_assign = (index: int, value: T): void => { // await this.download(); this.cpuWriteDirty = true; this.fastIndexAssign(index, value); }; this.__index_assign_op = (op_fn: (a: T, b: T) => T, index: int, value: T): void => { // await this.download(); this.cpuWriteDirty = true; this.fastIndexAssign(index, op_fn(this.fastIndex(index), value)); }; } } export type buffer = buffer_internal; /** * Creates a new buffer. * ```shadeup * let buf = buffer(100); * * ``` */ export function buffer(data: T[], typeName: string, structure?: object): buffer; export function buffer(size: int, typeName: string, structure?: object): buffer; export function buffer(e1: any, typeName: string, structure?: object): buffer { if (typeof e1 === 'number') { let size = e1; let buf = new buffer_internal(size, typeName, structure!); return buf; } else { let data = e1; let buf = new buffer_internal(data.length, typeName, structure!); for (let i = 0; i < data.length; i++) { buf.fastIndexAssign(i, data[i]); } return buf; } } ================================================ FILE: lang/shadeup/library/color.ts ================================================ export namespace color { export const slate50 = [0.9725490196078431, 0.9803921568627451, 0.9882352941176471, 1]; export const slate100 = [0.9450980392156862, 0.9607843137254902, 0.9764705882352941, 1]; export const slate200 = [0.8862745098039215, 0.9098039215686274, 0.9411764705882353, 1]; export const slate300 = [0.796078431372549, 0.8352941176470589, 0.8823529411764706, 1]; export const slate400 = [0.5803921568627451, 0.6392156862745098, 0.7215686274509804, 1]; export const slate500 = [0.39215686274509803, 0.4549019607843137, 0.5450980392156862, 1]; export const slate600 = [0.2784313725490196, 0.3333333333333333, 0.4117647058823529, 1]; export const slate700 = [0.2, 0.2549019607843137, 0.3333333333333333, 1]; export const slate800 = [0.11764705882352941, 0.1607843137254902, 0.23137254901960785, 1]; export const slate900 = [0.058823529411764705, 0.09019607843137255, 0.16470588235294117, 1]; export const slate950 = [0.00784313725490196, 0.023529411764705882, 0.09019607843137255, 1]; export const gray50 = [0.9764705882352941, 0.9803921568627451, 0.984313725490196, 1]; export const gray100 = [0.9529411764705882, 0.9568627450980393, 0.9647058823529412, 1]; export const gray200 = [0.8980392156862745, 0.9058823529411765, 0.9215686274509803, 1]; export const gray300 = [0.8196078431372549, 0.8352941176470589, 0.8588235294117647, 1]; export const gray400 = [0.611764705882353, 0.6392156862745098, 0.6862745098039216, 1]; export const gray500 = [0.4196078431372549, 0.4470588235294118, 0.5019607843137255, 1]; export const gray600 = [0.29411764705882354, 0.3333333333333333, 0.38823529411764707, 1]; export const gray700 = [0.21568627450980393, 0.2549019607843137, 0.3176470588235294, 1]; export const gray800 = [0.12156862745098039, 0.1607843137254902, 0.21568627450980393, 1]; export const gray900 = [0.06666666666666667, 0.09411764705882353, 0.15294117647058825, 1]; export const gray950 = [0.011764705882352941, 0.027450980392156862, 0.07058823529411765, 1]; export const zinc50 = [0.9803921568627451, 0.9803921568627451, 0.9803921568627451, 1]; export const zinc100 = [0.9568627450980393, 0.9568627450980393, 0.9607843137254902, 1]; export const zinc200 = [0.8941176470588236, 0.8941176470588236, 0.9058823529411765, 1]; export const zinc300 = [0.8313725490196079, 0.8313725490196079, 0.8470588235294118, 1]; export const zinc400 = [0.6313725490196078, 0.6313725490196078, 0.6666666666666666, 1]; export const zinc500 = [0.44313725490196076, 0.44313725490196076, 0.47843137254901963, 1]; export const zinc600 = [0.3215686274509804, 0.3215686274509804, 0.3568627450980392, 1]; export const zinc700 = [0.24705882352941178, 0.24705882352941178, 0.27450980392156865, 1]; export const zinc800 = [0.15294117647058825, 0.15294117647058825, 0.16470588235294117, 1]; export const zinc900 = [0.09411764705882353, 0.09411764705882353, 0.10588235294117647, 1]; export const zinc950 = [0.03529411764705882, 0.03529411764705882, 0.043137254901960784, 1]; export const neutral50 = [0.9803921568627451, 0.9803921568627451, 0.9803921568627451, 1]; export const neutral100 = [0.9607843137254902, 0.9607843137254902, 0.9607843137254902, 1]; export const neutral200 = [0.8980392156862745, 0.8980392156862745, 0.8980392156862745, 1]; export const neutral300 = [0.8313725490196079, 0.8313725490196079, 0.8313725490196079, 1]; export const neutral400 = [0.6392156862745098, 0.6392156862745098, 0.6392156862745098, 1]; export const neutral500 = [0.45098039215686275, 0.45098039215686275, 0.45098039215686275, 1]; export const neutral600 = [0.3215686274509804, 0.3215686274509804, 0.3215686274509804, 1]; export const neutral700 = [0.25098039215686274, 0.25098039215686274, 0.25098039215686274, 1]; export const neutral800 = [0.14901960784313725, 0.14901960784313725, 0.14901960784313725, 1]; export const neutral900 = [0.09019607843137255, 0.09019607843137255, 0.09019607843137255, 1]; export const neutral950 = [0.0392156862745098, 0.0392156862745098, 0.0392156862745098, 1]; export const stone50 = [0.9803921568627451, 0.9803921568627451, 0.9764705882352941, 1]; export const stone100 = [0.9607843137254902, 0.9607843137254902, 0.9568627450980393, 1]; export const stone200 = [0.9058823529411765, 0.8980392156862745, 0.8941176470588236, 1]; export const stone300 = [0.8392156862745098, 0.8274509803921568, 0.8196078431372549, 1]; export const stone400 = [0.6588235294117647, 0.6352941176470588, 0.6196078431372549, 1]; export const stone500 = [0.47058823529411764, 0.44313725490196076, 0.4235294117647059, 1]; export const stone600 = [0.3411764705882353, 0.3254901960784314, 0.3058823529411765, 1]; export const stone700 = [0.26666666666666666, 0.25098039215686274, 0.23529411764705882, 1]; export const stone800 = [0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1]; export const stone900 = [0.10980392156862745, 0.09803921568627451, 0.09019607843137255, 1]; export const stone950 = [0.047058823529411764, 0.0392156862745098, 0.03529411764705882, 1]; export const red50 = [0.996078431372549, 0.9490196078431372, 0.9490196078431372, 1]; export const red100 = [0.996078431372549, 0.8862745098039215, 0.8862745098039215, 1]; export const red200 = [0.996078431372549, 0.792156862745098, 0.792156862745098, 1]; export const red300 = [0.9882352941176471, 0.6470588235294118, 0.6470588235294118, 1]; export const red400 = [0.9725490196078431, 0.44313725490196076, 0.44313725490196076, 1]; export const red500 = [0.9372549019607843, 0.26666666666666666, 0.26666666666666666, 1]; export const red600 = [0.8627450980392157, 0.14901960784313725, 0.14901960784313725, 1]; export const red700 = [0.7254901960784313, 0.10980392156862745, 0.10980392156862745, 1]; export const red800 = [0.6, 0.10588235294117647, 0.10588235294117647, 1]; export const red900 = [0.4980392156862745, 0.11372549019607843, 0.11372549019607843, 1]; export const red950 = [0.27058823529411763, 0.0392156862745098, 0.0392156862745098, 1]; export const orange50 = [1, 0.9686274509803922, 0.9294117647058824, 1]; export const orange100 = [1, 0.9294117647058824, 0.8352941176470589, 1]; export const orange200 = [0.996078431372549, 0.8431372549019608, 0.6666666666666666, 1]; export const orange300 = [0.9921568627450981, 0.7294117647058823, 0.4549019607843137, 1]; export const orange400 = [0.984313725490196, 0.5725490196078431, 0.23529411764705882, 1]; export const orange500 = [0.9764705882352941, 0.45098039215686275, 0.08627450980392157, 1]; export const orange600 = [0.9176470588235294, 0.34509803921568627, 0.047058823529411764, 1]; export const orange700 = [0.7607843137254902, 0.2549019607843137, 0.047058823529411764, 1]; export const orange800 = [0.6039215686274509, 0.20392156862745098, 0.07058823529411765, 1]; export const orange900 = [0.48627450980392156, 0.17647058823529413, 0.07058823529411765, 1]; export const orange950 = [0.2627450980392157, 0.0784313725490196, 0.027450980392156862, 1]; export const amber50 = [1, 0.984313725490196, 0.9215686274509803, 1]; export const amber100 = [0.996078431372549, 0.9529411764705882, 0.7803921568627451, 1]; export const amber200 = [0.9921568627450981, 0.9019607843137255, 0.5411764705882353, 1]; export const amber300 = [0.9882352941176471, 0.8274509803921568, 0.30196078431372547, 1]; export const amber400 = [0.984313725490196, 0.7490196078431373, 0.1411764705882353, 1]; export const amber500 = [0.9607843137254902, 0.6196078431372549, 0.043137254901960784, 1]; export const amber600 = [0.8509803921568627, 0.4666666666666667, 0.023529411764705882, 1]; export const amber700 = [0.7058823529411765, 0.3254901960784314, 0.03529411764705882, 1]; export const amber800 = [0.5725490196078431, 0.25098039215686274, 0.054901960784313725, 1]; export const amber900 = [0.47058823529411764, 0.20784313725490197, 0.058823529411764705, 1]; export const amber950 = [0.27058823529411763, 0.10196078431372549, 0.011764705882352941, 1]; export const yellow50 = [0.996078431372549, 0.9882352941176471, 0.9098039215686274, 1]; export const yellow100 = [0.996078431372549, 0.9764705882352941, 0.7647058823529411, 1]; export const yellow200 = [0.996078431372549, 0.9411764705882353, 0.5411764705882353, 1]; export const yellow300 = [0.9921568627450981, 0.8784313725490196, 0.2784313725490196, 1]; export const yellow400 = [0.9803921568627451, 0.8, 0.08235294117647059, 1]; export const yellow500 = [0.9176470588235294, 0.7019607843137254, 0.03137254901960784, 1]; export const yellow600 = [0.792156862745098, 0.5411764705882353, 0.01568627450980392, 1]; export const yellow700 = [0.6313725490196078, 0.3843137254901961, 0.027450980392156862, 1]; export const yellow800 = [0.5215686274509804, 0.30196078431372547, 0.054901960784313725, 1]; export const yellow900 = [0.44313725490196076, 0.24705882352941178, 0.07058823529411765, 1]; export const yellow950 = [0.25882352941176473, 0.12549019607843137, 0.023529411764705882, 1]; export const lime50 = [0.9686274509803922, 0.996078431372549, 0.9058823529411765, 1]; export const lime100 = [0.9254901960784314, 0.9882352941176471, 0.796078431372549, 1]; export const lime200 = [0.8509803921568627, 0.9764705882352941, 0.615686274509804, 1]; export const lime300 = [0.7450980392156863, 0.9490196078431372, 0.39215686274509803, 1]; export const lime400 = [0.6392156862745098, 0.9019607843137255, 0.20784313725490197, 1]; export const lime500 = [0.5176470588235295, 0.8, 0.08627450980392157, 1]; export const lime600 = [0.396078431372549, 0.6392156862745098, 0.050980392156862744, 1]; export const lime700 = [0.30196078431372547, 0.48627450980392156, 0.058823529411764705, 1]; export const lime800 = [0.24705882352941178, 0.3843137254901961, 0.07058823529411765, 1]; export const lime900 = [0.21176470588235294, 0.3254901960784314, 0.0784313725490196, 1]; export const lime950 = [0.10196078431372549, 0.1803921568627451, 0.0196078431372549, 1]; export const green50 = [0.9411764705882353, 0.9921568627450981, 0.9568627450980393, 1]; export const green100 = [0.8627450980392157, 0.9882352941176471, 0.9058823529411765, 1]; export const green200 = [0.7333333333333333, 0.9686274509803922, 0.8156862745098039, 1]; export const green300 = [0.5254901960784314, 0.9372549019607843, 0.6745098039215687, 1]; export const green400 = [0.2901960784313726, 0.8705882352941177, 0.5019607843137255, 1]; export const green500 = [0.13333333333333333, 0.7725490196078432, 0.3686274509803922, 1]; export const green600 = [0.08627450980392157, 0.6392156862745098, 0.2901960784313726, 1]; export const green700 = [0.08235294117647059, 0.5019607843137255, 0.23921568627450981, 1]; export const green800 = [0.08627450980392157, 0.396078431372549, 0.20392156862745098, 1]; export const green900 = [0.0784313725490196, 0.3254901960784314, 0.17647058823529413, 1]; export const green950 = [0.0196078431372549, 0.1803921568627451, 0.08627450980392157, 1]; export const emerald50 = [0.9254901960784314, 0.9921568627450981, 0.9607843137254902, 1]; export const emerald100 = [0.8196078431372549, 0.9803921568627451, 0.8980392156862745, 1]; export const emerald200 = [0.6549019607843137, 0.9529411764705882, 0.8156862745098039, 1]; export const emerald300 = [0.43137254901960786, 0.9058823529411765, 0.7176470588235294, 1]; export const emerald400 = [0.20392156862745098, 0.8274509803921568, 0.6, 1]; export const emerald500 = [0.06274509803921569, 0.7254901960784313, 0.5058823529411764, 1]; export const emerald600 = [0.0196078431372549, 0.5882352941176471, 0.4117647058823529, 1]; export const emerald700 = [0.01568627450980392, 0.47058823529411764, 0.3411764705882353, 1]; export const emerald800 = [0.023529411764705882, 0.37254901960784315, 0.27450980392156865, 1]; export const emerald900 = [0.023529411764705882, 0.3058823529411765, 0.23137254901960785, 1]; export const emerald950 = [0.00784313725490196, 0.17254901960784313, 0.13333333333333333, 1]; export const teal50 = [0.9411764705882353, 0.9921568627450981, 0.9803921568627451, 1]; export const teal100 = [0.8, 0.984313725490196, 0.9450980392156862, 1]; export const teal200 = [0.6, 0.9647058823529412, 0.8941176470588236, 1]; export const teal300 = [0.3686274509803922, 0.9176470588235294, 0.8313725490196079, 1]; export const teal400 = [0.17647058823529413, 0.8313725490196079, 0.7490196078431373, 1]; export const teal500 = [0.0784313725490196, 0.7215686274509804, 0.6509803921568628, 1]; export const teal600 = [0.050980392156862744, 0.5803921568627451, 0.5333333333333333, 1]; export const teal700 = [0.058823529411764705, 0.4627450980392157, 0.43137254901960786, 1]; export const teal800 = [0.06666666666666667, 0.3686274509803922, 0.34901960784313724, 1]; export const teal900 = [0.07450980392156863, 0.3058823529411765, 0.2901960784313726, 1]; export const teal950 = [0.01568627450980392, 0.1843137254901961, 0.1803921568627451, 1]; export const cyan50 = [0.9254901960784314, 0.996078431372549, 1, 1]; export const cyan100 = [0.8117647058823529, 0.9803921568627451, 0.996078431372549, 1]; export const cyan200 = [0.6470588235294118, 0.9529411764705882, 0.9882352941176471, 1]; export const cyan300 = [0.403921568627451, 0.9098039215686274, 0.9764705882352941, 1]; export const cyan400 = [0.13333333333333333, 0.8274509803921568, 0.9333333333333333, 1]; export const cyan500 = [0.023529411764705882, 0.7137254901960784, 0.8313725490196079, 1]; export const cyan600 = [0.03137254901960784, 0.5686274509803921, 0.6980392156862745, 1]; export const cyan700 = [0.054901960784313725, 0.4549019607843137, 0.5647058823529412, 1]; export const cyan800 = [0.08235294117647059, 0.3686274509803922, 0.4588235294117647, 1]; export const cyan900 = [0.08627450980392157, 0.3058823529411765, 0.38823529411764707, 1]; export const cyan950 = [0.03137254901960784, 0.2, 0.26666666666666666, 1]; export const sky50 = [0.9411764705882353, 0.9764705882352941, 1, 1]; export const sky100 = [0.8784313725490196, 0.9490196078431372, 0.996078431372549, 1]; export const sky200 = [0.7294117647058823, 0.9019607843137255, 0.9921568627450981, 1]; export const sky300 = [0.49019607843137253, 0.8274509803921568, 0.9882352941176471, 1]; export const sky400 = [0.2196078431372549, 0.7411764705882353, 0.9725490196078431, 1]; export const sky500 = [0.054901960784313725, 0.6470588235294118, 0.9137254901960784, 1]; export const sky600 = [0.00784313725490196, 0.5176470588235295, 0.7803921568627451, 1]; export const sky700 = [0.011764705882352941, 0.4117647058823529, 0.6313725490196078, 1]; export const sky800 = [0.027450980392156862, 0.34901960784313724, 0.5215686274509804, 1]; export const sky900 = [0.047058823529411764, 0.2901960784313726, 0.43137254901960786, 1]; export const sky950 = [0.03137254901960784, 0.1843137254901961, 0.28627450980392155, 1]; export const blue50 = [0.9372549019607843, 0.9647058823529412, 1, 1]; export const blue100 = [0.8588235294117647, 0.9176470588235294, 0.996078431372549, 1]; export const blue200 = [0.7490196078431373, 0.8588235294117647, 0.996078431372549, 1]; export const blue300 = [0.5764705882352941, 0.7725490196078432, 0.9921568627450981, 1]; export const blue400 = [0.3764705882352941, 0.6470588235294118, 0.9803921568627451, 1]; export const blue500 = [0.23137254901960785, 0.5098039215686274, 0.9647058823529412, 1]; export const blue600 = [0.1450980392156863, 0.38823529411764707, 0.9215686274509803, 1]; export const blue700 = [0.11372549019607843, 0.3058823529411765, 0.8470588235294118, 1]; export const blue800 = [0.11764705882352941, 0.25098039215686274, 0.6862745098039216, 1]; export const blue900 = [0.11764705882352941, 0.22745098039215686, 0.5411764705882353, 1]; export const blue950 = [0.09019607843137255, 0.1450980392156863, 0.32941176470588235, 1]; export const indigo50 = [0.9333333333333333, 0.9490196078431372, 1, 1]; export const indigo100 = [0.8784313725490196, 0.9058823529411765, 1, 1]; export const indigo200 = [0.7803921568627451, 0.8235294117647058, 0.996078431372549, 1]; export const indigo300 = [0.6470588235294118, 0.7058823529411765, 0.9882352941176471, 1]; export const indigo400 = [0.5058823529411764, 0.5490196078431373, 0.9725490196078431, 1]; export const indigo500 = [0.38823529411764707, 0.4, 0.9450980392156862, 1]; export const indigo600 = [0.30980392156862746, 0.27450980392156865, 0.8980392156862745, 1]; export const indigo700 = [0.2627450980392157, 0.2196078431372549, 0.792156862745098, 1]; export const indigo800 = [0.21568627450980393, 0.18823529411764706, 0.6392156862745098, 1]; export const indigo900 = [0.19215686274509805, 0.1803921568627451, 0.5058823529411764, 1]; export const indigo950 = [0.11764705882352941, 0.10588235294117647, 0.29411764705882354, 1]; export const violet50 = [0.9607843137254902, 0.9529411764705882, 1, 1]; export const violet100 = [0.9294117647058824, 0.9137254901960784, 0.996078431372549, 1]; export const violet200 = [0.8666666666666667, 0.8392156862745098, 0.996078431372549, 1]; export const violet300 = [0.7686274509803922, 0.7098039215686275, 0.9921568627450981, 1]; export const violet400 = [0.6549019607843137, 0.5450980392156862, 0.9803921568627451, 1]; export const violet500 = [0.5450980392156862, 0.3607843137254902, 0.9647058823529412, 1]; export const violet600 = [0.48627450980392156, 0.22745098039215686, 0.9294117647058824, 1]; export const violet700 = [0.42745098039215684, 0.1568627450980392, 0.8509803921568627, 1]; export const violet800 = [0.3568627450980392, 0.12941176470588237, 0.7137254901960784, 1]; export const violet900 = [0.2980392156862745, 0.11372549019607843, 0.5843137254901961, 1]; export const violet950 = [0.1803921568627451, 0.06274509803921569, 0.396078431372549, 1]; export const purple50 = [0.9803921568627451, 0.9607843137254902, 1, 1]; export const purple100 = [0.9529411764705882, 0.9098039215686274, 1, 1]; export const purple200 = [0.9137254901960784, 0.8352941176470589, 1, 1]; export const purple300 = [0.8470588235294118, 0.7058823529411765, 0.996078431372549, 1]; export const purple400 = [0.7529411764705882, 0.5176470588235295, 0.9882352941176471, 1]; export const purple500 = [0.6588235294117647, 0.3333333333333333, 0.9686274509803922, 1]; export const purple600 = [0.5764705882352941, 0.2, 0.9176470588235294, 1]; export const purple700 = [0.49411764705882355, 0.13333333333333333, 0.807843137254902, 1]; export const purple800 = [0.4196078431372549, 0.12941176470588237, 0.6588235294117647, 1]; export const purple900 = [0.34509803921568627, 0.10980392156862745, 0.5294117647058824, 1]; export const purple950 = [0.23137254901960785, 0.027450980392156862, 0.39215686274509803, 1]; export const fuchsia50 = [0.9921568627450981, 0.9568627450980393, 1, 1]; export const fuchsia100 = [0.9803921568627451, 0.9098039215686274, 1, 1]; export const fuchsia200 = [0.9607843137254902, 0.8156862745098039, 0.996078431372549, 1]; export const fuchsia300 = [0.9411764705882353, 0.6705882352941176, 0.9882352941176471, 1]; export const fuchsia400 = [0.9098039215686274, 0.4745098039215686, 0.9764705882352941, 1]; export const fuchsia500 = [0.8509803921568627, 0.27450980392156865, 0.9372549019607843, 1]; export const fuchsia600 = [0.7529411764705882, 0.14901960784313725, 0.8274509803921568, 1]; export const fuchsia700 = [0.6352941176470588, 0.10980392156862745, 0.6862745098039216, 1]; export const fuchsia800 = [0.5254901960784314, 0.09803921568627451, 0.5607843137254902, 1]; export const fuchsia900 = [0.4392156862745098, 0.10196078431372549, 0.4588235294117647, 1]; export const fuchsia950 = [0.2901960784313726, 0.01568627450980392, 0.3058823529411765, 1]; export const pink50 = [0.9921568627450981, 0.9490196078431372, 0.9725490196078431, 1]; export const pink100 = [0.9882352941176471, 0.9058823529411765, 0.9529411764705882, 1]; export const pink200 = [0.984313725490196, 0.8117647058823529, 0.9098039215686274, 1]; export const pink300 = [0.9764705882352941, 0.6588235294117647, 0.8313725490196079, 1]; export const pink400 = [0.9568627450980393, 0.4470588235294118, 0.7137254901960784, 1]; export const pink500 = [0.9254901960784314, 0.2823529411764706, 0.6, 1]; export const pink600 = [0.8588235294117647, 0.15294117647058825, 0.4666666666666667, 1]; export const pink700 = [0.7450980392156863, 0.09411764705882353, 0.36470588235294116, 1]; export const pink800 = [0.615686274509804, 0.09019607843137255, 0.30196078431372547, 1]; export const pink900 = [0.5137254901960784, 0.09411764705882353, 0.2627450980392157, 1]; export const pink950 = [0.3137254901960784, 0.027450980392156862, 0.1411764705882353, 1]; export const rose50 = [1, 0.9450980392156862, 0.9490196078431372, 1]; export const rose100 = [1, 0.8941176470588236, 0.9019607843137255, 1]; export const rose200 = [0.996078431372549, 0.803921568627451, 0.8274509803921568, 1]; export const rose300 = [0.9921568627450981, 0.6431372549019608, 0.6862745098039216, 1]; export const rose400 = [0.984313725490196, 0.44313725490196076, 0.5215686274509804, 1]; export const rose500 = [0.9568627450980393, 0.24705882352941178, 0.3686274509803922, 1]; export const rose600 = [0.8823529411764706, 0.11372549019607843, 0.2823529411764706, 1]; export const rose700 = [0.7450980392156863, 0.07058823529411765, 0.23529411764705882, 1]; export const rose800 = [0.6235294117647059, 0.07058823529411765, 0.2235294117647059, 1]; export const rose900 = [0.5333333333333333, 0.07450980392156863, 0.21568627450980393, 1]; export const rose950 = [0.2980392156862745, 0.0196078431372549, 0.09803921568627451, 1]; } ================================================ FILE: lang/shadeup/library/common.shadeup ================================================ import buffer from "/_std/buffer"; import ui from "/_std/ui"; import texture2d, texture3d from "/_std/texture"; /** * Converts a position in screenSpace to a position in 2d clipSpace. e.g. (0, screenSize.x) -> (-1, 1) */ pub fn pixelToClip(pixelPosition: float2) -> float2 { let zeroToOne = pixelPosition / env.screenSize; let zeroToTwo = zeroToOne * 2.0; let clipSpace = zeroToTwo - 1.0.xy; return (clipSpace.x, clipSpace.y * -1.0); } /** * Value of PI to 35 decimal places. */ const PI = 3.14159265358979323846264338327950288; export { PI, buffer, texture2d, texture3d, ui }; /** * Quaternion helpers */ pub struct quat {} impl quat { /** * Creates a quaternion from an angle and axis. */ pub fn fromAngleAxis(angle: float, axis: float3) -> float4 { return float4(axis * sin(angle * 0.5), cos(angle * 0.5)); } /** * Multiplies two quaternions and returns the result. */ pub fn mul(a: float4, b: float4) -> float4 { return float4( b.xyz * a.w + a.xyz * b.w + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz) ); } /** * Rotates a vector by a quaternion and returns the rotated vector. */ pub fn rotate(quaternion: float4, vector: float3) -> float3 { let q = quat::mul(quat::mul(quaternion, float4(vector, 0)), quat::conjugate(quaternion)); return q.xyz; } /** * Returns the conjugate of the input quaternion. * * The conjugate of a quaternion number is a quaternion with the same magnitudes but with the sign of the imaginary parts changed */ pub fn conjugate(quaternion: float4) -> float4 { return float4(-quaternion.xyz, quaternion.w); } /** * Returns the inverse of the input quaternion. */ pub fn inverse(quaternion: float4) -> float4 { return quat::conjugate(quaternion) / dot(quaternion, quaternion); } /** * Generates a quaternion that rotates from one direction to another via the shortest path. */ pub fn fromToRotation(from: float3, to: float3) -> float4 { let q = 0.0.xyzw; let d = dot(from, to); if (d < -0.999999) { let right = float3(1, 0, 0); let up = float3(0, 1, 0); let tmp = cross(right, from); if (length(tmp) < 0.000001) { tmp = cross(up, from); } tmp = normalize(tmp); q = quat::fromAngleAxis(PI, tmp); } else if (d > 0.999999) { q = float4(0, 0, 0, 1); } else { q = float4(cross(from, to), 1 + d); q = normalize(q); } return q; } pub fn diff(a: float4, b: float4) -> float { return a * quat::inverse(b); } /** * Generates lookAt quaternion. */ pub fn lookAt(forward: float3, up: float3): float4 { let right = normalize(cross(forward, up)); up = normalize(cross(forward, right)); let m00 = right.x; let m01 = right.y; let m02 = right.z; let m10 = up.x; let m11 = up.y; let m12 = up.z; let m20 = forward.x; let m21 = forward.y; let m22 = forward.z; let num8 = (m00 + m11) + m22; let q = float4(0, 0, 0, 1); if (num8 > 0.0) { let num = sqrt(num8 + 1.0); let w = num * 0.5; num = 0.5 / num; let x = (m12 - m21) * num; let y = (m20 - m02) * num; let z = (m01 - m10) * num; return float4(x, y, z, w); } if ((m00 >= m11) && (m00 >= m22)) { let num7 = sqrt(((1.0 + m00) - m11) - m22); let num4 = 0.5 / num7; let x = 0.5 * num7; let y = (m01 + m10) * num4; let z = (m02 + m20) * num4; let w = (m12 - m21) * num4; return float4(x, y, z, w); } if (m11 > m22) { let num6 = sqrt(((1.0 + m11) - m00) - m22); let num3 = 0.5 / num6; let x = (m10 + m01) * num3; let y = 0.5 * num6; let z = (m21 + m12) * num3; let w = (m20 - m02) * num3; return float4(x, y, z, w); } let num5 = sqrt(((1.0 + m22) - m00) - m11); let num2 = 0.5 / num5; let x = (m20 + m02) * num2; let y = (m21 + m12) * num2; let z = 0.5 * num5; let w = (m01 - m10) * num2; return float4(x, y, z, w); } /** * Smooth interpolation between two quaternions. */ pub fn slerp(a: float4, b: float4, t: float) -> float4 { if (length(a) == 0.0) { if (length(b) == 0.0) { return float4(0, 0, 0, 1); } return b; } else if (length(b) == 0.0) { return a; } let cosHalfAngle = a.w * b.w + dot(a.xyz, b.xyz); if (cosHalfAngle >= 1.0 || cosHalfAngle <= -1.0) { return a; } else if (cosHalfAngle < 0.0) { b *= -1.0; cosHalfAngle = -cosHalfAngle; } let blendA = 0.0; let blendB = 0.0; if (cosHalfAngle < 0.99) { let halfAngle = acos(cosHalfAngle); let sinHalfAngle = sin(halfAngle); let oneOverSinHalfAngle = 1.0 / sinHalfAngle; blendA = sin(halfAngle * (1.0 - t)) * oneOverSinHalfAngle; blendB = sin(halfAngle * t) * oneOverSinHalfAngle; } else { blendA = 1.0 - t; blendB = t; } let result = float4(blendA * a.xyz + blendB * b.xyz, blendA * a.w + blendB * b.w); if (length(result) > 0.0) { return normalize(result); } return float4(0, 0, 0, 1); } /** * Converts quaternion to matrix. */ pub fn toMatrix(quaternion: float4) { let x = quaternion.x; let y = quaternion.y; let z = quaternion.z; let w = quaternion.w; let x2 = x + x; let y2 = y + y; let z2 = z + z; let xx = x * x2; let xy = x * y2; let xz = x * z2; let yy = y * y2; let yz = y * z2; let zz = z * z2; let wx = w * x2; let wy = w * y2; let wz = w * z2; let m = float4x4( 1.0 - (yy + zz), xy + wz, xz - wy, 0, xy - wz, 1.0 - (xx + zz), yz + wx, 0, xz + wy, yz - wx, 1.0 - (xx + yy), 0, 0, 0, 0, 1.0 ); return m; } pub fn fromEulerAngles(angles: float3) { let cr = cos(angles.x * 0.5); let sr = sin(angles.x * 0.5); let cp = cos(angles.y * 0.5); let sp = sin(angles.y * 0.5); let cy = cos(angles.z * 0.5); let sy = sin(angles.z * 0.5); return float4( sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy ) } } window.shadeupQuat = quat; pub struct Camera2d { pub position: float2 = float2(0, 0); pub zoom: float = 1; } impl Camera2d { pub fn transform(self, position: float2) -> float2 { return (position - self.position) * self.zoom; } /** * Moves and zooms the camera to fit the given size. (centers the camera in the viewport) */ pub fn fit(self, size: float2) { let zoom = 1/min(env.screenSize.x / size.x, env.screenSize.y / size.y); let position = (env.screenSize - size * (1/zoom)) / 2; self.position = position; self.zoom = zoom; } } pub struct Camera { pub position: float3 = float3(0, 0, 0); pub rotation: float4 = float4(1, 0, 0, 0); pub width: float = 1920; pub height: float = 1080; pub fov: float = 90; pub near: float = 1; pub far: float = 100000; } impl Camera { pub fn getRay(self, screen: float2) { let aspect = self.width / self.height; let x = screen.x; let y = screen.y; let Px = (2 * ((x + 0.5) / self.width) - 1) * tan(self.fov / 2 * PI / 180) * aspect; let Py = (1 - 2 * ((y + 0.5) / self.height)) * tan(self.fov / 2 * PI / 180); return quat::rotate(self.rotation, normalize((Px, Py, -1))); } pub fn getTransformToViewMatrix(self, position: float3, scale: float3, rotation: float4) { let rotationMatrix = quat::toMatrix(rotation); let translationMatrix = float4x4( scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, position.x, position.y, position.z, 1 ); return self.getPerspectiveMatrix() * self.getWorldToViewMatrix() * translationMatrix * rotationMatrix; } pub fn getCombinedMatrix(self) -> float4x4 { return self.getPerspectiveMatrix() * self.getWorldToViewMatrix(); } pub fn getCombinedMatrixReverseZ(self) -> float4x4 { return self.getPerspectiveMatrixReverseZ() * self.getWorldToViewMatrix(); } pub fn getWorldToViewMatrix(self) -> float4x4 { let rotationMatrix = quat::toMatrix(self.rotation); let translationMatrix = float4x4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, self.position.x, self.position.y, self.position.z, 1 ); return inverse(translationMatrix * rotationMatrix); } pub fn getPerspectiveMatrixReverseZ(self) -> float4x4 { return matrix::perspectiveReverseZ(self.fov, self.width / self.height, self.near); } pub fn getPerspectiveMatrix(self) -> float4x4 { return matrix::perspective(self.fov, self.width / self.height, self.near, self.far); // // let matrix = float4x4(); // let far = self.far; // let near = self.near; // let aspect = self.width / self.height; // let fovRad = radians(self.fov); // let tanFov = tan( fovRad * 0.5 ); // // matrix[0][0] = ; // // matrix[1][1] = 1.0 / tanFov; // // matrix[2][2] = -((far + near)/(far - near)); // // matrix[3][2] = -((2*(near*far))/(far - near)); // // matrix[2][3] = -1; // // matrix[3][3] = 0; // let matrix = float4x4( // 1.0 / (tanFov * aspect), 0, 0, 0, // 0, 1.0 / tanFov, 0, 0, // 0, 0, -((far + near)/(far - near)), -1, // 0, 0, -((2*(near*far))/(far - near)), 0 // ); // return matrix; } pub fn getOrthographicMatrix(self) -> float4x4 { let matrix = float4x4(); let far = self.far; let near = self.near; let w = 1.0 / self.width; let h = 1.0 / self.height; matrix[0][0] = w; matrix[1][1] = h; matrix[2][2] = -(2.0/(far - near)); matrix[2][3] = ((far + near)/(far-near)); //matrix[2][2] = -((far + near)/(far - near)); //matrix[3][2] = -((2*(near*far))/(far - near)); matrix[3][3] = 1.0; return matrix; } } window._makeCamera = Camera; window._makeCamera2d = Camera2d; fn easeA(aA1: float, aA2: float) -> float { return 1.0 - 3.0 * aA2 + 3.0 * aA1; } fn easeB(aA1: float, aA2: float) -> float { return 3.0 * aA2 - 6.0 * aA1; } fn easeC(aA1: float) -> float { return 3.0 * aA1; } fn calcBezier(aT: float, aA1: float, aA2: float) -> float { return ((easeA(aA1, aA2) * aT + easeB(aA1, aA2)) * aT + easeC(aA1)) * aT; } fn getSlope(aT: float, aA1: float, aA2: float) -> float { return 3.0 * easeA(aA1, aA2) * aT * aT + 2.0 * easeB(aA1, aA2) * aT + easeC(aA1); } // fn getTForX(aX: float, aA1: float, aA2: float) -> float { // let aGuessT = aX; // for (let i = 0; i <= 10; i++) { // let currentSlope = bezSlope(aGuessT, aA1, aA2); // if (currentSlope == 0.0) { // return aGuessT; // } // let currentX = calcBezier(aGuessT, aA1, aA2) - aX; // aGuessT -= currentX / currentSlope; // } // return aGuessT; // } const NEWTON_ITERATIONS = 4; const NEWTON_MIN_SLOPE = 0.02; const SUBDIVISION_PRECISION = 0.0000001; const SUBDIVISION_MAX_ITERATIONS = 10; const kSplineTableSize = 11; const kSampleStepSize = 1.0 / float(kSplineTableSize - 1); fn getTForX(aX: float, mX1: float, mX2: float) { let mSampleValues: float[11] = array(11, 0); for (let i = 0; i < kSplineTableSize; i++) { mSampleValues[i] = calcBezier(float(i) * kSampleStepSize, mX1, mX2); } // Find interval where t lies let intervalStart = 0.0; let currentSample = 1; let lastSample = kSplineTableSize - 1; for (let dummy = 0; currentSample != lastSample && mSampleValues[currentSample] <= aX; currentSample++) { intervalStart += kSampleStepSize; } currentSample--; // t now lies between *currentSample and *currentSample+1 // Interpolate to provide an initial guess for t let csamp = mSampleValues[currentSample]; let dst = (aX - csamp) / (mSampleValues[currentSample + 1] - csamp); let guessForT = intervalStart + dst * kSampleStepSize; // Check the slope to see what strategy to use. If the slope is too small // Newton-Raphson iteration won't converge on a root so we use bisection // instead. let initialSlope = getSlope(guessForT, mX1, mX2); if (initialSlope >= NEWTON_MIN_SLOPE) { return newtonRaphsonIterate(aX, guessForT, mX1, mX2); } else if (initialSlope == 0.0) { return guessForT; } else { return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize); } } fn newtonRaphsonIterate(aX: float, aGuessT: float, mX1: float, mX2: float) { // Refine guess with Newton-Raphson iteration for (let i = 0; i < NEWTON_ITERATIONS; i++) { // We're trying to find where f(t) = aX, // so we're actually looking for a root for: CalcBezier(t) - aX let currentX = calcBezier(aGuessT, mX1, mX2) - aX; let currentSlope = getSlope(aGuessT, mX1, mX2); if (currentSlope == 0.0) return aGuessT; aGuessT -= currentX / currentSlope; } return aGuessT; } fn binarySubdivide(aX: float, aA: float, aB: float) { let currentX = 0.0; let currentT = 0.0; let i = 0; while (true) { i++; if (abs(currentX) > SUBDIVISION_PRECISION && i < SUBDIVISION_MAX_ITERATIONS) { currentT = aA + (aB - aA) / 2.0; currentX = CalcBezier(currentT, mX1, mX2) - aX; if (currentX > 0.0) { aB = currentT; } else { aA = currentT; } }else{ break; } } return currentT; } pub struct bezier {}; impl bezier { pub fn cubic2(a: float2, b: float2, c: float2, d: float2, t: float) -> float2 { return (1.0 - t)**3 * a + 3.0 * (1.0 - t)**2 * t * b + 3.0 * (1.0 - t) * t**2 * c + t**3 * d; } pub fn cubic3(a: float3, b: float3, c: float3, d: float3, t: float) -> float3 { return (1.0 - t)**3 * a + 3.0 * (1.0 - t)**2 * t * b + 3.0 * (1.0 - t) * t**2 * c + t**3 * d; } pub fn quadratic2(a: float2, b: float2, c: float2, t: float) -> float2 { return (1.0 - t)**2 * a + 2.0 * (1.0 - t) * t * b + t**2 * c; } pub fn quadratic3(a: float3, b: float3, c: float3, t: float) -> float3 { return (1.0 - t)**2 * a + 2.0 * (1.0 - t) * t * b + t**2 * c; } /** * 3d triangle patch evaulation with barycentric coordinates. */ pub fn patch(a: float3, ab: float3, b: float3, bc: float3, c: float3, ca: float3, barycentricT: float3) { return 1.f * c * (s * s) + 2.f * bc * s * t + 2.f * ca * s * u + 1.f * b * (t * t) + 2.f * ab * t * u + 1.f * a * (u * u); } pub fn easing(controlA: float2, controlB: float2, t: float) -> float { return calcBezier(getTForX(t, controlA.x, controlB.x), controlA.y, controlB.y); } } /** * Provides space related utilities like z-order curves and quadtrees. */ pub struct spatial {}; impl spatial { pub fn cantorPair(v: int2) -> int { return ((v.x + v.y) * (v.x + v.y + 1)) / 2 + v.y; } pub fn cantorUnpair(v: int) -> int2 { let w = floor((sqrt(8.0 * v + 1.0) - 1.0) / 2.0); let t = (w * w + w) / 2.0; let y = v - t; let x = w - y; return int2(x, y); } pub fn hilbertRotate(n: int, b: int2, r: int2) -> int2 { let x = b.x; let y = b.y; if (r.y == 0) { if (r.x == 1) { x = n-1 - x; y = n-1 - y; } let t = x; x = y; y = t; } return int2(x, y); } pub fn hilbertUncurve(n: int, v: int2) -> int { let x = v.x; let y = v.y; let rx: int = 0; let ry: int = 0; let s: int = 0; let d: int = 0; for (s=n/2; s>0; s/=2) { rx = ((x & s) > 0) ? 1 : 0; ry = ((y & s) > 0) ? 1 : 0; d += s * s * ((3 * rx) ^ ry); let o = spatial::hilbertRotate(n, (x, y), (rx, ry)); x = o.x; y = o.y; } return d; } pub fn hilbertCurve(n: int, v: int) -> int2 { let rx: int = 0; let ry: int = 0; let t = v; let x = 0; let y = 0; for (let s: int = 1; s < n; s *= 2) { rx = 1 & (t/2); ry = 1 & (t ^ rx); let o = spatial::hilbertRotate(s, (x, y), (rx, ry)); x = o.x; y = o.y; x += s * rx; y += s * ry; t /= 4; } return int2(x, y); } pub fn mortonDecode(p: uint) -> uint2 { return uint2(reverseMortonCode2(p), reverseMortonCode2(p >> 1u)); } pub fn mortonEncode(p: uint2) -> uint { return uint(mortonCode2(p.x) | (mortonCode2(p.y) << 1u)); } } pub fn mortonCode2(x: uint) -> uint { x = x & 0x0000ffffu; x = (x ^ (x << 8)) & 0x00ff00ffu; x = (x ^ (x << 4)) & 0x0f0f0f0fu; x = (x ^ (x << 2)) & 0x33333333u; x = (x ^ (x << 1)) & 0x55555555u; return x; } pub fn randColor(seed: float) -> float4 { return float4(rand2((seed,5)), rand2((seed, 1)), rand2((seed, 4)), 1); } pub fn randColor2(seed: float2) -> float4 { return float4(rand3((seed,5)), rand3((seed, 1)), rand3((seed, 4)), 1); } pub fn reverseMortonCode2(x: uint) -> uint { x = x & 0x55555555u; x = (x ^ (x >> 1)) & 0x33333333u; x = (x ^ (x >> 2)) & 0x0f0f0f0fu; x = (x ^ (x >> 4)) & 0x00ff00ffu; x = (x ^ (x >> 8)) & 0x0000ffffu; return x; } pub struct noise {}; const PERLIN_YWRAPB = 4; const PERLIN_YWRAP = 1 << PERLIN_YWRAPB; const PERLIN_ZWRAPB = 8; const PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB; const PERLIN_SIZE = 4095; let perlin_octaves = 4; // default to medium smooth let perlin_amp_falloff = 0.5; // 50% reduction/octave fn scaled_cosine(i: float) -> float { return 0.5 * (1.0 - cos(i * PI)); } let perlin = buffer(PERLIN_SIZE + 1); for (let i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = rand(i); } // // By Morgan McGuire @morgan3d, http://graphicscodex.com // fn hash(n: float) -> float { return frac(sin(n) * 1e4); } fn hash2(p: float2) -> float { return frac(1e4 * sin(17.0 * p.x + p.y * 0.1) * (0.1 + abs(sin(p.y * 13.0 + p.x)))); } fn hash3(p: float3) -> float { let h = dot(p, float3(127.1, 311.7, 74.7)); return frac(sin(h) * 43758.5453123); } impl noise { pub fn gaussian3(v: float3) -> float { let p = v; let a = floor(p); let d = p - a; d = d * d * (3.0 - 2.0 * d); let b = a.xxyy + float4(0.0, 1.0, 0.0, 1.0); let k1 = perm(b.xyxy); let k2 = perm(k1.xyxy + b.zzww); let c = k2 + a.zzzz; let k3 = perm(c); let k4 = perm(c + 1.0); let o1 = frac(k3 * (1.0 / 41.0)); let o2 = frac(k4 * (1.0 / 41.0)); let o3 = o2 * d.z + o1 * (1.0 - d.z); let o4 = o3.yw * d.x + o3.xz * (1.0 - d.x); return o4.y * d.y + o4.x * (1.0 - d.y); } pub fn gaussian2(v: float2) -> float { return noise::gaussian3((v, 0)); } pub fn noise1(x: float) { let i = floor(x); let f = frac(x); let u = f * f * (3.0 - 2.0 * f); return lerp(hash(i), hash(i + 1.0), u); } pub fn noise2(x: float2) -> float { let i = floor(x); let f = frac(x); // Four corners in 2D of a tile let a = hash2(i); let b = hash2(i + float2(1.0, 0.0)); let c = hash2(i + float2(0.0, 1.0)); let d = hash2(i + float2(1.0, 1.0)); // Simple 2D lerp using smoothstep envelope between the values. // return float3(lerp(lerp(a, b, smoothstep(0.0, 1.0, f.x)), // lerp(c, d, smoothstep(0.0, 1.0, f.x)), // smoothstep(0.0, 1.0, f.y))); // Same code, with the clamps in smoothstep and common subexpressions // optimized away. let u = f * f * (3.0 - 2.0 * f); return lerp(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y; } pub fn fmb1(x: float) -> float { let v = 0.0; let a = 0.5; let shift = float(100); for (let i = 0; i < 5; i++) { v += a * noise::noise1(x); x = x * 2.0 + shift; a *= 0.5; } return v; } pub fn fbm2(x: float2) -> float { let v = 0.0; let a = 0.5; let shift = float2(100.xy); // Rotate to reduce axial bias let rot = float2x2(cos(0.5), sin(0.5), -sin(0.5), cos(0.50)); for (let i = 0; i < 5; i++) { v += a * noise::noise2(x); x = rot * x * 2.0 + shift; a *= 0.5; } return v; } pub fn fbm3(x: float3) -> float { let v = 0.0; let a = 0.5; let shift = float3(100.xyz); for (let i = 0; i < 5; i++) { v += a * noise::noise3(x); x = x * 2.0 + shift; a *= 0.5; } return v; } pub fn noise3(x: float3) -> float { const step = float3(110, 241, 171); let i = floor(x); let f = frac(x); // For performance, compute the base input to a 1D hash from the integer part of the argument and the // incremental change to the 1D based on the 3D -> 1D wrapping let n = dot(i, step); let u = f * f * (3.0 - 2.0 * f); return lerp(lerp(lerp( hash(n + dot(step, float3(0, 0, 0))), hash(n + dot(step, float3(1, 0, 0))), u.x), lerp( hash(n + dot(step, float3(0, 1, 0))), hash(n + dot(step, float3(1, 1, 0))), u.x), u.y), lerp(lerp( hash(n + dot(step, float3(0, 0, 1))), hash(n + dot(step, float3(1, 0, 1))), u.x), lerp( hash(n + dot(step, float3(0, 1, 1))), hash(n + dot(step, float3(1, 1, 1))), u.x), u.y), u.z); } pub fn simplex2(v: float2) -> float { let C = float4(0.211324865405187, 0.366025403784439, -0.577350269189626, 0.024390243902439); let i = floor(v + dot(v, C.yy)); let x0 = v - i + dot(i, C.xx); let xv = step(x0.y, x0.x); let i1 = float2(xv, 1.0 - xv); let x1 = x0 + C.xx - i1; let x2 = x0 + C.zz; i = mod289_2(i); let p = permute( permute(float3(0.0, i1.y, 1.0) + i.y) + float3(0.0, i1.x, 1.0) + i.x); let m = max(0.5.xyz - float3(dot(x0, x0), dot(x1, x1), dot(x2, x2)), 0.0); m = m * m; m = m * m; let x = 2.0 * frac(p * C.www) - 1.0; let h = abs(x) - 0.5; let ox = floor(x + 0.5); let a0 = x - ox; // Normalise gradients implicitly by scaling m m *= taylorInvSqrt(a0 * a0 + h * h); // Compute final noise value at P let g = float3( a0.x * x0.x + h.x * x0.y, a0.y * x1.x + h.y * x1.y, a0.z * x2.x + h.z * x2.y ); return 130.0 * dot(m, g); } pub fn perlin2(v: float2) -> float { let x = v.x; let y = v.y; let z = 0.0; if (x < 0) { x = -x; } if (y < 0) { y = -y; } if (z < 0) { z = -z; } let xi = int(floor(x)), yi = int(floor(y)), zi = int(floor(z)); let xf = x - xi; let yf = y - yi; let zf = z - zi; let rxf = 0.0, ryf = 0.0; let r = 0.0; let ampl = 0.5; let n1= 0.0, n2 = 0.0, n3 = 0.0; for (let o = 0; o < perlin_octaves; o++) { let of1: int = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); rxf = scaled_cosine(xf); ryf = scaled_cosine(yf); n1 = perlin[of1 & PERLIN_SIZE]; n1 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n1); n2 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n2 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2); n1 += ryf * (n2 - n1); of1 += PERLIN_ZWRAP; n2 = perlin[of1 & PERLIN_SIZE]; n2 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n2); n3 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n3 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3); n2 += ryf * (n3 - n2); n1 += scaled_cosine(zf) * (n2 - n1); r += n1 * ampl; ampl *= perlin_amp_falloff; xi = xi << 1; xf *= 2.0; yi = yi << 1; yf *= 2.0; zi = zi << 1; zf *= 2.0; if (xf >= 1.0) { xi++; xf-= 1.0; } if (yf >= 1.0) { yi++; yf-= 1.0; } if (zf >= 1.0) { zi++; zf-= 1.0; } } return r; } pub fn perlin3(v: float3) -> float { let x = v.x; let y = v.y; let z = v.z; if (x < 0) { x = -x; } if (y < 0) { y = -y; } if (z < 0) { z = -z; } let xi = int(floor(x)), yi = int(floor(y)), zi = int(floor(z)); let xf = x - xi; let yf = y - yi; let zf = z - zi; let rxf = 0.0, ryf = 0.0; let r = 0.0; let ampl = 0.5; let n1= 0.0, n2 = 0.0, n3 = 0.0; for (let o = 0; o < perlin_octaves; o++) { let of1: int = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); rxf = scaled_cosine(xf); ryf = scaled_cosine(yf); n1 = perlin[of1 & PERLIN_SIZE]; n1 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n1); n2 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n2 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2); n1 += ryf * (n2 - n1); of1 += PERLIN_ZWRAP; n2 = perlin[of1 & PERLIN_SIZE]; n2 += rxf * (perlin[(of1 + 1) & PERLIN_SIZE] - n2); n3 = perlin[(of1 + PERLIN_YWRAP) & PERLIN_SIZE]; n3 += rxf * (perlin[(of1 + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3); n2 += ryf * (n3 - n2); n1 += scaled_cosine(zf) * (n2 - n1); r += n1 * ampl; ampl *= perlin_amp_falloff; xi = xi << 1; xf *= 2.0; yi = yi << 1; yf *= 2.0; zi = zi << 1; zf *= 2.0; if (xf >= 1.0) { xi++; xf-= 1.0; } if (yf >= 1.0) { yi++; yf-= 1.0; } if (zf >= 1.0) { zi++; zf-= 1.0; } } return r; } /** * Returns 3 values: distance to closest cell, random value of closest cell, distance to closest edge. */ pub fn voronoi2(v: float2) -> float3 { let n = floor(v); let minDist = 10.0; let toClose = 0.0.xy; let closestCell = 0.0.xy; for (let j = -1; j <= 1; j++) { for (let i = -1; i <= 1; i++) { let cell = n + float2(i, j); let cellPos = cell + hash2(cell); let toCell = cellPos - v; let dst = length(toCell); if (dst < minDist) { minDist = dst; toClose = toCell; closestCell = cell; } } } let minEdge = 10.0; for (let j = -1; j <= 1; j++) { for (let i = -1; i <= 1; i++) { let cell = n + float2(i, j); let cellPos = cell + hash2(cell); let toCell = cellPos - v; let diff = abs(closestCell - cell); let isClosest = diff.x + diff.y < 0.1; if (!isClosest) { let toCenter = (toClose + toCell) * 0.5; let cellDiff = normalize(toCell - toClose); let edge = dot(toCenter, cellDiff); minEdge = min(minEdge, edge); } } } let random = hash2(closestCell); return float3(minDist, random, minEdge); } pub fn simplex3(v: float3) -> float { let C = float4(0.138196601125011, 0.276393202250021, 0.414589803375032, -0.447213595499958); let i = floor(v + dot(v, C.yyy)); let x0 = v - i + dot(i, C.xxx); let g = step(x0.yzx, x0.xyz); let l = 1.0 - g; let i1 = min(g.xyz, l.zxy); let i2 = max(g.xyz, l.zxy); let x1 = x0 - i1 + 1.0 * C.xxx; let x2 = x0 - i2 + 2.0 * C.xxx; let x3 = x0 - 1. + 3.0 * C.xxx; i = mod289_3(i); let p = permute( permute( permute(i.z + float3(0.0, i1.z, i2.z)) + i.y + float3(0.0, i1.y, i2.y)) + i.x + float3(0.0, i1.x, i2.x)); let m = max(0.5 - float3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0); m = m * m; m = m * m; let x = 2.0 * frac(p * C.www) - 1.0; let h = abs(x) - 0.5; let ox = floor(x + 0.5); let a0 = x - ox; // Normalise gradients implicitly by scaling m // Approximation of: m *= inversesqrt(a0 * a0 + h * h); m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h); // Compute final noise value at P let g2 = float3( a0.x * x0.x + h.x * x0.y, a0.y * x1.x + h.y * x1.y, a0.z * x2.x + h.z * x2.y ); return 130.0 * dot(m, g2); } } fn mod289_1(x: float) -> float { return x - floor(x * (1.0 / 289.0)) * 289.0;} fn mod289_4(x: float4) -> float4 { return x - floor(x * (1.0 / 289.0)) * 289.0;} fn perm(x: float4) -> float4 { return mod289_4(((x * 34.0) + 1.0) * x);} fn mod289_3(x: float3) -> float3 { return x - floor(x * (1.0 / 289.0)) * 289.0; } fn mod289_2(x: float2) -> float2 { return x - floor(x * (1.0 / 289.0)) * 289.0; } fn permute(x: float3) -> float3 { return mod289_3((x * 34.0 + 1.0) * x); } fn taylorInvSqrt(r: float3) -> float3 { return 1.79284291400159 - 0.85373472095314 * r; } pub struct matrix {} impl matrix { pub fn lookAt(from: float3, to: float3, up: float3) -> float4x4 { let zAxis = normalize(from - to); let xAxis = normalize(cross(up, zAxis)); let yAxis = normalize(cross(zAxis, xAxis)); let dst = float4x4(); dst[0][0] = xAxis.x; dst[0][1] = yAxis.x; dst[0][2] = zAxis.x; dst[0][3] = 0; dst[1][0] = xAxis.y; dst[1][1] = yAxis.y; dst[1][2] = zAxis.y; dst[1][3] = 0; dst[2][0] = xAxis.z; dst[2][1] = yAxis.z; dst[2][2] = zAxis.z; dst[2][3] = 0; dst[3][0] = -(xAxis.x * from.x + xAxis.y * from.y + xAxis.z * from.z); dst[3][1] = -(yAxis.x * from.x + yAxis.y * from.y + yAxis.z * from.z); dst[3][2] = -(zAxis.x * from.x + zAxis.y * from.y + zAxis.z * from.z); dst[3][3] = 1; return dst; let forward = normalize(from - to); let right = normalize(cross(up, forward)); let newup = cross(forward, right); let m = float4x4(); m[0][0] = right.x, m[0][1] = right.y, m[0][2] = right.z; m[1][0] = newup.x, m[1][1] = newup.y, m[1][2] = newup.z; m[2][0] = forward.x, m[2][1] = forward.y, m[2][2] = forward.z; m[3][0] = from.x, m[3][1] = from.y, m[3][2] = from.z; return m; } pub fn perspective(fov: float, aspect: float, near: float, far: float) -> float4x4 { // set the basic projection matrix // let scale = 1.0 / tan(fov * 0.5 * PI / 180); // let M = float4x4(); // M[0][0] = scale; //scale the x coordinates of the projected point // M[1][1] = scale * aspect; //scale the y coordinates of the projected point // M[2][2] = -far / (far - near); //used to remap z to [0,1] // M[3][2] = -far * near / (far - near); //used to remap z [0,1] // M[2][3] = -1; //set w = -z // M[3][3] = 0; //return M; let fovRad = radians(fov); let tanFov = tan( fovRad * 0.5 ); let matrx = float4x4( 1.0 / (tanFov * aspect), 0, 0, 0, 0, 1.0 / tanFov, 0, 0, 0, 0, -((far + near)/(far - near)), -1, 0, 0, -((2*(near*far))/(far - near)), 0 ); return matrx; } pub fn perspectiveReverseZ(fov: float, aspect: float, near: float) -> float4 { // let scale = 1.0 / tan(fov * 0.5 * PI / 180); // let far = 10000000.0; // let M = float4x4(); // M[0][0] = scale; //scale the x coordinates of the projected point // M[1][1] = scale * aspect; //scale the y coordinates of the projected point // M[2][2] = (-far / (far - near)) * -1; //used to remap z to [0,1] // M[3][2] = -far * near / (far - near); //used to remap z [0,1] // M[2][3] = 0; //set w = -z // M[3][3] = 0; // return M; let matrx = float4x4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 1, 1 ) * matrix::perspective(fov, aspect, near, 10000000.0); return matrx; } } /** * Uses Super Sampling Anti Aliasing to smooth out the image. */ pub fn screenAA(inScreenPos: float2, gridSize: int, func: (screenPos: float2) -> float4) { let weightSum = 0.0; let accumulatedColor = float4(0, 0, 0, 0); for (let y = 0; y < gridSize; y++) { for (let x = 0; x < gridSize; x++) { let offset = float2( (x + 0.5 - gridSize * 0.5) / gridSize, (y + 0.5 - gridSize * 0.5) / gridSize ); let weight = exp(-dot(offset, offset) * 5); // Gaussian weight accumulatedColor += func(inScreenPos + offset) * weight; weightSum += weight; } } return accumulatedColor / weightSum; } // Color conversion helpers // A color = float4 containing rgba values in the range [0, 1] // All functions have an extra alpha functon and a reverse // i.e. hsl, hsla, hslFromColor, hslaFromColor // fn hsl(v: float3) -> float4 pub fn hsl(v: float3) -> float4 { return hsla((v, 1)); } pub fn hsla(v: float4) -> float4 { let h = v.x; let s = v.y; let l = v.z; let a = v.w; let c = (1 - abs(2 * l - 1)) * s; let x = c * (1 - abs(((h / 60) % 2) - 1)); let m = l - c / 2; let r = 0.0; let g = 0.0; let b = 0.0; if (h < 60) { r = c; g = x; b = 0; } else if (h < 120) { r = x; g = c; b = 0; } else if (h < 180) { r = 0; g = c; b = x; } else if (h < 240) { r = 0; g = x; b = c; } else if (h < 300) { r = x; g = 0; b = c; } else { r = c; g = 0; b = x; } return float4(r + m, g + m, b + m, a); } pub fn hslFromColor(c: float4) -> float3 { let r = c.r; let g = c.g; let b = c.b; let a = c.a; let mx = max(r, max(g, b)); let mn = min(r, min(g, b)); let h = 0.0; let s = 0.0; let l = (mx + mn) / 2; if (mx == mn) { h = 0; s = 0; } else { let d = mx - mn; s = (l > 0.5) ? d / (2 - mx - mn) : d / (mx + mn); if (mx == r) { h = (g - b) / d + ((g < b) ? 6:0); } else if (mx == g) { h = (b - r) / d + 2; } else if (mx == b) { h = (r - g) / d + 4; } h /= 6; } return float3(h * 360, s, l); } pub fn hslaFromColor(c: float4) -> float4 { let hsl = hslFromColor(c); return float4(hsl, c.a); } pub fn hsv(v: float3) -> float4 { return hsva((v, 1)); } pub fn hsva(val: float4) -> float4 { let h = val.x; let s = val.y; let v = val.z; let a = val.w; let c = v * s; let x = c * (1 - abs(mod(h / 60, 2) - 1)); let m = v - c; let r = 0.0; let g = 0.0; let b = 0.0; if (h < 60) { r = c; g = x; b = 0; } else if (h < 120) { r = x; g = c; b = 0; } else if (h < 180) { r = 0; g = c; b = x; } else if (h < 240) { r = 0; g = x; b = c; } else if (h < 300) { r = x; g = 0; b = c; } else { r = c; g = 0; b = x; } return float4(r + m, g + m, b + m, a); } pub fn hsvFromColor(c: float4) -> float3 { let r = c.r; let g = c.g; let b = c.b; let mx = max(r, max(g, b)); let mn = min(r, min(g, b)); let h = 0.0; let s = 0.0; let v = mx; let d = mx - mn; s = (mx == 0) ? 0 : d / mx ; if (mx == mn) { h = 0; } else { if (mx == r) { h = (g - b) / d + ((g < b) ? 6 : 0 ); } else if (mx == g) { h = (b - r) / d + 2; } else if (mx == b) { h = (r - g) / d + 4; } h /= 6; } return float3(h * 360, s, v); } pub fn hsvaFromColor(c: float4) -> float4 { let hsv = hsvFromColor(c); return float4(hsv, c.a); } pub fn rgb(v: float3) -> float4 { return float4(v / 255.0, 1); } pub fn rgba(v: float4) -> float4 { return float4(v / 255.0); } pub fn rgbFromColor(c: float4) -> float3 { return c.rgb * 255.0; } pub fn rgbaFromColor(c: float4) -> float4 { return c * 255.0; } pub fn cmyk(v: float4) -> float4 { let c = v.r; let m = v.g; let y = v.b; let k = v.a; let r = 1 - min(1, c * (1 - k) + k); let g = 1 - min(1, m * (1 - k) + k); let b = 1 - min(1, y * (1 - k) + k); return float4(r, g, b, 1); } pub fn cmykFromColor(c: float4) -> float4 { let r = c.r; let g = c.g; let b = c.b; let k = 1 - max(r, max(g, b)); let c1 = (1 - r - k) / (1 - k); let m = (1 - g - k) / (1 - k); let y = (1 - b - k) / (1 - k); return float4(c1, m, y, k); } pub fn hex(v: int) -> float4 { let r: float = (v >> 16) & 0xFF; let g: float = (v >> 8) & 0xFF; let b: float = v & 0xFF; return float4(r / 255.0, g / 255.0, b / 255.0, 1.0); } pub fn hexFromColor(c: float4) -> int { let r = int(c.r * 255.0); let g = int(c.g * 255.0); let b = int(c.b * 255.0); return (r << 16) | (g << 8) | b; } /** * Returns sin remapped to [0, 1] */ pub fn sin1(v: float) -> float { return (sin(v) + 1) * 0.5; } /** * Returns cos remapped to [0, 1] */ pub fn cos1(v: float) -> float { return (cos(v) + 1) * 0.5; } /** * Returns tan remapped to [0, 1] */ pub fn tan1(v: float) -> float { return (tan(v) + 1) * 0.5; } pub fn remap(v: float, low1: float, high1: float, low2: float, high2: float) -> float { return low2 + (v - low1) * (high2 - low2) / (high1 - low1); } pub fn remap1(v: float, low: float, high: float) -> float { return remap(v, low, high, 0, 1); } pub struct color { static slate50: float4 = float4(0.9725490196078431, 0.9803921568627451, 0.9882352941176471, 1); static slate100: float4 = float4(0.9450980392156862, 0.9607843137254902, 0.9764705882352941, 1); static slate200: float4 = float4(0.8862745098039215, 0.9098039215686274, 0.9411764705882353, 1); static slate300: float4 = float4(0.796078431372549, 0.8352941176470589, 0.8823529411764706, 1); static slate400: float4 = float4(0.5803921568627451, 0.6392156862745098, 0.7215686274509804, 1); static slate500: float4 = float4(0.39215686274509803, 0.4549019607843137, 0.5450980392156862, 1); static slate600: float4 = float4(0.2784313725490196, 0.3333333333333333, 0.4117647058823529, 1); static slate700: float4 = float4(0.2, 0.2549019607843137, 0.3333333333333333, 1); static slate800: float4 = float4(0.11764705882352941, 0.1607843137254902, 0.23137254901960785, 1); static slate900: float4 = float4(0.058823529411764705, 0.09019607843137255, 0.16470588235294117, 1); static slate950: float4 = float4(0.00784313725490196, 0.023529411764705882, 0.09019607843137255, 1); static gray50: float4 = float4(0.9764705882352941, 0.9803921568627451, 0.984313725490196, 1); static gray100: float4 = float4(0.9529411764705882, 0.9568627450980393, 0.9647058823529412, 1); static gray200: float4 = float4(0.8980392156862745, 0.9058823529411765, 0.9215686274509803, 1); static gray300: float4 = float4(0.8196078431372549, 0.8352941176470589, 0.8588235294117647, 1); static gray400: float4 = float4(0.611764705882353, 0.6392156862745098, 0.6862745098039216, 1); static gray500: float4 = float4(0.4196078431372549, 0.4470588235294118, 0.5019607843137255, 1); static gray600: float4 = float4(0.29411764705882354, 0.3333333333333333, 0.38823529411764707, 1); static gray700: float4 = float4(0.21568627450980393, 0.2549019607843137, 0.3176470588235294, 1); static gray800: float4 = float4(0.12156862745098039, 0.1607843137254902, 0.21568627450980393, 1); static gray900: float4 = float4(0.06666666666666667, 0.09411764705882353, 0.15294117647058825, 1); static gray950: float4 = float4(0.011764705882352941, 0.027450980392156862, 0.07058823529411765, 1); static zinc50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9803921568627451, 1); static zinc100: float4 = float4(0.9568627450980393, 0.9568627450980393, 0.9607843137254902, 1); static zinc200: float4 = float4(0.8941176470588236, 0.8941176470588236, 0.9058823529411765, 1); static zinc300: float4 = float4(0.8313725490196079, 0.8313725490196079, 0.8470588235294118, 1); static zinc400: float4 = float4(0.6313725490196078, 0.6313725490196078, 0.6666666666666666, 1); static zinc500: float4 = float4(0.44313725490196076, 0.44313725490196076, 0.47843137254901963, 1); static zinc600: float4 = float4(0.3215686274509804, 0.3215686274509804, 0.3568627450980392, 1); static zinc700: float4 = float4(0.24705882352941178, 0.24705882352941178, 0.27450980392156865, 1); static zinc800: float4 = float4(0.15294117647058825, 0.15294117647058825, 0.16470588235294117, 1); static zinc900: float4 = float4(0.09411764705882353, 0.09411764705882353, 0.10588235294117647, 1); static zinc950: float4 = float4(0.03529411764705882, 0.03529411764705882, 0.043137254901960784, 1); static neutral50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9803921568627451, 1); static neutral100: float4 = float4(0.9607843137254902, 0.9607843137254902, 0.9607843137254902, 1); static neutral200: float4 = float4(0.8980392156862745, 0.8980392156862745, 0.8980392156862745, 1); static neutral300: float4 = float4(0.8313725490196079, 0.8313725490196079, 0.8313725490196079, 1); static neutral400: float4 = float4(0.6392156862745098, 0.6392156862745098, 0.6392156862745098, 1); static neutral500: float4 = float4(0.45098039215686275, 0.45098039215686275, 0.45098039215686275, 1); static neutral600: float4 = float4(0.3215686274509804, 0.3215686274509804, 0.3215686274509804, 1); static neutral700: float4 = float4(0.25098039215686274, 0.25098039215686274, 0.25098039215686274, 1); static neutral800: float4 = float4(0.14901960784313725, 0.14901960784313725, 0.14901960784313725, 1); static neutral900: float4 = float4(0.09019607843137255, 0.09019607843137255, 0.09019607843137255, 1); static neutral950: float4 = float4(0.0392156862745098, 0.0392156862745098, 0.0392156862745098, 1); static stone50: float4 = float4(0.9803921568627451, 0.9803921568627451, 0.9764705882352941, 1); static stone100: float4 = float4(0.9607843137254902, 0.9607843137254902, 0.9568627450980393, 1); static stone200: float4 = float4(0.9058823529411765, 0.8980392156862745, 0.8941176470588236, 1); static stone300: float4 = float4(0.8392156862745098, 0.8274509803921568, 0.8196078431372549, 1); static stone400: float4 = float4(0.6588235294117647, 0.6352941176470588, 0.6196078431372549, 1); static stone500: float4 = float4(0.47058823529411764, 0.44313725490196076, 0.4235294117647059, 1); static stone600: float4 = float4(0.3411764705882353, 0.3254901960784314, 0.3058823529411765, 1); static stone700: float4 = float4(0.26666666666666666, 0.25098039215686274, 0.23529411764705882, 1); static stone800: float4 = float4(0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1); static stone900: float4 = float4(0.10980392156862745, 0.09803921568627451, 0.09019607843137255, 1); static stone950: float4 = float4(0.047058823529411764, 0.0392156862745098, 0.03529411764705882, 1); static red50: float4 = float4(0.996078431372549, 0.9490196078431372, 0.9490196078431372, 1); static red100: float4 = float4(0.996078431372549, 0.8862745098039215, 0.8862745098039215, 1); static red200: float4 = float4(0.996078431372549, 0.792156862745098, 0.792156862745098, 1); static red300: float4 = float4(0.9882352941176471, 0.6470588235294118, 0.6470588235294118, 1); static red400: float4 = float4(0.9725490196078431, 0.44313725490196076, 0.44313725490196076, 1); static red500: float4 = float4(0.9372549019607843, 0.26666666666666666, 0.26666666666666666, 1); static red600: float4 = float4(0.8627450980392157, 0.14901960784313725, 0.14901960784313725, 1); static red700: float4 = float4(0.7254901960784313, 0.10980392156862745, 0.10980392156862745, 1); static red800: float4 = float4(0.6, 0.10588235294117647, 0.10588235294117647, 1); static red900: float4 = float4(0.4980392156862745, 0.11372549019607843, 0.11372549019607843, 1); static red950: float4 = float4(0.27058823529411763, 0.0392156862745098, 0.0392156862745098, 1); static orange50: float4 = float4(1, 0.9686274509803922, 0.9294117647058824, 1); static orange100: float4 = float4(1, 0.9294117647058824, 0.8352941176470589, 1); static orange200: float4 = float4(0.996078431372549, 0.8431372549019608, 0.6666666666666666, 1); static orange300: float4 = float4(0.9921568627450981, 0.7294117647058823, 0.4549019607843137, 1); static orange400: float4 = float4(0.984313725490196, 0.5725490196078431, 0.23529411764705882, 1); static orange500: float4 = float4(0.9764705882352941, 0.45098039215686275, 0.08627450980392157, 1); static orange600: float4 = float4(0.9176470588235294, 0.34509803921568627, 0.047058823529411764, 1); static orange700: float4 = float4(0.7607843137254902, 0.2549019607843137, 0.047058823529411764, 1); static orange800: float4 = float4(0.6039215686274509, 0.20392156862745098, 0.07058823529411765, 1); static orange900: float4 = float4(0.48627450980392156, 0.17647058823529413, 0.07058823529411765, 1); static orange950: float4 = float4(0.2627450980392157, 0.0784313725490196, 0.027450980392156862, 1); static amber50: float4 = float4(1, 0.984313725490196, 0.9215686274509803, 1); static amber100: float4 = float4(0.996078431372549, 0.9529411764705882, 0.7803921568627451, 1); static amber200: float4 = float4(0.9921568627450981, 0.9019607843137255, 0.5411764705882353, 1); static amber300: float4 = float4(0.9882352941176471, 0.8274509803921568, 0.30196078431372547, 1); static amber400: float4 = float4(0.984313725490196, 0.7490196078431373, 0.1411764705882353, 1); static amber500: float4 = float4(0.9607843137254902, 0.6196078431372549, 0.043137254901960784, 1); static amber600: float4 = float4(0.8509803921568627, 0.4666666666666667, 0.023529411764705882, 1); static amber700: float4 = float4(0.7058823529411765, 0.3254901960784314, 0.03529411764705882, 1); static amber800: float4 = float4(0.5725490196078431, 0.25098039215686274, 0.054901960784313725, 1); static amber900: float4 = float4(0.47058823529411764, 0.20784313725490197, 0.058823529411764705, 1); static amber950: float4 = float4(0.27058823529411763, 0.10196078431372549, 0.011764705882352941, 1); static yellow50: float4 = float4(0.996078431372549, 0.9882352941176471, 0.9098039215686274, 1); static yellow100: float4 = float4(0.996078431372549, 0.9764705882352941, 0.7647058823529411, 1); static yellow200: float4 = float4(0.996078431372549, 0.9411764705882353, 0.5411764705882353, 1); static yellow300: float4 = float4(0.9921568627450981, 0.8784313725490196, 0.2784313725490196, 1); static yellow400: float4 = float4(0.9803921568627451, 0.8, 0.08235294117647059, 1); static yellow500: float4 = float4(0.9176470588235294, 0.7019607843137254, 0.03137254901960784, 1); static yellow600: float4 = float4(0.792156862745098, 0.5411764705882353, 0.01568627450980392, 1); static yellow700: float4 = float4(0.6313725490196078, 0.3843137254901961, 0.027450980392156862, 1); static yellow800: float4 = float4(0.5215686274509804, 0.30196078431372547, 0.054901960784313725, 1); static yellow900: float4 = float4(0.44313725490196076, 0.24705882352941178, 0.07058823529411765, 1); static yellow950: float4 = float4(0.25882352941176473, 0.12549019607843137, 0.023529411764705882, 1); static lime50: float4 = float4(0.9686274509803922, 0.996078431372549, 0.9058823529411765, 1); static lime100: float4 = float4(0.9254901960784314, 0.9882352941176471, 0.796078431372549, 1); static lime200: float4 = float4(0.8509803921568627, 0.9764705882352941, 0.615686274509804, 1); static lime300: float4 = float4(0.7450980392156863, 0.9490196078431372, 0.39215686274509803, 1); static lime400: float4 = float4(0.6392156862745098, 0.9019607843137255, 0.20784313725490197, 1); static lime500: float4 = float4(0.5176470588235295, 0.8, 0.08627450980392157, 1); static lime600: float4 = float4(0.396078431372549, 0.6392156862745098, 0.050980392156862744, 1); static lime700: float4 = float4(0.30196078431372547, 0.48627450980392156, 0.058823529411764705, 1); static lime800: float4 = float4(0.24705882352941178, 0.3843137254901961, 0.07058823529411765, 1); static lime900: float4 = float4(0.21176470588235294, 0.3254901960784314, 0.0784313725490196, 1); static lime950: float4 = float4(0.10196078431372549, 0.1803921568627451, 0.0196078431372549, 1); static green50: float4 = float4(0.9411764705882353, 0.9921568627450981, 0.9568627450980393, 1); static green100: float4 = float4(0.8627450980392157, 0.9882352941176471, 0.9058823529411765, 1); static green200: float4 = float4(0.7333333333333333, 0.9686274509803922, 0.8156862745098039, 1); static green300: float4 = float4(0.5254901960784314, 0.9372549019607843, 0.6745098039215687, 1); static green400: float4 = float4(0.2901960784313726, 0.8705882352941177, 0.5019607843137255, 1); static green500: float4 = float4(0.13333333333333333, 0.7725490196078432, 0.3686274509803922, 1); static green600: float4 = float4(0.08627450980392157, 0.6392156862745098, 0.2901960784313726, 1); static green700: float4 = float4(0.08235294117647059, 0.5019607843137255, 0.23921568627450981, 1); static green800: float4 = float4(0.08627450980392157, 0.396078431372549, 0.20392156862745098, 1); static green900: float4 = float4(0.0784313725490196, 0.3254901960784314, 0.17647058823529413, 1); static green950: float4 = float4(0.0196078431372549, 0.1803921568627451, 0.08627450980392157, 1); static emerald50: float4 = float4(0.9254901960784314, 0.9921568627450981, 0.9607843137254902, 1); static emerald100: float4 = float4(0.8196078431372549, 0.9803921568627451, 0.8980392156862745, 1); static emerald200: float4 = float4(0.6549019607843137, 0.9529411764705882, 0.8156862745098039, 1); static emerald300: float4 = float4(0.43137254901960786, 0.9058823529411765, 0.7176470588235294, 1); static emerald400: float4 = float4(0.20392156862745098, 0.8274509803921568, 0.6, 1); static emerald500: float4 = float4(0.06274509803921569, 0.7254901960784313, 0.5058823529411764, 1); static emerald600: float4 = float4(0.0196078431372549, 0.5882352941176471, 0.4117647058823529, 1); static emerald700: float4 = float4(0.01568627450980392, 0.47058823529411764, 0.3411764705882353, 1); static emerald800: float4 = float4(0.023529411764705882, 0.37254901960784315, 0.27450980392156865, 1); static emerald900: float4 = float4(0.023529411764705882, 0.3058823529411765, 0.23137254901960785, 1); static emerald950: float4 = float4(0.00784313725490196, 0.17254901960784313, 0.13333333333333333, 1); static teal50: float4 = float4(0.9411764705882353, 0.9921568627450981, 0.9803921568627451, 1); static teal100: float4 = float4(0.8, 0.984313725490196, 0.9450980392156862, 1); static teal200: float4 = float4(0.6, 0.9647058823529412, 0.8941176470588236, 1); static teal300: float4 = float4(0.3686274509803922, 0.9176470588235294, 0.8313725490196079, 1); static teal400: float4 = float4(0.17647058823529413, 0.8313725490196079, 0.7490196078431373, 1); static teal500: float4 = float4(0.0784313725490196, 0.7215686274509804, 0.6509803921568628, 1); static teal600: float4 = float4(0.050980392156862744, 0.5803921568627451, 0.5333333333333333, 1); static teal700: float4 = float4(0.058823529411764705, 0.4627450980392157, 0.43137254901960786, 1); static teal800: float4 = float4(0.06666666666666667, 0.3686274509803922, 0.34901960784313724, 1); static teal900: float4 = float4(0.07450980392156863, 0.3058823529411765, 0.2901960784313726, 1); static teal950: float4 = float4(0.01568627450980392, 0.1843137254901961, 0.1803921568627451, 1); static cyan50: float4 = float4(0.9254901960784314, 0.996078431372549, 1, 1); static cyan100: float4 = float4(0.8117647058823529, 0.9803921568627451, 0.996078431372549, 1); static cyan200: float4 = float4(0.6470588235294118, 0.9529411764705882, 0.9882352941176471, 1); static cyan300: float4 = float4(0.403921568627451, 0.9098039215686274, 0.9764705882352941, 1); static cyan400: float4 = float4(0.13333333333333333, 0.8274509803921568, 0.9333333333333333, 1); static cyan500: float4 = float4(0.023529411764705882, 0.7137254901960784, 0.8313725490196079, 1); static cyan600: float4 = float4(0.03137254901960784, 0.5686274509803921, 0.6980392156862745, 1); static cyan700: float4 = float4(0.054901960784313725, 0.4549019607843137, 0.5647058823529412, 1); static cyan800: float4 = float4(0.08235294117647059, 0.3686274509803922, 0.4588235294117647, 1); static cyan900: float4 = float4(0.08627450980392157, 0.3058823529411765, 0.38823529411764707, 1); static cyan950: float4 = float4(0.03137254901960784, 0.2, 0.26666666666666666, 1); static sky50: float4 = float4(0.9411764705882353, 0.9764705882352941, 1, 1); static sky100: float4 = float4(0.8784313725490196, 0.9490196078431372, 0.996078431372549, 1); static sky200: float4 = float4(0.7294117647058823, 0.9019607843137255, 0.9921568627450981, 1); static sky300: float4 = float4(0.49019607843137253, 0.8274509803921568, 0.9882352941176471, 1); static sky400: float4 = float4(0.2196078431372549, 0.7411764705882353, 0.9725490196078431, 1); static sky500: float4 = float4(0.054901960784313725, 0.6470588235294118, 0.9137254901960784, 1); static sky600: float4 = float4(0.00784313725490196, 0.5176470588235295, 0.7803921568627451, 1); static sky700: float4 = float4(0.011764705882352941, 0.4117647058823529, 0.6313725490196078, 1); static sky800: float4 = float4(0.027450980392156862, 0.34901960784313724, 0.5215686274509804, 1); static sky900: float4 = float4(0.047058823529411764, 0.2901960784313726, 0.43137254901960786, 1); static sky950: float4 = float4(0.03137254901960784, 0.1843137254901961, 0.28627450980392155, 1); static blue50: float4 = float4(0.9372549019607843, 0.9647058823529412, 1, 1); static blue100: float4 = float4(0.8588235294117647, 0.9176470588235294, 0.996078431372549, 1); static blue200: float4 = float4(0.7490196078431373, 0.8588235294117647, 0.996078431372549, 1); static blue300: float4 = float4(0.5764705882352941, 0.7725490196078432, 0.9921568627450981, 1); static blue400: float4 = float4(0.3764705882352941, 0.6470588235294118, 0.9803921568627451, 1); static blue500: float4 = float4(0.23137254901960785, 0.5098039215686274, 0.9647058823529412, 1); static blue600: float4 = float4(0.1450980392156863, 0.38823529411764707, 0.9215686274509803, 1); static blue700: float4 = float4(0.11372549019607843, 0.3058823529411765, 0.8470588235294118, 1); static blue800: float4 = float4(0.11764705882352941, 0.25098039215686274, 0.6862745098039216, 1); static blue900: float4 = float4(0.11764705882352941, 0.22745098039215686, 0.5411764705882353, 1); static blue950: float4 = float4(0.09019607843137255, 0.1450980392156863, 0.32941176470588235, 1); static indigo50: float4 = float4(0.9333333333333333, 0.9490196078431372, 1, 1); static indigo100: float4 = float4(0.8784313725490196, 0.9058823529411765, 1, 1); static indigo200: float4 = float4(0.7803921568627451, 0.8235294117647058, 0.996078431372549, 1); static indigo300: float4 = float4(0.6470588235294118, 0.7058823529411765, 0.9882352941176471, 1); static indigo400: float4 = float4(0.5058823529411764, 0.5490196078431373, 0.9725490196078431, 1); static indigo500: float4 = float4(0.38823529411764707, 0.4, 0.9450980392156862, 1); static indigo600: float4 = float4(0.30980392156862746, 0.27450980392156865, 0.8980392156862745, 1); static indigo700: float4 = float4(0.2627450980392157, 0.2196078431372549, 0.792156862745098, 1); static indigo800: float4 = float4(0.21568627450980393, 0.18823529411764706, 0.6392156862745098, 1); static indigo900: float4 = float4(0.19215686274509805, 0.1803921568627451, 0.5058823529411764, 1); static indigo950: float4 = float4(0.11764705882352941, 0.10588235294117647, 0.29411764705882354, 1); static violet50: float4 = float4(0.9607843137254902, 0.9529411764705882, 1, 1); static violet100: float4 = float4(0.9294117647058824, 0.9137254901960784, 0.996078431372549, 1); static violet200: float4 = float4(0.8666666666666667, 0.8392156862745098, 0.996078431372549, 1); static violet300: float4 = float4(0.7686274509803922, 0.7098039215686275, 0.9921568627450981, 1); static violet400: float4 = float4(0.6549019607843137, 0.5450980392156862, 0.9803921568627451, 1); static violet500: float4 = float4(0.5450980392156862, 0.3607843137254902, 0.9647058823529412, 1); static violet600: float4 = float4(0.48627450980392156, 0.22745098039215686, 0.9294117647058824, 1); static violet700: float4 = float4(0.42745098039215684, 0.1568627450980392, 0.8509803921568627, 1); static violet800: float4 = float4(0.3568627450980392, 0.12941176470588237, 0.7137254901960784, 1); static violet900: float4 = float4(0.2980392156862745, 0.11372549019607843, 0.5843137254901961, 1); static violet950: float4 = float4(0.1803921568627451, 0.06274509803921569, 0.396078431372549, 1); static purple50: float4 = float4(0.9803921568627451, 0.9607843137254902, 1, 1); static purple100: float4 = float4(0.9529411764705882, 0.9098039215686274, 1, 1); static purple200: float4 = float4(0.9137254901960784, 0.8352941176470589, 1, 1); static purple300: float4 = float4(0.8470588235294118, 0.7058823529411765, 0.996078431372549, 1); static purple400: float4 = float4(0.7529411764705882, 0.5176470588235295, 0.9882352941176471, 1); static purple500: float4 = float4(0.6588235294117647, 0.3333333333333333, 0.9686274509803922, 1); static purple600: float4 = float4(0.5764705882352941, 0.2, 0.9176470588235294, 1); static purple700: float4 = float4(0.49411764705882355, 0.13333333333333333, 0.807843137254902, 1); static purple800: float4 = float4(0.4196078431372549, 0.12941176470588237, 0.6588235294117647, 1); static purple900: float4 = float4(0.34509803921568627, 0.10980392156862745, 0.5294117647058824, 1); static purple950: float4 = float4(0.23137254901960785, 0.027450980392156862, 0.39215686274509803, 1); static fuchsia50: float4 = float4(0.9921568627450981, 0.9568627450980393, 1, 1); static fuchsia100: float4 = float4(0.9803921568627451, 0.9098039215686274, 1, 1); static fuchsia200: float4 = float4(0.9607843137254902, 0.8156862745098039, 0.996078431372549, 1); static fuchsia300: float4 = float4(0.9411764705882353, 0.6705882352941176, 0.9882352941176471, 1); static fuchsia400: float4 = float4(0.9098039215686274, 0.4745098039215686, 0.9764705882352941, 1); static fuchsia500: float4 = float4(0.8509803921568627, 0.27450980392156865, 0.9372549019607843, 1); static fuchsia600: float4 = float4(0.7529411764705882, 0.14901960784313725, 0.8274509803921568, 1); static fuchsia700: float4 = float4(0.6352941176470588, 0.10980392156862745, 0.6862745098039216, 1); static fuchsia800: float4 = float4(0.5254901960784314, 0.09803921568627451, 0.5607843137254902, 1); static fuchsia900: float4 = float4(0.4392156862745098, 0.10196078431372549, 0.4588235294117647, 1); static fuchsia950: float4 = float4(0.2901960784313726, 0.01568627450980392, 0.3058823529411765, 1); static pink50: float4 = float4(0.9921568627450981, 0.9490196078431372, 0.9725490196078431, 1); static pink100: float4 = float4(0.9882352941176471, 0.9058823529411765, 0.9529411764705882, 1); static pink200: float4 = float4(0.984313725490196, 0.8117647058823529, 0.9098039215686274, 1); static pink300: float4 = float4(0.9764705882352941, 0.6588235294117647, 0.8313725490196079, 1); static pink400: float4 = float4(0.9568627450980393, 0.4470588235294118, 0.7137254901960784, 1); static pink500: float4 = float4(0.9254901960784314, 0.2823529411764706, 0.6, 1); static pink600: float4 = float4(0.8588235294117647, 0.15294117647058825, 0.4666666666666667, 1); static pink700: float4 = float4(0.7450980392156863, 0.09411764705882353, 0.36470588235294116, 1); static pink800: float4 = float4(0.615686274509804, 0.09019607843137255, 0.30196078431372547, 1); static pink900: float4 = float4(0.5137254901960784, 0.09411764705882353, 0.2627450980392157, 1); static pink950: float4 = float4(0.3137254901960784, 0.027450980392156862, 0.1411764705882353, 1); static rose50: float4 = float4(1, 0.9450980392156862, 0.9490196078431372, 1); static rose100: float4 = float4(1, 0.8941176470588236, 0.9019607843137255, 1); static rose200: float4 = float4(0.996078431372549, 0.803921568627451, 0.8274509803921568, 1); static rose300: float4 = float4(0.9921568627450981, 0.6431372549019608, 0.6862745098039216, 1); static rose400: float4 = float4(0.984313725490196, 0.44313725490196076, 0.5215686274509804, 1); static rose500: float4 = float4(0.9568627450980393, 0.24705882352941178, 0.3686274509803922, 1); static rose600: float4 = float4(0.8823529411764706, 0.11372549019607843, 0.2823529411764706, 1); static rose700: float4 = float4(0.7450980392156863, 0.07058823529411765, 0.23529411764705882, 1); static rose800: float4 = float4(0.6235294117647059, 0.07058823529411765, 0.2235294117647059, 1); static rose900: float4 = float4(0.5333333333333333, 0.07450980392156863, 0.21568627450980393, 1); static rose950: float4 = float4(0.2980392156862745, 0.0196078431372549, 0.09803921568627451, 1); } pub fn wrap2(value: float2, low: float, high: float) { return (wrap(value.x, low, high), wrap(value.y, low, high)); } pub fn wrap3(value: float3, low: float, high: float) { return (wrap(value.x, low, high), wrap(value.y, low, high), wrap(value.z, low, high)); } pub fn wrap4(value: float4, low: float, high: float) { return (wrap(value.x, low, high), wrap(value.y, low, high), wrap(value.z, low, high), wrap(value.w, low, high)); } ================================================ FILE: lang/shadeup/library/drawAttributes.ts ================================================ import { buffer } from '/_std/buffer'; import { float4, float3, float, float2, bool, int, uint } from '/std_math'; export function drawAttributes( indexBuffer: buffer, buffers: | Map> | { [key in keyof T]: buffer; }, vertexShader: shader, pixelShader: shader ) { __shadeup_dispatch_draw_attributes(indexBuffer, buffer, vertexShader, pixelShader); } ================================================ FILE: lang/shadeup/library/drawCount.ts ================================================ import { buffer } from '/_std/buffer'; import { float4, float3, float, float2, bool, int, uint } from '/std_math'; export function drawCount(triCount: number, vertexShader: shader, pixelShader: shader) { __shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader); } ================================================ FILE: lang/shadeup/library/drawIndexed.ts ================================================ import { buffer } from '/_std/buffer'; import { Mesh } from '/_std/mesh'; import { texture2d } from '/_std/texture'; import { float4, float3, float, float2, bool, int, uint, atomic, int3 } from '/std_math'; export function drawIndexed( indexBuffer: buffer, vertexShader: shader, pixelShader: shader ) { __shadeup_dispatch_draw_indexed(indexBuffer, vertexShader, pixelShader); } export function drawInstanced( mesh: Mesh, instanceCount: int, vertexShader: shader, pixelShader: shader ) { __shadeup_dispatch_draw_instanced(mesh, instanceCount, vertexShader, pixelShader); } export function drawInstancedIndexed( indexBuffer: buffer, instanceCount: int, vertexShader: shader, pixelShader: shader ) { __shadeup_dispatch_draw_instanced_indexed(indexBuffer, instanceCount, vertexShader, pixelShader); } export function drawIndexedIndirect( indirectBuffer: buffer | buffer>, vertexShader: shader, pixelShader: shader ) { __shadeup_dispatch_draw_indexed_indirect(indirectBuffer, vertexShader, pixelShader); } export function drawIndirect( mesh: Mesh, indirectBuffer: buffer | buffer>, vertexShader: shader, pixelShader: shader ) { __shadeup_dispatch_draw_indirect(mesh, indirectBuffer, vertexShader, pixelShader); } export function shader_start_shd_( s: shader, groupSize?: any ): shader { return s; } export type shader = ( __in: Omit ) => T_OUT; declare global { // function __shadeup_make_shader_inst( // key: string, // params: any, // closure: any // ): shader; // function __shadeup_dispatch_draw(fullScreenPixelShader: shader): void; // function __shadeup_dispatch_draw_geometry( // geometry: Mesh, // vertexShader: shader, // pixelShader: shader // ): void; interface Array { [index: int]: T; } let window: { [index: string]: any; }; } /**@shadeup=struct*/ export class ShaderInput { /** Interpolated world position (available in fragment, and vertex) */ position: float3 = float3(0, 0, 0); /** Interpolated normal (fragment), Source mesh normal (vertex) */ normal: float3 = float3(0, 0, 0); /** Interpolated tangent (fragment), Source mesh tangent (vertex) */ tangent: float3 = float3(0, 0, 0); /** Interpolated bitangent (fragment), Source mesh bitangent (vertex) */ bitangent: float3 = float3(0, 0, 0); /** Vertex shader output position */ clipPosition: float4 = float4(0, 0, 0, 0); realPosition: float4 = float4(0, 0, 0, 0); /** UV channel 0 input (available in fragment, and vertex) */ uv: float2 = float2(0, 0); /** Screen position in pixels (available in fragment, and vertex) */ screen: float2 = float2(0, 0); /** Interpolated vertex color (available in fragment, and vertex) */ color: float4 = float4(0, 0, 0, 0); /** Group ID (available in compute) */ groupId: int3 = int3(0, 0, 0); /** Group size (available in compute) */ groupSize: int3 = int3(0, 0, 0); /** Global id (groupId * groupSize + localId) (available in compute) */ globalId: int3 = int3(0, 0, 0); /** Local id (available in compute) */ localId: int3 = int3(0, 0, 0); /** Instance index (available in fragment, and vertex) */ instanceIndex: int = 0; /** Vertex index (available in vertex) */ vertexIndex: int = 0; /** @shadeup=noemit_gpu */ attr(index: int, interpolation?: 'flat' | 'linear' | 'perspective'): T { return null as any; } } /**@shadeup=struct*/ export class ShaderOutput { /** Vertex output position */ position: float4 = float4(0, 0, 0, 0); /** Vertex output normal */ normal: float3 = float3(0, 0, 0); /** Vertex output tangent */ tangent: float3 = float3(0, 0, 0); /** Vertex output bitangent */ bitangent: float3 = float3(0, 0, 0); /** UV channel 0 output */ uv: float2 = float2(0, 0); /** Pixel color output */ color: float4 = float4(0, 0, 0, 0); /** @shadeup=noemit_gpu */ attr(index: int, value: T, interpolation?: 'flat' | 'linear' | 'perspective') {} } /** @shadeup=shader */ export function makeShader( key: string, fn: (__in: I, __out: O) => void ): shader { return fn as shader; } type AttachmentBindings1 = { attachments: [texture2d]; vertex: shader; fragment: shader< ShaderInput, { attachment0: A0; } >; }; type AttachmentBindings2 = { attachments: [texture2d, texture2d]; vertex: shader; fragment: shader< ShaderInput, { attachment0: A0; attachment1: A1; } >; }; type AttachmentBindings3 = { attachments: [texture2d, texture2d, texture2d]; vertex: shader; fragment: shader< ShaderInput, { attachment0: A0; attachment1: A1; attachment2: A2; } >; }; type AttachmentBindings4 = { attachments: [texture2d, texture2d, texture2d, texture2d]; vertex: shader; fragment: shader< ShaderInput, { attachment0: A0; attachment1: A1; attachment2: A2; attachment3: A3; } >; }; type AttachmentBindings5 = { attachments: [texture2d, texture2d, texture2d, texture2d, texture2d]; vertex: shader; fragment: shader< ShaderInput, { attachment0: A0; attachment1: A1; attachment2: A2; attachment3: A3; attachment4: A4; } >; }; type AttachmentBindings6 = { attachments: [ texture2d, texture2d, texture2d, texture2d, texture2d, texture2d ]; vertex: shader; fragment: shader< ShaderInput, { attachment0: A0; attachment1: A1; attachment2: A2; attachment3: A3; attachment4: A4; attachment5: A5; } >; }; type AttachmentBindings7 = { attachments: [ texture2d, texture2d, texture2d, texture2d, texture2d, texture2d, texture2d ]; vertex: shader; fragment: shader< ShaderInput, { attachment0: A0; attachment1: A1; attachment2: A2; attachment3: A3; attachment4: A4; attachment5: A5; attachment6: A6; } >; }; type AttachmentBindings8 = { attachments: [ texture2d, texture2d, texture2d, texture2d, texture2d, texture2d, texture2d, texture2d ]; vertex: shader; fragment: shader< ShaderInput, { attachment0: A0; attachment1: A1; attachment2: A2; attachment3: A3; attachment4: A4; attachment5: A5; attachment6: A6; attachment7: A7; } >; }; type DrawDescriptorBase = ( | { mesh: Mesh; } | { indexBuffer: buffer; } | {} ) & { indirect?: buffer | buffer>; indirectOffset?: int | uint; depth?: texture2d; depthOnly?: boolean; depthTest?: boolean; depthCompare?: | 'greater' | 'less' | 'equal' | 'greater_equal' | 'less_equal' | 'not_equal' | 'always' | 'never'; backfaceCulling?: boolean; instances?: int; }; /** * Normal: * ```shadeup * drawAdvanced({ * mesh: mesh::box(0.xyz, 100.xyz), * vertex: shader { * // ... * }, * fragment: shader { * // ... * }, * }); * ``` * * Instancing: * ```shadeup * drawAdvanced({ * mesh: mesh::box(0.xyz, 100.xyz), * vertex: shader { * in.instanceIndex; * }, * fragment: shader { * // ... * }, * instances: 100, * }); * ``` * * Indirect: * ```shadeup * let mesh = mesh::box(0.xyz, 100.xyz); * * let indirectBuffer = buffer(5); * indirectBuffer[0] = uint(m.getTriangles().len()); // indexCount * indirectBuffer[1] = 1; // instanceCount * indirectBuffer[2] = 0; // firstIndex * indirectBuffer[3] = 0; // vertexOffset * indirectBuffer[4] = 0; // firstInstance * * drawAdvanced({ * mesh: mesh::box(0.xyz, 100.xyz), * vertex: shader { * // ... * }, * fragment: shader { * // ... * }, * indirect: indirectBuffer, * }); * ``` * * Attachments: * ```shadeup * let mesh = mesh::box(0.xyz, 100.xyz); * let color = texture2d(100.xy); * let normal = texture2d(100.xy); * let depth = texture2d(100.xy, "depth"); * * drawAdvanced({ * mesh: mesh, * vertex: shader { * // ... * }, * fragment: shader { * out.attachment0 = float4(1, 0, 0, 1); * out.attachment1 = float3(0, 0, 1); * }, * depth: depth, // Override depth buffer * attachments: [color, normal], * }); */ export function drawAdvanced( descriptor: DrawDescriptorBase & AttachmentBindings8 ): void; export function drawAdvanced( descriptor: DrawDescriptorBase & AttachmentBindings7 ): void; export function drawAdvanced( descriptor: DrawDescriptorBase & AttachmentBindings6 ): void; export function drawAdvanced( descriptor: DrawDescriptorBase & AttachmentBindings5 ): void; export function drawAdvanced( descriptor: DrawDescriptorBase & AttachmentBindings4 ): void; export function drawAdvanced( descriptor: DrawDescriptorBase & AttachmentBindings3 ): void; export function drawAdvanced( descriptor: DrawDescriptorBase & AttachmentBindings2 ): void; export function drawAdvanced(descriptor: DrawDescriptorBase & AttachmentBindings1): void; export function drawAdvanced( descriptor: DrawDescriptorBase & { vertex: shader; fragment: shader; } ): void; export function drawAdvanced(descriptor: any): void { (window as any).__shadeup_dispatch_draw_advanced(descriptor); } export function draw( geometry: Mesh, vertexShader: shader, pixelShader: shader ): void; export function draw(fullScreenPixelShader: shader): void; export function draw( first: Mesh | DrawDescriptorBase | shader, second?: shader | number, third?: shader ) { if ('vertices' in first && second && third) { (window as any).__shadeup_dispatch_draw_geometry(first, second, third); } else if (first && !second && !third) { (window as any).__shadeup_dispatch_draw(first as shader); } } export function drawFullscreen(fullScreenPixelShader: shader): void; export function drawFullscreen( first: Mesh | any | shader, second?: shader, third?: shader ) { if ('vertices' in first && second && third) { (window as any).__shadeup_dispatch_draw_geometry(first, second, third); } else if (first && !second && !third) { (window as any).__shadeup_dispatch_draw(first as shader); } } export function drawAlt2(fullScreenPixelShader: shader): void {} export function drawCount( triCount: number, vertexShader: shader, pixelShader: shader ) { __shadeup_dispatch_draw_count(triCount, vertexShader, pixelShader); } export function drawAttributes( indexBuffer: buffer, buffers: | Map> | { [key in keyof T]: buffer; }, vertexShader: shader, pixelShader: shader ) { __shadeup_dispatch_draw_attributes(indexBuffer, buffer, vertexShader, pixelShader); } export function computeIndirect( indirectBuffer: buffer | buffer>, indirectOffset: int, computeShader: shader ) { (window as any).__shadeup_dispatch_compute_indirect( indirectBuffer, indirectOffset, computeShader ); } ================================================ FILE: lang/shadeup/library/examples/deferred.shadeup ================================================ let depth = texture2d(env.screenSize, "depth"); let albedo = texture2d(env.screenSize, "16bit"); let normal = texture2d(env.screenSize, "16bit"); fn randNeg(seed: int) { return (rand(seed) - 0.5) * 2; } fn main() { let lights: float3[] = []; let lightXZArea = 400.0; let lightYArea = 200.0; for (let i = 0; i < 400; i++) { lights.push( lerp( (randNeg(i * 3 + 0) * lightXZArea, randNeg(i * 3 + 1) * lightYArea, randNeg(i * 3 + 2) * lightXZArea), (randNeg(i * 6 + 0) * lightXZArea, randNeg(i * 6 + 1) * lightYArea, randNeg(i * 6 + 2) * lightXZArea), sin(env.time / 1000.0 + i) ) ); } let projectionMatrix = matrix::perspective(120.0, env.screenSize.x / env.screenSize.y, 1.0, 2000.0); let t = env.time / 1000.0; let viewMatrix = ( matrix::lookAt((sin(t), 0.5, cos(t)) * 400.0, 0.xyz, (0, 1.0, 0)) ); let viewProjMatrix = projectionMatrix * viewMatrix; if (true) { viewProjMatrix = env.camera.getPerspectiveMatrix() * env.camera.getWorldToViewMatrix(); } let viewProjMatrixInv = inverse(viewProjMatrix); let meshes = [ mesh::box((sin(t * 2) * 100.0, 0.0, cos(t * 2) * 100.0), 100.xyz), mesh::box((0, -50.1, 0), (1000, 0.1, 1000)) ]; for (let m of meshes) drawAdvanced({ mesh: m, attachments: [albedo, normal], depth: depth, vertex: shader { out.position = viewProjMatrix * (in.position, 1); }, fragment: shader { out.attachment0 = (0.4.xyz, 1.0); out.attachment1 = (in.normal, 1); } }); draw(shader{ let d = depth[floor(in.uv * depth.size)]; let a = albedo.sample(in.uv); let n = normal.sample(in.uv); let posClip = float4(in.uv.x * 2.0 - 1.0, (1.0 - in.uv.y) * 2.0 - 1.0, d, 1.0); let posWorldW = viewProjMatrixInv * posClip; let posWorld = posWorldW.xyz / posWorldW.www; let finalColor = 0.0.xyz; for (let i = 0; i < lights.len(); i++) { let L = lights[i].xyz - posWorld; let radius = 200.0; let color = lerp((0.3, 0.2, 0.8), (0.1, 0.7, 0.7), rand(float(i) / float(lights.len()))); let distance = length(L); if (distance <= radius) { let lambert = max(dot(n.xyz, normalize(L)), 0.0); finalColor += lambert * pow((1.0 - distance / radius), 2.0) * color * a.xyz; } } finalColor += 0.5 * a.xyz; out.color = (finalColor, 1); let cornerNormal = normal.sample(in.uv * 10.0); let cornerDepth = depth.sample((in.uv - (0.1, 0.0)) * 10.0); if (in.uv.x < 0.1 && in.uv.y < 0.1) { out.color = (cornerNormal + 1.0) / 2.0; } else if (in.uv.x < 0.2 && in.uv.y < 0.1) { out.color = cornerDepth; } }); albedo.clear(); normal.clear(); depth.clear(); } ================================================ FILE: lang/shadeup/library/examples/shadow-map.shadeup ================================================ const shadowMapSize = 4096; let albedo = texture2d(env.screenSize, "16bit"); let normal = texture2d(env.screenSize, "16bit"); let shadow = texture2d(shadowMapSize.xy, "depth-32"); fn main() { let sun = (sin(env.time / 1000.0), 1, 0.5) * 600.0; env.camera.near = 20.0; env.camera.far = 20000.0; let sunProjectionMatrix = matrix::perspective(90.0, 1.0, env.camera.near, env.camera.far); let sunViewMatrix = matrix::lookAt(sun, 0.xyz, (0, 1.0, 0)); let sunViewProjMatrix = sunProjectionMatrix * sunViewMatrix; let viewProjMatrix = env.camera.getPerspectiveMatrix() * env.camera.getWorldToViewMatrix(); let t = env.time / 1000.0; let cube = mesh::box((sin(t * 2) * 100.0, 0.0, cos(t * 2) * 100.0), 100.xyz); let ground = mesh::box((0, -50.1, 0), (1000, 0.1, 1000)); let meshes = [cube, ground]; for (let m of meshes) drawAdvanced({ mesh: m, depth: shadow, depthOnly: true, vertex: shader { out.position = sunViewProjMatrix * (in.position, 1); }, fragment: shader {} }); for (let m of meshes) draw(m, shader { out.position = viewProjMatrix * (in.position, 1); }, shader { let posFromLight = sunViewProjMatrix * (in.position, 1.0); posFromLight /= posFromLight.w; let shadowPos = (posFromLight.xy * (0.5, -0.5) + 0.5.xy, posFromLight.z); let visibility = 0.0; for (let y = -1; y <= 1; y++) { for (let x = -1; x <= 1; x++) { let offset = float2(x, y) * (1.0 / shadowMapSize); let sampVal = shadow.sample(shadowPos.xy + offset).x; let compVal = shadowPos.z - 0.00007; visibility += compVal < sampVal ? 1 : 0; } } visibility /= 9.0; let lambertFactor = max(dot(normalize(sun - in.position), in.normal), 0.0); let lightingFactor = min(0.2 + visibility * lambertFactor, 1.0); out.color = float4(lightingFactor * 0.8.xyz, 1.0); } ); albedo.clear(); normal.clear(); shadow.clear(); } ================================================ FILE: lang/shadeup/library/examples/transparency.shadeup ================================================ struct LinkedListElement { pub color: float4, pub depth: float, pub next: uint }; let maxScreenSize = env.screenSize; let numPixels = int(maxScreenSize.x * maxScreenSize.y); let numFragments = buffer>(1); let heads = buffer>(numPixels); let headsInit = buffer>(numPixels); for (let i = 0; i < numPixels; i++) { headsInit[i] = atomic(0xffffffu); } headsInit.upload(); let linkedItems = buffer(numPixels * 4); /*linkedItems[0] = LinkedListElement { color: 0.xyzw, depth: 1.0, next: 2u };*/ //linkedItems.upload(); fn main() { statGraph("dt", env.deltaTime * 1000.0); heads.write(headsInit); numFragments[0] = atomic(0u); const colors = [ (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 0.0), (0.0, 1.0, 1.0), ]; let mat = env.camera.getTransformToViewMatrix(0.xyz, 1.xyz, 0.xyzw); for (let (x, y) of 4.xy) { let instance = uint(y * 4 + x); draw( mesh::box((x, 0, y) * 100.0 - (200, 0, 200), 90.xyz), shader { out.position = mat * (in.position, 1); }, shader { let pixel = in.screen; if (pixel.x < maxScreenSize.x && pixel.y < maxScreenSize.y) { let headIndex = int(pixel.y * maxScreenSize.x + pixel.x); let fragIndex = numFragments[0].add(1u); if (int(fragIndex) < numPixels * 4) { let lastHead = heads[headIndex].exchange(fragIndex); linkedItems[int(fragIndex)] = LinkedListElement { depth: in.clipPosition.z, next: lastHead, color: float4(colors[int(instance % 6u)], 0.3) }; linkedItems[int(fragIndex)].depth = in.clipPosition.z; linkedItems[int(fragIndex)].next = lastHead; linkedItems[int(fragIndex)].color = float4(colors[int(instance % 6u)], 0.3); } } } ); } draw(shader { let pixel = in.screen; if (pixel.x < maxScreenSize.x && pixel.y < maxScreenSize.y) { let headsIndex = uint(pixel.y * maxScreenSize.x + pixel.x); // The maximum layers we can process for any pixel const maxLayers = 24u; let layers: LinkedListElement[24]; let numLayers = 0u; let elementIndex = heads[headsIndex].load(); // copy the list elements into an array up to the maximum amount of layers while (elementIndex < 0xffffffu && numLayers < maxLayers) { layers[numLayers] = linkedItems[elementIndex]; numLayers++; elementIndex = linkedItems[elementIndex].next; } if (numLayers == 0u) { }else{ // sort the fragments by depth for (let i = 1u; i < numLayers; i++) { let toInsert = layers[i]; let j = i; while (j > 0u && toInsert.depth > layers[j - 1u].depth) { layers[j] = layers[j - 1u]; j--; } layers[j] = toInsert; } // pre-multiply alpha for the first layer let color = float4(layers[0].color.a * layers[0].color.rgb, layers[0].color.a); // blend the remaining layers for (let i = 1u; i < numLayers; i++) { let mixed = lerp(color.rgb, layers[i].color.rgb, layers[i].color.a); color = float4(mixed, color.a); } out.color = color; } } }); } ================================================ FILE: lang/shadeup/library/files.ts ================================================ import std from './std.ts?raw'; import ui from './ui.ts?raw'; import native from './native.ts?raw'; import buffer from './buffer.ts?raw'; import texture from './texture.ts?raw'; import physics from './physics.ts?raw'; import drawIndexed from './drawIndexed.ts?raw'; import drawCount from './drawCount.ts?raw'; import drawAttributes from './drawAttributes.ts?raw'; import paint from './paint.ts?raw'; import mesh from './mesh.shadeup?raw'; import geo from './geo.shadeup?raw'; import textures from './textures.shadeup?raw'; import common from './common.shadeup?raw'; import sdf from './sdf.shadeup?raw'; export default { shadeup: { mesh, textures, common, sdf, geo }, ts: { std, ui, native, paint, buffer, texture, drawIndexed, drawAttributes, drawCount, physics } }; ================================================ FILE: lang/shadeup/library/geo.shadeup ================================================ struct GeoSegment { start: float2, end: float2, kind: int, arcRadius: float, arcStart: float, arcEnd: float } struct GeoPoly { segments: GeoSegment[] } trait Geometry { fn area(self) -> float; fn perimeter(self) -> float; fn discretize(self) -> GeoPoly; } impl Geometry for GeoPoly { pub fn area(self) -> float { return 0.0; } pub fn perimeter(self) -> float { return 0.0; } pub fn discretize(self) -> GeoPoly { return self.clone(); } } ================================================ FILE: lang/shadeup/library/mesh.shadeup ================================================ pub struct Mesh { vertices: float3[]; triangles: int[]; normals: float3[]; tangents: float3[]; bitangents: float3[]; uvs: float2[]; colors: float4[]; pub symbol: any; } impl Mesh { pub fn rect(self, size: float2) { let index = self.vertices.len(); self.vertices.push((-size.x / 2, -size.y / 2, 0)); self.vertices.push((size.x / 2, -size.y / 2, 0)); self.vertices.push((size.x / 2, size.y / 2, 0)); self.vertices.push((-size.x / 2, size.y / 2, 0)); self.triangles.push(index + 2); self.triangles.push(index + 1); self.triangles.push(index + 0); self.triangles.push(index + 0); self.triangles.push(index + 3); self.triangles.push(index + 2); self.normals.push((0, 0, 1)); self.normals.push((0, 0, 1)); self.normals.push((0, 0, 1)); self.normals.push((0, 0, 1)); self.tangents.push((1, 0, 0)); self.tangents.push((1, 0, 0)); self.tangents.push((1, 0, 0)); self.tangents.push((1, 0, 0)); self.bitangents.push((0, 1, 0)); self.bitangents.push((0, 1, 0)); self.bitangents.push((0, 1, 0)); self.bitangents.push((0, 1, 0)); self.uvs.push((0, 0)); self.uvs.push((1, 0)); self.uvs.push((0, 1)); self.uvs.push((1, 1)); } pub fn quad(self, position: float3, direction: float3, right: float3, size: float2) { let up = normalize(cross(right, direction)); let halfSize = size / 2.0; let index = self.vertices.len(); self.vertices.push(position + right * -halfSize.x + up * halfSize.y); self.vertices.push(position + right * halfSize.x + up * halfSize.y); self.vertices.push(position + right * halfSize.x + up * -halfSize.y); self.vertices.push(position + right * -halfSize.x + up * -halfSize.y); self.triangles.push(index + 0); self.triangles.push(index + 1); self.triangles.push(index + 2); self.triangles.push(index + 2); self.triangles.push(index + 3); self.triangles.push(index + 0); self.normals.push(direction); self.normals.push(direction); self.normals.push(direction); self.normals.push(direction); self.tangents.push(right); self.tangents.push(right); self.tangents.push(right); self.tangents.push(right); self.bitangents.push(up); self.bitangents.push(up); self.bitangents.push(up); self.bitangents.push(up); self.uvs.push((1, 0)); self.uvs.push((0, 0)); self.uvs.push((0, 1)); self.uvs.push((1, 1)); } pub fn box(self, size: float3) { let halfSize = size / 2.0; const UP = (0, 1.0, 0); const DOWN = (0, -1.0, 0); const LEFT = (-1.0, 0, 0); const RIGHT = (1.0, 0, 0); const FORWARD = (0, 0, 1.0); const BACK = (0, 0, -1.0); // Up self.quad(UP * halfSize.y, UP, LEFT, (size.x, size.z)); // Down self.quad(DOWN * halfSize.y, DOWN, RIGHT, (size.x, size.z)); // Left self.quad(LEFT * halfSize.x, LEFT, BACK, (size.z, size.y)); // Right self.quad(RIGHT * halfSize.x, RIGHT, FORWARD, (size.z, size.y)); // Forward self.quad(FORWARD * halfSize.z, FORWARD, LEFT, (size.x, size.y)); // Back self.quad(BACK * halfSize.z, BACK, RIGHT, (size.x, size.y)); } pub fn rectAt(self, minPos: float2, maxPos: float2) { self.rect(maxPos - minPos); self.translate((minPos, 0)); } pub fn circle(self, pos: float2, radius: float, vertices: int = 32) { } pub fn uvSphere(self, pos: float3, radius: float, vertices: int = 32, rings: int = 16) { let index = self.vertices.len(); let verticesPerRing = vertices + 1; for (let i = 0; i <= rings; i++) { let y = i / float(rings); let angleY = y * PI; let posY = cos(angleY); let radiusY = sin(angleY); for (let j = 0; j <= vertices; j++) { let x = j / float(vertices); let angleX = x * PI * 2; let posX = cos(angleX); let posZ = sin(angleX); self.vertices.push((posX * radiusY * radius, posY * radius, posZ * radiusY * radius)); self.normals.push(normalize((posX * radiusY, posY, posZ * radiusY))); let tangent = normalize((posZ, 0, -posX)); let bitangent = normalize(cross(self.normals[self.normals.len() - 1], tangent)); self.tangents.push(tangent); self.bitangents.push(bitangent); self.uvs.push((x, y)); } } for (let i = 0; i < rings; i++) { for (let j = 0; j < vertices; j++) { let i0 = i * verticesPerRing + j; let i1 = i0 + 1; let i2 = i0 + verticesPerRing; let i3 = i2 + 1; self.triangles.push(index + i0); self.triangles.push(index + i1); self.triangles.push(index + i2); self.triangles.push(index + i2); self.triangles.push(index + i1); self.triangles.push(index + i3); } } self.translate(pos); } pub fn icoSphere(self, pos: float3, radius: float, subdivisions: int = 1) { let index = self.vertices.len(); let t = (1.0 + sqrt(5.0)) / 2.0; let vertices: float3[] = [ (-1, t, 0), (1, t, 0), (-1, -t, 0), (1, -t, 0), (0, -1, t), (0, 1, t), (0, -1, -t), (0, 1, -t), (t, 0, -1), (t, 0, 1), (-t, 0, -1), (-t, 0, 1), ]; let triangles: int3[] = [ (0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4), (11, 10, 2), (10, 7, 6), (7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8), (3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10), (8, 6, 7), (9, 8, 1), ]; for (let i = 0; i < vertices.len(); i++) { self.vertices.push(normalize(vertices[i]) * radius); } for (let i = 0; i < triangles.len(); i++) { self.triangles.push(index + triangles[i].x); self.triangles.push(index + triangles[i].y); self.triangles.push(index + triangles[i].z); } for (let i = 0; i < subdivisions; i++) { let newTriangles: int = []; for (let j = 0; j < self.triangles.len(); j += 3) { let i0 = self.triangles[j + 0]; let i1 = self.triangles[j + 1]; let i2 = self.triangles[j + 2]; let v0 = self.vertices[i0]; let v1 = self.vertices[i1]; let v2 = self.vertices[i2]; let v3 = normalize((v0 + v1) / 2.0); let v4 = normalize((v1 + v2) / 2.0); let v5 = normalize((v2 + v0) / 2.0); let i3 = self.vertices.len(); let i4 = i3 + 1; let i5 = i3 + 2; self.vertices.push(v3 * radius); self.vertices.push(v4 * radius); self.vertices.push(v5 * radius); newTriangles.push(i0, i3, i5); newTriangles.push(i3, i1, i4); newTriangles.push(i3, i4, i5); newTriangles.push(i5, i4, i2); } self.triangles = newTriangles; } for (let i = 0; i < self.vertices.len(); i++) { let normal = normalize(self.vertices[i]); let tangent = normalize((normal.z, 0, -normal.x)); let bitangent = normalize(cross(normal, tangent)); self.normals.push(normal); self.tangents.push(tangent); self.bitangents.push(bitangent); } for (let i = 0; i < self.triangles.len(); i += 3) { let i0 = self.triangles[i + 0]; let i1 = self.triangles[i + 1]; let i2 = self.triangles[i + 2]; let v0 = self.vertices[i0]; let v1 = self.vertices[i1]; let v2 = self.vertices[i2]; let uv0 = float2(atan2(v0.z, v0.x) / PI / 2.0 + 0.5, asin(v0.y) / PI + 0.5); let uv1 = float2(atan2(v1.z, v1.x) / PI / 2.0 + 0.5, asin(v1.y) / PI + 0.5); let uv2 = float2(atan2(v2.z, v2.x) / PI / 2.0 + 0.5, asin(v2.y) / PI + 0.5); self.uvs.push(uv0); self.uvs.push(uv1); self.uvs.push(uv2); } self.translate(pos); } pub fn cylinder(self, pos: float3, radius: float, height: float, vertices: int = 32) { self.translate(pos); } pub fn capsule(self, pos: float3, radius: float, height: float, vertices: int = 32) { self.translate(pos); } pub fn cone(self, pos: float3, radius: float, height: float, vertices: int = 32) { let index = self.vertices.len(); self.translate(pos); } pub fn plane(self, pos: float3, size: float2, subdivisions: int2 = 1) { let index = self.vertices.len(); let halfSize = size / 2.0; for (let i = 0; i <= subdivisions.x; i++) { let x = i / float(subdivisions.x); let posX = x * size.x - halfSize.x; for (let j = 0; j <= subdivisions.y; j++) { let y = j / float(subdivisions.y); let posY = y * size.y - halfSize.y; self.vertices.push((posX, 0, posY)); self.normals.push((0, 1, 0)); self.tangents.push((1, 0, 0)); self.bitangents.push((0, 0, 1)); self.uvs.push((x, y)); } } for (let i = 0; i < subdivisions.x; i++) { for (let j = 0; j < subdivisions.y; j++) { let i0 = i * (subdivisions.y + 1) + j; let i1 = i0 + 1; let i2 = i0 + subdivisions.y + 1; let i3 = i2 + 1; self.triangles.push(index + i0); self.triangles.push(index + i1); self.triangles.push(index + i2); self.triangles.push(index + i2); self.triangles.push(index + i1); self.triangles.push(index + i3); } } self.translate(pos); } pub fn translate(self, pos: float3): Mesh { for (let i = 0; i < self.vertices.len(); i++) { self.vertices[i] += pos; } return self; } pub fn rotate(self, quaternion: float4): Mesh { for (let i = 0; i < self.vertices.len(); i++) { self.vertices[i] = quat::rotate(quaternion, self.vertices[i]); } for (let i = 0; i < self.normals.len(); i++) { self.normals[i] = quat::rotate(quaternion, self.normals[i]); } return self; } pub fn transform(self, matrix: float4x4): Mesh { for (let i = 0; i < self.vertices.len(); i++) { self.vertices[i] = ((self.vertices[i], 1) * matrix).xyz; } for (let i = 0; i < self.normals.len(); i++) { self.normals[i] = ((self.normals[i], 1) * matrix).xyz; } return self; } pub fn scale(self, scale: float3): Mesh { for (let i = 0; i < self.vertices.len(); i++) { self.vertices[i] *= scale; } return self; } pub fn bounds(self): float3 { let mn = 0.0.xyz; let mx = 0.0.xyz; for (let i = 0; i < self.vertices.len(); i++) { mn = min(mn, self.vertices[i]); mx = max(mx, self.vertices[i]); } return mx - mn; } pub fn center(self): float3 { let bounds = self.bounds(); return bounds / 2.0; } pub fn new() { return Mesh { vertices: [], triangles: [], tangents: [], bitangents: [], normals: [], uvs: [], colors: [], } } pub fn append(self, other: Mesh) { let oldVertices = self.vertices.len(); let oldTriangles = self.triangles.len(); self.vertices.append(other.vertices); self.triangles.append(other.triangles); self.normals.append(other.normals); self.tangents.append(other.tangents); self.bitangents.append(other.bitangents); self.uvs.append(other.uvs); self.colors.append(other.colors); for (let i = oldTriangles; i < self.triangles.len(); i++) { self.triangles[i] += oldVertices; } } pub fn getVertices(self) { return self.vertices; } pub fn getTriangles(self) { return self.triangles; } pub fn getNormals(self) { return self.normals; } pub fn getTangents(self) { return self.tangents; } pub fn getBitangents(self) { return self.bitangents; } pub fn getUVs(self) { return self.uvs; } pub fn getColors(self) { return self.colors; } pub fn setVertices(self, vertices: float3[]) { self.vertices = vertices; } pub fn setTriangles(self, triangles: int[]) { self.triangles = triangles; } pub fn setNormals(self, normals: float3[]) { self.normals = normals; } pub fn setTangents(self, tangents: float3[]) { self.tangents = tangents; } pub fn setBitangents(self, bitangents: float3[]) { self.bitangents = bitangents; } pub fn setUVs(self, uvs: float2[]) { self.uvs = uvs; } pub fn setColors(self, colors: float4[]) { self.colors = colors; } } pub struct mesh {} impl mesh { pub fn rect(pos: float2, size: float2) -> Mesh { let g = Mesh::new(); g.rectAt(pos, pos + size); return g; } pub fn box(pos: float3, size: float3) -> Mesh { let g = Mesh::new(); g.box(size); g.translate(pos); return g; } pub fn uvSphere(pos: float3, radius: float, vertices: int = 32, rings: int = 16) -> Mesh { let g = Mesh::new(); g.uvSphere(pos, radius, vertices, rings); return g; } pub fn icoSphere(pos: float3, radius: float, subdivisions: int = 1) -> Mesh { let g = Mesh::new(); g.icoSphere(pos, radius, subdivisions); return g; } pub fn plane(pos: float3, size: float2, subdivisions: int2 = 1) -> Mesh { let g = Mesh::new(); g.plane(pos, size, subdivisions); return g; } /** * Returns a [-1, 1] position for a given index. */ pub fn triangleFromIndex(index: int): float2 { if (index == 0) { return float2(-1, 1); } else if (index == 1) { return float2(1, 1); } else if (index == 2) { return float2(0, -1); } else { return float2(0, 0); } } pub fn circleFromIndex(vertexIndex: int, vertices: int): float2 { vertexIndex = vertices - vertexIndex; let numSlices = vertices / 3; let sliceIndex = floor(float(vertexIndex) / float(vertices) * float(numSlices)); let incAngle = PI * 2.0 / float(numSlices); let baseAngle = incAngle * float(sliceIndex); if (vertexIndex % 3 == 0) { return float2(0, 0); } else if (vertexIndex % 3 == 1) { return float2(cos(baseAngle), sin(baseAngle)); } else { return float2(cos(baseAngle + incAngle), sin(baseAngle + incAngle)); } } pub fn rectFromIndex(index: int, vertices: int): float2 { let x = index % vertices; let y = index / vertices; return float2(x, y) / float(vertices) * 2.0 - 1.0; } pub fn empty(numVerts: int = 0) -> Mesh { let g = Mesh::new(); if (numVerts > 0) { g.setVertices(array(numVerts, 0.xyz)); g.setNormals(array(numVerts, 0.xyz)); g.setTangents(array(numVerts, 0.xyz)); g.setBitangents(array(numVerts, 0.xyz)); g.setUVs(array(numVerts, 0.xy)); g.setColors(array(numVerts, 0.xyzw)); let tris = array(numVerts, 0); for (let i = 0; i < numVerts; i++) { tris[i] = i; } g.setTriangles(tris); } return g; } pub fn join(mesh1: Mesh, mesh2: Mesh) { let g = Mesh::new(); g.append(mesh1); g.append(mesh2); return g; } // pub fn cylinder(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.cylinder(pos, radius, height, vertices); // return g; // } // pub fn capsule(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.capsule(pos, radius, height, vertices); // return g; // } // pub fn cone(pos: float3, radius: float, height: float, vertices: int = 32) -> Mesh { // let g = Mesh::new(); // g.cone(pos, radius, height, vertices); // return g; // } } pub struct Material { pub baseColor: float4, pub color: texture2d, pub normal: texture2d, pub normalScale: float2, pub roughness: texture2d, pub emissive: texture2d, pub metallic: texture2d, } pub struct ModelPart { pub mesh: Mesh, pub material: Material, pub transform: float4x4, } pub struct Model { pub parts: ModelPart[], } window.SHD_Mesh = Mesh; window.SHD_Model = Model; window.SHD_ModelPart = ModelPart; window.SHD_Material = Material; ================================================ FILE: lang/shadeup/library/mesh.ts ================================================ ================================================ FILE: lang/shadeup/library/native.ts ================================================ import { float4, float3, float, float2, bool, int } from '/std_math'; import { texture2d } from '/_std/texture'; import { Camera, Camera2d, quat } from '/_std/common'; export function shadeupMakeTextureFromUrl(url: string): texture2d { return (window as any)['shadeupMakeTextureFromUrlNative'](url); } export class FrameContext { /** Delta between the previous frame's time and this frame (in seconds */ deltaTime: float; /** Current time in seconds from the start of the renderer */ time: float; /** Canvas size in pixels */ screenSize: float2; /** Current frame index */ frame: int; /** Mouse/touch screen input state for this frame */ mouse: MouseInputState = new MouseInputState(); /** Keyboard input state for this frame */ keyboard: KeyboardInputState = new KeyboardInputState(); /** Controllable camera (Hold right click and use WASD to move) */ camera: Camera = new Camera(); camera2d: Camera2d = new Camera2d(); configureCamera(options: { mode?: 'free' | 'orbit' | 'orbit-free'; spinning?: boolean; initialPosition?: float3; initialPitch?: float; initialYaw?: float; speed?: float; orbitTarget?: float3; orbitDistance?: float; orbitPitch?: float; orbitYaw?: float; orbitMinDistance?: float; orbitMaxDistance?: float; orbitMinPitch?: float; orbitMaxPitch?: float; }) {} /** * Use external values from the host JavaScript environment. */ input(key: string, defaultValue: T): T { return defaultValue; } /** * Send values to the host JavaScript environment. */ output(key: string, value: T) {} } export class MouseInputState { /** Current mouse position relative to canvas in pixels ((0, 0) is the top left */ screen: float2; /** Current mouse position mapped from 0-1 in canvas space ((0, 0) is the top left while (1, 1) is the bottom right */ uv: float2; /** Caches the mouse position relative to canvas in pixels when any mouse button is pressed (resets after subsequent presses */ startScreen: float2; /** Caches the mouse position mapped from 0-1 in canvas space when any mouse button is pressed (resets after subsequent presses */ startUv: float2; /** If dragging, this will be the delta between the start and current mouse position */ deltaUv: float2; /** If dragging, this will be the delta between the mouse position last frame and the current mouse position */ frameDeltaUv: float2; /** If dragging, this will be the delta between the start and current mouse position */ deltaScreen: float2; /** If dragging, this will be the delta between the mouse position last frame and the current mouse position */ frameDeltaScreen: float2; /** , Some("Mouse button down state for buttons 0-3 (left, middle, right */ button: [boolean, boolean, boolean] = [false, false, false]; /** Mouse button pressed state for buttons 0-3 (left, middle, right) */ clicked: [boolean, boolean, boolean] = [false, false, false]; /** If currently dragging */ dragging: bool; /** Accumulated mouse wheel movement for this frame in the range of -1 to 1 */ wheel: float; /** Rate of change */ velocity: float; /** Is the mouse focused within the screen */ focused: bool; } export class KeyboardInputState { /** Is key down this frame */ backspace: bool; /** Is key down this frame */ tab: bool; /** Is key down this frame */ enter: bool; /** Is key down this frame */ shiftLeft: bool; /** Is key down this frame */ shiftRight: bool; /** Is key down this frame */ controlLeft: bool; /** Is key down this frame */ controlRight: bool; /** Is key down this frame */ altLeft: bool; /** Is key down this frame */ altRight: bool; /** Is key down this frame */ pause: bool; /** Is key down this frame */ capsLock: bool; /** Is key down this frame */ escape: bool; /** Is key down this frame */ space: bool; /** Is key down this frame */ pageUp: bool; /** Is key down this frame */ pageDown: bool; /** Is key down this frame */ end: bool; /** Is key down this frame */ home: bool; /** Is key down this frame */ arrowLeft: bool; /** Is key down this frame */ arrowUp: bool; /** Is key down this frame */ arrowRight: bool; /** Is key down this frame */ arrowDown: bool; /** Is key down this frame */ printScreen: bool; /** Is key down this frame */ insert: bool; /** Is key down this frame */ delete: bool; /** Is key down this frame */ digit0: bool; /** Is key down this frame */ digit1: bool; /** Is key down this frame */ digit2: bool; /** Is key down this frame */ digit3: bool; /** Is key down this frame */ digit4: bool; /** Is key down this frame */ digit5: bool; /** Is key down this frame */ digit6: bool; /** Is key down this frame */ digit7: bool; /** Is key down this frame */ digit8: bool; /** Is key down this frame */ digit9: bool; /** Is key down this frame */ keyA: bool; /** Is key down this frame */ keyB: bool; /** Is key down this frame */ keyC: bool; /** Is key down this frame */ keyD: bool; /** Is key down this frame */ keyE: bool; /** Is key down this frame */ keyF: bool; /** Is key down this frame */ keyG: bool; /** Is key down this frame */ keyH: bool; /** Is key down this frame */ keyI: bool; /** Is key down this frame */ keyJ: bool; /** Is key down this frame */ keyK: bool; /** Is key down this frame */ keyL: bool; /** Is key down this frame */ keyM: bool; /** Is key down this frame */ keyN: bool; /** Is key down this frame */ keyO: bool; /** Is key down this frame */ keyP: bool; /** Is key down this frame */ keyQ: bool; /** Is key down this frame */ keyR: bool; /** Is key down this frame */ keyS: bool; /** Is key down this frame */ keyT: bool; /** Is key down this frame */ keyU: bool; /** Is key down this frame */ keyV: bool; /** Is key down this frame */ keyW: bool; /** Is key down this frame */ keyX: bool; /** Is key down this frame */ keyY: bool; /** Is key down this frame */ keyZ: bool; /** Is key down this frame */ metaLeft: bool; /** Is key down this frame */ metaRight: bool; /** Is key down this frame */ contextMenu: bool; /** Is key down this frame */ numpad0: bool; /** Is key down this frame */ numpad1: bool; /** Is key down this frame */ numpad2: bool; /** Is key down this frame */ numpad3: bool; /** Is key down this frame */ numpad4: bool; /** Is key down this frame */ numpad5: bool; /** Is key down this frame */ numpad6: bool; /** Is key down this frame */ numpad7: bool; /** Is key down this frame */ numpad8: bool; /** Is key down this frame */ numpad9: bool; /** Is key down this frame */ numpadMultiply: bool; /** Is key down this frame */ numpadAdd: bool; /** Is key down this frame */ numpadSubtract: bool; /** Is key down this frame */ numpadDecimal: bool; /** Is key down this frame */ numpadDivide: bool; /** Is key down this frame */ f1: bool; /** Is key down this frame */ f2: bool; /** Is key down this frame */ f3: bool; /** Is key down this frame */ f4: bool; /** Is key down this frame */ f5: bool; /** Is key down this frame */ f6: bool; /** Is key down this frame */ f7: bool; /** Is key down this frame */ f8: bool; /** Is key down this frame */ f9: bool; /** Is key down this frame */ f10: bool; /** Is key down this frame */ f11: bool; /** Is key down this frame */ f12: bool; /** Is key down this frame */ numLock: bool; /** Is key down this frame */ scrollLock: bool; /** Is key down this frame */ semicolon: bool; /** Is key down this frame */ equal: bool; /** Is key down this frame */ comma: bool; /** Is key down this frame */ minus: bool; /** Is key down this frame */ period: bool; /** Is key down this frame */ slash: bool; /** Is key down this frame */ backquote: bool; /** Is key down this frame */ bracketLeft: bool; /** Is key down this frame */ backslash: bool; /** Is key down this frame */ bracketRight: bool; /** Is key down this frame */ quote: bool; /** Key pressed, triggered once until released */ pressedBackspace: bool; /** Key pressed, triggered once until released */ pressedTab: bool; /** Key pressed, triggered once until released */ pressedEnter: bool; /** Key pressed, triggered once until released */ pressedShiftLeft: bool; /** Key pressed, triggered once until released */ pressedShiftRight: bool; /** Key pressed, triggered once until released */ pressedControlLeft: bool; /** Key pressed, triggered once until released */ pressedControlRight: bool; /** Key pressed, triggered once until released */ pressedAltLeft: bool; /** Key pressed, triggered once until released */ pressedAltRight: bool; /** Key pressed, triggered once until released */ pressedPause: bool; /** Key pressed, triggered once until released */ pressedCapsLock: bool; /** Key pressed, triggered once until released */ pressedEscape: bool; /** Key pressed, triggered once until released */ pressedSpace: bool; /** Key pressed, triggered once until released */ pressedPageUp: bool; /** Key pressed, triggered once until released */ pressedPageDown: bool; /** Key pressed, triggered once until released */ pressedEnd: bool; /** Key pressed, triggered once until released */ pressedHome: bool; /** Key pressed, triggered once until released */ pressedArrowLeft: bool; /** Key pressed, triggered once until released */ pressedArrowUp: bool; /** Key pressed, triggered once until released */ pressedArrowRight: bool; /** Key pressed, triggered once until released */ pressedArrowDown: bool; /** Key pressed, triggered once until released */ pressedPrintScreen: bool; /** Key pressed, triggered once until released */ pressedInsert: bool; /** Key pressed, triggered once until released */ pressedDelete: bool; /** Key pressed, triggered once until released */ pressedDigit0: bool; /** Key pressed, triggered once until released */ pressedDigit1: bool; /** Key pressed, triggered once until released */ pressedDigit2: bool; /** Key pressed, triggered once until released */ pressedDigit3: bool; /** Key pressed, triggered once until released */ pressedDigit4: bool; /** Key pressed, triggered once until released */ pressedDigit5: bool; /** Key pressed, triggered once until released */ pressedDigit6: bool; /** Key pressed, triggered once until released */ pressedDigit7: bool; /** Key pressed, triggered once until released */ pressedDigit8: bool; /** Key pressed, triggered once until released */ pressedDigit9: bool; /** Key pressed, triggered once until released */ pressedKeyA: bool; /** Key pressed, triggered once until released */ pressedKeyB: bool; /** Key pressed, triggered once until released */ pressedKeyC: bool; /** Key pressed, triggered once until released */ pressedKeyD: bool; /** Key pressed, triggered once until released */ pressedKeyE: bool; /** Key pressed, triggered once until released */ pressedKeyF: bool; /** Key pressed, triggered once until released */ pressedKeyG: bool; /** Key pressed, triggered once until released */ pressedKeyH: bool; /** Key pressed, triggered once until released */ pressedKeyI: bool; /** Key pressed, triggered once until released */ pressedKeyJ: bool; /** Key pressed, triggered once until released */ pressedKeyK: bool; /** Key pressed, triggered once until released */ pressedKeyL: bool; /** Key pressed, triggered once until released */ pressedKeyM: bool; /** Key pressed, triggered once until released */ pressedKeyN: bool; /** Key pressed, triggered once until released */ pressedKeyO: bool; /** Key pressed, triggered once until released */ pressedKeyP: bool; /** Key pressed, triggered once until released */ pressedKeyQ: bool; /** Key pressed, triggered once until released */ pressedKeyR: bool; /** Key pressed, triggered once until released */ pressedKeyS: bool; /** Key pressed, triggered once until released */ pressedKeyT: bool; /** Key pressed, triggered once until released */ pressedKeyU: bool; /** Key pressed, triggered once until released */ pressedKeyV: bool; /** Key pressed, triggered once until released */ pressedKeyW: bool; /** Key pressed, triggered once until released */ pressedKeyX: bool; /** Key pressed, triggered once until released */ pressedKeyY: bool; /** Key pressed, triggered once until released */ pressedKeyZ: bool; /** Key pressed, triggered once until released */ pressedMetaLeft: bool; /** Key pressed, triggered once until released */ pressedMetaRight: bool; /** Key pressed, triggered once until released */ pressedContextMenu: bool; /** Key pressed, triggered once until released */ pressedNumpad0: bool; /** Key pressed, triggered once until released */ pressedNumpad1: bool; /** Key pressed, triggered once until released */ pressedNumpad2: bool; /** Key pressed, triggered once until released */ pressedNumpad3: bool; /** Key pressed, triggered once until released */ pressedNumpad4: bool; /** Key pressed, triggered once until released */ pressedNumpad5: bool; /** Key pressed, triggered once until released */ pressedNumpad6: bool; /** Key pressed, triggered once until released */ pressedNumpad7: bool; /** Key pressed, triggered once until released */ pressedNumpad8: bool; /** Key pressed, triggered once until released */ pressedNumpad9: bool; /** Key pressed, triggered once until released */ pressedNumpadMultiply: bool; /** Key pressed, triggered once until released */ pressedNumpadAdd: bool; /** Key pressed, triggered once until released */ pressedNumpadSubtract: bool; /** Key pressed, triggered once until released */ pressedNumpadDecimal: bool; /** Key pressed, triggered once until released */ pressedNumpadDivide: bool; /** Key pressed, triggered once until released */ pressedF1: bool; /** Key pressed, triggered once until released */ pressedF2: bool; /** Key pressed, triggered once until released */ pressedF3: bool; /** Key pressed, triggered once until released */ pressedF4: bool; /** Key pressed, triggered once until released */ pressedF5: bool; /** Key pressed, triggered once until released */ pressedF6: bool; /** Key pressed, triggered once until released */ pressedF7: bool; /** Key pressed, triggered once until released */ pressedF8: bool; /** Key pressed, triggered once until released */ pressedF9: bool; /** Key pressed, triggered once until released */ pressedF10: bool; /** Key pressed, triggered once until released */ pressedF11: bool; /** Key pressed, triggered once until released */ pressedF12: bool; /** Key pressed, triggered once until released */ pressedNumLock: bool; /** Key pressed, triggered once until released */ pressedScrollLock: bool; /** Key pressed, triggered once until released */ pressedSemicolon: bool; /** Key pressed, triggered once until released */ pressedEqual: bool; /** Key pressed, triggered once until released */ pressedComma: bool; /** Key pressed, triggered once until released */ pressedMinus: bool; /** Key pressed, triggered once until released */ pressedPeriod: bool; /** Key pressed, triggered once until released */ pressedSlash: bool; /** Key pressed, triggered once until released */ pressedBackquote: bool; /** Key pressed, triggered once until released */ pressedBracketLeft: bool; /** Key pressed, triggered once until released */ pressedBackslash: bool; /** Key pressed, triggered once until released */ pressedBracketRight: bool; /** Key pressed, triggered once until released */ pressedQuote: bool; /** 2D vector that encodes the arrow keys and WASD aligned with the screen (e.g. up arrow = (0, -1)) */ arrowVector: float2; } declare global { const env: FrameContext; } ================================================ FILE: lang/shadeup/library/paint.ts ================================================ type GraphicsAdapter = { drawImage(image: HTMLCanvasElement): void; addEventListener(name: string, fn: (...args: any) => void): void; activatePaintContext(): void; }; import type { float4, float2 } from './types'; export class PaintingContext { markDirtyCallback: () => void = () => {}; constructor(canvas: HTMLCanvasElement, gl: GraphicsAdapter | null) { if (!gl) return; this.__gl = gl; this.__canvas = canvas; this.__offscreen_canvas = document.createElement('canvas'); this.__offscreen_canvas.width = canvas.width; this.__offscreen_canvas.height = canvas.height; // document.body.appendChild(this.__offscreen_canvas); this.__ctx = this.__offscreen_canvas.getContext('2d', { willReadFrequently: true })!; this.__offscreen_canvas.style.position = 'absolute'; this.__offscreen_canvas.style.zIndex = '10'; // document.body.appendChild(this.__offscreen_canvas); this.__setColor([0, 0, 0, 1] as float4); gl.addEventListener('context', (toContext: string) => { if (toContext == 'draw') { this.flush(); } }); gl.addEventListener('flush', () => { this.flush(); }); } flush() { if (!this.__gl) return; if (!this.__canvas) return; if (!this.__offscreen_canvas) return; if (!this.stagedChanges) return; if (this.fastPoints) this.flushPoints(); this.__gl.drawImage(this.__offscreen_canvas); this.stagedChanges = false; if ( this.__offscreen_canvas.width != this.__canvas.width || this.__offscreen_canvas.height != this.__canvas.height ) { this.__offscreen_canvas.width = this.__canvas.width; this.__offscreen_canvas.height = this.__canvas.height; } this.pointsCounter = 0; } private __ctx: CanvasRenderingContext2D | null = null; private __gl: GraphicsAdapter | null = null; private __offscreen_canvas: HTMLCanvasElement | null = null; private __program: WebGLProgram | null = null; private stagedChanges: boolean = false; private dirty: boolean = false; private fastPoints: boolean = false; private fastPointsBuffer: ImageData | null = null; private __beforeDraw() { if (!this.__offscreen_canvas) return; if (!this.__ctx) return; if (!this.__canvas) return; this.markDirtyCallback(); this.__gl?.activatePaintContext(); if (!this.stagedChanges) { this.__ctx.clearRect(0, 0, this.__canvas.width, this.__canvas.height); this.__ctx.drawImage(this.__canvas, 0, 0); let color = this.__currentColor; this.__ctx.fillStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${ color[3] })`; this.__ctx.strokeStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${ color[3] })`; } } private __afterDraw() { let gl = this.__gl; this.dirty = true; this.stagedChanges = true; } private __currentColor: number[] | null = null; private __setColor(color?: float4) { if (!this.__ctx || !color) return; if ( this.__currentColor && this.__currentColor[0] == color[0] && this.__currentColor[1] == color[1] && this.__currentColor[2] == color[2] && this.__currentColor[3] == color[3] ) return; this.__ctx.strokeStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${ color[3] })`; this.__ctx.fillStyle = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${ color[3] })`; this.__currentColor = [color[0], color[1], color[2], color[3]]; } fillRect(pos: float2, size: float2, color?: float4) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.fillRect(pos[0], pos[1], size[0], size[1]); this.__afterDraw(); this.pointsCounter = 0; } fillCircle(pos: float2, radius: number, color?: float4) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; } fillArc(pos: float2, radius: number, startAngle: number, endAngle: number, color?: float4) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; } line(pos1: float2, pos2: float2, color?: float4, width: number = 1) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.moveTo(pos1[0], pos1[1]); this.__ctx.lineTo(pos2[0], pos2[1]); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; } circle(pos: float2, radius: number, color?: float4, width: number = 1) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; } arc( pos: float2, radius: number, startAngle: number, endAngle: number, color?: float4, width: number = 1 ) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.__ctx.arc(pos[0], pos[1], radius, startAngle, endAngle); this.__ctx.lineWidth = width; this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; } text(pos: float2, text: string, color?: float4) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__setColor(color); this.__ctx.fillText(text, pos[0], pos[1]); this.__afterDraw(); this.pointsCounter = 0; } startPath(pos: float2) { if (!this.__ctx) return; this.flushPoints(); this.__beforeDraw(); this.__ctx.beginPath(); this.__ctx.moveTo(pos[0], pos[1]); } lineTo(pos: float2) { if (!this.__ctx) return; this.__ctx.lineTo(pos[0], pos[1]); } strokePath(color?: float4, width: number = 1) { if (!this.__ctx) return; this.__ctx.lineWidth = width; this.__setColor(color); this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; } fillPath(color?: float4) { if (!this.__ctx) return; this.__setColor(color); this.__ctx.fill(); this.__afterDraw(); this.pointsCounter = 0; } setStrokeWidth(width: number) { if (!this.__ctx) return; this.__ctx.lineWidth = width; } setFont(font: string) { if (!this.__ctx) return; this.__ctx.font = font; } setFontSize(size: number) { if (!this.__ctx) return; this.__ctx.font = `${size}px ${this.__ctx.font.split(' ').slice(1).join(' ')}`; } setTextAlign(align: CanvasTextAlign) { if (!this.__ctx) return; this.__ctx.textAlign = align; } setTextBaseline(baseline: CanvasTextBaseline) { if (!this.__ctx) return; this.__ctx.textBaseline = baseline; } setLineCap(cap: 'butt' | 'round' | 'square') { if (!this.__ctx) return; this.__ctx.lineCap = cap; } setLineJoin(join: CanvasLineJoin) { if (!this.__ctx) return; this.__ctx.lineJoin = join; } setMiterLimit(limit: number) { if (!this.__ctx) return; this.__ctx.miterLimit = limit; } setShadowColor(color: float4) { if (!this.__ctx) return; this.__ctx.shadowColor = `rgba(${color[0] * 255}, ${color[1] * 255}, ${color[2] * 255}, ${ color[3] })`; } setShadowBlur(blur: number) { if (!this.__ctx) return; this.__ctx.shadowBlur = blur; } setShadowOffset(offset: float2) { if (!this.__ctx) return; this.__ctx.shadowOffsetX = offset[0]; this.__ctx.shadowOffsetY = offset[1]; } setGlobalAlpha(alpha: number) { if (!this.__ctx) return; this.__ctx.globalAlpha = alpha; } setGlobalCompositeOperation(op: string) { if (!this.__ctx) return; this.__ctx.globalCompositeOperation = op as any; } setImageSmoothingEnabled(enabled: boolean) { if (!this.__ctx) return; this.__ctx.imageSmoothingEnabled = enabled; } setImageSmoothingQuality(quality: ImageSmoothingQuality) { if (!this.__ctx) return; this.__ctx.imageSmoothingQuality = quality; } setLineDash(dash: number[]) { if (!this.__ctx) return; this.__ctx.setLineDash(dash); } setLineDashOffset(offset: number) { if (!this.__ctx) return; this.__ctx.lineDashOffset = offset; } setTransform(a: number, b: number, c: number, d: number, e: number, f: number) { if (!this.__ctx) return; this.__ctx.setTransform(a, b, c, d, e, f); } resetTransform() { if (!this.__ctx) return; this.__ctx.resetTransform(); } scale(v: float2) { if (!this.__ctx) return; this.__ctx.scale(v[0], v[1]); } rotate(angle: number) { if (!this.__ctx) return; this.__ctx.rotate(angle); } translate(v: float2) { if (!this.__ctx) return; this.__ctx.translate(v[0], v[1]); } private flushPoints() { if (!this.__ctx) return; if (!this.fastPoints) return; if (!this.fastPointsBuffer) return; this.__ctx.putImageData(this.fastPointsBuffer, 0, 0); this.fastPoints = false; this.fastPointsBuffer = null; this.pointsCounter = 0; } private pointsCounter: number = 0; private cacheSize: [number, number] = [0, 0]; point(pos: float2, color?: float4) { if (!this.__ctx) return; this.pointsCounter++; this.__beforeDraw(); if (this.pointsCounter > 10) { if (!this.fastPoints) { this.fastPoints = true; this.cacheSize = [this.__offscreen_canvas!.width, this.__offscreen_canvas!.height]; this.fastPointsBuffer = this.__ctx.getImageData(0, 0, this.cacheSize[0], this.cacheSize[1]); } if (!this.fastPointsBuffer) return; let x = Math.floor(pos[0]); let y = Math.floor(pos[1]); let index = (y * this.cacheSize[0] + x) * 4; if (!color) { color = this.__currentColor; } let oldColorx = this.fastPointsBuffer.data[index] / 255; let oldColory = this.fastPointsBuffer.data[index + 1] / 255; let oldColorz = this.fastPointsBuffer.data[index + 2] / 255; let oldColora = this.fastPointsBuffer.data[index + 3] / 255; this.fastPointsBuffer.data[index] = color[0] * 255 * color[3] + oldColorx * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 1] = color[1] * 255 * color[3] + oldColory * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 2] = color[2] * 255 * color[3] + oldColorz * 255 * (1 - color[3]); this.fastPointsBuffer.data[index + 3] = color[3] * 255 + oldColora * 255 * (1 - color[3]); } else { this.__setColor(color); this.__ctx.fillRect(pos[0], pos[1], 1, 1); } this.__afterDraw(); } vector( pos: float2, dir: float2, color: float4 = [0.9803921568627451, 0.8, 0.08235294117647059, 1] as float4, width: number = 4 ) { if (!this.__ctx || (dir[0] == 0 && dir[1] == 0)) return; this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.setStrokeWidth(width); this.__ctx.moveTo(pos[0], pos[1]); this.__ctx.lineCap = 'round'; this.__ctx.lineTo(pos[0] + dir[0], pos[1] + dir[1]); this.__ctx.stroke(); this.__ctx.beginPath(); this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]); // Arrows let arrowSize = 20; let arrowAngle = Math.PI / 5; let dirAngle = Math.atan2(dir[1], dir[0]) + Math.PI; let arrow1 = [ Math.cos(dirAngle + arrowAngle) * arrowSize, Math.sin(dirAngle + arrowAngle) * arrowSize ]; let arrow2 = [ Math.cos(dirAngle - arrowAngle) * arrowSize, Math.sin(dirAngle - arrowAngle) * arrowSize ]; this.__ctx.lineTo(pos[0] + dir[0] + arrow1[0], pos[1] + dir[1] + arrow1[1]); this.__ctx.moveTo(pos[0] + dir[0], pos[1] + dir[1]); this.__ctx.lineTo(pos[0] + dir[0] + arrow2[0], pos[1] + dir[1] + arrow2[1]); this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; } grid( center: float2, count: float2, gap: float2, color: float4 = [0.1607843137254902, 0.1450980392156863, 0.1411764705882353, 1] as float4, width: number = 2 ) { if (!this.__ctx) return; this.__beforeDraw(); this.__setColor(color); this.__ctx.beginPath(); this.setStrokeWidth(width); let start = [ center[0] - (count[0] / 2) * gap[0], center[1] - (count[1] / 2) * gap[1] ] as float2; for (let i = 0; i <= count[0]; i++) { this.__ctx.moveTo(start[0] + i * gap[0], start[1]); this.__ctx.lineTo(start[0] + i * gap[0], start[1] + count[1] * gap[1]); } for (let i = 0; i <= count[1]; i++) { this.__ctx.moveTo(start[0], start[1] + i * gap[1]); this.__ctx.lineTo(start[0] + count[0] * gap[0], start[1] + i * gap[1]); } this.__ctx.stroke(); this.__afterDraw(); this.pointsCounter = 0; } } declare global { const paint: PaintingContext; } ================================================ FILE: lang/shadeup/library/physics.ts ================================================ import type RAPIER2DNamespace from '@dimforge/rapier2d/rapier'; import type RAPIER3DNamespace from '@dimforge/rapier3d/rapier'; import type { float, float2, float3 } from './types'; type RAPIER2D = typeof RAPIER2DNamespace; export class PhysicsCollider2d { rapier: RAPIER2D; world: RAPIER2DNamespace.World; collider: RAPIER2DNamespace.Collider; constructor( rapier: RAPIER2D, world: RAPIER2DNamespace.World, collider: RAPIER2DNamespace.Collider ) { this.rapier = rapier; this.world = world; this.collider = collider; } setTranslation(position: float2) { this.collider.setTranslation(toVec2(position)); } setRotation(rotation: float) { this.collider.setRotation(rotation); } setSensor(isSensor: boolean) { this.collider.setSensor(isSensor); } setCollisionGroups(groups: int) { this.collider.setCollisionGroups(groups); } setCollidesWith(groups: int) { this.collider.setActiveCollisionTypes(groups); } setFriction(friction: float) { this.collider.setFriction(friction); } setRestitution(restitution: float) { this.collider.setRestitution(restitution); } setDensity(density: float) { this.collider.setDensity(density); } setMass(mass: float) { this.collider.setMass(mass); } setRadius(radius: float) { this.collider.setRadius(radius); } setHalfExtents(halfExtents: float2) { this.collider.setHalfExtents(toVec2(halfExtents)); } } function toVec2(v: float2): RAPIER2DNamespace.Vector2 { return { x: v[0], y: v[1] }; } function toVec3(v: float3): RAPIER3DNamespace.Vector { return { x: v[0], y: v[1], z: v[2] }; } export class PhysicsRayCastResult2d { rapier: RAPIER2D; result: RAPIER2DNamespace.RayIntersection; constructor(rapier: RAPIER2D, result: RAPIER2DNamespace.RayIntersection) { this.rapier = rapier; this.result = result; } } export class PhysicsRigidBody2d { rapier: RAPIER2D; world: RAPIER2DNamespace.World; body: RAPIER2DNamespace.RigidBody; constructor(rapier: RAPIER2D, world: RAPIER2DNamespace.World, body: RAPIER2DNamespace.RigidBody) { this.rapier = rapier; this.world = world; this.body = body; } addBallCollider(radius: float): PhysicsCollider2d { let colDesc = this.rapier.ColliderDesc.ball(radius); let col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); } addBoxCollider(halfExtents: float2): PhysicsCollider2d { let colDesc = this.rapier.ColliderDesc.cuboid(halfExtents[0], halfExtents[1]); let col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); } addCapsuleCollider(radius: float, halfHeight: float): PhysicsCollider2d { let colDesc = this.rapier.ColliderDesc.capsule(radius, halfHeight); let col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); } addTriangleCollider(a: float2, b: float2, c: float2): PhysicsCollider2d { let colDesc = this.rapier.ColliderDesc.triangle(toVec2(a), toVec2(b), toVec2(c)); let col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); } addConvexCollider(points: float2[]): PhysicsCollider2d { let floatarr = new Float32Array(points.length * 2); for (let i = 0; i < points.length; i++) { floatarr[i * 2 + 0] = points[i][0]; floatarr[i * 2 + 1] = points[i][1]; } let colDesc = this.rapier.ColliderDesc.convexHull(floatarr); if (!colDesc) throw new Error('Failed to create convex hull collider'); let col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); } addHeightfieldCollider(heights: float[], scale: float2): PhysicsCollider2d { let arr = new Float32Array(heights.length); for (let i = 0; i < heights.length; i++) { arr[i] = heights[i]; } let colDesc = this.rapier.ColliderDesc.heightfield(arr, toVec2(scale)); let col = this.world.createCollider(colDesc, this.body); return new PhysicsCollider2d(this.rapier, this.world, col); } setTranslation(position: float2) { this.body.setTranslation(toVec2(position), true); } setRotation(rotation: float) { this.body.setRotation(rotation, true); } setVelocity(velocity: float2) { this.body.setLinvel(toVec2(velocity), true); } setAngularVelocity(velocity: float) { this.body.setAngvel(velocity, true); } addForce(force: float2) { this.body.addForce(toVec2(force), true); } addForceAtPoint(force: float2, point: float2) { this.body.addForceAtPoint(toVec2(force), toVec2(point), true); } addTorque(torque: float) { this.body.addTorque(torque, true); } setAdditionalMass(mass: float) { this.body.setAdditionalMass(mass, true); } setEnabled(enabled: boolean) { this.body.setEnabled(enabled); } sleep() { this.body.sleep(); } wakeUp() { this.body.wakeUp(); } setGravityScale(scale: float) { this.body.setGravityScale(scale, true); } setLinearDamping(damping: float) { this.body.setLinearDamping(damping); } setAngularDamping(damping: float) { this.body.setAngularDamping(damping); } isSleeping(): boolean { return this.body.isSleeping(); } mass(): float { return this.body.mass() as float; } translation(): float2 { let t = this.body.translation(); return [t.x as float, t.y as float]; } rotation(): float { return this.body.rotation() as float; } velocity(): float2 { let t = this.body.linvel(); return [t.x as float, t.y as float]; } angularVelocity(): float { return this.body.angvel() as float; } isMoving(): boolean { return this.body.isMoving(); } collider(index: int): PhysicsCollider2d { let collider = this.body.collider(index); if (!collider) throw new Error('Failed to get collider'); return new PhysicsCollider2d(this.rapier, this.world, collider); } applyImpulse(impulse: float2) { this.body.applyImpulse(toVec2(impulse), true); } applyTorqueImpulse(impulse: float) { this.body.applyTorqueImpulse(impulse, true); } } export class PhysicsEngine2d { rapier: RAPIER2D; world: RAPIER2DNamespace.World; constructor(rapier: RAPIER2D) { this.rapier = rapier; this.world = new rapier.World(new rapier.Vector2(0.0, -9.81)); } step() { this.world.step(); } createRigidBody( position: float2, rotation: float, mode: 'dynamic' | 'fixed' ): PhysicsRigidBody2d { let rbDesc = mode == 'dynamic' ? this.rapier.RigidBodyDesc.dynamic() : mode == 'fixed' ? this.rapier.RigidBodyDesc.fixed() : this.rapier.RigidBodyDesc.dynamic(); rbDesc.setTranslation(position[0], position[1]); rbDesc.setRotation(rotation); let rb = this.world.createRigidBody(rbDesc); return new PhysicsRigidBody2d(this.rapier, this.world, rb); } bodies(): PhysicsRigidBody2d[] { let bodies = this.world.bodies; let result: PhysicsRigidBody2d[] = []; for (let i = 0; i < bodies.len(); i++) { result.push(new PhysicsRigidBody2d(this.rapier, this.world, bodies.get(i)!)); } return result; } castRay(start: float2, end: float2, maxi: int): PhysicsRigidBody2d | null { let result = this.world.castRay(new this.rapier.Ray(toVec2(start), toVec2(end)), maxi, true); if (!result) return null; return new PhysicsRigidBody2d(this.rapier, this.world, result.collider.parent()!); } setGravity(gravity: float2) { this.world.gravity = toVec2(gravity); } } export class PhysicsEngine3d { constructor() {} } export namespace physics { export function engine2d(): PhysicsEngine2d { return new PhysicsEngine2d((window as any).RAPIER_2D); } } ================================================ FILE: lang/shadeup/library/sdf.shadeup ================================================ /** * Heplful utility for working with signed distance fields. * Most of the implementation was taken from https://iquilezles.org/articles/distfunctions/ */ pub struct sdf {} fn dot2( v: float2 ) -> float { return dot(v,v); } fn dot3( v: float3 ) -> float { return dot(v,v); } fn ndot( a: float2, b: float2 ) -> float { return a.x*b.x - a.y*b.y; } impl sdf { pub fn sphere(samplePosition: float3, sphereCenter: float3, radius: float) -> float { let p = samplePosition - sphereCenter; let r = radius; return length(p) - r; } pub fn box(samplePosition: float3, boxCenter: float3, boxSize: float3) -> float { let p = samplePosition - boxCenter; let s = boxSize; let q = abs(p) - s; return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.0); } pub fn roundBox(samplePosition: float3, boxCenter: float3, boxSize: float3, cornerRadius: float) -> float { let p = samplePosition - boxCenter; let s = boxSize; let r = cornerRadius; let q = abs(p) - s; return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r; } pub fn boxFrame(samplePosition: float3, boxCenter: float3, boxSize: float3, frameThickness: float) -> float { let p = samplePosition - boxCenter; let b = boxSize; let e = frameThickness; p = abs(p )-b; let q = abs(p+e)-e; return min(min( length(max(float3(p.x,q.y,q.z),0.0))+min(max(p.x,max(q.y,q.z)),0.0), length(max(float3(q.x,p.y,q.z),0.0))+min(max(q.x,max(p.y,q.z)),0.0)), length(max(float3(q.x,q.y,p.z),0.0))+min(max(q.x,max(q.y,p.z)),0.0)); } pub fn torus( samplePosition: float3, torusCenter: float3, torusSize: float2 ) -> float { let p = samplePosition - torusCenter; let t = torusSize; let q = float2(length(p.xz)-t.x,p.y); return length(q)-t.y; } pub fn cappedTorus( samplePosition: float3, torusCenter: float3, torusSize: float2, ra: float, rb: float) -> float { let p1 = samplePosition - torusCenter; let p = (abs(p1.x), p1.yz); let sc = torusSize; let k = (sc.y*p.x>sc.x*p.y) ? dot(p.xy,sc) : length(p.xy); return sqrt( dot(p,p) + ra*ra - 2.0*ra*k ) - rb; } pub fn link( samplePosition: float3, linkCenter: float3, linkLength: float, r1: float, r2: float ) -> float { let p = samplePosition - linkCenter; let le = linkLength; let q = float3( p.x, max(abs(p.y)-le,0.0), p.z ); return length(float2(length(q.xy)-r1,q.z)) - r2; } pub fn infinteCylinder( samplePosition: float3, cylinderCenter: float3, cylinderSize: float3) -> float { let p = samplePosition - cylinderCenter; let c = cylinderSize; return length(p.xz-c.xy)-c.z; } pub fn cone( samplePosition: float3, coneCenter: float3, c: float2, coneHeight: float ) -> float { let p = samplePosition - coneCenter; let h = coneHeight; // c is the sin/cos of the angle, h is height // Alternatively pass q instead of (c,h), // which is the point at the base in 2D let q = h*float2(c.x/c.y,-1.0); let w = float2( length(p.xz), p.y ); let a = w - q*clamp( dot(w,q)/dot(q,q), 0.0, 1.0 ); let b = w - q*float2( clamp( w.x/q.x, 0.0, 1.0 ), 1.0 ); let k = sign( q.y ); let d = min(dot( a, a ),dot(b, b)); let s = max( k*(w.x*q.y-w.y*q.x),k*(w.y-q.y) ); return sqrt(d)*sign(s); } pub fn plane( samplePosition: float3, planeCenter: float3, planeNormal: float3, planeHeight: float ) -> float { let p = samplePosition - planeCenter; let n = planeNormal; let h = planeHeight; // n must be normalized return dot(p,n) + h; } pub fn hexPrism( samplePosition: float3, hexCenter: float3, hexSize: float2 ) -> float { let p = samplePosition - hexCenter; let h = hexSize; let k = float3(-0.8660254, 0.5, 0.57735); p = abs(p); let dddd = min(dot(k.xy, p.xy), 0.0) * 2.0; p = p - float3(dddd * k.xy, 0.0); let d = float2( length(p.xy-float2(clamp(p.x,-k.z*h.x,k.z*h.x), h.x))*sign(p.y-h.x), p.z-h.y ); return min(max(d.x,d.y),0.0) + length(max(d,0.0)); } pub fn triPrism( samplePosition: float3, triCenter: float3, triSize: float2 ) -> float { let p = samplePosition - triCenter; let h = triSize; let q = abs(p); return max(q.z-h.y,max(q.x*0.866025+p.y*0.5,-p.y)-h.x*0.5); } pub fn capsuleLine( samplePosition: float3, lineStart: float3, lineEnd: float3, capsuleRadius: float ) -> float { let p = samplePosition; let a = lineStart; let b = lineEnd; let r = capsuleRadius; let pa = p - a; let ba = b - a; let h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 ); return length( pa - ba*h ) - r; } pub fn capsule( samplePosition: float3, capsuleCenter: float3, height: float, radius: float ) -> float { let p1 = samplePosition - capsuleCenter; let h = height; let r = radius; let p = (p1.x, p1.y - clamp( p1.y, 0.0, h ), p1.z); return length( p ) - r; } pub fn cylinder( samplePosition: float3, cylinderCenter: float3, height: float, radius: float ) -> float { let p = samplePosition - cylinderCenter; let h = height; let r = radius; let d = abs(float2(length(p.xz),p.y)) - float2(r,h); return min(max(d.x,d.y),0.0) + length(max(d,0.0)); } pub fn cylinderLine( samplePosition: float3, lineStart: float3, lineEnd: float3, radius: float) -> float { let p = samplePosition; let a = lineStart; let b = lineEnd; let r = radius; let ba = b - a; let pa = p - a; let baba = dot(ba,ba); let paba = dot(pa,ba); let x = length(pa*baba-ba*paba) - r*baba; let y = abs(paba-baba*0.5) - baba*0.5; let x2 = x*x; let y2 = y*y*baba; let mxxy = max(x,y); let d = (mxxy<0.0)?-min(x2,y2):(((x>0.0)?x2:0.0)+((y>0.0)?y2:0.0)); return sign(d)*sqrt(abs(d))/baba; } pub fn roundedCylinder( samplePosition: float3, cylinderCenter: float, cylinderRadius: float, cornerRadius: float, height: float ) -> float { let p = samplePosition - cylinderCenter; let h = height; let ra = cylinderRadius; let rb = cornerRadius; let d = float2( length(p.xz)-2.0*ra+rb, abs(p.y) - h ); return min(max(d.x,d.y),0.0) + length(max(d,0.0)) - rb; } pub fn cappedCone( samplePosition: float3, coneCenter: float3, height: float, r1: float, r2: float ) -> float { let p = samplePosition - coneCenter; let h = height; let q = float2( length(p.xz), p.y ); let k1 = float2(r2,h); let k2 = float2(r2-r1,2.0*h); let ca = float2(q.x-min(q.x,(q.y<0.0)?r1:r2), abs(q.y)-h); let cb = q - k1 + k2*clamp( dot(k1-q,k2)/dot2(k2), 0.0, 1.0 ); let s = (cb.x<0.0 && ca.y<0.0) ? -1.0 : 1.0; return s*sqrt( min(dot2(ca),dot2(cb)) ); } pub fn solidAngle( samplePosition: float3, solidCenter: float3, size: float2, radius: float) -> float { let p = samplePosition - solidCenter; let c = size; let ra = radius; // c is the sin/cos of the angle let q = float2( length(p.xz), p.y ); let l = length(q) - ra; let m = length(q - c*clamp(dot(q,c),0.0,ra) ); return max(l,m*sign(c.y*q.x-c.x*q.y)); } pub fn cutSphere( samplePosition: float3, sphereCenter: float3, radius: float, height: float ) -> float { let p = samplePosition - sphereCenter; let h = height; let r = radius; // sampling independent computations (only depend on shape) let w = sqrt(r*r-h*h); // sampling dependant computations let q = float2( length(p.xz), p.y ); let s = max( (h-r)*q.x*q.x+w*w*(h+r-2.0*q.y), h*q.x-w*q.y ); return (s<0.0) ? length(q)-r : (q.x float { let p = samplePosition - sphereCenter; let r = radius; let h = height; let t = thickness; // sampling independent computations (only depend on shape) let w = sqrt(r*r-h*h); // sampling dependant computations let q = float2( length(p.xz), p.y ); return ((h*q.x float { let p = samplePosition - coneCenter; let h = height; let r1 = coneRadius; let r2 = cornerRadius; // sampling independent computations (only depend on shape) let b = (r1-r2)/h; let a = sqrt(1.0-b*b); // sampling dependant computations let q = float2( length(p.xz), p.y ); let k = dot(q,float2(-b,a)); if( k<0.0 ) return length(q) - r1; if( k>a*h ) return length(q-float2(0.0,h)) - r2; return dot(q, float2(a,b) ) - r1; } pub fn ellipsoid( samplePosition: float3, center: float3, radius: float3 ) -> float { let p = samplePosition - center; let r = radius; let k0 = length(p/r); let k1 = length(p/(r*r)); return k0*(k0-1.0)/k1; } pub fn rhombus( samplePosition: float3, rhombusCenter: float3, la: float, lb: float, height: float, ra: float) -> float { let p = samplePosition - rhombusCenter; let h = height; p = abs(p); let b = float2(la,lb); let f = clamp( (ndot(b,b-2.0*p.xz))/dot(b,b), -1.0, 1.0 ); let q = float2(length(p.xz-0.5*b*float2(1.0-f,1.0+f))*sign(p.x*b.y+p.z*b.x-b.x*b.y)-ra, p.y-h); return min(max(q.x,q.y),0.0) + length(max(q,0.0)); } pub fn octahedron( samplePosition: float3, center: float3, size: float) -> float { let p = samplePosition - center; let s = size; p = abs(p); let m = p.x+p.y+p.z-s; let q = 0.0.xyz; if( 3.0*p.x < m ) q = p.xyz; else if( 3.0*p.y < m ) q = p.yzx; else if( 3.0*p.z < m ) q = p.zxy; else return m*0.57735027; let k = clamp(0.5*(q.z-q.y+s),0.0,s); return length(float3(q.x,q.y-s+k,q.z-k)); } pub fn pyramid( samplePosition: float3, pyramidCenter: float3, height: float) -> float { let p1 = samplePosition - pyramidCenter; let h = height; let m2 = h*h + 0.25; let p2 = (abs(p1.x), p1.y, abs(p1.z)); if (p1.z > p1.x) { p2 = (p2.z, p2.y, p2.x); } p2 = (p2.x - 0.5, p2.y, p2.z - 0.5); let p = p2; let q = float3( p.z, h*p.y - 0.5*p.x, h*p.x + 0.5*p.y); let s = max(-q.x,0.0); let t = clamp( (q.y-0.5*p.z)/(m2+0.25), 0.0, 1.0 ); let a = m2*(q.x+s)*(q.x+s) + q.y*q.y; let b = m2*(q.x+0.5*t)*(q.x+0.5*t) + (q.y-m2*t)*(q.y-m2*t); let d2 = min(q.y,-q.x*m2-q.y*0.5) > 0.0 ? 0.0 : min(a,b); return sqrt( (d2+q.z*q.z)/m2 ) * sign(max(q.z,-p.y)); } pub fn udTriangle( samplePosition: float3, a: float3, b: float3, c: float3 ) -> float { let p = samplePosition; let ba = b - a; let pa = p - a; let cb = c - b; let pb = p - b; let ac = a - c; let pc = p - c; let nor = cross( ba, ac ); return sqrt( (sign(dot(cross(ba,nor),pa)) + sign(dot(cross(cb,nor),pb)) + sign(dot(cross(ac,nor),pc))<2.0) ? min( min( dot3(ba*clamp(dot(ba,pa)/dot3(ba),0.0,1.0) - pa), dot3(cb*clamp(dot(cb,pb)/dot3(cb),0.0,1.0) - pb) ), dot3(ac*clamp(dot(ac,pc)/dot3(ac),0.0,1.0) - pc) ) : dot(nor,pa)*dot(nor,pa)/dot3(nor) ); } pub fn udQuad( samplePosition: float3, a: float3, b: float3, c: float3, d: float3 ) -> float { let p = samplePosition; let ba = b - a; let pa = p - a; let cb = c - b; let pb = p - b; let dc = d - c; let pc = p - c; let ad = a - d; let pd = p - d; let nor = cross( ba, ad ); return sqrt( (sign(dot(cross(ba,nor),pa)) + sign(dot(cross(cb,nor),pb)) + sign(dot(cross(dc,nor),pc)) + sign(dot(cross(ad,nor),pd))<3.0) ? min( min( min( dot3(ba*clamp(dot(ba,pa)/dot3(ba),0.0,1.0)-pa), dot3(cb*clamp(dot(cb,pb)/dot3(cb),0.0,1.0)-pb) ), dot3(dc*clamp(dot(dc,pc)/dot3(dc),0.0,1.0)-pc) ), dot3(ad*clamp(dot(ad,pd)/dot3(ad),0.0,1.0)-pd) ) : dot(nor,pa)*dot(nor,pa)/dot3(nor) ); } /** * Returns the intersection of two SDFs * = max(a, b) */ pub fn intersect(a: float, b: float) -> float { return max(a, b); } /** * Returns the union of two SDFs * = min(a, b) */ pub fn union(a: float, b: float) -> float { return min(a, b); } pub fn subtract(a: float, b: float) -> float { return max(-a, b); } pub fn smoothIntersect(a: float, b: float, k: float) -> float { let h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return lerp(b, a, h) - k * h * (1.0 - h); } /** * Smoothly joins two SDFs using blending distance k */ pub fn smoothUnion(a: float, b: float, k: float) -> float { let d1 = a; let d2 = b; let h = clamp( 0.5 + 0.5*(d2-d1)/k, 0.0, 1.0 ); return lerp( d2, d1, h ) - k*h*(1.0-h); } pub fn smoothSubtract(a: float, b: float, k: float) -> float { let d1 = a; let d2 = b; let h = clamp( 0.5 - 0.5*(d2+d1)/k, 0.0, 1.0 ); return lerp( d2, -d1, h ) + k*h*(1.0-h); } /** * Blends between two SDFs using interpolation */ pub fn blend(a: float, b: float, t: float) -> float { return t * a + (1 - t) * b; } pub fn round(a: float, r: float) -> float { return a - r; } /** * Carve out the interior of an SDF */ pub fn onion(a: float, thickness: float) -> float { return abs(a) - thickness; } pub fn grad(p:float3, sampler: (pos: float3) -> float) { const DELTA = 0.0001; return float3(sampler(p + float3(DELTA, 0.0, 0.0)) - sampler(p - float3(DELTA, 0.0, 0.0)), sampler(p + float3(0.0, DELTA, 0.0)) - sampler(p - float3(0.0, DELTA, 0.0)), sampler(p + float3(0.0, 0.0, DELTA)) - sampler(p - float3(0.0, 0.0, DELTA))) / (2.0 * DELTA); } /** * Poorly returns the closest point on the surface of an SDF * This is an inaccurate method */ pub fn closest(position: float3, sampler: (pos: float3) -> float) -> float3 { let sep = 0.0001; let zero = min(env.frame, 0); let closest = position; let initialDist = sampler(position); let seed = 0; for (let j: int = 0; j < 200; j++) { let n = 0.0.xyz; let distSum = 0.0; for (let i: int = zero; i < 4; i++) { let e = 0.5773*(2.0*float3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0); let d = sampler(closest+e*sep); distSum += d; n += e*d; } closest = normalize(n) * distSum * -1 / 4.0 + closest; if (distSum < 0.0001) { break; } } return closest; } pub fn normal(position: float3, sampler: (pos: float3) -> float) -> float3 { const h = 0.1; let zero = min(env.frame, 0); let n = 0.0.xyz; let distSum = 0.0; for (let i: int = zero; i < 4; i++) { let e = 0.5773*(2.0*float3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0); let d = sampler(position+e*h); distSum += d; n += e*d; } return normalize(n); } pub fn vizRings(d: float) -> float4 { if (false) { let color = 1.0 - sign(d) * float3(0.1, 0.4, 0.7); color *= 1.0 - exp(-4.0 * abs(d)); color *= 0.8 + 0.2 * cos(140.0 * d); color = lerp(color, 1.0.xyz, 1.0 - smoothstep(0.0, 0.015, abs(d))); return (color, 1.0); }else{ let size = 2; let fadeDist = 100; let v = 1-clamp(d/ fadeDist, 0, 1); let color = (0.4 * v, 0.6* v, 1, 1); let s = sin(d / size); if (abs(d) < 1) { return float4(1.xyzw); }else{ return d > 0 ? color * ceil(1-s) : color * ceil(s); } } } pub fn march(position: float3, direction: float3, sampler: (pos: float3) -> float) -> float { let maxDist = 100000.0; let minDist = 1.0; let dist = minDist; for (let i = 0; i < 256 && dist < maxDist; i++) { let samp = sampler(position + direction * dist); dist += samp; if (abs(samp) < (0.00005 * dist)) { break; } } if (dist > maxDist) { dist = -1.0; } return dist; } /** * See: https://iquilezles.org/articles/distfunctions/ * Infinitely repeats an SDF with space in between. This returns an updated position * * Example: * ```shadeup * sdf::sphere(sdf::repeat(p, 100.xyz), 0.xyz, 50.0); * ``` */ pub fn repeat(position: float3, space: float3) -> float3 { let p = position; let s = space; return p - s*round(p/s); } /** * See: https://iquilezles.org/articles/distfunctions/ * Repeats an SDF with space in between upto the limit. This returns an updated position * * Example: * ```shadeup * sdf::sphere(sdf::repeatLimited(p, 100, 10.xyz), 0.xyz, 50.0); * ``` */ pub fn repeatLimited(position: float3, space: float, limit: float3) -> float3 { let p = position; let s = space; return p - s*clamp(round(p/s),-limit,limit); } } ================================================ FILE: lang/shadeup/library/std.ts ================================================ export { ui } from '/_std/ui'; export { mesh, Mesh } from '/_std/mesh'; export { sdf } from '/_std/sdf'; export { geo } from '/_std/geo'; export * from '/_std/native'; ================================================ FILE: lang/shadeup/library/test.shadeup ================================================ // Option 1 let idx = buffer::new(); let buf = buffer::new(); let otherBuf = buffer::new(); drawIndexed(idx, shader { let pos = buf[in.index].xyz; out.position = pos; out.custom("test", pos.x); }, shader { let px = in.custom("test"); let c = otherBuf[round(px)]; out.color = c.xyzw; }); // Option 2 let idx = buffer::new(); let buf = buffer::new(); let otherBuf = buffer::new(); drawIndexed(idx, shader -> ({test: float}) { let pos = buf[in.index].xyz; out.position = pos; out.test = pos.x; }, shader <- ({test: float}) { let px = in.test; let c = otherBuf[round(px)]; out.color = c.xyzw; }); // Option 3 let idx = buffer::new(); let buf = buffer::new(); let otherBuf = buffer::new(); drawIndexed(idx, shader<{}, {test: float}> { let pos = buf[in.index].xyz; out.position = pos; out.test = pos.x; }, shader<{test: float}, {}> { let px = in.test; let c = otherBuf[round(px)]; out.color = c.xyzw; }); ================================================ FILE: lang/shadeup/library/texture.ts ================================================ import { float4, float3, float, float2, bool, int, int2, int3, int4, uint, uint2, uint3, uint4, uint8 } from '/std_math'; import { ShaderInput, ShaderOutput, shader, draw, drawInstanced, drawAdvanced, drawIndexed } from '/_std/drawIndexed'; import { Mesh } from '/_std/mesh'; import { PaintingContext } from '/_std/paint'; export class texture2d_internal_empty { __opaque_texture2d: true = true; /** @shadeup=glsl(!texture($self$, $0$)) */ __index(index: int2 | uint2): T { return null as any; } __index_assign(index: int2 | uint2, value: T): void { return null as any; } getFast(index: int2 | uint2): T { return null as any; } setFast(index: int2 | uint2, value: T): void { return null as any; } /** @shadeup=tag(async) */ download(): void {} downloadAsync(): Promise { return null as any; } /** * Returns the underlying cpu buffer as a typed array. * * Note that this is considerably faster than using the raw index [] operator. * * ```shadeup * let tex = texture2d(); * let data = tex.getData(); * * for (let i = 0; i < data.length; i += 4) { * let r = data[i]; * let g = data[i + 1]; * let b = data[i + 2]; * let a = data[i + 3]; * * // Do something with the pixel * } * ``` */ getData(): Uint32Array | Float32Array | Uint8Array | Int32Array { return new Uint32Array(0); } upload(): void {} size: float2 = [0, 0]; paint: PaintingContext = null as any; sample(position: float2): float4 {} clear(color: float | float4 | 'auto' = 'auto'): void {} flush(): void {} // draw( // geometry: Mesh, // vertexShader: shader, // pixelShader: shader // ): void; // draw(fullScreenPixelShader: shader): void; // draw() { // throw new Error('Not implemented'); // } draw: typeof draw; drawIndexed: typeof drawIndexed; drawAdvanced: typeof drawAdvanced; drawInstanced: typeof drawInstanced; /** Release the texture */ destroy() {} } export type texture2d = texture2d_internal_empty; export type TextureFormat = '32bit' | '16bit' | '8bit' | 'depth' | 'depth-32' | 'auto'; export function texture2d( size: float2, format: TextureFormat, type: string ): texture2d { return (window as any).shadeupMakeTextureInternal(size, format, type) as texture2d; } export class texture3d_internal_empty { __opaque_texture3d: true = true; /** @shadeup=glsl(!texture($self$, $0$)) */ __index(index: int3): T { return null as any; } __index_assign(index: int3, value: T): void {} size: float3 = [0, 0, 0]; sample(position: float3): float4 {} } export type texture3d = texture3d_internal_empty; export function texture3d(size: float3, type: string): texture3d { return (window as any).shadeupMakeTextureInternal(size, type) as texture3d; } ================================================ FILE: lang/shadeup/library/textures.shadeup ================================================ ================================================ FILE: lang/shadeup/library/types.ts ================================================ export type bool = boolean; export type float = number & { _opaque_float: 2 }; export type int = number & { _opaque_int: 1 } & float; export type uint = number & { _opaque_uint: 1 } & float & int; type scalar = float | int; export type float2 = [float, float]; export type float3 = [float, float, float]; export type float4 = [float, float, float, float]; export type int2 = [int, int]; export type int3 = [int, int, int]; export type int4 = [int, int, int, int]; type anyFloat = float2 | float3 | float4; type anyInt = int2 | int3 | int4; type vector2 = float2 | int2; type vector3 = float3 | int3; type vector4 = float4 | int4; type vector = vector2 | vector3 | vector4; type vectorOrScalar = vector | scalar; type float2x2 = [float, float, float, float]; type float3x3 = [float, float, float, float, float, float, float, float, float]; type float4x4 = [ float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float ]; ================================================ FILE: lang/shadeup/library/ui.ts ================================================ export namespace ui { export function puck(position: float2): float2 { return (window as any)._SHADEUP_UI_PUCK(position); } export function draggable(position: float2, radius: float = 10): float2 { return (window as any)._SHADEUP_UI_PUCK(position, radius, true); } export function textbox(value: string): string { return (window as any)._SHADEUP_UI_CONTROL('textbox', value); } export function slider(value: float, min: float, max: float): float { return (window as any)._SHADEUP_UI_SLIDER(value, { min, max }); } export function label(text: string): void { return (window as any)._SHADEUP_UI_CONTROL('label', text); } export function checkbox(value: bool): bool { return (window as any)._SHADEUP_UI_CONTROL('checkbox', value); } export function combo(value: string, options: string[]): string { return (window as any)._SHADEUP_UI_CONTROL('combo', value, { options }); } export function group(text: string): void { return (window as any)._SHADEUP_UI_CONTROL('group', text); } export function button(text: string): bool { return (window as any)._SHADEUP_UI_CONTROL('button', false, { text }); } export function pop(): void { (window as any)._SHADEUP_UI_CONTROL('pop'); } } ================================================ FILE: lang/shadeup/monaco/connector.ts ================================================ import type { MonacoEditorInstance } from 'src/monaco/editor'; import type { ShadeupWorkspaceInterface } from '../compiler/interface'; import monaco from '../../monaco/monaco'; import ts from 'typescript'; export function connectMonacoEditorToShadeupWorkspace( workspace: ShadeupWorkspaceInterface, path: string, monacoFilename: string, editor: MonacoEditorInstance ) { editor.editor?.setValue(workspace.files.get(path) ?? ''); editor.editor?.onDidChangeModelContent((e) => { workspace.writeFile(path, editor.editor?.getValue() ?? '', true); setTimeout(() => { workspace.writeFile(path, editor.editor?.getValue() ?? ''); }, 100); }); let model = editor?.editor?.getModel(); if (model) { let m = model as monaco.editor.ITextModel; (model as any).$shd = { async provideCompletionItems(model: monaco.editor.ITextModel, position: monaco.Position) { let offset = model.getOffsetAt(position); let completions = await workspace.getCompletions(path, offset); let items: monaco.languages.CompletionItem[] = []; for (let completion of completions) { let c = completion.completion; let kind = { [ts.ScriptElementKind.functionElement]: monaco.languages.CompletionItemKind.Function, [ts.ScriptElementKind.memberVariableElement]: monaco.languages.CompletionItemKind.Field, [ts.ScriptElementKind.memberGetAccessorElement]: monaco.languages.CompletionItemKind.Field, [ts.ScriptElementKind.memberSetAccessorElement]: monaco.languages.CompletionItemKind.Field, [ts.ScriptElementKind.variableElement]: monaco.languages.CompletionItemKind.Variable, [ts.ScriptElementKind.constElement]: monaco.languages.CompletionItemKind.Variable, [ts.ScriptElementKind.localVariableElement]: monaco.languages.CompletionItemKind.Variable, [ts.ScriptElementKind.classElement]: monaco.languages.CompletionItemKind.Class, [ts.ScriptElementKind.interfaceElement]: monaco.languages.CompletionItemKind.Interface, [ts.ScriptElementKind.typeElement]: monaco.languages.CompletionItemKind.Class, [ts.ScriptElementKind.enumElement]: monaco.languages.CompletionItemKind.Enum, [ts.ScriptElementKind.moduleElement]: monaco.languages.CompletionItemKind.Module, [ts.ScriptElementKind.keyword]: monaco.languages.CompletionItemKind.Keyword, [ts.ScriptElementKind.scriptElement]: monaco.languages.CompletionItemKind.File, [ts.ScriptElementKind.alias]: monaco.languages.CompletionItemKind.File, [ts.ScriptElementKind.letElement]: monaco.languages.CompletionItemKind.Variable, [ts.ScriptElementKind.directory]: monaco.languages.CompletionItemKind.Folder, [ts.ScriptElementKind.string]: monaco.languages.CompletionItemKind.Text }[c.kind.toString()] ?? monaco.languages.CompletionItemKind.Property; let parts = displayPartsToString(completion.details?.displayParts); if (c.kind.toString() == ts.ScriptElementKind.alias) { if (parts.startsWith('(alias) class')) { kind = monaco.languages.CompletionItemKind.Class; } else if (parts.startsWith('(alias) enum')) { kind = monaco.languages.CompletionItemKind.Enum; } else if (parts.startsWith('(alias) interface')) { kind = monaco.languages.CompletionItemKind.Interface; } else if (parts.startsWith('(alias) type')) { kind = monaco.languages.CompletionItemKind.Class; } else if (parts.startsWith('(alias) namespace')) { kind = monaco.languages.CompletionItemKind.Module; } else if (parts.startsWith('(alias) function')) { kind = monaco.languages.CompletionItemKind.Function; } else if (parts.startsWith('(alias) var') || parts.startsWith('(alias) let')) { kind = monaco.languages.CompletionItemKind.Variable; } else if (parts.startsWith('(alias) const')) { kind = monaco.languages.CompletionItemKind.Variable; } } if (c.kind.toString() == ts.ScriptElementKind.string) { c.name = `"${c.name.replace(/"/g, '')}"`; } let documentation = completion.details?.documentation?.map((p) => ({ value: p.text })) ?? []; if (!c.name.startsWith('__')) items.push({ label: c.name, sortText: c.sortText, kind, insertText: c.name, detail: parts, documentation: documentation[0] ?? undefined, range: (completion as any).range }); } return { suggestions: items }; }, async provideHover( model: monaco.editor.ITextModel, position: monaco.Position ): Promise { let offset = model.getOffsetAt(position); let hover = await workspace.getHover(path, offset); if (hover) { let contents: monaco.IMarkdownString[] = []; if (hover.displayParts) { let content = ''; for (let p of hover.displayParts) { // if (p.kind == ts.SymbolDisplayPartKind) content += p.text; } contents.push({ value: '```ts\n' + content.replaceAll('__.', '') + '\n```' }); } if (hover.documentation) { let documentation = hover.documentation.map((p) => ({ value: p.text })); contents = contents.concat(documentation); } return { contents, range: hover.range }; } return null; } }; workspace.on('diagnostic', (e) => { let alerts: monaco.editor.IMarkerData[] = []; for (let d of e.detail.diagnostics) { if (d.path === path) { alerts.push({ message: d.message, startLineNumber: d.startLine, startColumn: d.startColumn, endLineNumber: d.endLine, endColumn: d.endColumn, severity: monaco.MarkerSeverity.Error }); } } monaco.editor.setModelMarkers(m, 'shadeup', alerts); }); } } function displayPartsToString(parts?: ts.SymbolDisplayPart[]): string { if (parts) { let content = ''; for (let p of parts) { content += p.text; } return content.replaceAll('__.', '').replaceAll('(property)', '').replaceAll('(method)', ''); } else { return ''; } } ================================================ FILE: lang/shadeup/runner.ts ================================================ import type { ShadeupWorkspaceInterface } from './compiler/interface'; import ShadeupEnvironment from './environment'; import frame from './frame.html?raw'; import frameHeadless from './engine/frame-headless.html?raw'; import engineUrlHeadless from './engine/engine-headless?url'; import type { ShadeupExternalSymbol } from './symbol'; import type { ShadeupRenderedFile } from './compiler/common'; export async function simpleRun(source: string, expose: ShadeupExternalSymbol[] = []) { let env = await makeEnvironment(source, expose); return await runEnvironment(env); } export async function makeEnvironment(source: string, expose: ShadeupExternalSymbol[] = []) { let env = new ShadeupEnvironment(); await env.load(); for (let sym of expose) { env.addSymbol(sym); } return env; } export async function runEnvironmentLong( env: ShadeupWorkspaceInterface, cb: (message: any) => void ) { let gid = (window as any).runLongId || 0; (window as any).runLongId = gid + 1; let iframe = document.createElement('iframe'); iframe.sandbox.add('allow-scripts'); iframe.srcdoc = frame; iframe.style.display = 'none'; iframe.srcdoc = frameHeadless.replace('%GID%', gid).replace('%ENGINE_URL%', engineUrlHeadless); let windowListener = (e: MessageEvent) => { console.log('got message from iframe', e); var frame = document.getElementById('sandboxed'); if (e.origin === 'null' && e.source === iframe.contentWindow && e.data && e.data.gid === gid) { cb(e.data.data); } }; window.addEventListener('message', windowListener); let iframeIsLoaded = false; let enqueuedFiles: ShadeupRenderedFile[] = []; const sendFilesToIframe = () => { iframe.contentWindow?.postMessage( { type: 'frame', files: enqueuedFiles }, '*' ); }; iframe.onload = () => { if (iframe.contentWindow) { iframeIsLoaded = true; if (enqueuedFiles.length > 0) { sendFilesToIframe(); } } }; env.on('output', (msg) => { enqueuedFiles = [...enqueuedFiles, ...msg.detail.files]; if (iframeIsLoaded) { sendFilesToIframe(); } }); document.body.appendChild(iframe); return () => { iframe.remove(); window.removeEventListener('message', windowListener); }; } export async function runEnvironment(env: ShadeupEnvironment) { env.evaluate('main.shadeup'); let js = await env.generateFile('main.shadeup'); return await new Promise((resolve) => { let iframe = document.createElement('iframe'); iframe.sandbox.add('allow-scripts'); iframe.srcdoc = frame; iframe.style.display = 'none'; let windowListener = (e: MessageEvent) => { var frame = document.getElementById('sandboxed'); if (e.origin === 'null' && e.source === iframe.contentWindow) { resolve(e.data); window.removeEventListener('message', windowListener); } }; window.addEventListener('message', windowListener); iframe.onload = () => { if (iframe.contentWindow) { iframe.contentWindow.postMessage(js, '*'); } else { console.log('no content window'); resolve(false); } }; document.body.appendChild(iframe); }); } ================================================ FILE: lang/shadeup/symbol.ts ================================================ export class ShadeupExternalSymbol { name: string = ''; kind: string = ''; outType: string = ''; parameters: [string, string, boolean][] = []; fields: [string, string][] = []; methods: ShadeupExternalSymbol[] = []; js: string = ''; constructor(name: string, kind: string) { this.name = name; this.kind = kind; } static makeFunction( name: string, outType: string, parameters: [string, string, boolean][], source: string ): ShadeupExternalSymbol { let symbol = new ShadeupExternalSymbol(name, 'function'); symbol.outType = outType; symbol.parameters = parameters; symbol.js = source; return symbol; } static makeVariable(name: string, outType: string): ShadeupExternalSymbol { const symbol = new ShadeupExternalSymbol(name, 'variable'); symbol.outType = outType; return symbol; } static makeType( name: string, fields: [string, string][], methods: ShadeupExternalSymbol[] ): ShadeupExternalSymbol { let symbol = new ShadeupExternalSymbol(name, 'type'); symbol.fields = fields; symbol.methods = methods; return symbol; } } ================================================ FILE: lang/shadeup/vite.config.js ================================================ import { defineConfig } from 'vite'; import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'; import wasm from 'vite-plugin-wasm'; // const prefix = `monaco-editor/esm/vs`; import { sveltekit } from '@sveltejs/kit/vite'; import nodeResolve from '@rollup/plugin-node-resolve'; import createExternal from 'vite-plugin-external'; export default defineConfig({ plugins: [ wasm(), nodeResolve(), createExternal({ externals: { typescript: 'typescript', chalk: 'chalk', '@typescript/vfs': '@typescript/vfs' } }) ], build: { commonjsOptions: { transformMixedEsModules: true }, lib: { // Could also be a dictionary or array of multiple entry points entry: './compiler/simple.ts', name: 'ShadeupCompiler', // the proper extensions will be added fileName: 'shadeup-compiler' }, outDir: '../../../compiler-api/', sourcemap: false }, esbuild: { keepNames: false }, resolve: { alias: { src: '/src', punycode: 'punycode/punycode.js', '/std_math': '../shadeup-frontend/lib/std/math.ts' } }, worker: { format: 'es', plugins: [wasm()] }, optimizeDeps: { esbuildOptions: { define: { self: 'globalThis', global: 'globalThis' }, plugins: [ NodeGlobalsPolyfillPlugin({ process: true, buffer: true }) ] } }, server: { fs: { // Allow serving files from one level up to the project root allow: ['..'] } } }); ================================================ FILE: lang/shadeup/worker.ts ================================================ import { makeEnvironment } from 'src/shadeup/runner'; import type * as TYPES from '../../../parser-wasm/pkg/parser_wasm'; import { ShadeupExternalSymbol } from './symbol'; const env = await makeEnvironment(``, [ ShadeupExternalSymbol.makeFunction( 'draw', 'void', [ ['geo', 'Geometry', false], ['shade', 'shader', false] ], ` console.log("Drawing"); ` ) ]); function hiddenProtosToObj(obj: any) { let out: any = {}; let proto = Object.getPrototypeOf(obj); while (proto) { for (let key of Object.getOwnPropertyNames(proto)) { if (key == 'constructor') continue; out[key] = obj[key]; } } return out; } let evaluating = new Map(); let evaluateQueue = new Map(); function evaluate(filename: string, skipGenerate = false) { let now = performance.now(); console.log('evaluating', filename); let success = env.evaluate(filename); let messages = []; let totalAlerts = 0; for (let f of env.files.keys()) { let alerts: TYPES.Alert[] = env.getAlerts(f); totalAlerts += alerts.length; } if (success && totalAlerts == 0 && !skipGenerate) { let out = env.generateFile(filename); messages.push({ type: 'rendered', filename, data: out }); } for (let f of env.files.keys()) { let alerts: TYPES.Alert[] = env.getAlerts(f); let alertsMessage = { type: 'alerts', filename: f, data: alerts.map((a) => ({ level: a.level, message: a.message, simple_message: a.simple_message, location: { start_line_and_column: [ a.location.start_line_and_column[0], a.location.start_line_and_column[1] ], end_line_and_column: [ a.location.end_line_and_column[0], a.location.end_line_and_column[1] ] } })) }; messages.push(alertsMessage); let imports = env.getImports(f); let importsMessage = { type: 'imports', filename: f, data: imports.map((s: any) => ({ imports: s.imports.map((i: any) => ({ name: i.name, alias: i.alias, span: mapSpan(i.span) })), path: s.path, span: mapSpan(s.span) })) }; messages.push(importsMessage); let intellisense = env.getIntellisense(f); let intellisenseMessage = { type: 'intellisense', filename: f, data: intellisense }; messages.push(intellisenseMessage); } let symbols = env.getSymbols(); let symbolsMessage = { type: 'symbols', data: symbols.map((s: any) => ({ name: s.name, file: s.file, aliased: s.aliased, imported: s.imported, kind: s.kind })) }; messages.push(symbolsMessage); function mapSpan(span: any) { return { start: span.start, end: span.end }; } postMessage({ type: 'messages', messages }); console.log('evaluated', filename, 'in', performance.now() - now, 'ms'); } onmessage = function (e) { const { type, filename, data } = e.data; if (type == 'addSymbol') { env.addSymbol(data); } else if (type == 'writeFile') { env.updateFile(filename, data); } else if (type == 'evaluate') { if (evaluating.has(filename)) { console.log('already evaluating', filename, 'skipping'); // Mark the file as dirty so that it will be re-evaluated after the current evaluation is done evaluateQueue.set(filename, true); return; } evaluating.set(filename, true); this.setTimeout(() => { evaluate(filename, data.skipGenerate); evaluating.delete(filename); }, 0); if (evaluateQueue.has(filename)) { // evaluateQueue.delete(filename); // evaluate(filename); } } else if (type == 'reset') { env.reset(); } }; ================================================ FILE: lang/shadeup-frontend/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: lang/shadeup-frontend/f.js ================================================ let x = [ 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ]; // 0x0804A7B0 ================================================ FILE: lang/shadeup-frontend/f.ts ================================================ let x = [ 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ]; // 0x0804A7B0 ================================================ FILE: lang/shadeup-frontend/index.html ================================================ Vite App
================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/_extensions.ts ================================================ declare global { interface Array { enumerate(): [number, T][]; filter_map(fn: (value: T, index: number) => B | null): B[]; max_by_key(fn: (value: T, index: number) => any): T; chain(arg: any): this; } } (Array.prototype as any).enumerate = function (): [number, B][] { let i = 0; let rv: [number, B][] = []; for (let item of this) rv.push([i++, item]); return rv; }; (Array.prototype as any).filter_map = function ( this, fn: (value: typeof this, index: number) => B | null ): B[] { return this.map(fn).filter((n) => n !== null) as B[]; }; (Array.prototype as any).max_by_key = function ( this, fn: (value: typeof this, index: number) => number ): typeof this { const max = (self: number[]) => { return Math.max.apply(null, self); }; return max(this.map(fn)) as any; }; (Array.prototype as any).chain = function (this, that) { return this.concat(that); }; declare global { interface Number { saturating_sub(n: number): number; max(n: number): number; min(n: number): number; } } (Number.prototype as any).saturating_sub = function (n: number): number { return this.valueOf() - n; }; (Number.prototype as any).max = function (n: number): number { return Math.max(this.valueOf(), n); }; (Number.prototype as any).min = function (n: number): number { return Math.min(this.valueOf(), n); }; export const __dummy = 1; ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/browser.ts ================================================ import "./_extensions" export { Display } from "./data/Display" export { Range } from './data/Range' export { mkStringWriter } from './data/Write' export { Color, Fixed } from './lib/Color' export { ColorGenerator } from "./lib/ColorGenerator" export { Config } from "./lib/Config" export { Label } from './lib/Label' export { Report } from './lib/Report' export { ReportKind } from './lib/ReportKind' export { Source, sources } from './lib/Source' export { format } from "./write" ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Display.ts ================================================ import { isCallback } from "../utils"; import { ColorFn } from "../lib/Color"; import { isOption, type Option } from "./Option"; export interface Display { fg(color: Option): any; bg(color: Option): any; chars(): string; display(): string; map(fn: (d: any) => any): this; unwrap_or_else(d: () => string): string; } export class Display implements Display { constructor(value: string | Display) { this.value = typeof value === "string" ? value : value.value } fg(color: Option | ColorFn): this { if (isOption(color)) { let func = (color.is_some() ? color.unwrap() : (a: any) => a) as any this.value = func(this.value) } else if (isCallback(color)) { this.value = color(this.value) } return this }; bg(color: Option | ColorFn): this { if (isOption(color)) { let func = (color.is_some() ? color.unwrap() : (a: any) => a) as any this.value = func(this.value) } else if (isCallback(color)) { this.value = color(this.value) } return this }; chars(): string { return this.value }; map(fn: (d: string) => string): Display { return new Display(fn(this.value)) }; display(): string { return this.value }; toString(): string { return this.value } unwrap_or_else(d: () => string): string { return this.value ?? d() }; private value: string static is = (o: any): o is Display => o instanceof Display } export const isDisplay = Display.is; ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Formatter.ts ================================================ import { none, type Option } from './Option'; import { mkStringWriter, type Write, StdoutWriter } from './Write'; export enum Alignment { Left = 'Left', Right = 'Right', Center = 'Center' } export interface Formatter { flags: number; fill: string; align: Alignment; width: Option; precision: Option; buf: Write | null; } export const formatter = new (class implements Formatter { flags: number = 0; fill: string = ''; align: Alignment = Alignment.Left; width: Option = none(); precision: Option = none(); buf: Write | null = null; })(); // formatter.buf = new StdoutWriter(); export const stringFormatter = () => new (class implements Formatter { flags: number = 0; fill: string = ''; align: Alignment = Alignment.Left; width: Option = none(); precision: Option = none(); buf = mkStringWriter(); unwrap() { return this.buf.unwrap(); } })(); ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Iter.ts ================================================ export class Iter {} ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Option.ts ================================================ export abstract class Option { abstract map(fn: (val: T) => R): Option abstract map_or(d: R, fn: (val: T) => R): R abstract filter(fn: (val: T) => boolean): Option abstract or(d: Option): Option abstract unwrap(): T abstract unwrap_or_else(d: () => T): T abstract is_some(): this is Some abstract is_none(): this is None abstract iter(): T[] abstract equal(other: Option): boolean static from(obj: T | undefined | null): Option { if (obj === undefined || obj === null) return none() return some(obj) } } class Some implements Option { constructor(private value: T) {} map(fn: (value: T) => R): Option { return some(fn(this.value)) } map_or(d: R, fn: (val: T) => R): R { return fn(this.value) } filter(fn: (m: T) => boolean): Option { if (fn(this.value)) return some(this.value) return none() } or(d: Option): Option { return this } iter(): T[] { return [this.value] } unwrap(): T { return this.value } unwrap_or_else(d: () => T): T { return this.unwrap() } is_some(): this is Some { return true } is_none(): this is None { return false } equal(other: Option): boolean { if (other.is_some()) return this.value === other.value return false } static is(o: Option): o is Some { return o instanceof Some } } class None implements Option { map(fn: (value: T) => R): Option { return none() } map_or(d: R, fn: (val: T) => R): R { return d } filter(fn: (m: T) => boolean): Option { return none() } or(d: Option): Option { return d } iter(): T[] { return [] } unwrap(): T { throw new Error("Unwrapped None") } unwrap_or_else(d: () => T): T { return d() } is_some(): this is Some { return false } is_none(): this is None { return true } equal(other: Option): boolean { return other.is_none() } static is(o: Option): o is None { return o instanceof None } } export const some = (value: T): Option => { return new Some(value); } export const none = (): Option => { return new None() } export const isOption = (o: any): o is Option => { return o instanceof Some || o instanceof None } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Range.ts ================================================ import { isNumber, isString } from '../utils'; import { Span, SpanInit } from './Span'; export class Range extends Span { public SourceId: any = null; public source(): any { return this.SourceId; } public len(): number { return Math.abs(this.start - this.end); } public contains(item: any): boolean { return item >= this.start && item < this.end; } static is(o: any): o is Range { return o instanceof Range; } static from(o: SpanInit): Range { if (isNumber(o[0]) && isNumber(o[1])) return new Span(o[0], o[1]); if (isString(o[0]) && Range.is(o[1])) { const s = new Range(o[1].start, o[1].end); s.SourceId = o[0]; return s; } throw new Error(`Invalid SpanInit`); } static new(start: number, end: number): Span { return new Range(start, end); } } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Result.ts ================================================ export type Result = Ok | Err; class Ok { constructor(private value: T) {} map(fn: (value: T) => R): Result { return ok(fn(this.value)) } map_or(d: R, fn: (val: T) => R): Result { return ok(fn(this.value)) } or(d: Result): Result { return this } is_ok(): this is Ok { return true } is_err(): this is Err { return false } unwrap(): T { return this.value } unwrap_or_else(d: (v: T) => R): R { return d(this.value) } static is(o: Result): o is Ok { return o instanceof Ok } } export class Err { constructor(private value: E) {} map(fn: (value: E) => R): Result { return ok(fn(this.value)) } map_or(d: R, fn: (val: T) => R): Result { return ok(d) } or(d: Result): Result { return d } unwrap(): E { return this.value } unwrap_or_else(d: (v: E) => R): R { return d(this.value) } is_ok(): this is Ok { return false } is_err(): this is Err { return true } static is(o: Result): o is Err { return o instanceof Err } } export const ok = (value: T): Result => { return new Ok(value); } export const err = (value: E): Result => { return new Err(value) } export const isResult = (o: any): o is Result => { return o instanceof Ok || o instanceof Err } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Show.ts ================================================ import { Formatter } from "./Formatter"; import { isOption } from "./Option"; import { isResult } from "./Result"; import { isCallback, range } from "../utils"; import { write } from "../write"; export class Show { constructor(public self: any) {} fmt(f: Formatter): void { if (isOption(this.self)) { this.self.map(x => new Show(x).fmt(f)) return } if (isResult(this.self)) { this.self.map(x => new Show(x).fmt(f)) return } if (typeof this.self === "string") { write(f.buf, "{}", this.self) return } // TODO: this is all probably wrong if (Array.isArray(this.self) && this.self.length === 2) { if (isCallback(this.self[1])) { for (let x of this.self[0]) { const func = this.self[1]; func(f, x) } } else { for (let _ of range(0, this.self[1])) { write(f.buf, "{}", this.self[0]) } } } else { const x = this.self[0]; write(f.buf, "{}", x) return } } static is = (o: any): o is Show => o instanceof Show } export const isShow = Show.is ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Span.ts ================================================ import { isNumber, isString, range } from "../utils"; import { Range } from "./Range"; export type SpanInit = [src: string, range: Range] | [start: number, end: number]; export class Span { constructor( private _start: number, private _end: number, ) {} /// The identifier used to uniquely refer to a source. In most cases, this is the fully-qualified path of the file. SourceId: any; /// Get the identifier of the source that this span refers to. source() { return this.SourceId } set start(value: number) { this._start = value }; get start(): number { return this._start }; set end(value: number) { this._end = value }; get end(): number { return this._end }; /// Get the length of this span (difference between the start of the span and the end of the span). len(): number { return this.end.saturating_sub(this.start) }; /// Determine whether the span contains the given offset. contains(offset: number): boolean { return range(this.start, this.end).includes(offset); }; static is = (o: any): o is Span => o instanceof Span static from(o: SpanInit) { if (isNumber(o[0]) && isNumber(o[1])) return new Span(o[0], o[1]) if (isString(o[0]) && Range.is(o[1])) { const s = new Span(o[1].start, o[1].end); s.SourceId = o[0] return s } throw new Error(`Invalid SpanInit`) } } export const isSpan = Span.is ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/data/Write.ts ================================================ import { format } from '../write'; import { ok, Result } from './Result'; export interface Write { write_str(s: string): Result; write_char(c: string): Result; write_fmt(...args: any[]): Result; } export class StdoutWriter implements Write { write_str(s: string): Result { throw new Error('Function not implemented'); } write_char(c: string): Result { throw new Error('Function not implemented'); } write_fmt(...args: any[]): Result { console.log(format(...args)); return ok(null); } } class StderrWriter implements Write { write_str(s: string): Result { throw new Error('Function not implemented'); } write_char(c: string): Result { throw new Error('Function not implemented'); } write_fmt(...args: any[]): Result { process.stderr.write(format(...args)); return ok(null); } } class StringWriter implements Write { private value: string[] = []; write_str(s: string): Result { this.value.push(s); return ok(null); } write_char(c: string): Result { this.value.push(c); return ok(null); } write_fmt(...args: any[]): Result { this.value.push(format(...args)); return ok(null); } map(fn: (value: string) => any) { return fn(this.unwrap()); } unwrap() { return this.value.join(''); } } export const stdoutWriter = new StdoutWriter(); export const stderrWriter = new StderrWriter(); export const mkStringWriter = () => new StringWriter(); ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/index.ts ================================================ import "./_extensions" export { Display } from "./data/Display" export { Range } from './data/Range' export { Color, Fixed } from './lib/Color' export { ColorGenerator } from "./lib/ColorGenerator" export { Config } from "./lib/Config" export { Label } from './lib/Label' export { Report } from './lib/Report' export { ReportKind } from './lib/ReportKind' export { Source, sources } from './lib/Source' export { include_str } from './utils/include_str' export { format } from "./write" ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/Characters.ts ================================================ export interface iCharacters { hbar: string; vbar: string; xbar: string; vbar_break: string; vbar_gap: string; uarrow: string; rarrow: string; ltop: string; mtop: string; rtop: string; lbot: string; rbot: string; mbot: string; lbox: string; rbox: string; lcross: string; rcross: string; underbar: string; underline: string; } export abstract class Characters { static unicode(): iCharacters { return { hbar: '─', vbar: '│', xbar: '┼', vbar_break: '·', vbar_gap: '⋮', uarrow: '▲', rarrow: '▶', ltop: '╭', mtop: '┬', rtop: '╮', lbot: '╰', mbot: '┴', rbot: '╯', lbox: '[', rbox: ']', lcross: '├', rcross: '┤', underbar: '┬', underline: '─', }; } static ascii(): iCharacters { return { hbar: '-', vbar: '|', xbar: '+', vbar_break: '*', vbar_gap: ':', uarrow: '^', rarrow: '>', ltop: ',', mtop: 'v', rtop: '.', lbot: '`', mbot: '^', rbot: '\'', lbox: '[', rbox: ']', lcross: '|', rcross: '|', underbar: '|', underline: '^', }; } } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/Color.ts ================================================ import chalk, { ChalkInstance } from './chalk/chalk/source/index'; const options: any = { enabled: true, level: 2 }; const c = chalk; export const colors = { blue: c.blue, green: c.green, red: c.red, yellow: c.yellow }; export const bgColors = { blue: c.bgBlue, green: c.bgGreen, red: c.bgRed, yellow: c.bgYellow }; export type ColorFn = ((s: string) => string) | ChalkInstance; export abstract class Color { static Fixed = Fixed; } export function Fixed(n: number) { return c.ansi256(n); } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/ColorGenerator.ts ================================================ import { ColorFn, Fixed } from "./Color" import { clamp, range, wrapping_add_usize } from "../utils" /// A type that can generate distinct 8-bit colors. export class ColorGenerator { constructor( public state: [number, number, number], public min_brightness: number, ) {} /// Create a new [`ColorGenerator`] with the given pre-chosen state. /// /// The minimum brightness can be used to control the colour brightness (0.0 - 1.0). The default is 0.5. static from_state(state: [number, number, number], min_brightness: number): ColorGenerator { return new ColorGenerator(state, clamp(min_brightness, 0.0, 1.0)) } /// Create a new [`ColorGenerator`] with the default state. static new(): ColorGenerator { return ColorGenerator.default() } /// Generate the next colour in the sequence. next(out?: [number, ColorFn][]): ColorFn { for (let i of range(0, 3)) { // magic constant, one of only two that have this property! const rhs = 40503 * (i * 4 + 1130) const c = wrapping_add_usize(this.state[i], rhs) const u16 = parseInt(`${c.toString(2).slice(-16)}`, 2) this.state[i] = u16; } const value = Math.floor(16 + ((this.state[2] / 65535.0 * (1.0 - this.min_brightness) + this.min_brightness) * 5.0 + (this.state[1] / 65535.0 * (1.0 - this.min_brightness) + this.min_brightness) * 30.0 + (this.state[0] / 65535.0 * (1.0 - this.min_brightness) + this.min_brightness) * 180.0) % 256) const colorFn = Fixed(value); out?.push([value, colorFn]) return colorFn } static default(): ColorGenerator { return new ColorGenerator([30000, 15000, 35000], 0.5) } } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/Config.ts ================================================ import { ColorFn, colors, Fixed } from "./Color"; import { Display } from "../data/Display"; import { Option, some } from "../data/Option"; export class Config { constructor( public cross_gap: boolean, public label_attach: LabelAttach, public compact: boolean, public underlines: boolean, public multiline_arrows: boolean, public color: boolean, public tab_width: number, public char_set: CharSet ) { } static default(): Config { return new Config( true, LabelAttach.Middle, false, true, true, true, 4, CharSet.Unicode ); } /// When label lines cross one-another, should there be a gap? /// /// The alternative to this is to insert crossing characters. However, these interact poorly with label colours. /// /// If unspecified, this defaults to [`false`]. with_cross_gap(cross_gap: boolean): this { this.cross_gap = cross_gap; return this; } /// Where should inline labels attach to their spans? /// /// If unspecified, this defaults to [`LabelAttach.Middle`]. with_label_attach(label_attach: LabelAttach): this { this.label_attach = label_attach; return this; } /// Should the report remove gaps to minimise used space? /// /// If unspecified, this defaults to [`false`]. with_compact(compact: boolean): this { this.compact = compact; return this; } /// Should underlines be used for label span where possible? /// /// If unspecified, this defaults to [`true`]. with_underlines(underlines: boolean): this { this.underlines = underlines; return this; } /// Should arrows be used to point to the bounds of multi-line spans? /// /// If unspecified, this defaults to [`true`]. with_multiline_arrows(multiline_arrows: boolean): this { this.multiline_arrows = multiline_arrows; return this; } /// Should colored output should be enabled? /// /// If unspecified, this defaults to [`true`]. with_color(color: boolean): this { this.color = color; return this; } /// How many characters width should tab characters be? /// /// If unspecified, this defaults to `4`. with_tab_width(tab_width: number): this { this.tab_width = tab_width; return this; } /// What character set should be used to display dynamic elements such as boxes and arrows? /// /// If unspecified, this defaults to [`CharSet.Unicode`]. with_char_set(char_set: CharSet): this { this.char_set = char_set; return this; } error_color(): Option { return some(colors.red).filter(() => this.color); } warning_color(): Option { return some(colors.yellow).filter(() => this.color); } advice_color(): Option { return some(Fixed(147)).filter(() => this.color); } margin_color(): Option { return some(Fixed(246)).filter(() => this.color); } unimportant_color():Option { return some(Fixed(249)).filter(() => this.color); } note_color(): Option { return some(Fixed(115)).filter(() => this.color); } // Find the character that should be drawn and the number of times it should be drawn for each char char_width(c: string, col: number): [Display, number] { if (c === '\t') { // Find the column that the tab should end at let tab_end = (col / this.tab_width + 1) * this.tab_width; return [new Display(' '), tab_end - col]; } if (c.match(/[\s]/)) return [new Display(' '), 1]; return [new Display(c), 1]; } } /// The attachment point of inline label arrows export enum LabelAttach { /// Arrows should attach to the start of the label span. Start = 'Start', /// Arrows should attach to the middle of the label span (or as close to the middle as we can get). Middle = 'Middle', /// Arrows should attach to the end of the label span. End = 'End' } /// Possible character sets to use when rendering diagnostics. export enum CharSet { /// Unicode characters (an attempt is made to use only commonly-supported characters). Unicode = 'Unicode', /// ASCII-only characters. Ascii = 'Ascii' } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/Label.ts ================================================ import { ColorFn } from "./Color"; import { none, Option, some } from "../data/Option"; import { SpanInit } from "../data/Span"; import { Range } from "../data/Range"; /// A type that represents a labelled section of source code. export interface Label { span: S; msg: Option; color: Option; order: number; priority: number; } export class Label { /// Create a new [`Label`]. constructor(span: S) { this.span = span; this.msg = none(); this.color = none(); this.order = 0; this.priority = 0; } /// Give this label a message. with_message(msg: string): this { this.msg = some(msg); return this; } /// Give this label a highlight colour. with_color(color: ColorFn): this { this.color = some(color); return this; } /// Specify the order of this label relative to other labels. /// /// Lower values correspond to this label having an earlier order. /// /// If unspecified, labels default to an order of `0`. /// /// When labels are displayed after a line the crate needs to decide which labels should be displayed first. By /// Default, the orders labels based on where their associated line meets the text (see [`LabelAttach`]). /// Additionally, multi-line labels are ordered before inline labels. You can this this function to override this /// behaviour. with_order(order: number): this { this.order = order; return this; } /// Specify the priority of this label relative to other labels. /// /// Higher values correspond to this label having a higher priority. /// /// If unspecified, labels default to a priority of `0`. /// /// Label spans can overlap. When this happens, the crate needs to decide which labels to prioritise for various /// purposes such as highlighting. By default, spans with a smaller length get a higher priority. You can this this /// function to override this behaviour. with_priority(priority: number): this { this.priority = priority; return this; } last_offset(): number { return this.span.end.saturating_sub(1).max(this.span.start) } static from = Label.new static new(obj: Init): Label { return new Label(Range.from(obj)) as Label } static is(other: any): other is Label{ return other instanceof Label } } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/LabelInfo.ts ================================================ import { Range } from "../data/Range"; import { Label } from "./Label"; export enum LabelKind { Inline = 'Inline', Multiline = 'Multiline', } export class LabelInfo { constructor( public kind: LabelKind, public label: Label, ) {} } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/Report.ts ================================================ import assert from 'assert'; import { Display } from '../data/Display'; import { none, Option, some } from '../data/Option'; import { Range } from '../data/Range'; import { Show } from '../data/Show'; import { Span } from '../data/Span'; import { stderrWriter, stdoutWriter, Write } from '../data/Write'; import { CharSet, Config, LabelAttach } from '../lib/Config'; import { bton, isBoolean, isNumber, max, min_by_key, range, rangeIter, sort_by_key } from '../utils'; import { eprintln, format, write, writeln } from '../write'; import { Characters, iCharacters } from './Characters'; import { Label } from './Label'; import { LabelInfo, LabelKind } from './LabelInfo'; import { ReportBuilder } from './ReportBuilder'; import { ReportKind } from './ReportKind'; import { Cache, CacheInit } from './Source'; import { SourceGroup } from './SourceGroup'; /// A type representing a diagnostic that is ready to be written to output. export interface iReport { kind: typeof ReportKind; code: Option; msg: Option; note: Option; help: Option; location: [S['SourceId'], number]; labels: Label[]; config: Config; eprint(cache: CacheInit): void; print(cache: CacheInit): void; printTo(init: CacheInit, writer: Write): void; } export class Report implements iReport { constructor( public kind: typeof ReportKind, public code: Option, public msg: Option, public note: Option, public help: Option, public location: [S['SourceId'], number], public labels: Label[], public config: Config ) {} /// Begin building a new [`Report`]. static build( kind: typeof ReportKind, src_id: Id | null, offset: number ): ReportBuilder { // TODO const builder = new ReportBuilder( kind, none(), none(), none(), none(), [Option.from(src_id), offset], [], Config.default() ); return builder; } /// Write this diagnostic out to `stderr`. eprint(init: CacheInit): void { const cache = Cache.from(init); this.write(cache, stderrWriter); } /// Write this diagnostic out to `stdout`. /// /// In most cases, [`Report::eprint`] is the /// ['more correct'](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) function to use. print(init: CacheInit): void { const cache = Cache.from(init); this.write(cache, stdoutWriter); } printTo(init: CacheInit, writer: Write): void { const cache = Cache.from(init); this.write(cache, writer); } private get_source_groups(cache: Cache): SourceGroup[] { let groups: SourceGroup[] = []; for (let label of this.labels) { let src_display = cache.display(label.span.source()); let res = cache.fetch(label.span.source()); if (res.is_err()) { console.error("Unable to fetch source '{}': {}", src_display, res.unwrap()); continue; } let src = res.unwrap(); assert(label.span.start <= label.span.end, 'Label start is after its end'); let start_line = src.get_offset_line(label.span.start).map(([_, l, __]) => l); let end_line = src .get_offset_line(label.span.end.saturating_sub(1).max(label.span.start)) .map(([_, l, __]) => l); let label_info = new LabelInfo( start_line.equal(end_line) ? LabelKind.Inline : LabelKind.Multiline, label ); const group = groups.find((g: SourceGroup) => g.src_id === label.span.source()); if (group) { group.span.start = group.span.start.min(label.span.start); group.span.end = group.span.end.max(label.span.end); group.labels.push(label_info); } else { groups.push( new SourceGroup(label.span.source(), new Range(label.span.start, label.span.end), [ label_info ]) ); } } return groups; } /// Write this diagnostic to an implementor of [`Write`]. /// /// If you wish to write to `stderr` or `stdout`, you can do so via [`Report::eprint`] or [`Report::print`] respectively. private write, W extends Write>(cache: C, w: W): void { let draw: iCharacters = match(this.config.char_set, [ [CharSet.Unicode, () => Characters.unicode()], [CharSet.Ascii, () => Characters.ascii()] ]); // --- Header --- let code = this.code ? format('[E{}] ', this.code) : ''; let id = format('{}{}:', code, this.kind.name); let kind_color = match(this.kind, [ [ReportKind.Error, () => this.config.error_color()], [ReportKind.Warning, () => this.config.warning_color()], [ReportKind.Advice, () => this.config.advice_color()], [ReportKind.Custom, (kind: any) => kind.color] ]); writeln(w, '{} {}', new Display(id).fg(kind_color), new Show(this.msg)); let groups = this.get_source_groups(cache); // Line number maximum width let filtered_groups = groups.filter_map(({ span, src_id }: SourceGroup) => { let src_name: string = cache .display(src_id)! .map((d) => d.toString()) .unwrap_or_else(() => ''); let res = cache.fetch(src_id); if (res.is_err()) { eprintln('Unable to fetch source {}: {}', src_name, res.unwrap()); return null; } let src = res.unwrap(); let line_range = src.get_line_range(span); let iter = rangeIter(1, Infinity); iter = map(iter, (x) => Math.pow(10, x)); iter = take_while(iter, (x) => { const d = Math.floor(line_range.end / x); return d !== 0; }); const cnt = count(iter); return cnt + 1; }); let line_no_width = max(filtered_groups) ?? 0; // --- Source sections --- let groups_len = groups.length; for (let [group_idx, { src_id, span, labels }] of enumerate(groups)) { let src_name = cache .display(src_id) .map((d) => d.toString()) .unwrap_or_else(() => ''); let res = cache.fetch(src_id); if (res.is_err()) { eprintln('Unable to fetch source {}: {}', src_name, res.unwrap()); continue; } let src = res.unwrap(); let line_range = src.get_line_range(span); // File name & reference let location = src_id === this.location[0] ? this.location[1] : labels[0].label.span.start; let [line_no, col_no] = src .get_offset_line(location) .map(([_, idx, col]) => [format('{}', idx + 1), format('{}', col + 1)]) .unwrap_or_else(() => ['?', '?']); let line_ref = format(':{}:{}', line_no, col_no); writeln( w, '{}{}{}{}{}{}{}', new Show([' ', line_no_width + 2]), new Display(group_idx === 0 ? draw.ltop : draw.lcross).fg(this.config.margin_color()), new Display(draw.hbar).fg(this.config.margin_color()), new Display(draw.lbox).fg(this.config.margin_color()), src_name, line_ref, new Display(draw.rbox).fg(this.config.margin_color()) ); if (!this.config.compact) { writeln( w, '{}{}', new Show([' ', line_no_width + 2]), new Display(draw.vbar).fg(this.config.margin_color()) ); } class LineLabel { constructor( public col: number, public label: Label, public multi: boolean, public draw_msg: boolean ) { this.col = Math.floor(col); } } // Generate a list of multi-line labels let multi_labels: Label[] = []; for (let label_info of labels) { if (label_info.kind === LabelKind.Multiline) { multi_labels.push(label_info.label); } } // Sort multiline labels by length multi_labels.sort((a, b) => b.span.len() - a.span.len()); //#region [ rgba(0, 20, 0, 0.3) ] Write_Margin let write_margin = ( w: W, idx: number, is_line: boolean, is_ellipsis: boolean, draw_labels: boolean, report_row: Option<[number, boolean]>, line_labels: Array>, margin_label: Option> ): void => { let line_no_margin: string; if (is_line && !is_ellipsis) { let line_no = format('{}', idx + 1); line_no_margin = format( '{}{} {}', new Show([' ', line_no_width - line_no.length]), line_no, draw.vbar ); } else { line_no_margin = format( '{}{}', new Show([' ', line_no_width + 1]), is_ellipsis ? draw.vbar_gap : draw.vbar_break ); } write( w, ' {}{}', new Display(line_no_margin).fg(this.config.margin_color()), new Show(some(' ').filter(() => !this.config.compact)) ); // Multi-line margins if (draw_labels) { for (let col of range(0, multi_labels.length + bton(multi_labels.length > 0))) { let corner: Option<[Label, boolean]> = none(); let hbar: Option> = none(); let vbar: Option> = none(); let margin_ptr: Option<[LineLabel, boolean]> = none(); let multi_label = Option.from(multi_labels[col]); let line_span = src.line(idx).unwrap().span(); for (let [i, label] of enumerate( multi_labels.slice(0, (col + 1).min(multi_labels.length)) )) { let margin = margin_label.filter((m) => label === m.label); if (label.span.start <= line_span.end && label.span.end > line_span.start) { let is_parent = i !== col; let is_start = line_span.contains(label.span.start); let is_end = line_span.contains(label.last_offset()); if (margin.filter(() => is_line).is_some()) { let _margin = margin.filter(() => is_line); margin_ptr = some([_margin.unwrap(), is_start]); } else if (!is_start && (!is_end || is_line)) { vbar = vbar.or(some(label).filter(() => !is_parent)); } else { if ( report_row.is_some() && report_row.map_or(false, (o) => isNumber(o[0]) && isBoolean(o[1])) ) { let [_report_row, is_arrow] = report_row.unwrap(); let label_row: number = Option.from( line_labels.enumerate().find(([_, l]) => label === l.label) ).map_or(0, ([r, _]) => r); if (_report_row === label_row) { if (margin.is_some()) { vbar = some(margin.unwrap().label).filter(() => col === i); if (is_start) { continue; } } if (is_arrow) { hbar = some(label); if (!is_parent) { corner = some([label, is_start]); } } else if (!is_start) { vbar = vbar.or(some(label).filter(() => !is_parent)); } } else { vbar = vbar.or( some(label).filter( () => !is_parent && !!(bton(is_start) ^ bton(_report_row < label_row)) ) ); } } } } } if ( margin_ptr.is_some() && margin_ptr.map_or(false, (o) => Label.is(o[0]) && isBoolean(o[1])) && is_line ) { let [margin, _is_start] = margin_ptr.unwrap(); if (_is_start) { let is_col = multi_label.map_or(false, (ml) => ml === margin.label); let is_limit = col + 1 === multi_labels.length; if (!is_col && !is_limit) { hbar = hbar.or(some(margin.label)); } } } hbar = hbar.filter( (l) => margin_label.map_or(true, (margin) => margin.label !== l) || !is_line ); const getCorners = (): [Display, Display] => { if ( corner.is_some() && Array.isArray(corner.unwrap()) && Label.is(corner.unwrap()[0]) && isBoolean(corner.unwrap()[1]) ) { let [label, is_start] = corner.unwrap(); return [ new Display(is_start ? draw.ltop : draw.lbot).fg(label.color), new Display(draw.hbar).fg(label.color) ]; } else if (hbar.filter(() => vbar.is_some() && !this.config.cross_gap).is_some()) { let label: Label = hbar .filter(() => vbar.is_some() && !this.config.cross_gap) .unwrap(); return [ new Display(draw.xbar).fg(label.color), new Display(draw.hbar).fg(label.color) ]; } else if (hbar.is_some()) { let label: Label = hbar.unwrap(); const d = new Display(draw.hbar).fg(label.color); return [d, d]; } else if (vbar.is_some()) { let label: Label = vbar.unwrap(); let vb = new Display(is_ellipsis ? draw.vbar_gap : draw.vbar); return [vb.fg(label.color), new Display(' ').fg(none())]; } else if (margin_ptr.is_some() && is_line) { let [margin, is_start] = margin_ptr.unwrap(); let is_col = multi_label.map_or(false, (ml) => ml === margin.label); let is_limit = col === multi_labels.length; return [ new Display( is_limit ? draw.rarrow : is_col ? is_start ? draw.ltop : draw.lcross : draw.hbar ).fg(margin.label.color), new Display(!is_limit ? draw.hbar : ' ').fg(margin.label.color) ]; } else { const d = new Display(' ').fg(none()); return [d, d]; } }; let [a, b] = getCorners(); write(w, '{}', a); if (!this.config.compact) { write(w, '{}', b); } } } }; // #endregion //#region [ rgba(0, 0, 0, 0.3) ] Body let is_ellipsis = false; for (let idx of range(line_range.start, line_range.end)) { if (src.line(idx).is_none()) { continue; } let line = src.line(idx).unwrap(); const f_labels = multi_labels.enumerate().filter_map(([_i, label]) => { let is_start = line.span().contains(label.span.start); let is_end = line.span().contains(label.last_offset()); if (is_start) { // TODO: Check to see whether multi is the first on the start line or first on the end line return new LineLabel(label.span.start - line.offset(), label, true, false); } else if (is_end) { return new LineLabel(label.last_offset() - line.offset(), label, true, true); } else { return null; } }); // let margin_label = min_by_key(f_labels, ll => [ll.col, !ll.label.span.start]); let margin_label = min_by_key(f_labels, (ll) => ll.col); // .min_by_key(ll => [ll.col, !ll.label.span.start])); // Generate a list of labels for this line, along with their label columns let line_labels = multi_labels.enumerate().filter_map(([_i, label]) => { let is_start = line.span().contains(label.span.start); let is_end = line.span().contains(label.last_offset()); if (is_start && margin_label.map_or(true, (m: any) => label !== m.label)) { // TODO: Check to see whether multi is the first on the start line or first on the end line return new LineLabel( label.span.start - line.offset(), label, true, false // Multi-line spans don;t have their messages drawn at the start ); } else if (is_end) { return new LineLabel( label.last_offset() - line.offset(), label, true, true // Multi-line spans have their messages drawn at the end ); } else { return null; } }); for (let label_info of labels.filter( (l) => l.label.span.start >= line.span().start && l.label.span.end <= line.span().end )) { if (label_info.kind === LabelKind.Inline) { let col = match(this.config.label_attach, [ [LabelAttach.Start, () => label_info.label.span.start], [ LabelAttach.Middle, () => (label_info.label.span.start + label_info.label.span.end) / 2 ], [LabelAttach.End, () => label_info.label.last_offset()] ]); line_labels.push( new LineLabel( col.max(label_info.label.span.start) - line.offset(), label_info.label, false, true ) ); } } // Skip this line if we don't have labels for it if (line_labels.length === 0 && margin_label.is_none()) { let within_label = multi_labels.some((label) => label.span.contains(line.span().start)); if (!is_ellipsis && within_label) { is_ellipsis = true; } else { if (!this.config.compact && !is_ellipsis) { write_margin(w, idx, false, is_ellipsis, false, none(), [], none()); write(w, '\n'); } is_ellipsis = true; continue; } } else { is_ellipsis = false; } // Sort the labels by their columns sort_by_key(line_labels, (ll) => ll.label.order); sort_by_key(line_labels, (ll) => ll.col); sort_by_key(line_labels, (ll) => bton(!ll.label.span.start)); // Determine label bounds so we know where to put error messages let arrow_end_space = this.config.compact ? 1 : 2; let arrow_len = line_labels.reduce((l, ll) => { return ll.multi ? line.len() : l.max(ll.label.span.end.saturating_sub(line.offset())); }, 0) + arrow_end_space; // Should we draw a vertical bar as part of a label arrow on this line? let get_vbar = (col: number, row: number): Option> => Option.from( line_labels // Only labels with notes get an arrow .enumerate() .filter( ([_, ll]) => ll.label.msg.is_some() && margin_label.map_or(true, (m) => ll.label !== m.label) ) .find( ([j, ll]) => ll.col === col && ((row <= j && !ll.multi) || (row <= j && ll.multi)) ) ).map(([_, ll]) => ll); let get_highlight = (col: number): Option> => min_by_key( margin_label .iter() .map((ll) => ll.label) .chain(multi_labels.map((l) => l)) .chain(line_labels.map((l) => l.label)) .filter((l) => l.span.contains(line.offset() + col)), // Prioritise displaying smaller spans // .min_by_key((l: any) => [-l.priority, l.span.len()]); // .min_by_key(l => l.span.len())); (l) => -l.priority + l.span.len() ); // l => l.span.len()); // l => -l.priority); let get_underline = (col: number): Option> => min_by_key( line_labels.filter((ll: any) => { return ( this.config.underlines && // Underlines only occur for inline spans (highlighting can occur for all spans) !ll.multi && ll.label.span.contains(line.offset() + col) ); }), // Prioritise displaying smaller spans // .min_by_key(ll => [-ll.label.priority, ll.label.span.len()]); // .min_by_key(ll => ll.label.span.len())); // ll => -ll.label.priority + ll.label.span.len()); (ll) => ll.label.span.len() ); // ll => -ll.label.priority); // Margin write_margin(w, idx, true, is_ellipsis, true, none(), line_labels, margin_label); // Line if (!is_ellipsis) { for (let [col, _c] of enumerate(line.chars() as any as string[])) { let highlight = get_highlight(col); let color = highlight.is_some() ? highlight.unwrap().color : this.config.unimportant_color(); let [c, width] = this.config.char_width(_c, col); for (let _ of range(0, width)) { write(w, '{}', new Display(c).fg(color)); } } } write(w, '\n'); // Arrows !!! for (let row of range(0, line_labels.length)) { let line_label = line_labels[row]; if (!this.config.compact) { // Margin alternate write_margin( w, idx, false, is_ellipsis, true, some([row, false]), line_labels, margin_label ); // Lines alternate let chars = line.chars(); let { next } = makeIter(chars); for (let col of range(0, arrow_len)) { let width = next().map_or(1, (c) => this.config.char_width(c, col)[1]); let vbar = get_vbar(col, row); let underline = get_underline(col).filter(() => row === 0); const getCTailOuter = () => { if (vbar.is_some()) { let vbar_ll = vbar.unwrap(); const getCTailInner = () => { if (underline.is_some()) { // TODO: Is this good? if (vbar_ll.label.span.len() <= 1) { return [draw.underbar, draw.underline]; } else if (line.offset() + col === vbar_ll.label.span.start) { return [draw.ltop, draw.underbar]; } else if (line.offset() + col === vbar_ll.label.last_offset()) { return [draw.rtop, draw.underbar]; } else { return [draw.underbar, draw.underline]; } } else if (vbar_ll.multi && row === 0 && this.config.multiline_arrows) { return [draw.uarrow, new Display(' ')]; } else { return [draw.vbar, new Display(' ')]; } }; let [c, tail] = getCTailInner(); return [ new Display(c).fg(vbar_ll.label.color), new Display(tail).fg(vbar_ll.label.color) ]; } else if (underline.is_some()) { let underline_ll = underline.unwrap(); return [ new Display(draw.underline).fg(underline_ll.label.color), new Display(draw.underline).fg(underline_ll.label.color) ]; } else { return [new Display(' ').fg(none()), new Display(' ').fg(none())]; } }; let [c, tail] = getCTailOuter(); for (let i of range(0, width)) { write(w, '{}', i === 0 ? c : tail); } } write(w, '\n'); } // Margin write_margin( w, idx, false, is_ellipsis, true, some([row, true]), line_labels, margin_label ); // Lines let chars = line.chars(); let { next } = makeIter(chars); for (let col of range(0, arrow_len)) { let n = next(); let width = n.map_or(1, (c) => this.config.char_width(c, col)[1]); let is_hbar = ((col > line_label.col ? 1 : 0) ^ (line_label.multi ? 1 : 0) || (line_label.label.msg.is_some() && line_label.draw_msg && col > line_label.col)) && line_label.label.msg.is_some(); const getctail = (): [any, any] => { if ( col === line_label.col && line_label.label.msg.is_some() && margin_label.map_or(true, (m) => line_label.label != m.label) ) { return [ new Display( line_label.multi ? (line_label.draw_msg ? draw.mbot : draw.rbot) : draw.lbot ).fg(line_label.label.color), new Display(draw.hbar).fg(line_label.label.color) ]; } else if ( get_vbar(col, row) .filter(() => col != line_label.col || line_label.label.msg.is_some()) .is_some() ) { let vbar_ll = get_vbar(col, row) .filter(() => col != line_label.col || line_label.label.msg.is_some()) .unwrap(); if (!this.config.cross_gap && is_hbar) { return [ new Display(draw.xbar).fg(line_label.label.color), new Display(' ').fg(line_label.label.color) ]; } else if (is_hbar) { let d = new Display(draw.hbar).fg(line_label.label.color); return [d, d]; } else { return [ new Display( vbar_ll.multi && row === 0 && this.config.compact ? draw.uarrow : draw.vbar ).fg(vbar_ll.label.color), new Display(' ').fg(line_label.label.color) ]; } } else if (is_hbar) { let d = new Display(draw.hbar).fg(line_label.label.color); return [d, d]; } else { let d = new Display(' ').fg(none()); return [d, d]; } }; let [c, tail] = getctail(); if (width > 0) { write(w, '{}', c); } for (let _ of range(1, width)) { write(w, '{}', tail); } } if (line_label.draw_msg) { write(w, ' {}', new Show(line_label.label.msg)); } write(w, '\n'); } } //#endregion let is_final_group = group_idx + 1 === groups_len; // Help if (this.help.is_some() && is_final_group) { let note = this.help.unwrap(); if (!this.config.compact) { write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, '\n'); } write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, '{}: {}\n', new Display('Help').fg(this.config.note_color()), note); } // Note if (this.note.is_some() && is_final_group) { let note = this.note.unwrap(); if (!this.config.compact) { write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, '\n'); } write_margin(w, 0, false, false, true, some([0, false]), [], none()); write(w, '{}: {}\n', new Display('Note').fg(this.config.note_color()), note); } // Tail of report if (!this.config.compact) { if (is_final_group) { let final_margin = format('{}{}', new Show([draw.hbar, line_no_width + 2]), draw.rbot); writeln(w, '{}', new Display(final_margin).fg(this.config.margin_color())); } else { writeln( w, '{}{}', new Show([' ', line_no_width + 2]), new Display(draw.vbar).fg(this.config.margin_color()) ); } } } if (groups_len === 0) { // Help if (this.help.is_some()) { let note = this.help.unwrap(); if (!this.config.compact) { write(w, '\n'); } write(w, '{}: {}\n', new Display('Help').fg(this.config.note_color()), note); } // Note if (this.note.is_some()) { let note = this.note.unwrap(); if (!this.config.compact) { write(w, '\n'); } write(w, '{}: {}\n', new Display('Note').fg(this.config.note_color()), note); } } } } type MatchResult = T extends abstract new (...args: any) => infer RT ? RT : T; function match(kind: T, matchers: [T, (arg: MatchResult) => R][]): R { for (let [type, then] of matchers) { // TODO: fixme .. this is a hack if (kind === type) return then(kind as any); } return null as any; } function* enumerate(groups: T[]) { for (let i = 0; i < groups.length; i++) yield [i, groups[i]] as [number, T]; return; } function* map(a: Iterator, f: (a: a) => b) { let value = a.next(); while (value.done === false) { yield f(value.value); value = a.next(); } } function* take_while(a: Iterator, p: (a: a) => boolean) { let current = a.next(); while (current.done === false) { if (p(current.value)) yield current.value; else break; current = a.next(); } } function to_array(a: Iterator) { let result: a[] = []; let current = a.next(); while (current.done === false) { result.push(current.value); current = a.next(); } return result; } function count(a: Iterator) { return to_array(a).length; } function makeIter(arr: T) { let cursor = 0; let next = (): Option => { const res = arr[cursor++]; if (res === undefined) return none(); return some(res); }; return { next, cursor }; } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/ReportBuilder.ts ================================================ import { Option, some } from "../data/Option"; import { Span } from "../data/Span"; import { Config } from "./Config"; import { Label } from "./Label"; import { iReport, Report } from "./Report"; import { ReportKind } from "./ReportKind"; /// A type used to build a [`Report`]. export interface iReportBuilder { kind: ReportKind; code: string; msg: string; note: string; help: string; location: [S['SourceId'] /* ::Owned */, number]; labels: Label[]; config: Config; } export class ReportBuilder { constructor( private kind: typeof ReportKind, private code: Option, private msg: Option, private note: Option, private help: Option, private location: [S['SourceId'], number], private labels: Label[], private config: Config ) { } /// Give this report a numerical code that may be used to more precisely look up the error in documentation. with_code(code: number | string): this { this.code = some(code.toString().padStart(2, '0')); return this; } /// Set the message of this report. set_message(msg: string) { this.msg = some(msg); } /// Add a message to this report. with_message(msg: string): this { this.msg = some(msg); return this; } /// Set the note of this report. set_note(note: string) { this.note = some(note); } /// Set the note of this report. with_note(note: string): this { this.set_note(note); return this; } /// Set the help message of this report. set_help(note: string) { this.help = some(note); } /// Set the help message of this report. with_help(note: string): this { this.set_help(note); return this; } /// Add a label to the report. add_label(label: Label) { this.labels.push(label); } /// Add multiple labels to the report. add_labels(labels: Label[]) { this.labels.push(...labels); } /// Add a label to the report. with_label(label: Label): this { this.add_label(label); return this; } /// Use the given [`Config`] to determine diagnostic attributes. with_config(config: Config): this { this.config = config; return this; } /// Finish building the [`Report`]. finish(): iReport { const r = new Report( this.kind, this.code, this.msg, this.note, this.help, this.location, this.labels, this.config ); return r; } } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/ReportKind.ts ================================================ import { Formatter } from "../data/Formatter"; import { write } from "../write"; /// A type that defines the kind of report being produced. export class ReportKind { constructor(...args: any[]) {} fmt(f: Formatter): any { if (this instanceof ReportKind.Error) return write(f.buf, "Error"); if (this instanceof ReportKind.Warning) return write(f.buf, "Warning"); if (this instanceof ReportKind.Advice) return write(f.buf, "Advice"); if (this instanceof ReportKind.Custom) return write(f.buf, "{}", this.s); throw 'invalid ReportKind'; } /// The report is an error and indicates a critical problem that prevents the program performing the requested /// action. static Error = class Error extends ReportKind { }; /// The report is a warning and indicates a likely problem, but not to the extent that the requested action cannot /// be performed. static Warning = class Warning extends ReportKind { }; /// The report is advice to the user about a potential anti-pattern of other benign issues. static Advice = class Advice extends ReportKind { }; /// The report is of a kind not built into Ariadne. static Custom = class Custom extends ReportKind { constructor(public s: any, public color: any) { super() } }; } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/Source.ts ================================================ import assert from 'assert'; import { Display } from '../data/Display'; import { none, Option, some } from '../data/Option'; import { err, ok, Result } from '../data/Result'; import { Span } from '../data/Span'; import { Range } from '../data/Range'; import { binary_search_by_key } from '../utils'; import { Displayable, format } from '../write'; export type ErrMsg = string; export type CacheInit = [id: string, source: Source] | Source | FnCache; /// A trait implemented by [`Source`] caches. export abstract class Cache { /// Fetch the [`Source`] identified by the given ID, if possible. abstract fetch(id: Id): Result; /// Display the given ID. as a single inline value. /// /// This function may make use of attributes from the [`Fmt`] trait. abstract display(id: Id): Option; static from(init: CacheInit) { if (Source.is(init)) return init; if (FnCache.is(init)) return init; const [id, source] = init; return new IdSource(source.lines(), source.len(), init); } } /// A type representing a single line of a [`Source`]. class Line { constructor(private _offset: number, private _len: number, private _chars: string) {} /// Get the offset of this line in the original [`Source`] (i.e: the number of characters that precede it). offset(): number { return this._offset; } /// Get the character length of this line. len(): number { return this._len; } /// Get the offset span of this line in the original [`Source`]. span(): Range { return new Range(this.offset(), this.offset() + this.len()); } /// Return an iterator over the characters in the line, excluding trailing whitespace. chars(): string { return this._chars; } } /// A type representing a single source that may be referred to by [`Span`]s. /// /// In most cases, a source is a single input file. export class Source implements Cache { constructor(private _lines: Line[], private _len: number) {} /// Generate a [`Source`] from the given [`str`]. /// /// Note that this function can be expensive for long strings. Use an implementor of [`Cache`] where possible. static from(s: string, ...args: any[]): Source { let offset = 0; const lines = s .split('\n') // TODO: Handle non-\n newlines .map((line) => { let l = new Line( offset, line.length + 1, // line.chars().count() + 1, line.trimEnd() ); offset += l.len(); return l; }); return new Source(lines, offset); } /// Get the length of the total number of characters in the source. len(): number { return this._len; } /// Return an iterator over the characters in the source. chars(): string { return this.lines() .map((l) => l.chars()) .flat() as any; // TODO } /// Get access to a specific, zero-indexed [`Line`]. line(idx: number): Option { const line = this.lines()[idx]; return line === undefined ? none() : some(line); } /// Return an iterator over the [`Line`]s in this source. lines(): Line[] { return this._lines; } /// Get the line that the given offset appears on, and the line/column numbers of the offset. /// /// Note that the line/column numbers are zero-indexed. get_offset_line(offset: number): Option<[Line, number, number]> { if (offset <= this.len()) { let idx = binary_search_by_key(this.lines(), offset, (line) => line.offset()).unwrap_or_else( (idx) => Math.max(0, (idx as any).saturating_sub(1)) ); let line = this.lines()[idx]; assert( line && offset >= line.offset(), format('offset = {}, line.offset = {}, idx = {}', offset, line?.offset() ?? Infinity, idx) ); const os = line.offset(); return some([line, idx, offset - os]); } else { return none(); } } /// Get the range of lines that this span runs across. /// /// The resulting range is guaranteed to contain valid line indices (i.e: those that can be used for /// [`Source::line`]). get_line_range(span: Span): Range { let start = this.get_offset_line(span.start).map_or(0, ([_, l, __]) => l); let end = this.get_offset_line((span.end as any).saturating_sub(1).max(span.start)).map_or( this.lines().length, ([_, l, __]) => l + 1 ); // start..end return new Range(start, end); } fetch(_: any): Result { return ok(this); } display(_: any): Option { return none(); } static is(other: any): other is Source { return other instanceof Source; } } export class IdSource extends Source { constructor(_lines: Line[], _len: number, public data: [id: string, source: Source]) { super(_lines, _len); } fetch(id: string): Result { return id === this.data[0] ? ok(this.data[1]) : err(format("Failed to fetch source '{}'", id)); } display(id: string): Option { return some(new Display(id)); } } type PathBuf = {}; type Path = { to_path_buf(): PathBuf; display(): Option; toString(): string; }; /// A [`Cache`] that fetches [`Source`]s from the filesystem. export class FileCache implements Cache { constructor(public files: Map) {} static default(): FileCache { return new FileCache(new Map() /* HashMap::default() */); } fetch(path: Path): Result { const entry = this.files.get(path.to_path_buf()); if (entry !== undefined) return ok(entry); const source = Source.from(''); this.files.set(path.to_path_buf(), source); return ok(source); } display(path: Path): Option { return path.display(); } static is(other: any): other is FileCache { return other instanceof FileCache; } } /// A [`Cache`] that fetches [`Source`]s using the provided function. export class FnCache implements Cache { constructor(public sources: Map, public get: F) {} /// Create a new [`FnCache`] with the given fetch function. static new(get: F): FnCache { return new FnCache(new Map() /* HashMap::default() */, get); } /// Pre-insert a selection of [`Source`]s into this cache. with_sources(sources: [Id, Source][]): this { // this.sources.reserve(sources.length); for (let [id, src] of sources) { this.sources.set(id, src); } return this; } fetch(id: any): Result { const entry = this.sources.get(id); if (entry !== undefined) return ok(entry); const source = Source.from(this.get(id)); this.sources.set(id, source); return ok(source); } display(id: any): Option { return some(id); } static is(other: any): other is FnCache { return other instanceof FnCache; } } /// Create a [`Cache`] from a collection of ID/strings, where each corresponds to a [`Source`]. export function sources>( iter: I ): FnCache { return FnCache.new((id: Id) => format("Failed to fetch source '{}'", id)).with_sources( iter.map(([id, s]) => [id, Source.from(s)] as [Id, Source]) ); } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/SourceGroup.ts ================================================ import { Span } from "../data/Span"; import { Range } from "../data/Range"; import { LabelInfo } from "./LabelInfo"; export class SourceGroup { constructor( public src_id: string, public span: Range, public labels: LabelInfo[] ) { } } ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/chalk/chalk/license ================================================ MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) 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. ================================================ FILE: lang/shadeup-frontend/lib/ariadne-ts/src/lib/chalk/chalk/readme.md ================================================



Chalk


> Terminal string styling done right [![Coverage Status](https://codecov.io/gh/chalk/chalk/branch/main/graph/badge.svg)](https://codecov.io/gh/chalk/chalk) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![run on repl.it](https://img.shields.io/badge/Run_on_Replit-f26207?logo=replit&logoColor=white)](https://repl.it/github/chalk/chalk) ![](media/screenshot.png)
---
---
## Highlights - Expressive API - Highly performant - No dependencies - Ability to nest styles - [256/Truecolor color support](#256-and-truecolor-color-support) - Auto-detects color support - Doesn't extend `String.prototype` - Clean and focused - Actively maintained - [Used by ~86,000 packages](https://www.npmjs.com/browse/depended/chalk) as of October 4, 2022 ## Install ```sh npm install chalk ``` **IMPORTANT:** Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. [Read more.](https://github.com/chalk/chalk/releases/tag/v5.0.0) ## Usage ```js import chalk from 'chalk'; console.log(chalk.blue('Hello world!')); ``` Chalk comes with an easy to use composable API where you just chain and nest the styles you want. ```js import chalk from 'chalk'; const log = console.log; // Combine styled and normal strings log(chalk.blue('Hello') + ' World' + chalk.red('!')); // Compose multiple styles using the chainable API log(chalk.blue.bgRed.bold('Hello world!')); // Pass in multiple arguments log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); // Nest styles log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); // Nest styles of the same type even (color, underline, background) log(chalk.green( 'I am a green line ' + chalk.blue.underline.bold('with a blue substring') + ' that becomes green again!' )); // ES2015 template literal log(` CPU: ${chalk.red('90%')} RAM: ${chalk.green('40%')} DISK: ${chalk.yellow('70%')} `); // Use RGB colors in terminal emulators that support it. log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); log(chalk.hex('#DEADED').bold('Bold gray!')); ``` Easily define your own themes: ```js import chalk from 'chalk'; const error = chalk.bold.red; const warning = chalk.hex('#FFA500'); // Orange color console.log(error('Error!')); console.log(warning('Warning!')); ``` Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): ```js import chalk from 'chalk'; const name = 'Sindre'; console.log(chalk.green('Hello %s'), name); //=> 'Hello Sindre' ``` ## API ### chalk.``); } }; return [ children, open, isFullscreen, styleStr, $panelHeight, panelHeight, shouldPush, resize_handler, click_handler, click_handler_1 ]; } class FloatingPanel extends SvelteComponent { constructor(options) { super(); init(this, options, instance$5, create_fragment$5, safe_not_equal, { children: 0 }); } } const host = ''; /* ui/components/Host.svelte generated by Svelte v3.59.2 */ function get_each_context$1(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[1] = list[i]; return child_ctx; } // (7:1) {#each children as child} function create_each_block$1(ctx) { let switch_instance; let switch_instance_anchor; let current; const switch_instance_spread_levels = [ { value: /*child*/ ctx[1].value }, { setValue: /*child*/ ctx[1].setValue }, { children: /*child*/ ctx[1].children }, /*child*/ ctx[1].options ]; var switch_value = /*child*/ ctx[1].type; function switch_props(ctx) { let switch_instance_props = {}; for (let i = 0; i < switch_instance_spread_levels.length; i += 1) { switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]); } return { props: switch_instance_props }; } if (switch_value) { switch_instance = construct_svelte_component(switch_value, switch_props()); } return { c() { if (switch_instance) create_component(switch_instance.$$.fragment); switch_instance_anchor = empty(); }, m(target, anchor) { if (switch_instance) mount_component(switch_instance, target, anchor); insert(target, switch_instance_anchor, anchor); current = true; }, p(ctx, dirty) { const switch_instance_changes = (dirty & /*children*/ 1) ? get_spread_update(switch_instance_spread_levels, [ { value: /*child*/ ctx[1].value }, { setValue: /*child*/ ctx[1].setValue }, { children: /*child*/ ctx[1].children }, get_spread_object(/*child*/ ctx[1].options) ]) : {}; if (dirty & /*children*/ 1 && switch_value !== (switch_value = /*child*/ ctx[1].type)) { if (switch_instance) { group_outros(); const old_component = switch_instance; transition_out(old_component.$$.fragment, 1, 0, () => { destroy_component(old_component, 1); }); check_outros(); } if (switch_value) { switch_instance = construct_svelte_component(switch_value, switch_props()); create_component(switch_instance.$$.fragment); transition_in(switch_instance.$$.fragment, 1); mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor); } else { switch_instance = null; } } else if (switch_value) { switch_instance.$set(switch_instance_changes); } }, i(local) { if (current) return; if (switch_instance) transition_in(switch_instance.$$.fragment, local); current = true; }, o(local) { if (switch_instance) transition_out(switch_instance.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(switch_instance_anchor); if (switch_instance) destroy_component(switch_instance, detaching); } }; } function create_fragment$4(ctx) { let div; let current; let each_value = /*children*/ ctx[0]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); return { c() { div = element("div"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(div, "class", "host"); }, m(target, anchor) { insert(target, div, anchor); for (let i = 0; i < each_blocks.length; i += 1) { if (each_blocks[i]) { each_blocks[i].m(div, null); } } current = true; }, p(ctx, [dirty]) { if (dirty & /*children*/ 1) { each_value = /*children*/ ctx[0]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context$1(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$1(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(div, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out(i); } check_outros(); } }, i(local) { if (current) return; for (let i = 0; i < each_value.length; i += 1) { transition_in(each_blocks[i]); } current = true; }, o(local) { each_blocks = each_blocks.filter(Boolean); for (let i = 0; i < each_blocks.length; i += 1) { transition_out(each_blocks[i]); } current = false; }, d(detaching) { if (detaching) detach(div); destroy_each(each_blocks, detaching); } }; } function instance$4($$self, $$props, $$invalidate) { let { children } = $$props; $$self.$$set = $$props => { if ('children' in $$props) $$invalidate(0, children = $$props.children); }; return [children]; } class Host extends SvelteComponent { constructor(options) { super(); init(this, options, instance$4, create_fragment$4, safe_not_equal, { children: 0 }); } } /* ui/components/Group.svelte generated by Svelte v3.59.2 */ function get_each_context(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[6] = list[i]; child_ctx[8] = i; return child_ctx; } // (43:2) {#each children as child, i} function create_each_block(ctx) { let div; let switch_instance; let t; let div_class_value; let current; const switch_instance_spread_levels = [ { value: /*child*/ ctx[6].value }, { setValue: /*child*/ ctx[6].setValue }, { children: /*child*/ ctx[6].children }, /*child*/ ctx[6].options ]; var switch_value = /*child*/ ctx[6].type; function switch_props(ctx) { let switch_instance_props = {}; for (let i = 0; i < switch_instance_spread_levels.length; i += 1) { switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]); } return { props: switch_instance_props }; } if (switch_value) { switch_instance = construct_svelte_component(switch_value, switch_props()); } return { c() { div = element("div"); if (switch_instance) create_component(switch_instance.$$.fragment); t = space(); attr(div, "class", div_class_value = "min-w-[200px - 16px] bg-gray-500 bg-opacity-5 control-" + /*child*/ ctx[6].name); toggle_class(div, "rounded-b-md", /*i*/ ctx[8] === /*children*/ ctx[1].length - 1); }, m(target, anchor) { insert(target, div, anchor); if (switch_instance) mount_component(switch_instance, div, null); append(div, t); current = true; }, p(ctx, dirty) { const switch_instance_changes = (dirty & /*children*/ 2) ? get_spread_update(switch_instance_spread_levels, [ { value: /*child*/ ctx[6].value }, { setValue: /*child*/ ctx[6].setValue }, { children: /*child*/ ctx[6].children }, get_spread_object(/*child*/ ctx[6].options) ]) : {}; if (dirty & /*children*/ 2 && switch_value !== (switch_value = /*child*/ ctx[6].type)) { if (switch_instance) { group_outros(); const old_component = switch_instance; transition_out(old_component.$$.fragment, 1, 0, () => { destroy_component(old_component, 1); }); check_outros(); } if (switch_value) { switch_instance = construct_svelte_component(switch_value, switch_props()); create_component(switch_instance.$$.fragment); transition_in(switch_instance.$$.fragment, 1); mount_component(switch_instance, div, t); } else { switch_instance = null; } } else if (switch_value) { switch_instance.$set(switch_instance_changes); } if (!current || dirty & /*children*/ 2 && div_class_value !== (div_class_value = "min-w-[200px - 16px] bg-gray-500 bg-opacity-5 control-" + /*child*/ ctx[6].name)) { attr(div, "class", div_class_value); } if (!current || dirty & /*children, children*/ 2) { toggle_class(div, "rounded-b-md", /*i*/ ctx[8] === /*children*/ ctx[1].length - 1); } }, i(local) { if (current) return; if (switch_instance) transition_in(switch_instance.$$.fragment, local); current = true; }, o(local) { if (switch_instance) transition_out(switch_instance.$$.fragment, local); current = false; }, d(detaching) { if (detaching) detach(div); if (switch_instance) destroy_component(switch_instance); } }; } function create_fragment$3(ctx) { let div0; let button; let span0; let svg; let path0; let path1; let t0; let span1; let t1; let t2; let t3; let t4; let div2; let div1; let current; let mounted; let dispose; let each_value = /*children*/ ctx[1]; let each_blocks = []; for (let i = 0; i < each_value.length; i += 1) { each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); return { c() { div0 = element("div"); button = element("button"); span0 = element("span"); svg = svg_element("svg"); path0 = svg_element("path"); path1 = svg_element("path"); t0 = space(); span1 = element("span"); t1 = text(/*value*/ ctx[0]); t2 = space(); t3 = text(/*$height*/ ctx[3]); t4 = space(); div2 = element("div"); div1 = element("div"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(path0, "d", "M0 0h24v24H0V0z"); attr(path0, "fill", "none"); attr(path1, "d", "M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6-6-6z"); attr(svg, "class", "transition-all duration-300 transform max-w-[16px]"); attr(svg, "xmlns", "http://www.w3.org/2000/svg"); attr(svg, "height", "24px"); attr(svg, "viewBox", "0 0 24 24"); attr(svg, "width", "24px"); attr(svg, "fill", "#fff"); toggle_class(svg, "rotate-90", /*open*/ ctx[2]); attr(span0, "class", "w-4 h-4 ml-1 opacity-50 flex items-center justify-center rounded-md"); attr(span1, "class", "flex-1 ml-2 text-left text-sm text-white text-opacity-75"); attr(button, "class", "flex flex-row items-center mx-1 bg-gray-500 bg-opacity-5"); toggle_class(button, "rounded-md", !/*open*/ ctx[2]); toggle_class(button, "rounded-t-md", /*open*/ ctx[2]); attr(div0, "class", "flex flex-col"); attr(div1, "class", "flex flex-col mx-1"); attr(div2, "class", "transition-all mb-1 flex flex-col"); set_style(div2, "max-height", (/*open*/ ctx[2] ? /*$height*/ ctx[3] : 0) + "px"); set_style(div2, "overflow", "hidden"); }, m(target, anchor) { insert(target, div0, anchor); append(div0, button); append(button, span0); append(span0, svg); append(svg, path0); append(svg, path1); append(button, t0); append(button, span1); append(span1, t1); append(span1, t2); append(span1, t3); insert(target, t4, anchor); insert(target, div2, anchor); append(div2, div1); for (let i = 0; i < each_blocks.length; i += 1) { if (each_blocks[i]) { each_blocks[i].m(div1, null); } } current = true; if (!mounted) { dispose = [ listen(button, "click", /*click_handler*/ ctx[5]), action_destroyer(measureElement.call(null, div1, { height: /*height*/ ctx[4] })) ]; mounted = true; } }, p(ctx, [dirty]) { if (!current || dirty & /*open*/ 4) { toggle_class(svg, "rotate-90", /*open*/ ctx[2]); } if (!current || dirty & /*value*/ 1) set_data(t1, /*value*/ ctx[0]); if (!current || dirty & /*$height*/ 8) set_data(t3, /*$height*/ ctx[3]); if (!current || dirty & /*open*/ 4) { toggle_class(button, "rounded-md", !/*open*/ ctx[2]); } if (!current || dirty & /*open*/ 4) { toggle_class(button, "rounded-t-md", /*open*/ ctx[2]); } if (dirty & /*children*/ 2) { each_value = /*children*/ ctx[1]; let i; for (i = 0; i < each_value.length; i += 1) { const child_ctx = get_each_context(ctx, each_value, i); if (each_blocks[i]) { each_blocks[i].p(child_ctx, dirty); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(div1, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out(i); } check_outros(); } if (!current || dirty & /*open, $height*/ 12) { set_style(div2, "max-height", (/*open*/ ctx[2] ? /*$height*/ ctx[3] : 0) + "px"); } }, i(local) { if (current) return; for (let i = 0; i < each_value.length; i += 1) { transition_in(each_blocks[i]); } current = true; }, o(local) { each_blocks = each_blocks.filter(Boolean); for (let i = 0; i < each_blocks.length; i += 1) { transition_out(each_blocks[i]); } current = false; }, d(detaching) { if (detaching) detach(div0); if (detaching) detach(t4); if (detaching) detach(div2); destroy_each(each_blocks, detaching); mounted = false; run_all(dispose); } }; } function instance$3($$self, $$props, $$invalidate) { let $height; let { value } = $$props; let { children } = $$props; let open = true; let height = writable(0); component_subscribe($$self, height, value => $$invalidate(3, $height = value)); const click_handler = () => { $$invalidate(2, open = !open); }; $$self.$$set = $$props => { if ('value' in $$props) $$invalidate(0, value = $$props.value); if ('children' in $$props) $$invalidate(1, children = $$props.children); }; return [value, children, open, $height, height, click_handler]; } class Group extends SvelteComponent { constructor(options) { super(); init(this, options, instance$3, create_fragment$3, safe_not_equal, { value: 0, children: 1 }); } } const Checkbox_svelte_svelte_type_style_lang = ''; /* ui/components/Checkbox.svelte generated by Svelte v3.59.2 */ function create_if_block(ctx) { let div; return { c() { div = element("div"); attr(div, "class", "w-2 h-2 rounded-sm bg-purple-600 "); }, m(target, anchor) { insert(target, div, anchor); }, d(detaching) { if (detaching) detach(div); } }; } function create_fragment$2(ctx) { let div; let button; let t; let input; let mounted; let dispose; let if_block = /*value*/ ctx[0] && create_if_block(); return { c() { div = element("div"); button = element("button"); if (if_block) if_block.c(); t = space(); input = element("input"); attr(button, "class", "rounded-md border border-gray-600 bg-gray-900 w-4 h-4 cursor-pointer flex items-center justify-center"); set_style(input, "display", "none"); input.hidden = true; attr(input, "type", "checkbox"); input.checked = /*value*/ ctx[0]; attr(div, "class", "px-3 pt-0 pb-1 flex flex-row items-center justify-end"); }, m(target, anchor) { insert(target, div, anchor); append(div, button); if (if_block) if_block.m(button, null); append(div, t); append(div, input); if (!mounted) { dispose = [ listen(button, "click", /*click_handler*/ ctx[2]), listen(input, "input", /*input_handler*/ ctx[3]) ]; mounted = true; } }, p(ctx, [dirty]) { if (/*value*/ ctx[0]) { if (if_block) ; else { if_block = create_if_block(); if_block.c(); if_block.m(button, null); } } else if (if_block) { if_block.d(1); if_block = null; } if (dirty & /*value*/ 1) { input.checked = /*value*/ ctx[0]; } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); if (if_block) if_block.d(); mounted = false; run_all(dispose); } }; } function instance$2($$self, $$props, $$invalidate) { let { value } = $$props; let { setValue = () => { } } = $$props; const click_handler = event => { $$invalidate(0, value = !value); setValue(value); }; const input_handler = e => { setValue(e.target.checked); $$invalidate(0, value = e.target.checked); }; $$self.$$set = $$props => { if ('value' in $$props) $$invalidate(0, value = $$props.value); if ('setValue' in $$props) $$invalidate(1, setValue = $$props.setValue); }; return [value, setValue, click_handler, input_handler]; } class Checkbox extends SvelteComponent { constructor(options) { super(); init(this, options, instance$2, create_fragment$2, safe_not_equal, { value: 0, setValue: 1 }); } } /* ui/components/Button.svelte generated by Svelte v3.59.2 */ function create_fragment$1(ctx) { let div; let button; let t; let mounted; let dispose; return { c() { div = element("div"); button = element("button"); t = text(/*text*/ ctx[0]); attr(button, "class", "rounded-md hover:border-purple-600 border border-gray-600 bg-gray-900 w-full cursor-pointer flex items-center justify-center"); attr(div, "class", "px-3 pt-0 pb-1 flex"); }, m(target, anchor) { insert(target, div, anchor); append(div, button); append(button, t); if (!mounted) { dispose = listen(button, "click", /*click_handler*/ ctx[2]); mounted = true; } }, p(ctx, [dirty]) { if (dirty & /*text*/ 1) set_data(t, /*text*/ ctx[0]); }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); mounted = false; dispose(); } }; } function instance$1($$self, $$props, $$invalidate) { let { text } = $$props; let { setValue = () => { } } = $$props; const click_handler = event => { setValue(true); }; $$self.$$set = $$props => { if ('text' in $$props) $$invalidate(0, text = $$props.text); if ('setValue' in $$props) $$invalidate(1, setValue = $$props.setValue); }; return [text, setValue, click_handler]; } class Button extends SvelteComponent { constructor(options) { super(); init(this, options, instance$1, create_fragment$1, safe_not_equal, { text: 0, setValue: 1 }); } } /* ui/components/Text.svelte generated by Svelte v3.59.2 */ function create_fragment(ctx) { let div; let input; let mounted; let dispose; return { c() { div = element("div"); input = element("input"); attr(input, "class", "outline-none border border-gray-600 bg-gray-800 bg-opacity-30 p-0.5 px-1 text-sm w-full rounded-md"); attr(input, "type", "text"); input.value = /*value*/ ctx[0]; attr(div, "class", "px-3 pt-0 pb-1"); }, m(target, anchor) { insert(target, div, anchor); append(div, input); if (!mounted) { dispose = listen(input, "input", /*input_handler*/ ctx[2]); mounted = true; } }, p(ctx, [dirty]) { if (dirty & /*value*/ 1 && input.value !== /*value*/ ctx[0]) { input.value = /*value*/ ctx[0]; } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); mounted = false; dispose(); } }; } function instance($$self, $$props, $$invalidate) { let { value } = $$props; let { setValue = () => { } } = $$props; const input_handler = e => { setValue(e.target.value); $$invalidate(0, value = e.target.value); }; $$self.$$set = $$props => { if ('value' in $$props) $$invalidate(0, value = $$props.value); if ('setValue' in $$props) $$invalidate(1, setValue = $$props.setValue); }; return [value, setValue, input_handler]; } class Text extends SvelteComponent { constructor(options) { super(); init(this, options, instance, create_fragment, safe_not_equal, { value: 0, setValue: 1 }); } } function initPuck(canvas) { let uiContainer = document.querySelector(".ui-container"); let puckDown = false; let puckId = ""; let pucks = {}; function blankUISink() { return { knob: /* @__PURE__ */ new Map(), knobCounter: 0, button: /* @__PURE__ */ new Map(), buttonCounter: 0, switch: /* @__PURE__ */ new Map(), switchCounter: 0, slider: /* @__PURE__ */ new Map(), sliderCounter: 0, puck: /* @__PURE__ */ new Map(), puckCounter: 0 }; } let uiSink = blankUISink(); let uiSinkLastFrame = blankUISink(); window.addEventListener("mousedown", (e) => { if (e.target.closest(".puck")) { let p = e.target.closest(".puck"); p.dataset.down = true; let mp = getPosRelativeToCanvas([e.clientX, e.clientY]); let rect = p.getBoundingClientRect(); let pmp = getPosRelativeToCanvas([rect.left + rect.width / 2, rect.top + rect.height / 2]); p.dataset.offsetX = pmp[0] - mp[0]; p.dataset.offsetY = pmp[1] - mp[1]; puckId = p.dataset.id; puckDown = true; lastPuckPos = [...pmp]; updateDocumentCursor(); } }); function updateDocumentCursor() { if (puckDown) { document.body.style.cursor = "grabbing"; } else { document.body.style.cursor = "default"; } } window.addEventListener("mouseup", (e) => { puckDown = false; updateDocumentCursor(); for (let el of [...document.querySelectorAll(".puck")]) { let p = el; if (p.dataset.down == "true") { p.dataset.down = "false"; } } }); function getPosRelativeToCanvas(pos) { let rect = canvas.getBoundingClientRect(); return [ (pos[0] - rect.left) / rect.width * canvas.width, (pos[1] - rect.top) / rect.height * canvas.height ]; } const host = new Host({ target: document.body, props: { children: [] } }); host.$on("init", (e) => { }); let lastPuckPos = [0, 0]; window.addEventListener("mousemove", (e) => { if (!puckDown) return; let puck = document.querySelector(`.puck[data-id="${puckId}"]`); if (!puck) return; let [x, y] = getPosRelativeToCanvas([e.clientX, e.clientY]); let velocityX = x - lastPuckPos[0]; let velocityY = y - lastPuckPos[1]; let vectorLength = Math.sqrt(velocityX * velocityX + velocityY * velocityY); let angle = Math.atan2(velocityY, velocityX); let oldVel = parseFloat(puck.dataset.velocity ?? "0"); puck.dataset.velocity = (oldVel + vectorLength).toString(); let oldAngle = parseFloat(puck.dataset.angle ?? "0"); let oldDirVelX = oldVel * Math.cos(oldAngle); let oldDirVelY = oldVel * Math.sin(oldAngle); let newDirVelX = vectorLength * Math.cos(angle); let newDirVelY = vectorLength * Math.sin(angle); puck.dataset.angle = Math.atan2(oldDirVelY + newDirVelY, oldDirVelX + newDirVelX).toString(); lastPuckPos = [x, y]; puck.dataset.oldX = puck.offsetLeft.toString(); puck.dataset.oldY = puck.offsetTop.toString(); x += parseInt(puck.dataset.offsetX ?? "0"); y += parseInt(puck.dataset.offsetY ?? "0"); uiSinkLastFrame.puck.set(puckId, { vec: [x, y] }); }); setInterval(() => { for (let el of [...document.querySelectorAll(".puck")]) { let p = el; let maxSpeed = 105; let restitution = 0.75; p.dataset.velocity = Math.max( Math.min(parseFloat(p.dataset.velocity ?? "0") * restitution, maxSpeed), -maxSpeed ).toString(); let angle = parseFloat(p.dataset.angle ?? "0"); let velocity = parseFloat(p.dataset.velocity ?? "0") / 5; if (p.dataset.down == "true") continue; { if (uiSink.puck.has(p.dataset.id) && velocity > 1) { let { vec } = uiSink.puck.get(p.dataset.id); uiSinkLastFrame.puck.set(p.dataset.id, { vec: [vec[0] + Math.cos(angle) * velocity, vec[1] + Math.sin(angle) * velocity] }); } } } }, 1e3 / 60); const SIMPLE_MATH = { clamp(a, min, max) { return Math.min(Math.max(a, min), max); }, clamp2(a, min, max) { return [this.clamp(a[0], min[0], max[0]), this.clamp(a[1], min[1], max[1])]; } }; function _SHADEUP_UI_PUCK(vec, radius = 10, invisible = false) { let id = uiSink.puckCounter++; uiSink.puck.set(id.toString(), { vec: [...vec] }); addPuck(id.toString(), vec, radius, invisible); if (uiSinkLastFrame.puck.has(id.toString())) { return SIMPLE_MATH.clamp2( uiSinkLastFrame.puck.get(id.toString()).vec, [0, 0], [canvas.width, canvas.height] ); } else { return [...vec]; } } function addPuck(name, puck, radius = 10, invisible = false) { puck = [puck[0] / canvas.width, puck[1] / canvas.height]; if (pucks[name]) { pucks[name].div.style.left = `calc(${puck[0] * 100}% - ${radius}px)`; pucks[name].div.style.top = `calc(${puck[1] * 100}% - ${radius}px)`; pucks[name].div.style.opacity = invisible ? "0" : "1"; pucks[name].div.style.width = `${radius * 2}px`; pucks[name].div.style.height = `${radius * 2}px`; return; } let div = document.createElement("div"); div.className = "puck"; div.dataset.id = name; div.innerHTML = ``; div.style.width = `${radius * 2}px`; div.style.height = `${radius * 2}px`; div.style.opacity = invisible ? "0" : "1"; uiContainer.appendChild(div); pucks[name] = { div, puck }; } let hostChildren = []; let childrenCrumbs = []; let rootChild; let preFrameHandlers = []; let postFrameHandlers = []; function createImmediateModeUIElement(type, component, canHaveChildren = false) { let els = /* @__PURE__ */ new Map(); function blankUISink2() { return { map: /* @__PURE__ */ new Map(), counter: 0 }; } let uiSink2 = blankUISink2(); let uiSinkLastFrame2 = blankUISink2(); preFrameHandlers.push(() => { uiSink2 = blankUISink2(); }); postFrameHandlers.push(() => { for (let name of els.keys()) { if (!uiSink2.map.has(name)) ; } uiSinkLastFrame2 = blankUISink2(); }); function invoke(value, options = {}) { let id = uiSink2.counter++; uiSink2.map.set(id.toString(), { value, options }); addControl( id.toString(), { value, options }, canHaveChildren ); if (uiSinkLastFrame2.map.has(id.toString())) { return uiSinkLastFrame2.map.get(id.toString()).value; } else { return value; } } function addControl(name, v, canHaveChildren2 = false) { if (els.has(name)) { els.get(name).$set({ value: v.value, ...v.options }); return; } function setValue(v2) { uiSinkLastFrame2.map.set(name, { value: v2 }); } rootChild.children?.push({ type: component, value: v.value, options: v.options, children: canHaveChildren2 ? [] : void 0, setValue, name: type }); if (canHaveChildren2) { childrenCrumbs.push(rootChild); rootChild = rootChild.children[rootChild.children.length - 1]; } } return invoke; } let slider = createImmediateModeUIElement("slider", Slider); let label = createImmediateModeUIElement("label", Label); let group = createImmediateModeUIElement("group", Group, true); let checkbox = createImmediateModeUIElement("checkbox", Checkbox); let textbox = createImmediateModeUIElement("textbox", Text); let combo = createImmediateModeUIElement("combo", Combo); let button = createImmediateModeUIElement("button", Button); function preFrame() { hostChildren = []; rootChild = { type: FloatingPanel, value: null, children: [], options: {}, setValue: () => { }, name: "root" }; hostChildren.push(rootChild); childrenCrumbs = [rootChild]; for (let handler of preFrameHandlers) { handler(); } uiSink = blankUISink(); } return { frame() { for (let name in pucks) { if (!uiSink.puck.has(name)) { pucks[name].div.remove(); delete pucks[name]; } } for (let post of postFrameHandlers) { post(); } uiSinkLastFrame = blankUISink(); host.$set({ children: hostChildren }); }, preFrame, puck: _SHADEUP_UI_PUCK, slider, controls: { label, group, checkbox, textbox, combo, button, pop() { childrenCrumbs.pop(); rootChild = childrenCrumbs[childrenCrumbs.length - 1]; } } }; } function initUI(canvas) { let { frame, puck, preFrame, slider, controls } = initPuck(canvas); return { frame() { frame(); }, preFrame() { preFrame(); }, puck, slider, controls // controls: host }; } const addUIHook = (engine) => { let { frame: uiFrame, puck, slider, preFrame: uiPreFrame, controls } = initUI(engine.canvas); engine._SHADEUP_UI_PUCK = puck; engine._SHADEUP_UI_SLIDER = slider; engine._SHADEUP_UI_CONTROL = (name, ...args) => { return controls[name](...args); }; return { beforeFrame() { uiPreFrame(); }, afterFrame() { uiFrame(); } }; }; export { addUIHook }; ================================================ FILE: package/engine-dist/ui-f4b4a003.js ================================================ function noop() { } const identity = x => x; function assign(tar, src) { // @ts-ignore for (const k in src) tar[k] = src[k]; return tar; } function run(fn) { return fn(); } function blank_object() { return Object.create(null); } function run_all(fns) { fns.forEach(run); } function is_function(thing) { return typeof thing === 'function'; } function safe_not_equal(a, b) { return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); } function is_empty(obj) { return Object.keys(obj).length === 0; } function subscribe(store, ...callbacks) { if (store == null) { return noop; } const unsub = store.subscribe(...callbacks); return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; } function component_subscribe(component, store, callback) { component.$$.on_destroy.push(subscribe(store, callback)); } function action_destroyer(action_result) { return action_result && is_function(action_result.destroy) ? action_result.destroy : noop; } const is_client = typeof window !== 'undefined'; let now = is_client ? () => window.performance.now() : () => Date.now(); let raf = is_client ? cb => requestAnimationFrame(cb) : noop; const tasks = new Set(); function run_tasks(now) { tasks.forEach(task => { if (!task.c(now)) { tasks.delete(task); task.f(); } }); if (tasks.size !== 0) raf(run_tasks); } /** * Creates a new task that runs on each raf frame * until it returns a falsy value or is aborted */ function loop(callback) { let task; if (tasks.size === 0) raf(run_tasks); return { promise: new Promise(fulfill => { tasks.add(task = { c: callback, f: fulfill }); }), abort() { tasks.delete(task); } }; } const globals = (typeof window !== 'undefined' ? window : typeof globalThis !== 'undefined' ? globalThis : global); function append(target, node) { target.appendChild(node); } function get_root_for_style(node) { if (!node) return document; const root = node.getRootNode ? node.getRootNode() : node.ownerDocument; if (root && root.host) { return root; } return node.ownerDocument; } function append_empty_stylesheet(node) { const style_element = element('style'); append_stylesheet(get_root_for_style(node), style_element); return style_element.sheet; } function append_stylesheet(node, style) { append(node.head || node, style); return style.sheet; } function insert(target, node, anchor) { target.insertBefore(node, anchor || null); } function detach(node) { if (node.parentNode) { node.parentNode.removeChild(node); } } function destroy_each(iterations, detaching) { for (let i = 0; i < iterations.length; i += 1) { if (iterations[i]) iterations[i].d(detaching); } } function element(name) { return document.createElement(name); } function svg_element(name) { return document.createElementNS('http://www.w3.org/2000/svg', name); } function text(data) { return document.createTextNode(data); } function space() { return text(' '); } function empty() { return text(''); } function listen(node, event, handler, options) { node.addEventListener(event, handler, options); return () => node.removeEventListener(event, handler, options); } function attr(node, attribute, value) { if (value == null) node.removeAttribute(attribute); else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value); } function children(element) { return Array.from(element.childNodes); } function set_data(text, data) { data = '' + data; if (text.data === data) return; text.data = data; } function set_style(node, key, value, important) { if (value == null) { node.style.removeProperty(key); } else { node.style.setProperty(key, value, important ? 'important' : ''); } } function toggle_class(element, name, toggle) { element.classList[toggle ? 'add' : 'remove'](name); } function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) { const e = document.createEvent('CustomEvent'); e.initCustomEvent(type, bubbles, cancelable, detail); return e; } class HtmlTag { constructor(is_svg = false) { this.is_svg = false; this.is_svg = is_svg; this.e = this.n = null; } c(html) { this.h(html); } m(html, target, anchor = null) { if (!this.e) { if (this.is_svg) this.e = svg_element(target.nodeName); /** #7364 target for