@ignifx/core 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/async-pipelines-CI5uT5iZ.js +26 -0
  2. package/dist/async-pipelines-CI5uT5iZ.js.map +1 -0
  3. package/dist/color-DrR6GFTd.js +351 -0
  4. package/dist/color-DrR6GFTd.js.map +1 -0
  5. package/dist/effect-task-CMbuO6Kb.js +205 -0
  6. package/dist/effect-task-CMbuO6Kb.js.map +1 -0
  7. package/dist/environment-C_JfuAjj.js +224 -0
  8. package/dist/environment-C_JfuAjj.js.map +1 -0
  9. package/dist/ignifx-error-R1ma_Lzv.js +544 -0
  10. package/dist/ignifx-error-R1ma_Lzv.js.map +1 -0
  11. package/dist/index.d.ts +3756 -1656
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +6404 -5777
  14. package/dist/index.js.map +1 -1
  15. package/dist/instanced-mesh-instance-Cgx1H87p.js +701 -0
  16. package/dist/instanced-mesh-instance-Cgx1H87p.js.map +1 -0
  17. package/dist/material-plugin-CTaWZXEk.js +485 -0
  18. package/dist/material-plugin-CTaWZXEk.js.map +1 -0
  19. package/dist/math-utils-BcDnL-gi.js +277 -0
  20. package/dist/math-utils-BcDnL-gi.js.map +1 -0
  21. package/dist/mesh-CnK_PX46.js +811 -0
  22. package/dist/mesh-CnK_PX46.js.map +1 -0
  23. package/dist/post-effect-C42XJFmo.js +155 -0
  24. package/dist/post-effect-C42XJFmo.js.map +1 -0
  25. package/dist/post-effect-compiler-DTlkT1si.js +311 -0
  26. package/dist/post-effect-compiler-DTlkT1si.js.map +1 -0
  27. package/dist/shader-declaration-5q__jycG.js +165 -0
  28. package/dist/shader-declaration-5q__jycG.js.map +1 -0
  29. package/dist/shader-material-DssOqsvZ.js +1009 -0
  30. package/dist/shader-material-DssOqsvZ.js.map +1 -0
  31. package/dist/shader-material-Xk7Oc9UG.js +207 -0
  32. package/dist/shader-material-Xk7Oc9UG.js.map +1 -0
  33. package/dist/shader-pragma-CNAK4SIb.js +685 -0
  34. package/dist/shader-pragma-CNAK4SIb.js.map +1 -0
  35. package/dist/surface-shader-C2HtysNN.js +1397 -0
  36. package/dist/surface-shader-C2HtysNN.js.map +1 -0
  37. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"material-plugin-CTaWZXEk.js","names":[],"sources":["../src/lite/material.ts","../src/render/material-plugin.ts"],"sourcesContent":["import {\n createPbrMaterial,\n createStandardMaterial,\n enableMaterialTracking,\n markMaterialUboDirty,\n rebuildMaterial,\n setPbrAlphaCutoff,\n setPbrEmissive,\n setPbrUnlit,\n setStandardBumpTexture,\n setStandardEmissiveTexture,\n setStandardOpacityTexture,\n setStandardSpecularTexture,\n} from \"@babylonjs/lite\";\nimport { assertNever } from \"../errors/ignifx-error.js\";\nimport type { Material, PbrMaterialProps, SceneContext, StandardMaterialProps, Texture2D } from \"@babylonjs/lite\";\n\n/**\n * Material half of the Babylon Lite adapter (`docs/architecture/07-rendering.md` §2.6): the three\n * material kinds a `MaterialAsset` can produce, built from plain ignifx props.\n *\n * Everything here is `@internal`, and every colour that reaches it is **linear** — the sRGB decode\n * belongs to the asset layer.\n *\n * ## What a Lite material is (verified against `@babylonjs/lite@1.27.0`)\n *\n * - A material is plain data plus one private `_buildGroup` function; `createPbrMaterial` is\n * literally `{ ...props, _buildGroup, _uboVersion: 0 }` (`lib/material/pbr/pbr-material.js`), so\n * none of these factories touches the GPU and all of them run under the null engine.\n * - **The build group is a per-family singleton.** `getPbrGroupBuilder()`, `getStandardGroupBuilder()`\n * and `getShaderGroupBuilder()` each memoise one function for the whole process\n * (`lib/material/pbr/pbr-material.js`, `lib/material/standard/create-standard-material.js`,\n * `lib/material/shader/shader-material.js` line 123), and a scene keys its renderable groups by\n * that function (`lib/scene/scene-core.js`, `addToScene`). \"Material family\" in\n * `docs/architecture/07-rendering.md` §1.1 therefore means *pbr*, *standard*, *shader* or *node* —\n * **not** an individual material. Only node materials get a per-material builder\n * (`lib/material/node/node-material.js`). This is what makes {@link warmUpMaterialFamilies} in\n * `./gpu/warm-up.ts` cheap: one hidden mesh per family covers every material in it.\n * - Scalar and vector edits only need `markMaterialUboDirty` (`index.d.ts` 6974), which bumps\n * `_uboVersion`. Anything that changes the compiled feature set — binding or clearing a texture,\n * flipping `doubleSided`, changing culling — needs {@link rebuildMaterialPipelines}.\n *\n * ## The custom WGSL family lives elsewhere\n *\n * `createShaderMaterial` and the `setShader*` setters are in `./gpu/shader-material.ts`, not here:\n * this module is statically reachable from every app through the material asset layer, and Babylon\n * Lite exports one barrel, so a static import of the shader factory would put Lite's whole\n * shader-material pipeline in every entry chunk. That module is reached through a dynamic\n * `import()` instead (`docs/plan/2026-09-terrain-particles-shaders.md` §3.1, \"Bundle cost\").\n */\n\n/**\n * The Babylon Lite material a `MaterialAsset` owns, re-exported under an ignifx name\n * (`CONSTITUTION.md` §3.4, coding standards §4).\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteMaterial = Material;\n\n/**\n * A Babylon Lite physically based material, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LitePbrMaterial = PbrMaterialProps;\n\n/**\n * A Babylon Lite Babylon-Standard material, re-exported under an ignifx name.\n *\n * @remarks\n * Unstable; excluded from the stability guarantees of `CONSTITUTION.md` Article IV.\n *\n * @public\n */\nexport type LiteStandardMaterial = StandardMaterialProps;\n\n/** glTF's default alpha cutoff, used when a `\"mask\"` material declares none. */\nconst DEFAULT_ALPHA_CUTOFF = 0.5;\n\n/**\n * How a material's alpha channel is interpreted, in glTF's vocabulary, in the order the inspector\n * lists them (`docs/architecture/07-rendering.md` §2.4).\n *\n * @public\n */\nexport const MATERIAL_ALPHA_MODES = [\"opaque\", \"mask\", \"blend\"] as const;\n\n/**\n * The union of the alpha modes a material can declare.\n *\n * @public\n */\nexport type MaterialAlphaMode = (typeof MATERIAL_ALPHA_MODES)[number];\n\n/**\n * The physically based material properties an ignifx `.material.json` declares\n * (`docs/architecture/06-serialization-and-scene-format.md` §6). Every field is optional; an\n * omitted field leaves Lite's own default in place.\n *\n * @internal\n */\nexport interface PbrMaterialInput {\n /** A human-readable name, used for glTF material overrides and diagnostics. */\n readonly name?: string;\n /** Linear base colour and alpha, multiplied with the base colour texture. */\n readonly baseColor?: readonly [number, number, number, number];\n /** The base colour texture. Load it with an sRGB format. */\n readonly baseColorTexture?: Texture2D;\n /** Metallic factor, 0 to 1. */\n readonly metallic?: number;\n /** Roughness factor, 0 to 1. */\n readonly roughness?: number;\n /** The packed occlusion/roughness/metallic texture (glTF `ORM`). */\n readonly metallicRoughnessTexture?: Texture2D;\n /** The tangent-space normal map. */\n readonly normalTexture?: Texture2D;\n /** Normal map strength. */\n readonly normalScale?: number;\n /** Linear emissive colour. */\n readonly emissive?: readonly [number, number, number];\n /** The emissive texture. */\n readonly emissiveTexture?: Texture2D;\n /** A separate occlusion texture, sampled on UV1 when the ORM texture is not used for it. */\n readonly occlusionTexture?: Texture2D;\n /** How strongly ambient occlusion darkens the surface, 0 to 1. */\n readonly occlusionStrength?: number;\n /** How the alpha channel is interpreted. */\n readonly alphaMode?: MaterialAlphaMode;\n /** The cutoff below which a `\"mask\"` material discards a fragment. */\n readonly alphaCutoff?: number;\n /** Overall material alpha, 0 to 1. */\n readonly alpha?: number;\n /** Whether back faces are drawn. */\n readonly doubleSided?: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit?: boolean;\n /** How strongly the environment map contributes. */\n readonly environmentIntensity?: number;\n}\n\n/**\n * The Babylon-Standard material properties an ignifx `.material.json` declares, for the cheap\n * non-PBR path (`docs/architecture/07-rendering.md` §2.6).\n *\n * @internal\n */\nexport interface StandardMaterialInput {\n /** A human-readable name. */\n readonly name?: string;\n /** Linear diffuse colour. */\n readonly diffuse?: readonly [number, number, number];\n /** The diffuse texture. */\n readonly diffuseTexture?: Texture2D;\n /** Linear specular colour. */\n readonly specular?: readonly [number, number, number];\n /** Specular exponent; higher values give a tighter highlight. */\n readonly specularPower?: number;\n /** The specular texture. */\n readonly specularTexture?: Texture2D;\n /** Linear emissive colour. */\n readonly emissive?: readonly [number, number, number];\n /** The emissive texture. */\n readonly emissiveTexture?: Texture2D;\n /** The tangent-space normal map. */\n readonly normalTexture?: Texture2D;\n /** The opacity texture. */\n readonly opacityTexture?: Texture2D;\n /** Overall material alpha, 0 to 1. */\n readonly alpha?: number;\n /** The cutoff below which a fragment is discarded. `0` disables the alpha test. */\n readonly alphaCutoff?: number;\n /** Whether back faces are drawn. */\n readonly doubleSided?: boolean;\n /** Whether lighting is skipped entirely. */\n readonly unlit?: boolean;\n}\n\n/**\n * Builds a Lite PBR material from ignifx props.\n *\n * @param input - The declared properties.\n * @returns The material. It holds no GPU resource of its own; the textures it references do.\n *\n * @example\n * ```ts\n * const gold = createPbrMaterialFromProps({ baseColor: [1, 0.77, 0.34, 1], metallic: 1, roughness: 0.25 });\n * ```\n *\n * @internal\n */\nexport function createPbrMaterialFromProps(input: PbrMaterialInput): PbrMaterialProps {\n const props: Partial<PbrMaterialProps> = {};\n if (input.name !== undefined) {\n props.name = input.name;\n }\n if (input.baseColor !== undefined) {\n props.baseColorFactor = [input.baseColor[0], input.baseColor[1], input.baseColor[2], input.baseColor[3]];\n }\n if (input.baseColorTexture !== undefined) {\n props.baseColorTexture = input.baseColorTexture;\n }\n if (input.metallic !== undefined) {\n props.metallicFactor = input.metallic;\n }\n if (input.roughness !== undefined) {\n props.roughnessFactor = input.roughness;\n }\n if (input.metallicRoughnessTexture !== undefined) {\n props.ormTexture = input.metallicRoughnessTexture;\n }\n if (input.normalTexture !== undefined) {\n props.normalTexture = input.normalTexture;\n }\n if (input.normalScale !== undefined) {\n props.normalTextureScale = input.normalScale;\n }\n if (input.emissiveTexture !== undefined) {\n props.emissiveTexture = input.emissiveTexture;\n }\n if (input.occlusionTexture !== undefined) {\n props.occlusionTexture = input.occlusionTexture;\n }\n if (input.occlusionStrength !== undefined) {\n props.occlusionStrength = input.occlusionStrength;\n }\n if (input.alpha !== undefined) {\n props.alpha = input.alpha;\n }\n if (input.doubleSided !== undefined) {\n props.doubleSided = input.doubleSided;\n }\n if (input.environmentIntensity !== undefined) {\n props.environmentIntensity = input.environmentIntensity;\n }\n if (input.alphaMode === \"blend\") {\n props.alphaBlend = true;\n }\n const material = createPbrMaterial(props);\n if (input.alphaMode === \"mask\") {\n setPbrAlphaCutoff(material, input.alphaCutoff ?? DEFAULT_ALPHA_CUTOFF);\n }\n if (input.emissive !== undefined) {\n setPbrEmissive(material, [input.emissive[0], input.emissive[1], input.emissive[2]]);\n }\n if (input.unlit === true) {\n setPbrUnlit(material);\n }\n return material;\n}\n\n/**\n * Builds a Lite Standard material from ignifx props.\n *\n * @param input - The declared properties.\n * @returns The material.\n *\n * @internal\n */\nexport function createStandardMaterialFromProps(input: StandardMaterialInput): StandardMaterialProps {\n const material = createStandardMaterial();\n if (input.name !== undefined) {\n material.name = input.name;\n }\n if (input.diffuse !== undefined) {\n writeTriple(material.diffuseColor, input.diffuse);\n }\n if (input.specular !== undefined) {\n writeTriple(material.specularColor, input.specular);\n }\n if (input.emissive !== undefined) {\n writeTriple(material.emissiveColor, input.emissive);\n }\n if (input.specularPower !== undefined) {\n material.specularPower = input.specularPower;\n }\n if (input.alpha !== undefined) {\n material.alpha = input.alpha;\n }\n if (input.alphaCutoff !== undefined) {\n material.alphaCutOff = input.alphaCutoff;\n }\n if (input.doubleSided !== undefined) {\n material.backFaceCulling = !input.doubleSided;\n }\n if (input.unlit !== undefined) {\n material.disableLighting = input.unlit;\n }\n if (input.diffuseTexture !== undefined) {\n material.diffuseTexture = input.diffuseTexture;\n }\n if (input.specularTexture !== undefined) {\n setStandardSpecularTexture(material, input.specularTexture);\n }\n if (input.emissiveTexture !== undefined) {\n setStandardEmissiveTexture(material, input.emissiveTexture);\n }\n if (input.normalTexture !== undefined) {\n setStandardBumpTexture(material, input.normalTexture);\n }\n if (input.opacityTexture !== undefined) {\n setStandardOpacityTexture(material, input.opacityTexture);\n }\n return material;\n}\n\n/**\n * The material a `MeshRenderer` uses when it declares none: a neutral, fully rough dielectric.\n *\n * @returns A fresh material. Callers share one instance per app rather than one per renderer.\n *\n * @internal\n */\nexport function createDefaultMaterial(): PbrMaterialProps {\n return createPbrMaterialFromProps({\n name: \"ignifx:default\",\n baseColor: [1, 1, 1, 1],\n metallic: 0,\n roughness: 0.9,\n });\n}\n\n/**\n * Replaces a PBR material's linear base colour.\n *\n * @param material - The material to change.\n * @param r - The linear red component.\n * @param g - The linear green component.\n * @param b - The linear blue component.\n * @param a - The alpha component.\n *\n * @internal\n */\nexport function setPbrBaseColor(material: PbrMaterialProps, r: number, g: number, b: number, a: number): void {\n const factor = material.baseColorFactor;\n if (factor === undefined) {\n material.baseColorFactor = [r, g, b, a];\n } else {\n factor[0] = r;\n factor[1] = g;\n factor[2] = b;\n factor[3] = a;\n }\n markMaterialDirty(material);\n}\n\n/**\n * Replaces a PBR material's metallic and roughness factors.\n *\n * @param material - The material to change.\n * @param metallic - The metallic factor, 0 to 1.\n * @param roughness - The roughness factor, 0 to 1.\n *\n * @internal\n */\nexport function setPbrMetallicRoughness(material: PbrMaterialProps, metallic: number, roughness: number): void {\n material.metallicFactor = metallic;\n material.roughnessFactor = roughness;\n markMaterialDirty(material);\n}\n\n/**\n * Replaces a material's overall alpha.\n *\n * @param material - The PBR or Standard material to change.\n * @param alpha - The new alpha, 0 to 1.\n *\n * @internal\n */\nexport function setMaterialAlpha(material: PbrMaterialProps | StandardMaterialProps, alpha: number): void {\n material.alpha = alpha;\n markMaterialDirty(material);\n}\n\n/**\n * Marks a material's uniform block for re-upload on the next frame.\n *\n * @remarks\n * This is the cheap path and covers every scalar, vector, and colour edit. It does **not** cover\n * changes that alter the compiled feature set; those go through {@link rebuildMaterialPipelines}.\n *\n * @param material - The material that changed.\n *\n * @internal\n */\nexport function markMaterialDirty(material: Material): void {\n markMaterialUboDirty(material);\n}\n\n/**\n * Rebuilds the renderables of a material whose compiled feature set changed.\n *\n * @remarks\n * Needed after binding or clearing a texture, changing culling, or toggling a sub-feature\n * (`index.d.ts` 9413). `rebuildFrameGraph` is left off so a component can batch several material\n * edits and rebuild the frame graph once.\n *\n * @param scene - The scene the material renders in.\n * @param material - The material that changed.\n *\n * @internal\n */\nexport function rebuildMaterialPipelines(scene: SceneContext, material: Material): void {\n rebuildMaterial(scene, material);\n}\n\n/**\n * Installs automatic dirty tracking on a material, so property writes mark its uniform block\n * without an explicit {@link markMaterialDirty}.\n *\n * @remarks\n * Lite installs the tracker by rewriting the material's property descriptors, and the module that\n * does it is loaded lazily, so this is asynchronous (`index.d.ts` 4480,\n * `lib/material/observable-material.js`). Opt-in only: it costs an accessor call per write, which\n * the zero-allocation rules (coding standards §7) do not want on every material.\n *\n * @param material - The PBR or Standard material to track.\n * @returns A promise that resolves once the tracker is installed.\n *\n * @internal\n */\nexport function enableMaterialChangeTracking(material: PbrMaterialProps | StandardMaterialProps): Promise<void> {\n return enableMaterialTracking(material);\n}\n\n/**\n * Reports whether Lite will alpha-blend a material declared with this alpha mode.\n *\n * @param mode - The declared alpha mode.\n * @returns `true` for `\"blend\"`, `false` for `\"opaque\"` and `\"mask\"`.\n *\n * @internal\n */\nexport function isBlendedAlphaMode(mode: MaterialAlphaMode): boolean {\n switch (mode) {\n case \"opaque\":\n case \"mask\":\n return false;\n case \"blend\":\n return true;\n default:\n return assertNever(mode, \"material alpha mode\");\n }\n}\n\n/**\n * Writes three components into a Lite colour tuple in place.\n *\n * @param target - The tuple Lite owns.\n * @param source - The values to copy.\n */\nfunction writeTriple(target: [number, number, number], source: readonly [number, number, number]): void {\n target[0] = source[0];\n target[1] = source[1];\n target[2] = source[2];\n}\n","import { CoreErrorCode } from \"../errors/error-codes.js\";\nimport { assertNever, IgnifxError } from \"../errors/ignifx-error.js\";\nimport { SHADER_UNIFORM_TYPES } from \"./shader-declaration.js\";\nimport type { ShaderTextureDeclaration, ShaderUniformDeclaration, ShaderUniformType } from \"./shader-declaration.js\";\n\n/**\n * The raw Babylon Lite material-plugin points, as a `@beta` escape hatch\n * (`docs/plan/2026-09-terrain-particles-shaders.md` §3.2, ADR-0024).\n *\n * `@beta` because the meaning of each point is whatever the surrounding Lite template declares at\n * that line; ignifx's stable contract is the three hooks of `./surface-shader.ts`. Four rules read\n * out of `@babylonjs/lite@1.27.0`'s `lib/` on 2026-09-08:\n *\n * - Plugin uniforms and samplers are **fragment-stage only** on both families\n * (`lib/material/plugin/plugin-bridge-shared.js` 99), and there is no vertex helper-function\n * channel, so vertex code may read only attributes, `mesh.world` and the scene block, and must be\n * statements rather than functions.\n * - `CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION` is injected **twice** — Lite maps it to the two\n * adjacent PBR slots `AI` and `NI` — so its code must be idempotent or guard itself with a flag\n * set at an earlier point, and must declare nothing at statement level.\n * - Only PBR carries `CUSTOM_FRAGMENT_UPDATE_DIFFUSE` after `CUSTOM_FRAGMENT_UPDATE_ALPHA`;\n * Standard's template orders them the other way and has no `AI`/`NI`/`MF` slots.\n * - `roughness` and `metallic` are `let` in the PBR template and cannot be written.\n */\n\n/**\n * The Babylon Lite injection points a {@link MaterialPluginDefinition} may fill in.\n *\n * @remarks\n * The names are Lite's own (`MaterialPluginPoint`, `index.d.ts` 7084) and are taught verbatim,\n * because a plugin's code is written against the template around the point.\n *\n * @beta\n */\nexport const LITE_MATERIAL_PLUGIN_POINTS = [\n \"CUSTOM_FRAGMENT_DEFINITIONS\",\n \"CUSTOM_FRAGMENT_MAIN_BEGIN\",\n \"CUSTOM_FRAGMENT_UPDATE_ALPHA\",\n \"CUSTOM_FRAGMENT_UPDATE_DIFFUSE\",\n \"CUSTOM_FRAGMENT_BEFORE_LIGHTS\",\n \"CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\",\n \"CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\",\n \"CUSTOM_VERTEX_MAIN_BEGIN\",\n \"CUSTOM_VERTEX_UPDATE_WORLDPOS\",\n \"CUSTOM_VERTEX_MAIN_END\",\n] as const;\n\n/**\n * One of Babylon Lite's ten material-plugin injection points.\n *\n * @beta\n */\nexport type LiteMaterialPluginPoint = (typeof LITE_MATERIAL_PLUGIN_POINTS)[number];\n\n/**\n * The default priority Babylon Lite gives a plugin with none (`index.d.ts` 7057).\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_DEFAULT_PRIORITY = 500;\n\n/**\n * How many `texture`/`sampler` pairs one material's plugins may declare together.\n *\n * @remarks\n * Measured on a device on 2026-09-08 (spike S0.2): a fully textured PBR material — base colour,\n * normal, ORM, emissive — with image-based lighting and one PCF shadow light already binds seven\n * textures and seven samplers of the sixteen per stage that every WebGPU implementation guarantees,\n * SwiftShader included, and Lite requests no higher `requiredLimits`. Nine is what is left, and it\n * drops to eight with a second shadow light and seven with a lightmap, so a material that means to\n * be portable should stay well under the cap.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_SAMPLER_BUDGET = 9;\n\n/**\n * The WGSL names the PBR and Standard templates already own, which a plugin may not reuse for a\n * uniform field or a sampler.\n *\n * @remarks\n * A plugin's fields land in the host's own uniform block and its samplers in the host's own bind\n * group, so a collision is a duplicate WGSL declaration and the whole material stops compiling with\n * a message that names neither the plugin nor the field. Refusing at attach time is the difference\n * between a sentence and a shader dump. Read from `pbr-template.js` `_baseMaterialUboFields` and\n * `_baseBindings`, and `standard-template.js` `materialStruct` and `_baseBindings`.\n *\n * @beta\n */\nexport const MATERIAL_PLUGIN_RESERVED_NAMES: readonly string[] = Object.freeze([\n // Blocks and entry points the templates declare.\n \"material\",\n \"mesh\",\n \"scene\",\n \"lights\",\n \"pluginUbo\",\n \"shadowParams\",\n \"main\",\n // PBR material uniform fields.\n \"environmentIntensity\",\n \"directIntensity\",\n \"reflectance\",\n \"materialAlpha\",\n \"baseColorFactor\",\n \"metallicFactor\",\n \"roughnessFactor\",\n \"normalScale\",\n \"lightFalloffMode\",\n \"anisotropyParams\",\n // PBR samplers.\n \"baseColorTexture\",\n \"baseColorSampler\",\n \"normalTexture\",\n \"normalSampler_\",\n \"ormTexture\",\n \"ormSampler\",\n \"emissiveTexture\",\n \"emissiveSampler\",\n \"specGlossTexture\",\n \"specGlossSampler\",\n // Standard samplers (`standard-template.js` uses two-letter names).\n \"dT\",\n \"dS\",\n \"mat\",\n \"up\",\n]);\n\n/**\n * What a raw material plugin declares: a name, the values and textures it wants beside the host\n * material's own, and the WGSL it injects.\n *\n * @beta\n */\nexport interface MaterialPluginDefinition {\n /** The plugin's identity. It is part of Lite's pipeline cache key, so it must be stable. */\n readonly name: string;\n /** Lower runs first; Lite's own default is {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority: number;\n /** The uniform fields appended to the host material's uniform block. Fragment stage only. */\n readonly uniforms: readonly ShaderUniformDeclaration[];\n /** The `texture`/`sampler` pairs added to the host material's bind group. Fragment stage only. */\n readonly textures: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. Vertex points take statements; there are no vertex helpers. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/**\n * The properties {@link defineMaterialPlugin} accepts; everything but `name` and `code` has a\n * default.\n *\n * @beta\n */\nexport interface MaterialPluginDefinitionInit {\n /** The plugin's identity. */\n readonly name: string;\n /** Lower runs first. Defaults to {@link MATERIAL_PLUGIN_DEFAULT_PRIORITY}. */\n readonly priority?: number;\n /** The uniform fields. Defaults to none. */\n readonly uniforms?: readonly ShaderUniformDeclaration[];\n /** The samplers. Defaults to none. */\n readonly textures?: readonly ShaderTextureDeclaration[];\n /** The WGSL to inject, by point. */\n readonly code: Readonly<Partial<Record<LiteMaterialPluginPoint, string>>>;\n}\n\n/** Matches a WGSL identifier. */\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Matches a legal plugin name: an identifier, optionally with `.`, `:`, or `-` inside it. */\nconst PLUGIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*(?:[.:-][A-Za-z0-9_]+)*$/;\n\n/**\n * Validates a raw material-plugin declaration and fills in its defaults.\n *\n * @remarks\n * Nothing here reaches a device: the result is plain data that `attachSurfaceShaders` and\n * `attachMaterialPlugin` turn into a Lite plugin. The checks are the ones whose failure would\n * otherwise surface as a WGSL compile error with no mention of the plugin — an empty `code`, a\n * duplicate or reserved binding name, a name that is not a WGSL identifier, an unknown injection\n * point, or more samplers than {@link MATERIAL_PLUGIN_SAMPLER_BUDGET}.\n *\n * The **surface-shader compiler produces one of these**, so a bug in this validation is a bug in\n * every surface shader too, which is why it lives here rather than inside the compiler.\n *\n * @param definition - The declaration.\n * @returns The same declaration with `priority`, `uniforms`, and `textures` filled in.\n * @throws IgnifxError with code `IGX-0723` when `code` fills in no point, `IGX-0712` when a name is\n * not a legal, unique, unreserved WGSL identifier or a point name is unknown, or `IGX-0726` when the\n * plugin alone exceeds the sampler budget.\n *\n * @example\n * ```ts\n * const tint = defineMaterialPlugin({\n * name: \"tint\",\n * code: { CUSTOM_FRAGMENT_UPDATE_ALPHA: \"baseColor = baseColor * vec3<f32>(1.0, 0.5, 0.5);\" },\n * });\n * ```\n *\n * @beta\n */\nexport function defineMaterialPlugin(definition: MaterialPluginDefinitionInit): MaterialPluginDefinition {\n const name = definition.name;\n if (!PLUGIN_NAME.test(name)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${JSON.stringify(name)} is not a legal material-plugin name.`,\n {\n context: { plugin: name, name },\n hint: \"Start with a letter or underscore; letters, digits, underscores, and inner . : - follow.\",\n },\n );\n }\n const points = Object.keys(definition.code);\n let filled = 0;\n for (const point of points) {\n if (!isLiteMaterialPluginPoint(point)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${name} declares no Lite point named ${point}.`, {\n context: { plugin: name, name: point, point },\n hint: `The ten points are ${LITE_MATERIAL_PLUGIN_POINTS.join(\", \")}.`,\n });\n }\n if ((definition.code[point] ?? \"\").trim().length > 0) {\n filled += 1;\n }\n }\n if (filled === 0) {\n throw new IgnifxError(CoreErrorCode.surfaceHookMissing, `${name} injects no WGSL at any Lite point.`, {\n context: { plugin: name, name },\n hint: \"Fill in at least one of the ten points, or do not attach the plugin.\",\n });\n }\n const uniforms = definition.uniforms ?? [];\n const textures = definition.textures ?? [];\n const seen = new Set<string>();\n for (const uniform of uniforms) {\n assertBindingName(name, uniform.name, seen);\n assertUniformType(name, uniform.name, uniform.type);\n }\n for (const texture of textures) {\n assertBindingName(name, texture.name, seen);\n assertBindingName(name, `${texture.name}Sampler`, seen);\n }\n if (textures.length > MATERIAL_PLUGIN_SAMPLER_BUDGET) {\n throw new IgnifxError(\n CoreErrorCode.surfaceSamplerBudgetExceeded,\n `${name} declares ${String(textures.length)} samplers; a material's plugins may declare ${String(MATERIAL_PLUGIN_SAMPLER_BUDGET)} together.`,\n {\n context: { plugin: name, samplers: textures.length, budget: MATERIAL_PLUGIN_SAMPLER_BUDGET },\n hint: \"Pack the maps into fewer textures — an RGBA control map rather than four masks.\",\n },\n );\n }\n return {\n name,\n priority: definition.priority ?? MATERIAL_PLUGIN_DEFAULT_PRIORITY,\n uniforms,\n textures,\n code: definition.code,\n };\n}\n\n/**\n * Whether a string is one of Lite's ten injection points.\n *\n * @param value - The candidate.\n * @returns `true` when Lite accepts it.\n *\n * @beta\n */\nexport function isLiteMaterialPluginPoint(value: string): value is LiteMaterialPluginPoint {\n for (const point of LITE_MATERIAL_PLUGIN_POINTS) {\n if (point === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * How many floats one uniform of a declared type occupies on the CPU side.\n *\n * @param type - The declared WGSL type.\n * @returns The component count: 1, 2, 3, 4, or 16.\n *\n * @internal\n */\nexport function uniformComponentCount(type: ShaderUniformType): number {\n switch (type) {\n case \"vec2<f32>\": {\n return 2;\n }\n case \"vec3<f32>\": {\n return 3;\n }\n case \"vec4<f32>\": {\n return 4;\n }\n case \"mat4x4<f32>\": {\n return 16;\n }\n case \"f32\":\n case \"u32\":\n case \"i32\": {\n return 1;\n }\n default: {\n return assertNever(type, \"shader uniform type\");\n }\n }\n}\n\n/**\n * Refuses a binding name that is not a unique, unreserved WGSL identifier.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The candidate name.\n * @param seen - The names already taken by this plugin; the accepted name is added.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertBindingName(plugin: string, binding: string, seen: Set<string>): void {\n if (!IDENTIFIER.test(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${JSON.stringify(binding)}, which is not a WGSL identifier.`,\n { context: { plugin, name: binding }, hint: \"Use letters, digits, and underscores, starting with a letter.\" },\n );\n }\n if (MATERIAL_PLUGIN_RESERVED_NAMES.includes(binding)) {\n throw new IgnifxError(\n CoreErrorCode.unknownShaderBinding,\n `${plugin} declares ${binding}, which Babylon Lite's own PBR or Standard shader already owns.`,\n { context: { plugin, name: binding }, hint: \"Rename it; a plugin shares the host material's WGSL namespace.\" },\n );\n }\n if (seen.has(binding)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin} declares ${binding} twice.`, {\n context: { plugin, name: binding },\n hint: \"Every uniform and texture of one plugin needs its own name.\",\n });\n }\n seen.add(binding);\n}\n\n/**\n * Refuses a uniform type Lite's plugin bridge cannot carry.\n *\n * @param plugin - The plugin's name, for the message.\n * @param binding - The uniform's name.\n * @param type - The declared type.\n * @throws IgnifxError with code `IGX-0712`.\n */\nfunction assertUniformType(plugin: string, binding: string, type: ShaderUniformType): void {\n if (!SHADER_UNIFORM_TYPES.includes(type)) {\n throw new IgnifxError(CoreErrorCode.unknownShaderBinding, `${plugin}.${binding} declares the type ${type}.`, {\n context: { plugin, name: binding, type },\n hint: `The plugin uniform types are ${SHADER_UNIFORM_TYPES.join(\", \")}.`,\n });\n }\n}\n"],"mappings":";;;;;AAmFA,MAA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Y,cAAc,sBAAsB,GAAG,OAAO,GAAG,QAAQ,qBAAqB,KAAK,IAAI;EAC3G,SAAS;GAAE;GAAQ,MAAM;GAAS;EAAK;EACvC,MAAM,gCAAgC,qBAAqB,KAAK,IAAI,EAAE;CACxE,CAAC;AAEL"}
