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AS,kBACvB,CACA,uBAAI,CAAoB,GAExB,CACA,0BAAI,GACF,OAAO,KAAK,SAAS,qBACvB,CACA,0BAAI,CAAuB,GAE3B,CAEA,cAAA,GACE,MAAM,SAAC,GAAY,KAAK,UAClB,OAAC,EAAM,SAAE,EAAQ,SAAE,EAAQ,OAAE,EAAM,OAAE,EAAM,UAAE,EAAS,WAAE,GAAc,KAC5E,EAAS,OAAO,MAAM,KAAK,GAC3B,EAAS,SAAS,MAAM,KAAK,GAC7B,EAAS,SAAS,MAAM,KAAK,GAC7B,EAAS,OAAO,MAAM,KAAK,GAC3B,EAAS,OAAO,MAAQ,EACxB,EAAS,QAAQ,MAAM,IAAI,EAAU,EAAG,EAAU,EAAG,GAAc,EACrE,CAEA,OAAA,GAEA,SAGO,WAAY,sBAAuB,qBAAsB,sBAAuB,sBAAuB,cAAe","file":"/npm/troika-three-utils@0.52.4/dist/troika-three-utils.esm.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/troika-three-utils@0.52.4/dist/troika-three-utils.esm.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","import { ShaderChunk, UniformsUtils, MeshDepthMaterial, RGBADepthPacking, MeshDistanceMaterial, ShaderLib, Matrix4, Vector3, Mesh, CylinderGeometry, Vector2, MeshStandardMaterial, DoubleSide } from 'three';\n\n/**\n * Regular expression for matching the `void main() {` opener line in GLSL.\n * @type {RegExp}\n */\nconst voidMainRegExp = /\\bvoid\\s+main\\s*\\(\\s*\\)\\s*{/g;\n\n/**\n * Recursively expands all `#include <xyz>` statements within string of shader code.\n * Copied from three's WebGLProgram#parseIncludes for external use.\n *\n * @param {string} source - The GLSL source code to evaluate\n * @return {string} The GLSL code with all includes expanded\n */\nfunction expandShaderIncludes( source ) {\n  const pattern = /^[ \\t]*#include +<([\\w\\d./]+)>/gm;\n  function replace(match, include) {\n    let chunk = ShaderChunk[include];\n    return chunk ? expandShaderIncludes(chunk) : match\n  }\n  return source.replace( pattern, replace )\n}\n\n/*\n * This is a direct copy of MathUtils.generateUUID from Three.js, to preserve compatibility with three\n * versions before 0.113.0 as it was changed from Math to MathUtils in that version.\n * https://github.com/mrdoob/three.js/blob/dd8b5aa3b270c17096b90945cd2d6d1b13aaec53/src/math/MathUtils.js#L16\n */\n\nconst _lut = [];\n\nfor (let i = 0; i < 256; i++) {\n  _lut[i] = (i < 16 ? '0' : '') + (i).toString(16);\n}\n\nfunction generateUUID() {\n\n  // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136\n\n  const d0 = Math.random() * 0xffffffff | 0;\n  const d1 = Math.random() * 0xffffffff | 0;\n  const d2 = Math.random() * 0xffffffff | 0;\n  const d3 = Math.random() * 0xffffffff | 0;\n  const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' +\n    _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' +\n    _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] +\n    _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff];\n\n  // .toUpperCase() here flattens concatenated strings to save heap memory space.\n  return uuid.toUpperCase()\n\n}\n\n// Local assign polyfill to avoid importing troika-core\nconst assign = Object.assign || function(/*target, ...sources*/) {\n  let target = arguments[0];\n  for (let i = 1, len = arguments.length; i < len; i++) {\n    let source = arguments[i];\n    if (source) {\n      for (let prop in source) {\n        if (Object.prototype.hasOwnProperty.call(source, prop)) {\n          target[prop] = source[prop];\n        }\n      }\n    }\n  }\n  return target\n};\n\n\nconst epoch = Date.now();\nconst CONSTRUCTOR_CACHE = new WeakMap();\nconst SHADER_UPGRADE_CACHE = new Map();\n\n// Material ids must be integers, but we can't access the increment from Three's `Material` module,\n// so let's choose a sufficiently large starting value that should theoretically never collide.\nlet materialInstanceId = 1e10;\n\n/**\n * A utility for creating a custom shader material derived from another material's\n * shaders. This allows you to inject custom shader logic and transforms into the\n * builtin ThreeJS materials without having to recreate them from scratch.\n *\n * @param {THREE.Material} baseMaterial - the original material to derive from\n *\n * @param {Object} options - How the base material should be modified.\n * @param {Object=} options.defines - Custom `defines` for the material\n * @param {Object=} options.extensions - Custom `extensions` for the material, e.g. `{derivatives: true}`\n * @param {Object=} options.uniforms - Custom `uniforms` for use in the modified shader. These can\n *        be accessed and manipulated via the resulting material's `uniforms` property, just like\n *        in a ShaderMaterial. You do not need to repeat the base material's own uniforms here.\n * @param {String=} options.timeUniform - If specified, a uniform of this name will be injected into\n *        both shaders, and it will automatically be updated on each render frame with a number of\n *        elapsed milliseconds. The \"zero\" epoch time is not significant so don't rely on this as a\n *        true calendar time.\n * @param {String=} options.vertexDefs - Custom GLSL code to inject into the vertex shader's top-level\n *        definitions, above the `void main()` function.\n * @param {String=} options.vertexMainIntro - Custom GLSL code to inject at the top of the vertex\n *        shader's `void main` function.\n * @param {String=} options.vertexMainOutro - Custom GLSL code to inject at the end of the vertex\n *        shader's `void main` function.\n * @param {String=} options.vertexTransform - Custom GLSL code to manipulate the `position`, `normal`,\n *        and/or `uv` vertex attributes. This code will be wrapped within a standalone function with\n *        those attributes exposed by their normal names as read/write values.\n * @param {String=} options.fragmentDefs - Custom GLSL code to inject into the fragment shader's top-level\n *        definitions, above the `void main()` function.\n * @param {String=} options.fragmentMainIntro - Custom GLSL code to inject at the top of the fragment\n *        shader's `void main` function.\n * @param {String=} options.fragmentMainOutro - Custom GLSL code to inject at the end of the fragment\n *        shader's `void main` function. You can manipulate `gl_FragColor` here but keep in mind it goes\n *        after any of ThreeJS's color postprocessing shader chunks (tonemapping, fog, etc.), so if you\n *        want those to apply to your changes use `fragmentColorTransform` instead.\n * @param {String=} options.fragmentColorTransform - Custom GLSL code to manipulate the `gl_FragColor`\n *        output value. Will be injected near the end of the `void main` function, but before any\n *        of ThreeJS's color postprocessing shader chunks (tonemapping, fog, etc.), and before the\n *        `fragmentMainOutro`.\n * @param {function({fragmentShader: string, vertexShader:string}):\n *        {fragmentShader: string, vertexShader:string}} options.customRewriter - A function\n *        for performing custom rewrites of the full shader code. Useful if you need to do something\n *        special that's not covered by the other builtin options. This function will be executed before\n *        any other transforms are applied.\n * @param {boolean=} options.chained - Set to `true` to prototype-chain the derived material to the base\n *        material, rather than the default behavior of copying it. This allows the derived material to\n *        automatically pick up changes made to the base material and its properties. This can be useful\n *        where the derived material is hidden from the user as an implementation detail, allowing them\n *        to work with the original material like normal. But it can result in unexpected behavior if not\n *        handled carefully.\n *\n * @return {THREE.Material}\n *\n * The returned material will also have two new methods, `getDepthMaterial()` and `getDistanceMaterial()`,\n * which can be called to get a variant of the derived material for use in shadow casting. If the\n * target mesh is expected to cast shadows, then you can assign these to the mesh's `customDepthMaterial`\n * (for directional and spot lights) and/or `customDistanceMaterial` (for point lights) properties to\n * allow the cast shadow to honor your derived shader's vertex transforms and discarded fragments. These\n * will also set a custom `#define IS_DEPTH_MATERIAL` or `#define IS_DISTANCE_MATERIAL` that you can look\n * for in your derived shaders with `#ifdef` to customize their behavior for the depth or distance\n * scenarios, e.g. skipping antialiasing or expensive shader logic.\n */\nfunction createDerivedMaterial(baseMaterial, options) {\n  // Generate a key that is unique to the content of these `options`. We'll use this\n  // throughout for caching and for generating the upgraded shader code. This increases\n  // the likelihood that the resulting shaders will line up across multiple calls so\n  // their GL programs can be shared and cached.\n  const optionsKey = getKeyForOptions(options);\n\n  // First check to see if we've already derived from this baseMaterial using this\n  // unique set of options, and if so reuse the constructor to avoid some allocations.\n  let ctorsByDerivation = CONSTRUCTOR_CACHE.get(baseMaterial);\n  if (!ctorsByDerivation) {\n    CONSTRUCTOR_CACHE.set(baseMaterial, (ctorsByDerivation = Object.create(null)));\n  }\n  if (ctorsByDerivation[optionsKey]) {\n    return new ctorsByDerivation[optionsKey]()\n  }\n\n  const privateBeforeCompileProp = `_onBeforeCompile${optionsKey}`;\n\n  // Private onBeforeCompile handler that injects the modified shaders and uniforms when\n  // the renderer switches to this material's program\n  const onBeforeCompile = function (shaderInfo, renderer) {\n    baseMaterial.onBeforeCompile.call(this, shaderInfo, renderer);\n\n    // Upgrade the shaders, caching the result by incoming source code\n    const cacheKey = this.customProgramCacheKey() + '|' + shaderInfo.vertexShader + '|' + shaderInfo.fragmentShader;\n    let upgradedShaders = SHADER_UPGRADE_CACHE[cacheKey];\n    if (!upgradedShaders) {\n      const upgraded = upgradeShaders(this, shaderInfo, options, optionsKey);\n      upgradedShaders = SHADER_UPGRADE_CACHE[cacheKey] = upgraded;\n    }\n\n    // Inject upgraded shaders and uniforms into the program\n    shaderInfo.vertexShader = upgradedShaders.vertexShader;\n    shaderInfo.fragmentShader = upgradedShaders.fragmentShader;\n    assign(shaderInfo.uniforms, this.uniforms);\n\n    // Inject auto-updating time uniform if requested\n    if (options.timeUniform) {\n      shaderInfo.uniforms[options.timeUniform] = {\n        get value() {return Date.now() - epoch}\n      };\n    }\n\n    // Users can still add their own handlers on top of ours\n    if (this[privateBeforeCompileProp]) {\n      this[privateBeforeCompileProp](shaderInfo);\n    }\n  };\n\n  const DerivedMaterial = function DerivedMaterial() {\n    return derive(options.chained ? baseMaterial : baseMaterial.clone())\n  };\n\n  const derive = function(base) {\n    // Prototype chain to the base material\n    const derived = Object.create(base, descriptor);\n\n    // Store the baseMaterial for reference; this is always the original even when cloning\n    Object.defineProperty(derived, 'baseMaterial', { value: baseMaterial });\n\n    // Needs its own ids\n    Object.defineProperty(derived, 'id', { value: materialInstanceId++ });\n    derived.uuid = generateUUID();\n\n    // Merge uniforms, defines, and extensions\n    derived.uniforms = assign({}, base.uniforms, options.uniforms);\n    derived.defines = assign({}, base.defines, options.defines);\n    derived.defines[`TROIKA_DERIVED_MATERIAL_${optionsKey}`] = ''; //force a program change from the base material\n    derived.extensions = assign({}, base.extensions, options.extensions);\n\n    // Don't inherit EventDispatcher listeners\n    derived._listeners = undefined;\n\n    return derived\n  };\n\n  const descriptor = {\n    constructor: {value: DerivedMaterial},\n    isDerivedMaterial: {value: true},\n\n    type: {\n      get: () => baseMaterial.type,\n      set: (value) => {baseMaterial.type = value;}\n    },\n\n    isDerivedFrom: {\n      writable: true,\n      configurable: true,\n      value: function (testMaterial) {\n        const base = this.baseMaterial;\n        return testMaterial === base || (base.isDerivedMaterial && base.isDerivedFrom(testMaterial)) || false\n      }\n    },\n\n    customProgramCacheKey: {\n      writable: true,\n      configurable: true,\n      value: function () {\n        return baseMaterial.customProgramCacheKey() + '|' + optionsKey\n      }\n    },\n\n    onBeforeCompile: {\n      get() {\n        return onBeforeCompile\n      },\n      set(fn) {\n        this[privateBeforeCompileProp] = fn;\n      }\n    },\n\n    copy: {\n      writable: true,\n      configurable: true,\n      value: function (source) {\n        baseMaterial.copy.call(this, source);\n        if (!baseMaterial.isShaderMaterial && !baseMaterial.isDerivedMaterial) {\n          assign(this.extensions, source.extensions);\n          assign(this.defines, source.defines);\n          assign(this.uniforms, UniformsUtils.clone(source.uniforms));\n        }\n        return this\n      }\n    },\n\n    clone: {\n      writable: true,\n      configurable: true,\n      value: function () {\n        const newBase = new baseMaterial.constructor();\n        return derive(newBase).copy(this)\n      }\n    },\n\n    /**\n     * Utility to get a MeshDepthMaterial that will honor this derived material's vertex\n     * transformations and discarded fragments.\n     */\n    getDepthMaterial: {\n      writable: true,\n      configurable: true,\n      value: function() {\n        let depthMaterial = this._depthMaterial;\n        if (!depthMaterial) {\n          depthMaterial = this._depthMaterial = createDerivedMaterial(\n            baseMaterial.isDerivedMaterial\n              ? baseMaterial.getDepthMaterial()\n              : new MeshDepthMaterial({ depthPacking: RGBADepthPacking }),\n            options\n          );\n          depthMaterial.defines.IS_DEPTH_MATERIAL = '';\n          depthMaterial.uniforms = this.uniforms; //automatically recieve same uniform values\n        }\n        return depthMaterial\n      }\n    },\n\n    /**\n     * Utility to get a MeshDistanceMaterial that will honor this derived material's vertex\n     * transformations and discarded fragments.\n     */\n    getDistanceMaterial: {\n      writable: true,\n      configurable: true,\n      value: function() {\n        let distanceMaterial = this._distanceMaterial;\n        if (!distanceMaterial) {\n          distanceMaterial = this._distanceMaterial = createDerivedMaterial(\n            baseMaterial.isDerivedMaterial\n              ? baseMaterial.getDistanceMaterial()\n              : new MeshDistanceMaterial(),\n            options\n          );\n          distanceMaterial.defines.IS_DISTANCE_MATERIAL = '';\n          distanceMaterial.uniforms = this.uniforms; //automatically recieve same uniform values\n        }\n        return distanceMaterial\n      }\n    },\n\n    dispose: {\n      writable: true,\n      configurable: true,\n      value() {\n        const {_depthMaterial, _distanceMaterial} = this;\n        if (_depthMaterial) _depthMaterial.dispose();\n        if (_distanceMaterial) _distanceMaterial.dispose();\n        baseMaterial.dispose.call(this);\n      }\n    }\n  };\n\n  ctorsByDerivation[optionsKey] = DerivedMaterial;\n  return new DerivedMaterial()\n}\n\n\nfunction upgradeShaders(material, {vertexShader, fragmentShader}, options, key) {\n  let {\n    vertexDefs,\n    vertexMainIntro,\n    vertexMainOutro,\n    vertexTransform,\n    fragmentDefs,\n    fragmentMainIntro,\n    fragmentMainOutro,\n    fragmentColorTransform,\n    customRewriter,\n    timeUniform\n  } = options;\n\n  vertexDefs = vertexDefs || '';\n  vertexMainIntro = vertexMainIntro || '';\n  vertexMainOutro = vertexMainOutro || '';\n  fragmentDefs = fragmentDefs || '';\n  fragmentMainIntro = fragmentMainIntro || '';\n  fragmentMainOutro = fragmentMainOutro || '';\n\n  // Expand includes if needed\n  if (vertexTransform || customRewriter) {\n    vertexShader = expandShaderIncludes(vertexShader);\n  }\n  if (fragmentColorTransform || customRewriter) {\n    // We need to be able to find postprocessing chunks after include expansion in order to\n    // put them after the fragmentColorTransform, so mark them with comments first. Even if\n    // this particular derivation doesn't have a fragmentColorTransform, other derivations may,\n    // so we still mark them.\n    fragmentShader = fragmentShader.replace(\n      /^[ \\t]*#include <((?:tonemapping|encodings|colorspace|fog|premultiplied_alpha|dithering)_fragment)>/gm,\n      '\\n//!BEGIN_POST_CHUNK $1\\n$&\\n//!END_POST_CHUNK\\n'\n    );\n    fragmentShader = expandShaderIncludes(fragmentShader);\n  }\n\n  // Apply custom rewriter function\n  if (customRewriter) {\n    let res = customRewriter({vertexShader, fragmentShader});\n    vertexShader = res.vertexShader;\n    fragmentShader = res.fragmentShader;\n  }\n\n  // The fragmentColorTransform needs to go before any postprocessing chunks, so extract\n  // those and re-insert them into the outro in the correct place:\n  if (fragmentColorTransform) {\n    let postChunks = [];\n    fragmentShader = fragmentShader.replace(\n      /^\\/\\/!BEGIN_POST_CHUNK[^]+?^\\/\\/!END_POST_CHUNK/gm, // [^]+? = non-greedy match of any chars including newlines\n      match => {\n        postChunks.push(match);\n        return ''\n      }\n    );\n    fragmentMainOutro = `${fragmentColorTransform}\\n${postChunks.join('\\n')}\\n${fragmentMainOutro}`;\n  }\n\n  // Inject auto-updating time uniform if requested\n  if (timeUniform) {\n    const code = `\\nuniform float ${timeUniform};\\n`;\n    vertexDefs = code + vertexDefs;\n    fragmentDefs = code + fragmentDefs;\n  }\n\n  // Inject a function for the vertexTransform and rename all usages of position/normal/uv\n  if (vertexTransform) {\n    // Hoist these defs to the very top so they work in other function defs\n    vertexShader = `vec3 troika_position_${key};\nvec3 troika_normal_${key};\nvec2 troika_uv_${key};\n${vertexShader}\n`;\n    vertexDefs = `${vertexDefs}\nvoid troikaVertexTransform${key}(inout vec3 position, inout vec3 normal, inout vec2 uv) {\n  ${vertexTransform}\n}\n`;\n    vertexMainIntro = `\ntroika_position_${key} = vec3(position);\ntroika_normal_${key} = vec3(normal);\ntroika_uv_${key} = vec2(uv);\ntroikaVertexTransform${key}(troika_position_${key}, troika_normal_${key}, troika_uv_${key});\n${vertexMainIntro}\n`;\n    vertexShader = vertexShader.replace(/\\b(position|normal|uv)\\b/g, (match, match1, index, fullStr) => {\n      return /\\battribute\\s+vec[23]\\s+$/.test(fullStr.substr(0, index)) ? match1 : `troika_${match1}_${key}`\n    });\n\n    // Three r152 introduced the MAP_UV token, replace it too if it's pointing to the main 'uv'\n    // Perhaps the other textures too going forward?\n    if (!(material.map && material.map.channel > 0)) {\n      vertexShader = vertexShader.replace(/\\bMAP_UV\\b/g, `troika_uv_${key}`);\n    }\n  }\n\n  // Inject defs and intro/outro snippets\n  vertexShader = injectIntoShaderCode(vertexShader, key, vertexDefs, vertexMainIntro, vertexMainOutro);\n  fragmentShader = injectIntoShaderCode(fragmentShader, key, fragmentDefs, fragmentMainIntro, fragmentMainOutro);\n\n  return {\n    vertexShader,\n    fragmentShader\n  }\n}\n\nfunction injectIntoShaderCode(shaderCode, id, defs, intro, outro) {\n  if (intro || outro || defs) {\n    shaderCode = shaderCode.replace(voidMainRegExp, `\n${defs}\nvoid troikaOrigMain${id}() {`\n    );\n    shaderCode += `\nvoid main() {\n  ${intro}\n  troikaOrigMain${id}();\n  ${outro}\n}`;\n  }\n  return shaderCode\n}\n\n\nfunction optionsJsonReplacer(key, value) {\n  return key === 'uniforms' ? undefined : typeof value === 'function' ? value.toString() : value\n}\n\nlet _idCtr = 0;\nconst optionsHashesToIds = new Map();\nfunction getKeyForOptions(options) {\n  const optionsHash = JSON.stringify(options, optionsJsonReplacer);\n  let id = optionsHashesToIds.get(optionsHash);\n  if (id == null) {\n    optionsHashesToIds.set(optionsHash, (id = ++_idCtr));\n  }\n  return id\n}\n\n// Copied from threejs WebGLPrograms.js so we can resolve builtin materials to their shaders\n// TODO how can we keep this from getting stale?\nconst MATERIAL_TYPES_TO_SHADERS = {\n  MeshDepthMaterial: 'depth',\n  MeshDistanceMaterial: 'distanceRGBA',\n  MeshNormalMaterial: 'normal',\n  MeshBasicMaterial: 'basic',\n  MeshLambertMaterial: 'lambert',\n  MeshPhongMaterial: 'phong',\n  MeshToonMaterial: 'toon',\n  MeshStandardMaterial: 'physical',\n  MeshPhysicalMaterial: 'physical',\n  MeshMatcapMaterial: 'matcap',\n  LineBasicMaterial: 'basic',\n  LineDashedMaterial: 'dashed',\n  PointsMaterial: 'points',\n  ShadowMaterial: 'shadow',\n  SpriteMaterial: 'sprite'\n};\n\n/**\n * Given a Three.js `Material` instance, find the shaders/uniforms that will be\n * used to render that material.\n *\n * @param material - the Material instance\n * @return {object} - the material's shader info: `{uniforms:{}, fragmentShader:'', vertexShader:''}`\n */\nfunction getShadersForMaterial(material) {\n  let builtinType = MATERIAL_TYPES_TO_SHADERS[material.type];\n  return builtinType ? ShaderLib[builtinType] : material //TODO fallback for unknown type?\n}\n\n/**\n * Find all uniforms and their types within a shader code string.\n *\n * @param {string} shader - The shader code to parse\n * @return {object} mapping of uniform names to their glsl type\n */\nfunction getShaderUniformTypes(shader) {\n  let uniformRE = /\\buniform\\s+(int|float|vec[234]|mat[34])\\s+([A-Za-z_][\\w]*)/g;\n  let uniforms = Object.create(null);\n  let match;\n  while ((match = uniformRE.exec(shader)) !== null) {\n    uniforms[match[2]] = match[1];\n  }\n  return uniforms\n}\n\n/**\n * Helper for smoothing out the `m.getInverse(x)` --> `m.copy(x).invert()` conversion\n * that happened in ThreeJS r123.\n * @param {Matrix4} srcMatrix\n * @param {Matrix4} [tgtMatrix]\n */\nfunction invertMatrix4(srcMatrix, tgtMatrix = new Matrix4()) {\n  if (typeof tgtMatrix.invert === 'function') {\n    tgtMatrix.copy(srcMatrix).invert();\n  } else {\n    tgtMatrix.getInverse(srcMatrix);\n  }\n  return tgtMatrix\n}\n\n/*\nInput geometry is a cylinder with r=1, height in y dimension from 0 to 1,\ndivided into a reasonable number of height segments.\n*/\n\nconst vertexDefs = `\nuniform vec3 pointA;\nuniform vec3 controlA;\nuniform vec3 controlB;\nuniform vec3 pointB;\nuniform float radius;\nvarying float bezierT;\n\nvec3 cubicBezier(vec3 p1, vec3 c1, vec3 c2, vec3 p2, float t) {\n  float t2 = 1.0 - t;\n  float b0 = t2 * t2 * t2;\n  float b1 = 3.0 * t * t2 * t2;\n  float b2 = 3.0 * t * t * t2;\n  float b3 = t * t * t;\n  return b0 * p1 + b1 * c1 + b2 * c2 + b3 * p2;\n}\n\nvec3 cubicBezierDerivative(vec3 p1, vec3 c1, vec3 c2, vec3 p2, float t) {\n  float t2 = 1.0 - t;\n  return -3.0 * p1 * t2 * t2 +\n    c1 * (3.0 * t2 * t2 - 6.0 * t2 * t) +\n    c2 * (6.0 * t2 * t - 3.0 * t * t) +\n    3.0 * p2 * t * t;\n}\n`;\n\nconst vertexTransform = `\nfloat t = position.y;\nbezierT = t;\nvec3 bezierCenterPos = cubicBezier(pointA, controlA, controlB, pointB, t);\nvec3 bezierDir = normalize(cubicBezierDerivative(pointA, controlA, controlB, pointB, t));\n\n// Make \"sideways\" always perpendicular to the camera ray; this ensures that any twists\n// in the cylinder occur where you won't see them: \nvec3 viewDirection = normalMatrix * vec3(0.0, 0.0, 1.0);\nif (bezierDir == viewDirection) {\n  bezierDir = normalize(cubicBezierDerivative(pointA, controlA, controlB, pointB, t == 1.0 ? t - 0.0001 : t + 0.0001));\n}\nvec3 sideways = normalize(cross(bezierDir, viewDirection));\nvec3 upish = normalize(cross(sideways, bezierDir));\n\n// Build a matrix for transforming this disc in the cylinder:\nmat4 discTx;\ndiscTx[0].xyz = sideways * radius;\ndiscTx[1].xyz = bezierDir * radius;\ndiscTx[2].xyz = upish * radius;\ndiscTx[3].xyz = bezierCenterPos;\ndiscTx[3][3] = 1.0;\n\n// Apply transform, ignoring original y\nposition = (discTx * vec4(position.x, 0.0, position.z, 1.0)).xyz;\nnormal = normalize(mat3(discTx) * normal);\n`;\n\nconst fragmentDefs = `\nuniform vec3 dashing;\nvarying float bezierT;\n`;\n\nconst fragmentMainIntro = `\nif (dashing.x + dashing.y > 0.0) {\n  float dashFrac = mod(bezierT - dashing.z, dashing.x + dashing.y);\n  if (dashFrac > dashing.x) {\n    discard;\n  }\n}\n`;\n\n// Debugging: separate color for each of the 6 sides:\n// const fragmentColorTransform = `\n// float sideNum = floor(vUV.x * 6.0);\n// vec3 mixColor = sideNum < 1.0 ? vec3(1.0, 0.0, 0.0) :\n//   sideNum < 2.0 ? vec3(0.0, 1.0, 1.0) :\n//   sideNum < 3.0 ? vec3(1.0, 1.0, 0.0) :\n//   sideNum < 4.0 ? vec3(0.0, 0.0, 1.0) :\n//   sideNum < 5.0 ? vec3(0.0, 1.0, 0.0) :\n//   vec3(1.0, 0.0, 1.0);\n// gl_FragColor.xyz = mix(gl_FragColor.xyz, mixColor, 0.5);\n// `\n\n\n\nfunction createBezierMeshMaterial(baseMaterial) {\n  return createDerivedMaterial(\n    baseMaterial,\n    {\n      chained: true,\n      uniforms: {\n        pointA: {value: new Vector3()},\n        controlA: {value: new Vector3()},\n        controlB: {value: new Vector3()},\n        pointB: {value: new Vector3()},\n        radius: {value: 0.01},\n        dashing: {value: new Vector3()} //on, off, offset\n      },\n      vertexDefs,\n      vertexTransform,\n      fragmentDefs,\n      fragmentMainIntro\n    }\n  )\n}\n\nlet geometry = null;\n\nconst defaultBaseMaterial = /*#__PURE__*/new MeshStandardMaterial({color: 0xffffff, side: DoubleSide});\n\n\n/**\n * A ThreeJS `Mesh` that bends a tube shape along a 3D cubic bezier path. The bending is done\n * by deforming a straight cylindrical geometry in the vertex shader based on a set of four\n * control point uniforms. It patches the necessary GLSL into the mesh's assigned `material`\n * automatically.\n *\n * The cubiz bezier path is determined by its four `Vector3` properties:\n * - `pointA`\n * - `controlA`\n * - `controlB`\n * - `pointB`\n *\n * The tube's radius is controlled by its `radius` property, which defaults to `0.01`.\n *\n * You can also give the tube a dashed appearance with two properties:\n *\n * - `dashArray` - an array of two numbers, defining the length of \"on\" and \"off\" parts of\n *   the dash. Each is a 0-1 ratio of the entire path's length. (Actually this is the `t` length\n *   used as input to the cubic bezier function, not its visible length.)\n * - `dashOffset` - offset of where the dash starts. You can animate this to make the dashes move.\n *\n * Note that the dashes will appear like a hollow tube, not solid. This will be more apparent on\n * thicker tubes.\n *\n * TODO: proper geometry bounding sphere and raycasting\n * TODO: allow control of the geometry's segment counts\n */\nclass BezierMesh extends Mesh {\n  static getGeometry() {\n    return geometry || (geometry =\n      new CylinderGeometry(1, 1, 1, 6, 64).translate(0, 0.5, 0)\n    )\n  }\n\n  constructor() {\n    super(\n      BezierMesh.getGeometry(),\n      defaultBaseMaterial\n    );\n\n    this.pointA = new Vector3();\n    this.controlA = new Vector3();\n    this.controlB = new Vector3();\n    this.pointB = new Vector3();\n    this.radius = 0.01;\n    this.dashArray = new Vector2();\n    this.dashOffset = 0;\n\n    // TODO - disabling frustum culling until I figure out how to customize the\n    //  geometry's bounding sphere that gets used\n    this.frustumCulled = false;\n  }\n\n  // Handler for automatically wrapping the base material with our upgrades. We do the wrapping\n  // lazily on _read_ rather than write to avoid unnecessary wrapping on transient values.\n  get material() {\n    let derivedMaterial = this._derivedMaterial;\n    const baseMaterial = this._baseMaterial || this._defaultMaterial || (this._defaultMaterial = defaultBaseMaterial.clone());\n    if (!derivedMaterial || derivedMaterial.baseMaterial !== baseMaterial) {\n      derivedMaterial = this._derivedMaterial = createBezierMeshMaterial(baseMaterial);\n      // dispose the derived material when its base material is disposed:\n      baseMaterial.addEventListener('dispose', function onDispose() {\n        baseMaterial.removeEventListener('dispose', onDispose);\n        derivedMaterial.dispose();\n      });\n    }\n    return derivedMaterial\n  }\n  set material(baseMaterial) {\n    this._baseMaterial = baseMaterial;\n  }\n\n  // Create and update material for shadows upon request:\n  get customDepthMaterial() {\n    return this.material.getDepthMaterial()\n  }\n  set customDepthMaterial(m) {\n    // future: let the user override with their own?\n  }\n  get customDistanceMaterial() {\n    return this.material.getDistanceMaterial()\n  }\n  set customDistanceMaterial(m) {\n    // future: let the user override with their own?\n  }\n\n  onBeforeRender() {\n    const {uniforms} = this.material;\n    const {pointA, controlA, controlB, pointB, radius, dashArray, dashOffset} = this;\n    uniforms.pointA.value.copy(pointA);\n    uniforms.controlA.value.copy(controlA);\n    uniforms.controlB.value.copy(controlB);\n    uniforms.pointB.value.copy(pointB);\n    uniforms.radius.value = radius;\n    uniforms.dashing.value.set(dashArray.x, dashArray.y, dashOffset || 0);\n  }\n\n  raycast(/*raycaster, intersects*/) {\n    // TODO - just fail for now\n  }\n}\n\nexport { BezierMesh, createDerivedMaterial, expandShaderIncludes, getShaderUniformTypes, getShadersForMaterial, invertMatrix4, voidMainRegExp };\n"]}