@@ -0,0 +1,277 @@
1
+ //#region src/math/math-utils.ts
2
+ /**
3
+ * Scalar helpers shared by the vector, quaternion and matrix types and by game code.
4
+ *
5
+ * Angles are **degrees** in every public API unless the name ends in `Rad`/`Radians`
6
+ * (coding standards §5.1, ADR-0011). Every function here is a pure scalar function: none of them
7
+ * allocate, so they are safe in per-frame code (coding standards §7).
8
+ */
9
+ /**
10
+ * The default tolerance for approximate float comparisons. Chosen for single-precision positions in
11
+ * metres: `Float32Array` round-tripping loses roughly 1e-7 of relative precision, so 1e-6 is the
12
+ * smallest value that does not report false differences on data that has been through the GPU.
13
+ *
14
+ * @public
15
+ */
16
+ const EPSILON = 1e-6;
17
+ /**
18
+ * Multiplier that converts degrees to radians.
19
+ *
20
+ * @public
21
+ */
22
+ const DEG_TO_RAD = Math.PI / 180;
23
+ /**
24
+ * Multiplier that converts radians to degrees.
25
+ *
26
+ * @public
27
+ */
28
+ const RAD_TO_DEG = 180 / Math.PI;
29
+ /**
30
+ * Converts an angle from degrees to radians.
31
+ *
32
+ * @param degrees - The angle in degrees.
33
+ * @returns The same angle in radians.
34
+ *
35
+ * @public
36
+ */
37
+ function degToRad(degrees) {
38
+ return degrees * DEG_TO_RAD;
39
+ }
40
+ /**
41
+ * Converts an angle from radians to degrees.
42
+ *
43
+ * @param radians - The angle in radians.
44
+ * @returns The same angle in degrees.
45
+ *
46
+ * @public
47
+ */
48
+ function radToDeg(radians) {
49
+ return radians * RAD_TO_DEG;
50
+ }
51
+ /**
52
+ * Constrains a value to an inclusive range.
53
+ *
54
+ * @param value - The value to constrain.
55
+ * @param min - The lower bound.
56
+ * @param max - The upper bound.
57
+ * @returns `min` when `value` is smaller, `max` when it is larger, otherwise `value` unchanged.
58
+ * `NaN` propagates.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * clamp(12, 0, 10); // 10
63
+ * ```
64
+ *
65
+ * @public
66
+ */
67
+ function clamp(value, min, max) {
68
+ if (value < min) return min;
69
+ if (value > max) return max;
70
+ return value;
71
+ }
72
+ /**
73
+ * Constrains a value to the 0–1 range.
74
+ *
75
+ * @param value - The value to constrain.
76
+ * @returns The value clamped into `[0, 1]`.
77
+ *
78
+ * @public
79
+ */
80
+ function clamp01(value) {
81
+ return clamp(value, 0, 1);
82
+ }
83
+ /**
84
+ * Linearly interpolates between two values. The interpolant is **not** clamped, so values outside
85
+ * `[0, 1]` extrapolate; wrap `t` in {@link clamp01} when that is not wanted.
86
+ *
87
+ * @param a - The value returned at `t === 0`.
88
+ * @param b - The value returned at `t === 1`.
89
+ * @param t - The interpolant.
90
+ * @returns The interpolated value.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * lerp(0, 10, 0.25); // 2.5
95
+ * ```
96
+ *
97
+ * @public
98
+ */
99
+ function lerp(a, b, t) {
100
+ return a + (b - a) * t;
101
+ }
102
+ /**
103
+ * The inverse of {@link lerp}: finds the interpolant that maps `a`–`b` onto `value`.
104
+ *
105
+ * @param a - The value that maps to 0.
106
+ * @param b - The value that maps to 1.
107
+ * @param value - The value to locate.
108
+ * @returns The interpolant, clamped into `[0, 1]`. Returns 0 when `a` and `b` are equal.
109
+ *
110
+ * @public
111
+ */
112
+ function inverseLerp(a, b, value) {
113
+ if (a === b) return 0;
114
+ return clamp01((value - a) / (b - a));
115
+ }
116
+ /**
117
+ * Smoothly interpolates between two edges with a Hermite curve (the GLSL `smoothstep`), easing in
118
+ * and out instead of the straight ramp of {@link lerp}.
119
+ *
120
+ * @param edge0 - The value below which the result is 0.
121
+ * @param edge1 - The value above which the result is 1.
122
+ * @param x - The value to map.
123
+ * @returns A value in `[0, 1]`. Degenerate edges (`edge0 === edge1`) step from 0 to 1 at the edge.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * smoothStep(0, 1, 0.5); // 0.5, but with zero slope at 0 and 1
128
+ * ```
129
+ *
130
+ * @public
131
+ */
132
+ function smoothStep(edge0, edge1, x) {
133
+ if (edge0 === edge1) return x < edge0 ? 0 : 1;
134
+ const t = clamp01((x - edge0) / (edge1 - edge0));
135
+ return t * t * (3 - 2 * t);
136
+ }
137
+ /**
138
+ * Moves a value towards a target without overshooting it.
139
+ *
140
+ * @param current - The value to move.
141
+ * @param target - The value to move towards.
142
+ * @param maxDelta - The largest step allowed this call; negative values move away from the target.
143
+ * @returns The stepped value, exactly `target` once the remaining distance fits in `maxDelta`.
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * // frame-rate independent approach at 2 units per second
148
+ * health = moveTowards(health, 100, 2 * time.deltaTime);
149
+ * ```
150
+ *
151
+ * @public
152
+ */
153
+ function moveTowards(current, target, maxDelta) {
154
+ const delta = target - current;
155
+ if (Math.abs(delta) <= maxDelta) return target;
156
+ return current + (delta < 0 ? -maxDelta : maxDelta);
157
+ }
158
+ /**
159
+ * Wraps a value into `[0, length)`, the way a looping animation time behaves. Unlike `%` the result
160
+ * is never negative.
161
+ *
162
+ * @param t - The value to wrap.
163
+ * @param length - The positive period to wrap into.
164
+ * @returns The wrapped value, clamped into `[0, length]` so float error cannot escape the range.
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * repeat(-1, 4); // 3
169
+ * ```
170
+ *
171
+ * @public
172
+ */
173
+ function repeat(t, length) {
174
+ return clamp(t - Math.floor(t / length) * length, 0, length);
175
+ }
176
+ /**
177
+ * Bounces a value back and forth between 0 and `length`, the way a ping-pong animation behaves.
178
+ *
179
+ * @param t - The value to fold.
180
+ * @param length - The positive half-period to fold into.
181
+ * @returns A value in `[0, length]` that rises then falls as `t` increases.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * pingPong(5, 4); // 3
186
+ * ```
187
+ *
188
+ * @public
189
+ */
190
+ function pingPong(t, length) {
191
+ return length - Math.abs(repeat(t, length * 2) - length);
192
+ }
193
+ /**
194
+ * Compares two numbers with an absolute tolerance. Use this instead of `===` on anything that has
195
+ * been through a matrix, a quaternion or a `Float32Array`.
196
+ *
197
+ * @param a - The first value.
198
+ * @param b - The second value.
199
+ * @param epsilon - The largest difference still considered equal. Defaults to {@link EPSILON}.
200
+ * @returns `true` when the values differ by no more than `epsilon`. `NaN` is never approximately
201
+ * equal to anything, including itself.
202
+ *
203
+ * @public
204
+ */
205
+ function approximately(a, b, epsilon = EPSILON) {
206
+ return Math.abs(a - b) <= epsilon;
207
+ }
208
+ /**
209
+ * The sign of a value, with zero treated as positive (matching Unity's `Mathf.Sign`, and unlike
210
+ * `Math.sign`, which returns 0 and `-0`).
211
+ *
212
+ * @param value - The value to inspect.
213
+ * @returns `-1` for negative values, `1` for positive values and for both `0` and `-0`, and `NaN`
214
+ * for `NaN`.
215
+ *
216
+ * @public
217
+ */
218
+ function sign(value) {
219
+ if (Number.isNaN(value)) return NaN;
220
+ return value < 0 ? -1 : 1;
221
+ }
222
+ /**
223
+ * Wraps an angle in degrees into `[-180, 180)`, the range rotations are most readable in.
224
+ *
225
+ * @param degrees - The angle to wrap.
226
+ * @returns The equivalent angle in `[-180, 180)`; exactly `180` wraps to `-180`.
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * wrapAngleDegrees(370); // 10
231
+ * wrapAngleDegrees(-190); // 170
232
+ * ```
233
+ *
234
+ * @public
235
+ */
236
+ function wrapAngleDegrees(degrees) {
237
+ return repeat(degrees + 180, 360) - 180;
238
+ }
239
+ /**
240
+ * The shortest signed rotation from one angle to another, in degrees.
241
+ *
242
+ * @param fromDegrees - The starting angle.
243
+ * @param toDegrees - The target angle.
244
+ * @returns The signed difference in `[-180, 180)`.
245
+ *
246
+ * @example
247
+ * ```ts
248
+ * deltaAngleDegrees(350, 10); // 20, not -340
249
+ * ```
250
+ *
251
+ * @public
252
+ */
253
+ function deltaAngleDegrees(fromDegrees, toDegrees) {
254
+ return wrapAngleDegrees(toDegrees - fromDegrees);
255
+ }
256
+ /**
257
+ * Interpolates between two angles in degrees the short way around the circle.
258
+ *
259
+ * @param fromDegrees - The angle returned at `t === 0`.
260
+ * @param toDegrees - The angle approached at `t === 1`.
261
+ * @param t - The interpolant; not clamped, matching {@link lerp}.
262
+ * @returns The interpolated angle. It is not wrapped, so feeding the result back in is stable.
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * lerpAngleDegrees(350, 10, 0.5); // 360
267
+ * ```
268
+ *
269
+ * @public
270
+ */
271
+ function lerpAngleDegrees(fromDegrees, toDegrees, t) {
272
+ return fromDegrees + deltaAngleDegrees(fromDegrees, toDegrees) * t;
273
+ }
274
+ //#endregion
275
+ export { smoothStep as _, clamp as a, deltaAngleDegrees as c, lerpAngleDegrees as d, moveTowards as f, sign as g, repeat as h, approximately as i, inverseLerp as l, radToDeg as m, EPSILON as n, clamp01 as o, pingPong as p, RAD_TO_DEG as r, degToRad as s, DEG_TO_RAD as t, lerp as u, wrapAngleDegrees as v };
276
+
277
+ //# sourceMappingURL=math-utils-BcDnL-gi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"math-utils-BcDnL-gi.js","names":[],"sources":["../src/math/math-utils.ts"],"sourcesContent":["/**\n * Scalar helpers shared by the vector, quaternion and matrix types and by game code.\n *\n * Angles are **degrees** in every public API unless the name ends in `Rad`/`Radians`\n * (coding standards §5.1, ADR-0011). Every function here is a pure scalar function: none of them\n * allocate, so they are safe in per-frame code (coding standards §7).\n */\n\n/**\n * The default tolerance for approximate float comparisons. Chosen for single-precision positions in\n * metres: `Float32Array` round-tripping loses roughly 1e-7 of relative precision, so 1e-6 is the\n * smallest value that does not report false differences on data that has been through the GPU.\n *\n * @public\n */\nexport const EPSILON: number = 1e-6;\n\n/**\n * Multiplier that converts degrees to radians.\n *\n * @public\n */\nexport const DEG_TO_RAD: number = Math.PI / 180;\n\n/**\n * Multiplier that converts radians to degrees.\n *\n * @public\n */\nexport const RAD_TO_DEG: number = 180 / Math.PI;\n\n/**\n * Converts an angle from degrees to radians.\n *\n * @param degrees - The angle in degrees.\n * @returns The same angle in radians.\n *\n * @public\n */\nexport function degToRad(degrees: number): number {\n return degrees * DEG_TO_RAD;\n}\n\n/**\n * Converts an angle from radians to degrees.\n *\n * @param radians - The angle in radians.\n * @returns The same angle in degrees.\n *\n * @public\n */\nexport function radToDeg(radians: number): number {\n return radians * RAD_TO_DEG;\n}\n\n/**\n * Constrains a value to an inclusive range.\n *\n * @param value - The value to constrain.\n * @param min - The lower bound.\n * @param max - The upper bound.\n * @returns `min` when `value` is smaller, `max` when it is larger, otherwise `value` unchanged.\n * `NaN` propagates.\n *\n * @example\n * ```ts\n * clamp(12, 0, 10); // 10\n * ```\n *\n * @public\n */\nexport function clamp(value: number, min: number, max: number): number {\n if (value < min) {\n return min;\n }\n if (value > max) {\n return max;\n }\n return value;\n}\n\n/**\n * Constrains a value to the 0–1 range.\n *\n * @param value - The value to constrain.\n * @returns The value clamped into `[0, 1]`.\n *\n * @public\n */\nexport function clamp01(value: number): number {\n return clamp(value, 0, 1);\n}\n\n/**\n * Linearly interpolates between two values. The interpolant is **not** clamped, so values outside\n * `[0, 1]` extrapolate; wrap `t` in {@link clamp01} when that is not wanted.\n *\n * @param a - The value returned at `t === 0`.\n * @param b - The value returned at `t === 1`.\n * @param t - The interpolant.\n * @returns The interpolated value.\n *\n * @example\n * ```ts\n * lerp(0, 10, 0.25); // 2.5\n * ```\n *\n * @public\n */\nexport function lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\n/**\n * The inverse of {@link lerp}: finds the interpolant that maps `a`–`b` onto `value`.\n *\n * @param a - The value that maps to 0.\n * @param b - The value that maps to 1.\n * @param value - The value to locate.\n * @returns The interpolant, clamped into `[0, 1]`. Returns 0 when `a` and `b` are equal.\n *\n * @public\n */\nexport function inverseLerp(a: number, b: number, value: number): number {\n if (a === b) {\n return 0;\n }\n return clamp01((value - a) / (b - a));\n}\n\n/**\n * Smoothly interpolates between two edges with a Hermite curve (the GLSL `smoothstep`), easing in\n * and out instead of the straight ramp of {@link lerp}.\n *\n * @param edge0 - The value below which the result is 0.\n * @param edge1 - The value above which the result is 1.\n * @param x - The value to map.\n * @returns A value in `[0, 1]`. Degenerate edges (`edge0 === edge1`) step from 0 to 1 at the edge.\n *\n * @example\n * ```ts\n * smoothStep(0, 1, 0.5); // 0.5, but with zero slope at 0 and 1\n * ```\n *\n * @public\n */\nexport function smoothStep(edge0: number, edge1: number, x: number): number {\n if (edge0 === edge1) {\n return x < edge0 ? 0 : 1;\n }\n const t = clamp01((x - edge0) / (edge1 - edge0));\n return t * t * (3 - 2 * t);\n}\n\n/**\n * Moves a value towards a target without overshooting it.\n *\n * @param current - The value to move.\n * @param target - The value to move towards.\n * @param maxDelta - The largest step allowed this call; negative values move away from the target.\n * @returns The stepped value, exactly `target` once the remaining distance fits in `maxDelta`.\n *\n * @example\n * ```ts\n * // frame-rate independent approach at 2 units per second\n * health = moveTowards(health, 100, 2 * time.deltaTime);\n * ```\n *\n * @public\n */\nexport function moveTowards(current: number, target: number, maxDelta: number): number {\n const delta = target - current;\n if (Math.abs(delta) <= maxDelta) {\n return target;\n }\n return current + (delta < 0 ? -maxDelta : maxDelta);\n}\n\n/**\n * Wraps a value into `[0, length)`, the way a looping animation time behaves. Unlike `%` the result\n * is never negative.\n *\n * @param t - The value to wrap.\n * @param length - The positive period to wrap into.\n * @returns The wrapped value, clamped into `[0, length]` so float error cannot escape the range.\n *\n * @example\n * ```ts\n * repeat(-1, 4); // 3\n * ```\n *\n * @public\n */\nexport function repeat(t: number, length: number): number {\n return clamp(t - Math.floor(t / length) * length, 0, length);\n}\n\n/**\n * Bounces a value back and forth between 0 and `length`, the way a ping-pong animation behaves.\n *\n * @param t - The value to fold.\n * @param length - The positive half-period to fold into.\n * @returns A value in `[0, length]` that rises then falls as `t` increases.\n *\n * @example\n * ```ts\n * pingPong(5, 4); // 3\n * ```\n *\n * @public\n */\nexport function pingPong(t: number, length: number): number {\n return length - Math.abs(repeat(t, length * 2) - length);\n}\n\n/**\n * Compares two numbers with an absolute tolerance. Use this instead of `===` on anything that has\n * been through a matrix, a quaternion or a `Float32Array`.\n *\n * @param a - The first value.\n * @param b - The second value.\n * @param epsilon - The largest difference still considered equal. Defaults to {@link EPSILON}.\n * @returns `true` when the values differ by no more than `epsilon`. `NaN` is never approximately\n * equal to anything, including itself.\n *\n * @public\n */\nexport function approximately(a: number, b: number, epsilon: number = EPSILON): boolean {\n return Math.abs(a - b) <= epsilon;\n}\n\n/**\n * The sign of a value, with zero treated as positive (matching Unity's `Mathf.Sign`, and unlike\n * `Math.sign`, which returns 0 and `-0`).\n *\n * @param value - The value to inspect.\n * @returns `-1` for negative values, `1` for positive values and for both `0` and `-0`, and `NaN`\n * for `NaN`.\n *\n * @public\n */\nexport function sign(value: number): number {\n if (Number.isNaN(value)) {\n return Number.NaN;\n }\n return value < 0 ? -1 : 1;\n}\n\n/**\n * Wraps an angle in degrees into `[-180, 180)`, the range rotations are most readable in.\n *\n * @param degrees - The angle to wrap.\n * @returns The equivalent angle in `[-180, 180)`; exactly `180` wraps to `-180`.\n *\n * @example\n * ```ts\n * wrapAngleDegrees(370); // 10\n * wrapAngleDegrees(-190); // 170\n * ```\n *\n * @public\n */\nexport function wrapAngleDegrees(degrees: number): number {\n return repeat(degrees + 180, 360) - 180;\n}\n\n/**\n * The shortest signed rotation from one angle to another, in degrees.\n *\n * @param fromDegrees - The starting angle.\n * @param toDegrees - The target angle.\n * @returns The signed difference in `[-180, 180)`.\n *\n * @example\n * ```ts\n * deltaAngleDegrees(350, 10); // 20, not -340\n * ```\n *\n * @public\n */\nexport function deltaAngleDegrees(fromDegrees: number, toDegrees: number): number {\n return wrapAngleDegrees(toDegrees - fromDegrees);\n}\n\n/**\n * Interpolates between two angles in degrees the short way around the circle.\n *\n * @param fromDegrees - The angle returned at `t === 0`.\n * @param toDegrees - The angle approached at `t === 1`.\n * @param t - The interpolant; not clamped, matching {@link lerp}.\n * @returns The interpolated angle. It is not wrapped, so feeding the result back in is stable.\n *\n * @example\n * ```ts\n * lerpAngleDegrees(350, 10, 0.5); // 360\n * ```\n *\n * @public\n */\nexport function lerpAngleDegrees(fromDegrees: number, toDegrees: number, t: number): number {\n return fromDegrees + deltaAngleDegrees(fromDegrees, toDegrees) * t;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,UAAkB;;;;;;AAO/B,MAAa,aAAqB,KAAK,KAAK;;;;;;AAO5C,MAAa,aAAqB,MAAM,KAAK;;;;;;;;;AAU7C,SAAgB,SAAS,SAAyB;CAChD,OAAO,UAAU;AACnB;;;;;;;;;AAUA,SAAgB,SAAS,SAAyB;CAChD,OAAO,UAAU;AACnB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,MAAM,OAAe,KAAa,KAAqB;CACrE,IAAI,QAAQ,KACV,OAAO;CAET,IAAI,QAAQ,KACV,OAAO;CAET,OAAO;AACT;;;;;;;;;AAUA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,MAAM,OAAO,GAAG,CAAC;AAC1B;;;;;;;;;;;;;;;;;AAkBA,SAAgB,KAAK,GAAW,GAAW,GAAmB;CAC5D,OAAO,KAAK,IAAI,KAAK;AACvB;;;;;;;;;;;AAYA,SAAgB,YAAY,GAAW,GAAW,OAAuB;CACvE,IAAI,MAAM,GACR,OAAO;CAET,OAAO,SAAS,QAAQ,MAAM,IAAI,EAAE;AACtC;;;;;;;;;;;;;;;;;AAkBA,SAAgB,WAAW,OAAe,OAAe,GAAmB;CAC1E,IAAI,UAAU,OACZ,OAAO,IAAI,QAAQ,IAAI;CAEzB,MAAM,IAAI,SAAS,IAAI,UAAU,QAAQ,MAAM;CAC/C,OAAO,IAAI,KAAK,IAAI,IAAI;AAC1B;;;;;;;;;;;;;;;;;AAkBA,SAAgB,YAAY,SAAiB,QAAgB,UAA0B;CACrF,MAAM,QAAQ,SAAS;CACvB,IAAI,KAAK,IAAI,KAAK,KAAK,UACrB,OAAO;CAET,OAAO,WAAW,QAA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